package org.positronicnet.sample.todo_cp;

import android.net.Uri;

// ContentProvider "Contract" declarations for the Todo ContentProvider
// in tests for ContentExporter, etc.

public class TodoContract {

  // URIs for common queries/updates

  public static String TODO_PREFIX =
    "content://org.positronicnet.sample.todo_cp/";

  public static String TODO_LISTS_PREFIX = TODO_PREFIX + "lists";
  public static Uri    TODO_LISTS_URI = Uri.parse( TODO_LISTS_PREFIX );

  public static Uri todoListUri( Long id )
  {
    return Uri.withAppendedPath( TODO_LISTS_URI, Long.toString( id ));
  }

  public static String TODO_LIST_ITEMS_PATTERN = TODO_LISTS_PREFIX + "/=/items";

  public static Uri todoListItemsUri( Long listId )
  {
    return Uri.withAppendedPath( TODO_LISTS_URI,
                                 Long.toString( listId ) + "/items" );
  }

  public static String TODO_LIST_ITEM_PATTERN = TODO_LISTS_PREFIX+"/=/items/=";

  public static Uri todoListItemUri( Long listId, Long itemId )
  {
    return Uri.withAppendedPath( TODO_LISTS_URI,
                                 Long.toString( listId ) + "/items/" + itemId );
  }

  public static String TODO_LIST_TYPE = "vnd.org.positronicnet.todolist";
  public static String TODO_ITEM_TYPE = "vnd.org.positronicnet.todoitem";

  // Columns for individual tables

  static class List {
    public static String _ID  = "_id";
    public static String NAME = "name";
  }

  static class Item {

    // Note that todo_list_id is implicit in the URI scheme above,
    // and the provider is smart enough to use the values in the URIs
    // on inserts and updates, so there's no need to explicitly map it.

    public static String _ID          = "_id";
    public static String DESCRIPTION  = "description";
    public static String IS_DONE      = "is_done";
  }

  // Generating content-types to match platform conventions.
  // Might want these somewhere where they'd be more generally useful

  public static String dirContentType( String s )
  {
    return "vnd.android.cursor.dir/"+s;
  }

  public static String rowContentType( String s )
  {
    return "vnd.android.cursor.item/"+s;
  }
}

Add ContentProvider Contract class for ContentProvider sample app.


package uk.gov.register.functional;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;
import org.junit.Assert;
import org.junit.Test;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

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

public class AssetsBundleCustomErrorHandlerTest extends FunctionalTestBase {
    @Test
    public void displays404pageForNonexistentAssets() {
        Response response = getRequest("/assets/not-an-assets");

        assertThat(response.getStatus(), equalTo(404));
        assertThat(response.getMediaType().isCompatible(MediaType.TEXT_HTML_TYPE), equalTo(true));

        Document doc = Jsoup.parse(response.readEntity(String.class));
        Elements notFoundHeader = doc.select("main h1");
        Assert.assertThat(notFoundHeader.first().text(), equalTo("Page not found"));
    }
}

Add test for handling not found assets


package ie.gmit.sw;

/**
 * Created by Ross Byrne on 10/01/17.
 * A singleton factory for handling the instances of
 * the metric calculators.
 */
public class MetricCalculatorFactory {

    // private, instantiated factory object for singleton pattern
    private MetricCalculatorFactory factory = new MetricCalculatorFactory();

    // private constructor for singleton pattern, so no one can create another instance.
    private MetricCalculatorFactory(){}

    /**
     * Method for obtaining an instance of the singleton factory
     *
     * @return
     * Returns the instance of the singleton factory, MetricCalculatorFactory.
     */
    public MetricCalculatorFactory getInstance(){

        return this.factory;

    } // getInstance()

} // class

Create the metricCalculator singleton factory.


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

//tag::snippet-in-doc[]
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.openqa.selenium.safari.SafariDriver;

import io.github.bonigarcia.DriverOptions;
import io.github.bonigarcia.Option;
import io.github.bonigarcia.SeleniumExtension;

@ExtendWith(SeleniumExtension.class)
public class SafariWithOptionsJupiterTest {

    @Disabled("SafariDriver requires Safari 10 running on OSX El Capitan or greater.")
    @Test
    public void safariTest(
            @DriverOptions(options = {
                    @Option(name = "useCleanSession", value = "true"),
                    @Option(name = "useTechnologyPreview", value = "false") }) SafariDriver safari)
            throws InterruptedException {
        safari.get(
                "https://webrtc.github.io/samples/src/content/devices/input-output/");

        Thread.sleep(3000); // Wait 3 seconds to see the page
    }

}
// end::snippet-in-doc[]

Include Safari test using options


//
// ScriptLanguage.java
//

/*
ImageJ software for multidimensional image processing and analysis.

Copyright (c) 2010, ImageJDev.org.
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
    * Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright
      notice, this list of conditions and the following disclaimer in the
      documentation and/or other materials provided with the distribution.
    * Neither the names of the ImageJDev.org developers nor the
      names of its contributors may be used to endorse or promote products
      derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/

package imagej.script;

import imagej.plugin.ImageJPlugin;

import javax.script.ScriptEngineFactory;

/**
 * The base interface for script language adapters
 *
 * @author Johannes Schindelin
 */
public interface ScriptLanguage extends ScriptEngineFactory, ImageJPlugin {
	// just so we can annotate the factories with @Plugin...
}

Add the annotation for discovering script languages


package org.estatio.dom.lease;

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

import org.joda.time.LocalDate;
import org.junit.Before;
import org.junit.Test;

public class LeaseTermForTaxTest_changeRegistration {

    @Before
    public void setUp() throws Exception {

    }

    @Test
    public void test() {
        // given
        LeaseTermForTax term = new LeaseTermForTax();
        term.setRegistrationDate(new LocalDate(2014, 1, 1));
        term.setRegistrationNumber("registrationNumber");
        term.setOfficeCode("officeCode");
        term.setOfficeName("officeName");
        term.setDescription("description");

        // when
        term.changeRegistration(new LocalDate(2014, 1, 1), "registrationNumber", "officeCode", "officeName", "description");

        assertThat(term.getRegistrationDate(), is(new LocalDate(2014, 1, 1)));
        assertThat(term.getRegistrationNumber(), is("registrationNumber"));
        assertThat(term.getOfficeCode(), is("officeCode"));
        assertThat(term.getOfficeName(), is("officeName"));
        assertThat(term.getDescription(), is("description"));

    }
}

Add additional test for lease term for test


/*
 * 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.ngrinder.operation.cotroller;

import org.ngrinder.common.controller.BaseController;
import org.ngrinder.common.controller.RestAPI;
import org.ngrinder.operation.service.SystemConfigService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.support.ReloadableResourceBundleMessageSource;
import org.springframework.http.HttpEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import static org.ngrinder.common.util.Preconditions.checkNotEmpty;

/**
 * Developer Feature.
 *
 * @since 3.3
 */
@Controller
@RequestMapping("/dev")
public class DevController extends BaseController {

	@Autowired
	private ReloadableResourceBundleMessageSource messageSource;

	/**
	 * Refresh the messages.
	 *
	 * @param model model
	 * @return "redirect:/"
	 */
	@RequestMapping("/msg")
	public String refreshMessage(ModelMap model) {
		messageSource.clearCacheIncludingAncestors();
		model.clear();
		return "redirect:/";
	}

}

Add the message refresh for dev


package com.coderevisited.coding;

public class ReplaceWithNextGreatest
{
    public static void main(String[] args)
    {
        int[] array = new int[]{16, 6, 9, 10, 11, 17, 4, 3, 9, 8, 5, 2, 14};
        replaceWithNextGreatest(array);

        for (int i : array) {
            System.out.print(i + " ");
        }
        System.out.println();
    }

    private static void replaceWithNextGreatest(int[] array)
    {
        int max = -1;
        for (int i = array.length - 1; i >= 0; i--) {
            int current = array[i];
            array[i] = max;
            max = max > current ? max : current;
        }
    }
}

Replace With next greatest element


package com.evgenii.jsevaluatortests;

import android.test.ActivityInstrumentationTestCase2;

public class EvaluateJsActivityTests extends
		ActivityInstrumentationTestCase2<EvaluateJsStringActivity> {

	private EvaluateJsStringActivity mActivity;

	public EvaluateJsActivityTests() {
		super(EvaluateJsStringActivity.class);
	}

	@Override
	protected void setUp() throws Exception {
		super.setUp();
		mActivity = getActivity();
	}

	public void testPreconditions() {
		assertNotNull("mActivity is null", mActivity);
	}
}

Add test for evaluatejs activity


package roart.config;

public class MLConstants {
    public static final String MCP = "MCP";
    public static final String LR = "LR";
    public static final String OVR = "OVR";
    public static final String DNN = "DNN";
    public static final String DNNL = "DNNL";
    public static final String L = "L";
}

Add constants for ML classifier names.


package ch.rasc.eds.starter.config;

import org.springframework.boot.context.embedded.ConfigurableEmbeddedServletContainer;
import org.springframework.boot.context.embedded.EmbeddedServletContainerCustomizer;
import org.springframework.boot.context.embedded.MimeMappings;
import org.springframework.context.annotation.Configuration;

@Configuration
public class WebFontMimeMapper implements EmbeddedServletContainerCustomizer {

