package org.verapdf.model.visitor.cos.pb;

import org.apache.pdfbox.cos.*;
import org.verapdf.model.impl.pb.cos.*;

import java.io.IOException;

/**
 * Created by Evgeniy on 5/16/2015.
 */
public final class PBCosVisitor implements ICOSVisitor {

    @Override
    public Object visitFromArray(COSArray obj) throws IOException {
        return new PBCosArray(obj);
    }

    @Override
    public Object visitFromBoolean(COSBoolean obj) throws IOException {
        return new PBCosBool(obj);
    }

    @Override
    public Object visitFromDictionary(COSDictionary obj) throws IOException {
        return new PBCosDict(obj);
    }

    @Override
    public Object visitFromDocument(COSDocument obj) throws IOException {
        return new PBCosDocument(obj);
    }

    @Override
    public Object visitFromFloat(COSFloat obj) throws IOException {
        return new PBCosReal(obj);
    }

    @Override
    public Object visitFromInt(COSInteger obj) throws IOException {
        return new PBCosInteger(obj);
    }

    @Override
    public Object visitFromName(COSName obj) throws IOException {
        return new PBCosName(obj);
    }

    @Override
    public Object visitFromNull(COSNull obj) throws IOException {
        return PBCosNull.NULL;
    }

    @Override
    public Object visitFromStream(COSStream obj) throws IOException {
        return new PBCosStream(obj);
    }

    @Override
    public Object visitFromString(COSString obj) throws IOException {
        return new PBCosString(obj, false);
    }
}

Add support of visitor pattern for creating object


/**
 * The {@code topology} package contains neuron grid strategy classes for
 * customizing self-organizing maps.  These classes are intended to be
 * instantiated and immediately given to a SOM.  All classes in this package
 * implement {@link cs437.som.GridType}.
 */
package cs437.som.topology;

Add a package annotation to topology.

Add a package annotation to topology.


/**
 * Created on 2008-6-21 上午06:53:10
 */
package cn.net.openid.jos.web.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.springframework.web.servlet.ModelAndView;

import cn.net.openid.jos.web.AbstractJosController;

/**
 * @author Sutra Zhou
 *
 */
public class SetPrimaryEmailController extends AbstractJosController {

	/*
	 * (non-Javadoc)
	 *
	 * @see org.springframework.web.servlet.mvc.Controller#handleRequest(javax.servlet.http.HttpServletRequest,
	 *      javax.servlet.http.HttpServletResponse)
	 */
	public ModelAndView handleRequest(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		String id = request.getParameter("id");
		if (!StringUtils.isEmpty(id)) {
			josService.setPrimaryEmail(getUser(request), id);
		}
		request.getRequestDispatcher("/email").forward(request, response);
		return null;
	}

}

Add support: set primary email address.

Add support: set primary email address.


package net.kencochrane.raven.marshaller;

import mockit.Injectable;
import mockit.Tested;
import mockit.Verifications;
import org.testng.annotations.Test;

import java.io.OutputStream;

public class UncloseableOutputStreamTest {
    @Tested
    private Marshaller.UncloseableOutputStream uncloseableOutputStream = null;
    @Injectable
    private OutputStream mockOutputStream = null;

    @Test
    public void testWriteSingleByte() throws Exception {
        final int i = 12;

        uncloseableOutputStream.write(i);

        new Verifications() {{
            mockOutputStream.write(i);
        }};
    }

    @Test
    public void testWriteByteArray() throws Exception {
        final byte[] array = new byte[0];

        uncloseableOutputStream.write(array);

        new Verifications() {{
            mockOutputStream.write(array);
        }};
    }

    @Test
    public void testWritePartOfByteArray() throws Exception {
        final byte[] array = new byte[0];
        final int off = 93;
        final int len = 42;

        uncloseableOutputStream.write(array, off, len);

        new Verifications() {{
            mockOutputStream.write(array, off, len);
        }};
    }

    @Test
    public void testFlush() throws Exception {
        uncloseableOutputStream.flush();

        new Verifications() {{
            mockOutputStream.flush();
        }};

    }

    @Test
    public void testClose() throws Exception {
        uncloseableOutputStream.close();

        new Verifications() {{
            mockOutputStream.close();
            times = 0;
        }};
    }
}

Add test coverage for the UncloseableOutputStream


package net.kencochrane.raven.event.helper;

import net.kencochrane.raven.event.EventBuilder;
import net.kencochrane.raven.event.interfaces.SentryInterface;
import net.kencochrane.raven.servlet.RavenServletRequestListener;
import org.junit.Before;
import org.junit.Test;
import org.mockito.ArgumentCaptor;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;

import javax.servlet.ServletRequestEvent;
import javax.servlet.http.HttpServletRequest;

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.notNullValue;
import static org.mockito.Mockito.*;

public class HttpEventBuilderHelperTest {
    @Mock
    private EventBuilder eventBuilder;
    private HttpEventBuilderHelper httpEventBuilderHelper;

    private static void simulateRequest(HttpServletRequest request) {
        RavenServletRequestListener ravenServletRequestListener = new RavenServletRequestListener();
        ServletRequestEvent servletRequestEvent = mock(ServletRequestEvent.class);
        when(servletRequestEvent.getServletRequest()).thenReturn(request);
        ravenServletRequestListener.requestInitialized(servletRequestEvent);
    }

    @Before
    public void setUp() throws Exception {
        MockitoAnnotations.initMocks(this);
        httpEventBuilderHelper = new HttpEventBuilderHelper();
    }

    @Test
    public void testNoRequest() throws Exception {
        httpEventBuilderHelper.helpBuildingEvent(eventBuilder);

        verify(eventBuilder, never()).addSentryInterface(any(SentryInterface.class));
    }

    @Test
    public void testWithRequest() throws Exception {
        simulateRequest(mock(HttpServletRequest.class));
        ArgumentCaptor<SentryInterface> interfaceCaptor = ArgumentCaptor.forClass(SentryInterface.class);

        httpEventBuilderHelper.helpBuildingEvent(eventBuilder);

        verify(eventBuilder).addSentryInterface(interfaceCaptor.capture());
        assertThat(interfaceCaptor.getValue(), is(notNullValue()));
    }
}

Add unit tests to check HttpEventBuilderHelper


package com.gurkensalat.android.xingsync.api;

import static org.hamcrest.core.Is.is;
import static org.hamcrest.core.IsEqual.equalTo;
import static org.hamcrest.core.IsNot.not;
import static org.junit.Assert.assertThat;

import java.util.List;

import org.json.JSONException;
import org.json.JSONObject;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;

@RunWith(JUnit4.class)
public class ContactsCallTest
{
	private ContactsCall testable;

	private JSONObject json;

	@Before
	public void setupMocks()
	{
		testable = new ContactsCall();
		// ContactsCall_.getInstance_(null);

		assertThat("API Call object could not be created", testable, is(not(equalTo(null))));
	}

	@Before
	public void populateJson() throws JSONException
	{
		StringBuffer sb = new StringBuffer(1024);

		sb.append("{");
		sb.append("  \"contacts\": {");
		sb.append("    \"total\": 297,");
		sb.append("    \"users\": [");
		sb.append("      {");
		sb.append("        \"id\": \"6841253_007b9e\",");
		sb.append("        \"first_name\": \"Hasmet\",");
		sb.append("        \"last_name\": \"Acar\",");
		sb.append("        \"display_name\": \"Hasmet Acar\",");
		sb.append("        \"active_email\": null");
		sb.append("      },");
		sb.append("      {");
		sb.append("        \"id\": \"4261890_ffd916\",");
		sb.append("        \"first_name\": \"Murat\",");
		sb.append("        \"last_name\": \"Acun\",");
		sb.append("        \"display_name\": \"Murat Acun\",");
		sb.append("        \"active_email\": null");
		sb.append("      }");
		sb.append("    ]");
		sb.append("  }");
		sb.append("}");

		JSONObject actual = new JSONObject(sb.toString());
		assertThat("JSON object could not be created", actual, is(not(equalTo(null))));

		json = actual;
	}

	@Test
	public void parseContactsCall() throws JSONException
	{
		List<User> actual = testable.parse(json);
		assertThat("Users list could not be created", actual, is(not(equalTo(null))));
	}
}

Use hamcrest matchers for expressive tests


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

import static org.junit.jupiter.api.condition.OS.LINUX;
import static org.junit.jupiter.api.condition.OS.MAC;
import static org.junit.jupiter.api.condition.OS.WINDOWS;

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

class BuiltinDisabledOnOsTest {

    @DisabledOnOs(LINUX)
    @Test
    void notLinuxTest() {
        System.out.println("Disabled on Linux");
    }

    @DisabledOnOs(WINDOWS)
    @Test
    void notWinTest() {
        System.out.println("Disabled on Windows");
    }

    @DisabledOnOs(MAC)
    @Test
    void notMacTest() {
        System.out.println("Disabled on Mac");
    }

}

Include test using JUnit 5's @DisabledOnOs


package uk.ac.ebi.quickgo.rest.cache;

import java.time.Duration;
import java.time.LocalTime;
import java.util.function.Supplier;

/**
 * This algorithm models the following situation - Start time of caching before end time. So the start and end of
 * caching occurs in one day. Here are the situations this class must deal with
 *
 * After Start Time Before End Time: Re-indexing is not going to take place until after End time. Give clients the time
 * in seconds until End Time will be reached.
 *
 * After End Time and before Start Time: We are around the indexing time. We tell all respondents not to cache - max
 * age is set to zero.
 *
 * See Caching best practices & max-age
 * gotchas,
 * Caching Tutorial for Web Authors and Webmasters,
 * Increasing Application Performance with HTTP Cache Headers | Heroku Dev Center
 *
 * @return a String that holds the number of seconds left before the cut-off time after which requests will not be
 * cached.
 * @author Tony Wardell
 * Date: 10/04/2017
 * Time: 15:47
 * Created with IntelliJ IDEA.
 */
public class MaxAgeWhenStartBeforeEndTime implements Supplier<Duration>{

    private LocalTime start, end;

    public MaxAgeWhenStartBeforeEndTime(LocalTime start, LocalTime end) {
        this.start = start;
        this.end = end;
    }

    @Override public Duration get() {
        Duration remaining;
        final LocalTime now = LocalTime.now();
        if (now.isAfter(start) && now.isBefore(end)) {
            remaining = Duration.between(now, end);
        } else {
            remaining = Duration.ZERO;
        }
        assert !remaining.isNegative();
        return remaining;
    }
}

Create a class to hold max age calculation when start and end time for caching availability is in the same day.


package com.izforge.izpack.compiler.packager.impl;

