package net.openhft.chronicle.logger;

import net.openhft.chronicle.Chronicle;
import net.openhft.chronicle.ExcerptAppender;
import net.openhft.chronicle.VanillaChronicle;
import net.openhft.chronicle.tools.ChronicleTools;
import org.apache.commons.lang3.StringUtils;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import java.io.IOException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

/**
 * Created by peter on 10/10/14.
 */
public class VanillChronicleQueuePerfTest {
    Chronicle chronicle;
    ExcerptAppender logger;

    @Before
    public void setUp() throws IOException {
        String baseDir = System.getProperty("java.io.tmpdir") + "/perf-binary-vanilla-chronicle";
        ChronicleTools.deleteDirOnExit(baseDir);
        chronicle = new VanillaChronicle(baseDir);
        logger = chronicle.createAppender();
    }

    @After
    public void tearDown() throws IOException {
        chronicle.close();
    }

    @Test
    public void testMultiThreadLogging() throws IOException, InterruptedException {

        final int RUNS = 2000000;
        final int THREADS = Runtime.getRuntime().availableProcessors();

        for (int size : new int[]{64, 128, 256}) {
            {
                final long start = System.nanoTime();

                ExecutorService es = Executors.newFixedThreadPool(THREADS);
                for (int t = 0; t < THREADS; t++) {
                    es.submit(new RunnableLogger(RUNS, size));
                }

                es.shutdown();
                es.awaitTermination(10, TimeUnit.SECONDS);

                final long time = System.nanoTime() - start;

                System.out.printf("ChronicleLog.MT (runs=%d, min size=%03d, elapsed=%.3f ms) took an average of %.3f us per entry\n",
                        RUNS,
                        size,
                        time / 1e6,
                        time / 1e3 / (RUNS * THREADS)
                );
            }
        }
    }

    protected final class RunnableLogger implements Runnable {
        private static final String fmtBase = " > val1={}, val2={}, val3={}";
        private final String fmt;
        private final int runs;

        public RunnableLogger(int runs, int pad) {
            this.runs = runs;
            fmt = StringUtils.rightPad(fmtBase, pad + fmtBase.length(), "X");
        }

        @Override
        public void run() {
            for (int i = 0; i < this.runs; i++) {
                logger.startExcerpt();
                logger.writeUTFΔ(fmt);
                logger.writeInt(i);
                logger.writeInt(i * 7);
                logger.writeInt(i / 16);
                logger.finish();
            }
        }
    }
}

Add performance test for Chronicle Queue


package com.intellij.execution.runners;

import com.intellij.execution.console.LanguageConsoleViewImpl;
import com.intellij.openapi.project.Project;
import org.jetbrains.annotations.NotNull;

public abstract class ConsoleRunnerWithHistory<T extends LanguageConsoleViewImpl> {
  protected final Project myProject;

  public ConsoleRunnerWithHistory(@NotNull Project project) {
    myProject = project;
  }
}

package com.intellij.execution.runners;

import com.intellij.execution.console.LanguageConsoleView;
import com.intellij.openapi.project.Project;
import org.jetbrains.annotations.NotNull;

public abstract class ConsoleRunnerWithHistory<T extends LanguageConsoleView> {
  protected final Project myProject;

  public ConsoleRunnerWithHistory(@NotNull Project project) {
    myProject = project;
  }
}

Implement get variable for console variables view.


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

/**
 * @author David BRASSELY (brasseld at gmail.com)
 */
public interface HttpHeadersValues {

    String CONNECTION_CLOSE = "close";

    String TRANSFER_ENCODING_CHUNKED = "chunked";

}

Add HTTP headers common values


package fi.jgke.tagger.domain;

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

/**
 *
 * @author jgke
 */
public class SourceParameterTest {

    @Test
    public void testSetGetTitle() {
        String title = UUID.randomUUID().toString();
        SourceParameter instance = new SourceParameter();
        instance.setTitle(title);
        assertEquals(title, instance.getTitle());
    }

    @Test
    public void testSetGetUrl() {
        String url = UUID.randomUUID().toString();
        SourceParameter instance = new SourceParameter();
        instance.setUrl(url);
        assertEquals(url, instance.getUrl());
    }

    @Test
    public void testSetGetTitleAndUrl() {
        String title = UUID.randomUUID().toString();
        String url = UUID.randomUUID().toString();
        SourceParameter instance = new SourceParameter();
        instance.setTitle(title);
        instance.setUrl(url);
        assertEquals(title, instance.getTitle());
        assertEquals(url, instance.getUrl());
    }

    @Test
    public void testSetGetSourceParametertype() {
        Long sourcetype = UUID.randomUUID().getLeastSignificantBits();
        SourceParameter instance = new SourceParameter();
        instance.setSourcetype(sourcetype);
        assertEquals(sourcetype, instance.getSourcetype());
    }

}

Add simple tests for SourceParameter


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

public class Main {
    public static void main(String args[]) throws IOException {
        InputStreamReader ir = new InputStreamReader(System.in);
        BufferedReader in = new BufferedReader(ir);

        float a, b, c;

        a = Float.parseFloat(in.readLine());
        b = Float.parseFloat(in.readLine());
        c = Float.parseFloat(in.readLine());

        System.out.printf("MEDIA = %.1f\n", (a * 2.0 + b * 3.0 + c * 5.0) / 10.0);
    }
}

Solve Average 2 in java


/*
 * Copyright 2017 MovingBlocks
 *
 * 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.destinationsol.game;

import com.badlogic.gdx.math.Vector2;
import org.destinationsol.game.item.ItemContainer;
import org.destinationsol.game.ship.FarShip;
import org.destinationsol.game.ship.ShipBuilder;
import org.destinationsol.game.ship.SolShip;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Answers;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;

import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyBoolean;
import static org.mockito.ArgumentMatchers.anyFloat;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;

@RunWith(MockitoJUnitRunner.class)
public class PlayerCreatorTest {

    private PlayerCreator playerCreator;

    @Mock(answer = Answers.RETURNS_DEEP_STUBS)
    private SolGame solGame;
    @Mock
    private ShipConfig shipConfig;
    @Mock
    private ShipBuilder shipBuilder;
    private RespawnState respawnState;
    private Vector2 galaxySpawnPosition;
    @Mock
    private FarShip farShip;
    @Mock
    private SolShip solShip;

    @Before
    public void setUp() {
        playerCreator = new PlayerCreator();
        respawnState = new RespawnState();
        galaxySpawnPosition = new Vector2(42, 43);
        when(solGame.getGalaxyFiller().getPlayerSpawnPos(any())).thenReturn(galaxySpawnPosition);
        mockShipBuilding();
    }

    private void mockShipBuilding() {
        when(solGame.getShipBuilder()).thenReturn(shipBuilder);
        when(shipBuilder.buildNewFar(any(), any(), any(), anyFloat(), anyFloat(), any(), any(), any(), any(), anyBoolean(), anyFloat(), any(), anyBoolean())).thenReturn(farShip);
        when(farShip.toObject(any())).thenReturn(solShip);
        when(solShip.getItemContainer()).thenReturn(new ItemContainer());
    }

    @Test
    public void testSpawnOnGalaxySpawnPosition() {
        when(solGame.getTutMan()).thenReturn(null);
        playerCreator.createPlayer(shipConfig, true, respawnState, solGame, false, false);
        verify(shipBuilder).buildNewFar(any(), eq(galaxySpawnPosition), any(), anyFloat(), anyFloat(), any(), any(), any(), any(), anyBoolean(), anyFloat(), any(), anyBoolean());
    }
}

Test spawn on galaxy spawn position


package com.fixture.generator.builder;

import static org.junit.Assert.assertEquals;

import java.util.List;

import org.junit.Test;

public class ClassInformationBuildersFactoryTest {

	@Test
	public void shouldCreateAListWithNecessaryBuilder() {
		List<ClassInformationBuilder> builders = ClassInformationBuildersFactory.get();

		assertEquals(5, builders.size());
		assertEquals(PackageBuilder.class, builders.get(0).getClass());
		assertEquals(ImportBuilder.class, builders.get(1).getClass());
		assertEquals(NameBuilder.class, builders.get(2).getClass());
		assertEquals(BaseFixtureBuilder.class, builders.get(3).getClass());
		assertEquals(MethodsBuilder.class, builders.get(4).getClass());
	}

}

Create class information builders favtory test


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

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;

/** */
@RunWith(JUnit4.class)
public final class MeetingRequestTest {
  // Some people that we can use in our tests.
  private static final String PERSON_A = "Person A";
  private static final String PERSON_B = "Person B";
  private static final String PERSON_C = "Person C";

  private static final int DURATION_1_HOUR = 60;

  @Test
  public void CantAddOptionalAttendeeWhoIsAlsoMandatory() {
    MeetingRequest request = new MeetingRequest(Arrays.asList(PERSON_A), DURATION_1_HOUR);
    request.addOptionalAttendee(PERSON_A);

    int actual = request.getOptionalAttendees().size();
    int expected = 0;
    Assert.assertEquals(expected, actual);
  }
}

Add a basic test for MeetingRequest.java


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

/**
 * Mock rules that returns a leap second on day 1000.
 *
 * @author Stephen Colebourne
 */
public class MockUTCRulesLeapOn1000 extends UTCRules {

    @Override
    public String getName() {
        return "Mock1000";
    }