	@Override
	public void customize(ConfigurableEmbeddedServletContainer container) {
		MimeMappings mappings = new MimeMappings(MimeMappings.DEFAULT);
		mappings.add("svg", "image/svg+xml");
		mappings.add("eot", "application/vnd.ms-fontobject");
		mappings.add("woff", "application/font-woff");
		mappings.add("woff2", "application/font-woff2");
		mappings.add("ttf", "application/font-sfnt");
		mappings.add("otf", "application/font-sfnt");
		container.setMimeMappings(mappings);
	}
}

Add mimetype mapping for self hosted webfonts


package com.tngtech.jgiven.junit;

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

import com.tngtech.jgiven.Stage;
import com.tngtech.jgiven.annotation.AfterStage;
import com.tngtech.jgiven.annotation.BeforeStage;
import com.tngtech.jgiven.annotation.ScenarioStage;
import org.junit.Ignore;
import org.junit.Test;

public class SimpleStageRepetitionUseTest
    extends SimpleScenarioTest<SimpleStageRepetitionUseTest.RepeatLifecycleMethods> {

    @ScenarioStage
    DontRepeatLifecycleMethods dontRepeatLifecycleMethods;

    /* FIXME:
    We use the change of a stage class to detect that there is a new stage.
    Hence, repeatedly using the same stage does not work!
    */
    @Test
    @Ignore("Feature not implemented yet")
    public void lifecycle_methods_of_a_shared_stage_are_called_individually() {
        given().a_simple_stage_containing_before_and_after_methods();
        when().the_test_is_executed();
        then().the_before_stage_was_called_$_times(3).and()
            .the_after_stage_method_was_called_$_times(2); //we assert before the last call to 'afterStage'
    }

    @Test
    public void non_repeatable_methods_are_called_exactly_once() {
        dontRepeatLifecycleMethods.given().a_simple_stage_containing_before_and_after_methods();
        dontRepeatLifecycleMethods.when().the_test_is_executed();
        dontRepeatLifecycleMethods.then().the_before_stage_was_called_$_times(1).and()
            .the_after_stage_method_was_called_$_times(0);
    }

    static class DontRepeatLifecycleMethods extends AllTestSteps<DontRepeatLifecycleMethods> {
        @BeforeStage
        protected void beforeStage() {
            callBeforeStage();
        }

        @AfterStage
        protected void afterStage() {
            callAfterStage();
        }
    }

    static class RepeatLifecycleMethods extends AllTestSteps<RepeatLifecycleMethods> {
        @BeforeStage(repeatable = true)
        protected void beforeStage() {
            callBeforeStage();
        }

        @AfterStage(repeatable = true)
        protected void afterStage() {
            callAfterStage();
        }
    }

    static class AllTestSteps<T extends AllTestSteps<?>> extends Stage<T> {

        private int beforeStageCalled = 0;
        private int afterStageCalled = 0;

        protected void callBeforeStage() {
            beforeStageCalled++;
        }

        protected void callAfterStage() {
            afterStageCalled++;
        }

        T a_simple_stage_containing_before_and_after_methods() {
            return self();
        }

        T the_test_is_executed() {
            return self();
        }

        T the_after_stage_method_was_called_$_times(int numberOfCalls) {
            assertThat(afterStageCalled).isEqualTo(numberOfCalls);
            return self();
        }

        T the_before_stage_was_called_$_times(int numberOfCalls) {
            assertThat(beforeStageCalled).isEqualTo(numberOfCalls);
            return self();
        }
    }
}

Test repeatable after stage methods when used in two consecutive stages


package com.wildducktheories.api.impl;

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

import com.wildducktheories.api.API;

public class APIManagerTest {

	static class TestAPI implements API {

		public boolean reset = false;

		@Override
		public void reset() {
			reset = true;
		}

	}

	static class TestAPIManager extends AbstractAPIManagerImpl<TestAPI>
	{
		public TestAPI create()
		{
			return new TestAPI();
		};
	}

	/**
	 * Test that resets causes a different object to be allocated. That the same
	 * object will be returned without a reset and that the reset method is called on reset.
	 */
	@Test
	public void testReset() {
		final  TestAPIManager manager = new TestAPIManager();

		TestAPI api1 = manager.get();
		TestAPI api2 = manager.get();
		Assert.assertFalse(api1.reset);
		manager.reset();
		TestAPI api3 = manager.get();

		Assert.assertNotNull(api1);
		Assert.assertNotNull(api3);
		Assert.assertSame(api1, api2);
		Assert.assertNotSame(api1, api3);
		Assert.assertTrue(api1.reset);
		Assert.assertFalse(api3.reset);
	}
}

Add a test for the reset case.


import java.io.File;
import java.io.FileWriter;
import org.apache.bcel.Repository;
import org.apache.bcel.classfile.*;
import org.json.simple.JSONObject;
import org.json.simple.JSONArray;

class ParseExamples {
    public static void main(String[] args) throws java.lang.Exception {
        String[] classNames = RunExamples.classNames();

        // e.g. com.opengamma.Class used in com.opengamma.example.ExampleClass:MethodName
        JSONObject classesUsed = new JSONObject();

        for (int k = 0; k < classNames.length; k++) {
            String className = classNames[k];
            JavaClass clazz = Repository.lookupClass(className);
            ConstantPool pool = clazz.getConstantPool();

            // Check each method in this class to see which OpenGamma classes it uses
            Method[] methods = clazz.getMethods(); for (int i = 0; i < methods.length; i++) {
                Method method = methods[i];
                Code code = method.getCode();

                // code.toString calls Utilities.codeToString which does lots
                // of useful parsing but then stores everything in a String
                // instead of a more accessible format, so we need to parse the string
                String[] codeLines = code.toString().split("\n");
                for (int m = 0; m < codeLines.length; m++) {
                    String line = codeLines[m];
                    int x = line.indexOf("invokespecial");
                    int y = line.indexOf(".<init>");
                    if (x > 0 && y > 0) {
                        String usedClassName = line.substring(x+13, y).trim();
                        if (usedClassName.startsWith("com.opengamma")) {
                            // This is one we are interested in!
                            JSONArray methodsUsedIn;

                            if (classesUsed.containsKey(usedClassName)) {
                                // Get existing array...
                                methodsUsedIn = (JSONArray)classesUsed.get(usedClassName);
                            } else {
                                // Init new array...
                                methodsUsedIn = new JSONArray();
                            }
                            String methodKey = className + ":" + method.getName();
                            methodsUsedIn.add(methodKey);
                            classesUsed.put(usedClassName, methodsUsedIn);
                        }
                    }
                }

                File f;
                FileWriter file;

                f = new File("../dexy--depends.json");
                file = new FileWriter(f);
                classesUsed.writeJSONString(file);
                file.close();
            }
        }
    }
}

Add script to detect which classes are being used (i.e. a new instance being creaetd) in examples.


//
// IJDelegationSelectionTool.java
//

/*
ImageJ software for multidimensional image processing and analysis.

Copyright (c) 2010, ImageJDev.org.
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
    * Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright
      notice, this list of conditions and the following disclaimer in the
      documentation and/or other materials provided with the distribution.
    * Neither the names of the ImageJDev.org developers nor the
      names of its contributors may be used to endorse or promote products
      derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/

package imagej.ui.swing.overlay;

import org.jhotdraw.draw.tool.DelegationSelectionTool;

@SuppressWarnings("serial")
public class IJDelegationSelectionTool extends DelegationSelectionTool
	implements JHotDrawTool
{

}

Add an adapter for JHotDraw's selection tool


/*
 * Copyright 2005-2010 The Kuali Foundation
 *
 * Licensed under the Educational Community 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.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.iacuc.auth;

import org.kuali.kra.iacuc.actions.amendrenew.IacucProtocolModule;

/**
 * The Modify Protocol Others Authorizer determines if
 * the user can modify the other parts of a protocol.
 */
public class ModifyIacucProtocolOthersAuthorizer extends ModifyIacucAmendmentAuthorizer {

    public ModifyIacucProtocolOthersAuthorizer() {
        super(IacucProtocolModule.OTHERS);
    }
}

Create authorizer and permission for IACUC Custom Data


package com.faforever.api.data.domain;

import com.yahoo.elide.annotation.Include;

import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToOne;
import javax.persistence.Table;
import java.sql.Time;
import java.util.Objects;

@Entity
@Table(name = "coop_leaderboard")
@Include(rootLevel = true, type = "coop_leaderboard")
public class CoopLeaderboard {

  private int id;
  private short mission;
  private Replay replay;
  private boolean secondaryObjectives;
  private Time duration;
  private short playerCount;

  @Id
  @Column(name = "id")
  public int getId() {
    return id;
  }

  public void setId(int id) {
    this.id = id;
  }

  @Basic
  @Column(name = "mission")
  public short getMission() {
    return mission;
  }

  public void setMission(short mission) {
    this.mission = mission;
  }

  @OneToOne
  @JoinColumn(name = "gameuid")
  public Replay getReplay() {
    return replay;
  }

  public void setReplay(Replay gameuid) {
    this.replay = gameuid;
  }

  @Basic
  @Column(name = "secondary")
  public boolean getSecondaryObjectives() {
    return secondaryObjectives;
  }

  public void setSecondaryObjectives(boolean secondary) {
    this.secondaryObjectives = secondary;
  }

  @Basic
  @Column(name = "time")
  public Time getDuration() {
    return duration;
  }

  public void setDuration(Time time) {
    this.duration = time;
  }

  @Basic
  @Column(name = "player_count")
  public short getPlayerCount() {
    return playerCount;
  }