import static org.junit.Assert.fail;

import java.io.IOException;

import org.junit.Test;

import com.izforge.izpack.compiler.resource.ResourceFinder;

public class PackagerTest {

	@Test
	public void testWritePacks() throws IOException {
		final ResourceFinder resourceFinder = new ResourceFinder(null, null,
				null, null);
		new Packager(null, null, null, null, null, null, null, null, null,
				null, null, resourceFinder).writeManifest();
		fail("Not yet implemented");
	}

}

Create stub for unit test

Create stub for unit test


package jeranvier.util;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Grep2List {

	public static void main(String[] arg){
		List<String> list = new ArrayList<String>();
		list.add("13 46095.097864315517654 7054.386046320822970 46095.097864315517654 7054.386046320822970");
		list.add("this is another test 3 with 2 times this 34");
		list.add("it's a final test for control");
		 for(String result :Grep2List.find("([0-9]+\\.[0-9]+)", list.get(0))){
			 System.out.println(result);
		 }
	}

	public static List<String> find(String stringPattern, String string) {
		if(! stringPattern.matches("\\\\(.*\\\\)")){
			stringPattern="("+stringPattern+")";
		}
		Pattern pattern = Pattern.compile(stringPattern);
		Matcher matcher = pattern.matcher(string);
		List<String> results = new ArrayList<String>();
		while (matcher.find()){
		    results.add(matcher.group(1));
		}
		return results;
	}

}

ADD little tool to return of list of matching grep


package org.mwc.debrief.core.contenttype;

import java.io.IOException;
import java.io.InputStream;

import org.eclipse.core.internal.content.TextContentDescriber;
import org.eclipse.core.runtime.content.IContentDescription;

/** import format test for SATC export files
 *
 * @author ian
 *
 */
@SuppressWarnings("restriction")
public class CSV_GZ_ContentDescriber extends TextContentDescriber
{

	@Override
	public int describe(InputStream contents, IContentDescription description)
			throws IOException
	{
	  return VALID;
	}

}

Create content describer for CSV data-fles


package com.github.sparkcaller.preprocessing;

import htsjdk.samtools.BAMIndexer;
import htsjdk.samtools.SamReader;
import htsjdk.samtools.SamReaderFactory;
import org.apache.spark.api.java.function.Function;

import java.io.File;

public class BamIndexer implements Function<File, File> {
    // Create an index (.bai) file for the given BAM file.
    public File call(File bamFile) throws Exception {
        final SamReader bamReader = SamReaderFactory.makeDefault()
                                              .enable(SamReaderFactory.Option.INCLUDE_SOURCE_IN_RECORDS)
                                              .open(bamFile);
        BAMIndexer.createIndex(bamReader, new File(bamFile.getPath() + ".bai"));

        return bamFile;
    }
}

Add a class which is used to generate BAM indexes, as this is required by several of the tools used later in the pipeline.


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

import java.net.URI;

import com.github.commonsrdf.api.AbstractRDFTermFactoryTest;
import com.github.commonsrdf.api.IRI;
import com.github.commonsrdf.api.RDFTermFactory;

/**
 * Test dummy without relative IRI support.
 * <p?>
 * Ensures that {@link AbstractRDFTermFactoryTest#createIRIRelative()} is
 * correctly skipped (without causing an error.
 *
 */
public class DummyNoRelativeIRIRDFTermFactoryTest extends
		AbstractRDFTermFactoryTest {
	@Override
	public RDFTermFactory createFactory() {
		return new DummyRDFTermFactory() {
			@Override
			public IRI createIRI(String iri) {
				if (!URI.create(iri).isAbsolute()) {
					throw new IllegalArgumentException("IRIs must be absolute");
					// ..in this subclass for testing purposes only :)
				}
				return super.createIRI(iri);
			}
		};
	}
}

Test dummy without relative IRI support

Test dummy without relative IRI support


/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package fi.jgke.tagger.domain;

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

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

    @Test
    public void testSetGetValue() {
        String value = UUID.randomUUID().toString();
        Tag instance = new Tag();
        instance.setValue(value);
        assertEquals(value, instance.getValue());
    }

}

Add simple test for Tag

Add simple test for Tag


package ca.dal.cs.scavenger;

import android.app.Application;

import net.gotev.uploadservice.UploadService;

/**
 * Created by odavi on 11/25/2016.
 */
public class ScavengerApplication extends Application {
    @Override
    public void onCreate() {
        super.onCreate();
        UploadService.NAMESPACE = BuildConfig.APPLICATION_ID;
    }
}

Create Application to use in setting up Android Upload Service


package pl.pkk82.filehierarchygenerator;

import static pl.pkk82.filehierarchygenerator.FileHierarchyGenerator.createRootDirectory;

import org.junit.Test;
import pl.pkk82.filehierarchyassert.FileHierarchyAssert;
import pl.pkk82.filehierarchygenerator.xml.FileContentXml;
import pl.pkk82.filehierarchygenerator.xml.FileContentXmlAssert;
import pl.pkk82.filehierarchygenerator.xml.FileContentXmlGenerator;

public class FileHierarchyGeneratorReadmeExamplesTest {

	private FileHierarchyGenerator fileHierarchyGenerator;
	private FileHierarchy fileHierarchy;
	private FileContentXmlGenerator fileContentXmlGenerator;
	private FileContentXml fileContentXml;

	@Test
	public void shouldGenerateFileHierarchy() {
		givenFileHierarchyGenerator("workspace")
				.directory("subdir1")
				.file("fileInSubdir1")
				.directory("subdir11")
				.file("fileInSubdir11")
				.up().up()
				.file("fileInWorkspace")
				.line("content of fileInWorkspace")
				.generate();
		whenGenerateFileHierarchy();
		thenFileHierarchy().hasCountOfSubdirs(2)
				.hasCountOfFiles(3)
				.containsFile("fileInSubdir1", "subdir1")
				.containsFile("fileInSubdir11", "subdir1", "subdir11")
				.containsFile("fileInWorkspace");
	}

	@Test
	public void shouldGenerateXmlFile() {
		givenXmlFile()
				.withElement("root")
				.withElement("subroot1")
				.withText("value")
				.up()
				.withElement("subroot2")
				.withElement("subroot21")
				.withText("text21")
				.up()
				.withElement("subroot22")
				.withText("text22")
				.formatted();
		whenGenerateXmlFile();
		thenFileContentXml().containsLines(
				"<root>",
				"    <subroot1>value</subroot1>",
				"    <subroot2>",
				"        <subroot21>text21</subroot21>",
				"        <subroot22>text22</subroot22>",
				"    </subroot2>",
				"</root>");

	}

	private void whenGenerateXmlFile() {

		fileContentXml = fileContentXmlGenerator.generate();
	}

	private FileContentXmlAssert thenFileContentXml() {
		return new FileContentXmlAssert(fileContentXml);
	}

	private FileContentXmlGenerator givenXmlFile() {
		fileContentXmlGenerator = FileContentXmlGenerator.createFile("root.xml");
		return fileContentXmlGenerator;
	}

	private FileHierarchyGenerator givenFileHierarchyGenerator(String workspace) {
		fileHierarchyGenerator = createRootDirectory(workspace);
		return fileHierarchyGenerator;
	}

	private FileHierarchy whenGenerateFileHierarchy() {
		fileHierarchy = fileHierarchyGenerator.generate();
		return fileHierarchy;
	}

	private FileHierarchyAssert thenFileHierarchy() {
		return new FileHierarchyAssert(fileHierarchy);
	}
}

Add test with examples from README.md

Add test with examples from README.md


package org.opennms.dashboard.server;

import org.acegisecurity.Authentication;
import org.acegisecurity.GrantedAuthority;
import org.acegisecurity.context.SecurityContextHolder;
import org.acegisecurity.providers.UsernamePasswordAuthenticationToken;
import org.acegisecurity.userdetails.User;
import org.acegisecurity.userdetails.UserDetails;
import org.opennms.test.ThrowableAnticipator;

import junit.framework.TestCase;

public class DefaultSurveillanceServiceTest extends TestCase {
    private DefaultSurveillanceService m_service;

    @Override
    protected void setUp() throws Exception {
        super.setUp();

        m_service = new DefaultSurveillanceService();

        /*
         * Since the SecurityContext is stored in a ThreadLocal we need to
         * be sure to clear it after every test.
         */
        SecurityContextHolder.clearContext();
    }

    public void testGetUsernameWithUserDetails() {
        UserDetails details = new User("user", "password", true, true, true, true, new GrantedAuthority[0]);
        Authentication auth = new UsernamePasswordAuthenticationToken(details, null, details.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(auth);

        String user = m_service.getUsername();
        assertNotNull("user should not be null", user);
        assertEquals("user name", details.getUsername(), user);
    }

    public void testGetUsernameWithStringPrincipal() {
        Authentication auth = new UsernamePasswordAuthenticationToken("user", null, new GrantedAuthority[0]);
        SecurityContextHolder.getContext().setAuthentication(auth);

        String user = m_service.getUsername();
        assertNotNull("user should not be null", user);
        assertEquals("user name", "user", user);
    }

    public void testGetUsernameNoAuthenticationObject() {
        ThrowableAnticipator ta = new ThrowableAnticipator();
        ta.anticipate(new IllegalStateException("No Authentication object found when calling getAuthentication on our SecurityContext object"));

        try {
            m_service.getUsername();
        } catch (Throwable t) {
            ta.throwableReceived(t);
        }

        ta.verifyAnticipated();
    }

    public void testGetUsernameNoPrincipalObject() {
        Authentication auth = new UsernamePasswordAuthenticationToken(null, null, new GrantedAuthority[0]);
        SecurityContextHolder.getContext().setAuthentication(auth);

        ThrowableAnticipator ta = new ThrowableAnticipator();
        ta.anticipate(new IllegalStateException("No principal object found when calling getPrinticpal on our Authentication object"));

        try {
            m_service.getUsername();
        } catch (Throwable t) {
            ta.throwableReceived(t);
        }

        ta.verifyAnticipated();
    }
}

Add some tests for getting he user's username for the DefaultSurveillanceService


//------------------------------------------------------------------------------------------------//
//                                                                                //
//                                  B e a m H e a d C l e a n e r                                 //
//                                                                                //
//------------------------------------------------------------------------------------------------//
// <editor-fold defaultstate="collapsed" desc="hdr">
//
//  Copyright ©  Audiveris 2017. All rights reserved.
//
//  This program is free software: you can redistribute it and/or modify it under the terms of the
//  GNU Affero General Public License as published by the Free Software Foundation, either version
//  3 of the License, or (at your option) any later version.
//
//  This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
//  without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
//  See the GNU Affero General Public License for more details.
//
//  You should have received a copy of the GNU Affero General Public License along with this
//  program.  If not, see <http://www.gnu.org/licenses/>.
//------------------------------------------------------------------------------------------------//
// </editor-fold>
package org.audiveris.omr.sig;

import org.audiveris.omr.sheet.Sheet;
import org.audiveris.omr.sheet.SystemInfo;
import org.audiveris.omr.sig.relation.BeamHeadRelation;
import org.audiveris.omr.sig.relation.Relation;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Set;

/**
 * Class {@code BeamHeadCleaner} remove all BeamHeadRelation links when they are no
 * longer needed.
 *
 * @author Hervé Bitteur
 */
public class BeamHeadCleaner
{
    //~ Static fields/initializers -----------------------------------------------------------------