    @Override
    public int getLeapSecondAdjustment(long mjDay) {
        return (mjDay == 1000 ? 1 : 0);
    }

    @Override
    public int getTAIOffset(long mjDay) {
        return (mjDay <= 1000 ? 10 : 11);
    }

    @Override
    public long[] getLeapSecondDates() {
        return new long[] {1000};
    }

    @Override
    public TAIInstant convertToTAI(UTCInstant utcInstant) {
        return null;
    }

    @Override
    public UTCInstant convertToUTC(TAIInstant taiInstant) {
        return null;
    }

}

Add with methods to UTCInstant


//@author: A0138848M
package seedu.oneline.model.task;

import static org.junit.Assert.*;

import org.junit.Before;
import org.junit.Test;
import seedu.oneline.testutil.TestDataHelper;

public class TaskTest {
    Task taskDate0;
    Task taskDate1;
    Task taskNameA;
    Task taskNameB;

    @Before
    public void setUp() throws Exception {
        taskDate0 = TestDataHelper.generateTask(0);
        taskDate1 = TestDataHelper.generateTask(1);
        taskNameA = TestDataHelper.generateTaskWithName("A");
        taskNameB = TestDataHelper.generateTaskWithName("B");
    }

    @Test
    public void task_sortsByDate() {
        assertTrue(taskDate0.compareTo(taskDate1) < 0);
    }

    @Test
    public void task_sortsByName() {
        assertTrue(taskNameA.compareTo(taskNameB) < 0);
    }
}

Add initial test cases for task sorting


package test;

import static org.junit.Assert.*;

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

import model.FixedTask;
import model.FloatingTask;
import model.TaskList;

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

public class TaskListTest {

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

	@Test
	public void testAddingTask() {
		TaskList tasks = new TaskList();
		// generate 50 dummy task and add them
		 for (int i = 0; i < 50; i++) {
	            tasks.addToList(new FloatingTask("No." + i));
		}
		assertEquals(50, tasks.count());
	}

	@Test
	public void testDeletingTask() {
		TaskList tasks = new TaskList();
		// generate 50 dummy task and add them
		 for (int i = 0; i < 50; i++) {
	            tasks.addToList(new FloatingTask("No." + i));
		}
		assertEquals(50, tasks.count());

		// delete single task
		List<Integer> toDelete = new ArrayList<Integer>();
		toDelete.add(1);
		try {
			tasks.deleteFromList(toDelete);
		} catch (IndexOutOfBoundsException e) {
			System.out.println(e.getMessage());
		}
		assertEquals(49, tasks.count());

		//delete multiple task
		toDelete = new ArrayList<Integer>();
		for (int i = 1; i <=25; i++) {
            toDelete.add(i);
		}
		try {
			tasks.deleteFromList(toDelete);
		} catch (IndexOutOfBoundsException e) {
			System.out.println(e.getMessage());
		}
		assertEquals(24, tasks.count());

		// clear tasks
		tasks.clearList();
		assertEquals(0, tasks.count());
	}

	public void testEditingTask() {
		TaskList tasks = new TaskList();
		// editing floating task
		FloatingTask floatTask = new FloatingTask("lowercase");
		tasks.addToList(floatTask);
		tasks.editTaskDescription(1, "UPPERCASE");
		assertEquals("UPPERCASE", tasks.get(0).getDescription());

		tasks.clearList();
		// editing floating task
		Date dateA = new Date(100);
		Date dateB = new Date(200);
		Date dateC = new Date(300);
		FixedTask fixedTask = new FixedTask("lowercase", dateA, dateB);
		tasks.addToList(fixedTask);
		tasks.editTaskStartDate(1, dateC);
		assertEquals(dateC, tasks.get(0).getDeadline());
	}

}

Add unit test for TaskList class.


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

package com.spotify.helios.system;

import com.spotify.helios.ZooKeeperTestManager;
import com.spotify.helios.ZooKeeperTestingClusterManager;
import com.spotify.helios.client.HeliosClient;

import org.junit.Test;

public class ZooKeeperBadNodeTest extends SystemTestBase {

  /**
   * This is a testing cluster that has one peer that can't be resolved. Note that this is different
   * from a cluster where a peer is down (that's tested in {@link ZooKeeperHeliosFailoverTest}).
   */
  private final ZooKeeperTestManager zkc = new ZooKeeperTestingClusterManager() {
    @Override
    public String connectString() {
      return super.connectString() + ",node-that-doesnt-exist:1738";
    }
  };

  @Test
  public void testGetJobsWithBadNode() throws Exception {
    startDefaultMaster("--zk-cluster-id=" + zkClusterId);

    final HeliosClient client = defaultClient();
    client.jobs().get();
  }

  @Override
  protected ZooKeeperTestManager zooKeeperTestManager() {
    return zkc;
  }

}

Add test for ZK cluster with unresolvable node


package org.cyclonedx.maven;

import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugins.annotations.LifecyclePhase;
import org.apache.maven.plugins.annotations.Mojo;
import org.apache.maven.plugins.annotations.ResolutionScope;
import org.cyclonedx.maven.model.Component;

import java.util.Set;
import java.util.stream.Collectors;

@Mojo(
        name = "makeAggregateBom",
        defaultPhase = LifecyclePhase.VERIFY,
        aggregator = true,
        requiresOnline = true,
        requiresDependencyResolution = ResolutionScope.COMPILE_PLUS_RUNTIME
)
public class CycloneDxAggregateMojo extends BaseCycloneDxMojo {

    public void execute() throws MojoExecutionException{

        final Set<Component> components = getReactorProjects().stream()
                .flatMap(mavenProject -> mavenProject.getArtifacts().stream())
                .filter(this::shouldInclude)
                .map(this::convert)
                .collect(Collectors.toSet());

        super.execute(components);
    }
}

Add mojo for generating aggregate bom for multi module projects


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

/**
 * You are given two 32-bit numbers,N and M, and two bit positions, i and j. Write a method to
 * insert M into N such that M starts at bit j and ends at bit i. You can assume that the bits j
 * through i have enough space to fit all of M. That is,if M= 10011, you can assume that there are
 * at least 5 bits between j and i. You would not, for example, have j-3 and i=2, because M could
 * not fully fit between bit 3 and bit 2.
 *
 * EXAMPLE:
 *
 * Input:N=16000000000, M=10011, i =2, j =6 Output: N = 10001001100
 *
 * @author Pedro Vicente Gómez Sánchez.
 */
public class MergeBinaryNumbers {

}

Add statement to problem 67


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

package org.hisp.dhis.android.core.enrollment.internal;

import androidx.annotation.NonNull;

import org.hisp.dhis.android.core.arch.handlers.internal.IdentifiableDataHandler;
import org.hisp.dhis.android.core.enrollment.Enrollment;

import java.util.List;

import javax.inject.Inject;

import dagger.Reusable;
import io.reactivex.Completable;

@Reusable
public final class EnrollmentPersistenceCallFactory {

    private final IdentifiableDataHandler<Enrollment> enrollmentHandler;

    @Inject
    EnrollmentPersistenceCallFactory(
            @NonNull IdentifiableDataHandler<Enrollment> enrollmentHandler) {
        this.enrollmentHandler = enrollmentHandler;
    }

    public Completable persistRelationships(final List<Enrollment> enrollments) {
        return persistEnrollmentsInternal(enrollments, true, false, false);
    }

    private Completable persistEnrollmentsInternal(
            final List<Enrollment> enrollments, boolean asRelationship, boolean isFullUpdate, boolean overwrite) {
        return Completable.defer(() -> {
            enrollmentHandler.handleMany(enrollments, asRelationship, isFullUpdate, overwrite);
            return Completable.complete();
        });
    }
}

Add enrollment persistence call factory


package utils;

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

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

import play.test.FakeApplication;
import play.test.Helpers;

import static org.fest.assertions.Assertions.assertThat;

public class ConfigTest {
    protected static FakeApplication app;
    private Map<String, String> additionalConfiguration;

    @Before
    public void before() {
        additionalConfiguration = new HashMap<String, String>(Helpers.inMemoryDatabase());
    }

    @Test
    public void getScheme() {
        additionalConfiguration.put("application.scheme", "http");
        app = Helpers.fakeApplication(additionalConfiguration);
        Helpers.start(app);
        assertThat(Config.getScheme("https")).isEqualTo("http");
        Helpers.stop(app);

        additionalConfiguration.put("application.scheme", "");
        app = Helpers.fakeApplication(additionalConfiguration);
        Helpers.start(app);
        assertThat(Config.getScheme("https")).isEqualTo("https");
        Helpers.stop(app);
    }

    @Test
    public void getHostname() {
        additionalConfiguration.put("application.hostname", "www.nforge.com");
        additionalConfiguration.put("application.port", "8080");
        app = Helpers.fakeApplication(additionalConfiguration);
        Helpers.start(app);
        assertThat(Config.getHostport("localhost")).isEqualTo("www.nforge.com:8080");
        Helpers.stop(app);

        additionalConfiguration.put("application.hostname", "www.nforge.com");
        additionalConfiguration.put("application.port", null);
        app = Helpers.fakeApplication(additionalConfiguration);
        Helpers.start(app);
        assertThat(Config.getHostport("localhost:9000")).isEqualTo("www.nforge.com");
        Helpers.stop(app);

        additionalConfiguration.put("application.hostname", null);
        additionalConfiguration.put("application.port", "8080");
        app = Helpers.fakeApplication(additionalConfiguration);
        Helpers.start(app);
        assertThat(Config.getHostport("localhost:9000")).isEqualTo("localhost:9000");
        Helpers.stop(app);

        additionalConfiguration.put("application.hostname", null);
        additionalConfiguration.put("application.port", null);
        app = Helpers.fakeApplication(additionalConfiguration);
        Helpers.start(app);
        assertThat(Config.getHostport("localhost:9000")).isEqualTo("localhost:9000");
        Helpers.stop(app);
    }

}

