/*
 * 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.harmony.beans.tests.java.beans.beancontext;

import java.beans.beancontext.BeanContextServiceProvider;
import java.beans.beancontext.BeanContextServices;
import java.beans.beancontext.BeanContextServicesSupport;
import java.util.Iterator;

import junit.framework.TestCase;

/*
 * Regression test for HARMONY-1369
 */
public class BeanContextServicesSupport2Test extends TestCase {

    public void test() {
        BeanContextServiceProvider bcsp = new BCSP();
        BCSS serviceSupport = new BCSS(new BeanContextServicesSupport());
        assertTrue("Expected first addService to return true", serviceSupport
                .addService(Boolean.TYPE, bcsp, false));
        assertFalse("Expected second addService to return false", serviceSupport
                .addService(Boolean.TYPE, bcsp, false));
    }

    class BCSP implements BeanContextServiceProvider {
        public Iterator getCurrentServiceSelectors(BeanContextServices p0,
                Class p1) {
            return null;
        }

        public void releaseService(BeanContextServices p0, Object p1, Object p2) {
            return;
        }

        public Object getService(BeanContextServices p0, Object p1, Class p2,
                Object p3) {
            return null;
        }
    }

    class BCSS extends BeanContextServicesSupport {
        public BCSS() {
            super();
        }

        public BCSS(BeanContextServicesSupport peer) {
            super(peer);
        }

        public boolean addService(Class serviceClass,
                BeanContextServiceProvider bcsp, boolean firevent) {
            return super.addService(serviceClass, bcsp, firevent);
        }
    }

}

Add regression test for HARMONY-1369 ([classlib][beans] compatibility: java.beans.beancontext.BeanContextServicesSupport.addService(..) returns true on RI and false on Harmony)


package com.vaadin.tests.components.ui;

import com.vaadin.annotations.Theme;
import com.vaadin.server.VaadinRequest;
import com.vaadin.tests.components.AbstractTestUI;
import com.vaadin.ui.Label;

@Theme("tests-tickets")
public class TestUITheme extends AbstractTestUI {

    @Override
    protected void setup(VaadinRequest request) {
        Label label = new Label("A red label");
        label.setStyleName("red");
        addComponent(label);
    }

    @Override
    public String getTestDescription() {
        return "UI with @Theme(\"tests-tickets\")";
    }

    @Override
    protected Integer getTicketNumber() {
        return Integer.valueOf(7885);
    }

}

package com.vaadin.tests.components.ui;

import com.vaadin.annotations.Theme;
import com.vaadin.server.VaadinRequest;
import com.vaadin.tests.components.AbstractTestUI;
import com.vaadin.ui.Label;

@Theme("tests-tickets")
public class TestUITheme extends AbstractTestUI {

    @Override
    protected void setup(VaadinRequest request) {
        Label label = new Label("A green label");
        label.setStyleName("green");
        addComponent(label);
    }

    @Override
    public String getTestDescription() {
        return "UI with @Theme(\"tests-tickets\"). The label uses a stylename that should only be defined in the test-tickets theme.";
    }

    @Override
    protected Integer getTicketNumber() {
        return Integer.valueOf(7885);
    }

}

Update test to not use red for success.


package com.sebastian.sokolowski.auctionhunter.database.models;

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

/**
 * Created by Sebastian Sokołowski on 03.03.17.
 */

public class Cat extends RealmObject {
    @PrimaryKey
    private Integer catId;
    private String catName;
    private Integer catParent;
    private Integer catPosition;
    private Integer catIsProductCatalogueEnabled;

    public Integer getCatId() {
        return catId;
    }

    public void setCatId(Integer catId) {
        this.catId = catId;
    }

    public String getCatName() {
        return catName;
    }

    public void setCatName(String catName) {
        this.catName = catName;
    }

    public Integer getCatParent() {
        return catParent;
    }

    public void setCatParent(Integer catParent) {
        this.catParent = catParent;
    }

    public Integer getCatPosition() {
        return catPosition;
    }

    public void setCatPosition(Integer catPosition) {
        this.catPosition = catPosition;
    }

    public Integer getCatIsProductCatalogueEnabled() {
        return catIsProductCatalogueEnabled;
    }

    public void setCatIsProductCatalogueEnabled(Integer catIsProductCatalogueEnabled) {
        this.catIsProductCatalogueEnabled = catIsProductCatalogueEnabled;
    }
}

Add new category realm model.


/*
 * Copyright (C) 2014  Ohm Data
 *
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU Affero General Public License as
 *  published by the Free Software Foundation, either version 3 of the
 *  License, or (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU Affero General Public License for more details.
 *
 *  You should have received a copy of the GNU Affero General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package c5db.interfaces.log;

import org.hamcrest.Description;
import org.hamcrest.TypeSafeMatcher;

import java.util.List;

import static c5db.interfaces.log.SequentialEntryIterable.SequentialEntryIterator;

public class SequentialEntryIterableMatchers {
  public static <E extends SequentialEntry> TypeSafeMatcher<SequentialEntryIterator<E>>
  isIteratorContainingInOrder(List<E> entries) {

    return new TypeSafeMatcher<SequentialEntryIterator<E>>() {
      private Exception exception;

      @Override
      protected boolean matchesSafely(SequentialEntryIterator<E> iterator) {
        int listIndex = 0;

        try {
          while (iterator.hasNext()) {
            E next = iterator.next();
            if (listIndex >= entries.size()
                || !next.equals(entries.get(listIndex))) {
              return false;
            }

            listIndex++;
          }
        } catch (Exception e) {
          exception = e;
          return false;
        }

        return listIndex == entries.size();
      }

      @Override
      public void describeTo(Description description) {
        description.appendText(" a SequentialEntryIterator containing, in order, ")
            .appendValue(entries);
      }

      @Override
      protected void describeMismatchSafely(SequentialEntryIterator<E> item, Description mismatchDescription) {
        if (exception != null) {
          mismatchDescription.appendValue(exception);
        } else {
          super.describeMismatchSafely(item, mismatchDescription);
        }
      }
    };
  }
}

Add a matcher class for SequentialEntryIterable and its iterator


package leetcode.integer_to_roman;

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

public class Solution {
    public String intToRoman(int num) {
    	Map<Integer, String> map = new HashMap<Integer, String>();
    	StringBuilder sb = new StringBuilder();
    	String[] romans = new String[]{
    		"", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX",
    		"X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC",
    		"C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM",
    		"M", "MM", "MMM",
    	};
    	for(int i = 0; i <= 9; i++){
    		map.put(i, romans[i]);
    	}
    	for(int i = 10; i <= 90; i += 10){
    		map.put(i, romans[i / 10 + 9]);
    	}
    	for(int i = 100; i <= 900; i += 100){
    		map.put(i, romans[i / 100 + 18]);
    	}
    	for(int i = 1000; i <= 3000; i += 1000){
    		map.put(i, romans[i / 1000 + 27]);
    	}
    	for(int x = 1000; x >= 1; x /= 10){
    		sb.append(map.get((num / x % 10) * x));
    	}
    	return sb.toString();
    }

    public static void main(String[] args){
    	for(int i = 1; i <= 3999; i++){
    		System.err.println(i + ":" + new Solution().intToRoman(i));
    	}
    }
}

Add java solution for 12. Integer to Roman


package com.google.re2j;

import static org.junit.Assert.fail;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;

@RunWith(Parameterized.class)
public class RE2CompileTest {
  // A list of regexp and expected error when calling RE2.compile. null implies that compile should
  // succeed.
  @Parameters()
  public static String[][] testData() {
    return new String[][]{
      {"", null},
      {".", null},
      {"^.$", null},
      {"a", null},
      {"a*", null},
      {"a+", null},
      {"a?", null},
      {"a|b", null},
      {"a*|b*", null},
      {"(a*|b)(c*|d)", null},
      {"[a-z]", null},
      {"[a-abc-c\\-\\]\\[]", null},
      {"[a-z]+", null},
      {"[abc]", null},
      {"[^1234]", null},
      {"[^\n]", null},
      {"\\!\\\\", null},
      {"abc]",  null}, // Matches the closing bracket literally.
      {"a??", null},
      {"*", "missing argument to repetition operator: `*`"},
      {"+", "missing argument to repetition operator: `+`"},
      {"?", "missing argument to repetition operator: `?`"},
      {"(abc", "missing closing ): `(abc`"},
      {"abc)", "regexp/syntax: internal error: `stack underflow`"},
      {"x[a-z", "missing closing ]: `[a-z`"},
      {"[z-a]", "invalid character class range: `z-a`"},
      {"abc\\", "trailing backslash at end of expression"},
      {"a**", "invalid nested repetition operator: `**`"},
      {"a*+", "invalid nested repetition operator: `*+`"},
      {"\\x", "invalid escape sequence: `\\x`"},
    };
  }

  private final String input;
  private final String expectedError;

  public RE2CompileTest(String input, String expectedError) {
    this.input = input;
    this.expectedError = expectedError;
  }

  @Test
  public void testCompile() {
    try {
      RE2.compile(input);
      if (expectedError != null) {
        fail("RE2.compile(" + input + ") was successful, expected " + expectedError);
      }
    } catch (PatternSyntaxException e) {
      if (expectedError == null ||
          !e.getMessage().equals("error parsing regexp: " + expectedError)) {
        fail("compiling " + input + "; unexpected error: " + e.getMessage());
      }
    }
  }
}

Split out RE2.compile test into its own parameterized JUnit4 test


package info.u_team.u_team_test.data.provider;

import info.u_team.u_team_core.data.*;

public class TestItemTagsProvider extends CommonItemTagsProvider {

	public TestItemTagsProvider(GenerationData data, CommonBlockTagsProvider blockProvider) {
		super(data, blockProvider);
	}

	@Override
	protected void registerTags() {
	}

}

Add test item tags provider


package uk.ac.ebi.spot.goci.curation.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.AsyncResult;
import org.springframework.stereotype.Service;
import uk.ac.ebi.spot.goci.curation.model.SnpAssociationTableView;
import uk.ac.ebi.spot.goci.model.Association;
import uk.ac.ebi.spot.goci.model.Study;
import uk.ac.ebi.spot.goci.repository.AssociationRepository;
import uk.ac.ebi.spot.goci.repository.StudyRepository;

import java.util.ArrayList;
import java.util.Collection;
import java.util.concurrent.Future;

/**
 * Created by emma on 06/06/2016.
 *
 * @author emma
 *         <p>
 *         Service to create a printable view of all study details
 */