    private static final Logger logger = LoggerFactory.getLogger(BeamHeadCleaner.class);

    //~ Instance fields ----------------------------------------------------------------------------
    /** Related sheet. */
    private final Sheet sheet;

    //~ Constructors -------------------------------------------------------------------------------
    /**
     * Creates a new {@code BeamHeadCleaner} object.
     *
     * @param sheet underlying sheet
     */
    public BeamHeadCleaner (Sheet sheet)
    {
        this.sheet = sheet;
    }

    //~ Methods ------------------------------------------------------------------------------------
    //---------//
    // process //
    //---------//
    public void process ()
    {
        for (SystemInfo system : sheet.getSystems()) {
            SIGraph sig = system.getSig();
            Set<Relation> set = SIGraph.getRelations(sig.edgeSet(), BeamHeadRelation.class);
            logger.debug("System#{} BeamHeadRelation instances: {}", system.getId(), set.size());
            sig.removeAllEdges(set);
        }
    }
}

Delete Beam-Head relations when no longer useful


package com.vladmihalcea.book.hpjp.hibernate.type.array;

import com.vladmihalcea.book.hpjp.hibernate.type.json.model.BaseEntity;
import com.vladmihalcea.book.hpjp.util.AbstractPostgreSQLIntegrationTest;
import com.vladmihalcea.book.hpjp.util.providers.DataSourceProvider;
import com.vladmihalcea.book.hpjp.util.providers.PostgreSQLDataSourceProvider;
import org.hibernate.annotations.Type;
import org.hibernate.annotations.TypeDef;
import org.junit.Test;

import javax.persistence.*;

import static org.junit.Assert.assertArrayEquals;

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

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

    @Override
    protected DataSourceProvider dataSourceProvider() {
        return new PostgreSQLDataSourceProvider() {
            @Override
            public String hibernateDialect() {
                return PostgreSQL95ArrayDialect.class.getName();
            }
        };
    }

    @Test
    public void test() {
        doInJPA(entityManager -> {
            entityManager.persist(
                new Event()
                    .setT1(new int[]{1, 3, 6})
                    .setT2(new int[]{8, 9})
            );

            entityManager.persist(
                new Event()
                    .setT1(new int[]{1, 2})
                    .setT2(new int[]{8})
            );

            entityManager.persist(
                new Event()
                    .setT1(new int[]{6})
                    .setT2(new int[]{8, 1})
            );
        });
        //https://stackoverflow.com/questions/23863255/aggregation-to-calculate-number-of-each-tag-where-there-are-two-types-of-tags/23863831#23863831
        doInJPA(entityManager -> {
            Event event = entityManager.find(Event.class, 1L);
        });
    }

    @Entity(name = "Event")
    @Table(name = "event")
    @TypeDef(typeClass = IntArrayType.class, defaultForType = int[].class)
    public static class Event {

        @Id
        @GeneratedValue
        private Long id;

        @Column(columnDefinition = "integer[]")
        private int[] t1;

        @Column(columnDefinition = "integer[]")
        private int[] t2;

        public int[] getT1() {
            return t1;
        }

        public Event setT1(int[] t1) {
            this.t1 = t1;
            return this;
        }

        public int[] getT2() {
            return t2;
        }

        public Event setT2(int[] t2) {
            this.t2 = t2;
            return this;
        }
    }
}

Add test for PostgreSQL unnest

Add test for PostgreSQL unnest


package org.ovirt.engine.core.utils.log;

import java.io.IOException;
import java.net.URL;

import javax.xml.parsers.FactoryConfigurationError;

import org.apache.log4j.FileAppender;
import org.apache.log4j.Level;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.apache.log4j.PatternLayout;
import org.apache.log4j.xml.DOMConfigurator;

/**
 * Contains methods for runtime log4j setup
 */
public class Log4jUtils {
    /**
     * Resets logging configuration and tries to configure logging using specified configuration.
     *
     * @param url
     *            URL with log4j.xml
     */
    public static void setupLogging(URL url) {
        try {
            LogManager.resetConfiguration();
            DOMConfigurator.configure(url);
        } catch (FactoryConfigurationError ex) {
            throw new RuntimeException("Cannot configure logging: " + ex.getMessage(), ex);
        }
    }

    /**
     * Adds file appender with specified file and log level to root logger
     *
     * @param fileName
     *            file name to log into
     * @param levelName
     *            log level to use
     */
    public static void addFileAppender(String fileName, String levelName) {
        try {
            Level level = Level.INFO;
            if (levelName != null) {
                level = Level.toLevel(levelName, null);
                if (level == null) {
                    throw new IllegalArgumentException(String.format("Invalid log level value: '%s'", levelName));
                }
            }

            FileAppender fa = new FileAppender(new PatternLayout("%d %-5p [%c] %m%n"), fileName, true);
            fa.setThreshold(level);
            Logger.getRootLogger().addAppender(fa);
        } catch (SecurityException | IOException ex) {
            throw new IllegalArgumentException(
                    String.format("Error accessing log file '%s': '%s'", fileName, ex.getMessage()),
                    ex);
        }
    }
}

core: Add common methods for runtime log4j setup

Adds Log4jUtils class which contains methods for runtime log4j setup
used in engine-config and engine-manage-domains.

Change-Id: Ic00ea0af643e8c978fd67eb8c56e2329d43e776d
Bug-Url: https://bugzilla.redhat.com/1063901
Bug-Url: https://bugzilla.redhat.com/1083411
Signed-off-by: Martin Perina <7bf83f5b771f1cc16b652b5fe02fa33310bda7b0@redhat.com>


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

import org.junit.Test;
import org.junit.runner.RunWith;
import org.ops4j.pax.exam.junit.PaxExam;

@RunWith(PaxExam.class)
public class CamelZipDeflaterTest extends BaseKarafTest {

    public static final String COMPONENT = extractName(CamelZipDeflaterTest.class);

    @Test
    public void test() throws Exception {
        testDataFormat(COMPONENT, "zipdeflater");
        testDataFormat(COMPONENT, "gzipdeflater");
    }

}

Move dataformats out of camel-core.

CAMEL-13474: Move dataformats out of camel-core.


/**
 *
 */
package edu.wustl.cab2b.common.util;

import junit.framework.TestCase;

/**
 * @author deepak_shingan
 *
 */
public class UtilityTest extends TestCase {

    /**
     * Test method for {@link edu.wustl.cab2b.common.util.Utility#replaceAllWords(java.lang.String, java.lang.String, java.lang.String)}.
     */
    public final void testReplaceAllWords() {
        //char replacement test
        assertEquals("Test", Utility.replaceAllWords("Teasta", "a", ""));

        //String replacement test
        assertEquals("What is this? this is this and is this Correct?",
                     Utility.replaceAllWords("What is that? that is that and is that Correct?", "that", "this"));
        //Null argument passing
        assertEquals(null, Utility.replaceAllWords(null, "that", "this"));

        //No replacement found test
        assertEquals("No replacement test", Utility.replaceAllWords("No replacement test", "Deepak", "Shingan"));
    }

}

Test case written for Utility.replaceAllWords() method


package org.realityforge.arez.integration;

import org.realityforge.arez.ArezTestUtil;
import org.realityforge.braincheck.BrainCheckTestUtil;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;

@SuppressWarnings( "Duplicates" )
public abstract class AbstractArezIntegrationTest
{
  @BeforeMethod
  protected void beforeTest()
    throws Exception
  {
    BrainCheckTestUtil.resetConfig( false );
    ArezTestUtil.resetConfig( false );
  }

  @AfterMethod
  protected void afterTest()
    throws Exception
  {
    BrainCheckTestUtil.resetConfig( true );
    ArezTestUtil.resetConfig( true );
  }
}

package org.realityforge.arez.integration;

import java.util.ArrayList;
import java.util.stream.Collectors;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import org.realityforge.arez.Arez;
import org.realityforge.arez.ArezTestUtil;
import org.realityforge.arez.Observer;
import org.realityforge.arez.ObserverError;
import org.realityforge.braincheck.BrainCheckTestUtil;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import static org.testng.Assert.*;

@SuppressWarnings( "Duplicates" )
public abstract class AbstractArezIntegrationTest
{
  private final ArrayList<String> _observerErrors = new ArrayList<>();
  private boolean _ignoreObserverErrors;

  @BeforeMethod
  protected void beforeTest()
    throws Exception
  {
    BrainCheckTestUtil.resetConfig( false );
    ArezTestUtil.resetConfig( false );
    _ignoreObserverErrors = false;
    _observerErrors.clear();
    Arez.context().addObserverErrorHandler( this::onObserverError );
  }

  protected void onObserverError( @Nonnull final Observer observer,
                                  @Nonnull final ObserverError error,
                                  @Nullable final Throwable throwable )
  {
    if ( !_ignoreObserverErrors )
    {
      final String message = "Observer: " + observer.getName() + " Error: " + error + " " + throwable;
      _observerErrors.add( message );
      System.out.println( message );
    }
  }

  @AfterMethod
  protected void afterTest()
    throws Exception
  {
    BrainCheckTestUtil.resetConfig( true );
    ArezTestUtil.resetConfig( true );
    if ( !_ignoreObserverErrors && !_observerErrors.isEmpty() )
    {
      fail( "Unexpected Observer Errors: " + _observerErrors.stream().collect( Collectors.joining( "\n" ) ) );
    }
  }
}

Make sure tests fail if unexpected observer errors occur


