/*
 *
 * 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.qpid.proton.engine;

/**
 * Transport
 *
 * @opt operations
 * @opt types
 *
 */

public interface Transport extends Endpoint
{

    /**
     * @param bytes input bytes for consumption
     * @param offset the offset within bytes where input begins
     * @param size the number of bytes available for input
     *
     * @return the number of bytes consumed
     */
    public int input(byte[] bytes, int offset, int size);

    /**
     * @param bytes array for output bytes
     * @param offset the offset within bytes where output begins
     * @param size the number of bytes available for output
     *
     * @return the number of bytes written
     */
    public int output(byte[] bytes, int offset, int size);

}

/*
 *
 * 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.qpid.proton.engine;

/**
 * Transport
 *
 * @opt operations
 * @opt types
 *
 */

public interface Transport extends Endpoint
{

    public int END_OF_STREAM = -1;
    /**
     * @param bytes input bytes for consumption
     * @param offset the offset within bytes where input begins
     * @param size the number of bytes available for input
     *
     * @return the number of bytes consumed
     */
    public int input(byte[] bytes, int offset, int size);

    /**
     * @param bytes array for output bytes
     * @param offset the offset within bytes where output begins
     * @param size the number of bytes available for output
     *
     * @return the number of bytes written
     */
    public int output(byte[] bytes, int offset, int size);

}

Add constant definition for Proton end of stream


/*
 * Copyright 2000-2017 JetBrains s.r.o.
 *
 * 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.intellij.debugger.memory.component;

import com.intellij.debugger.memory.utils.StackFrameItem;
import com.sun.jdi.ObjectReference;
import com.sun.jdi.ReferenceType;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.util.List;

/**
 * @author Vitaliy.Bibaev
 */
public interface TrackedStacksContainer {
  @Nullable
  List<StackFrameItem> getStack(@NotNull ObjectReference reference);

  void addStack(@NotNull ObjectReference ref, @NotNull List<StackFrameItem> frames);

  void pinStacks(@NotNull ReferenceType referenceType);

  void unpinStacks(@NotNull ReferenceType referenceType);

  void release();
}

Add interface for container with stack-frames which was tracked


package au.gov.ga.geodesy.gws.systemtest;

import static io.restassured.RestAssured.given;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;

import org.springframework.http.HttpStatus;
import org.testng.annotations.Test;

import io.restassured.response.Response;

public class SetupTest extends BaseSystemTest {

    @Test
    public void findSetupsByIdAndDate() throws Exception {
        Response response = given()
            .get(getConfig().getWebServicesUrl() + "/setups/search/findByFourCharacterId?id=ALIC&effectiveFrom=2011-12-12&effectiveTo=2014-12-12&timeFormat=uuuu-MM-dd")
            .then()
            .statusCode(HttpStatus.OK.value())
            .extract().response();

       assertThat(response.jsonPath().get("page.totalElements"), is(3));
       assertThat(response.jsonPath().get("_embedded.setups[0].name"), is("GNSS CORS Setup"));
       assertThat(response.jsonPath().get("_embedded.setups[0].name"), is("GNSS CORS Setup"));
       assertThat(response.jsonPath().get("_embedded.setups[0].effectivePeriod.from"), is("2011-07-20T00:00:00Z"));
       assertThat(response.jsonPath().get("_embedded.setups[0].effectivePeriod.to"), is("2013-03-08T00:00:00Z"));
    }
}

Add system test for cors setups


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

import com.google.common.testing.EqualsTester;
import org.junit.Test;

import static io.spine.server.delivery.UniformAcrossTargets.forNumber;
import static io.spine.server.delivery.UniformAcrossTargets.singleShard;

/**
 * @author Alex Tymchenko
 */
public class UniformAcrossTargetsShould {

    @Test
    public void support_equality() {
        new EqualsTester().addEqualityGroup(singleShard(), singleShard(), forNumber(1))
                          .addEqualityGroup(forNumber(3), forNumber(3))
                          .addEqualityGroup(forNumber(42), forNumber(42))
                          .testEquals();
    }

    @Test(expected = IllegalArgumentException.class)
    public void not_allow_negative_number_of_shards() {
        forNumber(-1);
    }

    @Test(expected = IllegalArgumentException.class)
    public void not_allow_zero_number_of_shards() {
        forNumber(0);
    }
}

Add more tests for `UniformAcrossTargets`.


/*
 * 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 org.junit.Test;

import nom.bdezonia.zorbage.algebras.G;
import nom.bdezonia.zorbage.procedure.Procedure1;
import nom.bdezonia.zorbage.type.data.int32.SignedInt32Member;
import nom.bdezonia.zorbage.type.storage.array.ArrayStorage;
import nom.bdezonia.zorbage.type.storage.datasource.IndexedDataSource;

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

	@Test
	public void test1() {
		SignedInt32Member value = G.INT32.construct();
		IndexedDataSource<SignedInt32Member> ints = ArrayStorage.allocateInts(new int[] {1,2,3});
		Procedure1<SignedInt32Member> proc = new Procedure1<SignedInt32Member>() {
			@Override
			public void call(SignedInt32Member a) {
				a.setV(17);
			}
		};

		Transform1.compute(G.INT32, proc, ints);

		assertEquals(3, ints.size());
		value.setV(0);
		ints.get(0,  value);
		assertEquals(17, value.v());
		value.setV(0);
		ints.get(1,  value);
		assertEquals(17, value.v());
		value.setV(0);
		ints.get(2,  value);
		assertEquals(17, value.v());
	}
}

Define a test for the Transform1 algorithm


/******************************************************************************
 *                                                                            *
 *                    Copyright 2018 Subterranean Security                    *
 *                                                                            *
 *  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.sandpolis.viewer.jfx.common;

import java.util.concurrent.TimeUnit;

import io.netty.util.concurrent.AbstractEventExecutor;
import io.netty.util.concurrent.EventExecutor;
import io.netty.util.concurrent.Future;
import javafx.application.Platform;

/**
 * This {@link EventExecutor} implementation runs tasks on the JavaFX
 * application thread. The primary motivation is to allow {@link Future}
 * listeners to be executed on the GUI update thread.

 *

 * Only one instance of this class may be created and should be accessed via
 * {@link #INSTANCE}.
 *
 * @author cilki
 * @since 5.0.0
 */
public final class FxEventExecutor extends AbstractEventExecutor {
	private FxEventExecutor() {
	}

	public static final FxEventExecutor INSTANCE = new FxEventExecutor();

	@Override
	public boolean isShuttingDown() {
		throw new UnsupportedOperationException();
	}

	@Override
	public Future<?> shutdownGracefully(long quietPeriod, long timeout, TimeUnit unit) {
		throw new UnsupportedOperationException();
	}

	@Override
	public Future<?> terminationFuture() {
		throw new UnsupportedOperationException();
	}

	@Override
	public boolean isShutdown() {
		throw new UnsupportedOperationException();
	}

	@Override
	public boolean isTerminated() {
		throw new UnsupportedOperationException();
	}

	@Override
	public boolean awaitTermination(long timeout, TimeUnit unit) throws InterruptedException {
		throw new UnsupportedOperationException();
	}

	@Override
	public boolean inEventLoop(Thread thread) {
		if (!Thread.currentThread().equals(thread))
			throw new UnsupportedOperationException(
					"FxEventExecutor supports querying the eventloop status of the current thread only");

		return Platform.isFxApplicationThread();
	}

	@Override
	public void execute(Runnable command) {
		Platform.runLater(command);
	}

	@Override
	public void shutdown() {
		Platform.exit();
	}

}

Add a JavaFX EventExecutor for Future implementations


package org.spongepowered.common.mixin.api.mcp.particles;

import net.minecraft.util.ResourceLocation;
import net.minecraft.util.registry.Registry;
import org.spongepowered.api.ResourceKey;
import org.spongepowered.api.effect.particle.ParticleOption;
import org.spongepowered.api.effect.particle.ParticleType;
import org.spongepowered.asm.mixin.Mixin;

import java.util.Collections;
import java.util.Map;
import java.util.Optional;

@Mixin(net.minecraft.particles.ParticleType.class)
public abstract class ParticleTypeMixin_API implements ParticleType {

    private ResourceKey impl$key;

    @Override
    public <V> Optional<V> getDefaultOption(ParticleOption<V> option) {
        // TODO
        return Optional.empty();
    }

    @Override
    public Map<ParticleOption<?>, Object> getDefaultOptions() {
        // TODO
        return Collections.emptyMap();
    }

    @SuppressWarnings("ConstantConditions")
    @Override
    public ResourceKey getKey() {
        if (this.impl$key == null) {
            final ResourceLocation location = Registry.PARTICLE_TYPE.getKey((net.minecraft.particles.ParticleType<?>) (Object) this);
            this.impl$key = (ResourceKey) (Object) location;
        }
        return this.impl$key;
    }
}

Implement sponge ParticleType onto minecraft ParticleType for standard named particles.


package com.m4gik;

/**
 * The basic visible methods of any hash algorithm.
 *

 * A hash (or message digest) algorithm produces its output by iterating a basic
 * compression function on blocks of data.
 */
public interface IMessageDigest extends Cloneable {
    /**
     * Returns the algorithm's (inner) block size in bytes.
     *
     * @return the algorithm's inner block size in bytes.
     */
    int blockSize();

    /**
     * Returns a clone copy of this instance.
     *
     * @return a clone copy of this instance.
     */
    Object clone();

    /**
     * Completes the message digest by performing final operations such as
     * padding and resetting the instance.
     *
     * @return the array of bytes representing the hash value.
     */
    byte[] digest();

    /**
     * Returns the output length in bytes of this message digest algorithm.
     *
     * @return the output length in bytes of this message digest algorithm.
     */
    int hashSize();

    /**
     * Returns the canonical name of this algorithm.
     *
     * @return the canonical name of this instance.
     */
    String name();

    /**
     * Resets the current context of this instance clearing any eventually
     * cached intermediary values.
     */
    void reset();