Add the test for Config.


/*
 * Copyright 2016-2018 Talsma ICT
 *
 * 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 nl.talsmasoftware.context.futures;

import nl.talsmasoftware.context.ContextSnapshot;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.hasToString;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.sameInstance;
import static org.junit.Assert.fail;
import static org.mockito.Mockito.mock;

/**
 * @author Sjoerd Talsma
 */
public class ContextSnapshotHolderTest {
    private ExecutorService unawareThreadpool;

    @Before
    public void setUp() {
        unawareThreadpool = Executors.newCachedThreadPool();
    }

    @After
    public void tearDown() throws InterruptedException {
        unawareThreadpool.shutdown();
        unawareThreadpool.awaitTermination(5, TimeUnit.SECONDS);
    }

    @Test
    public void testSetGet() {
        ContextSnapshot snapshot = mock(ContextSnapshot.class);
        ContextSnapshotHolder holder = new ContextSnapshotHolder();

        holder.accept(snapshot);
        assertThat(holder.get(), is(sameInstance(snapshot)));
    }

    @Test
    public void testInterruption() throws InterruptedException {
        ContextSnapshot snapshot = mock(ContextSnapshot.class);
        ContextSnapshotHolder holder = new ContextSnapshotHolder();

        Future<ContextSnapshot> future = unawareThreadpool.submit(holder::get);
        unawareThreadpool.shutdownNow();
        unawareThreadpool.awaitTermination(5, TimeUnit.SECONDS);

        try {
            future.get();
            fail("Exception expected");
        } catch (ExecutionException expected) {
            assertThat(expected.getCause(), hasToString(containsString("Interrupted waiting for context snapshot")));
        }
    }

}

Add unit tests to ContextSnapshotHolder


// Copyright Verizon Media. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.restapi;

import com.yahoo.container.jdisc.HttpRequest;
import com.yahoo.container.jdisc.HttpResponse;

import java.util.function.Function;

/**
 * A {@link RuntimeException} that represents a http response.
 *
 * @author bjorncs
 */
public class RestApiException extends RuntimeException {
    private final int statusCode;
    private final HttpResponse response;

    public RestApiException(int statusCode, String errorType, String message) {
        this(new ErrorResponse(statusCode, errorType, message), message, null);
    }

    public RestApiException(HttpResponse response, String message) {
        this(response, message, null);
    }

    public RestApiException(int statusCode, String errorType, String message, Throwable cause) {
        this(new ErrorResponse(statusCode, errorType, message), message, cause);
    }

    public RestApiException(HttpResponse response, String message, Throwable cause) {
        super(message, cause);
        this.statusCode = response.getStatus();
        this.response = response;
    }

    private RestApiException(Function<String, HttpResponse> responseFromMessage, String message, Throwable cause) {
        this(responseFromMessage.apply(message), message, cause);
    }

    public int statusCode() { return statusCode; }
    public HttpResponse response() { return response; }

    public static class NotFoundException extends RestApiException {
        public NotFoundException() { super(ErrorResponse::notFoundError, "Not Found", null); }
    }

    public static class MethodNotAllowed extends RestApiException {
        public MethodNotAllowed() { super(ErrorResponse::methodNotAllowed, "Method not allowed", null); }
        public MethodNotAllowed(HttpRequest request) {
            super(ErrorResponse::methodNotAllowed, "Method '" + request.getMethod().name() + "' is not allowed", null);
        }
    }

    public static class BadRequest extends RestApiException {
        public BadRequest(String message) { super(ErrorResponse::badRequest, message, null); }
        public BadRequest(String message, Throwable cause) { super(ErrorResponse::badRequest, message, cause); }
    }

    public static class InternalServerError extends RestApiException {
        public InternalServerError(String message) { super(ErrorResponse::internalServerError, message, null); }
        public InternalServerError(String message, Throwable cause) { super(ErrorResponse::internalServerError, message, cause); }
    }
}

Add exception type for restapi error responses


package org.assertj.db.api;

import org.assertj.core.api.WritableAssertionInfo;
import org.assertj.core.description.Description;
import org.assertj.core.description.TextDescription;
import org.assertj.db.common.AbstractTest;
import org.assertj.db.type.Table;
import org.junit.Test;

import java.lang.reflect.Field;

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

/**
 * Test on {@code Descriptable} interface methods.
 *
 * @author Régis Pouiller
 *
 */
public class Descriptable_Test extends AbstractTest {

  /**
   * This method tests the {@code as} method to modify the description.
   */
  @Test
  public void test_as() throws Exception {
    Field field = AbstractAssert.class.getDeclaredField("info");
    field.setAccessible(true);
    Table table = new Table(source, "actor");

    TableRowAssert assertion = assertThat(table).row();
    WritableAssertionInfo info1 = (WritableAssertionInfo) field.get(assertion);
    assertThat(info1.descriptionText()).isEqualTo("Row at index 0 of actor table");

    TableRowAssert assertion2 = assertion.as("message %s with text", 1);
    WritableAssertionInfo info2 = (WritableAssertionInfo) field.get(assertion2);
    assertThat(info2.descriptionText()).isEqualTo("message 1 with text");

    Description description = new TextDescription("description %s %s", "with", "information");
    TableRowAssert assertion3 = assertion.as(description);
    WritableAssertionInfo info3 = (WritableAssertionInfo) field.get(assertion3);
    assertThat(info3.descriptionText()).isEqualTo("description with information");
  }
}

Add test on Descriptable interface method


package com.secondthorn.solitaireplayer.solvers.tripeaks;

import java.io.IOException;
import java.net.URISyntaxException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;

/**
 * Prints out solutions for the random decks.
 */
public class RandomDeckSolutions {
    public static void main(String[] args) {
        List<String> lines;
        try {
            lines = readLinesFromFile("random-decks.txt");
        } catch (IOException | URISyntaxException ex) {
            ex.printStackTrace();
            return;
        }
        System.out.println("Board Challenge Solver");
        printSolutions(lines, new BoardChallengeSolver());
        System.out.println("Score Challenge Solver");
        printSolutions(lines, new ScoreChallengeSolver(ScoreChallengeSolver.MAX_POSSIBLE_SCORE, 0));
        System.out.println("Card Challenge Solver");
        printSolutions(lines, new CardChallengeSolver(12, 'A', 0));
    }

    private static void printSolutions(List<String> lines, TriPeaksSolver solver) {
        for (int i=0; i<lines.size(); i++) {
            Solution solution = solver.solve(new Deck(lines.get(i)), State.INITIAL_STATE);
            System.out.println(String.format("(%d \"%s\" %s)",
                    i+1, solution.getDescription(), actionsToCardList(solution.getActions())));
        }
    }

    private static List<String> readLinesFromFile(String filename) throws IOException, URISyntaxException {
        return Files.readAllLines(Paths.get(ClassLoader.getSystemResource(filename).toURI()));
    }

    private static String actionsToCardList(List<Action> actions) {
        StringBuilder sb = new StringBuilder();
        sb.append("(");
        for (Action action : actions) {
            switch (action.getCommand()) {
                case DRAW:
                case REMOVE:
                    sb.append("\"");
                    sb.append(action.getCard());
                    sb.append("\" ");
                    break;
                default:
                    throw new RuntimeException("Only DRAW or REMOVE should be in the solution for fully known decks");
            }
        }
        int lastIndex = sb.length() - 1;
        if (sb.charAt(lastIndex) == ' ') {
            sb.setCharAt(lastIndex, ')');
        } else {
            sb.append(")");
        }
        return sb.toString();
    }
}

Add a tester to play through random decks.


package gov.nih.nci.ncicb.cadsr.common.persistence.dao.jdbc;

import static org.junit.Assert.*;
import gov.nih.nci.ncicb.cadsr.common.dto.DesignationTransferObjectExt;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:/applicationContext.xml"})
public class JDBCDesignationDAOTest {

	@Autowired
	JDBCDesignationDAO designationV2Dao;

	@Before
	public void setUp() throws Exception {
	}

	@Test
	public void testCreateDesignationForComponent() {
		String formSeqid = "F4E8EEE7-2DDB-0476-E040-BB8921B676BA";
		String createdBy = "FORMLOADER";
		String contextSeqid = "29A8FB18-0AB1-11D6-A42F-0010A4C1E842"; //"test" context
		DesignationTransferObjectExt desig = new DesignationTransferObjectExt();
		desig.setLanguage("ENGLISH");
		desig.setName("SY Testing");
		desig.setType("ABBREVIATION");

		int res = designationV2Dao.createDesignationForComponent(formSeqid, contextSeqid, createdBy, desig);
		assertTrue(res == 1);
	}

}

Test class for the new JDBCDesignationDAO


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

