package com.persado.oss.quality.stevia.selenium.core;

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

import org.openqa.selenium.Point;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.internal.Locatable;
import org.openqa.selenium.support.ui.ExpectedCondition;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Created by manoskousteris on 12/8/16.
 */
public class CustomExpectedCondition {

    /**
     * The Constant LOG.
     */
    private static final Logger conditionsLogger = LoggerFactory.getLogger(CustomExpectedCondition.class);

    public static ExpectedCondition<Boolean> elementHasStoppedMoving(final WebElement element) {
        return new ExpectedCondition<Boolean>() {
            @Override
            public Boolean apply(WebDriver driver) {
                Point initialLocation = ((Locatable) element).getCoordinates().inViewPort();
                try {
                    Thread.sleep(50);
                }catch (InterruptedException e){
                    conditionsLogger.error(e.getMessage());
                }
                Point finalLocation = ((Locatable) element).getCoordinates().inViewPort();
                return initialLocation.equals(finalLocation);
            }
        };
    }
}

Create custom expected condition class. Add new expected condition for element has stopped moving


package io.particle.android.sdk.devicesetup;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;

public class SimpleReceiver extends BroadcastReceiver {

    public interface LambdafiableBroadcastReceiver {
        void onReceive(Context context, Intent intent);
    }

    public static SimpleReceiver newReceiver(Context ctx, IntentFilter intentFilter,
                                             LambdafiableBroadcastReceiver receiver) {
        return new SimpleReceiver(ctx, intentFilter, receiver);
    }

    public static SimpleReceiver newRegisteredReceiver(Context ctx, IntentFilter intentFilter,
                                                       LambdafiableBroadcastReceiver receiver) {
        SimpleReceiver sr = new SimpleReceiver(ctx, intentFilter, receiver);
        sr.register();
        return sr;
    }

    private final Context appContext;
    private final IntentFilter intentFilter;
    private final LambdafiableBroadcastReceiver receiver;

    private boolean registered = false;

    private SimpleReceiver(Context ctx, IntentFilter intentFilter,
                           LambdafiableBroadcastReceiver receiver) {
        this.appContext = ctx.getApplicationContext();
        this.intentFilter = intentFilter;
        this.receiver = receiver;
    }

    @Override
    public void onReceive(Context context, Intent intent) {
        receiver.onReceive(context, intent);
    }

    public void register() {
        if (registered) {
            return;
        }
        appContext.registerReceiver(this, intentFilter);
        registered = true;
    }

    public void unregister() {
        if (!registered) {
            return;
        }
        appContext.unregisterReceiver(this);
        registered = false;
    }

}

Create util class to make broadcast receivers less awkward


/*
 * 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.camel.impl.lw;

import org.apache.camel.ContextTestSupport;
import org.apache.camel.builder.RouteBuilder;
import org.junit.Before;
import org.junit.Test;

public class ImmutableContextTest extends ContextTestSupport {

    @Override
    @Before
    public void setUp() throws Exception {
        setUseImmutableContext(true);
        super.setUp();
    }

    @Test
    public void testCBRCamel() throws Exception {
        getMockEndpoint("mock:other").expectedMessageCount(0);
        getMockEndpoint("mock:camel").expectedMessageCount(1);
        getMockEndpoint("mock:donkey").expectedMessageCount(0);

        template.sendBody("direct:start", "Camel rules");

        assertMockEndpointsSatisfied();
    }

    @Test
    public void testCBRDonkey() throws Exception {
        getMockEndpoint("mock:other").expectedMessageCount(0);
        getMockEndpoint("mock:camel").expectedMessageCount(0);
        getMockEndpoint("mock:donkey").expectedMessageCount(1);

        template.sendBody("direct:start", "Donkey kong");

        assertMockEndpointsSatisfied();
    }

    @Test
    public void testCBROther() throws Exception {
        getMockEndpoint("mock:other").expectedMessageCount(1);
        getMockEndpoint("mock:camel").expectedMessageCount(0);
        getMockEndpoint("mock:donkey").expectedMessageCount(0);

        template.sendBody("direct:start", "Hello World");

        assertMockEndpointsSatisfied();
    }

    @Override
    protected RouteBuilder createRouteBuilder() throws Exception {
        return new RouteBuilder() {
            @Override
            public void configure() throws Exception {
                from("direct:start")
                        .choice()
                            .when(body().contains("Camel"))
                                .to("mock:camel")
                            .when(body().contains("Donkey"))
                                .to("mock:donkey")
                            .otherwise()
                                .to("mock:other");
            }
        };
    }
}

Add a test for the immutable context

Add a test for the immutable context


package com.tom_e_white.set_game.preprocess;

import boofcv.io.image.UtilImageIO;
import com.tom_e_white.set_game.model.Card;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;
import java.util.stream.Collectors;

/**
 * Takes a test image and a label file (ending in .txt) and creates a directory of test images with the
 * corresponding labels.
 */
public class CreateTestSetV2 {
    public static void main(String[] args) throws IOException {
        File testFile = new File("data/20170106_205743.jpg");
        CardDetector cardDetector = new CardDetector();
        List<CardImage> images = cardDetector.detect(testFile.getAbsolutePath(), false);
        List<Card> cards = Files.lines(Paths.get(testFile.getAbsolutePath().replace(".jpg", ".txt")))
                .map(Card::new)
                .collect(Collectors.toList());
        File outDir = new File("data/test-v2");;
        outDir.mkdirs();
        for (int i = 0; i < images.size(); i++) {
            CardImage image = images.get(i);
            Card card = cards.get(i);
            File labelledDirectory = new File(outDir, card.getDescription().replace(" ", "-"));
            labelledDirectory.mkdirs();
            File newFile = new File(labelledDirectory, testFile.getName().replace(".jpg", "_" + (i + 1) + ".jpg"));
            UtilImageIO.saveImage(image.getImage(), newFile.getAbsolutePath());
        }

    }
}

Add code to generate test data in same directory structure as training data


package info.u_team.u_team_test.container;

import info.u_team.u_team_core.container.UTileEntityContainer;
import info.u_team.u_team_test.init.TestContainers;
import info.u_team.u_team_test.tileentity.BasicFluidInventoryTileEntity;
import net.minecraft.entity.player.PlayerInventory;
import net.minecraft.network.PacketBuffer;

public class BasicFluidInventoryContainer extends UTileEntityContainer<BasicFluidInventoryTileEntity> {

	// Client
	public BasicFluidInventoryContainer(int id, PlayerInventory playerInventory, PacketBuffer buffer) {
		super(TestContainers.BASIC_FLUID_INVENTORY, id, playerInventory, buffer);
	}

	// Server
	public BasicFluidInventoryContainer(int id, PlayerInventory playerInventory, BasicFluidInventoryTileEntity tileEntity) {
		super(TestContainers.BASIC_FLUID_INVENTORY, id, playerInventory, tileEntity);
	}

	@Override
	protected void init(boolean server) {

	}

}

Add basic fluid inventory container

Add basic fluid inventory container


package org.springframework.roo.support.util;

import org.w3c.dom.Document;
import org.w3c.dom.Element;

/**
 * Very simple convenience Builder for XML {@code Element}s
 *
 * @author Stefan Schmidt
 * @since 1.0
 *
 */
public class XmlElementBuilder {

	private Element element;

	/**
	 * Create a new Element instance.
	 *
	 * @param name The name of the element (required, not empty)
	 * @param document The parent document (required)
	 */
	public XmlElementBuilder (String name, Document document) {
		Assert.hasText(name, "Element name required.");
		Assert.notNull(document, "Owner document required");
		element = document.createElement(name);
	}

	/**
	 * Add an attribute to the current element.
	 *
	 * @param qName The attribute name (required, not empty)
	 * @param value The value of the attribute (required)
	 * @return
	 */
	public XmlElementBuilder addAttribute(String qName, String value) {
		Assert.hasText(qName, "Attribute qName required.");
		Assert.notNull(value, "Attribute value required.");
		element.setAttribute(qName, value);
		return this;
	}

	/**
	 * Add a child element to the current element.
	 *
	 * @param element The new element (required)
	 * @return The builder for the current element
	 */
	public XmlElementBuilder addChild(Element element) {
		Assert.notNull(element, "Element required.");
		this.element.appendChild(element);
		return this;
	}

	/**
	 * Add text contents to the current element. This will overwrite
	 * any previous text content.
	 *
	 * @param element The text content (required, not empty)
	 * @return The builder for the current element
	 */
	public XmlElementBuilder setText(String text) {
		Assert.hasText(text, "Text content required.");
		element.setTextContent(text);
		return this;
	}

	/**
	 * Get the element instance.
	 *
	 * @return The element.
	 */
	public Element build() {
		return element;
	}
}

ROO-196: Introduce simple XML Element builder to improve DOM generation tasks


/*
 * Copyright 2020 Martin Winandy
 *
 * 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.
 */

/**
 * Runtime implementations for standard Java and Android.
 */
package org.tinylog.core.runtimes;

Add package for runtime implementations

Add package for runtime implementations


package org.gbif.occurrence.hive.udf;

import org.junit.jupiter.api.Test;

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

public class GeoDistanceUDFTest {

  @Test
  public void evaluateTest() {

    // At the Equator, moving 0.04° is 4448m.
    assertTrue(contains(0d, 0d, "5km", 0d, 0.04d));
    // And 0.5° is 5560m.
    assertFalse(contains(0d, 0d, "5km", 0d, 0.05d));

    // At 80° north, moving 0.04° is only 772m.
    assertTrue(contains(80d, 0d, "5km", 80d, 0.04d));
    // But we can move 0.25° and still have moved only 4827m.
    assertTrue(contains(80d, 0d, "5km", 80d, 0.25d));
    // This is 5020m.
    assertFalse(contains(80d, 0d, "5km", 80d, 0.26d));
  }

  private boolean contains(Double latitude1, Double longitude1, String distance, Double latitude2, Double longitude2) {
    return new GeoDistanceUDF().evaluate(latitude1, longitude1, distance, latitude2, longitude2).get();
  }
}