/* Copyright 2017 Alfa Financial Software
 *
 * 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.alfasoftware.morf.integration.testdatabaseupgradeintegration.upgrade.v1_0_0;

import static org.alfasoftware.morf.metadata.SchemaUtils.column;

import org.alfasoftware.morf.metadata.DataType;
import org.alfasoftware.morf.upgrade.DataEditor;
import org.alfasoftware.morf.upgrade.SchemaEditor;
import org.alfasoftware.morf.upgrade.Sequence;
import org.alfasoftware.morf.upgrade.UUID;

@Sequence(1)
@UUID("1ade56c0-b1d7-11e2-9e96-080020011111")
public class AddColumnWithoutDropDefaultValue extends AbstractTestUpgradeStep {
  @Override
  public void execute(SchemaEditor schema, DataEditor data) {
    schema.addColumn("WithDefaultValue",
      column("anotherValue", DataType.STRING, 10).defaultValue("OLD"));
  }
}

Upgrade step that forgotten to drop the default value.


/*
 * $Id: TranslatableMarker.java 1417 2006-11-03 14:57:33 +0000 (Fri, 03 Nov 2006) rodneykinney $
 *
 * Copyright (c) 2000-2006 by Rodney Kinney, Brent Easton
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Library General Public
 * License (LGPL) as published by the Free Software Foundation.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Library General Public License for more details.
 *
 * You should have received a copy of the GNU Library General Public
 * License along with this library; if not, copies are available
 * at http://www.opensource.org.
 */
package VASSAL.i18n;

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

import VASSAL.build.AbstractConfigurable;
import VASSAL.build.Buildable;
import VASSAL.build.module.documentation.HelpFile;
import VASSAL.counters.GamePiece;
import VASSAL.counters.PlaceMarker;

/**
 *
 * @author Brent Easton
 *
 * A dummy AbstractConfigurable to hold a PlaceMarker or Replace definition while translating
 */
public class TranslatableMarker extends AbstractConfigurable {

  protected GamePiece markerDefinition;
  protected String[] names;
  protected String[] values;

  public TranslatableMarker(PlaceMarker p) {
    markerDefinition = p.createBaseMarker();
    setConfigureName(p.getDescription());

  }

  public static String getConfigureTypeName() {
    return "Marker Definition";
  }

  public ComponentI18nData getI18nData() {
    return new ComponentI18nData(this, markerDefinition);
  }

  public String getAttributeValueString(String attr) {
    return getI18nData().getLocalUntranslatedValue(attr);
  }

  public void setAttribute(String attr, Object value) {

  }

  public void add(Buildable child) {
  }

  public void addTo(Buildable parent) {

  }

  public void build(Element e) {

  }

  public Element getBuildElement(Document doc) {
    return null;
  }

  public String[] getAttributeDescriptions() {
    return null;
  }

  public Class[] getAttributeTypes() {
    return null;
  }

  public String[] getAttributeNames() {
    return null;
  }
  public Class[] getAllowableConfigureComponents() {
    return null;
  }
  public HelpFile getHelpFile() {
    return null;
  }
  public void removeFrom(Buildable parent) {

  }

}

Add missing file from previous merge

Add missing file from previous merge

git-svn-id: ae08250ad33602a4155ea07c044985523749a64a@2113 67b53d14-2c14-4ace-a08f-0dab2b34000c


package leetcode;

/**
 * https://leetcode.com/problems/power-of-four/
 */
public class Problem342 {
    public boolean isPowerOfFour(int num) {
        // TODO:
        return false;
    }

    public static void main(String[] args) {
        Problem342 prob = new Problem342();
        System.out.println(prob.isPowerOfFour(16)); // true
        System.out.println(prob.isPowerOfFour(5)); // false
    }
}

Create a skeleton for problem 342

Create a skeleton for problem 342


/*
 * #%L
 * BroadleafCommerce Common Libraries
 * %%
 * Copyright (C) 2009 - 2013 Broadleaf Commerce
 * %%
 * 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.
 * #L%
 */
package org.broadleafcommerce.common.extensibility.jpa.clone;

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

/**
 * Marker annotation for fields that should not undergo enterprise sandbox config validation (if applicable)
 *
 * @author jfischer
 *
 */
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD})
public @interface IgnoreEnterpriseConfigValidation {

}

Add marker annotation for ignoring enterprise annotation config validation


package nl.github.martijn9612.fishy;

import junit.framework.TestCase;
import nl.github.martijn9612.fishy.models.Score;

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

/**
 * Testclass for ScoreController.
 * @author Danique Lummen
 */
public class ScoreControllerTest extends TestCase {

    private ScoreController test;

    /**
     * Setup for the test class.
     */
    @Before
    protected void setUp() {
        test = ScoreController.getInstance();
    }

    /**
     * Test method for getInstance method.
     */
    @Test
    public void testGetInstance() {
        assertEquals(test, ScoreController.getInstance());
    }

    /**
     * Test method for StorePlayerScore method.
     */
    @Test
    public void testStorePlayerScore() {
        test.storePlayerScore(100.0);
        assertEquals(test.getPlayerScore(), 100.0);
    }

    /**
     * Test method for addScore method.
     */
    @Test
    public void testAddScore() {
        Score score = new Score("Highscore", 1000.0);
        test.addScore(score);
        assertTrue(test.getScoreList().contains(score));
    }

    /**
     * Test method for removeScore method.
     */
    @Test
    public void testRemoveScore1() {
        Score score = new Score("Highscore", 1000.0);
        test.addScore(score);
        test.removeScore(score);
        assertFalse(test.getScoreList().contains(score));
    }

    /**
     * Test method for removeScore method.
     */
    @Test
    public void testRemoveScore2() {
        Score score = new Score("Highscore", 1000.0);
        test.removeScore(score);
        assertFalse(test.getScoreList().contains(score));
    }

    /**
     * Test method for savedStoredScore method.
     */
    @Test
    public void testSavedStoredScore() {
        test.storePlayerScore(200.0);
        test.savedStoredScore("player");
        assertEquals(test.getPlayerScore(), 0.0);

    }
}

Test class for the ScoreController class <testing


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

/**
 * Given a set of integers, can you write a method to calculate every possible combination?
 *
 * @author Pedro Vicente Gómez Sánchez.
 */
public class CombinationOfIntegers {
}

Add statement to problem 43

Add statement to problem 43


package io.quarkus.vertx.http.devconsole;

import org.hamcrest.Matchers;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;

import io.quarkus.test.QuarkusDevModeTest;
import io.restassured.RestAssured;

/**
 * Tests that a system property such as {@code %.intellij.command.histfile."}
 * doesn't lead to an exception because {@code "} is incorrectly seen as a quoted property.
 * <p>
 * Originally the bug stemmed from an environment property {@code __INTELLIJ_COMMAND_HISTFILE__}
 * which was (weirdly) interpreted as {@code %.intellij.command.histfile."},
 * but it's much easier to test system properties (which are mutable)
 * than environment properties.
 */
public class DevConsoleConfigMisinterpretedDoubleUnderscoreTest {

    @RegisterExtension
    static final QuarkusDevModeTest config = new QuarkusDevModeTest()
            .setBuildSystemProperty("%.intellij.command.histfile.\"", "foo")
            .withEmptyApplication();

    @Test
    public void testNoFailure() {
        RestAssured.get("q/dev/io.quarkus.quarkus-vertx-http/config")
                .then()
                .statusCode(200).body(Matchers.containsString("Config Editor"));
    }
}

Test properties containing a double-quote alone with q/dev/io.quarkus.quarkus-vertx-http/config

In particular the environment variable `__INTELLIJ_COMMAND_HISTFILE__`,
translated to `%.intellij.command.histfile.`, seems to be giving that
page a hard time.


/**
 *
 */
package org.corpus_tools.atomic.tokeneditor.commands;

import org.eclipse.core.commands.AbstractParameterValueConverter;
import org.eclipse.core.commands.ParameterValueConversionException;

/**
 * TODO Description
 *
 * @author Stephan Druskat <mail@sdruskat.net>
 *
 */
public class BooleanParameterValueConverter extends AbstractParameterValueConverter {

	/* (non-Javadoc)
	 * @see org.eclipse.core.commands.AbstractParameterValueConverter#convertToObject(java.lang.String)
	 */
	@Override
	public Object convertToObject(String parameterValue) throws ParameterValueConversionException {
		return Boolean.parseBoolean(parameterValue);
	}

	/* (non-Javadoc)
	 * @see org.eclipse.core.commands.AbstractParameterValueConverter#convertToString(java.lang.Object)
	 */
	@Override
	public String convertToString(Object parameterValue) throws ParameterValueConversionException {
		return Boolean.toString((Boolean) parameterValue);
	}

}

Create converter for Boolean parameters

Create converter for Boolean parameters


package leetcode;

import java.util.Arrays;

/**
 * https://leetcode.com/problems/spiral-matrix-ii/
 */
public class Problem59 {
    public int[][] generateMatrix(int n) {
        return null;
    }

    public static void main(String[] args) {
        Problem59 prob = new Problem59();
        for (int[] a : prob.generateMatrix(3)) {
            System.out.println(Arrays.toString(a));
        }
    }
}

Create a skeleton for problem 59

Create a skeleton for problem 59


/**
 * Package {@code nl.ulso.sprox.resolvers} contains implementations of resolvers that resolve references
 * to XML nodes and attributes from Java method and parameter names.
 *

 * By default uses the {@link nl.ulso.sprox.resolvers.DefaultElementNameResolver}, but you can set a custom
 * one, even per controller your setting up in a builder:
 *

 * // ...
 * builder
 *     .setElementNameResolver(new MyFirstCustomResolver())
 *     .addControllerClass(FirstController.class)
 *     .setElementNameResolver(new MySecondCustomResolver())
 *     .addControllerClass(SecondController.class)
 *     .resetElementNameResolver()
 *     .addControllerClass(DefaultController.class);
 *

 *
 * @see nl.ulso.sprox.XmlProcessorBuilder
 */
package nl.ulso.sprox.resolvers;

Add JavaDoc fot the resolvers package.

Add JavaDoc fot the resolvers package.


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

// https://www.hackerrank.com/challenges/mark-and-toys/problem
public class MarkAndToys {

  private static final String SPACE = " ";

  private static long getBudget(BufferedReader reader) throws IOException {
    String[] split = reader.readLine().split(SPACE);
    return Long.parseLong(split[1]);
  }

  private static long[] getPrices(BufferedReader reader) throws IOException {
    String[] split = reader.readLine().split(SPACE);
    return Arrays.stream(split).mapToLong(Long::parseLong).toArray();
  }

  private static int getMaxToys(long[] sortedPrices, long budget) {
    int toys = 0;
    long toPay = 0;
    for (long price : sortedPrices) {
      if (toPay + price > budget) {
        break;
      }
      toPay += price;
      toys += 1;
    }
    return toys;
  }