    /**
     * A basic test. Ensures that the digest of a pre-determined message is
     * equal to a known pre-computed value.
     *
     * @return true if the implementation passes a basic self-test.
     *         Returns false otherwise.
     */
    boolean selfTest();

    /**
     * Continues a message digest operation using the input byte.
     *
     * @param b
     *            the input byte to digest.
     */
    void update(byte b);

    /**
     * Continues a message digest operation, by filling the buffer, processing
     * data in the algorithm's HASH_SIZE-bit block(s), updating the context and
     * count, and buffering the remaining bytes in buffer for the next
     * operation.
     *
     * @param in
     *            the input block.
     */
    void update(byte[] in);

    /**
     * Continues a message digest operation, by filling the buffer, processing
     * data in the algorithm's HASH_SIZE-bit block(s), updating the context and
     * count, and buffering the remaining bytes in buffer for the next
     * operation.
     *
     * @param in
     *            the input block.
     * @param offset
     *            start of meaningful bytes in input block.
     * @param length
     *            number of bytes, in input block, to consider.
     */
    void update(byte[] in, int offset, int length);
}

Create interface for digest the given message


package co.kr.godo.test.stub;

public class TestObjectDriver {
	public static void main(String[] args) {
		TestObject testObject = new TestObject();
		testObject.setStubInterface(new Stub());

		int[] params = {10,10};
		int result = testObject.Calculate(params);
		System.out.println(result);
		if (result == -400) {
			System.out.println("정상");
		} else {
			System.out.println("오류");
		}
	}
}

Test Sample : Test Stub (2) 테스트 드라이브를 생성 Test 대상 클래스 메소드 호출 - Test 대상 Class의 메소드를 호출하는 부분이 있어야 함으로


package org.eclipse.dawnsci.plotting.api.trace;

import java.util.List;

import org.eclipse.dawnsci.analysis.api.dataset.IDataset;

/**
 * A trace for adding together multiple other traces and plotting
 * them as if they were images.
 *
 * The initial version is for multiple IImageTrace but future versions
 * might include an IImageTrace covered by a vector trace.
 *
 * @author Matthew Gerring
 *
 */
public interface ICompositeTrace extends ITrace {

	/**
	 * Add a subimage to the stacked image trace. The name of the
	 * image must be unique inside the IStackedImageTrace
	 *
	 * @param index or -1 to simply add the image on to the end.
	 * @param image
	 */
	public void add(ITrace image, int index) throws IllegalArgumentException;

	/**
	 * Add a subimage to the stacked image trace.
	 * @param image
	 * @param axes
	 */
	public void removeImage(String name);

	/**
	 * @return the axes which enclose all data
	 */
	public List<IDataset> getAxes();

}

package org.eclipse.dawnsci.plotting.api.trace;

import java.util.List;

import org.eclipse.dawnsci.analysis.api.dataset.IDataset;

/**
 * A trace for adding together multiple other traces and plotting
 * them as if they were images.
 *
 * The initial version is for multiple IImageTrace but future versions
 * might include an IImageTrace covered by a vector trace.
 *
 * @author Matthew Gerring
 *
 */
public interface ICompositeTrace extends ITrace {

	/**
	 * Add a subimage to the stacked image trace. The name of the
	 * image must be unique inside the IStackedImageTrace
	 *
	 * @param index or -1 to simply add the image on to the end.
	 * @param image
	 */
	public void add(ITrace image, int index) throws IllegalArgumentException;

	/**
	 * Add a subimage to the stacked image trace.
	 * @param image
	 * @param axes
	 */
	public void removeImage(String name);

	/**
	 * @return the axes which enclose all data
	 */
	public List<IDataset> getAxes();

	/**
	 * Set the colormap for the non-rgb datasets in the composite
	 *
	 * @param name
	 */
	public void setPalette(String name);

}

Change palette in composite trace


package io.silverspoon.bulldog.devices.sensors;

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

/**
 * Dallas DS18B20 temperature sensor implementation.
 *
 * @author sbunciak
 *
 */
public class DS18B20TemperatureSensor {

	private File deviceFile = null;

	public DS18B20TemperatureSensor(File deviceFile) {
		this.deviceFile = deviceFile;
	}

	// TODO: implement using UART?
	public float readTemperature() throws IOException {

		byte[] encoded = Files.readAllBytes(new File(deviceFile, "w1_slave").toPath());

		String tmp = new String(encoded);
		int tmpIndex = tmp.indexOf("t=");

		if (tmpIndex < 0) {
			throw new IOException("Could not read temperature!");
		}

		return Integer.parseInt(tmp.substring(tmpIndex + 2).trim()) / 1000f;
	}
}

Add support for DS18B20 Temperature Sensor


package org.owasp.appsensor.configuration;

import static org.junit.Assert.assertTrue;

import org.junit.Test;
import org.owasp.appsensor.configuration.server.ServerConfiguration;
import org.owasp.appsensor.configuration.server.ServerConfigurationReader;
import org.owasp.appsensor.configuration.server.XmlServerConfigurationReader;

public class XmlServerConfigurationReaderTest {

	@Test
	public void testConfigLoad() throws Exception {
		ServerConfigurationReader reader = new XmlServerConfigurationReader();
		ServerConfiguration configuration = reader.read("/appsensor-server-config.xml", "/appsensor_server_config_2.0.xsd");

		assertTrue("org.owasp.appsensor.analysis.impl.ReferenceStatisticalEventAnalysisEngine".equals(configuration.getEventAnalysisEngineImplementation()));
	}
}

Add test for server config file.


/**
 * 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.
 *
 * Copyright 2012-2015 the original author or authors.
 */
package org.assertj.swing.core.matcher.bylabel;

import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.swing.test.builder.JTextFields.textField;

import org.assertj.swing.test.core.EDTSafeTestCase;
import org.junit.Test;

/**
 * Tests for {@link JLabeledTextComponentMatcher#matches(java.awt.Component)}.
 * We are looking for a text field with a label. The component to be matched
 * should have a parent.
 *
 * @author Iñaki Ibarrola
 */
public class JLabeledTextComponentMatcher_no_parent_Test extends EDTSafeTestCase {

    @Test
    public void should_Always_Return_False_When_JTextComponent_Has_No_Parent() {
        JLabeledTextComponentMatcher matcher = JLabeledTextComponentMatcher.withLabelText("hello");
        assertThat(matcher.matches(textField().createNew())).isFalse();
    }
}

Add a test to check that a component with no parent does not match.


package com.github.tomitakussaari.mysqlcluscon;

import org.junit.Test;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

import static org.junit.Assert.assertTrue;

public class MyslclusconDriverMysqlTest {

    @Test
    public void canConnectToRealMysql() throws SQLException {
        Connection connection = DriverManager.getConnection("jdbc:myscluscon:mysql:read_cluster://127.0.0.1:3306/myscluscon_test", "travis", "");
        assertTrue(connection.isValid(100));
    }
}

Add test verifying connect to real mysql works on travis


/*
 * See the NOTICE file distributed with this work for additional
 * information regarding copyright ownership.
 *
 * This 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 software 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 software; if not, write to the Free
 * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
 * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
 */
package org.xwiki.job.event.status;

import org.junit.jupiter.api.Test;

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

/**
 * Unit tests for {@link AbstractProgressEvent}.
 *
 * @version $Id$
 */
public class AbstractProgressEventTest
{
    private class TestableProgressEvent extends AbstractProgressEvent
    {
    }

    @Test
    public void matches()
    {
        TestableProgressEvent event = new TestableProgressEvent();
        assertTrue(event.matches(new TestableProgressEvent()));
        assertFalse(event.matches(new String("whatever")));
    }
}

Improve mutation score (descartes). Added test for matches() (existing tests were not matching when the body of matches() was replaced by "return true").


/**
 * Definition for ListNode.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int val) {
 *         this.val = val;
 *         this.next = null;
 *     }
 * }
 */
public class Solution {
    /**
     * @param node: the node in the list should be deleted
     * @return: nothing
     */
    public void deleteNode(ListNode node) {
        /*
         * Replace the val of current node with the val of next node
         * Connect the current node with the next next node of the current node
         */
        node.val = node.next.val;
        node.next = node.next.next;
    }
}

Delete Node in Singly Linked List for Lintcode


package net.ssehub.kernel_haven.test_utils;

import java.util.LinkedList;
import java.util.List;
import java.util.Properties;

import net.ssehub.kernel_haven.SetUpException;
import net.ssehub.kernel_haven.analysis.AnalysisComponent;
import net.ssehub.kernel_haven.config.Configuration;

/**
 * Contains a helper method to execute analysis components.
 *
 * @author Adam
 */
public class AnalysisComponentExecuter {

    /**
     * Don't allow any instances.
     */
    private AnalysisComponentExecuter() {
    }

    /**
     * Creates and executes the given {@link AnalysisComponent} class.
     *
     * @param componentClass The component class to create and execute.
     * @param config The {@link Configuration} for the component. null if no special settings are needed.
     * @param inputs The input values for the component. The first dimension represent the different
     *      {@link AnalysisComponent} inputs; the second dimension represent that values that each input component
     *      should create.
     *
     * @param <T> The output type of the analysis component.
     *
     * @return The list of results that the component created.
     */
    public static <T> List<T> executeComponent(Class<?> componentClass, Configuration config, Object[]... inputs) {

        // create an empty configuration is none is passed to us
        if (config == null) {
            try {
                config = new TestConfiguration(new Properties());
            } catch (SetUpException e) {
                throw new RuntimeException("Can't create test configuration", e);
            }
        }

        // create input components based on the inputs parameter
        AnalysisComponent<?>[] inputComponents = new AnalysisComponent[inputs.length];
        for (int i = 0; i < inputs.length; i++) {
            try {
                inputComponents[i] = new TestAnalysisComponentProvider<>(inputs[i]);
            } catch (SetUpException e) {
                throw new RuntimeException("Can't create test input component", e);
            }
        }

        // create an array with the parameter types, to get the right constructor
        Class<?>[] parameterTypes = new Class[1 + inputComponents.length];
        parameterTypes[0] = Configuration.class;
        for (int i = 0; i < inputComponents.length; i++) {
            parameterTypes[i + 1] = AnalysisComponent.class;
        }

        // create an array with the parameter values, to pass to the consturctor
        Object[] parameterValues = new Object[1 + inputComponents.length];
        parameterValues[0] = config;
        for (int i = 0; i < inputComponents.length; i++) {
            parameterValues[i + 1] = inputComponents[i];
        }

        List<T> result = new LinkedList<>();

        try {
            // instantiate the component
            @SuppressWarnings("unchecked")
            AnalysisComponent<T> component = (AnalysisComponent<T>)
                    componentClass.getConstructor(parameterTypes).newInstance(parameterValues);

            // execute the component
            T r;
            while ((r = component.getNextResult()) != null) {
                result.add(r);
            }

        } catch (ReflectiveOperationException | ClassCastException | SecurityException e) {
            throw new RuntimeException("Can't instantiate analysis component", e);
        }

        return result;
    }

}

