/**
 * 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.hadoop.hdfs.server.datanode;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hdfs.DFSConfigKeys;
import org.apache.hadoop.hdfs.MiniDFSCluster;
import org.apache.hadoop.hdfs.protocol.datatransfer.PipelineAck;
import org.junit.Assert;
import org.junit.Test;

import java.io.IOException;

public class TestDataNodeECN {
  @Test
  public void testECNFlag() throws IOException {
    Configuration conf = new Configuration();
    conf.setBoolean(DFSConfigKeys.DFS_PIPELINE_ECN_ENABLED, true);
    MiniDFSCluster cluster = null;
    try {
      cluster = new MiniDFSCluster.Builder(conf).numDataNodes(1).build();
      PipelineAck.ECN ecn = cluster.getDataNodes().get(0).getECN();
      Assert.assertNotEquals(PipelineAck.ECN.DISABLED, ecn);
    } finally {
      if (cluster != null) {
        cluster.shutdown();
      }
    }
  }
}

Add the missing files for HDFS-8009.


package org.ops4j.pax.exam.regression.nat;

import static org.ops4j.pax.exam.Constants.START_LEVEL_SYSTEM_BUNDLES;
import static org.ops4j.pax.exam.Constants.START_LEVEL_TEST_BUNDLE;
import static org.ops4j.pax.exam.CoreOptions.bootDelegationPackage;
import static org.ops4j.pax.exam.CoreOptions.composite;
import static org.ops4j.pax.exam.CoreOptions.frameworkStartLevel;
import static org.ops4j.pax.exam.CoreOptions.mavenBundle;
import static org.ops4j.pax.exam.CoreOptions.systemProperty;
import static org.ops4j.pax.exam.CoreOptions.url;

import org.ops4j.pax.exam.Option;

public class RegressionConfiguration
{
    public static Option regressionDefaults()
    {
        return composite(
            bootDelegationPackage( "sun.*" ),
            frameworkStartLevel( START_LEVEL_TEST_BUNDLE ),
            url( "link:classpath:META-INF/links/org.ops4j.pax.exam.inject.link" ).startLevel( START_LEVEL_SYSTEM_BUNDLES ),
            url( "link:classpath:META-INF/links/org.ops4j.pax.extender.service.link" ).startLevel( START_LEVEL_SYSTEM_BUNDLES ),
            url( "link:classpath:META-INF/links/org.osgi.compendium.link" ).startLevel( START_LEVEL_SYSTEM_BUNDLES ),
            url( "link:classpath:META-INF/links/org.apache.geronimo.specs.atinject.link" ).startLevel( START_LEVEL_SYSTEM_BUNDLES ),
            mavenBundle("org.slf4j", "slf4j-api").versionAsInProject().startLevel( START_LEVEL_SYSTEM_BUNDLES ),
            mavenBundle("ch.qos.logback", "logback-core").versionAsInProject().startLevel( START_LEVEL_SYSTEM_BUNDLES ),
            mavenBundle("ch.qos.logback", "logback-classic").versionAsInProject().startLevel( START_LEVEL_SYSTEM_BUNDLES ),
            systemProperty("logback.configurationFile").value( "file:src/test/resources/logback.xml" )
            );
    }

}

Use logback in Native Container regression tests and reduce verbosity


package org.apache.markt.leaks.rmi;

import java.lang.ref.WeakReference;
import java.net.URL;
import java.net.URLClassLoader;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;

public class RegistryLeak {

    public static void main(String[] args) {

        RegistryLeak registryLeak = new RegistryLeak();

        // Switch TCCL
        registryLeak.start();

        // Register new object in RMI
        registryLeak.register();

        // Deregister object
        registryLeak.deregister();

        // Restore TCCL
        registryLeak.stop();

        // Trigger GC
        System.gc();

        // Check for leak
        registryLeak.leakCheck();
    }

    private static final ClassLoader ORIGINAL_CLASS_LOADER =
            Thread.currentThread().getContextClassLoader();

    private WeakReference<ClassLoader> moduleClassLoaderRef;

    private void start() {
        ClassLoader moduleClassLoader = new URLClassLoader(new URL[] {}, ORIGINAL_CLASS_LOADER);

        Thread.currentThread().setContextClassLoader(moduleClassLoader);
        moduleClassLoaderRef = new WeakReference<>(moduleClassLoader);
    }

    private void register() {
        try {
            LocateRegistry.createRegistry(Registry.REGISTRY_PORT);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void deregister() {
        // NO-OP. NO API available.
    }

    private void stop() {
        Thread.currentThread().setContextClassLoader(ORIGINAL_CLASS_LOADER);
    }

    private void leakCheck() {
        if (moduleClassLoaderRef.get() == null) {
            System.out.println("No leak");
        } else {
            System.out.println("Leak");
        }
    }
}

Add a simple Java app that demonstrates a TCCL memory leak with RMI registry creation.


package cgeo.geocaching.utils;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import rx.Single;
import rx.Single.OnSubscribe;
import rx.SingleSubscriber;
import rx.functions.Action0;
import rx.subscriptions.Subscriptions;

import java.io.IOException;
import java.util.concurrent.atomic.AtomicBoolean;

public class RxOkHttpUtils {

    private RxOkHttpUtils() {
        // Do not instantiate
    }

    /**
     * Create a Single for running a cancellable request.
     *
     * @param client the client to use for this request
     * @param request the request
     * @return a Single containing the response or an IOException
     */
    public static Single<Response> request(final OkHttpClient client, final Request request) {
        return Single.create(new OnSubscribe<Response>() {
            @Override
            public void call(final SingleSubscriber<? super Response> singleSubscriber) {
                final Call call = client.newCall(request);
                final AtomicBoolean completed = new AtomicBoolean(false);
                singleSubscriber.add(Subscriptions.create(new Action0() {
                    @Override
                    public void call() {
                        if (!completed.get()) {
                            call.cancel();
                        }
                    }
                }));
                call.enqueue(new Callback() {
                    @Override
                    public void onFailure(final Call call, final IOException e) {
                        completed.set(true);
                        singleSubscriber.onError(e);
                    }

                    @Override
                    public void onResponse(final Call call, final Response response) throws IOException {
                        completed.set(true);
                        singleSubscriber.onSuccess(response);
                    }
                });
            }
        });
    }

}

Add utility class to run a OkHttp requests as a RxJava Single


import java.util.Scanner;

/**
 * This program computes the Fibonacci Sequence using arrays, and the length specified
 * by the user.
 **/
public class Fibonacci_Array {
    public static void main(String[] args) {
        int z;
        System.out.println("How many Fibonacci numbers do you need?");
        Scanner m = new Scanner(System.in);
        z = m.nextInt();
        int a[] = new int[z];
        a[0] = 0;
        a[1] = 1;
        for (int i = 2; i < z; i++) {
            a[i] = a[i-1] + a[i-2];
        }
        for (int i = 0; i < z; i++) {
            System.out.print(a[i] + " ");
        }
        System.out.println();
    }
}

Add problem 2 to unit 2


package jeranvier.math.dsp;

import jeranvier.math.linearAlgebra.Vector;
import jeranvier.math.util.Complex;

public class ButterworthFilter {

	private final double frequencyCut;
	private final double sampleRate;
	private final int filterOrder;
	private final double DCGain;

	public ButterworthFilter(double sampleRate, double frequencyCut, int filterOrder, double DCGain){
		this.frequencyCut = frequencyCut;
		this.sampleRate = sampleRate;
		this.filterOrder = filterOrder;
		this.DCGain = DCGain;
	}

	public ButterworthFilter(double sampleRate, double frequencyCut, int filterOrder){
			this(frequencyCut, sampleRate, filterOrder, 1.0);
	}

	public Vector filter(Vector signal){
		Vector fft = Fourier.dft(signal);
		int n = signal.size();
		int numBins = n / 2;  // Half the length of the FFT by symmetry
		double binWidth = this.sampleRate / n; // Hz
		Vector.Builder filteredBuilder = new Vector.Builder(n);
		filteredBuilder.set(1, fft.get(1));
		filteredBuilder.set(n, fft.get(n));

		for(int i = 2; i < n/2+1; i++){
			double binFreq = binWidth * i;
			double gain = Math.abs(DCGain)/(Math.sqrt( ( 1 + Math.pow( binFreq / frequencyCut, 2.0 * filterOrder))));
			filteredBuilder.set(i, fft.get(i).multiplyBy(gain));
			filteredBuilder.set(n-i+1, fft.get(n-i+1).multiplyBy(gain));
		}

		Vector filtered = filteredBuilder.build();

		return Fourier.ift(filtered);
	}
}

Add butterworth low path filter. Todo: create hight path and band path filters as well.


package com.fatico.winthing.logging;

import java.util.Arrays;
import java.util.concurrent.ConcurrentLinkedQueue;

import com.fatico.winthing.gui.WindowGUI;

import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.ConsoleAppender;

public class ConsoleLogger extends ConsoleAppender<ILoggingEvent> {
	private static final int LOG_SIZE = 50;
	private static ConcurrentLinkedQueue<String> events = new ConcurrentLinkedQueue<String>();

	public static String getEvents() {
		if (events.size() == 0) {
			return "";
		}

		String[] logs = new String[events.size()];
		events.toArray(logs);

		String result = Arrays.toString(logs);

		return result;
	}

	protected void append(ILoggingEvent event) {
		super.append(event);

		if (events.size() > LOG_SIZE) {
			events.remove();
		}

		byte[] data = encoder.encode(event);
		events.add(new String(data));

		WindowGUI gui = WindowGUI.getInstance();
		gui.reload();
	}
}

Enable logging to a GUI console window


package org.webbitserver.netty;

import java.util.Set;
import org.junit.Test;

import static org.junit.Assert.assertEquals;

/**
 *
 * @author Kushal Pisavadia
 */
public class NettyWebServerTest {