Add test case for GeoDistanceUDF.

Add test case for GeoDistanceUDF.


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

import org.openehealth.ipf.platform.camel.flow.PlatformMessage;
import org.openehealth.ipf.platform.camel.flow.PlatformMessageRenderer;

/**
 * @author Martin Krasser
 */
public class DefaultRenderer implements PlatformMessageRenderer {

    @Override
    public String render(PlatformMessage message) {
        return message.getExchange().getIn().getBody(String.class);
    }

}

Use default renderer for all flow management interceptors

git-svn-id: 15d4771d83c46956b550e66b034a1e73d7ee3103@85 d594d982-de57-441b-9a2b-38caaf397e83


package uk.gov.dvla.services.authentication.exceptions;

public class DWPNegativeMatchException extends AuthenticationException {

    public DWPNegativeMatchException(String msg) {
        super(msg);
    }

    public DWPNegativeMatchException(String msg, Throwable t) {
        super(msg, t);
    }
}

Fix a couple of defects

Fix a couple of defects


/**
 * Copyright (C) 2009 - 2010 by OpenGamma Inc.
 *
 * Please see distribution for license.
 */
package com.opengamma.engine.view.calcnode;

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

import org.junit.Test;

/**
 *
 */
public class CalculationJobSpecificationTest {

  @Test
  public void testHashCode() {
    CalculationJobSpecification spec1 = new CalculationJobSpecification("view", "config", 1L, 1L);
    CalculationJobSpecification spec2 = new CalculationJobSpecification("view", "config", 1L, 1L);

    assertEquals(spec1.hashCode(), spec2.hashCode());

    spec2 = new CalculationJobSpecification("view2", "config", 1L, 1L);
    assertFalse(spec1.hashCode() == spec2.hashCode());
    spec2 = new CalculationJobSpecification("view", "config2", 1L, 1L);
    assertFalse(spec1.hashCode() == spec2.hashCode());
    spec2 = new CalculationJobSpecification("view", "config", 2L, 1L);
    assertFalse(spec1.hashCode() == spec2.hashCode());
    spec2 = new CalculationJobSpecification("view", "config", 1L, 2L);
    assertFalse(spec1.hashCode() == spec2.hashCode());
  }

  @Test
  public void testEquals() {
    CalculationJobSpecification spec1 = new CalculationJobSpecification("view", "config", 1L, 1L);
    assertTrue(spec1.equals(spec1));
    assertFalse(spec1.equals(null));
    assertFalse(spec1.equals("Kirk"));
    CalculationJobSpecification spec2 = new CalculationJobSpecification("view", "config", 1L, 1L);
    assertTrue(spec1.equals(spec2));

    spec2 = new CalculationJobSpecification("view2", "config", 1L, 1L);
    assertFalse(spec1.equals(spec2));
    spec2 = new CalculationJobSpecification("view", "config2", 1L, 1L);
    assertFalse(spec1.equals(spec2));
    spec2 = new CalculationJobSpecification("view", "config", 2L, 1L);
    assertFalse(spec1.equals(spec2));
    spec2 = new CalculationJobSpecification("view", "config", 1L, 2L);
    assertFalse(spec1.equals(spec2));
  }

}

[ENG-113] Test of .hashCode and equals on CalculationJobSpecification.


package flyway.ptimigration;

import fi.nls.oskari.util.JSONHelper;
import org.json.JSONObject;

/**
 * Removes mapUrlPrefix config from toolbar if available
 */
public class V1_11__Remove_mapurl_from_toolbar_config extends ConfigMigration {

    public String getBundle() {
        return "toolbar";
    }

    public String getModifiedConfig(final String param) throws Exception {
        final JSONObject config = JSONHelper.createJSONObject(param);
        config.remove("mapUrlPrefix");
        return config.toString(2);
    }

}

Remove link config from toolbar

Remove link config from toolbar


package ac.at.tuwien.infosys.visp.runtime.restAPI;

import java.util.List;

import ac.at.tuwien.infosys.visp.common.operators.Operator;
import ac.at.tuwien.infosys.visp.runtime.configuration.Configurationprovider;
import ac.at.tuwien.infosys.visp.runtime.reasoner.ReasonerUtility;
import ac.at.tuwien.infosys.visp.runtime.resourceManagement.ProcessingNodeManagement;
import ac.at.tuwien.infosys.visp.runtime.topology.TopologyManagement;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.DependsOn;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

@RequestMapping("/control")
@RestController
@DependsOn("configurationprovider")
public class ScalingAPI {

    @Autowired
    private TopologyManagement topologyMgmt;

    @Autowired
    private Configurationprovider config;

    @Autowired
    private ProcessingNodeManagement pcm;

    @Autowired
    private ReasonerUtility reasonerUtility;

    @RequestMapping(value = {"/scaleup/{operatorName}"}, method = RequestMethod.GET)
    public String scaleup(@PathVariable String operatorName) {

        List<Operator> operators = topologyMgmt.getOperatorsForAConcreteLocation(config.getRuntimeIP());

        Operator selectedOperator = null;

        for (Operator op : operators) {
            if (operatorName.equals(op.getName())) {
                selectedOperator = op;
                break;
            }
        }

        if (selectedOperator == null) {
            return "no operator with that name exists.";
        }

        pcm.scaleup(reasonerUtility.selectSuitableDockerHost(selectedOperator), selectedOperator);

        return "ok";
    }

}

Add scaling API for Operator instances

Add scaling API for Operator instances


package com.googlecode.jslint4java.maven;

import static com.googlecode.jslint4java.maven.RootCauseMatcher.*;
import static org.hamcrest.CoreMatchers.*;
import static org.junit.Assert.*;

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

public class RootCauseMatcherTest {

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

    private final RuntimeException exc = new RuntimeException(new IllegalArgumentException("foo"));

    @Test
    public void shouldMatchRootClauseByClass() {
        assertThat(exc, rootCause(IllegalArgumentException.class));
    }

    @Test
    public void shouldMatchRootClauseByMatcher() {
        assertThat(exc, rootCause(instanceOf(IllegalArgumentException.class)));
    }

    @Test
    public void shouldNotMatchNonException() {
        assertThat(new Object(), not(rootCause(IllegalArgumentException.class)));
    }

    @Test
    public void shouldDescribeFailure() {
        kaboom.handleAssertionErrors();
        kaboom.expect(AssertionError.class);
        kaboom.expectMessage(containsString("an exception with root cause"));

        // This should fail, and raise an AssertionErrror.
        assertThat(new Object(), rootCause(IllegalArgumentException.class));
    }
}

Add a test for RootCauseMatcher.

Add a test for RootCauseMatcher.


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

package com.uber.jenkins.phabricator;

import com.uber.jenkins.phabricator.utils.TestUtils;
import hudson.plugins.cobertura.targets.CoverageResult;
import org.junit.Test;

import static org.junit.Assert.assertEquals;

public class CodeCoverageMetricsTest {
    @Test
    public void testInstantiateFromCoverageResult() {
        CoverageResult result = TestUtils.getDefaultCoverageResult();
        CodeCoverageMetrics metrics = new CodeCoverageMetrics(result);

        assertEquals(100.0f, metrics.getPackageCoveragePercent(), 0);
        assertEquals(100.0f, metrics.getFilesCoveragePercent(), 0);
        assertEquals(100.0f, metrics.getClassesCoveragePercent(), 0);
        assertEquals(100.0f, metrics.getMethodCoveragePercent(), 0);
        assertEquals(100.0f, metrics.getLineCoveragePercent(), 0);
        assertEquals(-1f, metrics.getConditionalCoveragePercent(), 0);
    }

    @Test
    public void testInstantiateFromNullResult() {
        CodeCoverageMetrics metrics = new CodeCoverageMetrics(null);
        assertEquals(-1f, metrics.getLineCoveragePercent(), 0);
    }
}

Add unit test for CodeCoverageMetrics

Add unit test for CodeCoverageMetrics

Really just trolling for coverage at this point, but I noticed a large
amount of uncovered code in here which was easy to knock out.


package org.grouplens.lenskit.knn.item;

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

import it.unimi.dsi.fastutil.longs.LongAVLTreeSet;
import it.unimi.dsi.fastutil.longs.LongSortedSet;
import org.grouplens.lenskit.collections.ScoredLongList;
import org.grouplens.lenskit.collections.ScoredLongListIterator;
import org.junit.Before;
import org.junit.Test;

/**
 * @author Michael Ekstrand
 */
public class TestItemItemModelAccumulator {
    LongSortedSet universe;
    /**
     * An accumulator with a size of 5 and universe of [1,10].
     */
    ItemItemModelAccumulator accum;

    @Before
    public void newAccumulator() {
        universe = new LongAVLTreeSet();
        for (long i = 1; i <= 10; i++) {
            universe.add(i);
        }
        accum = new ItemItemModelAccumulator(5, universe);
    }

    @Test
    public void testEmpty() {
        ItemItemModel model = accum.build();
        assertThat(model, notNullValue());
        assertThat(model.getItemUniverse(), equalTo(universe));
    }

    @Test
    public void testAccum() {
        accum.put(1, 2, Math.PI);
        accum.put(7, 3, Math.E);
        ItemItemModel model = accum.build();
        ScoredLongList nbrs = model.getNeighbors(1);
        assertThat(nbrs, hasSize(1));
        assertThat(nbrs.get(0), equalTo(2L));
        assertThat(nbrs.getScore(0), closeTo(Math.PI, 1.0e-6));
        nbrs = model.getNeighbors(7);
        assertThat(nbrs, hasSize(1));
        assertThat(nbrs.get(0), equalTo(3L));
        assertThat(nbrs.getScore(0), closeTo(Math.E, 1.0e-6));
    }

