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

// --main-class de.sormuras.bach.Bach
open /*test*/ module de.sormuras.bach /*extends "main" module*/ {
  requires org.junit.jupiter;

  // ---

  requires java.compiler;
  requires java.net.http;

  // exports de.sormuras.bach;
  // exports de.sormuras.bach.project;
  // exports de.sormuras.bach.project;

  uses java.util.spi.ToolProvider;
}

Add missing test module declaration


package co.phoenixlab.dn.dngearsim.bootstrap;

import javafx.beans.binding.Bindings;
import javafx.concurrent.Task;
import javafx.fxml.FXML;
import javafx.scene.control.Label;
import javafx.scene.layout.AnchorPane;
import javafx.scene.shape.Rectangle;

public class BootstrapUi {

    @FXML
    private AnchorPane pane;

    @FXML
    private Rectangle loadingBar;

    @FXML
    private Label statusText;

    @FXML
    void initialize() {
        assert pane != null : "fx:id=\"pane\" was not injected: check your FXML file 'splash.fxml'.";
        assert loadingBar != null : "fx:id=\"loadingBar\" was not injected: check your FXML file 'splash.fxml'.";
        assert statusText != null : "fx:id=\"statusText\" was not injected: check your FXML file 'splash.fxml'.";

    }

    public void bindToTask(Task<?> task) {
        assert task != null : "Task cannot be null, check invocation site";
        statusText.textProperty().
                bind(task.messageProperty());
        loadingBar.widthProperty().
                bind(Bindings.multiply(pane.widthProperty(), task.progressProperty()));
    }

    public void unbind() {
        statusText.textProperty().unbind();
        loadingBar.widthProperty().unbind();
    }
}

Add UI controller for bootstrap


class App{
	public static  void main(String... args) {
		calcTime(Integer.parseInt(args[0]));
		// calc(Integer.parseInt(args[0]), args[1], Integer.parseInt(args[2]));
	}
	private static void calc(int m, String ops, int mm){
		if (ops.equals("*")) {
			System.err.println(m * mm);
		}else if (ops.equals("/")) {
			System.err.println(m / mm);
		}else if (ops.equals("%")) {
			System.err.println(m % mm);
		}

	}
	private static void calcTime(int $sumOfSeconds){
		try{
		int $houers=	( $sumOfSeconds		   ) / 3600;
		int $minutes=	( $sumOfSeconds % (3600)) / 60 ;
		int $secounds=	( $sumOfSeconds % (3600)  - $minutes * 60) ;
		System.err.println($houers+":"+$minutes+":"+$secounds);
	}catch(ArithmeticException ex){System.err.println(ex.getMessage());}
	}
}