    /**
     * Tests the stop() method in NettyWebServer. Makes sure that we are stopping
     * the web server cleanly and not leaving any resources hanging.
     *
     * @throws Exception
     * @see NettyWebServer
     */
    @Test
    public void testStop() throws Exception {
        int threadCountStart = 0, threadCountEnd = 0;

        threadCountStart = this.getCurrentThreadCount();

        // Build, start, wait and stop the Netty Web Server
        NettyWebServer instance = new NettyWebServer(8080).start();
        Thread.sleep(1000); // sleep for 1 second
        instance.stop();

        threadCountEnd = this.getCurrentThreadCount();

        assertEquals(threadCountStart, threadCountEnd);
    }

    private int getCurrentThreadCount() {
        Set<Thread> threadSet = Thread.getAllStackTraces().keySet();
        Thread[] threadArray = threadSet.toArray(new Thread[threadSet.size()]);
        return threadArray.length;
    }

}

Add a test for .stop() on NettyWebServer to make sure that all resources have been released cleanly


package edu.columbia.gemma.controller;

import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.validation.BindException;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.View;
import org.springframework.web.servlet.view.RedirectView;

import edu.columbia.gemma.BaseControllerTestCase;

/**
 * This test makes use of Spring's MockHttpServletRequest and MockHttpServletResponse.
 * I have used TaxonLoaderService as the loader of choice as it is fast (small file to read from).
 *

 *

 * Copyright (c) 2004 - 2005 Columbia University
 *
 * @author keshav
 * @version $Id$
 */
public class LoaderControllerTest extends BaseControllerTestCase {

    private LoaderController c;
    private MockHttpServletRequest request;
    private MockHttpServletResponse response;
    private View returnedView;

    public void setUp() throws Exception {
        c = ( LoaderController ) ctx.getBean( "loaderController" );
        request = new MockHttpServletRequest();
        response = new MockHttpServletResponse();
        returnedView = new RedirectView( "home.jsp" );
    }

    public void tearDown() {
        c = null;
    }

    /**
     * hasHeader = true The View returned by the onSubmit method ( a RedirectView(String view) ) will obviously not
     * point to the same place on the heap as returnedView defined in setUp(). Calling toString on both will, however
     * yield the same String value: org.springframework.web.servlet.view.RedirectView: unnamed; URL [home.jsp]
     *
     * @throws Exception
     */
    public void testOnSubmitHeaderIsTrue() throws Exception {
        request.addParameter( "hasHeader", "true" );
        request.addParameter( "typeOfLoader", "taxonLoaderService" );
        ModelAndView mav = c.onSubmit( request, response, ( Object ) null, ( BindException ) null );
        assertEquals( returnedView.toString(), mav.getView().toString() );

    }

    /**
     * hasHeader = false Calling onSubmit with hasHeader = false will cause a NumberFormatException, as expected. This
     * results in a call to the view numberFormatError.jsp (to display the error), with the view name being
     * numberFormatError.
     *
     * @throws Exception
     */
    public void testOnSubmitIsFalse() throws Exception {
        request.addParameter( "hasHeader", "false" );
        request.addParameter( "typeOfLoader", "taxonLoaderService" );
        ModelAndView mav = c.onSubmit( request, response, ( Object ) null, ( BindException ) null );
        assertEquals( "numberFormatError", mav.getViewName() );

    }

}

Test to test the LoaderController


package org.beanmaker;

import org.dbbeans.util.Strings;

import org.jcodegen.html.xmlbase.XMLElement;

public class WebXMLConfig {

    private static final String XML_CONFIG_PREFIX = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
            "<web-app xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n" +
            "\t\txmlns=\"http://java.sun.com/xml/ns/javaee\"\n" +
            "\t\txmlns:web=\"http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd\"\n" +
            "\t\txsi:schemaLocation=\"http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd\"\n" +
            "\t\tversion=\"3.0\"\n" +
            "\t\txmlns=\"http://caucho.com/ns/resin\"\n" +
            "\t\txmlns:resin=\"http://caucho.com/ns/resin/core\">\n\n";

    private static final String XML_CONFIG_SUFFIX = "\n</web-app>\n";

    private static final String URL_START = "/Control";

    private final String beanName;
    private final String packageName;

    public WebXMLConfig(final String beanName, final String packageName) {
        this.beanName = beanName;
        this.packageName = packageName;
    }

    private XMLElement getServletConfigXMLElement() {
        final XMLElement servlet = new XMLElement("servlet", 1);
        servlet.addChild(getOneLiner("servlet-name", getServletName()));
        servlet.addChild(getOneLiner("servlet-class", packageName + "." + beanName + "Servlet"));
        return servlet;
    }

    private XMLElement getOneLiner(final String name, final String value) {
        final XMLElement element = new XMLElement(name, value);
        element.setOnOneLine(true);
        return element;
    }

    private String getServletName() {
        return Strings.replace(packageName, ".", "-") + "-" + beanName;
    }

    private XMLElement getServletMappingConfigXMLElement() {
        final XMLElement servletMapping = new XMLElement("servlet-mapping", 1);
        servletMapping.addChild(getOneLiner("servlet-name", getServletName()));
        servletMapping.addChild(getOneLiner("url-pattern", getURLPattern()));
        return servletMapping;
    }

    private String getURLPattern() {
        String[] parts = packageName.split("\\.");
        StringBuilder pattern = new StringBuilder();
        pattern.append(URL_START);
        for (int index = 2; index < parts.length; ++index)
            pattern.append("/").append(Strings.capitalize(parts[index]));
        pattern.append("/").append(beanName);

        return pattern.toString();
    }

    public String getFilename() {
        return "web-" + getServletName() + ".xml";
    }

    public String getSourceCode() {
        return XML_CONFIG_PREFIX + getServletConfigXMLElement().toString() + "\n"
                + getServletMappingConfigXMLElement().toString() + XML_CONFIG_SUFFIX;
    }

}

Add generation of web.xml naming/mapping code for servlets


/*
 * 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-19
 * Site       : https://www.acmicpc.net/problem/10430
 */
public class Boj10430 {

    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        String[] inputs = br.readLine().split(" ");
        int a = Integer.parseInt(inputs[0]);
        int b = Integer.parseInt(inputs[1]);
        int c = Integer.parseInt(inputs[2]);

        System.out.println((a + b) % c);
        System.out.println(((a % c) + (b%c)) % c);
        System.out.println((a*b) % c);
        System.out.println(((a%c) * (b%c)) % c);
    }

}

Solve No.10430 from Baekjoon Online Judge


/*
 * Copyright (c) 2013 SimpleServer authors (see CONTRIBUTORS)
 *
 * 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 simpleserver.log;

import java.io.CharArrayWriter;
import java.io.PrintWriter;

public class EventsLog extends AbstractLog {
  public EventsLog() {
    super("events");
  }

  public void addMessage(String event, String message) {
    CharArrayWriter charWriter = new CharArrayWriter();
    PrintWriter writer = new PrintWriter(charWriter);

	writer.append(event + "\t" + message);
    super.addMessage(charWriter.toString());

    writer.close();
    charWriter.close();
  }
}

Add support for dedicated events logfile (2 out of 3)


package edu.iu.grid.oim.test;

import static org.junit.Assert.*;
/**
 * MT
 * Unit Test Cases for CNValidator
 */

import org.junit.Test;
import edu.iu.grid.oim.view.divrep.form.validator.CNValidator;

public class CNValidatorTest {

	@Test
	public final void testIsValidCertificate() {
		CNValidator cnv = new CNValidator();

		// List of valid certificates
		String[] validCertNames = {"iu.edu", "*.edu", "www.something.com"};

		for (String validCertName : validCertNames) 	{

			assertTrue("Certificate >" + validCertName + "< is valid", cnv.isValid(validCertName));
		}
	}

	@Test
	public final void testIsInvalidCertificate() {
		CNValidator cnv = new CNValidator();

		// List of invalid certificates
		String[] invalidCertNames = {".iu.edu", "/edu"};

		for (String invalidCertName : invalidCertNames) 	{

			assertFalse("Certificate >" + invalidCertName + "< is invalid", cnv.isValid(invalidCertName));
		}
	}
}

Test case for Jira OIM-82


package integration;

import com.codeborne.selenide.*;
import org.junit.Before;
import org.junit.Test;

import static com.codeborne.selenide.CollectionCondition.*;
import static com.codeborne.selenide.Condition.visible;
import static com.codeborne.selenide.Selenide.$;
import static com.codeborne.selenide.Selenide.$$;

public class LazyEvaluationTest extends IntegrationTest {

  static SelenideElement h1 = $("h1");
  static SelenideElement button = $("#double-clickable-button");

  static SelenideElement input1 = $$("input").first();
  static SelenideElement input2 = $$("input").last();
  static SelenideElement input3 = $$("input").get(1);

  static ElementsCollection inputs = $$("input").filterBy(visible);

  @Before
  public void openTestPageWithImages() {
    openFile("page_with_jquery.html");
  }

  @Test
  public void singleElementLazyFound() {
    h1.shouldBe(visible);
    button.click();
  }

  @Test
  public void collectionRelatedLazyOperations() {
    input1.shouldBe(visible);
    input2.shouldBe(visible);
    input3.shouldBe(visible);
    inputs.shouldHave(sizeGreaterThanOrEqual(1));
  }

}

Test for lazy evaluations is added (failing at the moment)