  public void setPlayerCount(short playerCount) {
    this.playerCount = playerCount;
  }

  @Override
  public int hashCode() {
    return Objects.hash(id, mission, replay, secondaryObjectives, duration, playerCount);
  }

  @Override
  public boolean equals(Object o) {
    if (this == o) {
      return true;
    }
    if (o == null || getClass() != o.getClass()) {
      return false;
    }
    CoopLeaderboard that = (CoopLeaderboard) o;
    return id == that.id &&
        mission == that.mission &&
        replay == that.replay &&
        secondaryObjectives == that.secondaryObjectives &&
        Objects.equals(duration, that.duration) &&
        Objects.equals(playerCount, that.playerCount);
  }
}

Add coop leaderboard (without ranking)


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

// Just add a class to make the compiler happy.
public class Main {
    public static void main(final String[] args) {
    }
}

Make compiler happy by adding a java file to the injection-test project


/**
 * The {@code learningrate} package contains strategy classes to parametrize
 * self-organizing maps.  The classes are intended to be created by the user
 * and given to a self-organizing map, which will assume control.  These
 * classes all derive from {@link cs437.som.LearningRateFunction} in
 * {@link cs437.som}.
 */
package cs437.som.learningrate;

Add a package annotation to learningrate.


/*
Copyright (c) 2014, 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.
*/

/**
 * Tests server-side support for listening on different ports with the
 * ServerMessageRouter, and distinguishing between the originating ports with
 * {@link MessageContext} instances.
 */
package galileo.test.multiport;

Add package info for multiport tests


package com.thoughtworks.xstream.converters.reflection;

import junit.framework.TestCase;

import java.util.Iterator;
import java.lang.reflect.Field;

public class FieldDictionaryTest extends TestCase {

    private FieldDictionary fieldDictionary;

    protected void setUp() throws Exception {
        super.setUp();
        fieldDictionary = new FieldDictionary();
    }

    class SomeClass {
        private String a;
        private String c;
        private String b;
    }

    public void testListsFieldsInClassInDefinitionOrder() {
        Iterator fields = fieldDictionary.serializableFieldsFor(SomeClass.class);
        assertEquals("a", ((Field)fields.next()).getName());
        assertEquals("c", ((Field)fields.next()).getName());
        assertEquals("b", ((Field)fields.next()).getName());
        assertFalse("No more fields should be present", fields.hasNext());
    }

    class SpecialClass extends SomeClass {
        private String brilliant;
    }

    public void testIncludesFieldsInSuperClasses() {
        Iterator fields = fieldDictionary.serializableFieldsFor(SpecialClass.class);
        assertEquals("brilliant", ((Field)fields.next()).getName());
        assertEquals("a", ((Field)fields.next()).getName());
        assertEquals("c", ((Field)fields.next()).getName());
        assertEquals("b", ((Field)fields.next()).getName());
        assertFalse("No more fields should be present", fields.hasNext());
    }
}

Test that fields come out in same order they are defined.


package org.jaexcel.framework.JAEX.definition;

/**
 * This will define the title orientation type when writing into the Excel.

 *
 * {@value = TitleOrientationType.TOP } Will paint the title over the element.

 * {@value = TitleOrientationType.LEFT } Will paint the title at the left of the element.

 * {@value = TitleOrientationType.RIGHT } Will paint the title at the right of the element.

 * {@value = TitleOrientationType.BOTTOM } Will paint the title under the element.

 *
 * @version 1.0
 * @author Carlos CRISTO ABREU
 */
public enum TitleOrientationType {

	// right
	TOP(0), LEFT(1), RIGHT(2), BOTTOM(3);

	private int code;

	private TitleOrientationType(int s) {
		code = s;
	}

	public int getCode() {
		return code;
	}
}

Create enum responsible to : define the title orientation type when writing into the Excel.


package org.biojava.nbio.structure.align.quaternary;

/**
 * The Quaternary Structure Relation describes the pairwise relation between two
 * quaternary structures.
 *
 * @author Aleix Lafita
 * @since 5.0.0
 *
 */
public enum QsRelation {

	/**
	 * All the Subunits of one Structure have an equivalent in the other
	 * Structure.
	 *

	 * An example of this relation is comparing an A2B2 complex with C2 symmetry
	 * against a similar A2B2 complex with the same C2 symmetry axis (same
	 * topology).
	 **/
	EQUIVALENT,

	/**
	 * All the Subunits of one Structure have an equivalent in the other
	 * Structure, but the other Structure contains additional non-matched
	 * Subunits.
	 *

	 * An example of this relation is comparing an A2B2 complex with C2 symmetry
	 * against a similar A2 complex with the same C2 symmetry axis. Another
	 * example is comparing an A4 complex with D2 symmetry against an A2 complex
	 * with the same C2 symmetry axis as one of the D2 axes.
	 */
	PARTIAL_COMPLETE,

	/**
	 * Only a subset of Subunits of one Structure have an equivalent in the
	 * other Structure, and the other Structure also contains additional
	 * non-matched Subunits.
	 *

	 * An example of this relation is comparing an A2B2 complex with C2 symmetry
	 * against an A2C2 complex, where As are similar but B and C differ, with
	 * the same C2 symmetry axis. Only the A2 part of the structure matches.
	 */
	PARTIAL_INCOMPLETE,

	/**
	 * None of the Subunits of one Structure have an equivalent in the other
	 * Structure.
	 *

	 * Two quaternary structures are different if they are not
	 * {@link #EQUIVALENT}, {@link #PARTIAL_COMPLETE} or
	 * {@link #PARTIAL_INCOMPLETE}.
	 */
	DIFFERENT;
}

Create quaternary alignment relations ENUM


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

package io.michaelrocks.lightsaber;

import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;

import static java.lang.annotation.ElementType.CONSTRUCTOR;
import static java.lang.annotation.ElementType.TYPE;
import static java.lang.annotation.RetentionPolicy.RUNTIME;

@Target(TYPE)
@Retention(RUNTIME)
@Documented
public @interface Factory {
  @Target(CONSTRUCTOR)
  @Retention(RUNTIME)
  @Documented
  @interface Inject {
  }
}

Add an annotation for factory interfaces


/*
	This class tests class Permutation
*/

package permutation;
import java.util.ArrayList;
import permutation.Permutation;
import java.util.Arrays;

class TestPermutation{

	// tests kth_permutation

	public static void testkth(int k){

		System.out.println("Test kth");

		Integer arr[] = {1,2,3,4,5,6,7,8,9};

		ArrayList<Integer> v = new ArrayList<Integer>(Arrays.asList(arr));

		ArrayList<Integer> result = Permutation.kth_permutation(v, k);

		for(Integer x: result)
			System.out.print(x+" ");
	}

	// tests next_permutation

	public static void test_next_permutation(){

		System.out.println("Test next permutation for: 1 2 3 4");

		Integer arr[] = {1,2,3,4};

		ArrayList<Integer> v = new ArrayList<Integer>( Arrays.asList(arr) );

		System.out.println("Further permutations: ");

		while(Permutation.next_permutation(v)){
			System.out.println();
			for(Integer x: v)
				System.out.print(x+" ");

		}

	}

	public static void main(String[] args){

		int k = 1;

		if( args.length > 0 )
			k = new Integer(args[0]);

		testkth(k);

		test_next_permutation();

	}

}

Add test class for class permutation


package com.formulasearchengine.mathosphere.mlp.gold;

import com.fasterxml.jackson.databind.ObjectMapper;

import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVRecord;
import org.junit.Ignore;
import org.junit.Test;

import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Moritz on 02.01.2016.
 */
public class AddTitles {

  @Test
  @Ignore
  public void addTitles() throws IOException {
    final File file = new File(getClass().getResource("gold.json").getFile());
    Map<Integer,String> titles = new HashMap<>();
    FileReader in = new FileReader(new File(getClass().getResource("titles.csv").getFile()));
    Iterable<CSVRecord> records = CSVFormat.RFC4180.parse(in);
    for (CSVRecord record : records) {
      titles.put(Integer.valueOf(record.get(0)),record.get(1));
    }
    ObjectMapper mapper = new ObjectMapper();
    List userData = mapper.readValue(file, List.class);
    for (Object o : userData) {
      final Map entry = (Map) o;
      Map formula = (Map) entry.get("formula");
      formula.put("title",titles.get(Integer.parseInt(String.valueOf(formula.get("oldId"))) ));
    }
    mapper.writeValue(file, userData);
  }
}

Add program to add titles


package org.jenkinsci.plugins.ewm.utils;

import org.junit.Test;

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

/**
 * Tests for {@link RandomUtil}.
 *
 * @author Alexandru Somai
 */
public class RandomUtilTest {

    @Test
    public void generateRandomHexStringLength() {
        String generatedString = RandomUtil.generateRandomHexString(32);
        assertThat(generatedString.length(), is(32));
    }
}

Write test for RandomUtil class


package binarytree;

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

import datastructures.tree.BinaryTree;
import datastructures.tree.TreeNode;

public class CountHalfNodesBinaryTree {
  private BinaryTree<Integer> tree = null;
  private Map<Integer, TreeNode<Integer>> nodesMap = null;
  private TreeNode<Integer> root = null;

  public CountHalfNodesBinaryTree() {
    tree = new BinaryTree<Integer>();
    nodesMap = new HashMap<Integer, TreeNode<Integer>>();
  }