    @Test
    public void testTruncate() {
        for (long i = 1; i <= 10; i++) {
            for (long j = 1; j <= 10; j += (i % 3) + 1) {
                accum.put(i, j, Math.pow(Math.E, -i) * Math.pow(Math.PI, -j));
            }
        }
        ItemItemModel model = accum.build();
        ScoredLongList nbrs = model.getNeighbors(1);
        assertThat(nbrs, hasSize(5));
        nbrs = model.getNeighbors(4);
        assertThat(nbrs, hasSize(5));
        ScoredLongListIterator iter = nbrs.iterator();
        while (iter.hasNext()) {
            long j = iter.nextLong();
            double s = iter.getScore();
            assertThat(s, closeTo(Math.pow(Math.E, -4) * Math.pow(Math.PI, -j), 1.0e-6));
        }
    }
}

Test the item-item model accumulator

Test the item-item model accumulator


package au.gov.ga.geodesy.domain.model;

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

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;

public interface EquipmentConfigurationRepository extends JpaRepository<EquipmentConfiguration, Integer> {

    @Override
    List<EquipmentConfiguration> findAll();

    @Query("select c from EquipmentConfiguration c" +
           " where c.equipmentId.id = :equipmentId and c.configurationTime = :configurationTime")
    EquipmentConfiguration findOne(@Param("equipmentId") Integer id, @Param("configurationTime") Date time);
}

Add generic equipment configuration repository.


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

package com.michaelrocks.lightsaber.processor.commons;

import org.objectweb.asm.ClassVisitor;

import static org.objectweb.asm.Opcodes.ASM5;

public class JavaVersionChanger extends ClassVisitor {
    private final int newVersion;

    public JavaVersionChanger(final ClassVisitor classVisitor, final int newVersion) {
        super(ASM5, classVisitor);
        this.newVersion = newVersion;
    }

    @Override
    public void visit(final int version, final int access, final String name, final String signature,
            final String superName, final String[] interfaces) {
        super.visit(newVersion, access, name, signature, superName, interfaces);
    }
}

Implement a class visitor that changes JVM version of a class


package com.linkedin.clustermanager.controller;

import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import com.linkedin.clustermanager.core.ClusterDataAccessor.InstanceConfigProperty;
import com.linkedin.clustermanager.model.ZNRecord;

public class InstanceConfigHolder
{
  private List<ZNRecord> _instanceConfigList;

  private Map<String, Boolean> _instanceEnabledMap = new TreeMap<String, Boolean>();

  public void refresh(List<ZNRecord> instanceConfigs)
  {
    _instanceConfigList = instanceConfigs;
    updateEnableMap();
  }

  void updateEnableMap()
  {
    _instanceEnabledMap.clear();
    for(ZNRecord config : _instanceConfigList)
    {
      boolean enabled = Boolean.parseBoolean(config.getSimpleField(InstanceConfigProperty.ENABLED.toString()));
      _instanceEnabledMap.put(config.getId(), enabled);
    }
  }

  public boolean isEnabled(String instanceName)
  {
    if (!_instanceEnabledMap.containsKey(instanceName))
    {
        return false;
    }
    return _instanceEnabledMap.get(instanceName);
  }
}

Add instanceHolder class to keep the enabled / disabled instances


package com.github.sormuras.bach.lookup;

import java.net.URI;
import java.nio.file.Path;

/** A builder of external module objects. */
public class ExternalModuleLookupBuilder {

  /** The name of the module to link. */
  private final String module;

  /**
   * Constructs an instance of this class with the given components.
   *
   * @param module the name of the module to link
   */
  public ExternalModuleLookupBuilder(String module) {
    this.module = module;
  }

  /**
   * Returns a module link whose uri is determined by the given target string.
   *
   * @param target the target to parse into a uri
   * @return a module link
   */
  public ExternalModuleLookup to(String target) {
    var maven = target.indexOf('/') == -1 && target.chars().filter(ch -> ch == ':').count() >= 2;
    if (maven) return toMavenCentral(target);
    return toUri(target);
  }

  /**
   * Returns a module link pointing to local path.
   *
   * @param base the base directory
   * @param more the path to the file
   * @return an external module link
   */
  public ExternalModuleLookup toPath(String base, String more) {
    var first = base.equals("~") ? System.getProperty("user.home") : base;
    var path = Path.of(first, more);
    return toUri(path.normalize().toUri());
  }

  /**
   * Returns a module link pointing to an artifact hosted at the given Maven repository.
   *
   * @param repository Maven repository
   * @param coordinates Maven groupId + ':' + artifactId + ':' version [+ ':' + classifier]
   * @return a Maven-based {@code Link} instance
   */
  public ExternalModuleLookup toMaven(String repository, String coordinates) {
    var split = coordinates.split(":");
    if (split.length < 3) throw new IllegalArgumentException();
    var joiner = Maven.Joiner.of(split[0], split[1], split[2])
        .repository(repository)
        .classifier(split.length < 4 ? "" : split[3]);
    return toUri(joiner.toString());
  }

  /**
   * Returns a module link pointing to an artifact hosted at Maven Central.
   *
   * @param coordinates Maven groupId + ':' + artifactId + ':' version [+ ':' + classifier]
   * @return a Maven Central-based {@code Link} instance
   * @see search.maven.org
   */
  public ExternalModuleLookup toMavenCentral(String coordinates) {
    return toMaven(Maven.CENTRAL_REPOSITORY, coordinates);
  }

  /**
   * Returns a module link pointing to the given uniform resource identifier.
   *
   * @param uri uniform resource identifier of the module
   * @return a module link
   */
  public ExternalModuleLookup toUri(String uri) {
    return toUri(URI.create(uri));
  }

  /**
   * Returns a module link pointing to the given uniform resource identifier.
   *
   * @param uri uniform resource identifier of the module
   * @return a module link
   */
  public ExternalModuleLookup toUri(URI uri) {
    return new ExternalModuleLookup(module, uri.toString());
  }
}

Introduce external module lookup builder class


/*
 * Copyright 2015 Open Networking Laboratory
 *
 * 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.onosproject.vtnrsc.tenantnetwork;

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.notNullValue;
import static org.onlab.junit.ImmutableClassChecker.assertThatClassIsImmutable;

import org.junit.Test;
import org.onosproject.vtnrsc.TenantNetworkId;

import com.google.common.testing.EqualsTester;

/**
 * Unit tests for TenantNetworkId class.
 */
public class TenantNetworkIdTest {

    final TenantNetworkId networkId1 = TenantNetworkId.networkId("1");
    final TenantNetworkId sameAsnetworkId1 = TenantNetworkId.networkId("1");
    final TenantNetworkId networkId2 = TenantNetworkId.networkId("2");

    /**
     * Checks that the TenantNetworkId class is immutable.
     */
    @Test
    public void testImmutability() {
        assertThatClassIsImmutable(TenantNetworkId.class);
    }

    /**
     * Checks the operation of equals() methods.
     */
    @Test
    public void testEquals() {
        new EqualsTester().addEqualityGroup(networkId1, sameAsnetworkId1)
                .addEqualityGroup(networkId2).testEquals();
    }

    /**
     * Checks the construction of a TenantNetworkId object.
     */
    @Test
    public void testConstruction() {
        final String networkIdValue = "s";
        final TenantNetworkId networkId = TenantNetworkId.networkId(networkIdValue);
        assertThat(networkId, is(notNullValue()));
        assertThat(networkId.networkId(), is(networkIdValue));
    }
}

[ONOS-3233] Add the junit test code of TenantNetworkId

Change-Id: Ibd30b8bb7bd936ea2e21477e5229edfe65ef9b2f


/**
 * Copyright 2015 Red Hat, Inc, and individual contributors.
 *
 * 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.wildfly.swarm.logstash.runtime;

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

import org.jboss.dmr.ModelNode;
import org.wildfly.swarm.container.runtime.AbstractServerConfiguration;
import org.wildfly.swarm.logstash.LogstashFraction;

/**
 * @author Bob McWhirter
 */
public class LogstashConfiguration extends AbstractServerConfiguration<LogstashFraction> {

    public LogstashConfiguration() {
        super(LogstashFraction.class);
    }

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

    @Override
    public LogstashFraction defaultFraction() {
        return (LogstashFraction) LogstashFraction.createDefaultLogstashFraction(false);
    }

    @Override
    public List<ModelNode> getList(LogstashFraction fraction) {
        return Collections.emptyList();
    }

}

/**
 * Copyright 2015 Red Hat, Inc, and individual contributors.
 *
 * 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.wildfly.swarm.logstash.runtime;

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

import org.jboss.dmr.ModelNode;
import org.wildfly.swarm.container.runtime.AbstractServerConfiguration;
import org.wildfly.swarm.logstash.LogstashFraction;

/**
 * @author Bob McWhirter
 */
public class LogstashConfiguration extends AbstractServerConfiguration<LogstashFraction> {

    public LogstashConfiguration() {
        super(LogstashFraction.class);
    }

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

    @Override
    public LogstashFraction defaultFraction() {
        return (LogstashFraction) LogstashFraction.createDefaultLogstashFraction(false);
    }

}

Add some more *Configuration super-classes to simplify boiler-plate stuff.


package io.quarkus.spring.web.test;

import static io.restassured.RestAssured.when;
import static org.hamcrest.Matchers.is;

import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.spec.JavaArchive;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;

import io.quarkus.test.QuarkusDevModeTest;

public class ControllerReloadTest {

    @RegisterExtension
    static QuarkusDevModeTest TEST = new QuarkusDevModeTest()
            .setArchiveProducer(() -> ShrinkWrap.create(JavaArchive.class)
                    .addClasses(SimpleSpringController.class));

    @Test
    public void testRepositoryIsReloaded() {
        when().get("/simple").then().body(is("hello"));

        TEST.modifySourceFile("SimpleSpringController.java", s -> s.replace("hello", "hi"));

        when().get("/simple").then().body(is("hi"));
    }
}

Add a dev-mode test for the Spring Web module


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