@Service
public class StudyPrintService {

    private StudyRepository studyRepository;
    private AssociationRepository associationRepository;
    private AssociationViewService associationViewService;

    @Autowired
    public StudyPrintService(StudyRepository studyRepository,
                             AssociationRepository associationRepository,
                             AssociationViewService associationViewService) {
        this.studyRepository = studyRepository;
        this.associationRepository = associationRepository;
        this.associationViewService = associationViewService;
    }

    public Collection<SnpAssociationTableView> generatePrintView(Long studyId) {
        // Get relevant study details
        Study studyToView = studyRepository.findOne(studyId);

        // Association information
        Collection<Association> associations = new ArrayList<>();
        associations.addAll(associationRepository.findByStudyId(studyId));

        // For our associations create a table view object and return
        Collection<SnpAssociationTableView> snpAssociationTableViews = new ArrayList<SnpAssociationTableView>();
        for (Association association : associations) {
            SnpAssociationTableView snpAssociationTableView =
                    associationViewService.createSnpAssociationTableView(association);
            snpAssociationTableViews.add(snpAssociationTableView);
        }
        return snpAssociationTableViews;
    }
}

Move the association view creation to this service rather that controller


package de.lmu.ifi.dbs.elki.math.statistics.distribution.estimator;

/*
 This file is part of ELKI:
 Environment for Developing KDD-Applications Supported by Index-Structures

 Copyright (C) 2013
 Ludwig-Maximilians-Universität München
 Lehr- und Forschungseinheit für Datenbanksysteme
 ELKI Development Team

 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/>.
 */
import de.lmu.ifi.dbs.elki.math.statistics.distribution.WaldDistribution;
import de.lmu.ifi.dbs.elki.utilities.datastructures.arraylike.NumberArrayAdapter;
import de.lmu.ifi.dbs.elki.utilities.optionhandling.AbstractParameterizer;

/**
 * Estimate parameter of the Wald distribution.
 *
 * @author Erich Schubert
 *
 * @apiviz.has WaldDistribution
 */
public class WaldMLEstimator implements DistributionEstimator<WaldDistribution> {
  /**
   * Static instance.
   */
  public static final WaldMLEstimator STATIC = new WaldMLEstimator();

  @Override
  public <A> WaldDistribution estimate(A data, NumberArrayAdapter<?, A> adapter) {
    final int len = adapter.size(data);
    double mean = 0.;
    for(int i = 0; i < len; i++) {
      double v = adapter.getDouble(data, i);
      mean += v;
    }
    mean /= len;
    double invmean = len / mean;
    double invdev = 0.;
    for(int i = 0; i < len; i++) {
      double v = adapter.getDouble(data, i);
      if(v > 0.) {
        invdev += len / v - invmean;
      }
    }
    return new WaldDistribution(mean, 1. / invdev);
  }

  @Override
  public Class<? super WaldDistribution> getDistributionClass() {
    return WaldDistribution.class;
  }

  /**
   * Parameterization class.
   *
   * @author Erich Schubert
   *
   * @apiviz.exclude
   */
  public static class Parameterizer extends AbstractParameterizer {
    @Override
    protected WaldMLEstimator makeInstance() {
      return STATIC;
    }
  }
}

Add estimator for Wald, untested.


/*
 * The Alluxio Open Foundation licenses this work under the Apache License, version 2.0
 * (the "License"). You may not use this work except in compliance with the License, which is
 * available at www.apache.org/licenses/LICENSE-2.0
 *
 * This software is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
 * either express or implied, as more fully set forth in the License.
 *
 * See the NOTICE file distributed with this work for information regarding copyright ownership.
 */

package alluxio.master.file;

import static org.junit.Assert.assertEquals;

import alluxio.AlluxioURI;
import alluxio.master.file.StartupConsistencyCheck.Status;

import com.google.common.collect.ImmutableList;
import org.junit.Test;

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

/**
 * Unit tests for {@link StartupConsistencyCheck}.
 */
public final class StartupConsistencyCheckTest {
    @Test
    public void createCompleteCheck() {
        List<AlluxioURI> uris = ImmutableList.of(new AlluxioURI("/"), new AlluxioURI("/dir"));
        StartupConsistencyCheck check = StartupConsistencyCheck.complete(uris);
        assertEquals(Status.COMPLETE, check.getStatus());
        assertEquals(uris, check.getInconsistentUris());
    }

    @Test
    public void createDisabledCheck() {
        StartupConsistencyCheck check = StartupConsistencyCheck.disabled();
        assertEquals(Status.DISABLED, check.getStatus());
        assertEquals(Collections.EMPTY_LIST, check.getInconsistentUris());
    }

    @Test
    public void createFailedCheck() {
        StartupConsistencyCheck check = StartupConsistencyCheck.failed();
        assertEquals(Status.FAILED, check.getStatus());
        assertEquals(Collections.EMPTY_LIST, check.getInconsistentUris());
    }

    @Test
    public void createRunningCheck() {
        StartupConsistencyCheck check = StartupConsistencyCheck.running();
        assertEquals(Status.RUNNING, check.getStatus());
        assertEquals(Collections.EMPTY_LIST, check.getInconsistentUris());
    }
}

Add startup consistency check unit test


package net.alcuria.umbracraft.definitions.skill.actions;

import net.alcuria.umbracraft.Game;
import net.alcuria.umbracraft.Listener;
import net.alcuria.umbracraft.engine.entities.Entity;

import com.badlogic.gdx.math.Vector3;

public class CameraChangeDefinition extends SkillActionDefinition {
	public static enum CameraDirection {
		CENTER(CENTER_POS, CENTER_POS), FAR(CENTER_POS - OFFSET, CENTER_POS + OFFSET), NEAR(CENTER_POS + OFFSET, CENTER_POS - OFFSET);

		private int friendly, nonFriendly;

		CameraDirection(int friendly, int nonFriendly) {
			this.friendly = friendly;
			this.nonFriendly = nonFriendly;
		}

		public int getPosition(final boolean isFriendly) {
			return isFriendly ? friendly : nonFriendly;
		}
	}

	private static final int CENTER_POS = 290; // center of the battle map
	private static final int OFFSET = 40; // offset for the left/right grid focus
	private final Entity cameraTarget;
	private final CameraDirection direction;
	private final boolean isFriendly;

	public CameraChangeDefinition(CameraDirection direction, boolean isFriendly, Entity cameraTarget) {
		this.direction = direction;
		this.cameraTarget = cameraTarget;
		this.isFriendly = isFriendly;
	}

	@Override
	public void start(Entity entity, Vector3 start, Vector3 target) {
		Game.view().setTarget(cameraTarget);
		cameraTarget.position.x = direction.getPosition(isFriendly);
	}

	@Override
	public void update(Entity entity, Listener stepCompleteListener) {
		stepCompleteListener.invoke();
	}

}

Add a definition to handle camera changes


/*
 * Copyright (c) 2016 Red Hat and others.  All rights reserved.
 *
 * This program and the accompanying materials are made available under the
 * terms of the Eclipse Public License v1.0 which accompanies this distribution,
 * and is available at http://www.eclipse.org/legal/epl-v10.html
 */
/**
 * Black magic Mockito utility.
 *
 *
This artifact is "black magic" because by merely depending on it (by its
 * presence on the classpath, without ever using any of its classes), all usages
 * of core Mockito.mock() in your existing tests will suddenly behave
 * differently automagically all by themselves: They will throw
 * ThrowsUnstubbedMethodException instead of returning null etc. as in default
 * Mockito. (This "magic" is also the technical reason why this is package
 * org.mockito.configuration instead of org.opendaylight.*)
 *
 *
TODO Point to the "other/new artifact with more sane Mockito helper, with
 * explicit API.
 *
 * @see MockitoConfiguration
 * @see org.mockito.configuration.IMockitoConfiguration
 */
package org.mockito.configuration;

Package JavaDoc to clarify what this artifact is & does


package com.cflint.plugins.core;

import ro.fortsoft.pf4j.Extension;
import net.htmlparser.jericho.Element;
import cfml.parsing.cfscript.CFExpression;
import cfml.parsing.cfscript.script.CFScriptStatement;

import com.cflint.BugInfo;
import com.cflint.BugList;
import com.cflint.plugins.CFLintScannerAdapter;

@Extension
public class FileCaseChecker extends CFLintScannerAdapter {
	final String severity = "INFO";

	public void startFile(String fileName, BugList bugs) {
		String actualFileName = fileName;
		String separator = System.getProperty("file.separator");
    	int seperatorPosition = fileName.lastIndexOf(separator);

    	if (seperatorPosition >= 0) {
    		actualFileName = fileName.substring(seperatorPosition + 1);
    	}

		if (actualFileName.contains(".cfm")) {
			if (Character.isUpperCase(actualFileName.charAt(0))) {
				bugs.add(new BugInfo.BugInfoBuilder().setLine(1).setMessageCode("FILE_SHOULD_START_WITH_LOWERCASE")
						.setSeverity(severity).setFilename(fileName)
						.setMessage("File " + actualFileName + " starts with a upper case letter. Only components (.cfc files) should start with an upper case letter.")
						.build());
			}
		}
	}
}