/*
 * Copyright 2008 The Kuali Foundation.
 *
 * Licensed under the Educational Community License, Version 1.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.opensource.org/licenses/ecl1.php
 *
 * 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.kuali.kra.budget.web;

import org.kuali.kra.proposaldevelopment.web.ProposalDevelopmentWebTestBase;

import com.gargoylesoftware.htmlunit.html.HtmlElement;
import com.gargoylesoftware.htmlunit.html.HtmlPage;

public class BudgetWebTestBase extends ProposalDevelopmentWebTestBase {

    private static final String PDDOC_BUDGET_VERSIONS_LINK_NAME = "methodToCall.headerTab.headerDispatch.save.navigateTo.budgetVersions.x";
    private static final String NEW_BUDGET_VERSION_NAME = "newBudgetVersionName";
    private static final String ADD_BUDGET_VERSION_BUTTON = "methodToCall.addBudgetVersion";

    private String documentNumber;

    protected HtmlPage getBudgetVersionsPage() throws Exception {
        HtmlPage proposalPage = this.getProposalDevelopmentPage();
        documentNumber = getFieldValue(proposalPage, "document.documentHeader.documentNumber");

        setRequiredFields(proposalPage, DEFAULT_DOCUMENT_DESCRIPTION,
                DEFAULT_PROPOSAL_SPONSOR_CODE,
                DEFAULT_PROPOSAL_TITLE,
                DEFAULT_PROPOSAL_REQUESTED_START_DATE,
                DEFAULT_PROPOSAL_REQUESTED_END_DATE,
                DEFAULT_PROPOSAL_ACTIVITY_TYPE,
                DEFAULT_PROPOSAL_TYPE_CODE,
                DEFAULT_PROPOSAL_OWNED_BY_UNIT);
        HtmlPage budgetVersionsPage = clickOn(proposalPage, PDDOC_BUDGET_VERSIONS_LINK_NAME);
        return budgetVersionsPage;
    }

    protected HtmlPage addBudgetVersion(HtmlPage budgetVersionsPage) throws Exception {
        setFieldValue(budgetVersionsPage, NEW_BUDGET_VERSION_NAME, "Test Budget Version - 1");
        HtmlElement addBtn = getElementByName(budgetVersionsPage, ADD_BUDGET_VERSION_BUTTON, true);
        budgetVersionsPage = clickOn(addBtn);
        HtmlElement openBtn = getElementByName(budgetVersionsPage, "methodToCall.openBudgetVersion.line0.x");
        budgetVersionsPage = clickOn(openBtn);
        return budgetVersionsPage;
    }

    protected String getDocumentNumber() {
        return documentNumber;
    }

    protected void setDocumentNumber(String documentNumber) {
        this.documentNumber = documentNumber;
    }

}

Update budget versions page flow


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

public class DefinitionTest {

    @Rule
    public ClearRule clearRule = new ClearRule();

    @Test
    public void definition_instantiatesCorrectly_true() {
        Definition definition = new Definition("a flying animal", "the bird flew away");
        assertEquals(true, definition instanceof Definition);
    }

    public void definition_hasDefinitionString_correctString() {
        Definition definition = new Definition("a flying animal", "the bird flew away");
        assertEquals("a flying animal", definition.getString());
    }

    public void definition_hasExample_correctString() {
        Definition definition = new Definition("a flying animal", "the bird flew away");
        assertEquals("the bird flew away", definition.getExample());
    }

}

Add initial unit tests for Definition class


package yaz4jtest;
import org.junit.*;
import static org.junit.Assert.*;
import org.yaz4j.*;

/**
 * @author adam
 */
public class DinosaurTest {
    @Test
    public void test() {
        Connection con = new Connection("z3950.loc.gov:7090/voyager", 0);
        assertNotNull(con);
        con.setSyntax("usmarc");
        PrefixQuery pqf = new PrefixQuery("@attr 1=7 0253333490");
        assertNotNull(pqf);
        ResultSet set = con.Search(pqf);
        assertNotNull(set);
        Record rec = set.getRecord(0);
	assertNotNull(rec);
	// System.out.println(rec.render());
    }
}

Add other test case (uses render).


package leetcode.isomorphic_strings;

public class Solution {
    public boolean isIsomorphic(String s, String t) {
        int idx;

        int[] charMapS = new int[128];
        int[] codeS = new int[s.length()];
        char[] charS = s.toCharArray();
        idx = 0;
        for(int i = 0; i < charS.length; i++){
            char c = charS[i];
            if(charMapS[c] == 0){
                charMapS[c] = ++idx;
            }
            codeS[i] = charMapS[c];
        }

        int[] charMapT = new int[128];
        char[] charT = t.toCharArray();
        idx = 0;
        for(int i = 0; i < charT.length; i++){
            char c = charT[i];
            if(charMapT[c] == 0){
                charMapT[c] = ++idx;
            }
            if(codeS[i] != charMapT[c]) return false;
        }
        return true;
    }
}

Add java solution for 205. Isomorphic Strings


/* sbt -- Simple Build Tool
 * Copyright 2012 Eugene Vigdorchik
 */
package xsbti;

/** An addition to standard reporter. Used by the IDE. */
public interface ExtendedReporter extends Reporter
{
	public void comment(Position pos, String msg);
}

Extend reporter to be used by the IDE.


/*******************************************************************************
 * This file is part of OpenNMS(R).
 *
 * Copyright (C) 2016 The OpenNMS Group, Inc.
 * OpenNMS(R) is Copyright (C) 1999-2016 The OpenNMS Group, Inc.
 *
 * OpenNMS(R) is a registered trademark of The OpenNMS Group, Inc.
 *
 * OpenNMS(R) 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.
 *
 * OpenNMS(R) 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 OpenNMS(R).  If not, see:
 *      http://www.gnu.org/licenses/
 *
 * For more information contact:
 *     OpenNMS(R) Licensing <license@opennms.org>
 *     http://www.opennms.org/
 *     http://www.opennms.com/
 *******************************************************************************/

package org.opennms.smoketest;

import org.junit.Test;

public class ForecastIT extends OpenNMSSeleniumTestCase {
    @Test
    public void canLoadGraph() throws Exception {
        // Request a known graph with an invalid resource id
        m_driver.get(BASE_URL + "opennms/graph/forecast.jsp?resourceId=node[999].nodeSnmp[]&report=mib2.tcpopen");
        // The graph should be rendered
        findElementByXpath("//div[@class='flot-datatable-tabs']");
        // It won't have any data, but this is sufficient to very that all of the required
        // Javascript files have been loaded, and the AJAX call to get the graph was successful
    }
}

Add a simple smoke test used to validate some of the Javascript rendering.


package leetcode.search_for_a_range;

public class Solution {
    public int[] searchRange(int[] A, int target) {
    	if(A == null || A.length == 0) return new int[]{-1, -1};
    	int U, L;
    	int left, right;
    	U = A.length;
    	L = -1;
    	while(L + 1 < U){
    		int mid = L + (U - L) / 2;
    		if(A[mid] >= target){
    			U = mid;
    		}else{
    			L = mid;
    		}
    	}
    	if(U < A.length && A[U] == target) left = U;
    	else left = -1;

    	U = A.length;
    	L = -1;
    	while(L + 1 < U){
    		int mid = L + (U - L) / 2;
    		if(A[mid] <= target){
    			L = mid;
    		}else{
    			U = mid;
    		}
    	}
    	if(L >= 0 && A[L] == target) right = L;
    	else right = -1;
    	return new int[]{left, right};
    }

    public static void main(String[] args){
    	for(int x : new Solution().searchRange(new int[]{1, 2, 3, 3}, 4))
    		System.err.print(x + ", ");
    	System.err.println("");
    }
}

Add java solution for 34. Search for a Range


package com.twu.biblioteca;

import org.junit.Test;

import static org.junit.Assert.assertEquals;

public class BookTest {

    @Test
    public void shouldReturnBookName() {
        Book book = new Book("The Alchemist", "Paulo Coelho", 1988);

        assertEquals("The Alchemist", book.getName());
    }

    @Test
    public void shouldReturnAuthorName() {
        Book book = new Book("The Alchemist", "Paulo Coelho", 1988);

        assertEquals("Paulo Coelho", book.getAuthor());
    }

    @Test
    public void shouldReturnPublicationYear() {
        Book book = new Book("The Alchemist", "Paulo Coelho", 1988);

        assertEquals(1988, book.getPublicationYear());
    }

    @Test
    public void shouldReturnABook() {
        Book book = new Book("The Alchemist", "Paulo Coelho", 1988);

        assertEquals("Book name = The Alchemist, Author = Paulo Coelho, Year of publication = 1988", book.toString());
    }

}

Test the attributes of Book class


/**
 * END USER LICENSE AGREEMENT (“EULA”)
 *
 * READ THIS AGREEMENT CAREFULLY (date: 9/13/2011):
 * http://www.akiban.com/licensing/20110913
 *
 * BY INSTALLING OR USING ALL OR ANY PORTION OF THE SOFTWARE, YOU ARE ACCEPTING
 * ALL OF THE TERMS AND CONDITIONS OF THIS AGREEMENT. YOU AGREE THAT THIS
 * AGREEMENT IS ENFORCEABLE LIKE ANY WRITTEN AGREEMENT SIGNED BY YOU.
 *
 * IF YOU HAVE PAID A LICENSE FEE FOR USE OF THE SOFTWARE AND DO NOT AGREE TO
 * THESE TERMS, YOU MAY RETURN THE SOFTWARE FOR A FULL REFUND PROVIDED YOU (A) DO
 * NOT USE THE SOFTWARE AND (B) RETURN THE SOFTWARE WITHIN THIRTY (30) DAYS OF
 * YOUR INITIAL PURCHASE.
 *
 * IF YOU WISH TO USE THE SOFTWARE AS AN EMPLOYEE, CONTRACTOR, OR AGENT OF A
 * CORPORATION, PARTNERSHIP OR SIMILAR ENTITY, THEN YOU MUST BE AUTHORIZED TO SIGN
 * FOR AND BIND THE ENTITY IN ORDER TO ACCEPT THE TERMS OF THIS AGREEMENT. THE
 * LICENSES GRANTED UNDER THIS AGREEMENT ARE EXPRESSLY CONDITIONED UPON ACCEPTANCE
 * BY SUCH AUTHORIZED PERSONNEL.
 *
 * IF YOU HAVE ENTERED INTO A SEPARATE WRITTEN LICENSE AGREEMENT WITH AKIBAN FOR
 * USE OF THE SOFTWARE, THE TERMS AND CONDITIONS OF SUCH OTHER AGREEMENT SHALL
 * PREVAIL OVER ANY CONFLICTING TERMS OR CONDITIONS IN THIS AGREEMENT.
 */