/**
 * Package for context-aware java {@link java.util.concurrent.Future} code.
 *
 *
{@linkplain nl.talsmasoftware.context.futures.ContextAwareCompletableFuture}

 *

 * A {@linkplain java.util.concurrent.CompletableFuture} that applies a certain
 * {@linkplain nl.talsmasoftware.context.ContextSnapshot} to all
 * {@linkplain java.util.concurrent.CompletionStage completion stages} of the completable future.
 */
package nl.talsmasoftware.context.futures;

Add javadoc to the java 8 futures package


package com.github.conradoqg.studydsa.hackerrank.challenges.ctci;

import java.util.Scanner;

public class LonelyInteger {
    public static int lonelyInteger(int[] a) {
        int lonelyOne = 0;
        for (int nextNumber : a) {
            lonelyOne = lonelyOne ^ nextNumber;
        }
        return lonelyOne;
    }

    public static void main(String[] args) {
        try (Scanner in = new Scanner(System.in)) {
            int n = in.nextInt();
            int a[] = new int[n];
            for (int a_i = 0; a_i < n; a_i++) {
                a[a_i] = in.nextInt();
            }
            System.out.println(lonelyInteger(a));
        }
    }
}

Add lonely integer CTCI challenge

Add lonely integer CTCI challenge


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

package enmasse.storage.controller.openshift;

import com.openshift.internal.restclient.model.ReplicationController;
import com.openshift.restclient.IClient;
import com.openshift.restclient.ResourceKind;
import enmasse.storage.controller.model.AddressType;
import enmasse.storage.controller.model.LabelKeys;
import org.jboss.dmr.ModelNode;
import org.junit.Test;

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

import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;

public class OpenshiftClientTest {
    @Test
    public void testListClusters() {
        IClient client = mock(IClient.class);
        OpenshiftClient osClient = new OpenshiftClient(client, "myspace");
        ReplicationController controller = new ReplicationController(new ModelNode(), client, Collections.emptyMap());
        controller.addLabel(LabelKeys.FLAVOR, "vanilla");
        controller.addLabel(LabelKeys.ADDRESS_TYPE, AddressType.QUEUE.value());
        controller.addLabel(LabelKeys.ADDRESS, "foo");
        when(client.list(ResourceKind.REPLICATION_CONTROLLER, "myspace")).thenReturn(Collections.singletonList(controller));

        List<StorageCluster> clusters = osClient.listClusters();
        verify(client).list(ResourceKind.REPLICATION_CONTROLLER, "myspace");
        assertThat(clusters.size(), is(1));
        StorageCluster cluster = clusters.get(0);
        assertThat(cluster.getDestination().address(), is("foo"));
        assertThat(cluster.getDestination().flavor(), is("vanilla"));
        assertTrue(cluster.getDestination().storeAndForward());
        assertFalse(cluster.getDestination().multicast());
    }
}

Add test for openshift client

Add test for openshift client


package com.cyq7on.leetcode.linked_list;

/**
 * @author cyq7on
 * @description Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list.
 *

 * Example 1:
 *

 * Input: 1->2->3->3->4->4->5
 * Output: 1->2->5
 * Example 2:
 *

 * Input: 1->1->1->2->3
 * Output: 2->3
 * @create 2019/12/22
 **/
public class RemoveDuplicatesFromSortedListII {
    public ListNode deleteDuplicates(ListNode head) {
        return deleteDuplicates(head, Integer.MAX_VALUE);
    }

    public ListNode deleteDuplicates(ListNode head,int lastVal) {
        if (head == null) {
            return null;
        }

        //头结点值等于上个节点的值，移除头节点，从下个节点开始递归
        if (head.val == lastVal) {
            return deleteDuplicates(head.next, head.val);
        }

        if (head.next == null) {
            return head;
        }

        //头节点的值等于下个节点的值，则移除头结点和下一个节点，从下下个节点开始递归
        if (head.val == head.next.val) {
            return deleteDuplicates(head.next.next,head.val);
        }

        //头结点和下个节点都存在且值不相等，保留头节点，从下个节点开始递归
        head.next = deleteDuplicates(head.next,head.val);
        return head;
    }

    public static void main(String[] args) {
        RemoveDuplicatesFromSortedListII removeDuplicatesFromSortedListII = new RemoveDuplicatesFromSortedListII();
        System.out.println(removeDuplicatesFromSortedListII.deleteDuplicates(new ListNode(new int[]{-1,0,0,0,0,3,3})));
        System.out.println(removeDuplicatesFromSortedListII.deleteDuplicates(new ListNode(new int[]{1,2,2})));
        System.out.println(removeDuplicatesFromSortedListII.deleteDuplicates(new ListNode(new int[]{1,2,3,3,4,4,5})));
        System.out.println(removeDuplicatesFromSortedListII.deleteDuplicates(new ListNode(new int[]{1,1,1,2,3})));
        System.out.println(removeDuplicatesFromSortedListII.deleteDuplicates(new ListNode(new int[]{1,1,1,2,3,3})));
    }
}

Remove Duplicates from Sorted List II

Remove Duplicates from Sorted List II


package org.springframework.content.docx4j.config;

import internal.org.springframework.content.docx4j.JpegToPngRenditionProvider;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

@Configuration
@ComponentScan(basePackageClasses = JpegToPngRenditionProvider.class)
public class Docx4jConfiguration {
}

Add a configuration that can be imported by applications to enable the docx4j renderers

#226


package org.apache.solr.handler.dataimport;

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

import com.carrotsearch.randomizedtesting.annotations.ThreadLeakAction;
import com.carrotsearch.randomizedtesting.annotations.ThreadLeakLingering;
import com.carrotsearch.randomizedtesting.annotations.ThreadLeakScope;
import com.carrotsearch.randomizedtesting.annotations.ThreadLeakZombies;
import org.apache.solr.SolrTestCaseJ4;

import java.sql.DriverManager;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Properties;

@ThreadLeakAction({ThreadLeakAction.Action.WARN})
@ThreadLeakLingering(linger = 0)
@ThreadLeakZombies(ThreadLeakZombies.Consequence.CONTINUE)
@ThreadLeakScope(ThreadLeakScope.Scope.NONE)
public class TestJdbcDataSourceConvertType extends AbstractDataImportHandlerTestCase {
  public void testConvertType() throws Throwable {
    // ironically convertType=false causes BigDecimal to String conversion
    convertTypeTest("false", String.class);

    // convertType=true uses the "long" conversion (see mapping of some_i to "long")
    convertTypeTest("true", Long.class);
  }

  private void convertTypeTest(String convertType, Class resultClass) throws Throwable {
    JdbcDataSource dataSource = new JdbcDataSource();
    Properties p = new Properties();
    p.put("driver", "org.apache.derby.jdbc.EmbeddedDriver");
    p.put("url", "jdbc:derby:memory:tempDB;create=true");
    p.put("convertType", convertType);

    List<Map<String, String>> flds = new ArrayList<>();
    Map<String, String> f = new HashMap<>();
    f.put("column", "some_i");
    f.put("type", "long");
    flds.add(f);

    Context c = getContext(null, null,
        dataSource, Context.FULL_DUMP, flds, null);
    dataSource.init(c, p);
    Iterator<Map<String, Object>> i = dataSource
        .getData("select 1 as id, CAST(9999 AS DECIMAL) as \"some_i\" from sysibm.sysdummy1");
    assertTrue(i.hasNext());
    Map<String, Object> map = i.next();
    Object val = map.get("some_i");
    assertEquals(resultClass, val.getClass());

    dataSource.close();
  }
}

SOLR-6165: Add tests for convertType and BigDecimal implicit conversion

git-svn-id: 308d55f399f3bd9aa0560a10e81a003040006c48@1611985 13f79535-47bb-0310-9956-ffa450edef68


package org.languagetool.rules.el;

import org.junit.Before;
import org.junit.Test;
import org.languagetool.JLanguageTool;
import org.languagetool.TestTools;
import org.languagetool.language.Greek;
import org.languagetool.rules.RuleMatch;
import java.io.IOException;
import static org.junit.Assert.assertEquals;

public class GreekRedundancyRuleTest {
	private GreekRedundancyRule rule;
	private JLanguageTool langTool;

	@Before
	public void setUp() throws IOException {
		rule = new GreekRedundancyRule(TestTools.getMessages("el"), new Greek());
		langTool = new JLanguageTool(new Greek());
	}

	// correct sentences
	@Test
	public void testRule() throws IOException {
		assertEquals(0, rule.match(langTool.getAnalyzedSentence("Τώρα μπαίνω στο σπίτι.")).length);
		assertEquals(0, rule.match(langTool.getAnalyzedSentence("Απόψε θα βγω.")).length);
	}

	// test for redundancy within the sentence
	@Test
	public void testRuleWithinSentence() throws IOException {
		RuleMatch[] matches = rule.match(langTool.getAnalyzedSentence("Τώρα μπαίνω μέσα στο σπίτι."));
		assertEquals(1, matches.length);
		assertEquals("μπαίνω", matches[0].getSuggestedReplacements().get(0));
	}

	// test for redundancy in the beggining of a sentence.
	@Test
	public void testRuleBegginingOfSentence() throws IOException {
		RuleMatch[] matches = rule.match(langTool.getAnalyzedSentence(
				"Απόψε το βράδυ θα βγω."));
		assertEquals(1, matches.length);
		assertEquals("Απόψε", matches[0].getSuggestedReplacements().get(0));
	}

	// test for redundancy with multiple suggestions
	@Test
	public void testRuleMultipleSuggestions() throws IOException {
		RuleMatch[] matches = rule.match(langTool.getAnalyzedSentence(
				"Το μαγαζί ήταν ωραίο, αλλά όμως δεν πέρασα καλά."));
		assertEquals(1, matches.length);
		assertEquals("αλλά,όμως", matches[0].getSuggestedReplacements().get(0));

	}

}

Add test cases for GreekRedundancyRule

Add test cases for GreekRedundancyRule


/*
 * Copyright 2019, TeamDev. 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.examples.todolist.server;

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

/**
 * An endpoint triggered by AppEngine when a new instance is being started.
 *
 * @see AppEngine doc
 */