Add rule to check if .cfm files start with an upper case letter


package nl.ekholabs.nlp;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.RequestBuilder;

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

@RunWith(SpringRunner.class)
@AutoConfigureMockMvc
@SpringBootTest
public class ElsieDeeApplicationTest {

  @Autowired
  private MockMvc mvc;

  @Test
  public void statusOk() throws Exception {
    final RequestBuilder request = get("/");
    mvc.perform(request).andExpect(status().is4xxClientError());
  }
}

Add test to check if the application is starting.


package nom.bdezonia.zorbage.misc;

import static org.junit.Assert.*;

import org.junit.Test;

public class TestLongUtils {

	@Test
	public void test() {
		assertEquals(0, LongUtils.numElements(new long[] {}));
		assertEquals(1, LongUtils.numElements(new long[] {1}));
		assertEquals(6, LongUtils.numElements(new long[] {2,3}));
		assertEquals(120, LongUtils.numElements(new long[] {4,5,6}));
		try {
			LongUtils.numElements(new long[] {-1});
			fail();
		} catch (IllegalArgumentException e) {
			assertTrue(true);
		}
		try {
			LongUtils.numElements(new long[] {2, Long.MAX_VALUE});
			fail();
		} catch (IllegalArgumentException e) {
			assertTrue(true);
		}
	}

}

Define tests for LongUtils class


package pl.vgtworld.imagedraw.filters.edgedetect;

import pl.vgtworld.imagedraw.ImageDrawEntity;
import pl.vgtworld.imagedraw.filters.ImageDrawFilter;
import pl.vgtworld.imagedraw.filters.matrix.MatrixFilter;

public class EdgeDetectFilter implements ImageDrawFilter {

	@Override
	public void doFilter(ImageDrawEntity image, int x, int y, int width, int height) {
		float[][] matrix = new float[][] {
				{ 0, 1, 0 },
				{ 1, -4, 1 },
				{ 0, 1, 0 }
		};
		MatrixFilter filter = new MatrixFilter(matrix);
		filter.doFilter(image, x, y, width, height);
	}

}

Add edge detection filter implementation.


/*
 * 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 be.fror.password.rule;

import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertThat;

import com.google.common.collect.ImmutableList;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;

/**
 *
 * @author Olivier Grégoire <https://github.com/fror>
 */
public class RuleResultTest {

  public RuleResultTest() {
  }

  /**
   *
   */
  @BeforeClass
  public static void setUpClass() {
  }

  /**
   *
   */
  @AfterClass
  public static void tearDownClass() {
  }

  /**
   *
   */
  @Before
  public void setUp() {
  }

  /**
   *
   */
  @After
  public void tearDown() {
  }

  /**
   * Test of isValid method, of class RuleResult.
   */
  @Test
  public void testIsValid() {
  }

  /**
   * Test of getFailures method, of class RuleResult.
   */
  @Test
  public void testGetFailures() {
  }

  /**
   * Test of ok method, of class RuleResult.
   */
  @Test
  public void testOk() {
    RuleResult result = RuleResult.ok();

    assertThat(result.isValid(), is(true));
    assertThat(result.getFailures(), is(equalTo(ImmutableList.of())));
  }

  /**
   * Test of failed method, of class RuleResult.
   */
  @Test
  public void testFailed_0args() {
    RuleResult result = RuleResult.failed();

    assertThat(result.isValid(), is(false));
    assertThat(result.getFailures(), is(equalTo(ImmutableList.of())));
  }

  /**
   * Test of failed method, of class RuleResult.
   */
  @Test
  public void testFailed_String() {
  }

  /**
   * Test of failed method, of class RuleResult.
   */
  @Test
  public void testFailed_3args() {
  }

  /**
   * Test of failed method, of class RuleResult.
   */
  @Test
  public void testFailed_5args() {
  }

  /**
   * Test of failed method, of class RuleResult.
   */
  @Test
  public void testFailed_7args() {
  }

  /**
   * Test of failed method, of class RuleResult.
   */
  @Test
  public void testFailed_String_Map() {
  }

}

Add basic unit tests for RuleResult.


/**
 * 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 CamelAwsSwfTest extends BaseKarafTest {

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

    @Test
    public void test() throws Exception {
    	testComponent(COMPONENT);
    }

}

Create single Karaf feature tests for single components, aws-swf test


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

import junit.framework.Test;

import org.apache.commons.collections4.trie.PatriciaTrie;
import org.apache.commons.collections4.trie.UnmodifiableTrie;

/**
 * Tests for TrieUtils factory methods.
 *
 * @version $Id$
 */
public class TrieUtilsTest extends BulkTest {

    public TrieUtilsTest(final String name) {
        super(name);
    }

    public static Test suite() {
        return BulkTest.makeSuite(TrieUtilsTest.class);
    }

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

    public void testUnmodifiableTrie() {
        Trie<String, Object> trie = TrieUtils.unmodifiableTrie(new PatriciaTrie<Object>());
        assertTrue("Returned object should be an UnmodifiableTrie.",
            trie instanceof UnmodifiableTrie);
        try {
            TrieUtils.unmodifiableTrie(null);
            fail("Expecting IllegalArgumentException for null trie.");
        } catch (final IllegalArgumentException ex) {
            // expected
        }
    }

}

Add unit test for TrieUtils.


package leetcode;

/**
 * https://leetcode.com/problems/trapping-rain-water/
 */
public class Problem42 {
    public int trap(int[] height) {
        return 0;
    }

    public static void main(String[] args) {
        Problem42 prob = new Problem42();
        System.out.println(prob.trap(new int[]{0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1})); // 6
    }
}

Create a skeleton for problem 42


package io.github.droidkaigi.confsched2017.util;

import android.app.Activity;
import android.net.Uri;
import android.support.annotation.NonNull;
import android.support.customtabs.CustomTabsIntent;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.webkit.URLUtil;

import io.github.droidkaigi.confsched2017.R;

/**
 * Created by shihochan on 2017/02/15.
 */

public class AppUtil {

    public static void openCustomTab(Activity activity, @NonNull String url) {
        if (TextUtils.isEmpty(url) || !URLUtil.isNetworkUrl(url)) {
            return;
        }

        CustomTabsIntent intent = new CustomTabsIntent.Builder()
                .setShowTitle(true)
                .setToolbarColor(ContextCompat.getColor(activity, R.color.theme))
                .build();

        intent.launchUrl(activity, Uri.parse(url));
    }
}

Implement app utility class and open chrome custom tabs method


package de.biomedical_imaging.traJ.features;

import javax.vecmath.Point3d;

import de.biomedical_imaging.traJ.Trajectory;

/**
 * Maximum distance from start point
 * @author Thorsten Wagner
 *
 */
public class MaxDistanceFromStartPointFeature extends AbstractTrajectoryFeature{
	Trajectory t;

	public MaxDistanceFromStartPointFeature(Trajectory t) {
		this.t = t;
	}

	@Override
	public double[] evaluate() {
		double maxDist = Double.MIN_VALUE;
		Point3d start = t.get(0);

		for(int i = 1; i < t.size(); i++){
			double d =start.distance(t.get(i));

			if(d > maxDist){
				maxDist = d;
			}
		}

		return new double[]{maxDist};
	}

	@Override
	public String getName() {
		// TODO Auto-generated method stub
		return "Max distances from start point";
	}

	@Override
	public String getShortName() {
		// TODO Auto-generated method stub
		return "MaxDist";
	}

	@Override
	public void setTrajectory(Trajectory t) {
		this.t = t;

	}

}

Add feature: maximum distance from start point


package seedu.address.model.datastructure;

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

/**
 * This class will handle the partial search algorithm and the search function itself
 */
public class PartialSearch {

    private final Set<String> infixes = new HashSet<>();

    private String itemToSearch;

    public PartialSearch(String itemToSearch) {
        this.itemToSearch = itemToSearch;
        prepareSearch();
    }

    /**
     * This method prepares the infix set for search
     */
    public void prepareSearch() {
        for (int i = 0; i < itemToSearch.length(); i++) {
            for (int j = i + 1; j <= itemToSearch.length(); j++) {
                infixes.add(itemToSearch.substring(i, j).toLowerCase());
            }
        }
    }

    /**
     * This method does the search by matching the hash set for match
     * @param searchString
     * @return true if exist and false if otherwise
     */
    public boolean search(String searchString) { // O(1) search
        return infixes.contains(searchString.toLowerCase());
    }
}

Add partial search algorithm and data structure


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

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

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

import com.google.common.testing.EqualsTester;

/**
 * Unit tests for SubnetId class.
 */
public class SubnetIdTest {

    final SubnetId subnetId1 = SubnetId.subnetId("1");
    final SubnetId sameAsSubnetId1 = SubnetId.subnetId("1");
    final SubnetId subnetId2 = SubnetId.subnetId("2");

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

    /**
     * Checks the operation of equals() methods.
     */
    @Test
    public void testEquals() {
        new EqualsTester().addEqualityGroup(subnetId1, sameAsSubnetId1).addEqualityGroup(subnetId2)
                .testEquals();
    }

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

Add the junit test code of SubnetId


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

import com.google.common.annotations.Beta;
import org.onosproject.net.PortNumber;
import org.onosproject.net.driver.HandlerBehaviour;

/**
 * A HandlerBehaviour to check the capability of VLAN.
 */
@Beta
public interface VlanQuery extends HandlerBehaviour {