Create helper method for testing analysis components


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

import java.util.EnumSet;

import javax.servlet.DispatcherType;
import javax.servlet.Filter;
import javax.servlet.FilterRegistration;
import javax.servlet.ServletContext;

import org.springframework.context.ApplicationContext;

/**
 * @author Eric F. Savage, code@efsavage.com.
 *
 */
public class FilterUtils {

	/**
	 * Convenience method for adding a filter to all requests.
	 *
	 * @see ServletContext#addFilter(String, Class)
	 * @param filterClass
	 *            The class of Filter to instantiate.
	 * @param servletContext
	 */
	public static void add(Class<? extends Filter> filterClass, ServletContext servletContext) {
		FilterRegistration.Dynamic mdcInsertingServletFilterReg = servletContext.addFilter(filterClass.getName(), filterClass);
		mdcInsertingServletFilterReg.addMappingForUrlPatterns(EnumSet.of(DispatcherType.REQUEST), true, "/*");
	}

	/**
	 * Convenience method for adding a filter that is available as a Spring
	 * bean/service to all requests.
	 *
	 * @see ServletContext#addFilter(String, Class)
	 * @param filterClass
	 *            The class of Filter to instantiate.
	 * @param appContext
	 *            The application context to find the bean in.
	 * @param servletContext
	 */
	public static void add(Class<? extends Filter> filterClass, ApplicationContext appContext, ServletContext servletContext) {
		Filter filter = appContext.getBean(filterClass);
		FilterRegistration.Dynamic mdcInsertingServletFilterReg = servletContext.addFilter(filterClass.getName(), filter);
		mdcInsertingServletFilterReg.addMappingForUrlPatterns(EnumSet.of(DispatcherType.REQUEST), true, "/*");
	}

}

Add helper methods for servlet filters


package org.fastnate.data;

import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;

import org.hibernate.SessionFactory;
import org.hibernate.SessionFactoryObserver;
import org.hibernate.boot.SchemaAutoTooling;
import org.hibernate.boot.spi.SessionFactoryOptions;
import org.hibernate.engine.jdbc.connections.spi.ConnectionProvider;
import org.hibernate.engine.spi.SessionFactoryImplementor;
import org.hibernate.tool.hbm2ddl.ImportScriptException;

/**
 * Imports data on startup of Hibernate, if {@link SessionFactoryOptions#getSchemaAutoTooling() schema auto tooling} is
 * set either to {@link SchemaAutoTooling#CREATE} or {@link SchemaAutoTooling#CREATE_DROP}.
 *
 * @author Tobias Liefke
 */
public class DatabaseStartupImport implements SessionFactoryObserver {

	private static final long serialVersionUID = 1L;

	@Override
	public void sessionFactoryClosed(final SessionFactory factory) {
		// Nothing to do
	}

	@Override
	public void sessionFactoryCreated(final SessionFactory factory) {
		// Only import, if Hibernate has just created an empty database
		final SchemaAutoTooling autoTooling = factory.getSessionFactoryOptions().getSchemaAutoTooling();
		if (autoTooling == SchemaAutoTooling.CREATE || autoTooling == SchemaAutoTooling.CREATE_DROP) {
			// Find a connection
			final SessionFactoryImplementor sessionFactoryImplementor = (SessionFactoryImplementor) factory;
			try (Connection connection = sessionFactoryImplementor.getServiceRegistry()
					.getService(ConnectionProvider.class).getConnection()) {
				// Import data
				new EntityImporter(new Properties()).importData(connection);
			} catch (final SQLException | IOException e) {
				throw new ImportScriptException("Could not import SQL data: " + e, e);
			}
		}
	}
}

Add an example for a connected startup importer


package io.syndesis.qe.pages.dashboard;

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

import org.openqa.selenium.By;

import com.codeborne.selenide.SelenideElement;

import io.syndesis.qe.pages.SyndesisPageObject;
import lombok.extern.slf4j.Slf4j;

/**
 * Created by sveres on 11/15/17.
 */
@Slf4j
public class DashboardPage extends SyndesisPageObject {

	private static final class Element {
		public static final By ROOT = By.cssSelector("syndesis-dashboard");
	}

	@Override
	public SelenideElement getRootElement() {
		return $(Element.ROOT);
	}

	@Override
	public boolean validate() {
		return $(Element.ROOT).is(visible);
	}

	SelenideElement getConnection(String connectionTitle) {
		log.info("searching for connection {}", connectionTitle);
		return this.getRootElement().$(String.format("h2.card-pf-title.text-center[title=\"%s\"]", connectionTitle));
	}

	void goToConnection(String connectionTitle) {
		log.info("searching for connection {}", connectionTitle);
		this.getConnection(connectionTitle).shouldBe(visible).click();
	}

	boolean isIntegrationPresent(String integrationName) {
		log.info("Checking if integration {} is present in the list", integrationName);
		SelenideElement integration = this.getRootElement().find(By.cssSelector(String.format("div[innertext='%s']", integrationName)));
		return integration.is(visible);
	}

}

Work on e2e refactoring to Java - dashboard


/*
 Copyright (C) 2003 EBI, GRL

 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 org.ensembl.healthcheck.testcase.generic;

import java.sql.Connection;

import org.ensembl.healthcheck.DatabaseRegistryEntry;
import org.ensembl.healthcheck.DatabaseType;
import org.ensembl.healthcheck.ReportManager;
import org.ensembl.healthcheck.testcase.SingleDatabaseTestCase;

/**
 * Check that certain seq_region_attribs are present.
 */
public class SeqRegionAttribsPresent extends SingleDatabaseTestCase {

	private String[] attribCodes = { "GeneNo_knwCod", "GeneNo_novCod" };

	/**
	 * Create a new SeqRegionAttribsPresent healthcheck.
	 */
	public SeqRegionAttribsPresent() {

		addToGroup("release");
		setDescription("Check that certain seq_region_attribs are present.");

	}

	/**
	 * This only really applies to core databases
	 */
	public void types() {

		removeAppliesToType(DatabaseType.OTHERFEATURES);
		removeAppliesToType(DatabaseType.ESTGENE);
		removeAppliesToType(DatabaseType.VEGA);
		removeAppliesToType(DatabaseType.CDNA);

	}

	/**
	 * Run the test.
	 *
	 * @param dbre
	 *          The database to check.
	 * @return true if the test passes.
	 */
	public boolean run(final DatabaseRegistryEntry dbre) {

		boolean result = true;

		Connection con = dbre.getConnection();

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

			String code = attribCodes[i];
			int count = getRowCount(con, "SELECT COUNT(*) FROM attrib_type at, seq_region_attrib sa WHERE sa.attrib_type_id=at.attrib_type_id AND at.code='" + code + "'");

			if (count == 0) {

				ReportManager.problem(this, con, "No seq_region_attribs of code " + code + " - there should be some. This may indicate that the seq_region_attribs.pl script needs to be run.");
				result = false;

			} else {

				ReportManager.correct(this, con, count + " seq_region_attrib entries for " + code);

			}
		}

		return result;

	} // run

	// -----------------------------------------------------------------

} // SeqRegionAttribsPresent


package seedu.taskitty.model;

import javafx.collections.FXCollections;
import seedu.taskitty.commons.core.UnmodifiableObservableList;
import seedu.taskitty.commons.exceptions.DataConversionException;
import seedu.taskitty.commons.exceptions.IllegalValueException;
import seedu.taskitty.model.task.Task;
import seedu.taskitty.model.task.TaskDate;
import seedu.taskitty.model.task.TaskTime;

import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;

import java.util.*;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertSame;
import static seedu.taskitty.testutil.TestUtil.assertThrows;

public class TaskTest {

    @Rule
    public ExpectedException thrown = ExpectedException.none();

    @Test
    public void invalidDateFormat_exceptionThrown() throws Exception {
        thrown.expect(IllegalValueException.class);
        TaskDate date = new TaskDate("25-12-2016");
    }

    @Test
    public void invalidDate_exceptionThrown() throws Exception {
        thrown.expect(IllegalValueException.class);
        TaskDate date = new TaskDate("29/2/2015");
    }

    @Test
    public void invalidTimeFormat_exceptionThrown() throws Exception {
        thrown.expect(IllegalValueException.class);
        TaskTime date = new TaskTime("3pm");
    }

    @Test
    public void invalidTime_exceptionThrown() throws Exception {
        thrown.expect(IllegalValueException.class);
        TaskDate date = new TaskDate("25:00");
    }
}

Add new test for Task


package com.google.sps.servlets;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;
import java.util.HashMap;
import com.github.mustachejava.Mustache;
import com.github.mustachejava.MustacheFactory;
import com.github.mustachejava.DefaultMustacheFactory;
import com.google.gson.Gson;
import com.google.sps.data.UrlRequest;

/** Servlet that shows projects.*/
@WebServlet("/project")
public class ProjectServlet extends HttpServlet {

  private static final String API_KEY = "API_KEY";  // Insert the API_KEY here for testing.
  private static final String API_PATH = "https://api.globalgiving.org/api/public/projectservice/projects/%s";