@WebServlet("/_ah/warmup")
public class WarmupServlet extends HttpServlet {

    private static final long serialVersionUID = 0L;

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) {
        Application application = Application.instance();
    }
}

Add warmup servlet for AppEngine instance start request.


package com.github.aureliano.damihilogs.config.input;

public enum InputConfigTypes {

	EXTERNAL_COMMAND,
	FILE_INPUT,
	FILE_TAILER,
	STANDARD_INPUT,
	URL,
	JDBC_INPUT,
	TWITTER_INPUT;
}

Create input config types enum.

Create input config types enum.


package com.github.sparkcaller.preprocessing;

import com.github.sparkcaller.BaseGATKProgram;
import com.github.sparkcaller.Utils;
import org.apache.spark.api.java.function.Function;
import scala.Tuple2;

import java.io.File;

public class BQSRTargetGenerator extends BaseGATKProgram implements Function<File, Tuple2<File, File>> {
    public BQSRTargetGenerator(String pathToReference, String knownSites, String extraArgs) {
        super("BaseRecalibrator", extraArgs);
        setReference(pathToReference);
        addArgument("-knownSites", knownSites);
    }

    public Tuple2<File, File> call(File file) throws Exception {
        setInputFile(file.getPath());
        String outputTableFilename = Utils.removeExtenstion(file.getPath(), "bam") + "-recal_data.table";
        File outputTable = new File(outputTableFilename);

        setOutputFile(outputTable.getPath());

        executeProgram();
        return new Tuple2<File, File>(file, outputTable);
    }
}

Add the class used to find which parts of the BAM file which requires BQSR.


package org.roklib.urifragmentrouting.parameter.converter;

import org.junit.Test;
import org.roklib.urifragmentrouting.exception.ParameterValueConversionException;

import java.util.Arrays;
import java.util.List;

import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertThat;

public class StringListParameterValueConverterTest {

    @Test
    public void testConversion() throws ParameterValueConversionException {
        final List<String> stringList = Arrays.asList("foo", "bar/baz", "foo;bar");
        StringListParameterValueConverter converter = StringListParameterValueConverter.INSTANCE;
        final String convertedString = converter.convertToString(stringList);
        assertThat(convertedString, is("foo;bar%2Fbaz;foo%3Bbar"));

        final List<String> convertedList = converter.convertToValue(convertedString);
        assertThat(convertedList, is(stringList));
    }
}

Add unit test for StringListParameterValueConverter


// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.hosted.node.admin.maintenance.servicedump;

import java.nio.file.Path;

/**
 * An artifact file produced by a {@link ArtifactProducer}.
 *
 * @author bjorncs
 */
class Artifact {

    enum Classification {
        CONFIDENTIAL("confidential"),
        INTERNAL("internal");

        private final String value;
        Classification(String value) { this.value = value; }
        public String value() { return value; }
    }

    private final Classification classification;
    private final Path file;
    private final boolean compressOnUpload;

    private Artifact(Builder builder) {
        this.file = builder.file;
        this.classification = builder.classification;
        this.compressOnUpload = builder.compressOnUpload != null ? builder.compressOnUpload : false;
    }

    static Builder newBuilder(Classification classification, Path file) {
        return new Builder(classification, file);
    }

    Classification classification() { return classification; }
    Path file() { return file; }
    boolean compressOnUpload() { return compressOnUpload; }

    static class Builder {
        private Classification classification;
        private Path file;
        private Boolean compressOnUpload;

        private Builder(Classification classification, Path file) {
            this.classification = classification;
            this.file = file;
        }

        Builder compressOnUpload() { this.compressOnUpload = true; return this; }
        Artifact build() { return new Artifact(this); }
    }
}

Add type representing a produced artifact

Include asset classification and compress flag in addition to file location.


package com.sunny.grokkingalgorithms.boot2019.phleps;

import java.util.HashSet;
import java.util.Set;

public class RemoveDuplicateElementsFromString {

    public static char[] removeDuplicates(char[] input){
        Set<Character> trackerSet = new HashSet<>();
        StringBuilder stringBuilder = new StringBuilder();
        for(int i = 0 ; i < input.length ; i++){
            if(!trackerSet.contains(input[i])){
                stringBuilder.append(input[i]);
                trackerSet.add(input[i]);
            }
        }
        return stringBuilder.toString().toCharArray();
    }

    public static void main(String[] args) {
        char str[] = "geeksforgeeks".toCharArray();
        System.out.println(String.valueOf(removeDuplicates(str)));
    }
}

Remove duplicate elements using hashig.

Remove duplicate elements using hashig.


/*
 * Copyright (c) 2012-2018 Red Hat, Inc.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *   Red Hat, Inc. - initial API and implementation
 */
package org.eclipse.che.api.workspace.server.wsnext;

import com.google.common.annotations.Beta;
import java.util.Collection;
import org.eclipse.che.api.workspace.server.spi.InfrastructureException;
import org.eclipse.che.api.workspace.server.spi.environment.InternalEnvironment;
import org.eclipse.che.api.workspace.server.wsnext.model.CheService;

/**
 * Applies Workspace.Next configuration to an internal runtime object that represents workspace
 * runtime configuration on an infrastructure level.
 *
 * @author Oleksander Garagatyi
 */
@Beta
public interface WorkspaceNextApplier {

  /**
   * Applies Workspace.Next configuration to internal environment.
   *
   * @param internalEnvironment infrastructure specific representation of workspace runtime
   *     environment
   * @param cheServices Workspace.Next configuration to apply to {@code internalEnvironment}
   * @throws InfrastructureException when applying Workspace.Next objects fails
   */
  void apply(InternalEnvironment internalEnvironment, Collection<CheService> cheServices)
      throws InfrastructureException;
}

CHE-8265: Add an interface to apply Workspace.Next objects to internal environment

Signed-off-by: Oleksandr Garagatyi <4052944973da826587020fa2673f873866877623@redhat.com>


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

import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
import org.verapdf.model.baselayer.Object;
import org.verapdf.model.impl.BaseTest;
import org.verapdf.model.pdlayer.PDFormField;

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

/**
 * @author Evgeniy Muravitskiy
 */
public class PBoxPDFormFieldTest extends BaseTest {

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

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

		setUp(FILE_RELATIVE_PATH);
		actual = new PBoxPDFormField(document.getDocumentCatalog().getAcroForm().getFields().get(0));
	}

	@Test
	public void testFTMethod() {
		Assert.assertEquals(FORM_TYPE, ((PDFormField) actual).getFT());
	}

	@Test
	public void testAdditionalActionLink() {
		List<? extends Object> additionalActions = actual.getLinkedObjects(PBoxPDFormField.ADDITIONAL_ACTION);
		Assert.assertEquals(0, additionalActions.size());
		for (Object object : additionalActions) {
			Assert.assertTrue("PDAction".equals(object.getType()) || "PDNamedAction".equals(object.getType()));
		}
	}

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

		document.close();
	}
}

Add test for form fields

Add test for form fields


package arez.integration.observable;

import arez.annotations.ArezComponent;
import arez.annotations.Feature;
import arez.annotations.Observable;
import arez.integration.AbstractArezIntegrationTest;
import arez.integration.util.SpyEventRecorder;
import java.util.concurrent.atomic.AtomicInteger;
import org.testng.annotations.Test;
import static org.testng.Assert.*;

public class ObservableDefaultReadAndWriteOutsideTransactionTest
  extends AbstractArezIntegrationTest
{
  @ArezComponent( defaultReadOutsideTransaction = Feature.ENABLE, defaultWriteOutsideTransaction = Feature.ENABLE )
  static abstract class MyComponent
  {
    @Observable
    abstract long getTime();

    abstract void setTime( long value );
  }

  @Test
  public void scenario()
    throws Throwable
  {
    final SpyEventRecorder recorder = SpyEventRecorder.beginRecording();

    final MyComponent component = new ObservableDefaultReadAndWriteOutsideTransactionTest_Arez_MyComponent();

    // Read outside a transaction
    assertEquals( component.getTime(), 0L );

    final AtomicInteger callCount = new AtomicInteger();

    observer( () -> {
      component.getTime();
      callCount.incrementAndGet();
    } );

    assertEquals( callCount.get(), 1 );

    component.setTime( 37L );

    // If gets here it reportObserved so observed re-ran
    assertEquals( callCount.get(), 2 );
    assertEquals( component.getTime(), 37L );

    component.setTime( 42L );

    assertEquals( callCount.get(), 3 );
    assertEquals( component.getTime(), 42L );

    assertMatchesFixture( recorder );
  }
}

Add an integration test that has default read and write outside transaction set


package org.apache.commons.jcs.engine.memory.util;

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

import org.apache.commons.jcs.engine.behavior.ICacheElement;

/**
 * This wrapper is needed for double linked lists.
 */
public class DefaultMemoryElementDescriptor<K, V>
    extends MemoryElementDescriptor<K, V>
{
    /** Don't change */
    private static final long serialVersionUID = -1905161209035522460L;

    /** The CacheElement wrapped by this descriptor */
    private final ICacheElement<K, V> ce;

    /**
     * Constructs a usable MemoryElementDescriptor.
     * <p>
     * @param ce
     */
    public DefaultMemoryElementDescriptor( ICacheElement<K, V> ce )
    {
        super( ce );
        this.ce = ce;
    }

    /**
     * @return the ce
     */
    @Override
    public ICacheElement<K, V> getCacheElement()
    {
        return ce;
    }
}

Make sure the SoftReference can actually be garbage collected.

git-svn-id: fd52ae19693b7be904def34076a5ebbd6e132215@1729183 13f79535-47bb-0310-9956-ffa450edef68


package org.openmhealth.shim.misfit.mapper;

import com.fasterxml.jackson.databind.JsonNode;
import org.openmhealth.schema.domain.omh.*;
import org.openmhealth.shim.common.mapper.DataPointMapperUnitTests;
import org.springframework.core.io.ClassPathResource;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;