    /**
     * Indicates if VLAN can be used at the port.
     *
     * @param port port to be checked for the capability
     * @return true if VLAN can be used at the port, false otherwise.
     */
    boolean isEnabled(PortNumber port);
}

Define an interface to query about VLAN capability


package me.zhengjie.utils;

import org.junit.Test;
import org.springframework.mock.web.MockHttpServletRequest;

import java.text.SimpleDateFormat;
import java.util.*;

import static me.zhengjie.utils.StringUtils.*;
import static org.junit.Assert.*;

public class StringUtilsTest {

    @Test
    public void testInString() {
        assertTrue(inString("?", "?"));
        assertFalse(inString("?", new String[]{}));
    }

    @Test
    public void testToCamelCase() {
        assertNull(toCamelCase(null));
    }

    @Test
    public void testToCapitalizeCamelCase() {
        assertNull(StringUtils.toCapitalizeCamelCase(null));
        assertEquals("HelloWorld", toCapitalizeCamelCase("hello_world"));
    }

    @Test
    public void testToUnderScoreCase() {
        assertNull(StringUtils.toUnderScoreCase(null));
        assertEquals("hello_world", toUnderScoreCase("helloWorld"));
        assertEquals("\u0000\u0000", toUnderScoreCase("\u0000\u0000"));
        assertEquals("\u0000_a", toUnderScoreCase("\u0000A"));
    }

    @Test
    public void testGetWeekDay() {
        SimpleDateFormat simpleDateformat = new SimpleDateFormat("E");
        assertEquals(simpleDateformat.format(new Date()), getWeekDay());
    }

    @Test
    public void testGetIP() {
        assertEquals("127.0.0.1", getIP(new MockHttpServletRequest()));
    }
}

Add unit tests for me.zhengjie.utils.StringUtils


package ch.rasc.eds.starter.entity;

import java.util.UUID;

import org.bson.codecs.IdGenerator;

public class UUIDStringGenerator implements IdGenerator {

	@Override
	public Object generate() {
		return UUID.randomUUID().toString();
	}

}

Add a simple id generator that converts uuid to string


package org.cometd.javascript.jquery;

import java.util.Map;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

import org.cometd.Bayeux;
import org.cometd.Client;
import org.cometd.server.BayeuxService;
import org.mozilla.javascript.ScriptableObject;
import org.testng.annotations.Test;

/**
 * @version $Revision$ $Date$
 */
public class CometdDeliverTest extends AbstractCometdJQueryTest
{
    private DeliverService service;

    protected void customizeBayeux(Bayeux bayeux)
    {
        super.customizeBayeux(bayeux);
        service = new DeliverService(bayeux);
    }

    @Test
    public void testDeliver() throws Exception
    {
        defineClass(Latch.class);

        evaluateScript("$.cometd.configure({url: '" + cometURL + "', logLevel: 'debug'});");
        evaluateScript("var _data;");
        evaluateScript("$.cometd.addListener('/deliver', function(message) { _data = message.data; });");

        evaluateScript("$.cometd.handshake();");

        // Wait for the handshake to complete
        Thread.sleep(1000);

        evaluateScript("var latch = new Latch(1);");
        Latch latch = get("latch");
        evaluateScript("var listener = $.cometd.addListener('/meta/publish', function(message) { latch.countDown(); });");
        evaluateScript("$.cometd.publish('/deliver', { deliver: false });");
        assert latch.await(1000);
        evaluateScript("$.cometd.removeListener(listener);");
        evaluateScript("window.assert(_data === undefined);");

        evaluateScript("latch = new Latch(1);");
        evaluateScript("listener = $.cometd.addListener('/meta/publish', function(message) { latch.countDown(); });");
        evaluateScript("$.cometd.publish('/deliver', { deliver: true });");
        assert latch.await(1000);
        evaluateScript("$.cometd.removeListener(listener);");
        // Wait for the listener to be notified
        Thread.sleep(500);
        evaluateScript("window.assert(_data !== undefined);");

        evaluateScript("$.cometd.disconnect();");
        Thread.sleep(500);
    }

    public static class Latch extends ScriptableObject
    {
        private volatile CountDownLatch latch;

        public String getClassName()
        {
            return "Latch";
        }

        public void jsConstructor(int count)
        {
            latch = new CountDownLatch(count);
        }

        public boolean await(long timeout) throws InterruptedException
        {
            return latch.await(timeout, TimeUnit.MILLISECONDS);
        }

        public void jsFunction_countDown()
        {
            latch.countDown();
        }
    }

    public static class DeliverService extends BayeuxService
    {
        public DeliverService(Bayeux bayeux)
        {
            super(bayeux, "deliver");
            subscribe("/deliver", "deliver");
        }

        public void deliver(Client remote, String channel, Object messageData, String messageId)
        {
            Map<String, ?> data = (Map<String,?>)messageData;
            Boolean deliver = (Boolean) data.get("deliver");
            if (deliver)
            {
                remote.deliver(getClient(), channel, messageData, messageId);
            }
        }
    }
}

Test for addListener() and deliver().


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

/**
 * Package containing an api for obtaining timing information about propagated contexts.
 *
 *
{@linkplain nl.talsmasoftware.context.timing.ContextTimer}

 *

 * Interface to be implemented and registered as SPI to receive updates about propagated contexts.
 * An example on how to use this can be found in the {@code context-propagation-metrics} library
 * that uses this functionality to update Dropwizard metrics' {@code Timer} instances.
 */
package nl.talsmasoftware.context.timing;

Add javadoc to the timing package


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

package org.springframework.boot.bind;

import java.util.Locale;

import org.junit.Test;

import org.springframework.core.convert.support.DefaultConversionService;

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

/**
 * Tests for {@link RelaxedConversionService}.
 *
 * @author Madhura Bhave
 */
public class RelaxedConversionServiceTests {

	private RelaxedConversionService conversionService = new RelaxedConversionService(new DefaultConversionService());

	@Test
	public void conversionServiceShouldAlwaysUseLocaleEnglish() {
		Locale.setDefault(new Locale("tr"));
		TestEnum result = this.conversionService.convert("accept-case-insensitive-properties",
				TestEnum.class);
		assertThat(result.equals(TestEnum.ACCEPT_CASE_INSENSITIVE_PROPERTIES));
	}

	enum TestEnum {

		ACCEPT_CASE_INSENSITIVE_PROPERTIES

	}

}

Add tests for binding to enum with different locale


package org.roklib.urifragmentrouting.parameter;

import org.roklib.urifragmentrouting.parameter.converter.ISO8601ToLocalDateParameterValueConverter;
import org.roklib.urifragmentrouting.parameter.converter.ParameterValueConverter;

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

public class SingleLocalDateUriParameterTest extends AbstractSingleUriParameterTest<LocalDate> {

    @Override
    public LocalDate getTestValue() {
        return LocalDate.of(2014, Month.SEPTEMBER, 8);
    }

    @Override
    public LocalDate getDefaultValue() {
        return LocalDate.now();
    }

    @Override
    public AbstractSingleUriParameter<LocalDate> getTestSingleURIParameter(String parameterName) {
        return new SingleLocalDateUriParameter(parameterName);
    }

    @Override
    public ParameterValueConverter<LocalDate> getTypeConverter() {
        return ISO8601ToLocalDateParameterValueConverter.INSTANCE;
    }
}

Add unit test for SingleLocalDateUriParameter


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

package org.spine3.tools.codestyle.javadoc;

import org.junit.Test;
import org.spine3.tools.codestyle.StepConfiguration;
import org.spine3.tools.codestyle.rightmargin.RightMarginValidator;

import java.io.File;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;

import static org.junit.Assert.*;

public class InvalidFqnUsageValidatorShould {
    public InvalidFqnUsageValidator validator;

    @Test(expected = RuntimeException.class)
    public void throw_exception_for_invalid_fqn_links_over_threshold() throws InvalidFqnUsageException {
        validator = setUpValidator(2, "error");
        validator.validate(getPath("MultipleWrongFqnLinks.java"));
    }

    @Test(expected = RuntimeException.class)
    public void throw_exception_file_format_is_not_utf8() throws InvalidFqnUsageException {
        validator = setUpValidator(2, "error");
        validator.validate(getPath("MultipleWrongFqnLinks.java"));
    }

    @Test
    public void check_only_files_with_java_extension() {
        validator = setUpValidator(0, "error");
        validator.validate(getPath(".hiden_file"));
    }

    @Test
    public void throw_warning_for_invalid_fqn_links_over_threshold() {
        validator = setUpValidator(2, "warn");
        validator.validate(getPath("MultipleWrongFqnLinks.java"));
    }

    @Test
    public void allow_correct_fqn_links() throws IOException {
        validator = setUpValidator(0, "error");
        validator.validate(getPath("AllowedFqnFormats.java"));

    }

    private static InvalidFqnUsageValidator setUpValidator(int threshold, String reportType) {
        final StepConfiguration configuration = new StepConfiguration();
        configuration.setThreshold(threshold);
        configuration.setReportType(reportType);
        InvalidFqnUsageValidator validator = new InvalidFqnUsageValidator(configuration);
        return validator;
    }

    private Path getPath (String fileName){
        final ClassLoader classLoader = getClass().getClassLoader();
        final File file = new File(classLoader.getResource(fileName).getFile());
        final Path path = Paths.get(file.getAbsolutePath());
        return path;
    }
}

Add unit tests for `InvalidFqnUsageValidator`.


/**
 * Load some tweets stored as JSON data and explore them.
 */
package com.oreilly.learningsparkexamples.java;

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

import org.apache.commons.lang.StringUtils;

import org.apache.spark.SparkConf;
import org.apache.spark.api.java.JavaSparkContext;
import org.apache.spark.sql.api.java.JavaSQLContext;

public class SparkSQLTwitter {
  public static void main(String[] args) {
    SparkConf conf = new SparkConf();
    JavaSparkContext sc = new JavaSparkContext(conf);
    JavaSQLContext sqlCtx = new JavaSQLContext(sc);
    }
}

Add the Spark SQL Java example


package com.bbn.bue.common.evaluation;

import com.bbn.bue.common.collections.IterableUtils.ZipPair;
import com.bbn.bue.common.symbols.Symbol;

import com.google.common.collect.ImmutableList;

import org.junit.Test;

import static com.bbn.bue.common.collections.IterableUtils.zip;
import static junit.framework.TestCase.assertEquals;

public class SummaryConfusionMatrixTest {