  public static void main(String[] args) throws IOException {
    try (BufferedReader reader = new BufferedReader(new InputStreamReader(System.in))) {
      long budget  = getBudget(reader);
      long[] prices = getPrices(reader);
      Arrays.sort(prices);
      int maxToys = getMaxToys(prices, budget);
      System.out.println(maxToys);
    }
  }
}

Add solution for Mark and toys problem.

Add solution for Mark and toys problem.


package leetcode.add_digits;

public class Solution {
    public int addDigits(int num) {
        if(num == 0) return 0;
        return 9 - (9 - (num % 9)) % 9;
    }
}

Add java solution for 258. Add Digits

Add java solution for 258. Add Digits

258. Add Digits: https://leetcode.com/problems/add-digits/


package org.agmip.translators.csv;

import java.io.File;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
//import java.util.HashMap;
import java.util.Map;
import org.agmip.util.MapUtil;

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

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class AlnkTest {
    private static final Logger log = LoggerFactory.getLogger(AlnkTest.class);
    private AlnkInput reader;
    private AlnkOutput writer;
    private URL resource = null;

    @Before
    public void setup() {
        reader = new AlnkInput();
        writer = new AlnkOutput();
    }

    @Test
    public void ACOMTest() {
        log.info("Test for reading link information from ACMO file starts");
        resource = this.getClass().getResource("/ACMO.csv");
        try {
            Map links = reader.readFile(resource.getPath());
            log.info("Translation results for link csv test: {}", links.toString());
        } catch (Exception ex) {
            ex.printStackTrace();
            assertTrue(false);
        }
        assertTrue(true);
    }

    @Test
    public void ALNKTest() {
        log.info("Test for reading link information from ALNK file starts");
        resource = this.getClass().getResource("/Linkage.alnk");
        try {
            Map links = reader.readFile(resource.getPath());
            writer.writeFile("output/Linkage.alnk", toACEFormat(links));
            log.info("Translation results for link csv test: {}", links.toString());
            File alnk = writer.getAlnkFile();
            alnk.delete();
            alnk.getParentFile().delete();
        } catch (Exception ex) {
            ex.printStackTrace();
            assertTrue(false);
        }
        assertTrue(true);
    }

    private Map toACEFormat(Map links) {
        HashMap ret = new HashMap();
        ArrayList<HashMap> arr = new ArrayList();
        ret.put("experiments", arr);
        HashMap<String, String> ovlLinks = MapUtil.getObjectOr(links, "link_overlay", new HashMap());
        HashMap<String, String> stgLinks = MapUtil.getObjectOr(links, "link_stragty", new HashMap());
        for (String key : ovlLinks.keySet()) {
            HashMap m = new HashMap();
            m.put("exname", key.substring(7));
            m.put("field_overlay", ovlLinks.get(key));
            m.put("seasonal_strategy", stgLinks.get(key));
            arr.add(m);
        }
        return ret;
    }
}

Add test class for *.ALNK file

Add test class for *.ALNK file


import java.io.*;
import java.util.*;

public class depth_first_search{

  static class Edge {
    int src;
    int nbr;
    int wt;

    Edge(int src, int nbr, int wt) {
      this.src = src;
      this.nbr = nbr;
      this.wt = wt;
    }
  }

    public static void main(String[] args) throws Exception {
      BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

      int vtces = Integer.parseInt(br.readLine());
      ArrayList<Edge>[] graph = new ArrayList<>[vtces];
      for (int i = 0; i < vtces; i++) {
        graph[i] = new ArrayList<>();
      }

      int edges = Integer.parseInt(br.readLine());
      for (int i = 0; i < edges; i++) {
        String[] parts = br.readLine().split(" ");
        int v1 = Integer.parseInt(parts[0]);
        int v2 = Integer.parseInt(parts[1]);
        int wt = Integer.parseInt(parts[2]);
        graph[v1].add(new depth_first_search.Edge(v1, v2, wt));
        graph[v2].add(new depth_first_search.Edge(v2, v1, wt));
      }

      int src = Integer.parseInt(br.readLine());
      int dest = Integer.parseInt(br.readLine());

      boolean[] visited = new boolean[vtces];
      boolean flag = depth_first_search.hasPath(graph, src, dest, visited);
      System.out.println(flag);
    }

  public static boolean hasPath(ArrayList< Edge>[] graph, int src, int dest, boolean[] visited) {
    if (src == dest)
      return true;

    visited[src] = true;
    for (Edge e : graph[src]) {
      if (!visited[e.nbr]) {
        boolean nbrHasPath = hasPath(graph, e.nbr, dest, visited);
        if (nbrHasPath)
          return true;
      }
    }
    return false;
  }
}

Add java code of Depth First Search.

Add java code of Depth First Search.

I have added the Java code for the Depth first search in an undirected graph


package peergos.server.tests;

import org.junit.*;
import peergos.server.*;
import peergos.server.storage.*;
import peergos.server.util.*;

import java.nio.file.*;
import java.util.*;

public class S3IpfsPluginTest {

    @Test
    public void loadPlugin() throws Exception {

        Path peergosDir = Files.createTempDirectory("peergos");
        Random r = new Random();
        int ipfsApiPort = 9000 + r.nextInt(50_000);
        int ipfsGatewayPort = 9000 + r.nextInt(50_000);
        int ipfsSwarmPort = 9000 + r.nextInt(50_000);
        Args args = Args.parse(new String[]{
                "-ipfs-api-address", "/ip4/127.0.0.1/tcp/" + ipfsApiPort,
                "-ipfs-gateway-address", "/ip4/127.0.0.1/tcp/" + ipfsGatewayPort,
                "-ipfs-swarm-port", Integer.toString(ipfsSwarmPort),
                "-logToConsole", "true",
                Main.PEERGOS_PATH, peergosDir.toString(),
                "-proxy-target", "/ip4/127.0.0.1/tcp/80",
                "-ipfs-plugins", "go-ds-s3",
                "-s3.bucket", "atest",
                "-s3.accessKey", "fake-key",
                "-s3.secretKey", "fake-key",
                "-s3.region.endpoint", "us-east-1.linodeobjects.com",
                "-s3.region", "us-east-1",
        });
        Main.ENSURE_IPFS_INSTALLED.main(args);
        IpfsWrapper ipfs = IpfsWrapper.build(args);
        ipfs.configure();
    }
}

Add test for ipfs S3 plugin loading

Add test for ipfs S3 plugin loading


package api.whatstatus;

import api.son.MySon;

/**
 * Get information about the various site service uptime in hours
 * using the whatstatus API
 */
public class WhatUptime {
	/**
	 * The irc.
	 */
	private String irc;

	/**
	 * The site.
	 */
	private String site;

	/**
	 * The tracker.
	 */
	private String tracker;

	/**
	 * Load the WhatStatus information
	 *
	 * @return the what status
	 */
	public static WhatUptime uptime(){
		String url = "https://whatstatus.info/api/uptime";
		return (WhatUptime)MySon.toObjectOther(url, WhatUptime.class);
	}

	/**
	 * Get the site uptime in hours
	 */
	public Integer site(){
		return Integer.parseInt(site);
	}

	/**
	 * Get the IRC uptime in hours
	 */
	public Integer irc(){
		return Integer.parseInt(irc);
	}

	/**
	 * Get the tracker uptime in hours
	 */
	public Integer tracker(){
		return Integer.parseInt(tracker);
	}

	@Override
	public String toString(){
		return "Status [getIrc()=" + irc + ", getSite()=" + site + ", getTracker()=" + tracker + "]";
	}
}

Add support for the uptime API on whatstatus


package net.simpvp.Portals;

import org.bukkit.entity.Entity;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.world.ChunkUnloadEvent;

public class ChunkUnload implements Listener {

	@EventHandler
	public void onChunkUnload(ChunkUnloadEvent event) {

		/* Do not let chunks containing entities about to be teleported unload */
		for (Entity entity : event.getChunk().getEntities()) {
			if (Portals.justTeleportedEntities.contains(entity.getUniqueId())) {
				event.setCancelled(true);
			}
		}

	}
}

Stop chunks from unloading while teleporting entities are inside


package org.mmog2048.utils;

import io.vertx.core.json.JsonObject;
import io.vertx.redis.RedisOptions;

public class RedisUtils {
  public static RedisOptions createRedisOptions(JsonObject conf) {
    RedisOptions options = new RedisOptions();
    options.setHost(conf.getString("host"));
    options.setPort(conf.getInteger("port"));
    return options;
  }
}

Put redis options in for use elsewhere

Put redis options in for use elsewhere


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

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

        double n;

        n = Double.parseDouble(in.readLine());

        System.out.printf("A=%.4f\n", n * n * 3.14159);
    }
}

Solve Area of a Circle in java

Solve Area of a Circle in java


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

package org.openecard.cif;

import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static org.testng.Assert.*;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;

/**
 * Test to evaluate the availability of the images.
 *
 * @author Tobias Wich
 */
public class ImageChecker {

    private static final Logger logger = LoggerFactory.getLogger(ImageChecker.class);
    private List<URL> imageUrls;

    @BeforeClass
    public void loadImageUrls() throws IOException {
	// load properties file
	InputStream in = ImageChecker.class.getResourceAsStream("/card-images/card-images.properties");
	Properties p = new Properties();
	p.load(in);

	// convert each entry into a URL
	imageUrls = new ArrayList<>();
	for (Map.Entry<Object, Object> next : p.entrySet()) {
	    String file = (String) next.getValue();
	    URL url = ImageChecker.class.getResource("/card-images/" + file);
	    imageUrls.add(url);
	}
    }

    @Test
    public void testPresence() throws IOException {
	for (URL url : imageUrls) {
	    url.openStream();
	    assertNotNull(url);
	}
    }

    // TODO: remove integration test as soon as OpenJDK 8 in Debian can handle JPEGs correctly
    // see also https://dev.openecard.org/issues/369
    @Test(groups={"it"})
    public void testLoadImages() throws IOException {
	for (URL url : imageUrls) {
	    logger.info("Trying to load image '{}'.", url);
	    BufferedImage bi = ImageIO.read(url);
	    ImageIcon icon = new ImageIcon(bi);
	}
    }

}

Add test to validate card images

Add test to validate card images


package sfBugs;

import edu.umd.cs.findbugs.annotations.DesireNoWarning;
import edu.umd.cs.findbugs.annotations.ExpectWarning;

public class RFE3026970 {
	private String get() { return null; }

	public void testDesireWarning() {
		if (get().equals("A"))
			System.out.println("test");
	}

	public void testDesireNoWarning() {
		if ("A".equals(get()))
			System.out.println("test");
	}
}

Add sample code for RFE 3026970