  public void constructTree(String[] input) {
    for (String line : input) {
      String[] values = line.split(" ");
      int val = 0;
      switch (values[0]) {
      case "insertRoot":
        val = Integer.parseInt(values[1]);
        TreeNode<Integer> root = tree.insertRoot(val);
        if (root != null) {
          nodesMap.put(val, root);
          this.root = root;
        }
        break;
      case "insertLeft":
        insert(values[1], values[2], true);
        break;
      case "insertRight":
        insert(values[1], values[2], false);
        break;
      }
    }
  }

  private void insert(String parentStr, String nodeStr, boolean isLeft) {
    int parentVal = Integer.parseInt(parentStr);
    int nodeVal = Integer.parseInt(nodeStr);
    TreeNode<Integer> parentNode = nodesMap.get(parentVal);
    if (parentNode == null) {
      return;
    }

    TreeNode<Integer> node = new TreeNode<Integer>(nodeVal);
    nodesMap.put(nodeVal, tree.insert(parentNode, node, isLeft));
  }

  public int countHalfNodes() {
    return countHalfNodes(root);
  }

  private int countHalfNodes(TreeNode<Integer> root) {
    if (root == null || (root.left == null && root.right == null)) {
      return 0;
    } else {
      int numHalfNodes = (root.left == null || root.right == null) ? 1 : 0;
      return countHalfNodes(root.left) + countHalfNodes(root.right) + numHalfNodes;
    }
  }
}

Add solution for count half nodes in a binary tree


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

/**
 * Given a matrix representing a word search, can you write a method to return true if a word
 * passed
 * as argument is inside the word search?
 *
 * @author Pedro Vicente Gómez Sánchez.
 */
public class WordSearch {

}

Add statement to problem 48


/*
 * Copyright (c) 2015-present, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 */
package com.facebook.cache.common;

/**
 * No-op implementation of {@link CacheEventListener} so that listeners can extend and implement
 * only the events they're interested in.
 */
public class BaseCacheEventListener implements CacheEventListener {

  @Override
  public void onHit(CacheEvent cacheEvent) {
  }

  @Override
  public void onMiss(CacheEvent cacheEvent) {
  }

  @Override
  public void onWriteAttempt(CacheEvent cacheEvent) {
  }

  @Override
  public void onWriteSuccess(CacheEvent cacheEvent) {
  }

  @Override
  public void onReadException(CacheEvent cacheEvent) {
  }

  @Override
  public void onWriteException(CacheEvent cacheEvent) {
  }

  @Override
  public void onEviction(CacheEvent cacheEvent) {
  }

  @Override
  public void onCleared() {
  }
}

Create abstract implementation of CacheEventListener


import java.util.*;

public class Solution {

    public static void main(String[] args) {

        Scanner scan = new Scanner(System.in);
        int n = scan.nextInt();

        // Write your solution here
        int[] a = new int[n];
        for (int i = 0; i < n; i++) {
            a[i] = scan.nextInt();
        }

        scan.close();

        // Prints each sequential element in array a
        for (int i = 0; i < a.length; i++) {
            System.out.println(a[i]);
        }
    }
}

Solve java 1d array intro


package edu.grinnell.callaway;

import static org.junit.Assert.*;

import java.io.Serializable;
import java.util.HashMap;
import java.util.Vector;

import org.junit.Test;

public class JSONTester
{
  JSONParser1 parser1 = new JSONParser1();
  ToString str = new ToString();

  @Test
  public void toStrTestVals()
    throws Exception
  {
    assertEquals("1. true", "true", str.toStr(true));
    assertEquals("2. false", "false", str.toStr(false));
    assertEquals("3. num", "2.34", str.toStr(2.34));
    assertEquals("4. enum", "2.3E35", str.toStr(23e34));
    assertEquals("5. null", "null", str.toStr(null));
  } // toStrTestVals

  @Test
  public void toStrTestObVec()
    throws Exception
  {
    HashMap<String, Object> hash = new HashMap<String, Object>(8);

    Vector<Serializable> vector = new Vector<Serializable>(3);
    vector.add(1);
    vector.add(2);

    assertEquals("1. vector alone", "[1,2]", str.toStr(vector));

    Vector<Serializable> vector2 = new Vector<Serializable>(3);
    vector2.add(vector);
    vector2.add(2);

    assertEquals("2. vector in vector", "[[1,2],2]", str.toStr(vector2));

    HashMap<String, Object> hmap = new HashMap<String, Object>(3);

    hmap.put("x", "it");
    hmap.put("y", 2.7e-4);

    assertEquals("3. hashMap", "{\"y\":2.7E-4,\"x\":\"it\"}", str.toStr(hmap));

    vector.add(hmap);

    assertEquals("4. hashMap in vector", "[1,2,{\"y\":2.7E-4,\"x\":\"it\"}]",
                 str.toStr(vector));

    hash.put("a", true);
    hash.put("b", 2.7e-4);
    hash.put("c", "The");
    hash.put("j", vector2);
    hash.put("d", vector);
    hash.put("e", null);
    hash.put("f", hmap);

    assertEquals("5. things within things",
                 "{\"f\":{\"y\":2.7E-4,\"x\":\"it\"},\"d\":[1,2,{\"y\":2.7E-4,\"x\":\"it\"}],\"e\":null,\"j\":[[1,2,{\"y\":2.7E-4,\"x\":\"it\"}],2],\"b\":2.7E-4,\"c\":\"The\",\"a\":true}",
                 str.toStr(hash));
  } // toStrTestObVec
} // class JSONTester

Create tester... add tests for toStr


package com.sunny.grokkingalgorithms.fasttrack.week1;

import com.sunny.grokkingalgorithms.ctci.c4.util.BinaryTreeNode;
import com.sunny.grokkingalgorithms.ctci.c4.util.TreeUtils;

/**
 * Created by sundas on 6/21/2018.
 */
public class CheckIfBinaryTreeIsFull {

  /**
   *
   * @param root
   * @return
   */
  public static boolean isFull(BinaryTreeNode root){
    if(root ==  null){
      return true;
    }
    if(root.right == null
        && root.right == null){
      return true;
    }
    if((root.left != null && root.right == null) ||
        (root.left == null && root.right != null)){
      return false;
    }
    boolean leftSubTreeFull = isFull(root.left);
    boolean rightSubTreeFull = isFull(root.right);
    return leftSubTreeFull && rightSubTreeFull;
  }

  /**
   *
   * @param args
   */
  public static void main(String[] args) {
    BinaryTreeNode root = TreeUtils.createBalancedBinaryTree();
    TreeUtils.performBfsLevelMarker(root);
    System.out.println(isFull(root));
    System.out.println("##################");
    root = TreeUtils.createBST();
    TreeUtils.performBfsLevelMarker(root);
    System.out.println(isFull(root));
  }

}

Check if a binary tree is full.


import edu.pdx.cs510.agile.team3.db.DBManager;
import org.junit.Test;
import org.junit.Assert;

import java.sql.SQLException;

/**
 * Created by dsanchez on 8/1/17.
 */
public class DBTest {

    @Test
    public void canConnect() {
        try {
            DBManager.connect();
            DBManager.close();
        } catch (SQLException e) {
            Assert.assertTrue(e.getMessage(), false);
        }
    }

    @Test
    public void canSave() {
        try {
            DBManager.connect();
            DBManager.saveConnection("testuser", "testpass", "testhost");
            DBManager.close();
        } catch (SQLException e) {
            Assert.assertTrue(e.getMessage(), false);
        }
    }

    @Test
    public void canLogin() {
        try {
            DBManager.connect();
            DBManager.saveConnection("testuser", "testpass", "testhost");
            boolean loggedIn = DBManager.login("testuser", "testpass");
            DBManager.close();
            Assert.assertTrue(loggedIn);
        } catch (SQLException e) {
            Assert.assertTrue(e.getMessage(), false);
        }
    }
}

Add tests for database manager


package leetcode;

/**
 * https://leetcode.com/problems/maximum-product-of-word-lengths/
 */
public class Problem318 {
    public int maxProduct(String[] words) {
        // TODO:
        return 0;
    }

    public static void main(String[] args) {
        Problem318 prob = new Problem318();
        System.out.println(prob.maxProduct(new String[]{"abcw", "baz", "foo", "bar", "xtfn", "abcdef"})); // 16
        System.out.println(prob.maxProduct(new String[]{"a", "ab", "abc", "d", "cd", "bcd", "abcd"})); // 4
        System.out.println(prob.maxProduct(new String[]{"a", "aa", "aaa", "aaaa"})); // 0
    }
}

Add skeleton for problem 318


/*
 * Java Genetic Algorithm Library (@__identifier__@).
 * Copyright (c) @__year__@ Franz Wilhelmstötter
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 *
 * Author:
 *     Franz Wilhelmstötter (franz.wilhelmstoetter@gmx.at)
 *
 */
package org.jenetics.util;

import java.util.concurrent.atomic.AtomicInteger;

import org.testng.Assert;
import org.testng.annotations.Test;

/**
 * @author Franz Wilhelmstötter
 * @version $Date: 2013-06-21 $
 */
public abstract class SeqTestBase<T> {

	protected abstract Seq<T> newSeq(final int length);

	@Test
	public void forEach() {
		final Seq<T> seq = newSeq(1000);

		final AtomicInteger counter = new AtomicInteger(0);
		seq.forEach(new Function<T, Void>() {
			@Override public Void apply(final T value) {
				counter.incrementAndGet();
				return null;
			}
		});

		Assert.assertEquals(counter.get(), seq.length());
	}

}