package com.akiban.sql.server;

import java.util.ArrayDeque;
import java.util.Deque;

public class ServerCallContextStack
{
    private ServerCallContextStack() {
    }

    private static final ThreadLocal<Deque<ServerQueryContext>> tl = new ThreadLocal<Deque<ServerQueryContext>>() {
        @Override
        protected Deque<ServerQueryContext> initialValue() {
            return new ArrayDeque<ServerQueryContext>();
        }
    };

    public static Deque<ServerQueryContext> stack() {
        return tl.get();
    }

    public static ServerQueryContext current() {
        return stack().peekLast();
    }

    public static void push(ServerQueryContext call) {
        stack().addLast(call);
    }

    public static void pop(ServerQueryContext call) {
        ServerQueryContext last = stack().removeLast();
        assert (call == last);
    }
}

Add a stack of calls.


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

package com.google.sps.servlets;

import java.io.IOException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/availability")
public class AvailabilityServlet extends HttpServlet {

    @Override
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
        response.setContentType("plain/text");
        response.getWriter().println("To be implemented");
    }

    @Override
    public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
        response.setContentType("plain/text");
        response.getWriter().println("To be implemented");
    }
}

Create servlet to handle displaying a tutor's availability.


// Copyright 2014 Google 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.google.devtools.build.docgen;

import com.google.devtools.build.lib.Constants;
import com.google.devtools.build.lib.analysis.ConfiguredRuleClassProvider;
import com.google.devtools.build.lib.packages.RuleClass;
import com.google.devtools.build.lib.packages.RuleClassProvider;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Map;

/**
 * Prints out list of known rules.
 */
public class ListRuleMain {

  private static ConfiguredRuleClassProvider createRuleClassProvider()
      throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException,
          IllegalAccessException {
    Class<?> providerClass = Class.forName(Constants.MAIN_RULE_CLASS_PROVIDER);
    Method createMethod = providerClass.getMethod("create");
    return (ConfiguredRuleClassProvider) createMethod.invoke(null);
  }

  public static void main(String[] args) throws Exception {
    RuleClassProvider provider = createRuleClassProvider();
    Map<String, RuleClass> rcMap = provider.getRuleClassMap();
    for (String name : rcMap.keySet()) {
      System.out.println(name);
    }
  }
}

Add main to print list of rules.


public class HybridSort {

    private static final int number = 154; // use insertion sort if size < number

    public static void hybridSort(int[] arr, int start, int end) {
        if ( end - start < number) {
            insertionSort(arr, start, end);
        } else {
            if (start < end) {
                int part = QuickSort.partition(arr, start, end);
                hybridSort(arr, start, part - 1);
                hybridSort(arr, part + 1, end);
            }
        }
    }

    private static void insertionSort(int[] arr, int start, int end) {
        for (int i = start; i <= end; i++) {
            int tmp = arr[i];
            for (int j = i - 1; j >= 0 && tmp < arr[j] ; j-- ) {
                arr[j+1] = arr[j];
                arr[j] = tmp ;
            }
        }
    }
}

Add hybrid sort java implementation


package au.org.ands.vocabs.toolkit.db;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;

/** Test of parsing JSON. */
public final class TestJsonParsing {

    /** Private constructor for test class. */
    private TestJsonParsing() {
    }

    /** Main program.
     * @param args Command-line arguments.
     */
    public static void main(final String[] args) {
      String jsonString =
              "[{\"type\": \"HARVEST\",\"provider_type\":"
              + " \"PoolParty\",\"project_id\":"
              + " \"1DCE1494-A022-0001-FFBD-12DE19E01FEB\"},"
              + "{\"type\": \"TRANSFORM\"},{\"type\": \"IMPORT\"}]";
      JsonNode root = TasksUtils.jsonStringToTree(jsonString);
      if (root == null) {
          System.out.println("Got null.");
      } else {
          System.out.println("Got instance of:" + root.getClass().toString());
          if (!(root instanceof ArrayNode)) {
              System.out.println("Didn't get an array.");
          } else {
              for (JsonNode node : (ArrayNode) root) {
                  System.out.println("Got element: " + node.toString());
                  if (!(node instanceof ObjectNode)) {
                      System.out.println("Didn't get an object.");
                  } else {
                      System.out.println("task type: "
                              + node.get("type"));
                  }
              }
          }
      }
    }

}

Add test of JSON parsing


/*
 * 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.logging.log4j.core.appender.rolling;

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

/**
 *
 */
public class FileSizeTest {

    private final static long EXPECTED = 10 * 1024;
    @Test
    public void testFileSize() throws Exception {

        long value = FileSize.parse("10KB", 0);
        assertTrue("unexpected value " + value, value == EXPECTED);
        value = FileSize.parse("10 KB", 0);
        assertTrue("unexpected value " + value, value == EXPECTED);
    }
}

Verify that file sizes are parsed correctly.


package cl.fatman.capital.fund;

import static org.junit.Assert.*;

import java.time.LocalDate;

import org.junit.Test;

public class ExtractFundDataTest {

	@Test
	public void getFundDataTest() {
		ExtractFundData efData = new ExtractFundData("blabla");
		assertNotNull("List with Fund data should not be null", efData.getFundData());
	}

	@Test
	public void getFundRateDataTest() {
		ExtractFundData efData = new ExtractFundData("blabla");
		LocalDate frDate = LocalDate.now();
		assertNotNull("List with Fund Rate data should not be null", efData.getFundRateData(frDate));
	}
}

Add junit test to check the fund data extraction is not empty.


package org.tinylog.impl.test;

import org.tinylog.impl.format.style.Style;

/**
 * Renderer for {@link Style Styles}.
 */
public class StyleRenderer {

	private final Style style;

	/**
	 * @param style The style to render
	 */
	public StyleRenderer(Style style) {
		this.style = style;
	}

	/**
	 * Renders the stored style with the passed text as input.
	 *
	 * @param text The text to style
	 * @return The render result
	 */
	public String render(String text) {
		StringBuilder builder = new StringBuilder(text);
		style.apply(builder, 0);
		return builder.toString();
	}

}

Add style render for JUnit tests


// Copyright Verizon Media. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package ai.vespa.feed.client;

import java.util.concurrent.CompletableFuture;

/**
 * Determines the number of requests to have inflight at any point.
 *
 * @author jonmv
 */
interface Throttler {

    /**
     * A request was just sent with {@code vessel}, with {@code inflight} total in flight.
     */
    void sent(long inflight, CompletableFuture<HttpResponse> vessel);

    /**
     * A successful response was obtained.
     */
    void success();

    /**
     * A throttle signal was obtained from the server.
     */
    void throttled(long inflight);

    /**
     * The target inflight operations right now.
     */
    long targetInflight();

}

Add interface that was moved up


package com.andela.voluminotesapp.utilities;

import android.graphics.Region;
import android.view.View;

import com.andela.voluminotesapp.callbacks.OnIntersectListener;

public class Collision {
    private Region region1;
    private Region region2;

    public Collision(View layout1, View layout2) {
        region1 = getRegion(layout1);
        region2 = getRegion(layout2);
    }

    public void intersect(OnIntersectListener listener){
        if (region1.op(region2, Region.Op.INTERSECT)) {
            listener.onIntersect();
        }
    }

    private Region getRegion(View viewHolder) {
        int[] layout = new int[2];
        viewHolder.getLocationOnScreen(layout);
        int x = layout[0];
        int y = layout[1];
        int width = viewHolder.getWidth();
        int height = viewHolder.getHeight();

        return new Region(x, y, x + width, y + height);
    }
}

Add class to detect collision on layouts


/*
 * Multiples of 3 or 5
 * Problem 1
 * If we list all the natural numbers below 10 that are multiples of 3 or 5,
 * we get 3, 5, 6 and 9. The sum of these multiples is 23.
 * Find the sum of all the multiples of 3 or 5 below 1000.
 */
public class Problem1 {
    public static void main (String[] args) {
        int sum = 0;
        for(int i = 1; i < 1000 ; i++){
            if(i%3==0 || i%5==0){   //if number is multiple of 3 OR 5...
               sum += i;            //add that number to the total sum
            }
        }
        System.out.println(sum);
    }
}

Check in solution to problem 1 in java


/**
 *
 * Copyright (c) Microsoft Corporation. All rights reserved.
 * Licensed under the MIT License. See License.txt in the project root for license information.
 *
 */

package com.microsoft.rest;

import com.fasterxml.jackson.annotation.JsonProperty;
import org.apache.commons.lang3.ClassUtils;
import org.apache.commons.lang3.reflect.FieldUtils;
import org.joda.time.DateTime;

import java.lang.reflect.Field;
import java.time.LocalDate;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * ServiceClient is the abstraction for accessing REST operations and their payload data types.
 */