import nom.bdezonia.zorbage.predicate.Predicate;
import nom.bdezonia.zorbage.type.algebra.Algebra;
import nom.bdezonia.zorbage.type.storage.datasource.IndexedDataSource;

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

	public static <T extends Algebra<T,U>, U>
		void compute(T alg, Predicate<U> cond, IndexedDataSource<U> a, IndexedDataSource<U> b)
	{
		throw new IllegalArgumentException("not written yet");
	}

}

Make a placeholder for an algorithm


package org.telegram.telegrambots.api.commands;

import org.telegram.telegrambots.bots.AbsSender;

/**
 * Representation of a command, which can be executed
 *
 * @author tschulz
 */
public abstract class Command extends AbsSender {

    public final static String COMMAND_INIT_CHARACTER = "/";
    public final static String COMMAND_PARAMETER_SEPERATOR = " ";
    private final static int COMMAND_MAX_LENGTH = 32;

    private final String commandIdentifier;
    private final String description;
    private final String botToken;

    /**
     * construct a command
     *
     * @param commandIdentifier the unique identifier of this command (e.g. the command string to enter into chat)
     * @param description       the description of this command
     */
    public Command(String commandIdentifier, String description, String botToken) {

        if (commandIdentifier == null || commandIdentifier.isEmpty()) {
            throw new IllegalArgumentException("commandIdentifier for command cannot be null or empty");
        }

        if (commandIdentifier.startsWith(COMMAND_INIT_CHARACTER)) {
            commandIdentifier = commandIdentifier.substring(1);
        }

        if (commandIdentifier.length() + 1 > COMMAND_MAX_LENGTH) {
            throw new IllegalArgumentException("commandIdentifier cannot be longer than " + COMMAND_MAX_LENGTH + " (including " + COMMAND_INIT_CHARACTER + ")");
        }

        this.commandIdentifier = commandIdentifier.toLowerCase();
        this.description = description;
        this.botToken = botToken;
    }

    /**
     * get the identifier of this command
     *
     * @return the identifier
     */
    public final String getCommandIdentifier() {
        return commandIdentifier;
    }

    /**
     * get the description of this command
     *
     * @return the description as String
     */
    public String getDescription() {
        return description;
    }

    @Override
    public String getBotToken() {
        return botToken;
    }

    /**
     * execute the command
     *
     * @param arguments passed arguments
     * @param chatId    id of the chat, to be able to send replies
     */
    abstract void execute(String[] arguments, long chatId);
}

Create and implement basic command


package com.mongodb;

import org.testng.annotations.Test;

/**
 *  Tests aspect of the DB - not really driver tests
 */
public class DBTests {

    /**
     *   This test will fail now.  Waiting for fix in DB.  Originally done to show the
     *   effect of removing "seen" in DBApiLayer
     *
     * @throws Exception
     */
    @Test
    public void testConcurrentUpdate()  throws Exception {

        Mongo m = new Mongo("com_mongodb_DBTests");

        DBCollection coll = m.getCollection("concurrentUpdate");

        coll.drop();

        for (int i = 0; i < 10000; i++) {
            coll.insert(new BasicDBObject("i", i).append("flarg", "ASDASDASDASDASDA)DA_)ASD_)IASD_OJASD_)AS_D)IAS_D)IAS_D)IA_S)DIA_S)DIA_S)DIA_S)DIA_S)DIA_S)DIA_S)DIA_S)DIA_S)DIA_S)DIA_S)"));
        }
        int count = 0;

        DBCursor c = coll.find();

        while(c.hasNext()) {

            DBObject o = c.next();

            if (count++ == 0) {
                o.put("woog", "12-3012-30123-0123-012312312-0312-012-01-203-012-0psaoija-0sid-as0daoisasoidas=0dias=0diapsodjasd");
                coll.update(new BasicDBObject("_id", o.get("_id")), o, false, false);
            }
        }

        System.out.println(count);
        assert(count == 10000);
    }

}

Test (not part of regular run) that shows DB update-during-iteration bug


package org.pdxfinder.web;

import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@EnableWebSecurity
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .headers()
                .xssProtection();

    }

    @Component
    public class PdxFinderURLFilter implements Filter {

        @Override
        public void destroy() {}

        @Override
        public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterchain)
                throws IOException, ServletException {

            HttpServletRequest request = (HttpServletRequest) servletRequest;
            HttpServletResponse response = (HttpServletResponse) servletResponse;

            System.out.println("Query String:"+request.getQueryString());
            System.out.println("Remote Address:"+request.getRequestURL().toString());

            System.out.println("Remote Address SANITIZED:"+sanitize(request.getQueryString()));

            if (request.getRequestURI().contains("JAX")){
                response.sendRedirect("http://localhost:8080/data/search");
            }else {
                filterchain.doFilter(servletRequest, servletResponse);
            }

        }

        @Override
        public void init(FilterConfig filterconfig) throws ServletException {

        }

        public String sanitize(String string) {

            return string
                    .replaceAll("(?i)<script.*?>.*?</script.*?>", "")   // script tags
                    .replaceAll("(?i)<.*?.*?>.*?</.*?>", "") // js calls
                    .replaceAll("(?i)<.*?\\s+on.*?>.*?</.*?>", "");     // remove "font-size:11.0pt" lang="EN-U

        }
    }

}

Fix Potential XSS vulnerabilities : Added Spring Security Headers and Custom URL Filter Component


/* (C) 2017 kagix
** Some code is heavily based on stackoverflow DOT com
*/
package net.kagix.gtfs.ratptools.buslinecolor;
import java.lang.*;
import java.util.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.image.*;
import java.io.*;
import javax.imageio.*;
import javax.swing.*;

public class HistogramCalculator
{
	private HashMap<Integer,Integer> histogram = null;

	public HistogramCalculator(BufferedImage image) {

		if (image != null) {
			histogram = new HashMap<Integer,Integer>();
			calculateHistogram(image);
		}
	}

	public HashMap<Integer,Integer> getHistogram() {
		return histogram;
	}

	private int calculateKey(int[] rgb) {
		int key = rgb[Image.RED]   * Image.RED_SHIFT
			 +rgb[Image.GREEN] * Image.GREEN_SHIFT
			 +rgb[Image.BLUE]  * Image.BLUE_SHIFT;
		return key;
	}

	private void addOrIncrementKeyCount( int key) {

		if (!histogram.containsKey(key)) {
			histogram.put(key,0);
		}

		histogram.put(key,histogram.get(key)+1);
	}

	private void processPixel( int[] pixel) {
		int key = calculateKey(pixel);

		addOrIncrementKeyCount( key );
	}

	private void calculateHistogram(BufferedImage image) {
		for (int row = 0; row < image.getHeight(null); row++) {
			for (int column = 0; column <image.getWidth(null); column++) {

				int[] pixel = image.getRaster().getPixel( column,
									  row,
									  new int[3]);
				processPixel( pixel );
			}
		}
	}

	public int getRedValue(int key) {

		return (key & Image.RED_MASK) / Image.RED_SHIFT;
	}

	public int getGreenValue(int key) {

		return (key & Image.GREEN_MASK) / Image.GREEN_SHIFT;
	}

	public int getBlueValue(int key) {

		return (key & Image.BLUE_MASK) / Image.BLUE_SHIFT;
	}

	public String getHexValue(int key) {

		return String.format("%06X",key);
	}

}

Build a histogram of pixel color repetitions


/*
 * (C) Copyright 2016 Boni Garcia (http://bonigarcia.github.io/)
 *
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the GNU Lesser General Public License
 * (LGPL) version 2.1 which accompanies this distribution, and is available at
 * http://www.gnu.org/licenses/lgpl-2.1.html
 *
 * 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.
 *
 */
package io.github.bonigarcia.wdm.test;

import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Ignore;
import org.openqa.selenium.phantomjs.PhantomJSDriver;

import io.github.bonigarcia.wdm.PhantomJsDriverManager;
import io.github.bonigarcia.wdm.base.BaseBrowserTst;

/**
 * Test with PhatomJS.
 *
 * @author Boni Garcia (boni.gg@gmail.com)
 * @since 1.4.0
 */
@Ignore
public class PhantomJsBetaTest extends BaseBrowserTst {

    @BeforeClass
    public static void setupClass() {
        PhantomJsDriverManager.getInstance().useBetaVersions().setup();
    }

    @Before
    public void setupTest() {
        driver = new PhantomJSDriver();
    }

}

Include PhantomJS test forcing beta versions


package com.example.rx;

import android.test.AndroidTestCase;

public class ComposeMessageTest extends AndroidTestCase {

    public void testComposeMessage() {
        assertTrue(true); // it works!
    }
}

Include dummy test case signal for CI


package org.stepic.droid.util;

import android.content.Context;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.support.annotation.DrawableRes;

import org.stepic.droid.R;

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

import javax.inject.Singleton;

@Singleton
public class StepTypeResolver {

    private Map<String, Drawable> mapFromTypeToDrawable;
    private Context mContext;