Add test base class for 'Seq' interface.


package org.mifos.application.rolesandpermission.business;

import junit.framework.TestCase;

import org.mifos.framework.TestUtils;
import org.mifos.framework.components.logger.TestLogger;

public class RoleActivityEntityTest extends TestCase {

	public void testEquals() throws Exception {
		RoleBO role77 = new RoleBO(new TestLogger(), 77);
		RoleBO another77 = new RoleBO(new TestLogger(), 77);
		RoleBO role78 = new RoleBO(new TestLogger(), 78);

		ActivityEntity activity66 = new ActivityEntity(66);

		TestUtils.assertAllEqual(
			new Object[] {
				new RoleActivityEntity(role77, activity66),
				new RoleActivityEntity(role77, activity66),
				new RoleActivityEntity(another77, activity66)
			});
		TestUtils.assertIsNotEqual(
			new RoleActivityEntity(role77, activity66),
			new RoleActivityEntity(role78, activity66));
		TestUtils.assertIsNotEqual(
			new RoleActivityEntity(role77, activity66),
			"object of some other type");
	}

}

Add file which should have been part of last checkin.


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

public class SelectionSortTest {

    @Test
    public void test() {
        int list[] = { -5, 8, 0, 12, 55, 1, -66, 35, 3 };
        SelectionSort selectionSort = new SelectionSort();
        selectionSort.sort(list);
        for (int i = 0; i < list.length - 1; i++) {
            assert (list[i] <= list[i + 1]);
        }
    }

    @Test
    public void nullList(){
        int list[] = {};
        int expectedList[] = {};
        SelectionSort selectionSort = new SelectionSort();
        selectionSort.sort(list);
        assert (Arrays.equals(list, expectedList));
    }
}

Add selection sort test for Java implementation


package org.trello4j;

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

import org.junit.Test;
import org.trello4j.model.Card;

import static org.hamcrest.CoreMatchers.equalTo;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.fail;

/**
 * @author Johan Mynhardt
 */
public class CardServiceTest {
	@Test
	public void testAddNewCardUsingPost() {
		Properties properties = new Properties();
		try {
			properties.load(CardServiceTest.class.getResourceAsStream("/cardservice.properties"));
		} catch (NullPointerException e) {
			fail("Could not load properties to test CardService: " + e.getMessage());
		} catch (IOException e) {
			fail(e.getMessage());
		}

		String developerKey = properties.getProperty("developerKey");
		String token = properties.getProperty("token");
		String listId = properties.getProperty("listId");

		String name = "Trello4J CardService: Add Card using POST";
		String description = "Something awesome happened :)";

		Map<String, String> keyValueMap = new HashMap<String, String>();
		keyValueMap.put("desc", description);

		Trello trello = new TrelloImpl(developerKey, token);
		Card card = trello.addNewCard(listId, name, keyValueMap);

		assertNotNull(card);

		assertThat(card.getName(), equalTo(name));
		assertThat(card.getDesc(), equalTo(description));
	}
}

Test for adding a card using POST.


package org.robockets.stronghold.robot.intake;

import org.robockets.stronghold.robot.Robot;
import org.robockets.stronghold.robot.drivetrain.AssistedDrive;
import org.robockets.stronghold.robot.drivetrain.AssistedRotateType;
import org.robockets.stronghold.robot.drivetrain.AssistedTranslateType;

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

/**
 *
 */
public class ChevalDeFrise extends CommandGroup {

	double encooder; // Dummy variable for now until a method is made for receiving encoder output
	// Assuming position fully down is 0 and fully up is 90.
    public ChevalDeFrise() {
    	Robot.driveTrain.gyroPID.setSetpoint(0); // 0 for now -Jake B. 2016
    	if (encooder > 80) { // Temporary way to check if arm is up
    		addSequential(new SetIntake(0));
    	} else if (encooder < 80) { // Temporary way to check if arm is down
    		addSequential(new SetIntake(90));
    		addSequential(new SetIntake(0));
    	}

        addSequential(new AssistedDrive(AssistedTranslateType.ENCODER, AssistedRotateType.GYRO, 1, 0)); // Dummy inputs for distance and relativeAngle
    	addParallel(new SetIntake(90)); // Slowly lift arm as robot moves across
    }
}

Add basic skeleton for automatic shoveling.


public class Solution {

    public boolean canConstruct(String ransomNote, String magazine) {

        int[] alphabetsCount = new int[26];

        for (int i = 0; i < magazine.length(); i++) {
            alphabetsCount[magazine.charAt(i) - 'a']++;
        }

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

            alphabetsCount[ransomNote.charAt(i) - 'a']--;

            if (alphabetsCount[ransomNote.charAt(i) - 'a'] < 0) {
                return false;
            }

        }

        return true;

    }

}

Create : 383 Ransom Note


public class Solution {

    public int findLUSlength(String a, String b) {

        if (a.equals(b)) {
            return -1;
        } else {
            return Math.max(a.length(), b.length());
        }

    }

}

Create : 521 Longest Uncommon Subsequence I


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

package com.solsticesquared.schelling.move;

import com.solsticesquared.schelling.Agent;
import com.solsticesquared.schelling.SchellingExplorer;

import java.util.ArrayList;

/**
 * Represents a mechanism for performing a single "movement" step in a
 * simulation, whereby one agent (or agents) try and move to a new location.
 */
public interface MovementMethod {

    /**
     * Returns the minimum number of agents that must be in an agent list in
     * order for this movement method to work.
     *
     * @return The minimum number of agents required.
     */
    int getMinimumNumberOfAgentsRequired();

    /**
     * Performs a single "movement" operation on the specified list of agents
     * using some arbitrary logic.
     *
     *

     *     The specifics of the algorithm used are irrelevant, however there
     *     are two important requirements that all implementations must meet:
     *

     *
The agent, or agents, that are moved must removed from
     *         the specified agent list.

     *
The agent, or agents, that are moved must have their
     *         positions updated before this method completes; this also
     *         applies to the empty cell list (that is why it consists of
     *         mutable coordinate objects).

     *

     *

     *
     *

     *     However, it should be noted that this project guarantees that by
     *     the time this method is called, all appropriate pre-requisites
     *     have been met.  In particular, the number of agents required for a
     *     single, successful movement operation (as defined by
     *     {@link #getMinimumNumberOfAgentsRequired()}) have been verified;
     *     there is no need for implementations to check.
     *

     *
     * @param agents
     *        The list of agents to use.
     * @param model
     *        The model to use.
     * @throws NullPointerException
     *         If either {@code agents} or {@code model} are {@code null}.
     */
    void move(final ArrayList<Agent> agents,
              final SchellingExplorer model);
}

Add mechanism for performing a single movement operation on an agent list.


package com.braintreegateway.unittest;

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

import com.braintreegateway.Dispute;
import com.braintreegateway.util.SimpleNodeWrapper;
import java.math.BigDecimal;
import java.text.ParseException;
import com.braintreegateway.testhelpers.CalendarTestUtils;

public class DisputeTest {
    @Test
    public void includesFields() throws ParseException {
        String xml = "<dispute>" +
            "<received-date type=\"date\">2017-01-02</received-date>" +
            "<reply-by-date type=\"date\">2017-01-04</reply-by-date>" +
            "<date-opened type=\"date\">2017-01-02</date-opened>" +
            "<date-won type=\"date\">2017-01-03</date-won>" +
            "<currency-iso-code>GBP</currency-iso-code>" +
            "<reason>fraud</reason>" +
            "<status>won</status>" +
            "<kind>chargeback</kind>" +
            "<amount>100.00</amount>" +
            "<id>dispute_id</id>" +
            "<transaction>" +
            "  <id>transaction_id</id>" +
            "  <amount>500.00</amount>" +
            "</transaction>" +
            "</dispute>";
        SimpleNodeWrapper node = SimpleNodeWrapper.parse(xml);

        Dispute dispute = new Dispute(node);

        assertEquals(CalendarTestUtils.date("2017-01-02"), dispute.getReceivedDate());
        assertEquals(CalendarTestUtils.date("2017-01-04"), dispute.getReplyByDate());
        assertEquals(CalendarTestUtils.date("2017-01-02"), dispute.getOpenedDate());
        assertEquals(CalendarTestUtils.date("2017-01-03"), dispute.getWonDate());
        assertEquals(Dispute.Reason.FRAUD, dispute.getReason());
        assertEquals(Dispute.Status.WON, dispute.getStatus());
        assertEquals(Dispute.Kind.CHARGEBACK, dispute.getKind());
        assertEquals(new BigDecimal("100.00"), dispute.getAmount());
        assertEquals("GBP", dispute.getCurrencyIsoCode());
        assertEquals("dispute_id", dispute.getId());
        assertEquals("transaction_id", dispute.getTransactionDetails().getId());
    }
}

Add basic unit test for Disputes


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

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

import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.openqa.selenium.By;
import org.openqa.selenium.chrome.ChromeDriver;

import io.github.bonigarcia.seljup.Arguments;
import io.github.bonigarcia.seljup.SeleniumExtension;

@ExtendWith(SeleniumExtension.class)
public class ChromeInConstructorWithOptionsJupiterTest {

    ChromeDriver driver;

    public ChromeInConstructorWithOptionsJupiterTest(
            @Arguments({ "--use-fake-device-for-media-stream",
                    "--use-fake-ui-for-media-stream" }) ChromeDriver driver) {
        this.driver = driver;
    }