import java.io.IOException;
import java.time.OffsetDateTime;
import java.time.ZoneOffset;
import java.util.Collections;
import java.util.List;

import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.notNullValue;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.greaterThan;
import static org.openmhealth.schema.domain.omh.DurationUnit.SECOND;
import static org.openmhealth.schema.domain.omh.LengthUnit.MILE;
import static org.openmhealth.shim.misfit.mapper.MisfitDataPointMapper.RESOURCE_API_SOURCE_NAME;

/**
 * @author Emerson Farrugia
 */
public class MisfitPhysicalActivityDataPointMapperUnitTests extends DataPointMapperUnitTests {

    private final MisfitPhysicalActivityDataPointMapper mapper = new MisfitPhysicalActivityDataPointMapper();

    private JsonNode responseNode;

    @BeforeTest
    public void initializeResponseNode() throws IOException {

        ClassPathResource resource = new ClassPathResource("org/openmhealth/shim/misfit/sessions.json");
        responseNode = objectMapper.readTree(resource.getInputStream());
    }

    @Test
    public void asDataPointsShouldReturnCorrectNumberOfDataPoints() {

        List<DataPoint<PhysicalActivity>> dataPoints = mapper.asDataPoints(Collections.singletonList(responseNode));

        assertThat(dataPoints, notNullValue());
        assertThat(dataPoints.size(), equalTo(3));
    }

    @Test
    public void asDataPointsShouldReturnCorrectDataPoints() {

        List<DataPoint<PhysicalActivity>> dataPoints = mapper.asDataPoints(Collections.singletonList(responseNode));

        assertThat(dataPoints, notNullValue());
        assertThat(dataPoints.size(), greaterThan(0));

        TimeInterval effectiveTimeInterval = TimeInterval.ofStartDateTimeAndDuration(
                OffsetDateTime.of(2015, 4, 13, 11, 46, 0, 0, ZoneOffset.ofHours(-7)),
                new DurationUnitValue(SECOND, 1140.0));

        PhysicalActivity physicalActivity = new PhysicalActivity.Builder("Walking")
                .setDistance(new LengthUnitValue(MILE, 0.9371))
                .setEffectiveTimeFrame(effectiveTimeInterval)
                .build();

        DataPoint<PhysicalActivity> dataPoint = dataPoints.get(0);

        assertThat(dataPoint.getBody(), equalTo(physicalActivity));

        DataPointAcquisitionProvenance acquisitionProvenance = dataPoint.getHeader().getAcquisitionProvenance();

        assertThat(acquisitionProvenance, notNullValue());
        assertThat(acquisitionProvenance.getSourceName(), equalTo(RESOURCE_API_SOURCE_NAME));
        assertThat(acquisitionProvenance.getAdditionalProperty("external_id").isPresent(), equalTo(true));
        assertThat(acquisitionProvenance.getAdditionalProperty("external_id").get(),
                equalTo("552eab896c59ae1f7300003e"));
    }
}

Add Misfit physical activity mapper tests


/*
 * Copyright 2015-2016 the original author or authors.
 *
 * All rights reserved. This program and the accompanying materials are
 * made available under the terms of the Eclipse Public License v1.0 which
 * accompanies this distribution and is available at
 *
 * http://www.eclipse.org/legal/epl-v10.html
 */

package org.junit.jupiter.engine.vintage.rulesupport;

import org.junit.Rule;
import org.junit.jupiter.api.extension.ExtendWith;
import org.junit.rules.ErrorCollector;

@ExtendWith(VerifierSupport.class)
public class VerifierSupportForErrorCollectorFieldTests {

	@Rule
	public ErrorCollector collector = new ErrorCollector();

	// TODO: this test does expose the correct behavior
	// - is there a way to formalize this in junit 5 without failing the test?
	// the expected org.junit.internal.runners.model.MultipleFailureException is only thrown
	// after the test method itself...
	// @Test
	void addingTwoThrowablesToErrorCollectorFailsLate() {
		collector.addError(new Throwable("first thing went wrong"));
		collector.addError(new Throwable("second thing went wrong"));
	}

}

Add  integration test for Verifier-rules using ErrorCollector example from JUnit 4

This test would fail correctly if commented in so serves as documentation only.

#433


package org.jenkinsci.plugins.relution_publisher.model;

import hudson.model.Result;

/**
 * Interface definition for a class that holds a {@link Result}.
 */
public interface ResultHolder {

    /**
     * @return The {@link Result}.
     */
    Result getResult();

    /**
     * Sets the result to the specified value.
     * @param result The {@link Result} to set.
     */
    void setResult(final Result result);
}

Add interface for classes that have a result.


package com.aviras.mrassistant.models;

import io.realm.RealmObject;
import io.realm.annotations.PrimaryKey;

/**
 * Represent medicine
 * <p/>
 * Created by ashish on 8/6/16.
 */
public class Medicine extends RealmObject {

    @PrimaryKey
    private int id;

    private String name;

    private Unit unit;

    public int getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Unit getUnit() {
        return unit;
    }

    public void setUnit(Unit unit) {
        this.unit = unit;
    }
}

Add model to represent medicine

Add model to represent medicine


/*
 * Copyright 2009-2010 by The Regents of the University of California
 * 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 from
 *
 *     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 edu.uci.ics.hyracks.client.net;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.SocketAddress;

import edu.uci.ics.hyracks.comm.channels.IChannelConnectionFactory;
import edu.uci.ics.hyracks.net.exceptions.NetException;
import edu.uci.ics.hyracks.net.protocols.muxdemux.ChannelControlBlock;
import edu.uci.ics.hyracks.net.protocols.muxdemux.MultiplexedConnection;
import edu.uci.ics.hyracks.net.protocols.muxdemux.MuxDemux;
import edu.uci.ics.hyracks.net.protocols.muxdemux.MuxDemuxPerformanceCounters;

public class ClientNetworkManager implements IChannelConnectionFactory {
    private static final int MAX_CONNECTION_ATTEMPTS = 5;

    private final MuxDemux md;

    public ClientNetworkManager(int nThreads)
            throws IOException {
        md = new MuxDemux(nThreads, MAX_CONNECTION_ATTEMPTS);
    }

    public void start() throws IOException {
        md.start();
    }

    public void stop() {

    }

    public ChannelControlBlock connect(SocketAddress remoteAddress) throws InterruptedException, NetException {
        MultiplexedConnection mConn = md.connect((InetSocketAddress) remoteAddress);
        return mConn.openChannel();
    }

    public MuxDemuxPerformanceCounters getPerformanceCounters() {
        return md.getPerformanceCounters();
    }
}

Implement a network manager for the dataset clients to talk to the result distributing nodes.

git-svn-id: 45400e483b316c70cab0969c275555ef2720fd29@2511 123451ca-8445-de46-9d55-352943316053


package sfBugs;

import java.io.Serializable;
import java.util.List;

public class RFE2958584
    implements Serializable
{
  private static final long serialVersionUID = 1L;
  private List<NotSerializable> list; // Not findbugs warning here.
  private NotSerializable ns;// Findbugs gives a proper warning here.

  static class NotSerializable
  {

  }
}

Add testcase for RFE 2958584

Add testcase for RFE 2958584

git-svn-id: e7d6bde23f017c9ff4efd468d79d66def666766b@12187 eae3c2d3-9b19-0410-a86e-396b6ccb6ab3


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

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

/**
 * @author bjorncs
 */
public class BlockingRequestFilter implements SecurityRequestFilter {

    @Override
    public void filter(DiscFilterRequest request, ResponseHandler handler) {
        Response response = new Response(Response.Status.FORBIDDEN);
        try (FastContentWriter writer = ResponseDispatch.newInstance(response).connectFastWriter(handler)) {
            writer.write("Forbidden to access this API");
        }
    }
}

Add simple security filters that returns 403 forbidden


package com.vladmihalcea.book.hpjp.hibernate.mapping.calculated;

import com.vladmihalcea.book.hpjp.util.AbstractPostgreSQLIntegrationTest;
import org.hibernate.annotations.Formula;
import org.junit.Test;

import javax.persistence.*;
import java.sql.Timestamp;
import java.time.LocalDateTime;
import java.util.Date;

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

/**
 * @author Vlad Mihalcea
 */
public class FormulaCurrentDateTest extends AbstractPostgreSQLIntegrationTest {

    @Override
    protected Class<?>[] entities() {
        return new Class<?>[] {
            Event.class,
        };
    }

    @Test
    public void test() {
        doInJPA(entityManager -> {
            Event event = new Event();
            event.setId(1L);

            entityManager.persist(event);
        });
        doInJPA(entityManager -> {
            Event event = entityManager.find(Event.class, 1L);

            assertNotNull(event.getCreatedOn());
        });
    }

    @Entity(name = "Event")
    @Table(name = "event")
    public static class Event {

        @Id
        private Long id;

        @Formula("(SELECT current_date)")
        @Temporal(TemporalType.TIMESTAMP)
        private Date createdOn;

        public Long getId() {
            return id;
        }

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

        public Date getCreatedOn() {
            return createdOn;
        }

        public void setCreatedOn(Date createdOn) {
            this.createdOn = createdOn;
        }
    }
}

Add @Formula test with currentdate

Add @Formula test with currentdate


package uk.ac.ebi.quickgo.annotation.controller;

import uk.ac.ebi.quickgo.annotation.AnnotationREST;
import uk.ac.ebi.quickgo.rest.metadata.MetaDataConfigProperties;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.FileSystemResource;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.ResultActions;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;

import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

/**
 * Test the failure to load the metadata information.
 *
 * @author Tony Wardell
 * Date: 09/03/2017
 * Time: 13:53
 * Created with IntelliJ IDEA.
 */
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = {AnnotationREST.class})
@WebAppConfiguration
public class AnnotationControllerMetaDataSourceFailIT {
    private static final String RESOURCE_URL = "/annotation";
    private MockMvc mockMvc;

    @Autowired
    private WebApplicationContext webApplicationContext;