Add sample code for RFE 3026970

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


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

package org.scijava;

/**
 * An object whose location is defined by a URL string.
 *
 * @author Curtis Rueden
 */
public interface Locatable {

	/** Gets the URL string defining the object's location. */
	String getLocation();

}

Add an interface for objects with URL locations

The initial use case is for ModuleInfo. Similar to Identifiable, it is
nice to able to ask a command or script: "In which URL are you defined?"
This is a different question than the delegate class, which is
Java-specific.


package com.jeromecompsci.dgui.examples;

import com.jeromecompsci.dgui.*;
import com.jeromecompsci.dgui.Label;
import com.jeromecompsci.dgui.TextField;
import com.jeromecompsci.dgui.Window;

/**
 * @author Derek Wang
 */
public class TypingProgram {
    public static Label label = new Label("");

    public static void main(String[] args) {
        TextField field = new TextField();
        field.on("change", TypingProgram.class, "textChanged");
        field.on("enter", TypingProgram.class, "textSubmitted");

        Window window = new Window(new VPane(field, label));
        window.show();
    }

    public static void textChanged() {
        label.setText("You typed!");
    }

    public static void textSubmitted() {
        label.setText("You pressed RETURN/ENTER!");
    }

}

Add example for TextField bindings (which doubles as another static-method-only example other than BasicGUI)


/*
 * This file is part of Mapyrus, software for plotting maps.
 * Copyright (C) 2003 Simon Chenery.
 *
 * Mapyrus is free software; you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * Mapyrus is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with Mapyrus; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
 */

/*
 * @(#) $Id$
 */
package org.mapyrus.function;

import org.mapyrus.Argument;
import org.mapyrus.ContextStack;
import org.mapyrus.MapyrusException;
import org.mapyrus.MapyrusMessages;

/**
 * Function returning square root of value.
 * For example, sqrt(9) = 3.
 */
public class Sqrt extends Function
{
	/**
	 * @see org.mapyrus.function.Function#evaluate(org.mapyrus.ContextStack, org.mapyrus.Argument, org.mapyrus.Argument)
	 */
	public Argument evaluate(ContextStack context, Argument arg1)
		throws MapyrusException
	{
		double d = arg1.getNumericValue();
		if (d < 0.0)
			throw new MapyrusException(MapyrusMessages.get(MapyrusMessages.NUMERIC_OVERFLOW));

		d = Math.sqrt(d);
		Argument retval = new Argument(d);
		return(retval);
	}

	/**
	 * @see org.mapyrus.function.Function#getMaxArgumentCount()
	 */
	public int getMaxArgumentCount()
	{
		return(1);
	}

	/**
	 * @see org.mapyrus.function.Function#getMinArgumentCount()
	 */
	public int getMinArgumentCount()
	{
		return(1);
	}

	/**
	 * @see org.mapyrus.function.Function#getName()
	 */
	public String getName()
	{
		return("sqrt");
	}
}

Split functions out from Expression.java into separate classes.


// Add a constructor to Triangle.

// A class for two-dimensional objects.
class TwoDShape {
  private double width;  // these are
  private double height; // now private

  // Accessor methods for width and height.
  double getWidth() { return width; }
  double getHeight() { return height; }
  void setWidth(double w) { width = w; }
  void setHeight(double h) { height = h; }

  void showDim() {
    System.out.println("Width and height are " + width + " and " + height);
  }
}

// A subclass of TwoDShape for triangles.
class Triangle extends TwoDShape {
  private String style;

  //Constructor
  Triangle(String s, double w, double h) {
    setWidth(w);
    setHeight(h);

    style = s;
  }

  double area () {
    return getWidth() * getHeight() / 2;
  }

  void showStyle() {
    System.out.println("Triangle is " + style);
  }
}

class Shapes3 {
  public static void main(String args[]) {
    Triangle t1 = new Triangle("isosceles", 4.0, 4.0);
    Triangle t2 = new Triangle("right", 8.0, 12.0);

    System.out.println("Info for t1: ");
    t1.showStyle();
    t1.showDim();
    System.out.println("Area is " + t1.area());

    System.out.println();

    System.out.println("Info for t2: ");
    t2.showStyle();
    t2.showDim();
    System.out.println("Area is " + t2.area());
  }
}

Add a Constructor to Triangle

Add a Constructor to Triangle

http://ideone.com/aeGs0g


/*
 *Key point: binary search
 *    if there's explicit constructor, the default one isn't available
 */

/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public TreeNode sortedArrayToBST(int[] num) {

        int length = num.length;
        //handle null pointer and empty array
        if(num == null || length == 0)
            return null;

        return realWorker(num, 0, length - 1);
    }

    public TreeNode realWorker(int[] num, int begin, int end){
        int mid = (begin + end + 1) / 2;

        //init a new node
        TreeNode node = new TreeNode(0);
        node.val = num[mid];

        if(begin <= mid - 1)
            node.left = realWorker(num,begin,mid-1);
        else
            node.left = null;

        if(mid+1 <= end)
            node.right = realWorker(num,mid+1,end);
        else
            node.right = null;

        return node;
    }
}

Convert Sorted Array to Binary Search Tree


package net.spy.memcached;

import java.util.logging.Level;
import java.util.logging.Logger;
import net.spy.memcached.ops.Operation;
import net.spy.memcached.ops.OperationCallback;
import net.spy.memcached.ops.OperationStatus;
import net.spy.memcached.protocol.ascii.ExtensibleOperationImpl;
import java.nio.ByteBuffer;

/**
 *
 * @author Matt Ingenthron <ingenthr@cep.net>
 */
public class TimeoutNowriteTest extends ClientBaseCase {

	@Override
	protected void tearDown() throws Exception {
		// override teardown to avoid the flush phase
		client.shutdown();
	}

	@Override
	protected void initClient() throws Exception {
		client=new MemcachedClient(new DefaultConnectionFactory() {
			@Override
			public long getOperationTimeout() {
				return 1000; // 1 sec
			}
			@Override
			public FailureMode getFailureMode() {
				return FailureMode.Retry;
			}},
			AddrUtil.getAddresses("127.0.0.1:11211"));
	}

	private void tryTimeout(String name, Runnable r) {
		try {
			r.run();
			fail("Expected timeout in " + name);
		} catch(OperationTimeoutException e) {
			// pass
		}
	}

	public void testTimeoutDontwrite() {
		Operation op = new ExtensibleOperationImpl(new OperationCallback(){
			public void complete() {
				System.err.println("Complete.");
			}

			public void receivedStatus(OperationStatus s) {
				System.err.println("Received a line.");
			}}) {

			@Override
			public void handleLine(String line) {
				System.out.println("Woo! A line!");
			}

			@Override
			public void initialize() {
				setBuffer(ByteBuffer.wrap("garbage\r\n".getBytes()));
			}

			};
	try {
	    Thread.sleep(1100);
	} catch (InterruptedException ex) {
	    System.err.println("Interrupted when sleeping for timeout nowrite");
	}

	client.addOp("x", op);
	System.err.println("Operation attempted:");
	System.err.println(op);
	System.err.println("Trying to get:");
	try {
		byte[] retVal = (byte[])client.get("x");
		String retValString = new String();
		System.err.println(retValString);
	}
	catch (net.spy.memcached.OperationTimeoutException ex) {
		System.err.println("Timed out successfully: " + ex.getMessage());
	}

	System.err.println("Op timed out is " + op.isTimedOut());
	assert(op.isTimedOut() == true);
	}

}

Test for timeout from operation epoch.

Test for timeout from operation epoch.

Change-Id: I81530461187509026cc18e995b3ceddcc3c76afb
Reviewed-on: http://review.membase.org/4208
Reviewed-by: Trond Norbye <60edd2ef23891a753f231b0c6f161dc634079a93@gmail.com>
Reviewed-by: Michael Wiederhold <a17fed27eaa842282862ff7c1b9c8395a26ac320@membase.com>
Tested-by: Dustin Sallings <1c08efb9b3965701be9d700d9a6f481f1ffec3ea@spy.net>
Reviewed-by: Dustin Sallings <1c08efb9b3965701be9d700d9a6f481f1ffec3ea@spy.net>


/*
 * Copyright 2015, 2020 StreamEx 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 one.util.streamex;

import org.junit.Test;

import java.util.Spliterator;

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

public class PrefixOpsTest {
  @Test
  public void testNoSplitAfterAdvance() {
    Spliterator<Integer> spliterator = IntStreamEx.range(100).boxed().unordered().prefix(Integer::sum).spliterator();
    assertTrue(spliterator.tryAdvance(i -> assertEquals((int) i, 0)));
    assertTrue(spliterator.tryAdvance(i -> assertEquals((int) i, 1)));
    assertTrue(spliterator.tryAdvance(i -> assertEquals((int) i, 3)));
    assertTrue(spliterator.tryAdvance(i -> assertEquals((int) i, 6)));
    assertNull(spliterator.trySplit());
  }
}

Test that PrefixOps.OfUnordRef.trySplit doesn't split after advance


package pt.fccn.arquivo.tests;

import static org.junit.Assert.assertTrue;

import org.junit.Test;
import org.openqa.selenium.By;

import pt.fccn.saw.selenium.WebDriverTestBaseParalell;

/**
 *
 * @author Ivo Branco <ivo.branco@fccn.pt>
 *
 */
public class ContaMeHistoriasTest extends WebDriverTestBaseParalell {

	public ContaMeHistoriasTest(String os, String version, String browser, String deviceName,
			String deviceOrientation) {
		super(os, version, browser, deviceName, deviceOrientation);
	}

	@Test
	public void testImageSearchOneTerm() {
		driver.get("http://contamehistorias.pt");

		appendError(() -> {
			assertTrue("Check element contains arquivo.pt reference",
					driver.findElement(By.xpath("/html/body/footer/div/div/div[1]/div[1]/div")).getText()
							.contains("Arquivo.pt"));
		});

	}
}

Add conta me historias test

Add conta me historias test


//  Copyright 2022 The KeepTry Open Source Project
//
// 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 set;

import java.util.function.Consumer;

/*
A set: No duplicates, order doesn't matter
Assume the value range is [0, N-1]
Require:
clear() should not allocate new memory
iterate() is O(size) runtime
insert(), remove(), lookup(), clear() is O(1) runtime

https://imgur.com/jaVze0v
*/
public class ValueRangeSet {
  int[] vi, iv;
  int i;

  public ValueRangeSet(int N) {
    vi = new int[N]; // Value To Index
    iv = new int[N]; // index To Value
    i = 0;
  }

  void insert(int x) { // Runtime O(1)
    if (!lookup(x)) {
      vi[x] = i;
      iv[i] = x;
      i++;
    }
  }