  @Override
  public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
    Map<String, String> queryParameters = new HashMap<>();
    queryParameters.put("api_key", API_KEY);
    String idString = request.getParameter("id");
    String path = String.format(API_PATH, idString);
    String jsonString = UrlRequest.urlQuery(path, queryParameters);

    Gson gson = new Gson();
    Map jsonMap = gson.fromJson(jsonString, Map.class);

    MustacheFactory mf = new DefaultMustacheFactory();
    Mustache mustache = mf.compile("project.html");
    response.setContentType("text/html;");
    mustache.execute(response.getWriter(), jsonMap).flush();
  }
}

Add servlet to serve html file with specific project information


package com.autonomy.abc.selenium.page;

import com.hp.autonomy.frontend.selenium.util.AppPage;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;

public class ErrorPage implements AppPage {
    private WebDriver driver;

    public ErrorPage(WebDriver driver) {
        this.driver = driver;
        waitForLoad();
    }

    public String getErrorCode() {
        return driver.findElement(By.tagName("h1")).getText();
    }

    public String getErrorTitle() {
        return driver.findElement(By.tagName("h3")).getText();
    }

    public String getErrorDescription() {
        return driver.findElement(By.cssSelector(".error-desc p")).getText();
    }

    public WebElement redirectButton() {
        return driver.findElement(By.tagName("a"));
    }

    @Override
    public void waitForLoad() {
        new WebDriverWait(driver, 20)
                .withMessage("loading error page")
                .until(ExpectedConditions.presenceOfElementLocated(By.tagName("a")));
    }
}

Add error page to represent 401, 500 pages etc


package eu.europa.esig.dss.client.http.proxy;

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

public class ProxyDaoImpl implements ProxyDao {

	protected Map<ProxyKey, ProxyPreference> proxyPreferences = new HashMap<ProxyKey, ProxyPreference>();

	public void setHttpsHost(String httpsHost) {
		update(ProxyKey.HTTPS_HOST, httpsHost);
	}

	public void setHttpsPort(String httpsPort) {
		update(ProxyKey.HTTPS_PORT, httpsPort);
	}

	public void setHttpsUser(String httpsUser) {
		update(ProxyKey.HTTPS_USER, httpsUser);
	}

	public void setHttpsPassword(String httpsPassword) {
		update(ProxyKey.HTTPS_PASSWORD, httpsPassword);
	}

	public void setHttpsExclude(String httpsExclude) {
		update(ProxyKey.HTTPS_EXCLUDE, httpsExclude);
	}

	public void setHttpsEnable(String httpsEnable) {
		update(ProxyKey.HTTPS_ENABLED, httpsEnable);
	}

	public void setHttpHost(String httpHost) {
		update(ProxyKey.HTTP_HOST, httpHost);
	}

	public void setHttpPort(String httpPort) {
		update(ProxyKey.HTTP_PORT, httpPort);
	}

	public void setHttpUser(String httpUser) {
		update(ProxyKey.HTTP_USER, httpUser);
	}

	public void setHttpPassword(String httpPassword) {
		update(ProxyKey.HTTP_PASSWORD, httpPassword);
	}

	public void setHttpExclude(String httpExclude) {
		update(ProxyKey.HTTP_EXCLUDE, httpExclude);
	}

	public void setHttpEnable(String httpEnable) {
		update(ProxyKey.HTTP_ENABLED, httpEnable);
	}

	private void update(ProxyKey key, String value) {
		ProxyPreference proxyPreference = proxyPreferences.get(key);
		if (proxyPreference == null) {
			proxyPreference = new ProxyPreference(key, value);
			proxyPreferences.put(key, proxyPreference);
		} else {
			proxyPreference.setValue(value);
		}
	}

	@Override
	public ProxyPreference get(ProxyKey id) {
		return proxyPreferences.get(id);
	}

	@Override
	public Collection<ProxyPreference> getAll() {
		return proxyPreferences.values();
	}

	@Override
	public void update(ProxyPreference entity) {
		proxyPreferences.put(entity.getProxyKey(), entity);
	}

}

Add an implementation of ProxyDao to inject properties with Spring


package de.morphbit.thymeleaf.helper;

import java.io.File;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

public class ResourcePathFinder {

	private final String directory;
	private final ClassLoader loader;

	public ResourcePathFinder(String directory) {
		this.directory = directory;
		this.loader = Thread.currentThread().getContextClassLoader();
	}

	public List<String> findResourceFiles(boolean recursively) {
		return getResourceFiles(directory, new ArrayList<>(), recursively);
	}

	private List<String> getResourceFiles(String dir, List<String> files,
	        boolean recursively) {
		URL url = loader.getResource(dir);
		String path = url.getPath();
		for (File file : new File(path).listFiles()) {
			if (recursively && file.isDirectory()) {
				return getResourceFiles(concatPath(dir, file.getName()), files,
				    recursively);
			} else {
				files.add(concatPath(dir, file.getName()));
			}
		}
		return files;
	}

	private String concatPath(String path1, String path2) {
		if (path1 == null) {
			return path2;
		}
		return path1.replaceAll("[/|\\\\]*$", "") + "/"
		        + path2.replaceAll("^[/|\\\\]*", "");
	}
}

Add helper class to find resource files


package com.tacitknowledge.performance.degrade;

import java.util.concurrent.TimeUnit;

import com.tacitknowledge.performance.Component;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelDuplexHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelPromise;
import io.netty.channel.socket.SocketChannel;

/**
 * TODO: refactor this. For higher traffic rates use buffers larger then 1 byte size and calculate appropriate delays
 * TODO: separate configs for up and down traffics
 *
 * @author Ivan Frolov (ifrolov@tacitknowledge.com) */
public class SlowDown implements Component
{
    private final long millisecondsPerByte;

    public SlowDown(final long millisecondsPerByte)
    {
        this.millisecondsPerByte = millisecondsPerByte;
    }

    @Override
    public void initChannel(final SocketChannel ch)
    {
        ch.config().setReceiveBufferSize(1);
        ch.pipeline().addLast(new SlowDownHandler(millisecondsPerByte));
    }

    public static class SlowDownHandler extends ChannelDuplexHandler
    {
        private final long millisecondsPerByte;

        public SlowDownHandler(final long millisecondsPerByte)
        {
            this.millisecondsPerByte = millisecondsPerByte;
        }

        @Override
        public void channelRead(final ChannelHandlerContext ctx, final Object msg) throws Exception
        {
            ctx.executor().schedule(new Runnable()
            {
                @Override
                public void run()
                {
                    ctx.fireChannelRead(msg);
                }
            }, millisecondsPerByte, TimeUnit.MILLISECONDS);
        }

        @Override
        public void write(final ChannelHandlerContext ctx, final Object msg, final ChannelPromise promise) throws Exception
        {
            final ByteBuf buf = (ByteBuf) msg;
            Runnable task = new Runnable()
            {
                private int ix = buf.readerIndex();
                @Override
                public void run()
                {
                    if(ix < buf.writerIndex()) {
                        ctx.writeAndFlush(Unpooled.wrappedBuffer(buf.copy(ix, 1)));
                        ix++;
                        ctx.executor().schedule(this, millisecondsPerByte, TimeUnit.MILLISECONDS);
                    } else {
                        promise.setSuccess();
                    }
                }
            };

            ctx.executor().submit(task);
        }
    }
}

Implement traffic slowdown degradation handler.


package router.client.api2;

import java.util.ArrayList;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;

public class RouteManager
{
  @Nonnull
  private OnChangeCallbackChain collectOnChangeCallbacks( @Nonnull String location )
  {
    return new OnChangeCallbackChain( new ArrayList<>() );
  }

  @Nonnull
  private OnEnterCallbackChain collectOnEnterCallbacks( @Nonnull String location )
  {
    return new OnEnterCallbackChain( new ArrayList<>() );
  }

  @Nonnull
  private OnLeaveCallbackChain collectOnLeaveCallbacks( @Nullable String location )
  {
    return new OnLeaveCallbackChain( new ArrayList<>() );
  }

  public void route( @Nullable final String previousLocation,
                     @Nonnull final String newLocation,
                     @Nullable final Runnable routingCompleteAction )
  {
    collectOnChangeCallbacks( newLocation ).
      onChange( previousLocation,
                () -> runIfNonNull( routingCompleteAction ),
                () -> collectOnLeaveCallbacks( previousLocation ).
                  onLeave( () ->
                             collectOnEnterCallbacks( newLocation ).onEnter( () -> runIfNonNull( routingCompleteAction ) ) ) );
  }

  private void runIfNonNull( @Nullable final Runnable routingCompleteAction )
  {
    if ( null != routingCompleteAction )
    {
      routingCompleteAction.run();
    }
  }
}

Add idea/spike about layout of callback chains


/*
 * Copyright (C) 2006 WTSI & EBI
 *
 * 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 org.ensembl.healthcheck.testcase.generic;

import java.sql.Connection;

import org.ensembl.healthcheck.DatabaseRegistryEntry;
import org.ensembl.healthcheck.DatabaseType;
import org.ensembl.healthcheck.ReportManager;
import org.ensembl.healthcheck.testcase.SingleDatabaseTestCase;

/**
 * Check that cigar lines in the identity_xref table are in the same format as
 * they are in the alignment tables, i.e. start with a number rather than a
 * letter.
 */

public class IdentityXrefCigarLines extends SingleDatabaseTestCase {

	/**
	 * Creates a new instance of Ditag.
	 */
	public IdentityXrefCigarLines() {

		addToGroup("post_genebuild");
		addToGroup("release");
		setDescription("Check that cigar lines in the identity_xref table are in the same format, as they are in the alignment tables, i.e. start with a number rather than a letter");

	}

	/**
	 * This test only applies to core databases.
	 */
	public void types() {

		removeAppliesToType(DatabaseType.OTHERFEATURES);
		removeAppliesToType(DatabaseType.ESTGENE);
		removeAppliesToType(DatabaseType.VEGA);
		removeAppliesToType(DatabaseType.CDNA);

	}