    public StepTypeResolver(Context context) {

        mapFromTypeToDrawable = new HashMap<>();

        mapFromTypeToDrawable.put("text", getDrawable(context, R.drawable.ic_theory));
        mapFromTypeToDrawable.put("video", getDrawable(context, R.drawable.ic_video));
        mapFromTypeToDrawable.put("matching", getDrawable(context, R.drawable.ic_matching));
        mapFromTypeToDrawable.put("sorting", getDrawable(context, R.drawable.ic_sorting));
        mapFromTypeToDrawable.put("match", getDrawable(context, R.drawable.ic_math));
        mapFromTypeToDrawable.put("free-answer", getDrawable(context, R.drawable.ic_free_answer));
        mapFromTypeToDrawable.put("table", getDrawable(context, R.drawable.ic_table));
        mapFromTypeToDrawable.put("string", getDrawable(context, R.drawable.ic_string));
        mapFromTypeToDrawable.put("choice", getDrawable(context, R.drawable.ic_choice));
        mapFromTypeToDrawable.put("number", getDrawable(context, R.drawable.ic_number));
        mapFromTypeToDrawable.put("dataset", getDrawable(context, R.drawable.ic_dataset));
        mapFromTypeToDrawable.put("animation", getDrawable(context, R.drawable.ic_animation));
        mapFromTypeToDrawable.put("chemical", getDrawable(context, R.drawable.ic_chemical));
        mapFromTypeToDrawable.put("fill-blanks", getDrawable(context, R.drawable.ic_fill_blanks));
        mapFromTypeToDrawable.put("puzzle", getDrawable(context, R.drawable.ic_puzzle));
        mapFromTypeToDrawable.put("pycharm", getDrawable(context, R.drawable.ic_pycharm));

    }

    public Drawable getDrawableForType(String type) {
        Drawable drawable = mapFromTypeToDrawable.get(type);
        if (drawable != null)
            return drawable;
        else
            return getDrawable(mContext, R.drawable.ic_theory);
    }

    private Drawable getDrawable(Context context, @DrawableRes int drawableRes) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            return context.getDrawable(drawableRes);
        } else {
            return context.getResources().getDrawable(drawableRes);
        }
    }

}

Add resolver for drawable item for step


package org.realityforge.arez.api2;

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

public class GuardsTest
  extends AbstractArezTest
{
  @Test
  public void fail()
    throws Exception
  {
    final IllegalStateException exception =
      expectThrows( IllegalStateException.class, () -> Guards.fail( () -> "My Failure Reason" ) );

    assertEquals( exception.getMessage(), "My Failure Reason" );
  }

  @Test
  public void fail_verboseErrorMessages_false()
    throws Exception
  {
    final ArezConfig.DynamicProvider provider = (ArezConfig.DynamicProvider) ArezConfig.getProvider();
    provider.setVerboseErrorMessages( false );

    final IllegalStateException exception =
      expectThrows( IllegalStateException.class, () -> Guards.fail( () -> "My Failure Reason" ) );

    assertEquals( exception.getMessage(), null );
  }

  @Test
  public void fail_checkInvariants_false()
    throws Exception
  {
    final ArezConfig.DynamicProvider provider = (ArezConfig.DynamicProvider) ArezConfig.getProvider();
    provider.setCheckInvariants( false );

    // No failure
    Guards.fail( () -> "My Failure Reason" );
  }

  @Test
  public void invariant_passed()
    throws Exception
  {
    Guards.invariant( () -> true, () -> "My Failure Reason" );
  }

  @Test
  public void invariant_failed()
    throws Exception
  {
    final IllegalStateException exception =
      expectThrows( IllegalStateException.class, () -> Guards.invariant( () -> false, () -> "My Failure Reason" ) );

    assertEquals( exception.getMessage(), "My Failure Reason" );
  }

  @Test
  public void invariant_condition_throws_exception()
    throws Exception
  {
    final IllegalStateException exception =
      expectThrows( IllegalStateException.class, () -> Guards.invariant( () -> {
        throw new RuntimeException( "X" );
      }, () -> "My Failure Reason" ) );

    final String message = exception.getMessage();
    assertTrue( message.startsWith( "Error checking condition.\n" +
                                    "Message: My Failure Reason\n" +
                                    "Throwable:\n" +
                                    "java.lang.RuntimeException: X" ) );
  }

  @Test
  public void invariant_verboseErrorMessages_false()
    throws Exception
  {
    final ArezConfig.DynamicProvider provider = (ArezConfig.DynamicProvider) ArezConfig.getProvider();
    provider.setVerboseErrorMessages( false );

    final IllegalStateException exception =
      expectThrows( IllegalStateException.class, () -> Guards.invariant( () -> false, () -> "My Failure Reason" ) );

    assertEquals( exception.getMessage(), null );
  }

  @Test
  public void invariant_checkInvariants_false()
    throws Exception
  {
    final ArezConfig.DynamicProvider provider = (ArezConfig.DynamicProvider) ArezConfig.getProvider();
    provider.setCheckInvariants( false );

    // No failure
    Guards.invariant( () -> false, () -> "My Failure Reason" );
  }
}

Add some tests for guards code


package org.graphstream.gama.extension.sender;

import msi.gama.precompiler.ISymbolKind;
import msi.gama.precompiler.GamlAnnotations.inside;
import msi.gama.precompiler.GamlAnnotations.symbol;
import msi.gama.runtime.IScope;
import msi.gama.runtime.exceptions.GamaRuntimeException;
import msi.gaml.descriptions.IDescription;
import msi.gaml.statements.AbstractStatement;
import msi.gaml.statements.IStatement;

import org.graphstream.gama.extension.GSManager;
import org.graphstream.gama.extension.IKeywordGSAdditional;

@symbol(name = IKeywordGSAdditional.CLEAR_SENDERS, kind = ISymbolKind.SINGLE_STATEMENT, with_sequence = false)
@inside(kinds = { ISymbolKind.BEHAVIOR, ISymbolKind.SINGLE_STATEMENT })
public class ClearSendersStatement extends AbstractStatement implements IStatement{

	public ClearSendersStatement(IDescription desc) {
		super(desc);
	}

	@Override
	protected Object privateExecuteIn(IScope scope) throws GamaRuntimeException {
		GSManager.clearSenders();
		return null;
	}

}

Add the 'clear senders' command


// Copyright 2008 Thiago H. de Paula Figueiredo
//
// 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 br.com.arsmachina.authentication.entity;

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

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

/**
 * Test class for {@link User}.
 *
 * @author Thiago H. de Paula Figueiredo (ThiagoHP)
 */
public class UserTest {

	@Test
	public void getRoles() {

		User user = new User();
		user.setName("Test");

		new ArrayList<Permission>();

		for (int i = 0; i < 2; i++) {

			final PermissionGroup group = new PermissionGroup();
			group.setName("Group " + i);
			user.getPermissionGroups().add(group);

		}

		for (int i = 0; i < 8; i++) {

			final Permission permission = new Permission();
			permission.setName("ROLE_" + i);

			user.getPermissionGroups().get(i % 2).getPermissions().add(permission);

			if (i % 4 == 0) {
				user.getRemovedPermissions().add(permission);
			}

		}

		List<Permission> permissions = user.getPermissions();

		Assert.assertEquals(permissions.size(), 6);

		for (Permission permission : permissions) {

			Assert.assertFalse(permission.getName().equals("ROLE_0"));
			Assert.assertFalse(permission.getName().equals("ROLE_4"));

		}

	}

}

Package change: from net.sf.arsmachina to br.com.arsmachina.


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

import static org.junit.Assert.assertEquals;

import java.math.BigInteger;

import org.junit.Test;

import nom.bdezonia.zorbage.tuple.Tuple2;
import nom.bdezonia.zorbage.type.data.rational.RationalMember;
import nom.bdezonia.zorbage.type.data.unbounded.UnboundedIntMember;

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

	@Test
	public void test1() {
		RationalMember value = new RationalMember(new UnboundedIntMember(14));
		Tuple2<BigInteger,BigInteger> tuple = new Tuple2<BigInteger,BigInteger>(null,null);
		SplatRational.toTuple(value, tuple);
		assertEquals(BigInteger.valueOf(14), tuple.a());
		assertEquals(BigInteger.valueOf(1), tuple.b());
	}

	@Test
	public void test2() {
		Tuple2<BigInteger,BigInteger> tuple = new Tuple2<BigInteger,BigInteger>(BigInteger.valueOf(7),BigInteger.valueOf(14));
		RationalMember value = new RationalMember();
		SplatRational.toValue(tuple, value);
		assertEquals(BigInteger.valueOf(1), value.n());
		assertEquals(BigInteger.valueOf(2), value.d());
	}
}

Define tests for the SpatRational algorithm


package org.cyclops.cyclopscore.helper;

import net.minecraft.block.properties.IProperty;
import net.minecraft.block.state.IBlockState;
import net.minecraftforge.common.property.IExtendedBlockState;
import net.minecraftforge.common.property.IUnlistedProperty;

import javax.annotation.Nullable;

/**
 * Contains helper methods for various block specific things.
 * @author rubensworks
 */
public final class BlockHelpers {

    /**
     * Safely get a block state property for a nullable state and value that may not have been set yet.
     * @param state The block state.
     * @param property The property to get the value for.
     * @param fallback The fallback value when something has failed.
     * @param <T> The type of value to fetch.
     * @return The value.
     */
    public static <T> T getSafeBlockStateProperty(@Nullable IBlockState state, IProperty property, T fallback) {
        Comparable value = state.getValue(property);
        if(value == null) {
            return fallback;
        }
        return (T) value;
    }

    /**
     * Safely get an extended block state property for a nullable state and value that may not have been set yet.
     * @param state The block state.
     * @param property The property to get the value for.
     * @param fallback The fallback value when something has failed.
     * @param <T> The type of value to fetch.
     * @return The value.
     */
    public static <T> T getSafeBlockStateProperty(@Nullable IExtendedBlockState state, IUnlistedProperty<T> property,
                                                  T fallback) {
        if(state == null) {
            return fallback;
        }
        T value = state.getValue(property);
        if(value == null) {
            return fallback;
        }
        return value;
    }

}