  void remove(int x) { // Runtime O(1)
    if (lookup(x)) {
      int xi = vi[x];

      i--; // swap with the last one
      int lastV = iv[i];

      vi[lastV] = xi;
      iv[xi] = lastV;
    }
  }

  boolean lookup(int x) { // Runtime O(1)
    return vi[x] < i && iv[vi[x]] == x;
  }

  void clear() { // Runtime O(1)
    i = 0;
  }

  void iterate(Consumer<Integer> f) { // Runtime O(count)
    for (int i = 0; i < this.i; i++) {
      f.accept(iv[i]);
    }
  }

  // test ----------------------------------------------------------------------
  public static void main(String[] args) {
    ValueRangeSet s = new ValueRangeSet(10);
    s.insert(5);
    s.insert(6);
    s.insert(7);
    s.remove(6);
    s.insert(9);
    s.iterate(v -> System.out.println(v));
    s.clear();
    s.insert(5);
    s.remove(5);
    s.insert(9);
    s.iterate(v -> System.out.println(v));
  }
}

Set with known value range

Set with known value range


package leetcode.simplify_path;

import java.util.Stack;

public class Solution {
    public String simplifyPath(String path) {
    	String[] components = path.split("/");
    	Stack<String> dirStack = new Stack<String>();
    	for(String component : components){
    		if(component.length() == 0) continue;
    		if(component.equals(".")) continue;
    		if(component.equals("..")){
    			if(!dirStack.isEmpty()){
    				dirStack.pop();
    			}
    		}else{
    			dirStack.push(component);
    		}
    	}
    	StringBuilder ans = new StringBuilder("/");
    	String prefix = "";
    	for(String component : dirStack){
    		ans.append(prefix);
    		ans.append(component);
    		prefix = "/";
    	}
    	return ans.toString();
    }
    public static void main(String[] args){
    	System.err.println(new Solution().simplifyPath("/home/ckclark/helloaaa/a/.../../../../././../ckclark/../../../../"));
    }
}

Add java solution for 71. Simplify Path

Add java solution for 71. Simplify Path

71. Simplify Path: https://leetcode.com/problems/simplify-path/


package uk.me.mjt.ch;

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

public class PumlTest {

    public PumlTest() {
    }

    @Test
    public void testForNodes() {
        System.out.println("forNodes");
        MapData a = MakeTestData.makeSimpleThreeEntry();

        String result = Puml.forNodes(a.getAllNodes());
        System.out.println(result);

        for (int i=1 ; i<=3 ; i++) {
            assertContains("(Node "+i+")", result);
            assertContains("Edge 100"+(i-1), result);
        }

        assertTrue(result.startsWith("@startuml"));
        assertTrue(result.endsWith("@enduml"));
    }

    private void assertContains(String substring, String toCheck) {
        assertTrue(toCheck.contains(substring));
    }

}

Improve test coverage of Puml class.

Improve test coverage of Puml class.


package net.acomputerdog.core.gen;

import java.util.Random;

public class StringGen {
    private static final Random random = new Random("StringGen".hashCode() + System.currentTimeMillis());
    private static final char[] alphabet = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVXYZ".toCharArray();

    public static int nextInt() {
        return random.nextInt();
    }

    public static String nextString(int length) {
        byte[] bytes = new byte[length];
        random.nextBytes(bytes);
        limBytes(bytes, (byte) alphabet.length);
        return createString(bytes);
    }

    public static String nextString() {
        return nextString(8);
    }

    private static String createString(byte[] bytes) {
        char[] chars = new char[bytes.length];
        for (int index = 0; index < bytes.length; index++) {
            bytes[index] = (byte) (bytes[index] % chars.length);
        }
        return new String(chars);
    }

    private static byte[] limBytes(byte[] bytes, byte max) {
        for (int index = 0; index < bytes.length; index++) {
            bytes[index] %= max;
        }
        return bytes;
    }
}

Add string generator utility class

Add string generator utility class


/*
 * Key point: good practice for dp, first try to use recursive solution
 *    but time limit exceed
 */

public class Solution {
    public boolean wordBreak(String s, Set<String> dict) {
        if(s == null || s.length() == 0 || dict == null)
            return true;

        int length = s.length();

        //dp[i] is true when the substring from i to the end can be partitioned
        boolean[] dp = new boolean[length+1];
        for(boolean b : dp)
            b = false;

        //empty string can be partitioned for sure
        dp[length] = true;

        //bottom up dp, start from the end
        for(int i = length - 1;i>=0;i--){
            for(int j = i;j < length;j++){
                String sub = s.substring(i,j+1);
                if(dict.contains(sub) == true && dp[j+1] == true){
                    dp[i]= true;
                    break;  //break, just jump out current level of loop
                }
            }
        }

        return dp[0];
    }
}

/*********recursive solution***********/
public class Solution {
    public boolean wordBreak(String s, Set<String> dict) {
        if(dict.contains(s) == true)
            return true;

        int length = s.length();
        for(int i = 1;i < length;i++){

            String firstPart = s.substring(0,i);
            if(dict.contains(firstPart) == true){

                String remainPart = s.substring(i,length);

                boolean result = wordBreak(remainPart, dict);
                if(result == true){
                    return true;
                }
            }
        }

        return false;
    }
}

Work Break, dp and recursive solution

Work Break, dp and recursive solution


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

/**
 * Given an absolute path and two relative paths to a directory, can you write a method to calculate
 * the final path?
 *
 * @author Pedro Vicente Gómez Sánchez.
 */
public class PathCalculator {
}

Add statement to problem 37

Add statement to problem 37


package leetcode;

/**
 * https://leetcode.com/problems/coin-change/
 */
public class Problem322 {
    public int coinChange(int[] coins, int amount) {
        // TODO
        return 0;
    }

    public static void main(String[] args) {

    }
}

Add skeleton for problem 322

Add skeleton for problem 322


package com.iesebre.dam2.roger.todos;

import java.util.ArrayList;

/**
 * Created by roger on 13/11/15.
 */
public class TodoArrayList extends ArrayList<TodoItem> {
}

Add TodoArray and extends ArrayList

Add TodoArray and extends ArrayList


package net.imagej.ops.viewOp;

import org.scijava.ItemIO;
import org.scijava.plugin.Parameter;
import org.scijava.plugin.Plugin;

import net.imagej.ops.view.ViewOps;
import net.imagej.ops.view.ViewOps.ExtendValue;
import net.imglib2.RandomAccessibleInterval;
import net.imglib2.type.Type;
import net.imglib2.view.ExtendedRandomAccessibleInterval;
import net.imglib2.view.Views;

@Plugin(type = ViewOps.ExtendValue.class, name = ViewOps.ExtendValue.NAME)
public class DefaultExtendValue<T extends Type<T>, F extends RandomAccessibleInterval<T>>
		extends AbstractView<F, ExtendedRandomAccessibleInterval<T, F>>
		implements ExtendValue<F, ExtendedRandomAccessibleInterval<T, F>> {

	@Parameter(type = ItemIO.INPUT)
	private T value;

	@Override
	public ExtendedRandomAccessibleInterval<T, F> compute(F input) {
		return Views.extendValue(input, value);
	}

}

Add default implementation of ExtendValue interface.


/*
 * Copyright (c) 2013 Red Rainbow IT Solutions GmbH, Germany
 *
 * 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 org.jeeventstore.core;

/**
 * Base class for the JEEventStore exceptions.
 *
 * @author Alexander Langer
 */
public abstract class EventStoreException extends Exception {

    public EventStoreException() {
    }

    public EventStoreException(String message) {
        super(message);
    }

    public EventStoreException(Throwable cause) {
        super(cause);
    }

    public EventStoreException(String message, Throwable cause) {
        super(message, cause);
    }

}

Add base class for our exceptions

Add base class for our exceptions


package cracking_the_coding_interview.arrays_and_strings;

import java.util.HashSet;

/*
	This class implements a method to check if all characters contained in a string are unique.
*/

class UniqueChars{

	// Checks if all characters contained in string s are unique
	// Time Complexity: O(N)		N - No. of characters in string s
	// Space Complexity: O(N)

	public static boolean check(String s){

		// throw exception if string is empty
		if(s == null){
			throw new NullPointerException("String is empty");
		}

		// Create hashset to hold all characters
		HashSet<Character> chars = new HashSet<Character>(s.length());

		// For each character in s
		for(int i=0;i<s.length();i++){

			// If it is already present in chars, return false
			if(chars.contains(s.charAt(i))){
				return false;
			}
			else { // otherwise, add this character to chars
				chars.add(s.charAt(i));
			}

		}

		// if no character was found twice, return true
		return true;
	}

}

Add class to check whether all characters in a string are unique


package google.dao;

import static org.junit.Assert.assertEquals;

import java.time.LocalDate;
import java.time.Month;

import org.junit.Test;

import google.model.Result;

public class SqlHelperTest {

	@Test
	public void testInsert() {
		Result result = new Result("Asterix i Obelix");
		result.setNumberOfResults(2_000);
		result.setDate(LocalDate.of(2017, Month.APRIL, 15));
		String expectedSql = "INSERT INTO RESULTS (GOOGLE_QUERY, NUMBER_OF_RESULTS, DATE_OF_SEARCH)"
				+ " VALUES ('Asterix i Obelix', 2000, '2017-04-15')";
		assertEquals(expectedSql, SqlHelper.getSqlForInsert(result));
	}

	@Test
	public void testSelectAll() {
		assertEquals("SELECT * FROM RESULTS", SqlHelper.getSqlForSelectAll());
	}

	@Test
	public void testSingleSelect() {
		assertEquals("SELECT * FROM RESULTS WHERE GOOGLE_QUERY = 'Papa Smerf'",
				SqlHelper.getSqlForSingleSelect("Papa Smerf"));
	}

	@Test
	public void testDeleteAll() {
		assertEquals("DELETE FROM RESULTS", SqlHelper.getSqlForDeleteAll());
	}

	@Test
	public void testDelete() {
		assertEquals("DELETE FROM RESULTS WHERE GOOGLE_QUERY = 'Myszka Miki'",
				SqlHelper.getSqlForDelete("Myszka Miki"));
	}

}

Add JUnit tests for SqlHelper.

Add JUnit tests for SqlHelper.


package tests;

import static org.junit.Assert.assertEquals;

import org.junit.Test;

import backend.resource.TurboLabel;
import backend.resource.serialization.SerializableLabel;

public class SerializationTests {