	/**
	 * Test various things about ditag features.
	 *
	 * @param dbre
	 *          The database to use.
	 * @return Result.
	 */
	public boolean run(DatabaseRegistryEntry dbre) {

		boolean result = true;

		Connection con = dbre.getConnection();

		int rows = getRowCount(con, "SELECT COUNT(*) FROM identity_xref WHERE cigar_line REGEXP '^[MDI]'");

		if (rows > 0) {

			ReportManager.problem(this, con, rows + " cigar lines in identity_xref appear to be in the wrong format (number first)");
			result = false;

		} else {

			ReportManager.correct(this, con, "All cigar lines in identity_xref are in the correct format");
		}

		return result;

	}

	// ----------------------------------------------------------------------

}

Check that cigar lines in the identity_xref table are in the same format, as they are in the alignment tables, i.e. start with a number rather than a letter.


import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.util.Iterator;
import java.util.LinkedList;

class ColumnNames
{
    public static void main(String[] args) throws Exception
    {
        File file = new File(args[0]);
        BufferedReader in = new BufferedReader(new FileReader(file));
        String line;

        while ((line = in.readLine()) != null) {
            int number = Integer.parseInt(line.trim());
            System.out.println(convertToExcelColumnName(number));
        }

        in.close();
    }

    private static final int OFFSET = (int) 'A';

    private static String convertToExcelColumnName(int number)
    {
        number--;
        LinkedList<Character> result = new LinkedList<>();

        while (number >= 0) {
            int quotient = number / 26;
            int remainder = number % 26;
            result.add((char) (OFFSET + remainder));
            number = quotient - 1;
        }

        StringBuilder sb = new StringBuilder();

        Iterator it = result.descendingIterator();
        while(it.hasNext()){
            sb.append(it.next());
        }

        return sb.toString();
    }
}

Add Java solution to the column names problem


// You should obtain the registration token from your backend
// pushToken is optional and you include it if you want us to handle push notifications
twilioAuth.setPushToken(pushToken);

Remove invalid comment in snippet


package org.twig.syntax;

import org.junit.Assert;
import org.junit.Test;
import org.twig.exception.SyntaxErrorException;

public class TokenStreamTests {
    @Test
    public void canNext() throws SyntaxErrorException {
        TokenStream tokenStream = new TokenStream("aFile");
        Token token1 = new Token(Token.Type.TEXT, "foo", 1);
        tokenStream.add(token1);
        Token token2 = new Token(Token.Type.VAR_START, null, 1);
        tokenStream.add(token2);

        Assert.assertSame("1st nexted token should be token1", token1, tokenStream.next());
        Assert.assertSame("2nd nexted token should be token2", token2, tokenStream.next());
    }

    @Test
    public void canLook() throws SyntaxErrorException {
        TokenStream tokenStream = new TokenStream("aFile");
        Token token1 = new Token(Token.Type.TEXT, "foo", 1);
        tokenStream.add(token1);

        Assert.assertSame("Look at token at index 0 should return 1st token", token1, tokenStream.look(0));
        Assert.assertSame("1st nexted token should be 1st token even after looking", token1, tokenStream.next());
    }
}

Add unit tests for TokenStream


package com.valerysamovich.java.trail.basic.statements.switchstatement;

public class SwitchDemo2 {

    public static void main(String[] args) {

        // variables
        int month = 2;
        int year = 2000;
        int numDays = 0;

        // switch statement
        switch (month) {
            case 1: case 3: case 5: case 7: case 8: case 10: case 12:
                numDays = 31;
                break;
            case 4: case 6: case 9: case 11:
                numDays = 30;
                break;
            case 2:
                if (((year % 4 == 0) && (year % 100 == 0)) || (year % 400 == 0)) {
                    numDays = 29;
                } else {
                    numDays = 28;
                }
                break;
            default:
                System.out.println("Invalid month.");
        }

        System.out.println("Number of days = " + numDays);
    }

}

Add Switch Example with multiple case labels


package org.csanchez.aws.glacier.actions;

import org.csanchez.aws.glacier.utils.MockTestHelper;
import org.jmock.Expectations;
import org.junit.Before;
import org.junit.Test;

import com.amazonaws.services.glacier.AmazonGlacierClient;
import com.amazonaws.services.glacier.model.ListVaultsRequest;
import com.amazonaws.services.glacier.model.ListVaultsResult;

public class VaultsTest extends MockTestHelper {

    private AmazonGlacierClient client;

    @Before
    public void setUp() {
        client = mock( AmazonGlacierClient.class );
    }

    @Test
    public void vaults_singleResultsList() {
        ListVaultsResult result = mock( ListVaultsResult.class );

        expectThat( vaultServiceCallWith( result ) );
        expectThat( hasMoreResults( result, false ) );

        new Vaults( client ).call();
    }

    @Test
    public void vaults_multipleResultsList() {
        ListVaultsResult firstResult = mock( ListVaultsResult.class, "Result with marker" );
        ListVaultsResult secondResult = mock( ListVaultsResult.class, "Result with no marker" );

        expectThat( vaultServiceCallWith( firstResult ) );
        expectThat( hasMoreResults( firstResult, true ) );
        expectThat( vaultServiceCallWith( secondResult ) );
        expectThat( hasMoreResults( secondResult, false ) );

        new Vaults( client ).call();
    }

    private Expectations vaultServiceCallWith( final ListVaultsResult result ) {
        return new Expectations() {
            {
                one( client ).listVaults( with( any( ListVaultsRequest.class ) ) );
                will( returnValue( result ) );
            }
        };
    }

    private Expectations hasMoreResults( final ListVaultsResult result, final boolean hasMoreResults ) {
        return new Expectations() {
            {
                allowing( result ).getVaultList();

                one( result ).getMarker();
                if ( hasMoreResults ) {
                    will( returnValue( "marker" ) );
                } else {
                    will( returnValue( null ) );
                }
            }
        };
    }
}

Add tests for Vaults callable to ensure that all vaults are acquired (multiple service calls are necessary if there are over 1000 vaults)


package info.u_team.u_team_core.data;

import java.io.IOException;

import org.apache.logging.log4j.*;

import com.google.common.base.Preconditions;

import net.minecraft.data.*;
import net.minecraft.util.ResourceLocation;
import net.minecraftforge.client.model.generators.*;

public abstract class CommonBlockStatesProvider extends BlockStateProvider {

	protected final Marker marker;

	public CommonBlockStatesProvider(DataGenerator generator, String modid, ExistingFileHelper existingFileHelper) {
		super(generator, modid, existingFileHelper);
		marker = MarkerManager.getMarker(getName());
	}

	@Override
	public void act(DirectoryCache cache) throws IOException {
		this.cache = cache;
		generatedModels.clear();
		registerModels0();
		generatedModels.values().forEach(model -> {
			try {
				final ResourceLocation location = model.getLocation();
				CommonProvider.write(cache, model.toJson(), generator.getOutputFolder().resolve("assets/" + location.getNamespace() + "/models/" + location.getPath() + ".json"));
			} catch (IOException ex) {
				CommonProvider.LOGGER.error(marker, "Could not write data.", ex);
			}
		});
		this.cache = null;
	}

	// We need to overide registerModels, but this method is marked final...
	private void registerModels0() {
		registeredBlocks.clear();
		registerStatesAndModels();

		registeredBlocks.forEach((block, generatedState) -> {
			try {
				final ResourceLocation location = Preconditions.checkNotNull(block.getRegistryName());
				CommonProvider.write(cache, generatedState.toJson(), generator.getOutputFolder().resolve("assets/" + location.getNamespace() + "/blockstates/" + location.getPath() + ".json"));
			} catch (IOException ex) {
				CommonProvider.LOGGER.error(marker, "Could not write data.", ex);
			}
		});
	}

	@Override
	public String getName() {
		return "Block-States | Block-Models";
	}
}

Add block state / block models provider


package builder;

import uk.ac.ebi.spot.goci.model.AssociationUploadRow;

/**
 * Created by emma on 24/03/2016.
 *
 * @author emma
 *         <p>
 *         Builder for BatchUploadRow
 */
public class AssociationUploadRowBuilder {

    AssociationUploadRow associationUploadRow = new AssociationUploadRow();

    public AssociationUploadRowBuilder setRowNumber(Integer rowNumber) {
        associationUploadRow.setRowNumber(rowNumber);
        return this;
    }

    public AssociationUploadRowBuilder setAuthorReportedGene(String genes) {
        associationUploadRow.setAuthorReportedGene(genes);
        return this;
    }

    public AssociationUploadRowBuilder setStrongestAllele(String alleles) {
        associationUploadRow.setStrongestAllele(alleles);
        return this;
    }

    public AssociationUploadRowBuilder setSnp(String snp) {
        associationUploadRow.setSnp(snp);
        return this;
    }

    public AssociationUploadRowBuilder setProxy(String proxy) {
        associationUploadRow.setProxy(proxy);
        return this;
    }

    public AssociationUploadRowBuilder setRiskFrequency(String riskFrequency) {
        associationUploadRow.setRiskFrequency(riskFrequency);
        return this;
    }

    public AssociationUploadRowBuilder setEffectType(String effectType) {
        associationUploadRow.setEffectType(effectType);
        return this;
    }

    public AssociationUploadRowBuilder setOrPerCopyNum(Float orPerCopyNum) {
        associationUploadRow.setOrPerCopyNum(orPerCopyNum);
        return this;
    }

    public AssociationUploadRowBuilder setOrPerCopyRecip(Float orPerCopyRecip) {
        associationUploadRow.setOrPerCopyRecip(orPerCopyRecip);
        return this;
    }

    public AssociationUploadRowBuilder setBetaNum(Float betaNum) {
        associationUploadRow.setBetaNum(betaNum);
        return this;
    }

    public AssociationUploadRowBuilder setBetaUnit(String betaUnit) {
        associationUploadRow.setBetaUnit(betaUnit);
        return this;
    }

    public AssociationUploadRowBuilder setBetaDirection(String betaDirection) {
        associationUploadRow.setBetaDirection(betaDirection);
        return this;
    }

    public AssociationUploadRowBuilder setRange(String range) {
        associationUploadRow.setRange(range);
        return this;
    }