Write a java program that inputs an integer that represents a length of time in seconds. The program should then output the number of hours, minutes, and seconds that corresponds to that number of seconds. For example, if the user inputs 50391 total seconds then the program should output 13 hours, 59 minutes, and 51 seconds. (Note: Don't use loops or if condition)


package leetcode.valid_number;

public class Solution {

	public boolean isExponent(String s){
		if(s.length() == 0) return false;
		int first = s.toLowerCase().indexOf('e');
		int last = s.toLowerCase().lastIndexOf('e');
		if(first != last) return false;
		if(first < 0) return false;
		return isFloat(s.substring(0, first)) && isInteger(s.substring(first + 1));
	}

	public boolean isFloat(String s){
		if(s.length() == 0) return false;
		if(isInteger(s)) return true;
		int first = s.indexOf('.');
		int last = s.lastIndexOf('.');
		if(first != last) return false;
		if(first < 0) return false;
		int start = 0;
		if(s.charAt(0) == '+' || s.charAt(0) == '-') start = 1;
		if(isAllDigit(s.substring(start, first), true) && isAllDigit(s.substring(first + 1), false)) return true;
		if(isAllDigit(s.substring(start, first), false) && isAllDigit(s.substring(first + 1), true)) return true;
		return false;
	}

	public boolean isAllDigit(String s, boolean canBeEmpty){
		if(s.length() == 0 && !canBeEmpty) return false;
		char [] chars = s.toCharArray();
		for(int i = 0; i < chars.length; i++){
			char c = chars[i];
			if(!Character.isDigit(c)) return false;
		}
		return true;
	}

	public boolean isInteger(String s){
		if(s.length() == 0) return false;
		char[] chars = s.toCharArray();
		if(chars[0] == '+' || chars[0] == '-') return isAllDigit(s.substring(1), false);
		return isAllDigit(s, false);
	}

    public boolean isNumber(String s) {
    	s = s.trim();
    	if(s.length() == 0) return false;
    	// floating point
    	if(isFloat(s)) return true;
    	// Exponent +1e10
    	if(isExponent(s)) return true;
    	return false;
    }

    public static void main(String[] args){
    	System.err.println(new Solution().isNumber("-."));
    }
}

Add java solution for 65. Valid Number


package org.opendatakit.consts;

/**
 * Created by jbeorse on 7/17/17.
 */

public class RequestCodeConsts {
    /**
     * Request codes, used with startActivityForResult
     */
    public static final class RequestCodes {
        /**
         * Used to view a collection or a join table in a SpreadsheetFragment in
         * TableDisplayActivity
         */
        public static final int DISPLAY_VIEW = 1;
        /**
         * Used when launching the file picker to change the detail view file
         */
        public static final int CHOOSE_DETAIL_FILE = 2;
        /**
         * Used when launching the file picker to change the list view file
         */
        public static final int CHOOSE_LIST_FILE = 3;
        /**
         * Used when launching the file picker to change the map view file
         */
        public static final int CHOOSE_MAP_FILE = 4;
        /**
         * A generic code for now. Can refactor to make more specific if needed.
         */
        public static final int LAUNCH_VIEW = 5;
        /**
         * Used to launch the device preferences screen (the one with the server settings, device
         * settings, tables specific settings, user restrictions, etc... options)
         */
        public static final int LAUNCH_DISPLAY_PREFS = 6;
        /**
         * For launching an intent to import csv files into a table
         */
        public static final int LAUNCH_IMPORT = 7;
        /**
         * For launching an intent to sync
         */
        public static final int LAUNCH_SYNC = 8;
        /**
         * For launching an HTML file not associated with a table. Unused
         */
        public static final int LAUNCH_WEB_VIEW = 10;
        /**
         * For launching an intent to edit a table's properties.
         */
        public static final int LAUNCH_TABLE_PREFS = 11;
        /**
         * For launching an intent to list a column's color rules
         */
        public static final int LAUNCH_COLOR_RULE_LIST = 16;
        /**
         * For launching an intent to add a row in survey
         */
        public static final int ADD_ROW_SURVEY = 17;
        /**
         * For launching an intent to edit a row in survey
         */
        public static final int EDIT_ROW_SURVEY = 18;
        /**
         * For launching an intent to resolve checkpoints
         */
        public static final int LAUNCH_CHECKPOINT_RESOLVER = 19;
        /**
         * For launching an intent to resolve conflicts
         */
        public static final int LAUNCH_CONFLICT_RESOLVER = 20;
        /**
         * For launching an intent to export a table to a csv
         */
        public static final int LAUNCH_EXPORT = 21;
        /**
         * Used when the javascript has started a DoAction and needs to be notified of its result
         */
        public static final int LAUNCH_DOACTION = 22;
        /**
         * Used to launch an intent to open a column preference fragment via table level preference
         * activity
         */
        public static final int LAUNCH_COLUMN_PREFS = 23;

        /**
         * Do not instantiate this class
         */
        private RequestCodes() {
        }
    }

}

Generalize request code constants out of Tables


/*
 *  Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
 *
 *  WSO2 Inc. 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.wso2.carbon.connector.framework.websocket;

import java.util.HashMap;
import java.util.Map;
import javax.websocket.Session;

/**
 * This interface can be used to set the common details of a given WebSocket message.

 * Note: Use this class in the application level only and only if the user needs to set the parameters of a given
 * WebSocket message or need transport properties in any mean.

 *
 * Casting any WebSocket message to this class in the application level is not recommended. If user needs this class
 * for any casting in application level indicates that there is a missing functionality from the given WebSocket
 * message type.

 *
 * Also note that this class is public since developers might need to create WebSocket messages in the application
 * level for testing purposes and this class can be extended to use the setter methods for those purposes.
 */
public abstract class WebSocketMessagePropertiesManager {

    private Map<String, Object> properties = new HashMap<>();

    public void setProperty(String key, Object value) {
        properties.put(key, value);
    }

    public void setProperties(Map<String, Object> properties) {
        properties.entrySet().forEach(
                entry -> this.properties.put(entry.getKey(), entry.getValue())
        );
    }

    public Object getProperty(String key) {
        return properties.get(key);
    }

    public Map<String, Object> getProperties() {
        return properties;
    }

    // WebSocket channel context related setters
    abstract void setSubProtocol(String subProtocol);
    abstract void setTarget(String target);
    abstract void setListenerPort(String listenerPort);
    abstract void setWebSocketProtocolVersion(String protocolVersion);
    abstract void setIsConnectionSecured(boolean isConnectionSecured);

    // WebSocket Session context related setters
    abstract void setServerSession(Session serverSession);
    abstract void addClientSession(Session clientSession);
}

Introduce WebSocket message properties manager


package leetcode;

/**
 * https://oj.leetcode.com/problemset/algorithms/
 */
public class Problem29 {
    public int divide(int dividend, int divisor) {
        // TODO: to be implemented
        return 0;
    }

    public static void main(String[] args) {
        Problem29 prob = new Problem29();
    }
}

Put skeleton for problem 29


package info.u_team.u_team_test.init;

import info.u_team.u_team_test.entity.TestLivingEntity;
import net.minecraft.entity.ai.attributes.GlobalEntityTypeAttributes;
import net.minecraftforge.eventbus.api.IEventBus;
import net.minecraftforge.fml.event.lifecycle.FMLCommonSetupEvent;

public class TestGlobalEntityTypeAttributes {

	private static void setup(FMLCommonSetupEvent event) {
		event.enqueueWork(() -> {
			GlobalEntityTypeAttributes.put(TestEntityTypes.TEST_LIVING.get(), TestLivingEntity.registerAttributes().create());
		});
	}

	public static void registerMod(IEventBus bus) {
		bus.addListener(TestGlobalEntityTypeAttributes::setup);
	}

}

Create test entity type attributes


/*
 * (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.test.forced;

import static org.junit.jupiter.api.Assertions.assertThrows;

import java.util.List;

import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.openqa.selenium.WebDriver;

import io.github.bonigarcia.SeleniumExtension;

@ExtendWith(SeleniumExtension.class)
public class ForcedEmptyListJupiterTest {

    @Test
    public void test(List<WebDriver> drivers) {
        assertThrows(NullPointerException.class, () -> drivers.get(0));
    }

}

Include test with empty list of Docker browsers


package net.kencochrane.raven.log4j;

import mockit.Expectations;
import mockit.Injectable;
import mockit.Mocked;
import mockit.Verifications;
import net.kencochrane.raven.Raven;
import net.kencochrane.raven.event.Event;
import net.kencochrane.raven.event.EventBuilder;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.apache.log4j.spi.LoggingEvent;
import org.hamcrest.Matchers;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;

import java.util.Date;
import java.util.UUID;

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

public class SentryAppenderNGTest {
    private SentryAppender sentryAppender;
    @Mocked
    private Raven mockRaven = null;

    @BeforeMethod
    public void setUp() {
        sentryAppender = new SentryAppender(mockRaven);
    }

    @Test
    public void testSimpleMesageLogging(@Injectable final Logger logger) throws Exception {
        final String loggerName = UUID.randomUUID().toString();
        final String message = UUID.randomUUID().toString();
        final String threadName = UUID.randomUUID().toString();
        final Date date = new Date(1373883196416L);
        new Expectations() {{
                logger.getName();
                result = loggerName;
            }};

        sentryAppender.append(new LoggingEvent(null, logger, date.getTime(), Level.INFO, message, threadName,
                null, null, null, null));

        new Verifications() {{
            Event event;
            mockRaven.runBuilderHelpers(withAny(new EventBuilder()));
            mockRaven.sendEvent(event = withCapture());
            assertThat(event.getMessage(), is(message));
            assertThat(event.getLogger(), is(loggerName));
            assertThat(event.getExtra(), Matchers.<String, Object>hasEntry(SentryAppender.THREAD_NAME, threadName));
            assertThat(event.getTimestamp(), is(date));
        }};
    }
}

Add new tests using testNG in raven-log4j


package org.slc.sli.modeling.rest;

import static org.junit.Assert.*;

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

import org.junit.Before;
import org.junit.Test;
import org.slc.sli.modeling.xdm.DmNode;

/**
 *
 * JUnit test for Documentation class.
 *
 * @author wscott
 *
 */
public class DocumentationTest {

    private Documentation documentation;  //class under test
    private static final String TITLE = "doctest";
    private static final String LANGUAGE = "en";
    private final List<DmNode> CONTENTS = new ArrayList<DmNode>(0);

    @Before
    public void setup() {
        documentation = new Documentation(TITLE, LANGUAGE, CONTENTS);
    }

    @Test (expected = NullPointerException.class)
    public void testNullContents() {
        new Documentation(TITLE, LANGUAGE, null);
    }

    @Test
    public void testGetTitle() {
        assertEquals(TITLE, documentation.getTitle());
    }

    @Test
    public void testGetLanguage() {
        assertEquals(LANGUAGE, documentation.getLanguage());
    }

    @Test
    public void testGetContents() {
        assertEquals(CONTENTS, documentation.getContents());
    }

    @Test
    public void testToString() {
        String expected = "{language : " + LANGUAGE + ", title : " + TITLE + ", contents : []}";
        assertEquals(expected, documentation.toString());
    }

}

Add JUnit test for Documentation class in rest modeling module.


package leetcode;

import java.util.Iterator;

/**
 * https://leetcode.com/problems/peeking-iterator/
 */
public class Problem284 {
    private static class PeekingIterator implements Iterator<Integer> {
        public PeekingIterator(Iterator<Integer> iterator) {
            // initialize any member here.
        }

        // Returns the next element in the iteration without advancing the iterator.
        public Integer peek() {
            // TODO
            return null;
        }

        // hasNext() and next() should behave the same as in the Iterator interface.
        // Override them if needed.
        @Override
        public Integer next() {
            // TODO
            return null;
        }

        @Override
        public boolean hasNext() {
            // TODO
            return false;
        }
    }

    public static void main(String[] args) {

    }
}

Add a skeleton for problem 284


package io.pivotal.arca.provider;

import android.content.ContentValues;
import android.database.Cursor;
import android.database.MatrixCursor;
import android.net.Uri;

public abstract class SearchDataset extends ContextDataset {

    public abstract Cursor search(String[] args) throws Exception;

    @Override
    public Cursor query(final Uri uri, final String[] projection, final String selection, final String[] selectionArgs, final String sortOrder) {
        try {
            return search(selectionArgs);
        } catch (final Exception e) {
            return new MatrixCursor(new String[] { "_id" });
        }
    }

    @Override
    public int update(final Uri uri, final ContentValues values, final String selection, final String[] selectionArgs) {
        throw new UnsupportedOperationException();
    }

    @Override
    public Uri insert(final Uri uri, final ContentValues values) {
        throw new UnsupportedOperationException();
    }

    @Override
    public int bulkInsert(final Uri uri, final ContentValues[] values) {
        throw new UnsupportedOperationException();
    }

    @Override
    public int delete(final Uri uri, final String selection, final String[] selectionArgs) {
        throw new UnsupportedOperationException();
    }
}

Add search dataset to provider


package roart.common.inmemory.model;

import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;

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

import roart.common.constants.Constants;

import org.apache.commons.codec.digest.DigestUtils;

public class InmemoryUtil {
    private static Logger log = LoggerFactory.getLogger(InmemoryUtil.class);

    public static boolean validate(String md5, String content) {
        String contentMd5 = DigestUtils.md5Hex(content.getBytes(StandardCharsets.ISO_8859_1) );
        if (!md5.equals(contentMd5)) {
            log.error("Md5 differs {} {}", md5, contentMd5);
            return false;
        }
        return true;
    }

    public static boolean validate(String md5, InputStream content) {
        String contentMd5;
        try {
            contentMd5 = DigestUtils.md5Hex(content);
        } catch (Exception e) {
            log.error(Constants.EXCEPTION, e);
            return false;
        }
        if (!md5.equals(contentMd5)) {
            log.error("Md5 differs {} {}", md5, contentMd5);
            return false;
        }
        return true;
    }

    public static byte[] convertWithCharset(String content) {
        return content.getBytes(StandardCharsets.ISO_8859_1);
    }

    public static String convertWithCharset(byte[] bytes) {
        try {
            return new String(bytes, "ISO_8859_1");
        } catch (Exception e) {
            log.error(Constants.EXCEPTION, e);
        }
        return null;
    }

    public static String convertWithCharset(Path path) {
        try {
            return new String(Files.readAllBytes(path), "ISO_8859_1");
        } catch (Exception e) {
            log.error(Constants.EXCEPTION, e);
        }
        return null;
    }
}

Add utils for communication with small msg and data in memory (I243).


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

/**
 * Given a String as input, can you write a method to check if that String is a palindrome?
 *
 * A palindrome is a word, phrase, number, or other sequence of characters which reads the same
 * backward or forward. Allowances may be made for adjustments to capital letters, punctuation, and
 * word dividers.
 *
 * @author Pedro Vicente Gómez Sánchez.
 */
public class Palindromes {
}

Add statement to problem 26


// Copyright (C) 2019 The Android 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 com.google.gerrit.index.query;

import static com.google.common.truth.Truth.assertThat;

import com.google.common.truth.ThrowableSubject;
import com.google.gerrit.testing.GerritBaseTests;
import java.util.Collection;
import java.util.Objects;
import org.junit.Test;

public class QueryBuilderTest extends GerritBaseTests {
  private static class TestPredicate extends Predicate<Object> {
    private final String field;
    private final String value;

    TestPredicate(String field, String value) {
      this.field = field;
      this.value = value;
    }

    @Override
    public Predicate<Object> copy(Collection<? extends Predicate<Object>> children) {
      throw new UnsupportedOperationException();
    }

    @Override
    public int hashCode() {
      return Objects.hash(field, value);
    }

    @Override
    public boolean equals(Object o) {
      if (!(o instanceof TestPredicate)) {
        return false;
      }
      TestPredicate p = (TestPredicate) o;
      return Objects.equals(field, p.field) && Objects.equals(value, p.value);
    }
  }

  private static class TestQueryBuilder extends QueryBuilder<Object> {
    TestQueryBuilder() {
      super(new QueryBuilder.Definition<>(TestQueryBuilder.class));
    }

    @Operator
    public Predicate<Object> a(String value) {
      return new TestPredicate("a", value);
    }
  }

  @Test
  public void fieldNameAndValue() throws Exception {
    assertThat(parse("a:foo")).isEqualTo(new TestPredicate("a", "foo"));
  }

  @Test
  public void fieldWithParenthesizedValues() throws Exception {
    assertThatParseException("a:(foo bar)")
        .hasMessageThat()
        .isEqualTo("line 1:2 no viable alternative at input '('");
  }

  private static Predicate<Object> parse(String query) throws Exception {
    return new TestQueryBuilder().parse(query);
  }

  private static ThrowableSubject assertThatParseException(String query) {
    try {
      new TestQueryBuilder().parse(query);
      throw new AssertionError("expected QueryParseException for " + query);
    } catch (QueryParseException e) {
      return assertThat(e);
    }
  }
}

Add simple test of index-agnostic QueryBuilder


package by.vshkl.mvp.domain;

import by.vshkl.mvp.model.Quote;
import by.vshkl.repository.Repository;
import io.reactivex.Observable;

public class DeleteQuoteUsecase implements Usecase<Boolean> {

    private Repository repository;
    private Quote quote;

    public DeleteQuoteUsecase(Repository repository) {
        this.repository = repository;
    }

    public void setQuote(Quote quote) {
        this.quote = quote;
    }

    @Override
    public Observable<Boolean> execute() {
        return repository.deleteQuote(quote);
    }
}

Delete quote from favourites usecase added


package com.btkelly.gnag.utils;

import org.gradle.api.Project;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

public interface DefaultRelativeFilePathComputer {

    /**
     * @param absoluteFilePath the absolute path to a target file. Should be trimmed of all excess whitespace and
     *                         newlines.
     * @param project the current project
     * @return the path to the target file, relative to the root directory of the current project, iff the target file
     *         is contained within that directory; null otherwise
     */
    @Nullable
    default String computeFilePathRelativeToProjectRoot(
            @NotNull final String absoluteFilePath, @NotNull final Project project) {

        final String expectedFilePathPrefix = project.getRootDir().getAbsolutePath() + "/";

        if (!absoluteFilePath.startsWith(expectedFilePathPrefix)) {
            // The target file _is not_ contained within the root directory of the current project. Return null.
            return null;
        } else {
            /*
             * The target file _is_ contained within the root directory of the current project. Return the path to the
             * target file relative to the root directory.
             */
            return absoluteFilePath.replace(expectedFilePathPrefix, "");
        }
    }

}

Add interface that handles default absolute -> relative file path conversions


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.


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


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


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


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


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


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


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);
        }
    }
}

Add common methods for runtime log4j setup


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


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


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


/*
 * #%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


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


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


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


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


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.


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


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


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.


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


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


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


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


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


/*
 * #%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


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


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


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