    @Test
    public void testGlobalChrome() {
        driver.get(
                "https://webrtc.github.io/samples/src/content/devices/input-output/");
        assertThat(driver.findElement(By.id("video")).getTagName(),
                equalTo("video"));
    }

}

Include test using options and driver in constructor


/*
 * Copyright 2016 Peter Kenji Yamanaka
 *
 * 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.pyamsoft.pydroid.support;

import android.support.annotation.CheckResult;
import android.support.annotation.NonNull;
import android.text.Spannable;
import com.pyamsoft.pydroid.util.StringUtil;

public abstract class RatingActivity extends DonationActivity
    implements RatingDialog.ChangeLogProvider {

  @NonNull @Override public final Spannable getChangeLogText() {
    // The changelog text
    final String title = "What's New in Version " + getVersionName();
    final String[] lines = getChangeLogLines();

    // Turn it into a spannable
    final String[] fullLines = new String[lines.length + 1];
    fullLines[0] = title;
    System.arraycopy(lines, 0, fullLines, 1, fullLines.length - 1);
    final Spannable spannable = StringUtil.createLineBreakBuilder(fullLines);

    int start = 0;
    int end = title.length();
    final int largeSize =
        StringUtil.getTextSizeFromAppearance(this, android.R.attr.textAppearanceLarge);
    final int largeColor =
        StringUtil.getTextColorFromAppearance(this, android.R.attr.textAppearanceLarge);
    final int smallSize =
        StringUtil.getTextSizeFromAppearance(this, android.R.attr.textAppearanceSmall);
    final int smallColor =
        StringUtil.getTextColorFromAppearance(this, android.R.attr.textAppearanceSmall);

    StringUtil.boldSpan(spannable, start, end);
    StringUtil.sizeSpan(spannable, start, end, largeSize);
    StringUtil.colorSpan(spannable, start, end, largeColor);

    start += end + 2;
    for (final String line : lines) {
      end += 2 + line.length();
    }

    StringUtil.sizeSpan(spannable, start, end, smallSize);
    StringUtil.colorSpan(spannable, start, end, smallColor);

    return spannable;
  }

  @CheckResult @NonNull protected abstract String[] getChangeLogLines();

  @CheckResult @NonNull protected abstract String getVersionName();
}

Update changelog to use new activity


package com.yammer.stresstime.entities;

import com.yammer.stresstime.managers.EmployeeManager;
import com.yammer.stresstime.test.DatabaseTest;
import org.junit.Before;
import org.junit.Test;

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.collection.IsEmptyCollection.empty;
import static org.junit.Assert.assertNotNull;

public class EmployeeTest extends DatabaseTest {

    private EmployeeManager mEmployeeManager;

    @Before
    @Override
    public void setUp() throws Exception {
        super.setUp();
        mEmployeeManager = new EmployeeManager(getSessionFactory());
    }

    @Test
    public void testNewHasEmptyAssignmentsAfterRetrievedFromDb() {
        Employee employee = new Employee();
        employee.setName("John Doe");
        employee.setYammerId("lorem");
        mEmployeeManager.save(employee);
        refresh(employee);

        assertNotNull(employee.getAssignments());
        assertThat(employee.getAssignments(), empty());

        mEmployeeManager.delete(employee);
    }
}

Add test for Employee entity


package to.etc.testutil;

/**
 * @author Frits Jalvingh
 * Created on 15-04-22.
 */
final public class TestUtil {
	private TestUtil() {}

	public static void nonTestPrintln(String text) {
		if(! inTest())
			System.out.println(text);
	}

	static public boolean inTest() {
		return System.getProperty("surefire.real.class.path") != null || System.getProperty("surefire.test.class.path") != null;
	}

}

Add utility class that decides whether code runs under test, to control things like debug logs


package fuzion24.device.vulnerability.vulnerabilities.helper;

import android.content.Context;
import android.content.SharedPreferences;
import android.os.Build;
import android.util.Base64;

import java.io.File;
import java.security.MessageDigest;
import java.util.HashSet;
import java.util.Scanner;

import fuzion24.device.vulnerability.util.SharedPreferencesUtils;

/**
 * Created by fuzion24 on 12/4/15.
 */
public class DeviceUpdateChecker {
    public static boolean wasDeviceUpdated(Context ctx){

        /*
            Take a hash of the build.prop and /proc/version
            If this changes, assume the device has been updated
        */
        String buildPropFile = readFile("/system/build.prop");
        String procVersion   = readFile("/proc/version");

        String fingerprint = hashString(buildPropFile + procVersion);
        String lastFingerprint = SharedPreferencesUtils.getBuildUpdateFingerprint(ctx);
        if(fingerprint.equals(lastFingerprint)){
            return false;
        } else {
            SharedPreferencesUtils.setBuildUpdateFingerPrint(ctx, fingerprint);
            return true;
        }
    }

    private static String hashString(String data){
        try {
            MessageDigest md = MessageDigest.getInstance("SHA");
            md.update(data.getBytes());
            byte[] hash = md.digest();
            return Base64.encodeToString(hash, Base64.DEFAULT);
        } catch (Exception e) {
            return "";
        }
    }

    private static String readFile(String filename){
        try {
            return new Scanner(new File(filename)).useDelimiter("\\Z").next();
        }catch(Exception e){
            return "";
        }
    }

}

Add a class with our hueristics to check if a device was updated


package rotateit.controller;

import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;

import static org.springframework.http.HttpStatus.OK;
import static org.springframework.http.MediaType.APPLICATION_JSON_VALUE;
import static org.springframework.web.bind.annotation.RequestMethod.POST;

@RestController
public class LabelWebhookController {
    @RequestMapping(value = "/api/labelPostEvent", method = POST, consumes = APPLICATION_JSON_VALUE)
    @ResponseStatus(OK)
    public void labelPostEvent(@RequestBody String labelPayload) {

    }
}

Add webhook endpoint for github's label payload


/*
 * Copyright 2017 Isaac Pateau
 *
 * 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.zaclimon.iptvproviderlibrary.persistence;

import com.zaclimon.iptvproviderlibrary.model.AvContent;

import java.util.List;

/**
 * Persistence API for {@link AvContent}.
 * Will mostly be used if a content must be persisted to the disk (For caching or other reasons)
 *
 * @author zaclimon
 * Creation date: 11/08/17
 */

public interface ContentPersistence {

    /**
     * Gives a content to be persisted
     *
     * @param avContent the content that will be saved
     */
    void insert(AvContent avContent);

    /**
     * Gives a list of content to be to be persisted
     *
     * @param avContents the list that will be saved
     */
    void insert(List<AvContent> avContents);

    /**
     * Deletes a category based on {@link AvContent#mContentCategory}
     *
     * @param category the category which will get deleted.
     */
    void deleteCategory(String category);

    /**
     * Deletes all the items that have been persisted.
     */
    void deleteAllItems();

    /**
     * Lists all the items that have been persisted.
     *
     * @return the list of all the {@link AvContent} that have been persisted
     */
    List<AvContent> listAllItems();

    /**
     * Gives a list of the {@link AvContent} belonging to a given category. The list can be sorted
     * or not.
     *
     * @param category the given category for a content
     * @param isAlphabeticallySorted whether the retrieved contents should be sorted by alphabetical order
     * @return the list of contents
     */
    List<AvContent> searchCategory(String category, boolean isAlphabeticallySorted);

    /**
     * Gets the total size of the persistence medium
     *
     * @return the total number of elements for this medium.
     */
    int size();

    /**
     * Gets the size for a given category in the persistence medium
     *
     * @param category the category in which a size is wanted
     * @return the total number of elements for that given category.
     */
    int size(String category);
}

Implement a basic API for AvContent persistence


/**
 * The MIT License (MIT)
 *
 * Copyright (c) 2017 Yegor Bugayenko
 *
 * 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 NON-INFRINGEMENT. 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 org.cactoos.func;

import org.hamcrest.MatcherAssert;
import org.hamcrest.Matchers;
import org.junit.Test;

/**
 * Test case for {@link False}.
 *
 * @author Vseslav Sekorin (vssekorin@gmail.com)
 * @version $Id$
 * @since 0.5
 * @checkstyle JavadocMethodCheck (500 lines)
 */
public final class FalseTest {

    @Test
    public void asValue() throws Exception {
        MatcherAssert.assertThat(
            new False().asValue(),
            Matchers.equalTo(false)
        );
    }

}

Add test case for False


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

/**
 * A very simple main class to test the {@link RemoteUpdater} class.
 *
 * @author Johannes Schindelin
 */
public class RemoteUpdaterTestDrive {

	public static void main(String[] args) {
		System.setProperty("imagej.dir", System.getProperty("user.home") + "/Fiji.app");
		System.err.println(RemoteUpdater.runRemote());
	}

}

Add a test drive for the new remote updater feature


// Copyright 2018 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.hosted.controller.restapi.filter;

import com.yahoo.jdisc.handler.ResponseHandler;
import com.yahoo.jdisc.http.filter.DiscFilterRequest;
import com.yahoo.jdisc.http.filter.SecurityRequestFilter;

/**
 * A no-op filter. Used for bindings that are whitelisted and do not require any authorization.
 *
 * @author bjorncs
 */
@SuppressWarnings("unused") // Injected
public class NoopFilter implements SecurityRequestFilter {

    @Override
    public void filter(DiscFilterRequest request, ResponseHandler handler) {}

}

Add noop security filter for controller


package org.robockets.stronghold.robot.highgoalshooter;