    public AssociationUploadRowBuilder setOrPerCopyRecipRange(String orPerCopyRecipRange) {
        associationUploadRow.setOrPerCopyRecipRange(orPerCopyRecipRange);
        return this;
    }

    public AssociationUploadRowBuilder setStandardError(Float standardError) {
        associationUploadRow.setStandardError(standardError);
        return this;
    }

    public AssociationUploadRowBuilder setDescription(String description) {
        associationUploadRow.setDescription(description);
        return this;
    }

    public AssociationUploadRowBuilder setSnpType(String snpType) {
        associationUploadRow.setSnpType(snpType);
        return this;
    }

    public AssociationUploadRow build() {
        return associationUploadRow;
    }
}

Package to store builder classes used in testing


package org.gluu.oxauth.controller;

import javax.enterprise.context.ApplicationScoped;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;

/**
 * Health check controller
 *
 * @author Yuriy Movchan
 * @version Jul 24, 2020
 */
@ApplicationScoped
@Path("/")
public class HealthCheckController {

    @GET
    @POST
    @Path("/health-check")
    @Produces(MediaType.APPLICATION_JSON)
	public String healthCheckController() {
        return "{\"status\":\"running\"}";
	}

}

Add health-check controller to oxauth-server


package es.sandbox;

/**
 * It will force to create javadoc jar, because
 * it's mandatory to publish in maven central.
 * Created by jeslopalo on 17/11/16.
 */
public final class NoSourceCode {

    private NoSourceCode() {
        throw new UnsupportedOperationException();
    }
}

Add a useless class to force to generate javadoc jar


package com.uwetrottmann.shopr.algorithm.model;

public abstract class GenericAttribute<T> {

    private T currentValue;

    double[] mValueWeights;

    public double[] getValueWeights() {
        return mValueWeights;
    }

    @Override
    public String toString() {
        StringBuilder builder = new StringBuilder();
        T[] values = getValueSymbols();

        builder.append("[");
        for (int i = 0; i < mValueWeights.length; i++) {
            if (mValueWeights[i] != 0) {
                builder.append(values[i]).append(":").append(mValueWeights[i]).append(" ");
            }
        }
        builder.append("]");

        return builder.toString();
    }

    public abstract T[] getValueSymbols();

    public T currentValue() {
        return currentValue;
    }

    public GenericAttribute<T> currentValue(T currentValue) {
        this.currentValue = currentValue;
        return this;
    }

}

package com.uwetrottmann.shopr.algorithm.model;

public abstract class GenericAttribute<T> {

    private T currentValue;

    double[] mValueWeights;

    public double[] getValueWeights() {
        return mValueWeights;
    }

    @Override
    public String toString() {
        StringBuilder builder = new StringBuilder();
        T[] values = getValueSymbols();

        builder.append("[");
        for (int i = 0; i < mValueWeights.length; i++) {
            if (mValueWeights[i] == 1) {
                return "[" + values[i] + ":" + mValueWeights[i] + "]";
            }
            builder.append(values[i]).append(":").append(mValueWeights[i]).append(" ");
        }
        builder.append("]");

        return builder.toString();
    }

    public abstract T[] getValueSymbols();

    public T currentValue() {
        return currentValue;
    }

    public GenericAttribute<T> currentValue(T currentValue) {
        this.currentValue = currentValue;
        return this;
    }

}

Print zero weights if there is no 1.0 weight.


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

package jacobi.core.impl;

import jacobi.api.Matrix;

import java.util.function.Function;

/**
 * @author Y.K. Chan
 */
public class UnsafeMatrix implements Matrix {

    public UnsafeMatrix(double[][] rows) {
        this(rows, cls -> {
            throw new UnsupportedOperationException("");
        });
    }

    public UnsafeMatrix(double[][] rows, Function<Class, ?> facadeFactory) {
        this.numCols = rows == null ? 0 : rows[0].length;
        this.rows = rows;
        this.facadeFactory = facadeFactory;
    }

    @Override
    public int getRowCount() {
        return this.rows.length;
    }

    @Override
    public int getColCount() {
        return this.numCols;
    }

    @Override
    public double[] getRow(int index) {
        return this.rows[index];
    }

    @Override
    public Matrix setRow(int index, double[] values) {
        double[] row = this.rows[index];
        if(row != values) {
            System.arraycopy(values, 0, row, 0, row.length);
        }
        return this;
    }

    @Override
    public Matrix swapRow(int i, int j) {
        if(i != j){
            double[] tmp = this.rows[i];
            this.rows[i] = this.rows[j];
            this.rows[j] = tmp;
        }
        return this;
    }

    @Override
    public <T> T ext(Class<T> clazz) {
        return (T) this.facadeFactory.apply(clazz);
    }

    @Override
    public Matrix copy() {
        return new UnsafeMatrix(this.toArray(), this.facadeFactory);
    }

    public double[][] getRows() {
        return rows;
    }

    private int numCols;
    private double[][] rows;
    private Function<Class, ?> facadeFactory;
}

Update DefaultMatrix to not return inner array instance


package com.github.rschmitt.dynamicobject;

import org.junit.Test;

import java.math.BigDecimal;

import static com.github.rschmitt.dynamicobject.DynamicObject.deserialize;
import static com.github.rschmitt.dynamicobject.DynamicObject.newInstance;
import static com.github.rschmitt.dynamicobject.DynamicObject.serialize;
import static org.junit.Assert.assertEquals;

public class NumberTest {
    @Test
    public void BigDecimal() {
        String edn = "{:bigDecimal 3.14159M}";
        ArbitraryPrecision arbitraryPrecision = deserialize(edn, ArbitraryPrecision.class);
        assertEquals(edn, serialize(arbitraryPrecision));
        assertEquals(newInstance(ArbitraryPrecision.class).bigDecimal(new BigDecimal("3.14159")), arbitraryPrecision);
    }
}

interface ArbitraryPrecision extends DynamicObject<ArbitraryPrecision> {
    BigDecimal bigDecimal();

    ArbitraryPrecision bigDecimal(BigDecimal bigDecimal);
}

Add a test for basic BigDecimal support


package eu.nerro.wolappla.util;

import android.util.Log;

import eu.nerro.wolappla.BuildConfig;

/**
 * Helper methods that make logging more consistent throughout the app.
 */
public class LogUtils {
  private static final String LOG_PREFIX = "wolappla_";
  private static final int LOG_PREFIX_LENGTH = LOG_PREFIX.length();
  private static final int MAX_LOG_TAG_LENGTH = 25;

  private LogUtils() {
  }

  public static String makeLogTag(String name) {
    if (name.length() > MAX_LOG_TAG_LENGTH - LOG_PREFIX_LENGTH) {
      return LOG_PREFIX + name.substring(0, MAX_LOG_TAG_LENGTH - LOG_PREFIX_LENGTH - 1);
    }

    return LOG_PREFIX + name;
  }

  public static String makeLogTag(Class clazz) {
    return makeLogTag(clazz.getSimpleName());
  }

  public static void LOGD(final String tag, String message) {
    if (BuildConfig.DEBUG || Log.isLoggable(tag, Log.DEBUG)) {
      Log.d(tag, message);
    }
  }

  public static void LOGD(final String tag, String message, Throwable cause) {
    if (BuildConfig.DEBUG || Log.isLoggable(tag, Log.DEBUG)) {
      Log.d(tag, message, cause);
    }
  }
}

Add log helper to make logging more consistent


/*
 * oxCore is available under the MIT License (2008). See http://opensource.org/licenses/MIT for full text.
 *
 * Copyright (c) 2014, Gluu
 */

package org.gluu.site.ldap.persistence.exception;

/**
 * Configuration exception
 */
public class InvalidConfigurationException extends RuntimeException {

	private static final long serialVersionUID = 6541769232087073304L;

	public InvalidConfigurationException(Throwable root) {
		super(root);
	}

	public InvalidConfigurationException(String string, Throwable root) {
		super(string, root);
	}

	public InvalidConfigurationException(String s) {
		super(s);
	}

}

Add exception to show LDAP configuration error


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

/**
 * Given a binary tree, can you write a method to return a list of nodes by level?
 * And without any additional data structure?
 *
 * @author Pedro Vicente Gómez Sánchez.
 */
public class PrintBinaryTreeByLevel {
}

Add statement for problem 13


/****************************************************************************
 * Copyright (C) 2015 ecsec GmbH.
 * All rights reserved.
 * Contact: ecsec GmbH (info@ecsec.de)
 *
 * This file is part of the Open eCard App.
 *
 * GNU General Public License Usage
 * This file may be used under the terms of the GNU General Public
 * License version 3.0 as published by the Free Software Foundation
 * and appearing in the file LICENSE.GPL included in the packaging of
 * this file. Please review the following information to ensure the
 * GNU General Public License version 3.0 requirements will be met:
 * http://www.gnu.org/copyleft/gpl.html.
 *
 * Other Usage
 * Alternatively, this file may be used in accordance with the terms
 * and conditions contained in a signed written agreement between
 * you and ecsec GmbH.
 *
 ***************************************************************************/

package org.openecard.control.binding.http.interceptor;

import java.io.IOException;
import org.openecard.apache.http.HttpException;
import org.openecard.apache.http.HttpResponse;
import org.openecard.apache.http.HttpResponseInterceptor;
import org.openecard.apache.http.protocol.HttpContext;
import org.openecard.common.Version;

/**
 * HttpResponseInterceptor implementation which adds the {@code Server} header to all responses sent by the HTTP Binding.
 *
 * @author Hans-Martin Haase
 */
public class ServerHeaderResponseInterceptor implements HttpResponseInterceptor {

    @Override
    public void process(HttpResponse hr, HttpContext hc) throws HttpException, IOException {
	hr.addHeader("Server", buildServerHeaderValue());
    }