public class Validator {
    public static void validate(Object request, Class type) throws NullPointerException {
        Field[] fields = FieldUtils.getAllFields(type);
        for (Field field : fields) {
            field.setAccessible(true);
            JsonProperty annotation = field.getAnnotation(JsonProperty.class);
            Object property = null;
            try {
                property = field.get(request);
            } catch (IllegalAccessException e) {
                // Ignore inaccessible fields
            }
            if (annotation != null && annotation.required()) {
                Objects.requireNonNull(property, field.getName() + " == null");
            }

            if (property != null) {
                Class propertyType = property.getClass();
                if (ClassUtils.isAssignable(propertyType, List.class)) {
                    List<?> items = (List<?>)property;
                    for (Object item : items) {
                        Validator.validate(item, item.getClass());
                    }
                }
                if (ClassUtils.isAssignable(propertyType, Map.class)) {
                    Map<?, ?> entries = (Map<?, ?>)property;
                    for (Map.Entry<?, ?> entry : entries.entrySet()) {
                        Validator.validate(entry.getKey(), entry.getKey().getClass());
                        Validator.validate(entry.getValue(), entry.getValue().getClass());
                    }
                }
                else if (!(ClassUtils.isPrimitiveOrWrapper(propertyType) ||
                        ClassUtils.isAssignable(propertyType, LocalDate.class) ||
                        ClassUtils.isAssignable(propertyType, DateTime.class) ||
                        ClassUtils.isAssignable(propertyType, String.class))) {
                    Validator.validate(property, propertyType);
                }
            }
        }
    }
}

Add validator based on JSON annotation


//
// $Id$

package com.threerings.util;

import com.threerings.util.unsafe.Unsafe;

/**
 * Does something extraordinary.
 */
public class UIDTest
{
    public static void main (String[] args)
    {
        if (Unsafe.setuid(1000)) {
            System.err.println("Yay! My uid is changed.");
        } else {
            System.err.println("Boo hoo! I couldn't change my uid.");
        }
        if (Unsafe.setgid(60)) {
            System.err.println("Yay! My gid is changed.");
        } else {
            System.err.println("Boo hoo! I couldn't change my gid.");
        }
        try {
            Thread.sleep(60*1000L);
        } catch (Exception e) {
        }
    }
}

Test program for the uid fiddly business.


package org.concord.framework.otrunk.wrapper;

import org.concord.framework.otrunk.OTObjectInterface;
import org.concord.framework.otrunk.OTObjectMap;

public interface OTHash extends OTObjectInterface {
	public OTObjectMap getEntries();
}

Add a wrapper for OTObjectMap.


package org.apache.pig.tools.grunt;

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

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

import org.apache.pig.ExecType;
import org.apache.pig.PigServer;
import org.apache.pig.tools.grunt.GruntParser.ExplainState;
import org.junit.Before;
import org.junit.Test;

public class TestGruntParser {
    private GruntParser parser;
    static PigServer pig;

    @Before
    public void setup() throws IOException {
        pig = new PigServer(ExecType.LOCAL);
    }

    @Test
    public void testProcessRemove() throws IOException {
        File tmpFile = File.createTempFile("TestGruntParser", "testProcessRemove");
        String dummyScript = "";
        parser = new GruntParser(new ByteArrayInputStream(dummyScript.getBytes()));
        parser.setParams(pig);

        //Delete existing file and check that it doesn't exist
        parser.processRemove(tmpFile.getAbsolutePath(), "");
        assertFalse(tmpFile.exists());

        //Delete non-existing file and check for exception
        try {
            parser.processRemove(tmpFile.getAbsolutePath(), "");
            fail("processRemove should throw exception when deleting missing file.");
        } catch (IOException e) {
            //Yay
        }

        //Delete non-existing file with force, no exception
        parser.processRemove(tmpFile.getAbsolutePath(), "force");

        //Ensure that remove isn't processed when in explain mode
        tmpFile = File.createTempFile("TestGruntParser", "testProcessRemove");
        parser.setExplainState(new ExplainState("","","",false,""));
        parser.processRemove(tmpFile.getAbsolutePath(), "force");
        assertTrue(tmpFile.exists());
    }
}

Add support for removing s3 files


package edu.stuy.commands;

/**
 * Drives to fender, shoots balls at two point hoop.
 * @author 694
 */

import edu.stuy.subsystems.Flywheel;
import edu.wpi.first.wpilibj.command.CommandGroup;

public class AutonSetting7_3Point extends CommandGroup {

    public AutonSetting7_3Point() {
        addSequential(new AutonDriveToFender(Autonomous.t_closeKeyToFender));
        double distanceInches = Flywheel.distances[Flywheel.FENDER_INDEX];
        addParallel(new AutonWaitThenConvey());
        addSequential(new FlywheelRun(distanceInches, Flywheel.speedsTopHoop));
    }
}

Add 3 point auton drive to fender.


package imagej2.ij1bridge.plugin;

import ij.IJ;
import ij.ImageJ;
import ij.Menus;
import imagej2.plugin.PluginEntry;
import imagej2.plugin.PluginFinder;

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

import org.openide.util.lookup.ServiceProvider;

@ServiceProvider(service=PluginFinder.class)
public class Ij1PluginFinder implements PluginFinder {

	@Override
	public void findPlugins(List<PluginEntry> plugins) {
		if (IJ.getInstance() == null) {
			// TODO -- use NO_SHOW mode (requires ImageJ 1.44)
			new ImageJ();
			IJ.getInstance().setVisible(false);
		}
		final Hashtable<?, ?> commands = Menus.getCommands();
		for (final Object key : commands.keySet()) {
			final String pluginClass = commands.get(key).toString();
			final List<String> parentMenu = new ArrayList<String>();
			// TODO -- populate with actual menu location
			parentMenu.add("Plugins");
			final String label = key.toString();
			final PluginEntry pluginEntry = new PluginEntry(pluginClass, parentMenu, label);
			plugins.add(pluginEntry);
		}
	}

	/**
	 * Tests the IJ1 plugin discovery mechanism,
	 * printing a list of all discovered plugins.
	 */
	public static void main(String[] args) {
		System.setProperty("plugins.dir", "/Applications/Science/ImageJ/plugins");//TEMP
		System.out.println("Finding plugins...");
		List<PluginEntry> plugins = new ArrayList<PluginEntry>();
		new Ij1PluginFinder().findPlugins(plugins);
		System.out.println("Discovered plugins:");
		for (PluginEntry plugin : plugins) {
			System.out.println("\t" + plugin);
		}
		System.exit(0);
	}

}

Add (overly) simple IJ1 discovery code, using ij.Menus.