    @Before
    public void setup() {
        mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();

    }

    // ------------------------------- Check about information -------------------------------

    @Test
    public void about() throws Exception {
        ResultActions response = mockMvc.perform(get(RESOURCE_URL + "/about"));

        response.andDo(print())
                .andExpect(status().isInternalServerError());
    }

    /**
     * Configure properties used by co-term generation, using test values.
     */
    @Configuration
    public static class TestConfig {
        @Primary
        @Bean
        public MetaDataConfigProperties primaryMetaDataConfigProperties() {
            MetaDataConfigProperties properties = new MetaDataConfigProperties();
            FileSystemResource fileSystemResource = new FileSystemResource("/does/not/exist");
            properties.setSource(fileSystemResource);
            return properties;
        }
    }

}

Test the failure to load the source of metadata information for annotations.


/* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*-
 *
 * The contents of this file are subject to the Netscape Public
 * License Version 1.1 (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.mozilla.org/NPL/
 *
 * Software distributed under the License is distributed on an "AS
 * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
 * implied. See the License for the specific language governing
 * rights and limitations under the License.
 *
 * The Original Code is Rhino code, released
 * May 6, 1998.
 *
 * The Initial Developer of the Original Code is Netscape
 * Communications Corporation.  Portions created by Netscape are
 * Copyright (C) 1997-1999 Netscape Communications Corporation. All
 * Rights Reserved.
 *
 * Contributor(s):
 * Norris Boyd
 *
 * Alternatively, the contents of this file may be used under the
 * terms of the GNU Public License (the "GPL"), in which case the
 * provisions of the GPL are applicable instead of those above.
 * If you wish to allow use of your version of this file only
 * under the terms of the GPL and not to allow others to use your
 * version of this file under the NPL, indicate your decision by
 * deleting the provisions above and replace them with the notice
 * and other provisions required by the GPL.  If you do not delete
 * the provisions above, a recipient may use your version of this
 * file under either the NPL or the GPL.
 */

import org.mozilla.javascript.*;

/**
 * An example WrapFactory that can be used to avoid wrapping of Java types
 * that can be converted to ECMA primitive values.
 * So java.lang.String is mapped to ECMA string, all java.lang.Numbers are
 * mapped to ECMA numbers, and java.lang.Booleans are mapped to ECMA booleans
 * instead of being wrapped as objects. Additionally java.lang.Characters are
 * converted to ECMA strings. Other types have the default behavior.
 *

 * Note that calling "new java.lang.String('foo')" in JavaScript with this
 * wrap factory enabled will still produce a wrapped Java object since the
 * WrapFactory.wrapNewObject method is not overridden.
 *

 * The PrimitiveWrapFactory is enabled on a Context by calling setWrapFactory
 * on that context.
 */
public class PrimitiveWrapFactory extends WrapFactory {

  public Object wrap(Context cx, Scriptable scope, Object obj,
                     Class staticType)
  {
    if (obj instanceof String || obj instanceof Number ||
        obj instanceof Boolean)
    {
      return obj;
    } else if (obj instanceof Character) {
      char[] a = { ((Character)obj).charValue() };
      return new String(a);
    }
    return super.wrap(cx, scope, obj, staticType);
  }
}

Add example of the use of a WrapFactory.


/**
 * 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-2014 the original author or authors.
 */
package org.assertj.db.api.assertions;

import org.assertj.core.api.Assertions;
import org.assertj.db.api.ChangesAssert;
import org.assertj.db.common.AbstractTest;
import org.assertj.db.common.NeedReload;
import org.assertj.db.type.Changes;
import org.assertj.db.type.Request;
import org.assertj.db.type.Table;
import org.junit.Test;

import static org.assertj.db.api.Assertions.assertThat;
import static org.junit.Assert.fail;

/**
 * Tests on {@link org.assertj.db.api.assertions.AssertOnNumberOfChanges} class :
 * {@link org.assertj.db.api.assertions.AssertOnNumberOfChanges#hasNumberOfChanges(int)} method.
 *
 * @author Régis Pouiller
 *
 */
public class AssertOnNumberOfChanges_HasNumberOfChanges_Test extends AbstractTest {

  /**
   * This method tests the {@code hasNumberOfChanges} assertion method.
   */
  @Test
  @NeedReload
  public void test_has_number_of_changes() throws Exception {
    Table table = new Table(source, "actor");
    Changes changes = new Changes(table).setStartPointNow();
    updateChangesForTests();
    changes.setEndPointNow();

    ChangesAssert changesAssert = assertThat(changes);
    ChangesAssert changesAssert2 = changesAssert.hasNumberOfChanges(3);
    Assertions.assertThat(changesAssert).isSameAs(changesAssert2);
  }

  /**
   * This method should fail because the number of changes is different.
   */
  @Test
  @NeedReload
  public void should_fail_because_number_of_changes_is_different() throws Exception {
    Request request = new Request(source, "select * from actor");
    Changes changes = new Changes(request).setStartPointNow();
    updateChangesForTests();
    changes.setEndPointNow();

    try {
      assertThat(changes).hasNumberOfChanges(9);
      fail("An exception must be raised");
    } catch (AssertionError e) {
      Assertions.assertThat(e.getMessage()).isEqualTo("[Changes on 'select * from actor' request of 'sa/jdbc:h2:mem:test' source] \n"
                                                      + "Expecting size (number of changes) to be equal to :\n"
                                                      + "   <9>\n"
                                                      + "but was:\n"
                                                      + "   <4>");
    }
  }
}

Add tests on AssertOnNumberOfChanges assertion method


package com.yahoo.config.model.api.container;

import org.junit.Test;

import static com.yahoo.config.model.api.container.ContainerServiceType.CLUSTERCONTROLLER_CONTAINER;
import static com.yahoo.config.model.api.container.ContainerServiceType.CONTAINER;
import static com.yahoo.config.model.api.container.ContainerServiceType.LOGSERVER_CONTAINER;
import static com.yahoo.config.model.api.container.ContainerServiceType.METRICS_PROXY_CONTAINER;
import static com.yahoo.config.model.api.container.ContainerServiceType.QRSERVER;
import static org.junit.Assert.assertEquals;

/**
 * @author gjoranv
 */
public class ContainerServiceTypeTest {

    @Test
    public void new_values_are_not_added_without_updating_tests() {
        assertEquals(5, ContainerServiceType.values().length);
    }

    @Test
    public void service_names_do_not_change() {
        assertEquals("container", CONTAINER.serviceName);
        assertEquals("qrserver", QRSERVER.serviceName);
        assertEquals("container-clustercontroller", CLUSTERCONTROLLER_CONTAINER.serviceName);
        assertEquals("logserver-container", LOGSERVER_CONTAINER.serviceName);
        assertEquals("metrics-proxy-container", METRICS_PROXY_CONTAINER.serviceName);
    }

}

Add unit test to ensure names don't change.


package org.realityforge.replicant.client.gwt;

import com.google.gwt.user.client.rpc.AsyncCallback;
import java.util.Objects;
import javax.annotation.Nonnull;

public final class ReplicantGwtRpcAsyncCallback<T>
  implements AsyncCallback<T>
{
  @Nonnull
  private final replicant.Request _r;
  @Nonnull
  private final AsyncCallback<T> _callback;

  public ReplicantGwtRpcAsyncCallback( @Nonnull final replicant.Request r, @Nonnull final AsyncCallback<T> callback )
  {
    _r = Objects.requireNonNull( r );
    _callback = Objects.requireNonNull( callback );
  }

  @Override
  public void onSuccess( final T result )
  {
    _r.onSuccess( false, () -> _callback.onSuccess( result ) );
  }

  @Override
  public void onFailure( final Throwable caught )
  {
    _r.onFailure( () -> _callback.onFailure( caught ) );
  }
}

Add an adapter for gwt-rpc calls

Add an adapter for gwt-rpc calls


package de.fu_berlin.cdv.chasingpictures.api;

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;

import java.util.List;

/**
 * @author Simon Kalt
 */
@JsonIgnoreProperties(value = {"data"}, ignoreUnknown = true)
public class PictureApiResult extends ApiResult<List<Picture>> {
    public List<Picture> getPictures() {
        return getData();
    }

    public void setPictures(List<Picture> pictures) {
        setData(pictures);
    }
}

Add API result object for picture requests


package org.svetovid.util;

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

public class CompoundList<E> extends AbstractList<E> {

    private List<List<E>> lists = new ArrayList<>();

    public CompoundList() {
    }

    @SafeVarargs
    public CompoundList(List<E>... lists) {
        for (List<E> list : lists) {
            this.lists.add(list);
        }
    }

    public List<E> getSublist(int index) {
        return lists.get(index);
    }

    public void setSublist(int index, List<E> list) {
        lists.set(index, list);
    }

    public int addSublist(List<E> list) {
        lists.add(list);
        return lists.size() - 1;
    }

    public int insertSublist(int index, List<E> list) {
        lists.add(index, list);
        return index;
    }

    public List<E> removeSublist(int index) {
        return lists.remove(index);
    }

    @Override
    public int size() {
        int size = 0;
        for (List<E> list : lists) {
            if (list == null) {
                continue;
            }
            size = size + list.size();
        }
        return size;
    }

    @Override
    public E get(int index) {
        if (index < 0) {
            throw new IndexOutOfBoundsException("Index: " + index);
        }
        int totalSize = 0;
        for (List<E> list : lists) {
            if (list == null) {
                continue;
            }
            int size = list.size();
            if (index < size) {
                return list.get(index);
            }
            index = index - size;
            totalSize = totalSize + size;
        }
        throw new IndexOutOfBoundsException("Index: " + index + ", Size: " + totalSize);
    }

    @Override
    public Object[] toArray() {
        Object[][] arrays = new Object[lists.size()][];
        int size = 0;
        for (int i = 0; i < lists.size(); i++) {
            List<E> list = lists.get(i);
            if (list == null) {
                continue;
            }
            arrays[i] = list.toArray();
            size = size + arrays[i].length;
        }
        Object[] array = new Object[size];
        int index = 0;
        for (Object[] arr : arrays) {
            System.arraycopy(arr, 0, array, index, arr.length);
            index = index + arr.length;
        }
        return array;
    }