  private static final Symbol LOC = Symbol.from("LOC");
  private static final Symbol ORG = Symbol.from("ORG");
  private static final Symbol PER = Symbol.from("PER");

  @Test
  public void testSummaryConfusionMatrix() {
    final ImmutableList<Symbol> goldAssignments = ImmutableList.of(
        PER, LOC, ORG, ORG, ORG, LOC, PER, PER);
    final ImmutableList<Symbol> systemAssignments = ImmutableList.of(
        PER, ORG, ORG, PER, ORG, LOC, PER, LOC);

    final SummaryConfusionMatrices.Builder confusionMatrixB = SummaryConfusionMatrices.builder();

    for (final ZipPair<Symbol, Symbol> goldSystemPair : zip(goldAssignments, systemAssignments)) {
      final Symbol goldSymbol = goldSystemPair.first();
      final Symbol systemSymbol = goldSystemPair.second();

      confusionMatrixB.accumulatePredictedGold(systemSymbol, goldSymbol, 1.0);
    }

    final SummaryConfusionMatrix confusionMatrix = confusionMatrixB.build();

    // F-measure for PER: 2 true positives, 1 false positive, 1 false negative
    // precision = 2/3, recall = 2/3, F = 2/3
    assertEquals(2.0F / 3.0F,
        SummaryConfusionMatrices.FMeasureVsAllOthers(confusionMatrix, PER).F1());

    // F-measure for ORG: 2 true positives, 1 false positive, 1 false negative
    // precision = 2/3, recall = 2/3, F = 2/3
    assertEquals(2.0F / 3.0F,
        SummaryConfusionMatrices.FMeasureVsAllOthers(confusionMatrix, ORG).F1());

    // F-measure for LOC: 1 true positive, 1 false positive, 1 false negative
    // precision = 1/2, recall = 1/2, F=1/2
    assertEquals(0.5F, SummaryConfusionMatrices.FMeasureVsAllOthers(confusionMatrix, LOC).F1());
  }
}

Add test and example for SummaryConfusionMatrix


package com.stefanhoth.ropasclisp;

import android.graphics.Bitmap;
import android.graphics.BitmapShader;
import android.graphics.Canvas;
import android.graphics.ColorFilter;
import android.graphics.Paint;
import android.graphics.PixelFormat;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.Shader;
import android.graphics.drawable.Drawable;
import android.support.annotation.ColorInt;

public class CircularFrameDrawable extends Drawable {

    private final Drawable content;
    private final RectF bounds;
    private final Paint backgroundPaint;
    private final Paint contentPaint;
    private final Paint outlinePaint;

    public CircularFrameDrawable(Drawable content, @ColorInt int backgroundColor, @ColorInt int outlineColor) {
        this.content = content;
        this.bounds = new RectF();
        this.backgroundPaint = getBackgroundPaint(backgroundColor);
        this.contentPaint = new Paint();
        this.outlinePaint = getOutlinePaint(outlineColor);
    }

    private Paint getBackgroundPaint(@ColorInt int backgroundColor) {
        Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
        paint.setColor(backgroundColor);
        paint.setStyle(Paint.Style.FILL);
        return paint;
    }

    private Paint getOutlinePaint(@ColorInt int outlineColor) {
        Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
        paint.setColor(outlineColor);
        paint.setStyle(Paint.Style.STROKE);
        return paint;
    }

    @Override
    protected void onBoundsChange(Rect bounds) {
        this.bounds.set(bounds);
        content.setBounds(bounds);
        outlinePaint.setStrokeWidth(bounds.width() * .05f);
        contentPaint.setShader(null);
    }

    @Override
    public int getIntrinsicWidth() {
        return content.getIntrinsicWidth();
    }

    @Override
    public int getIntrinsicHeight() {
        return content.getIntrinsicHeight();
    }

    @Override
    public void draw(Canvas canvas) {
        if (contentPaint.getShader() == null) {
            updateContentPaint(content);
        }
        canvas.drawOval(bounds, backgroundPaint);
        canvas.drawOval(bounds, contentPaint);
        canvas.drawOval(bounds, outlinePaint);
    }

    private void updateContentPaint(Drawable content) {
        Rect bounds = getBounds();
        Bitmap bitmap = Bitmap.createBitmap(bounds.width(), bounds.height(), Bitmap.Config.ARGB_8888);
        content.draw(new Canvas(bitmap));
        contentPaint.setShader(new BitmapShader(bitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP));
    }

    @Override
    public void setAlpha(int alpha) {
        backgroundPaint.setAlpha(alpha);
        contentPaint.setAlpha(alpha);
        outlinePaint.setAlpha(alpha);
    }

    @Override
    public void setColorFilter(ColorFilter colorFilter) {
        backgroundPaint.setColorFilter(colorFilter);
        contentPaint.setColorFilter(colorFilter);
        outlinePaint.setColorFilter(colorFilter);
    }

    @Override
    public int getOpacity() {
        return PixelFormat.UNKNOWN;
    }

}

Add custom drawable to draw hand signs with correct clipping.


/**
 * Created by nadia on 02/10/2016.
 */
public abstract class Shape2D extends  Shape implements  Translatable2D{

    private Point2D refPoint ;

    public Shape2D(Point2D refPoint) {

        this.refPoint = refPoint;
    }
    public Shape2D() {
    }

    public abstract double perimeter();

    public Point2D getRefPoint() {
        return refPoint;
    }
}

ADD THE API OF SHAPE2D


/*
 * Copyright (c) 2016 Fraunhofer FOKUS
 * 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.openbaton.exceptions;

/**
 * Created by lto on 13/06/16.
 */
public class EntityUnreachableException extends Exception {
    public EntityUnreachableException(String message) {
        super(message);
    }

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

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

Improve logs and add check on vim reachability


/*
 * Copyright 2015 Open mHealth
 *
 * 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.openmhealth.data.generator.configuration;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.validation.beanvalidation.LocalValidatorFactoryBean;

/**
 * @author Emerson Farrugia
 */
@Configuration
public class ValidationConfiguration {

    @Bean
    public javax.validation.Validator localValidatorFactoryBean() {
        return new LocalValidatorFactoryBean();
    }
}

Add a JSR-303 validator configuration


package guitests;

import static org.junit.Assert.assertTrue;

import org.junit.Test;

import seedu.tache.logic.commands.UndoCommand;
import seedu.tache.testutil.TestTask;

public class UndoCommandTest extends TaskManagerGuiTest {

    @Test
    public void undo() {
        //nothing to undo
        commandBox.runCommand(UndoCommand.COMMAND_WORD);
        assertResultMessage(UndoCommand.MESSAGE_EMPTY_HISTORY);

        //add one task
        TestTask[] currentList = td.getTypicalTasks();
        TestTask taskToAdd = td.getFit;
        commandBox.runCommand(taskToAdd.getAddCommand());
        assertUndoSuccess(currentList);

        //TODO: Add undo cases for other commands
    }

    private void assertUndoSuccess(TestTask... originalList) {
        commandBox.runCommand(UndoCommand.COMMAND_WORD);

        //confirm the list now contains the previous tasks
        assertTrue(taskListPanel.isListMatching(originalList));
    }
}

Add partial test case for Undo Command


package som.tests;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Collection;

import org.graalvm.polyglot.Context;
import org.graalvm.polyglot.Context.Builder;
import org.graalvm.polyglot.Source;
import org.graalvm.polyglot.Value;
import org.graalvm.polyglot.tck.LanguageProvider;
import org.graalvm.polyglot.tck.Snippet;

import som.Launcher;
import som.interpreter.SomLanguage;
import som.vm.VmOptions;

public class SomSnippets implements LanguageProvider {

  @SuppressWarnings("unused")
  void foo() {
    Builder builder = Launcher.createContextBuilder(new String[] {
        "--kernel", VmOptions.STANDARD_KERNEL_FILE,
        "--platform", VmOptions.STANDARD_PLATFORM_FILE});
    Context context = builder.build();

    InputStream in = getClass().getResourceAsStream("TruffleSomTCK.ns");
    try {
      Source source = Source.newBuilder(
          SomLanguage.LANG_ID, new InputStreamReader(in), "TruffleSomTCK.ns").build();
    } catch (IOException e) {
      throw new RuntimeException(e);
    }

    // TODO:
    // Value tckModule = context.eval(source);
    // tckModule.SClass tck = tckModule.as(SClass.class);
    //
    // ObjectTransitionSafepoint.INSTANCE.register();
    // tck.getMixinDefinition().instantiateObject(tck, vm.getVmMirror());
    // ObjectTransitionSafepoint.INSTANCE.unregister();
  }

  @Override
  public String getId() {
    return SomLanguage.LANG_ID;
  }

  @Override
  public Value createIdentityFunction(final Context context) {
    // TODO Auto-generated method stub
    return null;
  }

  @Override
  public Collection<? extends Snippet> createValueConstructors(final Context context) {
    // TODO Auto-generated method stub
    return null;
  }

  @Override
  public Collection<? extends Snippet> createExpressions(final Context context) {
    // TODO Auto-generated method stub
    return null;
  }

  @Override
  public Collection<? extends Snippet> createStatements(final Context context) {
    // TODO Auto-generated method stub
    return null;
  }