package org.apache.ddlutils.platform;

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

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

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

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

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

    public void setUp()
    {
    }

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

    protected String getDatabaseName() {
        return null;
    }

    public class SqlBuilderImpl extends SqlBuilder {

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

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


public class Solution {
    public static boolean isAbbr(String name, String abbr) {
        int namePos = 0;
        int abbrPos = 0;
        while (namePos < name.length() && abbrPos < abbr.length()) {
            if (Character.isDigit(abbr.charAt(abbrPos))) {
                int digitEnd = abbrPos;
                while (Character.isDigit(abbr.charAt(digitEnd))) {
                    digitEnd++;
                }
                int abbrNum = Integer.parseInt(abbr.substring(abbrPos, digitEnd));
                namePos += abbrNum;
                abbrPos = digitEnd;
            } else {
                if (name.charAt(namePos) != abbr.charAt(abbrPos)) {
                    return false;
                }
                namePos++;
                abbrPos++;
            }
        }
        return namePos == name.length() && abbrPos == abbr.length();
    }

    public static void main(String[] args) {
        System.out.println(isAbbr("LOCALIZATION", "L10N"));
        System.out.println(isAbbr("LOCALIZATION", "L9N"));
        System.out.println(isAbbr("LOCALIZATION", "L10Q"));
    }
}

Add java solution to q2


/**
 *  @author georgeda
 *
 *  $Id: EvsTreeUtil.java,v 1.1 2005-09-21 20:34:59 georgeda Exp $
 *
 *  $Log: not supported by cvs2svn $
 *
 */
package gov.nih.nci.camod.util;

import gov.nih.nci.camod.Constants;
import gov.nih.nci.evs.query.EVSQuery;
import gov.nih.nci.evs.query.EVSQueryImpl;
import gov.nih.nci.system.applicationservice.ApplicationService;

import java.util.*;

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

/**
 * Static helper class for caching EVS values.
 *
 */
public class EvsTreeUtil {

    static private final Log log = LogFactory.getLog(EvsTreeUtil.class);

    static private Map ourOrganDescriptions = new HashMap();

    private EvsTreeUtil() {
    }

    /**
     * Get a preferred name based on a concept code. Will return the cached
     * value if it has been fetched before.
     *
     * @param inConceptCode the concept code to get the preferred name for.
     *
     * @return the preferred name, or an empty string if something goes wrong.
     */
    public static synchronized String getEVSPreferedOrganDescription(String inConceptCode) {

        log.trace("Entering getEVSPreferedOrganDescription");

        String theDescription = "";

        if (ourOrganDescriptions.containsKey(inConceptCode)) {
            theDescription = (String) ourOrganDescriptions.get(inConceptCode);
        } else {

            try {
                // Get the app service uri
                ResourceBundle theBundle = ResourceBundle.getBundle("camod");

                ApplicationService appService = ApplicationService.getRemoteInstance(theBundle
                        .getString(Constants.Evs.URI_KEY));

                EVSQuery theConceptNameQuery = new EVSQueryImpl();
                theConceptNameQuery.getConceptNameByCode(Constants.Evs.NAMESPACE, inConceptCode);

                List theConceptNames = (List) appService.evsSearch(theConceptNameQuery);

                // Should only be one
                if (theConceptNames.size() > 0) {

                    String theDisplayName = (String) theConceptNames.get(0);

                    EVSQuery theDisplayNameQuery = new EVSQueryImpl();
                    theDisplayNameQuery.getPropertyValues(Constants.Evs.NAMESPACE, theDisplayName,
                            Constants.Evs.DISPLAY_NAME_TAG);

                    // Should only be one
                    List theDisplayNameList = (List) appService.evsSearch(theDisplayNameQuery);

                    if (theDisplayNameList.size() > 0) {
                        theDescription = (String) theDisplayNameList.get(0);

                        // Cache for next time
                        ourOrganDescriptions.put(inConceptCode, theDescription);
                    }
                }

            } catch (Exception e) {
                log.error("Exception getting preferred description: ", e);
            }
        }
        log.trace("Exiting getEVSPreferedOrganDescription");

        return theDescription;
    }
}

Create util for fetching/caching EVS data


package io.miti.shortstop.util;

public final class HeaderField
{
  public static final String HK_CONTENT_LENGTH = "Content-Length";
  public static final String HK_ACCEPT_ENCODING = "Accept-Encoding";
  public static final String HK_TRANSFER_ENCODING = "Transfer-Encoding";
  public static final String HK_CONTENT_ENCODING = "Content-Encoding";

  /** Make the default constructor private. */
  private HeaderField() {
    super();
  }
}

Use constants for header field keys.


package com.elmakers.mine.bukkit.action.builtin;

import com.elmakers.mine.bukkit.action.BaseSpellAction;
import com.elmakers.mine.bukkit.api.action.CastContext;
import com.elmakers.mine.bukkit.api.block.MaterialBrush;
import com.elmakers.mine.bukkit.api.spell.SpellResult;
import org.bukkit.block.Block;

public class CheckBlockAction extends BaseSpellAction {
    @SuppressWarnings("deprecation")
    @Override
    public SpellResult perform(CastContext context) {
        MaterialBrush brush = context.getBrush();
        Block block = context.getTargetBlock();
        if (brush != null && brush.isErase()) {
            if (!context.hasBreakPermission(block)) {
                return SpellResult.CANCELLED;
            }
        } else {
            if (!context.hasBuildPermission(block)) {
                return SpellResult.CANCELLED;
            }
        }
        if (!context.isDestructible(block)) {
            return SpellResult.CANCELLED;
        }
        return SpellResult.CAST;
    }

    @Override
    public boolean requiresTarget() {
        return true;
    }
}

Add CheckBlock action, for conditionally cancelling a spell


package org.svetovid.installer;

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

public final class JavaInstallation {

    private Path location;
    private Path binLocation;
    private Path libLocation;

    private JavaInstallation() {
        this.location = null;
        String[] extdirs = System.getProperty("java.ext.dirs").split(File.pathSeparator);
        if (extdirs.length > 1) {
            libLocation = Paths.get(extdirs[1]);
        }
    }

    private JavaInstallation(Path location) {
        this.location = location;
        initialize();
    }

    private void initialize() {
        if (location == null) {
            return;
        }
        binLocation = libLocation = null;
        if (!Files.isDirectory(location)) {
            return;
        }
        binLocation = location.resolve("bin");
        if (!Files.isDirectory(binLocation)) {
            return;
        }
        libLocation = location.resolve("jre/lib/ext");
        if (!Files.isDirectory(libLocation)) {
            libLocation = location.resolve("lib/ext");
        }
        if (!Files.isDirectory(libLocation)) {
            return;
        }
    }

    public Path getLocation() {
        return location;
    }

    public Path getBinLocation() {
        return binLocation;
    }

    public Path getLibLocation() {
        return libLocation;
    }
}

Add class for representation of Java installations


/***************************************************************************
 *   Copyright (C) 2015 by Fabrizio Montesi <famontesi@gmail.com>          *
 *                                                                         *
 *   This program is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU Library General Public License as       *
 *   published by the Free Software Foundation; either version 2 of the    *
 *   License, or (at your option) any later version.                       *
 *                                                                         *
 *   This program is distributed in the hope that it will be useful,       *
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
 *   GNU General Public License for more details.                          *
 *                                                                         *
 *   You should have received a copy of the GNU Library General Public     *
 *   License along with this program; if not, write to the                 *
 *   Free Software Foundation, Inc.,                                       *
 *   59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
 *                                                                         *
 *   For details about the authors of this software, see the AUTHORS file. *
 ***************************************************************************/

package jolie;

import java.util.Map;
import java.util.concurrent.Future;
import jolie.net.SessionMessage;
import jolie.runtime.InputOperation;

/**
 *
 * @author Fabrizio Montesi
 */
public abstract class TransparentExecutionThread extends ExecutionThread
{
	public TransparentExecutionThread( jolie.process.Process process, ExecutionThread parent )
	{
		super( process, parent );
	}

	public jolie.State state()
	{
		return parent.state();
	}

	public Future< SessionMessage> requestMessage( InputOperation operation, ExecutionThread ethread )
	{
		return parent.requestMessage( operation, ethread );
	}

	public Future< SessionMessage> requestMessage( Map< String, InputOperation> operations, ExecutionThread ethread )
	{
		return parent.requestMessage( operations, ethread );
	}

	@Override
	public String getSessionId()
	{
		return parent.getSessionId();
	}
}

Fix for invoke@Reflection, part 2


package lemming.data;

import java.util.AbstractMap;

/**
 * An Entry maintaining a key and a value. The value may be changed using the setValue method.
 *
 * @param <K> key data type
 * @param <V> value data type
 * @see java.util.AbstractMap.SimpleEntry
 */
public class Tuple<K, V> extends AbstractMap.SimpleEntry<K, V> {

    /**
     * Creates a tuple.
     *
     * @param key   key object
     * @param value value object
     */
    public Tuple(K key, V value) {
        super(key, value);
    }
}

Implement a tuple data type based on class AbstractMap.SimpleEntry.


package leetcode.triangle;

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

public class Solution {
    public int minimumTotal(ArrayList<ArrayList<Integer>> triangle) {
        if(triangle == null || triangle.size() == 0) return 0;
        int size = triangle.size();
        for(int i = size - 1; i > 0; i--){
        	for(int j = 0; j < i; j++){
        		ArrayList<Integer> row_i = triangle.get(i);
        		ArrayList<Integer> row_i_1 = triangle.get(i - 1);
        		int a = row_i.get(j);
        		int b = row_i.get(j + 1);
        		int v = row_i_1.get(j);
        		row_i_1.set(j, v + Math.min(a, b));
        	}
        }
        return triangle.get(0).get(0);
    }
    public static void main(String[] args){
    	ArrayList<ArrayList<Integer>> input = new ArrayList<ArrayList<Integer>>();
    	input.add(new ArrayList<Integer>(Arrays.asList(new Integer[]{2})));
    	input.add(new ArrayList<Integer>(Arrays.asList(new Integer[]{3, 4})));
    	input.add(new ArrayList<Integer>(Arrays.asList(new Integer[]{6, 5, 7})));
    	input.add(new ArrayList<Integer>(Arrays.asList(new Integer[]{4, 1, 8, 3})));
    	System.err.println(new Solution().minimumTotal(input) + "");
    }
}

Add java solution for 120. Triangle


package com.google.sps.tool;

import java.io.IOException;
import javax.servlet.http.HttpServletResponse;
import com.google.gson.Gson;
import java.util.Map;
import java.util.HashMap;

public class ResponseHandler {

  public static void sendErrorMessage(HttpServletResponse response, String error) throws IOException {
    Map<String, String> jsonErrorInfo = new HashMap<>();
    jsonErrorInfo.put("error", error);
    response.setContentType("application/json;");
    response.getWriter().println(new Gson().toJson(jsonErrorInfo));
  }
}

Add class that handles error


package com.vtence.molecule.examples.session;

import com.vtence.molecule.Application;
import com.vtence.molecule.Request;
import com.vtence.molecule.Response;
import com.vtence.molecule.Session;
import com.vtence.molecule.middlewares.Router;
import com.vtence.molecule.routing.DynamicRoutes;
import com.vtence.molecule.simple.SimpleServer;
import com.vtence.molecule.simple.session.CookieTracker;
import com.vtence.molecule.simple.session.SessionPool;

import java.io.IOException;

public class EnablingSessions {

    public static void main(String[] args) throws IOException {
        SimpleServer server = new SimpleServer(8080);

        // Enable sessions, using a cookie tracking strategy with an in-memory session pool
        server.enableSessions(new CookieTracker(new SessionPool()));

        server.run(Router.draw(new DynamicRoutes() {{

            map("/").to(new Application() {
                public void handle(Request request, Response response) throws Exception {
                    Session session = request.session(false);
                    String username = (session != null) ?
                            session.<String>get("username") : "Guest";
                    response.body("Welcome, " + username);
                }
            });

            post("/login").to(new Application() {
                public void handle(Request request, Response response) throws Exception {
                    String username = request.parameter("username");
                    request.session().put("username", username);
                    response.redirectTo("/");
                }
            });

            delete("/logout").to(new Application() {
                public void handle(Request request, Response response) throws Exception {
                    Session session = request.session(false);
                    if (session != null) session.invalidate();
                    response.redirectTo("/");
                }
            });
        }}));
    }
}

Add example showing basic session usage


package dijkstras;

import dijkstras.Dijkstras;		// My implementation of Dijkstras algorithm in package dijkstras

/*
	This class test Dijkstras shortest path algorithm
*/

class TestDijkstras
{

	// Test A

	public static void testA(){

		int N = 6;		// No. of vertices
		int M = 10;		// No. of edges
		int edges[][] = {	{1,2,10}, 		// Edges
							{2,3,1},
							{3,4,4},
							{4,3,6},
							{5,4,2},
							{1,5,5},
							{2,5,2},
							{5,2,3},
							{5,3,9},
							{4,1,7}
						};

		int s = 1;		// source vertex

		Dijkstras dk = new Dijkstras(N, M, edges, s);

		dk.findShortestPaths();

		System.out.println("Shortest Distances: ");
		dk.showDist();

		System.out.println("Shortest Paths: ");
		for(int i=1;i<=N;i++){

			System.out.print(i+ ": ");
			dk.printPath(i);
			System.out.println();
		}

	}

	public static void main(String args[]){

			// Call testA()

			testA();
	}
}

Add test class for dijkstras algorithm


package leetcode.maximal_rectangle;

import java.util.Random;
import java.util.Stack;

public class Solution {
    public int maximalRectangle(char[][] matrix) {
    	if(matrix == null || matrix.length == 0 || matrix[0].length == 0) return 0;
    	int height = matrix.length;
    	int width = matrix[0].length;
    	int[][] subsum = new int[height][width];
        for(int i = 0; i < height; i++){
        	for(int j = 0; j < width; j++){
        		if(i == 0){
        			subsum[i][j] = (matrix[i][j] == '1' ? 1 : 0);
        		}else{
        			if(matrix[i][j] == '1'){
        				subsum[i][j] = subsum[i - 1][j];
        			}
        			subsum[i][j] += (matrix[i][j] == '1' ? 1 : 0);
        		}
        	}
        }
        int maxArea = 0;
        for(int i = 0; i < height; i++){
        	int area = largestRectangleArea(subsum[i]);
        	if(area > maxArea) maxArea = area;
        }
        return maxArea;
    }

    public static class Histogram{
		int offset, height;
		public Histogram(int offset, int height){
			this.offset = offset;
			this.height = height;
		}
	}

    public int largestRectangleArea(int[] height) {
    	Stack<Histogram> stack = new Stack<Histogram>();
    	int length = height.length;
    	int max = 0;
    	for(int i = 0; i < length; i++){
    		int left = i;
    		while(!stack.isEmpty() && stack.peek().height >= height[i]){
    			Histogram hist = stack.pop();
    			int area = hist.height * (i - hist.offset);
    			left = hist.offset;
    			if(area > max) max = area;
    		}
    		stack.push(new Histogram(left, height[i]));
    	}
    	while(!stack.isEmpty()){
			Histogram hist = stack.pop();
			int area = hist.height * (length - hist.offset);
			if(area > max) max = area;
    	}
    	return max;
    }

    public static void main(String[] args){
    	int W = 10, H = 5;
    	char[][] matrix = new char[H][W];
    	Random r = new Random();
    	for(int i = 0; i < H; i++){
    		for(int j = 0; j < W; j++){
    			int d = r.nextInt(7);
    			if(d > 0)
    				matrix[i][j] = '1';
    			else
    				matrix[i][j] = '0';
    		}
    	}
    	for(char[] s : matrix){
    		System.err.println(s);
    	}
    	System.err.println(new Solution().maximalRectangle(matrix));
    }
}

Add java solution for 85. Maximal Rectangle


/*
 * Copyright 2017, TeamDev Ltd. All rights reserved.
 *
 * Redistribution and use in source and/or binary forms, with or without
 * modification, must retain the above copyright notice and the following
 * disclaimer.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

package org.spine3.base;

import org.junit.Test;
import org.spine3.test.Tests;

/**
 * @author Alexander Yevsyukov
 */
public class VersionsShould {

    @Test
    public void have_private_utility_ctor() {
        Tests.hasPrivateParameterlessCtor(Versions.class);
    }

    @Test(expected = IllegalArgumentException.class)
    public void check_version_increment() {
        Versions.checkIsIncrement(
                Tests.newVersionWithNumber(2),
                Tests.newVersionWithNumber(1)
        );
    }
}

Increase coverage of `Versions` tests


/*
 * Copyright 2015 Open mHealth
 *
 * 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.openmhealth.shimmer.common.domain;

/**
 * FIXME
 *
 * @author Emerson Farrugia
 */
public class DataPointRequest {

}

Add a bare data point request


package edu.chl.proton.model;

import org.testng.annotations.Test;
import static org.junit.Assert.assertTrue;

/**
 * @author Stina Werme
 * Created by stinawerme on 09/05/17.
 */
public class FileTest {

    @Test public void test() {
    }
}

Add test class for File


package leetcode;

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

/**
 * https://leetcode.com/problems/n-queens/
 */
public class Problem51 {
    public List<List<String>> solveNQueens(int n) {
        List<List<String>> result = new ArrayList<>();
        // TODO
        return result;
    }

    public static void main(String[] args) {
        Problem51 prob = new Problem51();
        List<List<String>> result = prob.solveNQueens(4);
        for (List<String> row : result) {
            System.out.println(row);
        }
    }
}

Add skeleton for problem 51


package mylab.puzzles;

/**
 * Minimum Horizontal Strokes
 *
 * Sample input:
 * A[] = new int[]{1,1,1,1}
 * Output:
 * 1
 *
 * Sample input:
 * A[] = new int[]{1,3,2,1,2,1,5,3,3,4,2}
 * Output:
 * 9
 *
 * If strokes > 1,000,000,000 then return -1
 *
 * http://stackoverflow.com/questions/33399211/how-to-find-least-strokes-required-to-paint-a-skyline-with-time-and-storage-comp
 *
 */

public class MinHorizontalStrokes {

		public int solve(int A[]) {
        int level = 0;
        int strokes = 0;

        for (int i = 0;i < A.length;i++) {
            if (A[i] > level) {
                strokes += A[i] - level;
                level = A[i];
            } else if (A[i] < level) {
                level = A[i];
            }

            if (strokes > 1000000000)
                return -1;
      	}
      	return strokes;
		}

		public static void main(String[] args) {
				MinHorizontalStrokes problem = new MinHorizontalStrokes();
				System.out.println(problem.solve(new int[]{ 1,1,1,1 }));
				System.out.println(problem.solve(new int[]{ 1,3,2,1,2,1,5,3,3,4,2 }));
		}

}

Add puzzle from OrionHealth interview question taken from codility.com


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

import org.apache.guacamole.protocol.GuacamoleStatus;

/**
 * An exception which is thrown when a resource is no longer available because
 * it is closed.
 */
public class GuacamoleResourceClosedException extends GuacamoleClientException {

    /**
     * Creates a new GuacamoleResourceClosedException with the given message
     * and cause.
     *
     * @param message
     *     A human readable description of the exception that occurred.
     *
     * @param cause
     *     The cause of this exception.
     */
    public GuacamoleResourceClosedException(String message, Throwable cause) {
        super(message, cause);
    }

    /**
     * Creates a new GuacamoleResourceClosedException with the given message.
     *
     * @param message
     *     A human readable description of the exception that occurred.
     */
    public GuacamoleResourceClosedException(String message) {
        super(message);
    }

    /**
     * Creates a new GuacamoleResourceClosedException with the given cause.
     *
     * @param cause
     *     The cause of this exception.
     */
    public GuacamoleResourceClosedException(Throwable cause) {
        super(cause);
    }

    @Override
    public GuacamoleStatus getStatus() {
        return GuacamoleStatus.RESOURCE_CLOSED;
    }

}

Define missing exception for the RESOURCE_CLOSED status code.


package hr.fer.java.vjezbe.zadatak4.component;

import org.springframework.stereotype.Component;

@Component
public class ZelBarComponent extends CoreComponent {

	@Override
	protected String setStudentName() {
		return "Zeljko";
	}

}

Add ZelBar component implementation Unknown userzelbar


import java.util.Scanner;

/**
 * This program strips words of repeating letters, or reports if there are none.
 **/
public class RemoveDuplicateLetters {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.println("Input word");
        String word = scanner.nextLine();
        String ans = "";

        for (int i = 0; i < word.length(); i++) {
            int count = 0;
            for (int j = 0; j < ans.length(); j++) {
                if (word.charAt(i) == ans.charAt(j)) {
                    count++;
                }
            }
            if (count == 0) {
                ans += word.charAt(i);
            }
        }

        if (word.equals(ans)) {
            System.out.println("No repeated letters");
        } else {
            System.out.println(ans);
        }
    }
}