Add BlockState property value retrieval helpers


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

package org.apache.jmeter.resources;

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

import org.apache.jmeter.junit.JMeterTestCaseJUnit3;
import org.apache.jmeter.util.JMeterUtils;

public class TestPropertiesFiles extends JMeterTestCaseJUnit3 {

    public void testUserProperties() throws Exception {
        Properties props = loadProps(new File(JMeterUtils.getJMeterBinDir(), "user.properties"));
        assertTrue("user.properties should not contain any enabled properties", props.isEmpty());
    }

    // The keys in jmeter.properties and reportgenerator.properties should be distinct
    public void testDefaultProperties() throws Exception {
        Properties jmeter = loadProps(new File(JMeterUtils.getJMeterBinDir(), "jmeter.properties"));
        Properties report = loadProps(new File(JMeterUtils.getJMeterBinDir(), "reportgenerator.properties"));
        {
            Enumeration<?> names = jmeter.propertyNames();
            while(names.hasMoreElements()) {
                final Object key = names.nextElement();
                assertFalse("reportgenerator should not contain the jmeter key " + key, report.containsKey(key));
            }
        }
        {
            Enumeration<?> names = report.propertyNames();
            while(names.hasMoreElements()) {
                final Object key = names.nextElement();
                assertFalse("jmeter should not contain the reportgenerator key " + key, jmeter.containsKey(key));
            }
        }
    }

    private static Properties loadProps(File file) throws Exception{
        Properties props = new Properties();
        try (FileInputStream inStream = new FileInputStream(file)){
            props.load(inStream);
        }
        return props;
    }
}

Add tests for properties files


/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */

public class Solution {

    private int sum = 0;

    public TreeNode convertBST(TreeNode root) {

        if (root == null) {
            return null;
        }

        convertBST(root.right);

        root.val += sum;
        sum = root.val;

        convertBST(root.left);

        return root;

    }

}

Create : 538 Convert BST to Greater Tree


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

package org.springframework.security.oauth2.client.web.reactive.function.client;

import org.springframework.security.oauth2.client.web.OAuth2AuthorizedClientRepository;
import org.springframework.web.reactive.function.client.WebClient;

import java.util.function.Consumer;

/**
 * @author Rob Winch
 * @since 5.1
 */
public final class OAuth2ExchangeFilterFunctions {

	/**
	 * Configures the WebClient for OAuth2 support in a servlet environment.
	 * @param repository the repository to use
	 * @return the {@link Consumer} to configure the WebClient
	 */
	public static Consumer<WebClient.Builder> oauth2ServletConfig(OAuth2AuthorizedClientRepository repository) {
		return new ServletOAuth2AuthorizedClientExchangeFilterFunction(repository)
				.oauth2Configuration();
	}

	/**
	 * Configures the WebClient for OAuth2 support in a servlet environment.
	 * @return the {@link Consumer} to configure the WebClient
	 */
	public static Consumer<WebClient.Builder> oauth2ServletConfig() {
		return new ServletOAuth2AuthorizedClientExchangeFilterFunction()
				.oauth2Configuration();
	}

	private OAuth2ExchangeFilterFunctions() {}
}

Add static methods for ServletOAuth2AuthorizedClientExchangeFilterFunction


package cs437.som.learningrate;

import cs437.som.LearningRateFunction;

/**
 * Learning rate strategy for self-organizing maps that decays the learning
 * rate exponentially as the iterations progress.
 *
 * <pre>
 * The exact behavior follows the formula:
 *      \alpha_0 * e^(-t / t_{max})
 *  where
 *      \alpha_0 is the initial learning rate
 *      e        is the base of the natural logarithm
 *      t        is the current iteration
 *      t_{max}  is the maximum expected iteration
 * </pre>
 */
public class ExponentialDecayLearningRateFunction implements LearningRateFunction {
    private final double initialLearningRate;
    private double expectedIterations = 0.0;

    /**
     * Create an exponentially decaying learning rate function.
     *
     * @param initialWidth The initial learning rate.
     */
    public ExponentialDecayLearningRateFunction(double initialWidth) {
        initialLearningRate = initialWidth;
    }

    public void setExpectedIterations(int expectedIterations) {
        this.expectedIterations = expectedIterations;
    }

    public double learningRate(int iteration) {
        return initialLearningRate * Math.exp(-iteration / expectedIterations);
    }

    @Override
    public String toString() {
        return "ExponentialDecayLearningRateFunction";
    }
}

Add exponential decay learning rate.


/*
 * Electronic Logistics Management Information System (eLMIS) is a supply chain management system for health commodities in a developing country setting.
 *
 * Copyright (C) 2015  John Snow, Inc (JSI). This program was produced for the U.S. Agency for International Development (USAID). It was prepared under the USAID | DELIVER PROJECT, Task Order 4.
 *
 * This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package org.openlmis.vaccine.domain.inventory;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.openlmis.core.domain.BaseModel;

@Data
@NoArgsConstructor
@AllArgsConstructor
public class AdjustmentReason extends BaseModel {
    private Long lotOnHandId;
    private String name;
    private Long quantity;
}

Add Adjustment Reason to save


package org.simpleframework.xml.core;

import java.io.StringWriter;

import junit.framework.TestCase;

import org.simpleframework.xml.Attribute;
import org.simpleframework.xml.Root;
import org.simpleframework.xml.Serializer;
import org.simpleframework.xml.Text;
import org.simpleframework.xml.transform.Matcher;
import org.simpleframework.xml.transform.Transform;

public class TextConstructorInjectionWithTransformTest extends TestCase {

   private static class DateTime {
      private String time;
      public DateTime(String time) {
         this.time = time;
      }
      public String getTime() {
         return time;
      }
      public String toString() {
         return time;
      }
   }

   private static class DateTimeTransform implements Transform<DateTime> {
      public DateTime read(String text) throws Exception {
          return new DateTime(text);
      }
      public String write(DateTime value) throws Exception {
          return value.getTime();
      }
   }

   public class DateTimeMatcher implements Matcher {
      public Transform match(Class type) throws Exception {
         if(type == DateTime.class) {
            return new DateTimeTransform();
         }
         return null;
      }
   }

   @Root
   public static class Embargo {
      @Attribute
      private String name;
      @Text
      private DateTime embargo_datetime;
      public Embargo(@Text DateTime embargo_datetime, @Attribute(name="name") String name) {
          this.embargo_datetime = embargo_datetime;
          this.name = name;
      }
      public DateTime getEmbargo() {
          return embargo_datetime;
      }
      public void setEmbargo(DateTime embargo_datetime) {
          this.embargo_datetime = embargo_datetime;
      }
  }

   public void testConstructor() throws Exception {
      Embargo embargo = new Embargo(new DateTime("2010-06-02T12:00:12"), "cuba");
      Serializer serializer = new Persister(new DateTimeMatcher());
      StringWriter writer = new StringWriter();

      serializer.write(embargo, writer);

      Embargo embargoout = serializer.read(Embargo.class, writer.toString());

      System.out.println(writer.toString());
   }

}

Add test for @Text injection


package com.javarush.task.task05.task0510;

/*
Кошкоинициация
*/

/*
    — Имя,
    — Имя, вес, возраст
    — Имя, возраст (вес стандартный)
    — вес, цвет (имя, адрес и возраст неизвестны, это бездомный кот)
    — вес, цвет, адрес (чужой домашний кот)
*/

public class Cat {

    /*

    Валидатор поел говна.
    Закомментированый ниже код не принимается (WTF?).

    private String name = null;
    private int age;
    private int weight;
    private String address = null;
    private String color = null;

    public void initialize(String name) {
        this.name = name;
        this.age = 4;
        this.weight = 5;
        this.color = "white";
    }

    public void initialize(String name, int weight, int age) {
        this.name = name;
        this.weight = weight;
        this.age = age;
        this.color = "white";
    }

    private void initialize(String name, int age) {
        this.name = name;
        this.age = age;
        this.weight = 5;
        this.color = "white";
    }

    public void initialize(int weight, String color) {
        this.age = 4;
        this.weight = weight;
        this.color = color;
    }

    public void initialize(int weight, String color, String address) {
        this.age = 4;
        this.weight = weight;
        this.address = address;
        this.color = color;
    }
    */

    private String name = null;
    private int weight; //weight
    private int age;
    private String color = null;
    private String address = null;

    public void initialize (String name) {
        this.name = name;
        this.weight = 5;
        this.age = 5;
        this.color = "black";
    }

    public void initialize (String name, int weight, int age) {
        this.name = name;
        this.weight= weight;
        this.age = age;
        this.color = "black";
    }

    public void initialize (String name, int age) {
        this.name = name;
        this.weight= 5;
        this.age = age;

    }

    public void initialize (int weight, String color) {
        this.weight= weight;
        this.age = 5;
        this.color = color;
    }

    public void initialize (int weight, String color, String address) {
        this.weight= weight;
        this.age = 5;
        this.color = color;
        this.address = address;
    }

    public static void main(String[] args) {

    }
}

Complete 0510. Validator poel govna in this task IMHO


package com.jmb.springfactory.controller.api;

import org.springframework.beans.factory.annotation.Autowired;