import org.robockets.stronghold.robot.flipper.FireShooter;
import org.robockets.stronghold.robot.hood.MoveHood;

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

/**
 *
 */
public class ShootPosition extends CommandGroup {

    public  ShootPosition() {
    	addSequential(new MoveHood(-70));
    	addSequential(new FireShooter()); // Unstick ball
    }
}

Add shoot position command that unsticks the ball


package org.helioviewer.plugins.eveplugin.view.linedataselector;

import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;

import javax.swing.JPanel;
import javax.swing.JTable;

public class LineDateSelectorTablePanel extends JPanel {

    private static final int ROW_HEIGHT = 20;
    private static final int ICON_WIDTH = 16;

    private static final int VISIBLE_ROW = 0;
    private static final int TITLE_ROW = 1;
    public static final int LOADING_ROW = 2;
    private static final int REMOVE_ROW = 3;

    private final JTable grid;

    private final LineDataSelectorTableModel tableModel;

    GridBagConstraints gc = new GridBagConstraints();

    public LineDateSelectorTablePanel() {
        this.setLayout(new GridBagLayout());
        tableModel = new LineDataSelectorTableModel();
        grid = new JTable(tableModel);
        tableModel.addTableModelListener(grid);

        gc.gridx = 0;
        gc.gridy = 0;
        gc.weightx = 1;
        gc.weighty = 0;
        gc.fill = GridBagConstraints.BOTH;

    }
}

Introduce the line selector panel based on a table


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

//tag::snippet-in-doc[]
import static org.junit.jupiter.api.Assertions.assertTrue;

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

// tag::snippet-in-doc[]
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.remote.DesiredCapabilities;

import io.github.bonigarcia.DriverCapabilities;
import io.github.bonigarcia.SeleniumExtension;

@ExtendWith(SeleniumExtension.class)
public class ChromeWithGlobalCapabilitiesJupiterTest {

    @DriverCapabilities
    DesiredCapabilities capabilities = DesiredCapabilities.chrome();
    {
        Map<String, String> mobileEmulation = new HashMap<String, String>();
        mobileEmulation.put("deviceName", "Nexus 5");
        Map<String, Object> chromeOptions = new HashMap<String, Object>();
        chromeOptions.put("mobileEmulation", mobileEmulation);
        capabilities.setCapability(ChromeOptions.CAPABILITY, chromeOptions);
    }

    @Test
    void webrtcTest1(ChromeDriver chrome) throws InterruptedException {
        chrome.get("https://bonigarcia.github.io/selenium-jupiter/");

        assertTrue(chrome.getTitle().startsWith("selenium-jupiter"));

        Thread.sleep(1500); // Wait 1.5 seconds to see the page
    }

}
// end::snippet-in-doc[]

Include test using Chrome and global capabilities (mobile emulation)


package edu.columbia.cs.psl.test.phosphor;

import static org.junit.Assert.*;

import org.junit.Test;

public class LambdaIntTagITCase {
	@Test
	public void testEmptyLambda() throws Exception {
		Runnable r = () -> {
		};
	}
}

Add empty lambda test case


package org.skife.jdbi.v2.sqlobject;

import junit.framework.TestCase;
import org.h2.jdbcx.JdbcDataSource;
import org.junit.Test;
import org.skife.jdbi.v2.DBI;
import org.skife.jdbi.v2.Handle;
import org.skife.jdbi.v2.Something;
import org.skife.jdbi.v2.TransactionCallback;
import org.skife.jdbi.v2.TransactionStatus;
import org.skife.jdbi.v2.sqlobject.mixins.GetHandle;
import org.skife.jdbi.v2.tweak.HandleCallback;
import java.util.Random;

public class TestReentrancy extends TestCase
{
    private DBI    dbi;
    private Handle handle;

    interface TheBasics extends GetHandle
    {
        @SqlUpdate("insert into something (id, name) values (:id, :name)")
        int insert(@BindBean Something something);
    }

    @Test
    public void testHandleReentrant() throws Exception
    {
        final TheBasics dao = dbi.onDemand(TheBasics.class);

        dao.withHandle(new HandleCallback<Void>() {
            @Override
            public Void withHandle(Handle handle) throws Exception
            {
                dao.insert(new Something(7, "Martin"));

                handle.createQuery("SELECT 1").list();

                return null;
            }
        });
    }

    @Test
    public void testTxnReentrant() throws Exception
    {
        final TheBasics dao = dbi.onDemand(TheBasics.class);

        dao.withHandle(new HandleCallback<Void>() {
            @Override
            public Void withHandle(Handle handle) throws Exception
            {
                handle.inTransaction(new TransactionCallback<Void>() {
                    @Override
                    public Void inTransaction(Handle conn, TransactionStatus status) throws Exception
                    {
                        dao.insert(new Something(1, "x"));

                        conn.createQuery("SELECT 1").list();
                        return null;
                    }
                });

                return null;
            }
        });
    }

    @Override
    public void setUp() throws Exception
    {
        JdbcDataSource ds = new JdbcDataSource();
        // in MVCC mode h2 doesn't shut down immediately on all connections closed, so need random db name
        ds.setURL("jdbc:h2:mem:test" + new Random().nextInt() +";MVCC=TRUE");

        dbi = new DBI(ds);

        dbi.registerMapper(new SomethingMapper());

        handle = dbi.open();

        handle.execute("create table something (id int primary key, name varchar(100))");
    }

    @Override
    public void tearDown() throws Exception
    {
        handle.execute("drop table something");
        handle.close();
    }
}

Add a (failing) test to demonstrate confusing behavior when mixing SqlObject and GetHandle


package com.zulip.android.util;

import android.animation.Animator;
import android.support.v4.view.animation.FastOutSlowInInterpolator;
import android.view.View;
import android.view.ViewPropertyAnimator;
import android.view.animation.Interpolator;

public class AnimationHelper {

    private static final Interpolator FAST_OUT_SLOW_IN_INTERPOLATOR = new FastOutSlowInInterpolator();

    public static void showView(final View view, int duration) {
        ViewPropertyAnimator slideOutAnimator = view.animate()
                .translationX(view.getWidth())
                .setInterpolator(FAST_OUT_SLOW_IN_INTERPOLATOR)
                .setDuration(duration);

        slideOutAnimator.setListener(new Animator.AnimatorListener() {
            @Override
            public void onAnimationStart(Animator animator) {
            }

            @Override
            public void onAnimationEnd(Animator animator) {
                view.setVisibility(View.GONE);
            }

            @Override
            public void onAnimationCancel(Animator animator) {
            }

            @Override
            public void onAnimationRepeat(Animator animator) {
            }
        });
        slideOutAnimator.start();
    }

    public static void hideView(final View view, int duration) {
        ViewPropertyAnimator slideOutAnimator = view.animate()
                .translationX(0)
                .setInterpolator(FAST_OUT_SLOW_IN_INTERPOLATOR)
                .setDuration(duration);

        slideOutAnimator.setListener(new Animator.AnimatorListener() {
            @Override
            public void onAnimationStart(Animator animator) {
                view.setVisibility(View.VISIBLE);
            }

            @Override
            public void onAnimationEnd(Animator animator) {

            }

            @Override
            public void onAnimationCancel(Animator animator) {

            }

            @Override
            public void onAnimationRepeat(Animator animator) {
            }
        });
        slideOutAnimator.start();
    }
}

Implement Animation Helper class to have methods for animation


/**
 * 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.azure.management.resources.fluentcore.arm.collection;

import com.microsoft.azure.PagedList;
import com.microsoft.azure.management.apigeneration.LangDefinition;
import com.microsoft.azure.management.apigeneration.LangDefinition.MethodConversion;
import com.microsoft.azure.management.resources.fluentcore.arm.Region;

/**
 * Provides access to listing Azure resources of a specific type based on their tag.
 * <p>
 * (Note: this interface is not intended to be implemented by user code)
 *
 * @param <T> the fluent type of the resource
 */
@LangDefinition(ContainerName = "CollectionActions", MethodConversionType = MethodConversion.OnlyMethod)
public interface SupportsListingByTag<T> {
    /**
     * Lists all the resources of the specified type in the specified tag.
     *
     * @param tag the tag value
     * @return list of resources
     */
    PagedList<T> listByTag(String resourceGroupName, String tag);
}

Add supporting by tag interface


// 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.data;

import com.google.appengine.api.datastore.Entity;

/**
 * A class to make a Trip type, containing
 * a specific id, destinations, interests and routes
 * to be used when updating a trip.
 */
public final class Trip{

  private long id;
  private final ArrayList<String> destinations;
  private final ArrayList<String> interests;
  private final ArrayList<String> route;

  public Trip(long id, ArrayList<String> destinations) {
    this.id = id;
    this.destinations = destinations;
    this.interests = null;
    this.route = null;
  }

  public void setInterestsFor(long id, ArrayList<String> interests){
    if(this.id == id) {
      this.interests = interests;
    } else {
      // Indicate illegal action somehow?
      return;
    }
  }

  public void setRouteFor(long id, ArrayList<String> route) {
    if(this.id == id) {
      this.route = route;
    } else {
      // Indicate illegal action somehow?
      return;
    }
  }

  public ArrayList<String> getInterests() {
      return this.interests;
  }

  public ArrayList<String> getRoute() {
      return this.route;
  }
}

Make Trip class to use throughout servlets


package leetcode.search_a_2d_matrix;