Add problem 6 to unit 3


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

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

/**
 * Represents the version information.
 *
 * @author David BRASSELY (brasseld at gmail.com)
 * @author GraviteeSource Team
 */
public final class Version {

    /**
     * Represents the build id, which is a string like "b13".
     */
    public final String BUILD_ID;

    /**
     * Represents the complete build number
     */
    public final String BUILD_NUMBER;

    /**
     * Represents the major version, such as "2.0".
     */
    public final String MAJOR_VERSION;

    /**
     * Represents the latest Revision number.
     */
    public final String REVISION;

    /**
     * The Runtime Version.
     */
    public static final Version RUNTIME_VERSION = Version.create(Version.class.getResourceAsStream("/version.properties"));

    private Version(String buildId, String buildVersion, String majorVersion, String revision) {
        this.BUILD_ID = fixNull(buildId);
        this.BUILD_NUMBER = fixNull(buildVersion);
        this.MAJOR_VERSION = fixNull(majorVersion);
        this.REVISION = fixNull(revision);
    }

    public static Version create(InputStream is) {
        Properties props = new Properties();
        try {
            props.load(is);
        } catch (IOException e) {
            // ignore even if the property was not found. we'll treat everything as unknown
        } catch (Exception e) {
            //ignore even if property not found
        }

        return new Version(
                props.getProperty("build-id"),
                props.getProperty("build-version"),
                props.getProperty("major-version"),
                props.getProperty("revision"));
    }

    private String fixNull(String v) {
        if(v==null) return "unknown";
        return v;
    }

    public String toString() {
        return MAJOR_VERSION + " (build: " + BUILD_ID + ") revision#" + REVISION;
    }
}

Add version class used to read data from a properties file available from classloader


package uk.me.graphe.client;

import java.util.Collection;

public class DrawingGraphML{

    private static Collection<EdgeDrawable> mEdgesToDraw;
    private static Collection<VertexDrawable> mVerticesToDraw;

    public static String getString(Collection<EdgeDrawable> edges,Collection<VertexDrawable> vertices){
        mEdgesToDraw = edges;
        mVerticesToDraw = vertices;
        return "hello world";
    }
}

Create class to convert graph to GaphML


package leetcode;

/**
 * https://leetcode.com/problems/house-robber-iii/
 */