import com.jmb.springfactory.controller.GenericController;
import com.jmb.springfactory.model.dto.RolDto;
import com.jmb.springfactory.service.GenericService;
import com.jmb.springfactory.service.rol.RolService;

public class RolController extends GenericController<RolDto, String>{

  @Autowired
  private RolService rolService;

  @Override
  public GenericService<RolDto, String> genericService() {
    return rolService;
  }

}

Create a controller to handle petition to rol resources


package org.nwapw.abacus.plugin;

import org.nwapw.abacus.number.NumberInterface;

import java.util.Map;
import java.util.function.Function;

public abstract class NumberImplementation {

    private Class<? extends NumberInterface> implementation;
    private Map<String, Function<NumberInterface, NumberInterface>> promotionPaths;
    private int priority;

    public abstract NumberInterface instanceForString(String string);
    public abstract NumberInterface instanceForPi();

}

Add a class that keeps track of the implementation information.


package org.bouncycastle.crypto.prng;

/**
 * Takes bytes generated by an underling RandomGenerator and reverses the order in
 * each small window (of configurable size).
 * <p>
 * Access to internals is synchronized so a single one of these can be shared.
 * </p>
 */
public class ReversedWindowGenerator
    implements RandomGenerator
{
    private final RandomGenerator generator;

    private byte[] window;
    private int windowCount;

    public ReversedWindowGenerator(
        RandomGenerator generator,
        int             windowSize)
    {
        if (generator == null)
            throw new IllegalArgumentException("generator cannot be null");
        if (windowSize < 2)
            throw new IllegalArgumentException("windowSize must be at least 2");

        this.generator = generator;
        this.window = new byte[windowSize];
    }

    /**
     * Add more seed material to the generator.
     *
     * @param seed a byte array to be mixed into the generator's state.
     */
    public void addSeedMaterial(
        byte[] seed)
    {
        synchronized (this)
        {
            windowCount = 0;
            generator.addSeedMaterial(seed);
        }
    }

    /**
     * Add more seed material to the generator.
     *
     * @param seed a long value to be mixed into the generator's state.
     */
    public void addSeedMaterial(
        long seed)
    {
        synchronized (this)
        {
            windowCount = 0;
            generator.addSeedMaterial(seed);
        }
    }

    /**
     * Fill bytes with random values.
     *
     * @param bytes byte array to be filled.
     */
    public void nextBytes(
        byte[] bytes)
    {
        doNextBytes(bytes, 0, bytes.length);
    }

    /**
     * Fill part of bytes with random values.
     *
     * @param bytes byte array to be filled.
     * @param start index to start filling at.
     * @param len length of segment to fill.
     */
    public void nextBytes(
        byte[]  bytes,
        int     start,
        int     len)
    {
        doNextBytes(bytes, start, len);
    }

    private void doNextBytes(
        byte[]  bytes,
        int     start,
        int     len)
    {
        synchronized (this)
        {
            int done = 0;
            while (done < len)
            {
                if (windowCount < 1)
                {
                    generator.nextBytes(window, 0, window.length);
                    windowCount = window.length;
                }

                bytes[start + done++] = window[--windowCount];
            }
        }
    }
}

Add a generator that reverses the output of another generator over each short window.


/* This file is part of SableCC (http://sablecc.org/).
 *
 * See the NOTICE file distributed with this work for copyright information.
 *
 * 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.sablecc.sablecc.alphabet;

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

import org.junit.Test;
import org.sablecc.sablecc.exception.InternalException;

public class InternalExceptionTest {

    @Test
    @SuppressWarnings("unused")
    public void testInternalExceptionString() {

        // Initializing a good internal exception.
        InternalException goodInternalException = new InternalException(
                "Not null");

        // Testing no thrown exception when the message is not null.
        try {
            goodInternalException = new InternalException("Valid message");
        }
        catch (InternalException e) {
            fail("InternalException not expected here.");
        }

        // Testing thrown exception when the message is null.
        try {
            InternalException nullMessageInternalException = new InternalException(
                    null);
            fail("An InternalException should be thrown.");
        }
        catch (InternalException e) {
            // Expected
        }

        // Verifying validity provided message is taken correctly.
        assertEquals("Invalid exception message", "Valid message",
                goodInternalException.getMessage());
    }

    @Test
    @SuppressWarnings("unused")
    public void testInternalExceptionStringThrowable() {

        Throwable cause = new Throwable();

        // Initializing a good internal exception.
        InternalException goodInternalException = new InternalException(
                "Not null", cause);

        // Testing no thrown exception when message and cause not null.
        try {
            goodInternalException = new InternalException("Valid message",
                    cause);
        }
        catch (InternalException e) {
            fail("InternalException not expected here.");
        }

        // Testing thrown exception when message is null, cause is good.
        try {
            InternalException nullMessageInternalException = new InternalException(
                    null, cause);
            fail("An InternalException should be thrown.");
        }
        catch (InternalException e) {
            // Expected
        }

        // Testing thrown exception when cause is null, message is good.
        try {
            InternalException nullCauseInternalException = new InternalException(
                    "Message", null);
            fail("An InternalException should be thrown.");
        }
        catch (InternalException e) {
            // Expected
        }

        // Testing thrown exception when message and cause are null.
        try {
            InternalException nullMessageAndCauseInternalException = new InternalException(
                    null, null);
            fail("An InternalException should be thrown.");
        }
        catch (InternalException e) {
            // Expected
        }

        // Verifying validity provided message is taken correctly.
        assertEquals("Invalid exception message", "Valid message",
                goodInternalException.getMessage());

        // Verifying validity provided message is taken correctly.
        assertEquals("Invalid exception cause", cause, goodInternalException
                .getCause());

    }

}

Add JUnit tests for InternalException.


/*
 * FindBugs - Find Bugs in Java programs
 * Copyright (C) 2003-2007 University of Maryland
 *
 * 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., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */

package edu.umd.cs.findbugs;

import java.io.IOException;
import java.util.HashSet;
import java.util.Set;

import org.dom4j.DocumentException;

/**
 * @author pugh
 */
public class ExcludingHashesBugReporter extends DelegatingBugReporter {

	Set<String> excludedHashes = new HashSet<String>();
	/**
     * @param delegate
	 * @throws DocumentException
	 * @throws IOException
     */
    public ExcludingHashesBugReporter(BugReporter delegate, String baseline) throws IOException, DocumentException {
	    super(delegate);
		Project project = new Project();
		BugCollection origCollection;
		origCollection = new SortedBugCollection();
		origCollection.readXML(baseline, project);
		for(BugInstance b : origCollection.getCollection())
			excludedHashes.add(b.getInstanceHash());
    }
	@Override
	public void reportBug(BugInstance bugInstance) {
		if (!excludedHashes.contains(bugInstance.getInstanceHash()))
				getDelegate().reportBug(bugInstance);
	}
}

Add delegating bug reporter that filters out bugs that match a known instance hash


/*******************************************************************************
 * This file is part of OpenNMS(R).
 *
 * Copyright (C) 2016 The OpenNMS Group, Inc.
 * OpenNMS(R) is Copyright (C) 1999-2016 The OpenNMS Group, Inc.
 *
 * OpenNMS(R) is a registered trademark of The OpenNMS Group, Inc.
 *
 * OpenNMS(R) is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published
 * by the Free Software Foundation, either version 3 of the License,
 * or (at your option) any later version.
 *
 * OpenNMS(R) is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with OpenNMS(R).  If not, see:
 *      http://www.gnu.org/licenses/
 *
 * For more information contact:
 *     OpenNMS(R) Licensing <license@opennms.org>
 *     http://www.opennms.org/
 *     http://www.opennms.com/
 *******************************************************************************/

package org.opennms.smoketest;

import java.util.List;

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

import com.google.common.collect.Lists;

public class TopologyIT extends OpenNMSSeleniumTestCase {

    private static final String TOPOLOGY_UI_URL = BASE_URL + "opennms/topology";

    private final TopologyUiPage topologyUiPage = new TopologyUiPage();

    private final static List<String> availableLayouts = Lists.newArrayList(
            "Circle Layout",
            "D3 Layout",
            "FR Layout",
            "Hierarchy Layout",
            "ISOM Layout",
            "KK Layout",
            "Manual Layout",
            "Real Ultimate Layout",
            "Spring Layout"
            );

    /**
     * Class to control the inputs and workflow of the "Topology UI" Page
     */
    private class TopologyUiPage {
        public TopologyUiPage open() {
            m_driver.get(TOPOLOGY_UI_URL);
            return this;
        }

        public TopologyUiPage selectLayout(String layoutName) {
            clickItemInMenuBar("View");
            clickItemInMenuBar(layoutName);
            showEntireMap();
            return this;
        }

        private void clickItemInMenuBar(String itemName) {
            findElementByXpath("//span[@class='v-menubar-menuitem-caption' and text()='" + itemName + "']").click();
        }

        private void showEntireMap() {
            findElementByXpath("//i[@class='icon-globe']").click();
        }
    }

    @Before
    public void setUp() {
        topologyUiPage.open();
    }

    @Test
    public void canSelectLayouts() throws InterruptedException {
        for (String layout : availableLayouts) {
            topologyUiPage.selectLayout(layout);
        }
    }
}

Add a simple Topology UI tests that cycles through known layouts.


package org.robockets.stronghold.robot.commands;