public class Solution {
	public boolean searchMatrix(int[][] matrix, int target) {
		if(matrix == null) return false;
		if(matrix.length == 0) return false;
		if(matrix[0].length== 0) return false;
		int height = matrix.length;
		int width = matrix[0].length;
		int U = height * width;
		int L = 0;
		if(matrix[0][0] == target) return true;
		if(matrix[0][0] > target || matrix[height - 1][width - 1] < target) return false;
		while(L + 1 < U){
			int mid = (L + U) / 2;
			int x = mid / width;
			int y = mid % width;
			if(matrix[x][y] == target) return true;
			if(matrix[x][y] > target) U = mid;
			else L = mid;
		}
		return false;
    }

	public static void main(String[] args){
		final int height = 5;
		final int width = 3;
		int[][] matrix = new int[height][width];
		for(int i = 0; i < height; i++){
			for(int j = 0; j < width; j++){
				matrix[i][j] = (i * width + j) * 2;
			}
		}
		for(int i = -1; i < (height * width) * 2 + 1; i++){
			System.err.println("" + new Solution().searchMatrix(matrix, i));
		}
	}
}

Add java solution for 74. Search a 2D Matrix


public class Solution {

    public String convertToBase7(int num) {

        if (num < 0) {
            return '-' + convertToBase7(-num);
        }

        if (num < 7) {
            return Integer.toString(num);
        }

        return convertToBase7(num / 7) + num % 7;

    }

}

Create : 504 Base 7


//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// This file is a part of the 'esoco-common' project.
// Copyright 2016 Elmar Sonnenschein, esoco GmbH, Flensburg, Germany
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//	  http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
package de.esoco.lib.property;

/********************************************************************
 * Enumeration of abstract event types for user interface interactions. The
 * values are:
 *
 *

 *
<l>{@link #UPDATE}: The value of an element has been updated.

 *
<l>{@link #ACTION}: An action has been triggered for an element.

 *
<l>{@link #FOCUS_LOST}: An element has lost the input focus.

 *

 */
public enum InteractionEventType { UPDATE, ACTION, FOCUS_LOST }

Add support for arbitrary client events


package net.imagej.ops.filter.min;

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

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

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

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

}

Add default implementation of MinFilterOp


package net.chrizzly.csharp4netbeans.utils;

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import java.util.stream.IntStream;

/**
 *
 * @author pedrohidalgo
 */
public class MiscUtil {
    public static final String LINE_SEPARATOR = System.getProperty("line.separator");

    public static List<String> getLinesFromFileContent(String fileContent) {
        List<String> result = new ArrayList<>();
        try (Scanner scanner = new Scanner(fileContent)) {
            while (scanner.hasNextLine()) {
                result.add(scanner.nextLine());
            }
        }

        return result;
    }

    public static int getOpenSymbolsAmount(String line) {
        int result = 0;
        char[] chars = line.toCharArray();
        for (int i = 0; i < chars.length; i++) {
            char ch = chars[i];
            if (ch == '{' || ch == '(') {
                result++;
            } else if (ch == '}' || ch == ')') {
                result--;
            }
        }
        return result;
    }

    public static String getAmountSeparatorChars(int amount) {
        if (amount <= 0) {
            return "";
        }
        StringBuilder stringBuilder = new StringBuilder();
        IntStream.rangeClosed(1, amount).forEach((int i) -> {
            stringBuilder.append(" ");
        });
        return stringBuilder.toString();
    }
}

Copy over the reformat code from a fork of pedro.


package com.pengrad.telegrambot;

import com.pengrad.telegrambot.model.Chat;
import com.pengrad.telegrambot.model.Message;
import com.pengrad.telegrambot.model.Update;
import com.pengrad.telegrambot.model.User;
import com.pengrad.telegrambot.response.GetUpdatesResponse;

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

/**
 * stas
 * 3/31/16.
 */
public class TestLoopGetUpdates {

    public static void main(String[] args) throws IOException {
        Properties properties = new Properties();
        properties.load(new FileInputStream("local.properties"));
        TelegramBot bot = TelegramBotAdapter.build(properties.getProperty("TEST_TOKEN"));

        GetUpdatesResponse updatesResponse;
        int j = 0;
        while (true) {
            try {
                updatesResponse = bot.getUpdates(j, 100, 20);
                List<Update> updates = updatesResponse.updates();
                for (int z = 0; z < updates.size(); z++) {
                    j = updates.get(z).updateId() + 1;
                    Message message = updates.get(z).message();
                    //
                    Chat chat = message.chat();
                    User user = message.from();
                    //String mes=message.text();

                    // Base64.getEncoder().encodeToString(s.getBytes(StandardCharsets.UTF_8));
                    if (message.text() != null) {
                        System.out.println("New message: " + message.text() + " id: " + message.messageId() + " from " + chat);
                    }

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

Test get updates in endless loop


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

package com.nkming.utils.str;

import java.util.Collection;

public class StrUtils
{
	/**
	 * Join multiple objects with toString(). @a glue will be inserted between
	 * each objects
	 *
	 * @param glue
	 * @param c
	 * @return
	 */
	public static <T> String Implode(String glue, Collection<T> c)
	{
		String product = null;
		for (T obj : c)
		{
			if (product == null)
			{
				product = obj.toString();
			}
			else
			{
				product += glue + obj.toString();
			}
		}
		return product;
	}
}

Add implode to join strings


package sortingalgorithms;

/**
 *  An interface for sorting algorithms. A class must implement
 *  SortingAlgorithm to work with SortingTest.
 *
 *  @author  Joel Abrahamsson
 *  @version %G%
 */
public interface SortingAlgorithm
{
  public void sort(int[] array);
}

Create interface for sorting algorithms


package ch.skymarshall.tcwriter.jupiter;

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

import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.condition.DisabledIfSystemProperty;

@Target({ ElementType.METHOD, ElementType.TYPE })
@Retention(RetentionPolicy.RUNTIME)
@Test
@DisabledIfSystemProperty(named = "java.awt.headless", matches = "true")
public @interface DisableIfHeadless {
	// noop
}

Use Jupiter annotation to skip gui tests, instead of using maven profile


package fi.helsinki.cs.tmc.cli.command;

import fi.helsinki.cs.tmc.cli.Application;
import fi.helsinki.cs.tmc.cli.CliContext;
import fi.helsinki.cs.tmc.cli.io.TestIo;

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

public class ShellHelperCommandTest {

    private Application app;
    private TestIo io;

    @Before
    public void setUp() {
        io = new TestIo();
        CliContext ctx = new CliContext(io);
        app = new Application(ctx);
    }

    @Test
    public void failWhenNoOptionsGiven() {
        String[] args = {"shell-helper"};
        app.run(args);
        io.assertContains("internal usage");
    }

    @Test
    public void getCommandList() {
        String[] args = {"shell-helper", "-c"};
        app.run(args);
        io.assertContains("help\n");
    }
}

Add unit tests for shell helper.


package com.iesebre.dam2.roger.todos;

import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;

public class Main2Activity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main2);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                    Intent intent = new Intent(Main2Activity.this, MainActivity.class);
                    startActivity(intent);

                //Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                //        .setAction("Action", null).show();
            }
        });
    }

}

Create a Main2activity and buton to MainActivity


package commands;

import MovementAndImageAPI.*;

public class ActivityCommand extends CommandsTurtle {

    public enum CommandType {HIDE, SHOW, PICK_UP, PUT};
    private CommandType command;

    public ActivityCommand(Turtle turtle, CommandType command) {
        super(turtle);
        this.command = command;
    }

    @Override
    public void execute() {
        switch(command) {
            case HIDE:
                turtle().hide();
                break;
            case SHOW:
                turtle().show();
                break;
            case PICK_UP:
                turtle().pickUp();
                break;
            case PUT:
                turtle().put();
                break;
        }

    }

}

Implement turtle activity commands subset


package cl.fatman.capital.fund;

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

import java.util.List;

public class ControllerFailTest {

	private Controller control;
	private PersistenceData persistence;

	@Before
	public void setUp() {
		control = Controller.getInstance();
		control.setUp();
		persistence = PersistenceData.getInstance();
	}

	@After
	public void tearDown() {
		control.tearDown();
	}

	@Test
	public void storeFundDataFailTest() {
		control.storeFundData();
		control.storeFundData();
		List<?> fundRateList = persistence.selectAllObjects("from FundRate", FundRate.class);
		assertEquals("Fund rate list size shold be 0.", 0, fundRateList.size());
	}
}

Create a junit class to test the fails in the Controller.


package javaDatatypes;

import java.util.*;

class Solution{

	public static void getNumberAndOutoutType(Scanner sc){
		try
        {
            long x = sc.nextLong();
            System.out.println(x+" can be fitted in:");
            if( x >= -128 && x <= 127 )
                System.out.println("* byte");
            if( x >= -32768 && x <= 32767 )
                System.out.println("* short");
            if( x >= -2147483648 && x <= 2147483647)
                System.out.println("* int");
            if( x >= -9223372036854775808L && x <= 9223372036854775807L)
                System.out.println("* long");
        }
        catch(Exception e)
        {
            System.out.println(sc.next() + " can't be fitted anywhere.");
        }
	}

    public static void main(String []argh)
    {
        Scanner sc = new Scanner(System.in);
        int t = sc.nextInt();

        for(int i = 0;i < t; ++i)
        	getNumberAndOutoutType(sc);

        sc.close();
    }
}

Add solution for problem Java Datatypes, HackerRank/Introduction/Java Datatypes