    @Test
    public void testSerializableLabelNoColorColorToString() {
        TurboLabel label = new TurboLabel("dummy/dummy", "label.name");
        SerializableLabel serializedLabel = new SerializableLabel(label);

        assertEquals(serializedLabel.toString(), "Label: {name: label.name, color: ffffff}");
    }

    @Test
    public void testSerializableLabelWithColorToString() {
        TurboLabel label = new TurboLabel("dummy/dummy", "abcdef", "label.name");
        SerializableLabel serializedLabel = new SerializableLabel(label);

        assertEquals(serializedLabel.toString(), "Label: {name: label.name, color: abcdef}");
    }
}

Add tests for serializableLabel's toString


import java.sql.ResultSet;
import java.sql.SQLException;

public class BadResultSetAccessTest
{

	public void test1( ResultSet rs ) throws SQLException
	{
		int i = rs.getInt(0);
		i++;
		rs.updateInt(0, i );
	}

	public void test2( ResultSet rs ) throws SQLException
	{
		String s = rs.getString(0);
		s = s.substring(1);
		rs.updateString(0, s );
	}

	public void test3( ResultSet rs ) throws SQLException
	{
		String s = rs.getString("foo");
		s = s.substring(1);
		rs.updateString("foo", s );
	}
}

Add new detector that looks for calls to ResultSet.getXXX and ResultSet.updateXXX where the field index specified is 0. - add test

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


/*
 * Copyright 2022 Daniel Gredler
 *
 * 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 uk.org.okapibarcode.backend;

import static org.junit.Assert.assertEquals;

import org.junit.Test;

/**
 * Tests for {@link TextBox}.
 */
public class TextBoxTest {

    @Test
    public void testTextBox() {
        TextBox text = new TextBox(1, 2, 3, "abc", HumanReadableAlignment.RIGHT);
        assertEquals(1, text.x, 0.001);
        assertEquals(2, text.y, 0.001);
        assertEquals(3, text.width, 0.001);
        assertEquals("abc", text.text);
        assertEquals(HumanReadableAlignment.RIGHT, text.alignment);
        assertEquals("TextBox[x=1.0, y=2.0, width=3.0, text=abc, alignment=RIGHT]", text.toString());
    }

}

Add unit test for TextBox

Add unit test for TextBox


package de.cinovo.cloudconductor.api.interfaces;

import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;

import de.cinovo.cloudconductor.api.IRestPath;
import de.cinovo.cloudconductor.api.MediaType;
import de.cinovo.cloudconductor.api.model.AgentOption;
import de.cinovo.cloudconductor.api.model.PackageState;
import de.cinovo.cloudconductor.api.model.PackageStateChanges;
import de.cinovo.cloudconductor.api.model.ServiceStates;
import de.cinovo.cloudconductor.api.model.ServiceStatesChanges;

/**
 *
 * Copyright 2017 Cinovo AG

 *

 *
 * @author mweise
 *
 */
@Path(IRestPath.AGENT)
public interface IAgent {

	/**
	 * @param template the template name
	 * @param host the host name
	 * @param rpmState the rpm state
	 * @param uuid the UUID of the agent
	 * @return list of instructions with changes to match the template
	 */
	@PUT
	@Path(IRestPath.AGENT_PACKAGE_STATE)
	@Consumes(MediaType.APPLICATION_JSON)
	@Produces(MediaType.APPLICATION_JSON)
	public PackageStateChanges notifyPackageState(@PathParam(IRestPath.VAR_TEMPLATE) String template, @PathParam(IRestPath.VAR_HOST) String host, PackageState rpmState, @PathParam(IRestPath.VAR_UUID) String uuid);

	/**
	 * @param template the template name
	 * @param host the host name
	 * @param serviceState the service state
	 * @param uuid the UUID of the agent
	 * @return list of instructions with changes to match the template
	 */
	@PUT
	@Path(IRestPath.AGENT_SERVICE_STATE)
	@Consumes(MediaType.APPLICATION_JSON)
	@Produces(MediaType.APPLICATION_JSON)
	public ServiceStatesChanges notifyServiceState(@PathParam(IRestPath.VAR_TEMPLATE) String template, @PathParam(IRestPath.VAR_HOST) String host, ServiceStates serviceState, @PathParam(IRestPath.VAR_UUID) String uuid);

	/**
	 * @param template the template name
	 * @param host the host name
	 * @param agent the agent name
	 * @param uuidString the UUID of the agent
	 * @return the current agent options
	 */
	@GET
	@Path(IRestPath.AGENT_HEART_BEAT)
	@Produces(MediaType.APPLICATION_JSON)
	public AgentOption heartBeat(@PathParam(IRestPath.VAR_TEMPLATE) String template, @PathParam(IRestPath.VAR_HOST) String host, @PathParam(IRestPath.VAR_AGENT) String agent, @PathParam(IRestPath.VAR_UUID) String uuidString);

}

Add interface for agent communication.

Add interface for agent communication.


package org.graphstream.gama.extension.sender;

import msi.gama.precompiler.ISymbolKind;
import msi.gama.precompiler.GamlAnnotations.facet;
import msi.gama.precompiler.GamlAnnotations.facets;
import msi.gama.precompiler.GamlAnnotations.inside;
import msi.gama.precompiler.GamlAnnotations.symbol;
import msi.gama.runtime.IScope;
import msi.gama.runtime.exceptions.GamaRuntimeException;
import msi.gaml.descriptions.IDescription;
import msi.gaml.expressions.IExpression;
import msi.gaml.statements.AbstractStatement;
import msi.gaml.statements.IStatement;
import msi.gaml.types.IType;

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

@symbol(name = IKeywordGSAdditional.ADD_SENDER, kind = ISymbolKind.SINGLE_STATEMENT, with_sequence = false)
@inside(kinds = { ISymbolKind.BEHAVIOR, ISymbolKind.SINGLE_STATEMENT })
@facets(value = { @facet(name = IKeywordGSAdditional.SENDERID, type = IType.STRING, optional = false),
		 @facet(name = IKeywordGSAdditional.HOST, type = IType.STRING, optional = false),
		 @facet(name = IKeywordGSAdditional.PORT, type = IType.INT, optional = false)})
public class AddSenderStatement extends AbstractStatement implements IStatement{

	final IExpression senderid;
	final IExpression host;
	final IExpression port;

	public AddSenderStatement(IDescription desc) {
		super(desc);
		senderid = getFacet(IKeywordGSAdditional.SENDERID);
		host = getFacet(IKeywordGSAdditional.HOST);
		port = getFacet(IKeywordGSAdditional.PORT);
	}

	@Override
	protected Object privateExecuteIn(IScope scope) throws GamaRuntimeException {
		String s = (String)(senderid.value(scope));
		String h = (String)(host.value(scope));
		int p = (Integer)(port.value(scope));
		GSManager.addSender(s, h, p);
		return null;
	}

}

Add the 'add sender' command

Add the 'add sender' command


package net.licks92.wirelessredstone.util;

import static org.junit.Assert.*;

import org.junit.Test;

public class PositionTest {

    /**
     * Simple Test to ensure the values are saved correctly.
     *
     * Basically just to get the coverage.
     */
    @Test
    public void test() {
        Position pos = new Position(1, 2, 3, "world");
        assertEquals(1, pos.getPosX());
        assertEquals(2, pos.getPosY());
        assertEquals(3, pos.getPosZ());
        assertEquals("world", pos.getWorldName());
    }

}

Add Test for Utility Class 'Position'

Add Test for Utility Class 'Position'


/**
 *
 */
package com.boundary.sdk.event.snmp;

import static org.junit.Assert.*;

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

/**
 * @author davidg
 *
 */
public class OidLookupTest {

	/**
	 * @throws java.lang.Exception
	 */
	@BeforeClass
	public static void setUpBeforeClass() throws Exception {
	}

	/**
	 * @throws java.lang.Exception
	 */
	@AfterClass
	public static void tearDownAfterClass() throws Exception {
	}

	/**
	 * @throws java.lang.Exception
	 */
	@Before
	public void setUp() throws Exception {
	}

	/**
	 * @throws java.lang.Exception
	 */
	@After
	public void tearDown() throws Exception {
	}

	@Test
	public void test() {

	}

}

Add stubbed test for testing lookup of OIDs in from SNMP4J.

Former-commit-id: 6841a3af8d3fed8ff546323131551274593822c6


/*
 * JBoss, Home of Professional Open Source.
 * Copyright 2010, Red Hat, Inc., and individual contributors
 * as indicated by the @author tags. See the copyright.txt file in the
 * distribution for a full listing of individual contributors.
 *
 * This is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License as
 * published by the Free Software Foundation; either version 2.1 of
 * the License, or (at your option) any later version.
 *
 * This software is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this software; if not, write to the Free
 * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
 * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
 */
package org.jboss.hal.ballroom;

import com.google.gwt.core.client.Scheduler;
import jsinterop.annotations.JsMethod;
import jsinterop.annotations.JsOverlay;
import jsinterop.annotations.JsType;
import org.jetbrains.annotations.NonNls;

import static jsinterop.annotations.JsPackage.GLOBAL;
import static org.jboss.hal.resources.CSS.selectpicker;

@JsType(isNative = true)
public class PatternFly {

    /**
     * Same as {@code initComponents(true)}
     */
    @JsOverlay
    public static void initComponents() {
        initComponents(true);
    }

    /**
     * Initializes JavaScript based PatternFly components.
     *
     * @param scheduled whether to run the initialization using {@code Scheduler.get().scheduleDeferred()}
     */
    @JsOverlay
    public static void initComponents(boolean scheduled) {
        if (scheduled) {
            Scheduler.get().scheduleDeferred(PatternFly::init);
        } else {
            init();
        }
    }

    @JsOverlay
    private static void init() {
        $("." + selectpicker).selectpicker();
        $("[data-toggle=tooltip]").tooltip();
    }

    @JsMethod(namespace = GLOBAL)
    private native static PatternFly $(@NonNls String selector);

    private native void selectpicker();

    private native void tooltip();
}

Fix messed up 'Patternfly.java' file name (1)


package de.springbootbuch.extconfig;

import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.junit4.SpringRunner;

import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.is;

@RunWith(SpringRunner.class)
@SpringBootTest
@ActiveProfiles("demo2")
public class NegatedProfilesTest {

    @Autowired
    private ExampleConfiguration exampleConfiguration;

    @Value("${someValue}")
    private Integer someValue;

    @Test
    public void negatedProfilesShouldWork() {
        Assert.assertThat(exampleConfiguration.getGreeting(), is(equalTo("Hello, Demo2!")));
        Assert.assertThat(someValue, is(equalTo(4711)));
    }
}

Add test for negated profiles

Add test for negated profiles