    /**
     * Creates the value of the {@code Server} header according to BSI-TR-03124-1 v1.2 section 2.2.2.1.
     *
     * @return A string containing the {@code Server} header value.
     */
    public String buildServerHeaderValue() {
	StringBuilder builder = new StringBuilder();
	builder.append(Version.getName());
	builder.append("/");
	builder.append(Version.getVersion());
	builder.append(" (");
	for (String version : Version.getSpecVersions()) {
	    builder.append(Version.getSpecName());
	    builder.append("/");
	    builder.append(version);
	    builder.append(" ");
	}
	// remove last white space
	builder.deleteCharAt(builder.lastIndexOf(" "));
	builder.append(")");
	return builder.toString();
    }

}

Add HttpResponseInterceptor implementation which add the Server header to the response.


/*
 */
package org.datadryad.rest.storage.resolvers;

import org.datadryad.rest.storage.json.ManuscriptJSONStorageImpl;
import com.sun.jersey.spi.inject.SingletonTypeInjectableProvider;
import java.io.File;
import javax.ws.rs.core.Context;
import javax.ws.rs.ext.Provider;
import org.datadryad.rest.storage.AbstractManuscriptStorage;

/**
 *
 * @author Dan Leehr <dan.leehr@nescent.org>
 */
@Provider
public class ManuscriptStorageResolver extends SingletonTypeInjectableProvider<Context, AbstractManuscriptStorage> {
    private static final String PATH = "/tmp/dryad_rest_manuscripts";
    public ManuscriptStorageResolver() {
        super(AbstractManuscriptStorage.class, new ManuscriptJSONStorageImpl(new File(PATH)));
        File directory = new File(PATH);
        if(!directory.exists()) {
            directory.mkdir();
        }
    }
}

/*
 */
package org.datadryad.rest.storage.resolvers;

import org.datadryad.rest.storage.json.ManuscriptJSONStorageImpl;
import com.sun.jersey.spi.inject.SingletonTypeInjectableProvider;
import java.io.File;
import javax.ws.rs.core.Context;
import javax.ws.rs.ext.Provider;
import org.datadryad.rest.storage.AbstractManuscriptStorage;

/**
 *
 * @author Dan Leehr <dan.leehr@nescent.org>
 */
@Provider
public class ManuscriptStorageResolver extends SingletonTypeInjectableProvider<Context, AbstractManuscriptStorage> {
    private static final String PATH = "/tmp/dryad_rest";
    public ManuscriptStorageResolver() {
        super(AbstractManuscriptStorage.class, new ManuscriptJSONStorageImpl(new File(PATH)));
        File directory = new File(PATH);
        if(!directory.exists()) {
            directory.mkdir();
        }
    }
}

Change Manuscript JSON storage to same basedir


package net.restlesscoder.sandbox.interview;

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

public class MedianFilter {

	private static void medianFilter(double[][] in, double[][] out,
		final int radius)
	{
		final int h = in.length, w = in[0].length;
		for (int y = 0; y < h; y++) {
			for (int x = 0; x < w; x++) {
				out[y][x] = median(in, y, x, radius);
			}
		}
	}

	private static double median(double[][] in, int py, int px, int radius) {
		final int h = in.length, w = in[0].length;
		final List<Double> pts = new ArrayList<>();
		for (int y = py - radius; y <= py + radius; y++) {
			for (int x = px - radius; x <= px + radius; x++) {
				if (y >= 0 && y < h && x >= 0 && x < w) {
					pts.add(in[y][x]);
				}
			}
		}
		Collections.sort(pts);
		return pts.get(pts.size() / 2);
	}

	public static void show(final String title, final double[][] matrix,
		final int radius)
	{
		final int w = matrix[0].length, h = matrix.length;
		final double[][] scaled = new double[h][w];
		medianFilter(matrix, scaled, radius);
		Images.display(title, Images.makeBufferedImage(scaled));
	}

	public static void main(final String... args) {
		final int w = 300, h = 200;
		final double[][] matrix = Images.noise(w, h);

		show("Radius 1", matrix, 1);
		show("Radius 3", matrix, 3);
		show("Radius 7", matrix, 7);
	}
}

Add simple solution for doing a median filter


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

package com.facebook.litho.viewcompat;

import android.view.View;

/**
 * Empty implementation of {@link com.facebook.litho.viewcompat.ViewBinder}. This can be useful if
 * we need to override only one method.
 */
public class SimpleViewBinder<V extends View> implements ViewBinder<V> {

  @Override
  public void prepare() {}

  @Override
  public void bind(V view) {}

  @Override
  public void unbind(V view) {}
}

Add empty implementation of ViewBinder


/*
 * Copyright 2020 The jspecify 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.
 */

import org.jspecify.annotations.DefaultNonNull;
import org.jspecify.annotations.Nullable;
import org.jspecify.annotations.NullnessUnspecified;

@DefaultNonNull
class MultiplePathsToTypeVariable {
  interface TBounded<T, U extends T> {
    U get();
  }

  interface TUnspecBounded<T, U extends @NullnessUnspecified T> {
    U get();
  }

  interface TUnionNullBounded<T, U extends @Nullable T> {
    U get();
  }

  <T> Object x0(TBounded<T, ? extends T> t) {
    return t.get();
  }

  <T> Object x1(TBounded<T, ? extends @NullnessUnspecified T> t) {
    return t.get();
  }

  <T> Object x2(TBounded<T, ? extends @Nullable T> t) {
    return t.get();
  }

  <T> Object x3(TUnspecBounded<T, ? extends T> t) {
    return t.get();
  }

  <T> Object x4(TUnspecBounded<T, ? extends @NullnessUnspecified T> t) {
    // jspecify_nullness_not_enough_information
    return t.get();
  }

  <T> Object x5(TUnspecBounded<T, ? extends @Nullable T> t) {
    // jspecify_nullness_not_enough_information
    return t.get();
  }

  <T> Object x6(TUnionNullBounded<T, ? extends T> t) {
    return t.get();
  }

  <T> Object x7(TUnionNullBounded<T, ? extends @NullnessUnspecified T> t) {
    // jspecify_nullness_not_enough_information
    return t.get();
  }

  <T> Object x8(TUnionNullBounded<T, ? extends @Nullable T> t) {
    // jspecify_nullness_mismatch
    return t.get();
  }
}

Add a sample in which there are multiple "paths" from one type variable to another.


package org.mitre.synthea.helpers;

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

import java.io.File;
import java.util.Map;

import org.junit.Test;
import org.mitre.synthea.helpers.Attributes.Inventory;

public class AttributesTest {
  @Test
  public void testAttributes() throws Exception {
    Map<String,Inventory> inventory = Attributes.getAttributeInventory();
    assertNotNull(inventory);
    assertFalse(inventory.isEmpty());
    assertFalse(inventory.containsKey(""));
  }

  @Test
  public void testGraphs() throws Exception {
    Map<String,Inventory> inventory = Attributes.getAttributeInventory();
    String filename = "TestAttributesGraph";
    Attributes.graph(inventory, filename, true);
    File file = new File("./output/" + filename + ".png");
    assertTrue(file.exists());
    assertTrue(file.isFile());
    file.deleteOnExit();
  }
}

Add Attributes helper unit test.


package com.kryptnostic.kodex.v1.constants;

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

public class NamesTest {

    /**
     *  Changing this suffix could break existing users
     *  so this is here to make sure that something breaks when it changes
     */
    @Test
    public void testRegistrarSuffixHasntChanged() {
        Assert.assertTrue( Names.REGISTRAR_USER_SUFFIX == "_registrar" );
    }
}

Add a test to ensure that tests fail when the registrar name suffix changes


package org.verapdf.model.impl.pb.pd;

import org.apache.pdfbox.pdmodel.interactive.action.PDActionNamed;
import org.apache.pdfbox.pdmodel.interactive.documentnavigation.outline.PDOutlineItem;
import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
import org.verapdf.model.pdlayer.PDAction;
import org.verapdf.model.pdlayer.PDNamedAction;

import java.io.IOException;
import java.net.URISyntaxException;

/**
 * @author Evgeniy Muravitskiy
 */
public class PBoxPDNamedActionTest extends PBoxPDActionTest {

	public static final String FILE_RELATIVE_PATH = "pd/InteractiveObjects.pdf";

	@BeforeClass
	public static void setUp() throws URISyntaxException, IOException {
		expectedType = PBoxPDNamedAction.NAMED_ACTION_TYPE;
		expectedID = null;

		setUp(FILE_RELATIVE_PATH);
		PDOutlineItem node = document.getDocumentCatalog().getDocumentOutline().getFirstChild().getFirstChild();
		actual = new PBoxPDNamedAction((PDActionNamed) node.getAction());
	}

	// TODO : try to simplify
	@Override
	@Test
	public void testSMethod() {
		Assert.assertEquals("Named", ((PDAction) actual).getS());
	}

	@Test
	public void testNMethod() {
		Assert.assertEquals("NextPage", ((PDNamedAction) actual).getN());
	}

	@AfterClass
	public static void tearDown() throws IOException {
		expectedType = null;
		expectedID = null;
		actual = null;

		document.close();
	}
}

Add test for named actions


package org.helioviewer.gl3d.plugin.pfss.data;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;

import nom.tam.fits.BasicHDU;
import nom.tam.fits.BinaryTableHDU;
import nom.tam.fits.Fits;
import nom.tam.fits.FitsException;
import nom.tam.fits.Header;