  @Override
  public Collection<? extends Snippet> createScripts(final Context context) {
    // TODO Auto-generated method stub
    return null;
  }

  @Override
  public Collection<? extends Source> createInvalidSyntaxScripts(final Context context) {
    // TODO Auto-generated method stub
    return null;
  }

}

Add support for Polyglot TCK


/*
 * Copyright 2008 Arne Limburg
 *
 * 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 net.sf.jpasecurity.persistence;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;

import junit.framework.TestCase;
import net.sf.jpasecurity.security.authentication.TestAuthenticationProvider;

/**
 * @author Arne Limburg
 * @author Johannes Siemer
 */
public class JpqlQueryParserTest extends TestCase {

    public static final String USER1 = "user1";

    public void testCount() {
        executeQuery("SELECT COUNT(tb) FROM FieldAccessAnnotationTestBean tb");
    }

    public void testDistinct() {
        executeQuery("SELECT DISTINCT tb FROM FieldAccessAnnotationTestBean tb");
    }

    public void testExists() {
        executeQuery(
            "SELECT tb FROM FieldAccessAnnotationTestBean tb WHERE EXISTS(SELECT tb2 FROM FieldAccessAnnotationTestBean tb2)");
    }

    private void executeQuery(String query) {
        TestAuthenticationProvider.authenticate(USER1);
        EntityManagerFactory factory = Persistence.createEntityManagerFactory("annotation-based-field-access");
        EntityManager entityManager = factory.createEntityManager();
        entityManager.getTransaction().begin();
        entityManager.createQuery(query).getResultList();
        entityManager.getTransaction().rollback();
        entityManager.close();
    }

    public void tearDown() {
        TestAuthenticationProvider.authenticate(null);
    }
}

Test demonstrating a bug handling COUNT-Queries


/*
 * Copyright 2017 haeun kim
 *
 * 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 algorithm.boj;

import java.io.*;

/**
 * Created by haeun on 2017-10-02
 * Site       : https://www.acmicpc.net/problem/1316
 */

public class Boj1316 {

    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        int n = Integer.parseInt(br.readLine());
        int result = n ;
        String[] inputs = new String[n];
        for(int i=0; i<n; i++){
            inputs[i] = br.readLine();
        }
        for(int i=0; i<n; i++){
            int[] atoz = new int[26];
            char pre = ' ';
            int noGroup = 0;
            for(int j=0; j<inputs[i].length(); j++){
                if(pre != inputs[i].charAt(j)) {
                    atoz[(int) inputs[i].charAt(j) - 97]++;
                }
                pre = inputs[i].charAt(j);
            }
            for(int j=0; j<atoz.length; j++){
                if(atoz[j]>1){
                    noGroup++;
                }
            }
            if(noGroup > 0){
                result--;
            }
        }
        System.out.println(result);
    }

}

Solve No.1316 from Baekjoon Online Judge


package npe;

import edu.umd.cs.findbugs.annotations.CheckForNull;

public class CheckForNullField {
	@CheckForNull Object x;
	 public int getNonNullXDoNotReport() {
		if (x == null)
			x = new Object();
		return x.hashCode();
	}
	 public Object getNonNullXDoNotReport2() {
		if (x != null) return x.hashCode();
		x = new Object();
		return x.hashCode();
	}
}

Add test case for @CheckForNull fields


package at.ac.tuwien.inso.service.course_recommendation.filters;

import org.springframework.stereotype.Component;

import java.util.List;
import java.util.stream.Collectors;

import at.ac.tuwien.inso.entity.Course;
import at.ac.tuwien.inso.entity.Student;

@Component
public class DismissedCoursesFilter implements CourseRelevanceFilter {

    @Override
    public List<Course> filter(List<Course> courses, Student student) {
        return courses.stream().filter(course -> !student.getDismissedCourses().contains(course)).collect(Collectors.toList());
    }
}

Add filter to the recommendation algorithm to excludes dismissed courses


package com.ibm.watson.developer_cloud.speech_to_text.v1;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

import com.ibm.watson.developer_cloud.http.HttpMediaType;
import com.ibm.watson.developer_cloud.speech_to_text.v1.model.RecognizeOptions;
import com.ibm.watson.developer_cloud.speech_to_text.v1.model.SpeechResults;
import com.ibm.watson.developer_cloud.speech_to_text.v1.websocket.BaseRecognizeCallback;

/**
 * Recognize microphone input speech continuously using WebSockets.
 */
public class MicrophoneWithWebSocketsExample {
  public static void main(String[] args) throws FileNotFoundException, InterruptedException {
    SpeechToText service = new SpeechToText();
    service.setUsernameAndPassword("<username>", "<password>");

    // Signed PCM AudioFormat with 16kHz, 16 bit sample size, mono
    int sampleRate = 16000;
    AudioFormat format = new AudioFormat(sampleRate, 16, 1, true, false);
    DataLine.Info info = new DataLine.Info(TargetDataLine.class, format);

    if (!AudioSystem.isLineSupported(info)) {
      System.out.println("Line not supported");
      System.exit(0);
    }

    TargetDataLine line = (TargetDataLine) AudioSystem.getLine(info);
    line.open(format);
    line.start();

    AudioInputStream audio = new AudioInputStream(line);

    RecognizeOptions options = new RecognizeOptions.Builder()
      .continuous(true)
      .interimResults(true)
      .timestamps(true)
      .wordConfidence(true)
      //.inactivityTimeout(5) // use this to stop listening when the speaker pauses, i.e. for 5s
      .contentType(HttpMediaType.AUDIO_RAW + "; rate=" + sampleRate)
      .build();

    service.recognizeUsingWebSocket(audio, options, new BaseRecognizeCallback() {
      @Override
      public void onTranscription(SpeechResults speechResults) {
        System.out.println(speechResults);
      }
    });

    System.out.println("Listening to your voice for the next 30s...");
    Thread.sleep(30 * 1000);

    // closing the WebSockets underlying InputStream will close the WebSocket itself.
    line.stop();
    line.close();

    System.out.println("Fin.");
  }
}

Add speech-to-text Microphone + WebSocket example


package net.darkhax.bookshelf.api.util;

import com.mojang.blaze3d.vertex.PoseStack;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.Font;
import net.minecraft.network.chat.FormattedText;
import net.minecraft.util.FormattedCharSequence;

import java.util.List;

public class RenderHelper {

    public static void renderLinesWrapped (PoseStack matrix, int x, int y, FormattedText text, int textWidth) {

        final Font font = Minecraft.getInstance().font;
        renderLinesWrapped(matrix, font, x, y, font.lineHeight, 0, text, textWidth);
    }

    public static void renderLinesWrapped (PoseStack matrix, Font fontRenderer, int x, int y, int spacing, int defaultColor, FormattedText text, int textWidth) {

        renderLinesWrapped(matrix, fontRenderer, x, y, spacing, defaultColor, fontRenderer.split(text, textWidth));
    }

    public static void renderLinesWrapped (PoseStack matrix, Font fontRenderer, int x, int y, int spacing, int defaultColor, List<FormattedCharSequence> lines) {

        for (int lineNum = 0; lineNum < lines.size(); lineNum++) {

            final FormattedCharSequence lineFragment = lines.get(lineNum);
            fontRenderer.draw(matrix, lineFragment, x, y + lineNum * spacing, defaultColor);
        }
    }

    public static int renderLinesReversed (PoseStack matrix, int x, int y, FormattedText text, int textWidth) {

        final Font font = Minecraft.getInstance().font;
        return renderLinesReversed(matrix, font, x, y, font.lineHeight, 0xffffff, text, textWidth);
    }

    public static int renderLinesReversed (PoseStack matrix, Font fontRenderer, int x, int y, int spacing, int defaultColor, FormattedText text, int textWidth) {

        return renderLinesReversed(matrix, fontRenderer, x, y, spacing, defaultColor, fontRenderer.split(text, textWidth));
    }

    public static int renderLinesReversed (PoseStack matrix, Font fontRenderer, int x, int y, int spacing, int defaultColor, List<FormattedCharSequence> lines) {

        final int lineCount = lines.size();
        for (int lineNum = lineCount - 1; lineNum >= 0; lineNum--) {

            final FormattedCharSequence lineFragment = lines.get(lineCount - 1 - lineNum);
            fontRenderer.draw(matrix, lineFragment, x, y - (lineNum + 1) * (spacing + 1), defaultColor);
        }

        return lineCount * (spacing + 1);
    }
}

Add helpers for rendering wrapped text.


package swing;

import java.awt.Color;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JSplitPane;

public class TestJSplitPane2 {
  private void init() {
    JFrame frame = new JFrame();
    JPanel one = new JPanel();
    one.setBackground(Color.YELLOW);
    JPanel two = new JPanel();
    two.setBackground(Color.GREEN);
    JPanel three = new JPanel();
    three.setBackground(Color.RED);
    JPanel four = new JPanel();
    four.setBackground(Color.BLUE);
    JSplitPane splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, one, two);
    splitPane.setResizeWeight(0.5);
    splitPane.setOneTouchExpandable(true);
    JSplitPane splitPane2 = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, three, four);
    splitPane2.setResizeWeight(0.5);
    splitPane2.setOneTouchExpandable(true);
    JSplitPane splitPane3 = new JSplitPane(JSplitPane.VERTICAL_SPLIT, splitPane, splitPane2);
    splitPane3.setResizeWeight(0.5);
    splitPane3.setOneTouchExpandable(true);
    frame.setContentPane(splitPane3);
    frame.pack();
    frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
    frame.addWindowListener(new WindowAdapter() {
      @Override
      public void windowClosing(WindowEvent e) {
        int reply =
            JOptionPane.showConfirmDialog(null, "Do you really want to exit?",
                "Exit form the application", JOptionPane.YES_NO_OPTION);
        if (reply == JOptionPane.YES_OPTION) {
          JOptionPane.showMessageDialog(null, "Bye! See you later :)");
          System.exit(0);
        }
      }
    });
    frame.setVisible(true);
  }

  public static void main(String[] args) {
    new TestJSplitPane2().init();
  }
}