    @SuppressWarnings("unchecked")
    @Override
    public <T> T[] toArray(T[] a) {
        Object[] array = toArray();
        if (a.length < array.length) {
            return (T[]) array;
        }
        System.arraycopy(array, 0, a, 0, array.length);
        return a;
    }
}

Add a list implementation that is a live view of concatenation of multiple lists


package com.codenvy.ide.ext.datasource.client.properties;

import com.google.gwt.i18n.client.Constants;

public interface DataEntityPropertiesConstants extends Constants {

    @DefaultStringValue("Product name")
    String productNameLabel();

    @DefaultStringValue("Product version")
    String productVersionLabel();

    @DefaultStringValue("User name")
    String usernameLabel();

    @DefaultStringValue("Primary key")
    String primaryKeyLabel();

    @DefaultStringValue("Table type")
    String tableTypeLabel();

    @DefaultStringValue("Data type")
    String dataTypeLabel();

    @DefaultStringValue("Column size")
    String columnSizeLabel();

    @DefaultStringValue("Decimal digits")
    String decimalDigitsLabel();

    @DefaultStringValue("Nullable")
    String nullableLabel();

    @DefaultStringValue("Default value")
    String defaultValueLabel();

    @DefaultStringValue("None")
    String noValue();
}

Add a constant class for database entity properties


/*-
 * Copyright 2017 Diamond Light Source Ltd.
 *
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 */

package org.eclipse.dawnsci.analysis.dataset;

import java.lang.ref.SoftReference;
import java.util.IdentityHashMap;
import java.util.Map;

import org.eclipse.dawnsci.analysis.dataset.impl.function.DatasetToDatasetFunction;
import org.eclipse.january.dataset.Dataset;
import org.eclipse.january.dataset.DatasetUtils;
import org.eclipse.january.dataset.IDataset;

/**
 * Cache of computed dataset values
 */
public class DatasetCache {

	private DatasetToDatasetFunction function;
	private Map<IDataset, SoftReference<Dataset>> map;

	/**
	 * Create a cache for given function
	 * @param function
	 */
	public DatasetCache(DatasetToDatasetFunction function) {
		this.function = function;
		map = new IdentityHashMap<IDataset, SoftReference<Dataset>>();
	}

	/**
	 * Retrieve computed value (evaluate if not cached)
	 * @param input
	 * @return computed value
	 */
	public Dataset get(IDataset input) {
		SoftReference<Dataset> ref = map.get(input);
		Dataset output;
		if (ref == null || ref.get() == null) {
			output = DatasetUtils.convertToDataset(function.value(input).get(0));
			map.put(input, new SoftReference<Dataset>(output));
		} else {
			output = ref.get();
		}
		return output;
	}

	/**
	 * Remove entry from cache
	 * @param input
	 * @return true if was cached
	 */
	public boolean remove(Dataset input) {
		SoftReference<Dataset> ref = map.remove(input);
		if (ref == null || ref.get() == null) {
			return false;
		}
		ref.clear();
		return true;
	}

	/**
	 * Clear cache
	 */
	public void clear() {
		map.clear();
	}
}

Add new cache to store computed datasets


package benchmarking;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.reflect.Field;
import java.util.Date;

public class CpuMonitor {
    private boolean continueMonitoring = true;
    private StringBuilder commandOutput;
    private Date date;

    public void startMonitoring(){
        boolean firstAppearance = true;

        Thread cpuMonit = new Thread(new Runnable() {
            @Override
            public void run() {
                String line;
                Process process;
                commandOutput = new StringBuilder();

                String processPid = getPid();
                String[] cmd = {
                        "/bin/sh",
                        "-c",
                        " atop 1 -a | unbuffer -p awk '/" + processPid + "|nmap/ {print $1 \" \" $11}'"
                };

                try {
                    process = Runtime.getRuntime().exec(cmd);
                    Field pid = process.getClass().getDeclaredField("pid");
                    pid.setAccessible(true);
                    BufferedReader br = new BufferedReader(new InputStreamReader(process.getInputStream()));

                    while ( continueMonitoring && (line = br.readLine()) != null) {
                        if (firstAppearance  && line.contains(processPid)) {
                            date = new Date();
                        }
                        commandOutput.append(line + "\n");
                    }
                    process.destroy();
                } catch (IOException e) {
                    System.err.println(e.getStackTrace());
                } catch (NoSuchFieldException e) {
                    e.printStackTrace();
                }

                //System.out.println("Command output: " + commandOutput.toString());
            }
        });
        cpuMonit.start();
    }

    public String parseForPid(long pid) {
        stopMonitoring();
        String cmdOut = commandOutput.toString();
        StringBuilder parsedResultsAfterPid = new StringBuilder();

        String[] outputLines = cmdOut.split(System.getProperty("line.separator"));
        for (String line : outputLines) {
            String[] processData = line.split(" ");
            try {
                long resultsPid = Long.parseLong(processData[0]);
                String cpuUsage = processData[1];
                if (resultsPid == pid) {
                    parsedResultsAfterPid.append(resultsPid + "," + cpuUsage + "\n");
                }
            } catch (NumberFormatException e) {
                e.printStackTrace();
            }
        }

        return parsedResultsAfterPid.toString();
    }

    private static String getPid() {
        String processName = java.lang.management.ManagementFactory.getRuntimeMXBean().getName();
        return processName.split("@")[0];
    }

    public void stopMonitoring() {
        continueMonitoring = false;
    }
}

Add monitoring class for CPU usage.

Add monitoring class for CPU usage.


// Use continue with a label.
class ContToLabel {
	public static void main(String args[]) {

outerloop:
		for(int i=1; i < 10; i++) {
			System.out.print("\nOuter loop pass " + i + ", Inner loop: ");

			for(int j = 1; j < 10; j++) {
				if(j == 5) continue outerloop; // continue outer loop
				System.out.print(j);
			}
		}
	}
}

Use continue with a label

Use continue with a label


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

package com.google.enterprise.connector.util.diffing;

import com.google.enterprise.connector.spi.TraversalSchedule;
import com.google.enterprise.connector.util.diffing.ChangeQueue;
import com.google.enterprise.connector.util.diffing.ChangeQueue.DefaultCrawlActivityLogger;

import java.sql.Timestamp;
import java.util.ArrayList;
import junit.framework.TestCase;

/**
 * Tests for {@link DocumentSnapshotRepositoryMonitorManagerImpl}.
 */
public class DocumentSnapshotRepositoryMonitorManagerImplTest extends TestCase {

  // Borrowed from filesystem connector's  MockTraversalSchedule.java
  public class MockTraversalSchedule implements TraversalSchedule {
    private final int load;
    private final int retryDelay;
    private final boolean isDisabled;
    private final boolean inInterval;

    public MockTraversalSchedule() {
      this(500, -1, false, true);
    }

    public MockTraversalSchedule(int load, int retryDelay, boolean isDisabled,
                                 boolean inInterval) {
      this.load = load;
      this.retryDelay = retryDelay;
      this.isDisabled = isDisabled;
      this.inInterval = inInterval;
    }

    /** Returns the target traversal rate in documents per minute. */
    /* @Override */
    public int getTraversalRate() {
      return load;
    }

    /** Returns the number of seconds to delay after finding no new content. */
    /* @Override */
    public int getRetryDelay() {
      return retryDelay;
    }

    /** Returns {@code true} if the traversal schedule is disabled. */
    /* @Override */
    public boolean isDisabled() {
      return isDisabled;
    }

    /**
     * Returns {@code true} if the current time is within a scheduled travesal
     * interval.
     */
    /* @Override */
    public boolean inScheduledInterval() {
      return inInterval;
    }

    /* @Override */
    public int nextScheduledInterval() {
      return -1;
    }

    /**
     * Returns {@code true} if traversals could run at this time,
     * equivalent to <pre>!isDisabled() && inScheduledInterval()</pre>.
     */
    /* @Override */
    public boolean shouldRun() {
      return !isDisabled() && inScheduledInterval();
    }
  }

  public void testSetTraversalSchedule() {
    ChangeQueue queue;
    queue = new ChangeQueue(10, 0L, null);

    DocumentSnapshotRepositoryMonitorManagerImpl manager =
        new DocumentSnapshotRepositoryMonitorManagerImpl(
            new ArrayList<SnapshotRepository<? extends DocumentSnapshot>>(), null, null, null,
            queue, null);

    assertEquals(0, queue.getSleepInterval());
    manager.setTraversalSchedule(new MockTraversalSchedule(500, 8074, false, false));
    assertEquals(8074000, queue.getSleepInterval());
  }
}

Add a new test for DocumentSnapshotRepositoryMonitorManagerImpl


package com.github.rnowling.bps.datagenerator.datareaders;

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

import java.util.List;

import org.junit.Test;

import com.github.rnowling.bps.datagenerator.Constants;
import com.github.rnowling.bps.datagenerator.datamodels.inputs.ZipcodeRecord;

public class TestZipcodeReader
{

	@Test
	public void testRead() throws Exception
	{
		ZipcodeReader reader = new ZipcodeReader();
		reader.setCoordinatesFile(Constants.COORDINATES_FILE);
		reader.setIncomesFile(Constants.INCOMES_FILE);
		reader.setPopulationFile(Constants.POPULATION_FILE);

		List<ZipcodeRecord> zipcodes = reader.readData();

		assertTrue(zipcodes.size() > 0);

		assertNotNull(zipcodes.get(0));
		assertNotNull(zipcodes.get(0).getCoordinates());
		assertNotNull(zipcodes.get(0).getMedianHouseholdIncome());
		assertNotNull(zipcodes.get(0).getPopulation());
		assertNotNull(zipcodes.get(0).getZipcode());
	}

}

Add unit test for ZipcodeReader

Add unit test for ZipcodeReader