public class TestOpenFits {
    public static void main(String[] args) {
        FileInputStream is;
        try {
            is = new FileInputStream(new File("/Users/freekv/swhv/build/data/pfss/testfile.fits"));

            Fits fits = new Fits(is, true);
            BasicHDU hdus[] = fits.read();
            BinaryTableHDU bhdu = (BinaryTableHDU) hdus[1];

            short[] fieldlinex = ((short[]) bhdu.getColumn("FIELDLINEx"));
            for (int i = 0; i < fieldlinex.length; i++) {
                System.out.println(fieldlinex[i]);
            }

            Header header = bhdu.getHeader();
            String date = header.findKey("DATE-OBS");
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
            dateFormat.setTimeZone(TimeZone.getTimeZone("GMT"));
            Date ddate = null;
            //ddate.UTC(year, month, date, hrs, min, sec)
            try {
                ddate = dateFormat.parse(date.substring(11, 30));
            } catch (ParseException e) {
                e.printStackTrace();
            }
            int year = Integer.parseInt(date.substring(11, 15));
            int month = Integer.parseInt(date.substring(16, 18));
            int day = Integer.parseInt(date.substring(19, 21));
            int hours = Integer.parseInt(date.substring(22, 24));
            int minutes = Integer.parseInt(date.substring(25, 27));
            int seconds = Integer.parseInt(date.substring(28, 30));
            System.out.println(ddate);
            System.out.println(year + " " + month + " " + day + "T" + hours + " " + minutes + " " + seconds);

        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (FitsException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

Test class for opening new fits file type


package leetcode.first_missing_positive;

public class Solution {
    public int firstMissingPositive(int[] A) {
        if(A == null || A.length == 0) return 1;
        int length = A.length;
        for(int i = 0; i < length; i++){
        	if(A[i] < 0) A[i] = 0;
        }
        for(int i = 0; i < length; i++){
        	int target = Math.abs(A[i]);
        	if(target > 0 && target <= length){
        		if(A[target - 1] == 0){
        			A[target - 1] = -target;
        		}else{
        			A[target - 1] = -Math.abs(A[target - 1]);
        		}
        	}
        }
        for(int i = 0; i < length; i++){
        	if(A[i] >= 0) return i + 1;
        }
        return length + 1;
    }

    public static void main(String[] args){
    	int[] input = new int[]{1};
    	System.err.println(new Solution().firstMissingPositive(input));
    }
}

Add java solution for 41. First Missing Positive


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

import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertNotNull;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;

import org.jsmpp.DefaultPDUReader;
import org.jsmpp.DefaultPDUSender;
import org.jsmpp.PDUSender;
import org.jsmpp.SMPPConstant;
import org.jsmpp.bean.Command;
import org.jsmpp.bean.GenericNack;
import org.jsmpp.util.DefaultDecomposer;
import org.jsmpp.util.PDUDecomposer;
import org.testng.annotations.Test;

/**
 * Simulating sending and receive data from client to server (vice versa) by
 * simple compose and decomposing the PDU.
 *
 * @author uudashr
 *
 */
public class ComposeDecompose {
    private PDUSender pduSender = new DefaultPDUSender();
    private DefaultPDUReader pduReader = new DefaultPDUReader();
    private PDUDecomposer decomposer = new DefaultDecomposer();

    /**
     * Test the composed PDU can decomposed properly.
     *
     * @throws Exception if an unexpected error found.
     */
    @Test(groups="checkintest")
    public void sendGenericNack() throws Exception {
        ByteArrayOutputStream out = new ByteArrayOutputStream();

        pduSender.sendGenericNack(out, SMPPConstant.STAT_ESME_RINVBNDSTS, 10);

        DataInputStream in = new DataInputStream(new ByteArrayInputStream(out.toByteArray()));
        Command header = pduReader.readPDUHeader(in);
        assertEquals(header.getCommandId(), SMPPConstant.CID_GENERIC_NACK, "Unexpected command_id");

        byte[] pdu = pduReader.readPDU(in, header);
        GenericNack nack = decomposer.genericNack(pdu);
        assertNotNull(nack);
    }

}

Add test case for composing and decomposing trough pduSender


package net.contargo.types.container;

/**
 * Describes the loading state of a {@link net.contargo.domain.Container}.
 *
 * @author  Aljona Murygina - murygina@synyx.de
 * @since  0.2.0
 */
public enum LoadingState {

    FULL,
    EMPTY
}

Add container loading state type


package ijx.plugin;

import imagej2.plugin.PluginEntry;
import imagej2.plugin.PluginFinder;

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

import org.openide.util.Lookup;

public class PluginDiscovery {

	/**
	 * Tests the plugin discovery mechanism,
	 * printing a list of all discovered plugins.
	 */
	public static void main(String[] args) {
		System.out.println("Scanning for plugin finders...");
		Collection<? extends PluginFinder> finders =
			Lookup.getDefault().lookupAll(PluginFinder.class);
		List<PluginEntry> plugins = new ArrayList<PluginEntry>();
		for (PluginFinder finder : finders) {
			System.out.println("Querying " + finder + "...");
			finder.findPlugins(plugins);
		}
		System.out.println("Discovered plugins:");
		for (PluginEntry plugin : plugins) {
			System.out.println("\t" + plugin);
		}
	}

}

Add test class for plugin discovery logic.


package com.lucene;

import java.io.File;
import java.io.FileFilter;

public class TextFileFilter implements FileFilter {

	@Override
	public boolean accept(File pathname) {
		return pathname.getName().toLowerCase().endsWith(".xls");
	}
}

Handle only .xls Files in Data Path Directory


package no.deichman.services.marc;

import java.io.ByteArrayOutputStream;

import org.marc4j.MarcWriter;
import org.marc4j.MarcXmlWriter;
import org.marc4j.marc.Leader;
import org.marc4j.marc.Record;

import info.freelibrary.marc4j.impl.LeaderImpl;
import info.freelibrary.marc4j.impl.RecordImpl;

/**
 * Responsibility: Make a MARCXML record.
 */
public final class MarcXmlProvider {

    private Record record;

    public MarcXmlProvider() {}

    private Leader createLeader() {
        Leader leader = new LeaderImpl();
        leader.unmarshal("                        ");
        return leader;
    }

    public void createRecord() {
        this.record = new RecordImpl();
        this.record.setLeader(createLeader());
    }

    public String getMarcXml() {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        MarcWriter writer = new MarcXmlWriter(baos);
        writer.write(this.getRecord());
        writer.close();
        return baos.toString();
    }

    public Record getRecord() {
        return this.record;
    }
}

package no.deichman.services.marc;

import java.io.ByteArrayOutputStream;

import org.marc4j.MarcWriter;
import org.marc4j.MarcXmlWriter;
import org.marc4j.marc.Leader;
import org.marc4j.marc.Record;

import info.freelibrary.marc4j.impl.LeaderImpl;
import info.freelibrary.marc4j.impl.RecordImpl;

/**
 * Responsibility: Make a MARCXML record.
 */
public final class MarcXmlProvider {

    private static final String TWENTY_FOUR_SPACES = "                        ";
    private Record record;

    public MarcXmlProvider() {}

    private Leader createLeader() {
        Leader leader = new LeaderImpl();
        leader.unmarshal(TWENTY_FOUR_SPACES);
        return leader;
    }

    public void createRecord() {
        this.record = new RecordImpl();
        this.record.setLeader(createLeader());
    }

    public String getMarcXml() {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        MarcWriter writer = new MarcXmlWriter(baos);
        writer.write(this.getRecord());
        writer.close();
        return baos.toString();
    }

    public Record getRecord() {
        return this.record;
    }
}

Refactor magic spaces to constant


package com.polidea.rxandroidble.sample;

import android.app.Application;
import android.content.Context;

import com.polidea.rxandroidble.RxBleClient;
import com.polidea.rxandroidble.internal.RxBleLog;

public class SampleApplication extends Application {

    private RxBleClient rxBleClient;

    /**
     * In practise you will use some kind of dependency injection pattern.
     */
    public static RxBleClient getRxBleClient(Context context) {
        SampleApplication application = (SampleApplication) context.getApplicationContext();
        return application.rxBleClient;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        rxBleClient = RxBleClient.getInstance(this);
        RxBleClient.setLogLevel(RxBleLog.DEBUG);
    }
}

package com.polidea.rxandroidble.sample;

import android.app.Application;
import android.content.Context;

import com.polidea.rxandroidble.RxBleClient;
import com.polidea.rxandroidble.internal.RxBleLog;

public class SampleApplication extends Application {

    private RxBleClient rxBleClient;

    /**
     * In practise you will use some kind of dependency injection pattern.
     */
    public static RxBleClient getRxBleClient(Context context) {
        SampleApplication application = (SampleApplication) context.getApplicationContext();
        return application.rxBleClient;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        rxBleClient = RxBleClient.create(this);
        RxBleClient.setLogLevel(RxBleLog.DEBUG);
    }
}

Use create instead of getInstance


package net.rdrei.android.wakimail.ui;

import net.rdrei.android.wakimail.R;
import roboguice.activity.RoboFragmentActivity;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.FragmentTransaction;

import com.actionbarsherlock.app.ActionBar;

public class MailDetailActivity extends RoboFragmentActivity {
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		Uri uri = this.getIntent().getData();

		ActionBar actionBar = this.getSupportActionBar();
		actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_HOME
				| ActionBar.DISPLAY_HOME_AS_UP | ActionBar.DISPLAY_SHOW_TITLE);

		setContentView(R.layout.activity_singlepane_empty);

		// First-time init; create fragment to embed in activity.
		FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
		MailDetailFragment newFragment = MailDetailFragment.newInstance(uri);
		ft.replace(R.id.root_container, newFragment);
		ft.commit();

	}
}

package net.rdrei.android.wakimail.ui;

import net.rdrei.android.wakimail.R;
import roboguice.activity.RoboFragmentActivity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.FragmentTransaction;

import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.view.MenuItem;

public class MailDetailActivity extends RoboFragmentActivity {
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		final Uri uri = this.getIntent().getData();

		final ActionBar actionBar = this.getSupportActionBar();
		actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_HOME
				| ActionBar.DISPLAY_HOME_AS_UP | ActionBar.DISPLAY_SHOW_TITLE);

		setContentView(R.layout.activity_singlepane_empty);

		// First-time init; create fragment to embed in activity.
		final FragmentTransaction ft = getSupportFragmentManager()
				.beginTransaction();
		final MailDetailFragment newFragment = MailDetailFragment
				.newInstance(uri);
		ft.replace(R.id.root_container, newFragment);
		ft.commit();
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		if (item.getItemId() == android.R.id.home) {
			// The app icon was clicked, move up to list.
			final Intent intent = new Intent(this, MailListActivity.class);
			intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
			startActivity(intent);
			return true;
		}

		return super.onOptionsItemSelected(item);
	}
}

Use action bar icon to move up from Mail details