Add an advanced example about the JSplitPane. Using three JSplitPane with colors. Show a confirm dialog and message dialog if the user wants to exit.


/**
 * Illustrates a simple map then filter in Java
 */
package com.oreilly.learningsparkexamples.java;

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

import org.apache.commons.lang.StringUtils;

import org.apache.spark.api.java.JavaRDD;
import org.apache.spark.api.java.JavaSparkContext;
import org.apache.spark.api.java.function.Function;
import org.apache.spark.streaming.api.java.JavaDStream;
import org.apache.spark.streaming.api.java.JavaStreamingContext;
import org.apache.spark.streaming.Duration;

public class StreamingLogInput {
  public static void main(String[] args) throws Exception {
		String master = args[0];
		JavaSparkContext sc = new JavaSparkContext(
      master, "StreamingLogInput", System.getenv("SPARK_HOME"), System.getenv("JARS"));
    // Create a StreamingContext with a 1 second batch size
    JavaStreamingContext jssc = new JavaStreamingContext(sc, new Duration(1000));
    // Create a DStream from all the input on port 7777
    JavaDStream<String> lines = jssc.socketTextStream("localhost", 7777);
    // Filter our DStream for lines with "error"
    JavaDStream<String> errorLines = lines.filter(new Function<String, Boolean>() {
        public Boolean call(String line) {
          return line.contains("error");
        }});
    // Print out the lines with errors, which causes this DStream to be evaluated
    errorLines.print();
	}
}

Add simple streaming log input example


package de.gurkenlabs.litiengine.entities.behavior;

import de.gurkenlabs.litiengine.Game;
import de.gurkenlabs.litiengine.abilities.Ability;
import de.gurkenlabs.litiengine.graphics.IRenderable;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;

import java.awt.geom.Rectangle2D;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.any;
import static org.mockito.Mockito.when;

public class AStarGridTest {
    private Rectangle2D rectangle;
    private AStarGrid aStarGrid;
    private AStarNode node;

    @BeforeEach
    public void setup() {
        aStarGrid = new AStarGrid(10,20,5);
        rectangle = mock(Rectangle2D.class);
        node = mock(AStarNode.class);
        aStarGrid.getIntersectedNodes(rectangle);
        aStarGrid.updateWalkable(rectangle);
    }

    @Test
    public void testUpdateWalkable() {
        verify(rectangle, times(0)).intersects(rectangle);
    }

}

Add test case for AStarGrid::updateWalkable()


package org.pentaho.platform.dataaccess.datasource.ui.service;

import org.pentaho.ui.xul.XulServiceCallback;

import com.google.gwt.core.client.JavaScriptObject;

public class XulServiceCallbackJavascriptObject {

  XulServiceCallback<Boolean> xulCallback;
  public XulServiceCallbackJavascriptObject (XulServiceCallback<Boolean> callback){
    xulCallback = callback;
  }

  private void onSuccess(boolean flag){
    xulCallback.success(new Boolean(flag));
  }

  private void onError(String errorMsg) {
    xulCallback.error(errorMsg, null);
  }
  public native JavaScriptObject getJavascriptObject()/*-{
    var thisInstance = this;
    return {
      success : function(flag){
        thisInstance.@org.pentaho.platform.dataaccess.datasource.ui.service.XulServiceCallbackJavascriptObject::onSuccess(Z)(flag);
      },
      error : function(errorMsg) {
        thisInstance.@org.pentaho.platform.dataaccess.datasource.ui.service.XulServiceCallbackJavascriptObject::onError(Ljava/lang/String;)(errorMsg);
      }
    }
  }-*/;
}

Update some of the JSNI fix for pluggable datasources


package de.philipphager.disclosure.util.ui;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatDialogFragment;
import de.philipphager.disclosure.ApplicationComponent;
import de.philipphager.disclosure.DisclosureApp;
import de.philipphager.disclosure.feature.navigation.Navigates;
import de.philipphager.disclosure.feature.navigation.Navigator;
import javax.inject.Inject;

public abstract class BaseDialogFragment extends AppCompatDialogFragment implements Navigates {
  @Inject protected Navigator navigator;

  @Override public void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    inject();
  }

  @Override public Navigator navigate() {
    return navigator;
  }

  protected abstract void injectFragment(ApplicationComponent appComponent);

  private void inject() {
    DisclosureApp application = (DisclosureApp) getActivity().getApplication();
    injectFragment(application.getApplicationComponent());

    navigator.setActivity(getActivity());
  }
}

Add base class for dialog fragments


/* 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 tests.api.java.net;

import java.io.IOException;
import java.io.InputStream;
import java.net.SecureCacheResponse;
import java.security.Principal;
import java.security.cert.Certificate;
import java.util.List;
import java.util.Map;

import javax.net.ssl.SSLPeerUnverifiedException;

import junit.framework.TestCase;

public class SecureCacheResponseTest extends TestCase {

    public void testSecureCacheResponse() {
        // test constructor
        SecureCacheResponse sc = new MockCacheResponse();
        // nothing happened
        assertNull(sc.getCipherSuite());
    }

    class MockCacheResponse extends SecureCacheResponse{

        @Override
        public String getCipherSuite() {
            // do nothing
            return null;
        }

        @Override
        public List<Certificate> getLocalCertificateChain() {
            // do nothing
            return null;
        }

        @Override
        public Principal getLocalPrincipal() {
            // do nothing
            return null;
        }

        @Override
        public Principal getPeerPrincipal() throws SSLPeerUnverifiedException {
            // do nothing
            return null;
        }

        @Override
        public List<Certificate> getServerCertificateChain() throws SSLPeerUnverifiedException {
            // do nothing
            return null;
        }

        @Override
        public InputStream getBody() throws IOException {
            // do nothing
            return null;
        }

        @Override
        public Map<String, List<String>> getHeaders() throws IOException {
            // do nothing
            return null;
        }

    }
}

Apply patch for HARMONY-3606( [classlib][luni]Add tests for java.net.SecureCacheResponse)


/*
 * Copyright 2017 haeun kim
 *
 * 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 algorithm.boj;

import java.io.*;

/**
 * Created by haeun on 2017-09-26
 * Site       : https://www.acmicpc.net/problem/4344
 */

public class Boj4344 {

    public static void main(String[] args) throws IOException {

        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        int c = Integer.parseInt(br.readLine());

        for (int i = 0; i < c; i++) {
            String[] inputs = br.readLine().split(" ");
            int size = Integer.parseInt(inputs[0]);
            int[] inputss = new int[size];
            for (int j = 0; j < size; j++) {
                inputss[j] = Integer.parseInt(inputs[j + 1]);
            }

            float sum = 0;
            float avr[] = new float[c];

            for (int k = 0; k < size; k++) {
                sum += inputss[k];
            }

            avr[i] = sum / size;
            float count = 0;
            for (int k = 0; k < size; k++) {
                if (inputss[k] > avr[i]) {
                    count++;
                }
            }
            System.out.println(String.format("%.3f", count / size * 100) + "%");
        }

    }
}

Solve No.4344 from Baekjoon Online Judge