import org.robockets.stronghold.robot.highgoalshooter.MoveHood;
import org.robockets.stronghold.robot.highgoalshooter.MoveTurnTable;
import org.robockets.stronghold.robot.intake.IntakesUp;

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

/**
 *
 */
public class DrivePosition extends CommandGroup {

    public  DrivePosition() {
        addSequential(new MoveHood(-70));
        addSequential(new IntakesUp());
        addSequential(new MoveTurnTable(0));
    }
}

Add command to move robot to its driving position


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

/**
 * Given a BinaryTree and two nodes, can you write a method to find the lowest common ancestor of
 * this nodes?
 *
 * @author Pedro Vicente Gómez Sánchez.
 */
public class LowestCommonAncestor {
}

Add statement to problem 21


package com.sunny.grokkingalgorithms.ctc.c2;

import com.sunny.grokkingalgorithms.ctc.c2.util.LinkedListUtil;
import com.sunny.grokkingalgorithms.ctc.c2.util.Node;

/**
 * Created by sundas on 3/14/2018.
 */
public class DeleteMiddleOfLinkedListGivenReference {

  /*
  Given reference to a node , delete it from the linked list.If it is last element you
  will not be delete it.

  a->b->c->d
  delete c
  after deletion
  a->b->d
   */

  /**
   *
   * @param middle
   */
  public static void deleteNodeFromMiddle(Node middle){
    if(middle != null
        && middle.next != null){
      /*
      Copy next node's value into middle which is essentailly line overwriting existing middle's value and then
      delete next
       */
      middle.data = middle.next.data;
      middle.next = middle.next.next;
    }
  }

  /**
   *
   * @param root
   * @return
   */
  public static Node findMiddleOfLinkedList(Node root){
    /*
    Once again we use the fast runner apporach. The fast runner covers twice as much noes as slow
     runner so when fast runner will be at the end, slow runner will be in the middle
     */
    Node slowRunner = root;
    Node fastRunner = root;
    while(fastRunner != null && slowRunner != null){
      slowRunner = slowRunner.next;
      fastRunner = fastRunner.next;
      if(fastRunner != null){
        fastRunner = fastRunner.next;
      }
    }
    //Now slow runner is at the middle
    return slowRunner;
  }

  /**
   *
   * @param args
   */
  public static void main(String[] args) {
    int[] input = new int[]{1,2,3,4,5,6,7,8};
    Node root = LinkedListUtil.createLinkedList(input);
    LinkedListUtil.printLinkedList(root);
    Node middle = findMiddleOfLinkedList(root);
    System.out.println(middle.data);
    deleteNodeFromMiddle(middle);
    LinkedListUtil.printLinkedList(root);
  }
}

Delete node from middle of linked list.


// ======================================================================
// Filename: Card.java
// Description: Define and implement a basic playing card.
// Created: Fri Mar 24 21:37:59 2017 (-0500)
// Last-Updated: Fri Mar 24 23:02:27 2017 (-0500)
// Author: Ivan Guerra <Ivan.E.Guerra-1@ou.edu>
// ======================================================================
package com.mouthofrandom.cardshark.game.blackjack;

public class Card {
    private String suit;
    private String cardType;
    private int value;

    public Card(final String suit, final String cardType, final int value) {
	this.suit = suit;
	this.cardType = cardType;
	this.value = value;
    }

    /* Return the card suit. */
    public String getSuit() {
	return suit;
    }

    /* Return the card type. */
    public String getCardType() {
	return cardType;
    }

    /* Return the card value. */
    public int getValue() {
	return value;
    }

    /* Return the string representation of a Card. */
    public String toString() {
	return ("(" + this.suit + ", " + this.cardType + ", " + this.value + ")");
    }
}

Add a class for representing playing cards.


package com.suse.saltstack.netapi.event;

import java.io.IOException;

import javax.websocket.CloseReason;
import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;

import com.suse.saltstack.netapi.utils.ClientUtils;

/**
 * This class is intended to emulate the Server WebSocket
 * EndPoint where EventStream is connected to, and where events came from.
 */
@ServerEndpoint(value = "/token")
public class WebSocketServerSalt {

    /**
     * Note: The event stream message is a String delimited by "\n\n". The resource file
     * events_stream.txt contains some events separated by "\n\n".
     */
    static final String[] TEXT_EVENT_STREAM_MESSAGES =
            ClientUtils.streamToString(WebSocketServerSalt.class
                    .getResourceAsStream("/events_stream.txt")).split("\n\n");

    @OnOpen
    public void onOpen(Session session) {
    }

    @OnMessage
    public void onMessage(String message, Session session) {
        try {
            for (String s : TEXT_EVENT_STREAM_MESSAGES) {
                session.getBasicRemote().sendText(s);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @OnClose
    public void onClose(Session session, CloseReason closeReason) {
    }
}

Add an emulation of a websocket server endpoint


Create a text "template" file for class instantiation. Will find a better solution in the future.


package at.ac.univie.isc.asio.junit;

import com.hp.hpl.jena.rdf.model.Model;
import org.hamcrest.Description;
import org.hamcrest.TypeSafeMatcher;

public final class IsSuperSetOf extends TypeSafeMatcher<Model> {
  /**
   * Create a matcher for {@link com.hp.hpl.jena.rdf.model.Model jena rdf models}, matching when the
   * examined model contains all statements in the given reference model.
   *
   * @param expected expected RDF statements
   */
  public static IsSuperSetOf superSetOf(final Model expected) {
    return new IsSuperSetOf(expected);
  }

  private final Model expected;

  private IsSuperSetOf(final Model expected) {
    this.expected = expected;
  }

  @Override
  protected boolean matchesSafely(final Model item) {
    return item.containsAll(expected);
  }

  @Override
  public void describeTo(final Description description) {
    description.appendText("model containing all statements from ").appendValue(expected);
  }
}

Add contains matcher for jena models


/*
 * $Id: IOPScienceUrlNormalizer.java,v 1.1 2013-10-10 00:06:43 etenbrink Exp $
 */

/*

Copyright (c) 2000-2013 Board of Trustees of Leland Stanford Jr. University,
all rights reserved.

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
STANFORD UNIVERSITY 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.

Except as contained in this notice, the name of Stanford University shall not
be used in advertising or otherwise to promote the sale, use or other dealings
in this Software without prior written authorization from Stanford University.

*/

package org.lockss.plugin.iop;

import org.apache.commons.lang.StringUtils;
import org.lockss.daemon.PluginException;
import org.lockss.plugin.*;
import org.lockss.util.*;

/**
 *
This URL normalizer is only for org.lockss.plugin.iop.(Clockss)IOPSciencePlugin

 */
public class IOPScienceUrlNormalizer implements UrlNormalizer {

  private static final String host = "http://iopscience.iop.org/";

  protected static final String[] endings = new String[] {
    "?rel=ref",
    "?rel=sem",
  };

  protected static Logger log =
      Logger.getLogger(IOPScienceUrlNormalizer.class);

  @Override
  public String normalizeUrl(String url, ArchivalUnit au) throws PluginException {
    if (url == null) {
      return null;
    }
    if (StringUtil.startsWithIgnoreCase(url, host)) {
      if (url.indexOf("?") > 0) {
        // Normalize ending
        for (String ending : endings) {
          url = StringUtils.substringBefore(url, ending);
        }
      }
    }
    return url;
  }

}

Add to remove ?rel=(ref|sem), links to articles in the same AU


package refdiff.core.diff;

import refdiff.core.rast.RastNode;

public class PotentialMatch implements Comparable<PotentialMatch> {

	private final RastNode nodeBefore;
	private final RastNode nodeAfter;
	private final int maxDepth;
	private final double score;

	public PotentialMatch(RastNode nodeBefore, RastNode nodeAfter, int maxDepth, double score) {
		this.nodeBefore = nodeBefore;
		this.nodeAfter = nodeAfter;
		this.maxDepth = maxDepth;
		this.score = score;
	}

	public RastNode getNodeBefore() {
		return nodeBefore;
	}

	public RastNode getNodeAfter() {
		return nodeAfter;
	}

	public double getScore() {
		return score;
	}

	public double getMaxDepth() {
		return score;
	}

	@Override
	public String toString() {
		return String.format("(%s, %s)", this.nodeBefore, this.nodeAfter);
	}

	@Override
	public int compareTo(PotentialMatch o) {
		int c1 = Integer.compare(maxDepth, o.maxDepth);
		int c2 = -Double.compare(score, o.score);
		return c1 != 0 ? c1 : c2;
	}
}

Use node depth to sort candidates


package uk.ac.ebi.atlas.bioentity.properties;

import org.junit.Test;
import uk.ac.ebi.atlas.model.experiment.baseline.BioentityPropertyName;

import java.util.Map.Entry;

import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
import static uk.ac.ebi.atlas.model.experiment.baseline.BioentityPropertyName.GENE_BIOTYPE;

public class BioEntityCardPropertiesTest {

    @Test
    public void linkTemplatesExceptGeneBiotypeHaveFormatElements() throws Exception {
        for (Entry<BioentityPropertyName, String> linkTemplate : BioEntityCardProperties.linkTemplates.entrySet()) {
            if (linkTemplate.getKey() != GENE_BIOTYPE) {
                assertThat(linkTemplate.getValue().matches(".+\\{\\d\\}.*"), is(true));
            }
        }
    }

}

Add new test for BioEntityCardProperties