public class Problem337 {
    public static class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode(int x) {
            val = x;
        }
    }

    public int rob(TreeNode root) {
        // TODO
        return 0;
    }

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

        TreeNode root = new TreeNode(3);
        root.left = new TreeNode(2);
        root.left.right = new TreeNode(3);
        root.right = new TreeNode(3);
        root.right.right = new TreeNode(1);
        System.out.println(prob.rob(root)); // 7

        root = new TreeNode(3);
        root.left = new TreeNode(4);
        root.left.left = new TreeNode(1);
        root.left.right = new TreeNode(3);
        root.right = new TreeNode(5);
        root.right.right = new TreeNode(1);
        System.out.println(prob.rob(root)); // 9
    }
}

Create a skeleton for problem 337


package edu.northwestern.bioinformatics.studycalendar.domain;

import edu.northwestern.bioinformatics.studycalendar.testing.StudyCalendarTestCase;
import org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean;
import org.hibernate.mapping.PersistentClass;
import org.hibernate.annotations.GenericGenerator;
import org.hibernate.annotations.Parameter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Iterator;

/**
 * @author Rhett Sutphin
 */
public class OracleCompatibilityTest extends StudyCalendarTestCase {
    private final Logger log = LoggerFactory.getLogger(getClass());

    @SuppressWarnings({ "unchecked" })
    public void testAllConfiguredSequencesLessThan30Characters() throws Exception {
        AnnotationSessionFactoryBean sessionFactoryBean
            = (AnnotationSessionFactoryBean) getDeployedApplicationContext().getBean("&sessionFactory");
        Iterator<PersistentClass> mappedClasses = sessionFactoryBean.getConfiguration().getClassMappings();
        while (mappedClasses.hasNext()) {
            PersistentClass pc =  mappedClasses.next();
            Class<?> clazz = pc.getMappedClass();
            GenericGenerator generator = clazz.getAnnotation(GenericGenerator.class);
            if (generator == null) {
                log.debug("{} has no declared generator", clazz.getName());
                continue;
            }
            Parameter sequence = null;
            for (Parameter parameter : generator.parameters()) {
                if ("sequence".equals(parameter.name())) {
                    sequence = parameter; break;
                }
            }
            if (sequence == null) {
                fail("Generator for " + clazz.getName() + " has no sequence parameter");
            }
            assertTrue("Oracle sequence for " + clazz.getName() + " is too long: " + sequence.value() + " (" + sequence.value().length() + " chars). It must be no more than 30 characters. Bering will generate an appropriately named sequence; be sure to configure the same one in the class annotation.",
                sequence.value().length() <= 30);
        }
    }
}

Test for checking that all configured (in the annotations) sequences for oracle are less than 30 characters


package com.bignerdranch.android.criminalintent;

import android.os.Bundle;
import android.support.v4.app.FragmentActivity;

public class CrimePagerActivity extends FragmentActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_crime_pager);
    }
}

Create activity for the new crime pager


/*******************************************************************************
 * Copyright (c) 2012 - 2015 Signal Iduna Corporation and others.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 * Signal Iduna Corporation - initial API and implementation
 * akquinet AG
 *******************************************************************************/
package org.testeditor.ui.parts.commons;

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

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

import org.eclipse.e4.core.contexts.ContextInjectionFactory;
import org.eclipse.e4.core.contexts.EclipseContextFactory;
import org.eclipse.e4.core.contexts.IEclipseContext;
import org.eclipse.swt.widgets.Shell;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.testeditor.core.model.teststructure.TestCase;
import org.testeditor.core.model.teststructure.TestProject;
import org.testeditor.core.services.interfaces.TestProjectService;
import org.testeditor.ui.adapter.TestProjectServiceAdapter;

/**
 * Tests for the SearchTestStructureDialog.
 *
 */
public class SearchTestStructureDialogTest {

	private Shell shell;

	/**
	 * Tests the building of the dialog.
	 *
	 * @throws Exception
	 *             on test failure
	 */
	@Test
	public void testCreateDialogAndFillResultView() throws Exception {
		IEclipseContext context = EclipseContextFactory.create();

		context.set(TestProjectService.class, new TestProjectServiceAdapter() {
			@Override
			public List<TestProject> getProjects() {
				ArrayList<TestProject> list = new ArrayList<TestProject>();
				TestCase testCase = new TestCase();
				TestProject testProject = new TestProject();
				testCase.setName("MyTest");
				testProject.addChild(testCase);
				list.add(testProject);
				return list;
			}
		});
		SearchTestStructureDialog dialog = new SearchTestStructureDialog(shell) {
			@Override
			public Shell getShell() {
				return shell;
			}
		};
		ContextInjectionFactory.inject(dialog, context);
		assertNull(dialog.getSelectedTestStructure());
		dialog.createDialogArea(shell);
		dialog.createTestStructureNamesLoader().run();
		assertSame(1, dialog.getResultViewer().getTable().getItemCount());
	}

	/**
	 * Creates UI handle for test.
	 */
	@Before
	public void setup() {
		shell = new Shell();
	}

	/**
	 * Cleanup ui handles.
	 */
	@After
	public void teardown() {
		shell.dispose();
	}
}

Test the Dialog Result view.


/*
Copyright (c) 2016, Colorado State University
All rights reserved.

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 holder 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 io.sigpipe.sing.util;

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

/**
 * Simple utility that consumes a list of Geohash strings and outputs their
 * respective binary forms. The command line version receives the Geohash
 * strings from stdin.
 *
 * @author malensek
 */
public class GeoBits {

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

        InputStreamReader in = new InputStreamReader(System.in);
        try (BufferedReader br = new BufferedReader(in)) {
            String line;
            while ((line = br.readLine()) != null) {
                System.out.println(GeoBits.geohashToBinString(line));
            }
        }
    }

    public static String geohashToBinString(String geohash) {
        long l = GeoHash.hashToLong(geohash);
        return Long.toBinaryString(l);
    }

}

Add utility class for printing binary GeoHashes


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

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

import com.cloudera.cdk.morphline.base.PrettyPrinter;

public class PrettyPrinterTest extends Assert {

  @Test
  public void testBasic() throws Exception {
    PrettyPrinter.main(new String[] {"target/test-classes/test-morphlines/grokSyslogNgCisco.conf"});
    PrettyPrinter.main(new String[] {"target/test-classes/test-morphlines/parseComplexConfig.conf"});
  }

}

Add utility to nicely indent and format a morphline config file


/*
 * The MIT License
 *
 * Copyright (c) 2021, Daniel Beck
 *
 * 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 jenkins;

import hudson.Extension;
import hudson.URLConnectionDecorator;
import jenkins.model.Jenkins;
import jenkins.util.SystemProperties;
import org.jenkinsci.Symbol;
import org.kohsuke.accmod.Restricted;
import org.kohsuke.accmod.restrictions.NoExternalUse;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URLConnection;

/**
 * Sets a Jenkins specific user-agent HTTP header for {@link HttpURLConnection}.
 *
 * @since TODO
 */
@Extension
@Restricted(NoExternalUse.class)
@Symbol("userAgent")
public class UserAgentURLConnectionDecorator extends URLConnectionDecorator {
    private static /* non-final for Groovy */ boolean DISABLED = SystemProperties.getBoolean(UserAgentURLConnectionDecorator.class.getName() + ".DISABLED");

    @Override
    public void decorate(URLConnection con) throws IOException {
        if (!DISABLED && con instanceof HttpURLConnection) {
            HttpURLConnection httpConnection = (HttpURLConnection) con;
            httpConnection.setRequestProperty("User-Agent", "Jenkins/" + Jenkins.getVersion());
        }
    }
}

Add a Jenkins User-Agent header to outgoing HTTP requests


import java.util.Scanner;

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

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

}

Add Second Exercise Horizontal Line


package org.agmip.core.types;

import java.util.Map;

/**
 *
 * @author Meng Zhang
 */
public interface DividableOutputTranslator {
    public void writeFile(String filePath, Map input, int size);
}

Add dividable interface for translator which could get divided translation result


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

package org.springframework.cloud.netflix.eureka.server;

import static org.hamcrest.Matchers.equalTo;
import static org.junit.Assert.assertThat;

import java.io.IOException;

import org.apache.log4j.Logger;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Rule;
import org.junit.Test;
import org.springframework.boot.logging.LogLevel;
import org.springframework.boot.logging.log4j.Log4JLoggingSystem;
import org.springframework.boot.test.OutputCapture;
import org.springframework.core.io.ClassPathResource;
import org.springframework.util.ClassUtils;
import org.springframework.util.StringUtils;

import com.netflix.blitz4j.LoggingConfiguration;

/**
 * Tests for {@link Log4JLoggingSystem}.
 *
 * @author Phillip Webb
 */
public class Log4JLoggingSystemTests {

	@Rule
	public OutputCapture output = new OutputCapture();

	private final Log4JLoggingSystem loggingSystem = new Log4JLoggingSystem(getClass()
			.getClassLoader());

	private Logger logger;

	@Before
	public void setup() {
		System.setProperty("log4j.configuration", getPackagedConfigFile("log4j.properties"));
		logger = Logger.getLogger(getClass());
		LoggingConfiguration.getInstance().configure();
	}

	@Test
	@Ignore("gh-48")
	public void setLevel() throws Exception {
		this.loggingSystem.beforeInitialize();
		this.loggingSystem.initialize(null, null);
		this.logger.debug("Hello");
		this.loggingSystem.setLogLevel("org.springframework.cloud", LogLevel.DEBUG);
		this.logger.debug("Hello");
		assertThat(StringUtils.countOccurrencesOf(this.output.toString(), "Hello"),
				equalTo(1));
	}

	private final String getPackagedConfigFile(String fileName) {
		try {
			return new ClassPathResource(fileName, Log4JLoggingSystem.class).getURL().toString();
		}
		catch (IOException e) {
			throw new IllegalStateException("Cannot create URL", e);
		}
	}
}

Add ignored test to show that blitz4j is not responding