/*
 * (C) Copyright 2022 Boni Garcia (https://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.wdm.test.watcher;

//tag::snippet-in-doc[]
import static java.lang.invoke.MethodHandles.lookup;
import static org.assertj.core.api.Assertions.assertThat;
import static org.slf4j.LoggerFactory.getLogger;

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

import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.openqa.selenium.WebDriver;
import org.slf4j.Logger;

import io.github.bonigarcia.wdm.WebDriverManager;

class DockerGatherLogsChromeTest {

    static final Logger log = getLogger(lookup().lookupClass());

    WebDriverManager wdm = WebDriverManager.edgedriver().browserInDocker()
            .watch();
    WebDriver driver;

    @BeforeEach
    void setup() {
        driver = wdm.create();
    }

    @AfterEach
    void teardown() {
        driver.quit();
    }

    @Test
    void test() {
        driver.get(
                "https://bonigarcia.dev/selenium-webdriver-java/console-logs.html");

        List<Map<String, Object>> logMessages = wdm.getLogs();

        for (Map<String, Object> map : logMessages) {
            log.debug("[{}] [{}.{}] {}", map.get("datetime"),
                    map.get("wrapper").toString().toUpperCase(),
                    String.format("%1$-7s",
                            map.get("type").toString().toUpperCase()),
                    map.get("message"));
        }

        assertThat(logMessages).hasSize(5);
    }

}
//end::snippet-in-doc[]

Include test for gathering logs using Chrome in Docker


package com.haxademic.core.render;

import java.awt.image.BufferedImage;

import processing.core.PApplet;
import processing.core.PImage;

import com.haxademic.core.app.P;
import com.haxademic.core.image.AnimatedGifEncoder;
import com.haxademic.core.system.FileUtil;
import com.haxademic.core.system.SystemUtil;

public class GifRenderer {

	public AnimatedGifEncoder encoder;
	protected int _frameRate = 30;
	protected int _quality = 10;
	protected int _framesRendered = 0;

	public GifRenderer(int frameRate, int quality) {
		_frameRate = frameRate;
		_quality = quality;
	}

	public void startGifRender(PApplet p) {
		encoder = new AnimatedGifEncoder();
		encoder.start( FileUtil.getHaxademicOutputPath() + SystemUtil.getTimestamp(p) + "-export.gif" );
		encoder.setFrameRate( _frameRate );
		encoder.setQuality( _quality );
		encoder.setRepeat( 0 );
		P.println("== started rendering gif ==");
	}

	public void renderGifFrame(PApplet p) {
		if(encoder == null) return; // no-op if we're starting after frameCount == 1
		_framesRendered++;
		P.println("== rendering gif frame: "+_framesRendered+" ==");
		PImage screenshot = p.get();
		BufferedImage newFrame = (BufferedImage) screenshot.getNative();
		encoder.addFrame(newFrame);
	}

	public void finish() {
		P.println("== finished rendering gif ==");
		encoder.finish();
		encoder = null;
	}
}

Add gif rendering class (used in PAppletHax)


/*
 * This file is part of Dimdwarf Application Server <http://dimdwarf.sourceforge.net/>
 *
 * Copyright (c) 2008-2009, Esko Luontola. All Rights Reserved.
 *
 * Redistribution and use in source and binary forms, with or without modification,
 * are permitted provided that the following conditions are met:
 *
 *     * Redistributions of source code must retain the above copyright notice,
 *       this list of conditions and the following disclaimer.
 *
 *     * Redistributions in binary form must reproduce the above copyright notice,
 *       this list of conditions and the following disclaimer in the documentation
 *       and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
 * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
 * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

package net.orfjackal.dimdwarf;

import com.google.inject.util.ReferenceCache;
import junit.framework.TestCase;

import java.util.*;
import java.util.concurrent.*;

public class ReferenceCacheConcurrencyTest extends TestCase {

    // TODO: upgrade to Guice 2.0 and check that this bug does not appear there
    // http://groups.google.com/group/google-guice/browse_thread/thread/7cdff66a4b7acc9d
    public void testConcurrentGet() throws Exception {
        final ReferenceCache<String, String> cache = new ReferenceCache<String, String>() {
            protected String create(String key) {
                return key;
            }
        };
        ArrayList<Callable<String>> callsToGet = new ArrayList<Callable<String>>();
        for (int i = 0; i < 10; i++) {
            callsToGet.add(new Callable<String>() {
                public String call() throws Exception {
                    return cache.get("foo");
                }
            });
        }
        List<Future<String>> results = Executors.newCachedThreadPool().invokeAll(callsToGet);
        for (Future<String> result : results) {
            assertEquals("foo", result.get());
        }
    }
}

Test case for checking a bug in Guice 1.0


package org.csstudio.perspectives;

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

import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URISyntaxException;
import java.net.URL;

import org.eclipse.emf.common.util.URI;
import org.junit.Before;
import org.junit.Test;

public class FileUtilsUnitTest {

    private FileUtils fileUtils;
    private URL simpleUrl;
    private String fileString = "/tmp/hello.txt";

    @Before
    public void setUp() throws Exception {
        fileUtils = new FileUtils();
        simpleUrl = new URL("file:" + fileString);
    }

    @Test(expected=NullPointerException.class)
    public void checkUrlToEmfUriThrowsNullPointerExceptionIfNullArgument() {
        fileUtils.urlToEmfUri(null);
    }

    @Test
    public void checkUrlToEmfUriHandlesSimpleFile() throws MalformedURLException {
        URI uri = fileUtils.urlToEmfUri(simpleUrl);
        assertEquals(uri.scheme(), "file");
        assertArrayEquals(uri.segments(), new String[] {"tmp", "hello.txt"});
        assertEquals(uri.fileExtension(), "txt");
    }

    @Test(expected=NullPointerException.class)
    public void checkUrlToFileThrowsNullPointerExceptionIfNullArgument() {
        fileUtils.urlToFile(null);
    }

    @Test
    public void checkUrlToFileHandlesSimpleFile() {
        File file = fileUtils.urlToFile(simpleUrl);
        assertEquals(file.getAbsolutePath(), fileString);
    }

    @Test(expected=NullPointerException.class)
    public void checkStringPathToFileThrowsNullPointerExceptionIfArgumentIsNull() throws IOException, URISyntaxException {
        fileUtils.stringPathToFile(null);
    }

    @Test(expected=NullPointerException.class)
    public void checkStringPathToUriFileStringThrowsNullPointerExceptionIfArgumentIsNull() throws IOException, URISyntaxException {
        fileUtils.stringPathToUriFileString(null);
    }

    @Test
    public void checkStringPathToUriFileStringPrependsFile() throws IOException, URISyntaxException {
        String uri = fileUtils.stringPathToUriFileString(fileString);
        assertTrue(uri.startsWith("file"));
        assertTrue(uri.endsWith(fileString));
    }
}

Add some unit tests for FileUtils.


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

package io.spine.server.integration;

import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;

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

/**
 * @author Mykhailo Drachuk
 */
@DisplayName("Rejection Predicate should")
class RejectionPredicateTest {

    @Test
    @DisplayName("contain default error message")
    void containDefaultErrorMessage() {
        RejectionPredicate predicate = target -> true;
        String message = predicate.message();
        assertNotNull(message);
    }
}

Add a rejection predicate test.


package com.bryanjswift.simplenote.app;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;

import com.bryanjswift.simplenote.Constants;
import com.bryanjswift.simplenote.R;
import com.bryanjswift.simplenote.ui.LoginDialog;

/**
 * Helper methods for posting Notifications
 * @author bryanjswift
 */
public class Notifications {
	/**
	 * Post credentials Notification with given messages
	 * @param context under which the Notification is created
	 * @param ticker message to show when Notification is posted
	 * @param title of Notification in pull down
	 * @param description of Notification in pull down
	 */
	public static void Credentials(Context context, CharSequence ticker, CharSequence title, CharSequence description) {
		final NotificationManager notifier = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
		final Notification notification = new Notification(R.drawable.simplenote_status, title, System.currentTimeMillis());
		final PendingIntent intent = PendingIntent.getActivity(context, 0, new Intent(context, LoginDialog.class), 0);
		notification.setLatestEventInfo(context.getApplicationContext(), title, description, intent);
		notification.iconLevel = 3;
		notifier.notify(Constants.NOTIFICATION_CREDENTIALS, notification);
	}
	/**
	 * Post Notification with default invalid credentials messages
	 * @param context under which the Notification is created
	 */
	public static void Credentials(Context context) {
		Credentials(context,
				context.getString(R.string.status_credentials_invalid_ticker),
				context.getString(R.string.status_credentials_invalid_title),
				context.getString(R.string.status_credentials_invalid_description));
	}
}

Create helper class to assist with Notification posting


/*
 * 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.sis.util.iso;

import java.util.Map;
import java.util.Set;
import org.opengis.util.Type;
import org.opengis.util.TypeName;
import org.opengis.util.MemberName;
import org.opengis.util.Record;
import org.opengis.util.RecordType;
import org.opengis.util.RecordSchema;

/**
 * Auto-generated by NetBeans.
 */
public class DefaultRecordType implements RecordType {

    @Override
    public TypeName getTypeName() {
        throw new UnsupportedOperationException();
    }

    @Override
    public RecordSchema getContainer() {
        throw new UnsupportedOperationException();
    }

    @Override
    public Map<MemberName, Type> getMemberTypes() {
        throw new UnsupportedOperationException();
    }

    @Override
    public Set<MemberName> getMembers() {
        throw new UnsupportedOperationException();
    }

    @Override
    public TypeName locate(MemberName mn) {
        throw new UnsupportedOperationException();
    }

    @Override
    public boolean isInstance(Record record) {
        throw new UnsupportedOperationException();
    }
}

Add the auto-generated stub for licensing reason (making clear that we start this class from scratch).


package org.knowm.xchange.service.trade.params;

import org.knowm.xchange.currency.CurrencyPair;

public class DefaultCancelOrderByPairAndIfParams implements CancelOrderByIdParams, CancelOrderByCurrencyPair {

	private CurrencyPair currencyPair;
	private String orderId;

	public DefaultCancelOrderByPairAndIfParams(CurrencyPair currencyPair, String orderId) {
		this.currencyPair = currencyPair;
		this.orderId = orderId;
	}

	public void setCurrencyPair(CurrencyPair pair) {
		this.currencyPair = pair;
	}

	public void setOrderId(String orderId) {
		this.orderId = orderId;
	}

	@Override
	public CurrencyPair getCurrencyPair() {
		return currencyPair;
	}

	@Override
	public String getOrderId() {
		return orderId;
	}
}

Add DefaultCancelOrder with pair and id params


// Copyright 2010 The Apache Software Foundation
//
// 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.apache.tapestry5.internal.services.assets;

import java.io.IOException;

import org.apache.tapestry5.ioc.test.TestBase;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;

public class ContextAssetRequestHandlerTest extends TestBase
{
    @DataProvider
    public Object[][] invalid_paths()
    {
        return new Object[][]
        {
        { "web-Inf/classes/hibernate.cfg.xml" },
        { "Meta-Inf/MANIFEST.mf" },
        { "Index.tml" },
        { "folder/FolderIndex.TML" } };
    }

    @Test(dataProvider = "invalid_paths")
    public void ensure_assets_are_rejected(String path) throws IOException
    {
        ContextAssetRequestHandler handler = new ContextAssetRequestHandler(null, null);

        assertFalse(handler.handleAssetRequest(null, null, path), "Handler should return false for invalid path.");
    }
}

Add tests to validate that ContextAssetRequestHandler screens out access to WEB-INF, META-INF and .tml files.


/*
 * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
 * or more contributor license agreements. Licensed under the Elastic License;
 * you may not use this file except in compliance with the Elastic License.
 */

package org.elasticsearch.xpack.security.cli;

import org.elasticsearch.test.ESTestCase;

public class TestSuiteCannotBeEmptyTests extends ESTestCase {

    public void testIsHereSoThisSuiteIsNonEmpty() {
        // This is needed on a FIPS JVM as the rest of the suite is skipped
    }
}

Add empty test case for FIPS