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

package imagej.ext.plugin;

import imagej.ext.Priority;
import imagej.ext.module.Module;
import imagej.ext.module.ModuleInfo;
import imagej.ext.plugin.process.PreprocessorPlugin;

/**
 * A preprocessor plugin that verifies module validity. If the module is not
 * valid, the module execution is canceled.
 *
 * @author Curtis Rueden
 */
@Plugin(type = PreprocessorPlugin.class,
	priority = Priority.VERY_HIGH_PRIORITY + 1)
public class ValidityPreprocessor implements PreprocessorPlugin {

	// -- Fields --

	private boolean canceled;
	private String message;

	// -- ModulePreprocessor methods --

	@Override
	public boolean canceled() {
		return canceled;
	}

	@Override
	public String getMessage() {
		return message;
	}

	// -- ModuleProcessor methods --

	@Override
	public void process(final Module module) {
		final ModuleInfo info = module.getInfo();

		canceled = !info.isValid();
		if (!canceled) return;

		final StringBuilder sb =
			new StringBuilder("The module \"" + info.getDelegateClassName() +
				"\" is invalid:\n");
		for (final String problem : info.getProblems()) {
			sb.append("- " + problem);
			sb.append("\n");
		}
		message = sb.toString();
	}

}

Add preprocessor that verifies module validity


package au.gov.ga.geodesy.test.integration.standalone;

import static com.jayway.restassured.RestAssured.given;

import java.io.File;

import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.testng.annotations.Test;

import au.gov.ga.geodesy.support.TestResources;

/**
 * Upload all SOPAC site logs.
 */
public class UploadSopacSiteLogs extends StandaloneIntegrationTest {

    private static final Logger log = LoggerFactory.getLogger(UploadSopacSiteLogs.class);

    private void uploadSopacSiteLog(File siteLog) throws Exception {
        log.info("Uploading " + siteLog.getName() + " to " + getConfig().getWebServicesUrl());
        given()
            .contentType("text/xml; charset=ISO-8859-1")
            .body(FileUtils.readFileToString(siteLog, "ISO-8859-1"))
        .when()
            .post(getConfig().getWebServicesUrl() + "/siteLog/sopac/upload")
        .then()
            .statusCode(201);
    }

    @Test
    public void upload() throws Exception {
        for (File siteLog : TestResources.sopacSiteLogs()) {
            uploadSopacSiteLog(siteLog);
        }
    }
}

Add standalone test to upload SOPAC site logs


package com.vladmihalcea.hibernate.masterclass.laboratory.idgenerator;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

import org.junit.Test;

import com.vladmihalcea.hibernate.masterclass.laboratory.util.AbstractMySQLIntegrationTest;

public class AutoIdentifierMySQLTest extends AbstractMySQLIntegrationTest {

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

    @Override
    protected boolean nativeHibernateSessionFactoryBootstrap() {
        return false;
    }

    @Test
    public void test() {
        doInJPA(entityManager -> {
            for ( int i = 1; i <= 3; i++ ) {
                entityManager.persist(
                    new Post(
                        String.format(
                            "High-Performance Java Persistence, Part %d", i
                        )
                    )
                );
            }
        });
    }

    @Entity(name = "Post")
    @Table(name = "post")
    public static class Post {

        @Id
        @GeneratedValue(strategy = GenerationType.AUTO)
        private Long id;

        private String title;

        public Post() {}

        public Post(String title) {
            this.title = title;
        }
    }
}

Add test for MySQL AUTO identifier


/*******************************************************************************
 * Copyright (c) 2009 David A Carlson.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *     David A Carlson (XMLmodeling.com) - initial API and implementation
 *
 * $Id$
 *******************************************************************************/
package org.openhealthtools.mdht.uml.common.util;

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

import org.eclipse.uml2.uml.Class;
import org.eclipse.uml2.uml.Classifier;
import org.eclipse.uml2.uml.Property;

public class AttributeList {

	private Class clazz;
	private List<Property> attributes;

	private boolean isOmitAssociations = true;
	private boolean isAllSuperclasses = true;
	private boolean isSorted = true;

	public AttributeList(Class clazz) {
		this.clazz = clazz;
	}

	public List<Property> getAttributes() {
		if (attributes == null) {
			fillAttributeList();
		}

		if (isSorted) {
			Collections.sort(attributes, new NamedElementComparator());
		}

		return attributes;
	}

	public Property getForName(String name) {
		if (name != null) {
			for (Property property : getAttributes()) {
				if (name.equals(property.getName())) {
					return property;
				}
			}
		}

		return null;
	}

	private void fillAttributeList() {
		attributes = new ArrayList<Property>();
		addAttributes(clazz);
	}

	private void addAttributes(Class aClass) {
		for (Property property : aClass.getOwnedAttributes()) {
			if (isOmitAssociations && property.getAssociation() != null) {
				continue;
			}
			// skip implicit redefinitions
			if (getForName(property.getName()) == null) {
				attributes.add(property);
			}

			//TODO skip explicit redefinitions

		}

		if (isAllSuperclasses) {
			for (Classifier general : aClass.getGenerals()) {
				if (general instanceof Class)
					addAttributes((Class)general);
			}
		}
	}

}

Add SubclassEditorDialog, generalized from RIM clone editor.


package be.kuleuven.cs.distrinet.jnome.core.type;

import java.util.List;

import org.aikodi.chameleon.oo.member.Member;
import org.aikodi.chameleon.oo.method.SimpleNameMethodHeader;
import org.aikodi.chameleon.oo.plugin.ObjectOrientedFactory;
import org.aikodi.chameleon.oo.type.ClassImpl;
import org.aikodi.chameleon.oo.type.RegularType;
import org.aikodi.chameleon.oo.type.generics.TypeArgument;
import org.aikodi.chameleon.support.member.simplename.method.NormalMethod;
import org.aikodi.chameleon.support.modifier.Native;
import org.aikodi.chameleon.support.modifier.Public;

import be.kuleuven.cs.distrinet.jnome.core.language.Java7;
import be.kuleuven.cs.distrinet.jnome.workspace.JavaView;

public abstract class AbstractJavaType extends RegularType implements JavaType {

	protected List<Member> _implicitMemberCache;

	/**
	 * A Java reference type has a default constructor when no other constructor
	 * is present.
	 */
	@Override
	public List<Member> implicitMembers() {
		if (_implicitMemberCache == null) {
			_implicitMemberCache = buildImplicitMembersCache();
		}
		return _implicitMemberCache;
	}

	public AbstractJavaType(String name) {
		super(name);
	}

	protected abstract List<Member> buildImplicitMembersCache();

	/**
	 * This is actually cheating because the getClass method in Java is a member
	 * of Object. Maybe we should set the parent to Object instead of the current
	 * class.
	 *
	 * @return
	 */
	protected static NormalMethod getClassMethod(ClassImpl type) {
		NormalMethod result = null;
		if (type.view(JavaView.class).topLevelType() != type) {
			Java7 language = type.language(Java7.class);
			BasicJavaTypeReference returnType = language.createTypeReference("java.lang.Class");
			JavaTypeReference erasedThisType = language.createTypeReference(type.name());
			TypeArgument arg = language.createExtendsWildcard(erasedThisType);
			returnType.addArgument(arg);
			result = language.plugin(ObjectOrientedFactory.class).createNormalMethod(new SimpleNameMethodHeader("getClass", returnType));
//			result = new NormalMethod(new SimpleNameMethodHeader("getClass", returnType));
			result.addModifier(new Public());
			result.addModifier(new Native());
			result.setUniParent(type);
		}
		return result;
	}

}

Use the factory to create the method. Otherwise, the getClass() method is not a JavaMethod, and does not erase its return type.


package com.orientechnologies.orient.distributed.impl.coordinator.network;

import com.orientechnologies.orient.distributed.impl.coordinator.ONodeResponse;
import com.orientechnologies.orient.distributed.impl.coordinator.OSubmitResponse;
import com.orientechnologies.orient.distributed.impl.coordinator.ddl.ODDLQueryOperationRequest;
import com.orientechnologies.orient.distributed.impl.coordinator.ddl.ODDLQueryOperationResponse;
import com.orientechnologies.orient.distributed.impl.coordinator.ddl.ODDLQuerySubmitResponse;
import com.orientechnologies.orient.distributed.impl.coordinator.transaction.OSessionOperationId;
import com.orientechnologies.orient.distributed.impl.log.OLogId;
import org.junit.Assert;
import org.junit.Test;

import java.io.*;

public class OOperationResponseTest {

  @Test
  public void testSerialize() throws IOException {

    String db = "testDb";
    OLogId oplogId = new OLogId(10, 20, 19);
    ODDLQueryOperationResponse res = new ODDLQueryOperationResponse();
    OOperationResponse response = new OOperationResponse(db, oplogId, res);

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    DataOutputStream out = new DataOutputStream(baos);
    response.write(out);
    byte[] serialized = baos.toByteArray();
    out.close();
    baos.close();
    ByteArrayInputStream bais = new ByteArrayInputStream(serialized);
    DataInputStream in = new DataInputStream(bais);

    OOperationResponse response2 = new OOperationResponse();
    response2.read(in);
    in.close();
    bais.close();

    Assert.assertEquals(response.getCommand(), response2.getCommand());
    Assert.assertEquals(response.getDatabase(), response2.getDatabase());
    Assert.assertEquals(response.getId(), response2.getId());
    ONodeResponse res2 = response2.getResponse();
    Assert.assertEquals(res.getResponseType(), res2.getResponseType());
    Assert.assertEquals(res.getClass(), res2.getClass());

  }
}

Add serialization tests for OOperationResponse


package eu.xenit.de.testing.actions;

import com.github.dynamicextensionsalfresco.actions.annotations.ActionMethod;
import com.github.dynamicextensionsalfresco.actions.annotations.ActionParam;
import org.alfresco.service.cmr.repository.NodeRef;
import org.springframework.stereotype.Component;

@Component
public class TestAction {

    @ActionMethod(value = "testAction")
    public void testAction(final NodeRef nodeRef, @ActionParam("name") final String name) {
        throw new UnsupportedOperationException();
    }

}

Add action to test bundle


package de.retest.recheck.review.ignore;

import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;

import org.junit.jupiter.api.Test;

import de.retest.recheck.ui.descriptors.Element;
import de.retest.recheck.ui.diff.AttributeDifference;

class ExcludeFilterIT {

	@Test
	void load_should_handle_multiple_entries() {
		final Element element = mock( Element.class );

		final AttributeFilter.AttributeFilterLoader delegate = new AttributeFilter.AttributeFilterLoader();
		final ExcludeFilter.FilterLoader cut = new ExcludeFilter.FilterLoader( delegate );

		assertThat( cut.load( "exclude(attribute=text), exclude(attribute=font)" ) ).hasValueSatisfying( filter -> {
			assertThat( filter.matches( element, "class" ) ).isTrue();
			assertThat( filter.matches( element, difference( "class" ) ) ).isTrue();

			assertThat( filter.matches( element, "font" ) ).isFalse();
			assertThat( filter.matches( element, difference( "font" ) ) ).isFalse();

			assertThat( filter.matches( element, "text" ) ).isFalse();
			assertThat( filter.matches( element, difference( "text" ) ) ).isFalse();
		} );
	}

	private AttributeDifference difference( final String key ) {
		return new AttributeDifference( key, "expected", "actual" );
	}
}

Add integration test to handle multiple excludes


package org.springframework.site.test;

import org.springframework.context.annotation.Primary;
import org.springframework.site.services.GitHubService;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestClientException;

@Service
@Primary
@SuppressWarnings("unused")
public class FakeGithubService extends GitHubService {

	public FakeGithubService() {
		super(null);
	}

	@Override
	public String renderToHtml(String markdownSource) {
		return markdownSource;
	}

	@Override
	public <T> T postForObject(String path, Object request, Class<T> responseType, Object... uriVariables) {
		try {
			return responseType.newInstance();
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	@Override
	public <T> T getForObject(String path, Class<T> responseType, Object... uriVariables) throws RestClientException {
		try {
			return responseType.newInstance();
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	@Override
	public String getRawFileAsHtml(String path) {
		return "HTML";
	}
}

Add a fake github service to avoid network calls in our integration tests


package com.salsaw.msalsa;

import com.salsaw.msalsa.algorithm.TerminalGAPsStrategy;
import com.salsaw.msalsa.cli.SalsaParameters;
import com.salsaw.msalsa.cli.ScoringMatrix;
import com.vaadin.annotations.AutoGenerated;
import com.vaadin.data.fieldgroup.FieldGroup;
import com.vaadin.data.fieldgroup.PropertyId;
import com.vaadin.data.util.BeanItem;
import com.vaadin.ui.AbsoluteLayout;
import com.vaadin.ui.ComboBox;
import com.vaadin.ui.CustomComponent;
import com.vaadin.ui.FormLayout;
import com.vaadin.ui.TextField;

public class SalsaParametersForm extends CustomComponent {
    /**
	 *
	 */
	private static final long serialVersionUID = 1L;

	@PropertyId("GOP")
    TextField GOPField = new TextField("GOP");

    @PropertyId("GEP")
    TextField GEPField = new TextField("GEP");

    @PropertyId("gamma")
    TextField gammaField = new TextField("Gamma");

    @PropertyId("scoringMatrix")
    ComboBox scoringMatrixField = new ComboBox("Scoring Matrix");

    @PropertyId("minIterations")
    TextField minIterationsField = new TextField("Min Matrix");

    @PropertyId("probabilityOfSplit")
    TextField probabilityOfSplitField = new TextField("Probability Of Split");

    @PropertyId("terminalGAPsStrategy")
    ComboBox terminalGAPsStrategyField = new ComboBox("Terminal GAPs Strategy");

	public SalsaParametersForm(SalsaParameters salsaParameters) {
        FormLayout formLayout = new FormLayout();
        scoringMatrixField.setNullSelectionAllowed(false);
        for(ScoringMatrix scoringMatrix : ScoringMatrix.values()) {
        	scoringMatrixField.addItem(scoringMatrix);
        }
        scoringMatrixField.setImmediate(true);
        formLayout.addComponent(scoringMatrixField);
        minIterationsField.setImmediate(true);
        formLayout.addComponent(minIterationsField);
        formLayout.addComponent(GOPField);
        formLayout.addComponent(GEPField);
        formLayout.addComponent(probabilityOfSplitField);
        formLayout.addComponent(gammaField);
        formLayout.addComponent(terminalGAPsStrategyField);
        terminalGAPsStrategyField.setNullSelectionAllowed(false);
        for(TerminalGAPsStrategy terminalGAPsStrategy : TerminalGAPsStrategy.values()) {
        	terminalGAPsStrategyField.addItem(terminalGAPsStrategy);
        }

        BeanItem<SalsaParameters> item = new BeanItem<SalsaParameters> (salsaParameters);
        FieldGroup binder = new FieldGroup(item);
        binder.bindMemberFields(this);

        formLayout.setSizeUndefined();

		setCompositionRoot(formLayout);
	}

}

Add class to create UI of Salsa Parameters


package org.jsmpp.util;
import static org.testng.Assert.assertEquals;

import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
/**
 * @author uudashr
 *
 */
public class PDUByteBufferTest {
    private static final int BYTE_LENGTH = 1;
    private static final int INTEGER_LENGTH = 4;
    private static final int INITIAL_LENGTH = INTEGER_LENGTH;

    private PDUByteBuffer byteBuffer;

    @BeforeMethod
    public void setUp() {
        byteBuffer = new PDUByteBuffer(new DumbCapacityPolicy());
    }

    @Test(groups="checkintest")
    public void initialLengthValidity() {
        assertEquals(byteBuffer.toBytes().length, INITIAL_LENGTH);
    }

    @Test(groups="checkintest", dependsOnMethods="initialLengthValidity")
    public void testLengthValidityForIntAppends() {
        for (int i = 0; i < 5; i++) {
            byteBuffer.append(10);
            assertEquals(byteBuffer.toBytes().length, INITIAL_LENGTH + (INTEGER_LENGTH * (i + 1)), "Failed on iteration " + i);
        }
    }

    @Test(groups="checkintest", dependsOnMethods="initialLengthValidity")
    public void testLengthValidityForByteAppends() {
        for (int i = 0; i < 5; i++) {
            byteBuffer.append((byte)10);
            assertEquals(byteBuffer.toBytes().length, INITIAL_LENGTH + (BYTE_LENGTH * (i + 1)), "Failed on iteration " + i);
        }
    }

    @Test(groups="checkintest", dependsOnMethods="initialLengthValidity")
    public void testLengthValidityForCString() {
        String hello = "PDUByteBuffer integration test for JSMPP API";
        for (int i = 0; i < 5; i++) {
            byteBuffer.append(hello);
            assertEquals(byteBuffer.toBytes().length, INITIAL_LENGTH + (hello.length() * (i + 1)) + (i + 1), "Failed on iteration " + i);
        }
    }

    @Test(groups="checkintest", dependsOnMethods="initialLengthValidity")
    public void testLengthValidityForString() {
        String hello = "PDUByteBuffer integration test for JSMPP API";
        for (int i = 0; i < 5; i++) {
            byteBuffer.append(hello, false);
            assertEquals(byteBuffer.toBytes().length, INITIAL_LENGTH + (hello.length() * (i + 1)), "Failed on iteration " + i);
        }
    }
}

Add unit test for PDUByteBuffer


package reactfx;

import static org.junit.Assert.*;

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

import org.junit.Test;

public class InterceptableEventStreamTest {

    @Test
    public void testInterceptionStacking() {
        EventSource<Integer> src = new EventSource<>();
        InterceptableEventStream<Integer> stream = src.interceptable();
        List<Integer> accum = new ArrayList<>();
        stream.subscribe(i -> accum.add(i));

        src.push(1);
        src.push(2);
        assertEquals(Arrays.asList(1, 2), accum);
        stream.pauseWhile(() -> {
            src.push(3);
            src.push(4);
            stream.fuseWhile((Integer a, Integer b) -> {
                if(a + b == 0) {
                    return FusionResult.annihilated();
                } else if(a + b <= 20) {
                    return FusionResult.fused(a + b);
                } else {
                    return FusionResult.failed();
                }
            }, () -> {
                src.push(5);
                src.push(6);
                src.push(7);
                src.push(8);
                src.push(9);
                src.push(-7);
                stream.retainLatestWhile(() -> {
                    src.push(100);
                    src.push(200);
                    src.push(-10);
                });
                src.push(4);
                stream.fuseWhile((Integer a, Integer b) -> a + b, () -> {
                    src.push(1);
                    src.push(2);
                    src.push(3);
                    stream.muteWhile(() -> {
                        src.push(4);
                        src.push(5);
                        src.push(6);
                    });
                });
                src.push(5);
                src.push(10);
                src.push(10);
            });
            src.push(5);
        });
        assertEquals(Arrays.asList(1, 2, 3, 4, 18, 15, 20, 5), accum);
        src.push(4);
        assertEquals(Arrays.asList(1, 2, 3, 4, 18, 15, 20, 5, 4), accum);
    }

    @Test(expected = IllegalStateException.class)
    public void testInteceptionReleaseOrder() {
        EventSource<Integer> src = new EventSource<>();
        InterceptableEventStream<Integer> stream = src.interceptable();
        Hold h1 = stream.pause();
        Hold h2 = stream.retainLatest();
        h1.close();
        h2.close();
    }
}

Add tests for interceptable streams.


import org.junit.*;

public class QueueTest {

  Queue q;

  @Before
  public void setUp() {
    q = new Queue(5);
  }

  @After
  public void tearDown() {
    q = null;
  }

  @Test
  public void testIsEmptyOnEmpty() {

  }

  @Test
  public void testIsEmpty() {

  }

  @Test
  public void testHasCapacityOnEmpty() {

  }

  @Test
  public void testHasCapacityOnFull() {

  }

  @Test
  public void testEnqueueOnEmpty() {

  }

  @Test
  public void testEnqueueOnFull() {

  }

  @Test
  public void testDequeueOnEmpty() {

  }

  @Test
  public void testDequeueOnFull() {

  }
}

Add Queue skeleton test cases.


package MWC.GUI;

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

/** declare an annotation as a marker, used for methods that have changed the fundamental
 *  data in debrief, and need a 'fireExtended' event versus a 'fireModified' event.
 */
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface FireExtended{

}

Introduce marker annotation for methods that have changed the data structure


package com.github.booknara.cryptographic;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Formatter;

public class CryptographicHashFunction {

    public static void main(String[] args) {
        String input = new String("input_string");

        MessageDigest digest;
        try {
            // MD5
            digest = MessageDigest.getInstance("MD5");
            System.out.printf(digest.getAlgorithm() + " (%s) = %s \n", input, bytesTooHex(getHashValue(digest, input.getBytes())));
            System.out.printf(digest.getAlgorithm() + " (%s) = %s \n", input, bytesTooHex(getHashValue(digest, input.getBytes())));
            // SHA-1
            digest = MessageDigest.getInstance("SHA-1");
            System.out.printf(digest.getAlgorithm() + " (%s) = %s \n", input, bytesTooHex(getHashValue(digest, input.getBytes())));
            System.out.printf(digest.getAlgorithm() + " (%s) = %s \n", input, bytesTooHex(getHashValue(digest, input.getBytes())));
            // SHA-256
            digest = MessageDigest.getInstance("SHA-256");
            System.out.printf(digest.getAlgorithm() + " (%s) = %s \n", input, bytesTooHex(getHashValue(digest, input.getBytes())));
            System.out.printf(digest.getAlgorithm() + " (%s) = %s \n", input, bytesTooHex(getHashValue(digest, input.getBytes())));
            // SHA-384
            digest = MessageDigest.getInstance("SHA-384");
            System.out.printf(digest.getAlgorithm() + " (%s) = %s \n", input, bytesTooHex(getHashValue(digest, input.getBytes())));
            System.out.printf(digest.getAlgorithm() + " (%s) = %s \n", input, bytesTooHex(getHashValue(digest, input.getBytes())));
            // SHA-512
            digest = MessageDigest.getInstance("SHA-512");
            System.out.printf(digest.getAlgorithm() + " (%s) = %s \n", input, bytesTooHex(getHashValue(digest, input.getBytes())));
            System.out.printf(digest.getAlgorithm() + " (%s) = %s \n", input, bytesTooHex(getHashValue(digest, input.getBytes())));

        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }

    }

    public static byte[] getHashValue(MessageDigest digest, byte[] bytes) {
        digest.update(bytes, 0, bytes.length);
        return digest.digest();
    }

    public static String bytesTooHex(byte[] hashValue) {
        System.out.println("Length of byte : " +hashValue.length);
        Formatter formatter = new Formatter();
        for (int i = 0; i < hashValue.length; i++) {
            formatter.format("%02x", hashValue[i]);
        }

        return formatter.toString();
    }
}

Add a cryptographic hash function main file


/*******************************************************************************
 * Mission Control Technologies, Copyright (c) 2009-2012, United States Government
 * as represented by the Administrator of the National Aeronautics and Space
 * Administration. All rights reserved.
 *
 * The MCT platform is 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.
 *
 * MCT includes source code licensed under additional open source licenses. See
 * the MCT Open Source Licenses file included with this distribution or the About
 * MCT Licenses dialog available at runtime from the MCT Help menu for additional
 * information.
 *******************************************************************************/
package gov.nasa.arc.mct.scenario.component;

import gov.nasa.arc.mct.components.AbstractComponent;
import gov.nasa.arc.mct.platform.spi.PersistenceProvider;
import gov.nasa.arc.mct.platform.spi.PlatformAccess;
import gov.nasa.arc.mct.services.component.ComponentRegistry;
import gov.nasa.arc.mct.services.component.CreateWizardUI;

import java.util.Collections;

import javax.swing.JButton;
import javax.swing.JComponent;

public class RepositoryWizardDecorator extends CreateWizardUI {
	private CreateWizardUI wizard;
	private String repositoryID;

	public AbstractComponent createComp(ComponentRegistry comp,
			AbstractComponent parentComp) {
		AbstractComponent created = wizard.createComp(comp, parentComp);

		// Also persist the created component to the designated repository
		PersistenceProvider persistence = PlatformAccess.getPlatform().getPersistenceProvider();
		AbstractComponent repository = persistence.getComponent(repositoryID);
		repository.addDelegateComponent(created);
		repository.save();
		persistence.persist(Collections.singleton(repository));

		return created;
	}

	public JComponent getUI(JButton create) {
		return wizard.getUI(create);
	}

	public String toString() {
		return wizard.toString();
	}
}

Add decorator for repository save


package com.thegongoliers.output;

import com.kylecorry.geometry.Path;
import com.thegongoliers.output.interfaces.DriveTrainInterface;
import edu.wpi.first.wpilibj.RobotDrive;

/**
 * Created by Kylec on 3/27/2017.
 */
public class DriveUtil {

    /**
     * Return the time to drive a given distance.
     *
     * @param distance      The distance to drive.
     * @param robotMaxSpeed The max speed of the robot.
     * @param targetSpeed   The max speed to drive this distance from 0 to 1 inclusive.
     * @return The time to drive a given distance.
     */
    public double timeToDriveDistanceDeadReckoning(double distance, double robotMaxSpeed, double targetSpeed) {
        double distancePerSecond = robotMaxSpeed * targetSpeed;
        return distance / distancePerSecond;
    }

    /**
     * Drive to a given distance using bang-bang control.
     *
     * @param distance        The distance to drive to.
     * @param currentDistance The current distance travelled (by encoders)
     * @param threshold       The threshold in which to stop driving.
     * @param maxSpeed        The max speed of the robot from 0 to 1 inclusive.
     * @param driveTrain      The drive train of the robot.
     * @return True if the robot is at the target distance within the threshold.
     */
    public boolean bangBangDriveDistance(double distance, double currentDistance, double threshold, double maxSpeed, DriveTrainInterface driveTrain) {
        double error = distance - currentDistance;
        if (error > threshold) {
            driveTrain.forward(maxSpeed);
        } else if (error < -threshold) {
            driveTrain.backward(maxSpeed);
        } else {
            driveTrain.stop();
            return true;
        }
        return false;
    }

    /**
     * Drive along a precomputed trajectory with the given velocity and acceleration using feed forward control.
     *
     * @param velocity     The desired velocity.
     * @param acceleration The desired acceleration.
     * @param kv           The velocity constant (normally 1 / maxVelocity).
     * @param ka           The acceleration constant.
     * @param driveTrain   The drive train of the robot.
     */
    public void feedForwardControl(double velocity, double acceleration, double kv, double ka, DriveTrainInterface driveTrain) {
        driveTrain.forward(kv * velocity + ka * acceleration);
    }

}

Add several driving control functions


public class Solution {

    public int hammingDistance(int x, int y) {

        int xor = x ^ y;
        int distance = 0;

        while (xor != 0) {

            xor &= xor - 1;
            distance++;

        }

        return distance;

    }

}

Create : 461 Hamming Distance


package org.graphwalker.core.model;

import com.google.gson.Gson;
import org.junit.Assert;
import org.junit.Test;

/**
 * @author Nils Olsson
 */
public class JsonTest {

    @Test
    public void convertModelTest() {
        Model model1 = new Model()
            .setName("MyModel")
            .setId("MyModelId")
            .addAction(new Action("MyActionScript"))
            .addRequirement(new Requirement("REQ123"))
            .setProperty("MyProperty", "valueA")
            .addEdge(new Edge()
                .setName("MyEdgeName")
                .setId("MyEdgeId")
                .setProperty("MyEdgeProperty", "valueX")
                .setSourceVertex(new Vertex()
                    .setName("MySourceVertex")
                    .setId("MySourceVertexId")
                    .setProperty("MySourceProperty", "valueY")
                )
                .setTargetVertex(new Vertex()
                    .setName("MyTargetVertex")
                    .setId("MyTargetVertexId")
                    .setProperty("MyTargetProperty", "valueZ")
                )
            );
        Gson gson = new Gson();
        String json1 = gson.toJson(model1);
        Model model2 = gson.fromJson(json1, Model.class);
        String json2 = gson.toJson(model2);
        Assert.assertEquals(json1, json2);
    }
}

Add a test that transform a model to json format and back


package ieg.util.xml;

import java.util.Date;
import java.util.GregorianCalendar;

import javax.xml.datatype.DatatypeConfigurationException;
import javax.xml.datatype.DatatypeFactory;

/**
 * Convert date time object to and from a XML compliant string.
 *
 *

 * The date format is closely related to the dates and times described in ISO
 * 8601 (see XML Schema 1.0
 * Part 2, Section 3.2.7). Internally, {@link DatatypeFactory} is used,
 * because this format is not supported by {@link java.text.SimpleDateFormat}.
 * Further alternatives would be JodaTime or
 * {@link javax.xml.bind.DatatypeConverter}.
 *
 *

 * Instances of this class are not safe for use by multiple threads.
 *
 * @author Rind
 *
 */
public class XmlCalendarConverter {

    private GregorianCalendar cal;
    private DatatypeFactory factory;

    public XmlCalendarConverter() throws DatatypeConfigurationException {
        factory = DatatypeFactory.newInstance();
        cal = new GregorianCalendar();
    }

    public String toXML(long millis) {
        cal.setTimeInMillis(millis);
        return toXML(cal);
    }

    public String toXML(Date date) {
        cal.setTime(date);
        return toXML(cal);
    }

    public String toXML(GregorianCalendar cal) {
        return factory.newXMLGregorianCalendar(cal).toXMLFormat();
    }

    public GregorianCalendar toCalendar(String xml)
            throws IllegalArgumentException {
        return factory.newXMLGregorianCalendar(xml).toGregorianCalendar();
    }

    public Date toDate(String xml) {
        cal = toCalendar(xml);
        return cal.getTime();
    }

    public long toTimeInMillis(String xml) {
        cal = toCalendar(xml);
        return cal.getTimeInMillis();
    }
}

Convert date time object to and from a XML compliant string using DatatypeFactory


package com.google.sps.servlets;

import com.google.api.gax.longrunning.OperationFuture;
import com.google.cloud.vision.v1.*;

import java.io.IOException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;
import com.google.sps.data.ServletLibrary;

@WebServlet("/create-product")
public class CreateProductServlet extends HttpServlet {

  public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
    String projectId = "cloudberry-step-2";
    String computeRegion = "us-east1";
    String productId = request.getParameter("product-id");
    String productDisplayName = request.getParameter("product-display");
    String productCategory = "toys-v2";
    String setId;

    ServletsLibrary.createProduct(projectId, computeRegion, productId, productDisplayName, productCategory);

    ServletsLibrary.addProductToProductSet(projectId, computeRegion, productId, setId);

    response.sendRedirect("create-product.html");

  }
}

Add a servlet that creates a product and add a product to a product set


package beaform.search;

import java.util.concurrent.Callable;

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

import beaform.dao.GraphDbHandlerForJTA;
import beaform.debug.DebugUtils;
import beaform.entities.Formula;
import junit.framework.TestCase;

/**
 * Tests for searching formulas by tag.
 *
 * @author Steven Post
 *
 */
public class SearchFormulasTaskTest extends TestCase {

	/**
	 * {@inheritDoc}
	 */
	@Override
	@Before
	public void setUp() {
		GraphDbHandlerForJTA.initInstance("test");
		DebugUtils.clearDb();
		DebugUtils.fillDb();
	}

	/**
	 * Test the search method.
	 * @throws Exception
	 */
	@Test
	public void testSearch() throws Exception {
		final Callable<Formula> task = new SearchFormulaTask("Form1");
		final Formula result = task.call();
		assertEquals("This isn't the tag we searched for", "Form1", result.getName());
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	@After
	public void tearDown() {
		DebugUtils.clearDb();
	}

}

Add test for searching a formula by name


package me.prettyprint.cassandra.service;

import static org.junit.Assert.*;

import org.junit.Test;

public class CassandraClientTest {

  @Test
  public void testGetKeySpaceString() {
    fail("Not yet implemented");
  }

  @Test
  public void testGetKeySpaceStringConsistencyLevel() {
    fail("Not yet implemented");
  }

  @Test
  public void testGetStringProperty() {
    fail("Not yet implemented");
  }

  @Test
  public void testGetKeyspaces() {
    fail("Not yet implemented");
  }

  @Test
  public void testGetClusterName() {
    fail("Not yet implemented");
  }

  @Test
  public void testGetTokenMap() {
    fail("Not yet implemented");
  }

  @Test
  public void testGetConfigFile() {
    fail("Not yet implemented");
  }

}

Add a basic test case, that just fails


public class Solution {

    public int singleNumber(int[] nums) {

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

		        singleNum ^= nums[i];

        }

	      return singleNum;

    }

}

Create : 136 Single Number


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

import static org.wildfly.common.Assert.checkNotNullParam;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.util.Map;

import javax.security.auth.callback.Callback;
import javax.security.auth.callback.CallbackHandler;
import javax.security.auth.callback.UnsupportedCallbackException;

import org.wildfly.security.auth.callback.SocketAddressCallback;
import org.wildfly.security.http.HttpAuthenticationException;
import org.wildfly.security.http.HttpServerAuthenticationMechanism;
import org.wildfly.security.http.HttpServerAuthenticationMechanismFactory;
import org.wildfly.security.http.HttpServerRequest;

/**
 * A wrapper {@link HttpServerAuthenticationMechanismFactory} that sets the peer address using the current
 * authentication request.
 *
 * @author Farah Juma
 */
public final class SocketAddressCallbackServerMechanismFactory implements HttpServerAuthenticationMechanismFactory {

    private final HttpServerAuthenticationMechanismFactory delegate;

    /**
     * Construct a wrapping mechanism factory instance.
     *
     * @param delegate the wrapped mechanism factory
     */
    public SocketAddressCallbackServerMechanismFactory(final HttpServerAuthenticationMechanismFactory delegate) {
        this.delegate = checkNotNullParam("delegate", delegate);
    }

    @Override
    public String[] getMechanismNames(Map<String, ?> properties) {
        return delegate.getMechanismNames(properties);
    }

    @Override
    public HttpServerAuthenticationMechanism createAuthenticationMechanism(String mechanismName, Map<String, ?> properties, CallbackHandler callbackHandler) throws HttpAuthenticationException {
        final HttpServerAuthenticationMechanism mechanism = delegate.createAuthenticationMechanism(mechanismName, properties, callbackHandler);
        return mechanism != null ? new HttpServerAuthenticationMechanism() {

            @Override
            public String getMechanismName() {
                return mechanism.getMechanismName();
            }

            @Override
            public void evaluateRequest(HttpServerRequest request) throws HttpAuthenticationException {
                final InetSocketAddress peerAddress = request.getSourceAddress();
                if (peerAddress != null) {
                    final SocketAddressCallback peerCallback = new SocketAddressCallback(peerAddress, SocketAddressCallback.Kind.PEER);
                    try {
                        callbackHandler.handle(new Callback[] { peerCallback });
                    } catch (IOException | UnsupportedCallbackException e) {
                        throw new HttpAuthenticationException(e);
                    }
                }

                mechanism.evaluateRequest(request);
            }
        } : null;
    }
}

Add a wrapper HttpServerAuthenticationMechanismFactory that sets the peer address using the current authentication request


package org.mutabilitydetector;

import org.hamcrest.Description;
import org.hamcrest.Matcher;
import org.hamcrest.TypeSafeDiagnosingMatcher;
import org.mutabilitydetector.checkers.IMutabilityChecker;

/*
 * Mutability Detector
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 *
 * Further licensing information for this project can be found in
 * 		license/LICENSE.txt
 */

public class TestMatchers {

	public static Matcher<? super IMutabilityChecker> hasReasons() {
		return new TypeSafeDiagnosingMatcher<IMutabilityChecker>() {

			@Override protected boolean matchesSafely(IMutabilityChecker item, Description mismatchDescription) {

				mismatchDescription.appendText(" got a checker (" + item.toString() + ") containing zero reasons ");
				return !(item.reasons().isEmpty());
			}

			@Override public void describeTo(Description description) {
				description.appendText(" got a checker reporting at least one reason ");
			}

		};
	}

}

Add a matcher for testing that a checker reports reasons - currently the AnalysisResult will prevent this in practice, with an IllegalArgumentException, but that may not always be the case, so keep the check.


/*
 * Copyright 2019 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.gradle.integtests.fixtures;

import com.google.common.collect.ImmutableMap;
import org.gradle.instantexecution.SystemProperties;

/**
 * Intended to be a temporary runner until there is full cross-cutting coverage for all int tests with instant execution enabled.
 */
public class InstantExecutionRunner extends BehindFlagFeatureRunner {
    public InstantExecutionRunner(Class<?> target) {
        super(target, ImmutableMap.of(SystemProperties.isEnabled, booleanFeature("instant execution")));
    }
}

Add a test runner that can run a test with instant execution enabled and disabled.


package it.near.sdk;

import android.content.Context;
import android.content.SharedPreferences;

import com.google.common.collect.Maps;

import org.json.JSONObject;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import it.near.sdk.Recipes.Models.Recipe;
import it.near.sdk.Recipes.RecipeCooler;

import static it.near.sdk.Recipes.RecipeCooler.*;
import static junit.framework.Assert.*;
import static org.mockito.Mockito.*;

/**
 * Created by cattaneostefano on 14/02/2017.
 */

@RunWith(MockitoJUnitRunner.class)
public class RecipeCoolerTest {

    @Mock
    Context mockContext;
    @Mock
    SharedPreferences mockSharedPreferences;
    @Mock
    SharedPreferences.Editor mockEditor;

    Recipe criticalRecipe;

    @Before
    public void init() {

        when(mockContext.getSharedPreferences(anyString(), anyInt())).thenReturn(mockSharedPreferences);
        when(mockSharedPreferences.edit()).thenReturn(mockEditor);
        when(mockEditor.remove(anyString())).thenReturn(mockEditor);
        when(mockEditor.commit()).thenReturn(true);

        criticalRecipe = new Recipe();
        criticalRecipe.setId("recipe_id");
        HashMap<String, Object> cooldown = Maps.newHashMap();
        cooldown.put(GLOBAL_COOLDOWN, 0L);
        cooldown.put(SELF_COOLDOWN, 0L);
        criticalRecipe.setCooldown(cooldown);
    }

    @Before
    public void resetSingleton() throws SecurityException, NoSuchFieldException, IllegalArgumentException, IllegalAccessException {
        Field instance = RecipeCooler.class.getDeclaredField("INSTANCE");
        instance.setAccessible(true);
        instance.set(null, null);
    }

    @Test
    public void whenLogIsEmpty_enableRecipe() {
        when(mockSharedPreferences.getString(eq(LOG_MAP), anyString())).thenReturn("{}");

        List<Recipe> recipeList = new ArrayList(Arrays.asList(criticalRecipe));
        assertEquals(1, recipeList.size());
        RecipeCooler.getInstance(mockContext).filterRecipe(recipeList);
        assertEquals(1, recipeList.size());

    }

    @Test
    public void whenRecipeShown_historyUpdated() {

        RecipeCooler.getInstance(mockContext).markRecipeAsShown("recipe_id");
        Map<String, Long> logMap = Maps.newHashMap();
        logMap.put("recipe_id", System.currentTimeMillis());
        JSONObject jsonObject = new JSONObject(logMap);
        String jsonString = jsonObject.toString();
        verify(mockEditor).putString(eq(LOG_MAP), contains("recipe_id"));

    }

    @Test
    public void whenRecipeWithSelfCooldownShown_cantBeShownAgain() {
        assertTrue(true);
        RecipeCooler.getInstance(mockContext).markRecipeAsShown("recipe_id");
    }

}

Add unit test class for recipe cooler.


package com.verybadalloc.designlib.adapters;

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;

import com.verybadalloc.designlib.views.BooksListFragmentBuilder;

/**
 * Created by aambri on 16-01-28.
 */
public class TabsPagerAdapter extends FragmentPagerAdapter {

    private static final String[] categories = new String[]{"All", "New Arrival", "Novels", "Non-fiction", "Classics", "Science-fiction"};

    public TabsPagerAdapter(FragmentManager fm) {
        super(fm);
    }

    @Override
    public Fragment getItem(int position) {
        return BooksListFragmentBuilder.newBooksListFragment(categories[position]);
    }

    @Override
    public int getCount() {
        return categories.length;
    }

    @Override
    public CharSequence getPageTitle(int position) {
        return categories[position];
    }
}

Add adapter used for tab layout


/*
 * Flow-Design for Java
 *
 * Copyright (c) 2015 Falko Schumann
 * Released under the terms of the MIT License (MIT).
 */

package de.muspellheim.flowdesign;

/**
 * Basisklasse oder Beispielklasse für die Initialisierung eines Flows für eine Applikation. Die
 * {@code protected}-Methoden werden überschrieben, um die entsprechende Phase zu realisiereren.
 *
 *

 *
{@link #build()}

 *
{@link #bind()}

 *
{@link #inject()}

 *
{@link #configure(String[])}

 *
{@link #run(String[])}

 *

 *
 * @author Falko Schumann <falko.schumann@muspellheim.de>
 */
public abstract class Flow {

    /**
     * Schablonenmethode zur Initialisierung und zum Start des Flows.
     *
     * @param args die Kommandozeilenoptionen der Applikation.
     */
    public final void initializeAndStart(String[] args) {
        build();
        bind();
        inject();
        configure(args);
        run(args);
    }

    /**
     * Diese Methode überschreiben, um in ihr die Functional-Units anzulegen.
     */
    protected void build() {
    }

    /**
     * Diese Methode überschreiben, um in ihr die Output-Pins und Input-Pins der Functional-Units miteinander zu
     * verbinden.
     */
    protected void bind() {
    }

    /**
     * Diese Methode überschreiben, um die Abhängigkeiten der Functional-Units in diese zu injizieren. Wenn
     * Abhängigkeiten per Konstruktor injiziert werden, geschieht dies bereits in {@link #build()}.
     */
    protected void inject() {
    }

    /**
     * Diese Methode überschreiben, um die Functional-Units zu konfigurieren. Die Kommandozeilenargumente der
     * Applikation werden an die Functional-Units weitergereicht, die sie benötigen, damit diese ihre Konfiguration
     * davon lesen können.
     *
     * @param args die Kommandozeilenoptionen der Applikation.
     */
    protected void configure(String[] args) {
    }

    /**
     * Diese Methode überschreiben, um die Functional-Units die den Entry-Point des Flows darstellt zu starten.
     * Der Entry-Point bekommt ebenfalls die Kommandozeilenargumente der Applikation übergeben.
     *
     * @param args die Kommandozeilenoptionen der Applikation.
     */
    protected void run(String[] args) {
    }

}

Add template to create flow


package committools.data;

import org.eclipse.jgit.lib.PersonIdent;

import com.google.common.base.Objects;

/**
 * A struct object containing the git commiter identity. Such objects are equal
 * when at least the name or the email are equal, allowing better deduplication.
 *
 * @author Miltos Allamanis <m.allamanis@ed.ac.uk>
 *
 */
public final class GitCommiterIdentity {

	public final String name;

	public final String emailUsername;

	public GitCommiterIdentity(final PersonIdent jgitIdenity) {
		name = jgitIdenity.getName();
		emailUsername = jgitIdenity.getEmailAddress().split("@")[0];
	}

	@Override
	public boolean equals(final Object obj) {
		if (this == obj) {
			return true;
		}
		if (obj == null) {
			return false;
		}
		if (getClass() != obj.getClass()) {
			return false;
		}
		final GitCommiterIdentity other = (GitCommiterIdentity) obj;
		return Objects.equal(name, other.name)
				|| Objects.equal(emailUsername, other.emailUsername);
	}

	@Override
	public int hashCode() {
		return 0;
	}

	@Override
	public String toString() {
		return name + ":" + emailUsername;
	}

}

Use git blame to find faction mememberships


/**
 *
 */
package fish.dreaming.oj.leetcode;

/**
 * @author tao
 *
 */
public class RemoveDuplicatesFromSortedList {
	public ListNode deleteDuplicates(ListNode head) {
		if (head == null) {
			return null;
		}

		int lastVal = head.val;
		ListNode pointer = head;
		while (pointer.next != null) {
			if (pointer.next.val == lastVal) {
				pointer.next = pointer.next.next;
			} else {
				lastVal = pointer.next.val;
				pointer = pointer.next;
			}
		}

		return head;
	}

	public class ListNode {
		int val;
		ListNode next;

		ListNode(int x) {
			val = x;
			next = null;
		}
	}

}

Remove Duplicates From Sorted List


package slicktest;

import org.newdawn.slick.AppGameContainer;
import org.newdawn.slick.BasicGame;
import org.newdawn.slick.GameContainer;
import org.newdawn.slick.Graphics;
import org.newdawn.slick.SlickException;
import org.newdawn.slick.tiled.TiledMap;

public class SlickTest extends BasicGame
{
    private TiledMap testMap;

    public SlickTest()
    {
        super ( "Slick Test" );
    }

    @Override
    public void init ( GameContainer container ) throws SlickException
    {
        testMap = new TiledMap ( "data/TestMap.tmx" );
    }

    @Override
    public void update ( GameContainer container, int delta ) throws SlickException
    {
        // Do nothing
    }

    @Override
    public void render ( GameContainer container, Graphics g ) throws SlickException
    {
        testMap.render ( 0, 0 );
    }

    public static void main ( String args[] ) throws SlickException
    {
        SlickTest game = new SlickTest();
        AppGameContainer container = new AppGameContainer ( game );
        container.setDisplayMode ( 1024, 768, false );
        container.setAlwaysRender ( true );
        container.start();
    }
}

Add test for Slick graphics library.


// Use accessor methods to set and get private members.

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

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

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

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

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

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

class Shapes2 {
  public static void main(String args[]) {
    Triangle t1 = new Triangle();
    Triangle t2 = new Triangle();

    t1.setWidth(4.0);
    t1.setHeight(4.0);
    t1.style = "isosceles";

    t2.setWidth(8.0);
    t2.setHeight(12.0);
    t2.style = "right";

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

    System.out.println();

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


package pinterest;

import org.apache.http.client.utils.URIBuilder;

import java.net.URI;
import java.net.URISyntaxException;

import static org.apache.commons.lang3.StringUtils.isNotBlank;

public class EndPointURIBuilder {
    private static final String PROTOCOL = "https";
    private static final String HOST = "api.pinterest.com";
    private static final String PIN_PATH = "/v1/pins/{PIN_ID}/";
    private static final String MY_PIN_PATH = "/v1/me/pins/";
    private static final String BOARD_PIN_PATH = "/v1/boards/{BOARD_NAME}/pins/";
    private static final String BOARD_PATH = "/v1/boards/{USER_NAME}/{BOARD_NAME}/";
    private static final String MY_BOARD_PATH = "/v1/me/boards/";

    public static URI buildPinUri(final String accessToken, final String id, final String fields) throws URISyntaxException {
        final URIBuilder uriBuilder =  new URIBuilder()
                .setScheme(PROTOCOL)
                .setHost(HOST)
                .setPath(PIN_PATH.replace("{PIN_ID}", id))
                .setParameter("access_token", accessToken);

        if (isNotBlank(fields)) {
            uriBuilder.setParameter("fields", fields);
        }

        return uriBuilder.build();
    }

    public static URI buildMyPinUri(final String accessToken, final String fields) throws URISyntaxException {
        final URIBuilder uriBuilder =  new URIBuilder()
                .setScheme(PROTOCOL)
                .setHost(HOST)
                .setPath(MY_PIN_PATH)
                .setParameter("access_token", accessToken);

        if (isNotBlank(fields)) {
            uriBuilder.setParameter("fields", fields);
        }

        return uriBuilder.build();
    }

    public static URI buildBoardPinUri(final String accessToken, final String name, final String fields) throws URISyntaxException {
        final URIBuilder uriBuilder = new URIBuilder()
                .setScheme(PROTOCOL)
                .setHost(HOST)
                .setPath(BOARD_PIN_PATH.replace("{BOARD_NAME}", name))
                .setParameter("access_token", accessToken);

        if (isNotBlank(fields)) {
            uriBuilder.setParameter("fields", fields);
        }

        return uriBuilder.build();
    }

    public static URI buildBoardUri(final String accessToken, final String userName, final String boardName, final String fields) throws URISyntaxException {
        final URIBuilder uriBuilder = new URIBuilder()
                .setScheme(PROTOCOL)
                .setHost(HOST)
                .setPath(BOARD_PATH.replace("{USER_NAME}", userName).replace("{BOARD_NAME}", boardName))
                .setParameter("access_token", accessToken);

        if (isNotBlank(fields)) {
            uriBuilder.setParameter("fields", fields);
        }

        return uriBuilder.build();
    }

    public static URI buildMyBoardUri(final String accessToken, final String fields) throws URISyntaxException {
        final URIBuilder uriBuilder = new URIBuilder()
                .setScheme(PROTOCOL)
                .setHost(HOST)
                .setPath(MY_BOARD_PATH)
                .setParameter("access_token", accessToken);

        if (isNotBlank(fields)) {
            uriBuilder.setParameter("fields", fields);
        }

        return uriBuilder.build();
    }
}

Move end point URI builder to separate class


package net.restlesscoder.sandbox;

import java.lang.reflect.Array;
import java.util.Arrays;

public class ZipArrays {

	public static void main(final String... args) throws Exception {
		final String[] a = { "hello", "cruel", "world" };
		final String[] b = { "how", "are", "you" };
		final String[] c = { "until", "next", "time" };
		System.out.println(Arrays.deepToString(zip(a, b, c)));
	}

	@SafeVarargs
	public static <T> T[][] zip(final T[]... arrays) {
		@SuppressWarnings("unchecked")
		final T[][] zipped = (T[][]) //
		Array.newInstance(arrays[0].getClass().getComponentType(), arrays[0].length, arrays.length);
		return pivot(arrays, zipped);
	}

	private static <T> T[][] pivot(final T[][] src, final T[][] dest) {
		for (int a = 0; a < src.length; a++) {
			for (int i = 0; i < src[a].length; i++) {
				dest[i][a] = src[a][i];
			}
		}
		return dest;
	}
}

Add Java implementation of Python's zip function


package org.msf.records.ui.userlogin;

import android.test.ActivityInstrumentationTestCase2;

import org.msf.records.R;

import java.util.Date;

import static com.google.android.apps.common.testing.ui.espresso.Espresso.onView;
import static com.google.android.apps.common.testing.ui.espresso.action.ViewActions.click;
import static com.google.android.apps.common.testing.ui.espresso.action.ViewActions.typeText;
import static com.google.android.apps.common.testing.ui.espresso.assertion.ViewAssertions.matches;
import static com.google.android.apps.common.testing.ui.espresso.matcher.ViewMatchers.isDisplayed;
import static com.google.android.apps.common.testing.ui.espresso.matcher.ViewMatchers.withId;
import static com.google.android.apps.common.testing.ui.espresso.matcher.ViewMatchers.withText;

public class UserLoginActivityTest extends
        ActivityInstrumentationTestCase2<UserLoginActivity> {

    public UserLoginActivityTest() {
        super(UserLoginActivity.class);
    }

    @Override
    public void setUp() throws Exception {
        super.setUp();
        getActivity();
    }

    public void testAddUser() {
        String id = "" + new Date().getTime() % 1000;
        String username = "user" + id;
        String given = "Foo" + id;
        String family = "Bar" + id;
        onView(withText("Add User")).perform(click());
        onView(withId(R.id.add_user_username_tv)).perform(typeText(username));
        onView(withId(R.id.add_user_given_name_tv)).perform(typeText(given));
        onView(withId(R.id.add_user_family_name_tv)).perform(typeText(family));
        onView(withText("OK")).perform(click());
        onView(withText(given + " " + family)).check(matches(isDisplayed()));
        onView(withText("FB")).check(matches(isDisplayed()));
        onView(withText("FB")).perform(click());
        onView(withText("MSF Medical Records")).check(matches(isDisplayed()));
        onView(withText("FB")).perform(click());
        onView(withText(given + " " + family)).check(matches(isDisplayed()));
        onView(withId(R.id.button_log_out)).perform(click());
        onView(withText("Add User")).check(matches(isDisplayed()));
    }
}

Add a functional test for logging in and adding a user.


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

package com.dmdirc.util.annotations.observable;

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

/**
 * Denotes that an observable subclass should be generated.
 */
@Target(ElementType.TYPE)
public @interface Observable {

    /**
     * Custom name for the observable. If not specified, 'Observable' + the class name will be used.
     *
     * @return The name to use for the observable.
     */
    String name() default "";

    /**
     * The prefixes of methods which should be wrapped, and fire change listeners.
     *
     * @return The method prefixes which should be wrapped.
     */
    String[] methodPrefixes() default {"set"};

    /**
     * Whether or not to include the old value of the field in listener calls.
     *
     * @return True to pass the old value, false to just pass the new one.
     */
    boolean oldValue() default true;

}

Add annotation for observable generation.


/*
 * Copyright 2020, 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.core;

import io.spine.server.event.EventFactory;
import io.spine.server.type.EventEnvelope;
import io.spine.server.type.given.GivenEvent;
import io.spine.testing.core.given.GivenUserId;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;

import static com.google.common.truth.Truth.assertThat;
import static io.spine.protobuf.AnyPacker.pack;
import static io.spine.server.event.EventFactory.on;

/**
 * Extra tests for {@link Signal}s.
 *
 * <p>The main test suite for {@code Signal}s is located in the {@code core} module. This test suite
 * only hosts tests which rely on the components from the {@code server} module.
 */
@DisplayName("`Signal` also should")
class SignalTest {

    @Test
    @DisplayName("produce correct origin")
    void produceOrigin() {
        Event originalEvent = GivenEvent.arbitrary();
        UserId producerEntityId = GivenUserId.generated();
        EventFactory factory = on(EventEnvelope.of(originalEvent), pack(producerEntityId));
        Event derivativeEvent = factory.createEvent(GivenEvent.message(), null);
        Origin origin = derivativeEvent.getContext().getPastMessage();
        assertThat(origin.getMessage())
                .isEqualTo(originalEvent.messageId());
        assertThat(origin.hasGrandOrigin())
                .isFalse();
    }
}

Add a test for message origins


package net.restlesscoder.sandbox;

import java.io.IOException;

public class GenericThrows {

	interface Executable<E extends Exception> {
		void run() throws E;
	}

	public static <E extends Exception> void assertThrows(Class<E> exceptionType, Executable<E> executable) {
		try {
			executable.run();
		}
		catch (Exception exc) {
			if (exceptionType.isInstance(exc)) {
				// assert true!
			}
			else {
				throw new RuntimeException("User passed a lying executable object");
			}
			// assert false!
			exc.printStackTrace();
		}
	}

	public static void main(final String... args) {
		assertThrows(IOException.class, () -> {});
	}
}

Add example of throws clause w/ generic parameter


package com.growthbeat.model;

import static org.junit.Assert.fail;

import org.junit.Test;

import com.growthbeat.BaseTest;
import com.growthbeat.GrowthbeatException;

public class ActionTest extends BaseTest {

	@Test
	public void findById() {
		// Service credential is required.
		try {
			Action action = Action.findById("Action:Growthbeat", testCredential.getId());
			fail();
		} catch (GrowthbeatException e) {
		}
	}

	@Test
	public void create() {
		// Service credential is required.
		try {
			Action action = Action.create("Action:Growthbeat", "XXX", testCredential.getId());
			fail();
		} catch (GrowthbeatException e) {
		}
	}

	@Test
	public void deleteById() {
		// Service credential is required.
		try {
			Action.deleteById("Action:Growthbeat:XXX", testCredential.getId());
			fail();
		} catch (GrowthbeatException e) {
		}
	}

}

Add test of Action model


package org.twig.functional;

import org.junit.Assert;
import org.junit.Test;
import org.twig.Environment;
import org.twig.exception.TwigException;
import org.twig.loader.HashMapLoader;

import java.util.HashMap;

public class RenderTests {
    private Environment environment;

    @Test
    public void canRenderText() throws TwigException {
        HashMap<String, String> templates = new HashMap<>();
        templates.put("foo.twig", "bar");
        setupEnvironment(templates);

        Assert.assertEquals("Text should be rendered properly", "bar", environment.render("foo.twig"));
    }

    @Test
    public void canRenderBasicPrintStatement() throws TwigException {
        HashMap<String, String> templates = new HashMap<>();
        templates.put("foo.twig", "{{ 'bar' }}");
        setupEnvironment(templates);

        Assert.assertEquals("Rendered string should equal string contents", "bar", environment.render("foo.twig"));
    }

    private void setupEnvironment(HashMap<String, String> templates) {
        environment = new Environment(new HashMapLoader(templates));
    }
}

Add functional tests for text & basic print statement


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

import java.util.StringTokenizer;
import java.util.regex.Pattern;

/**
 * Utility to simplify comparisons.
 */
public final class RegexUtils {

  /**
   * Restricted constructor.
   */
  private RegexUtils() {
  }

  /**
   * Converts a simple wildcard style pattern to a regex pattern.
   *

   * The asterisk (*) matches zero or more characters.

   * The question mark (?) matches one character.

   *

   * The returned pattern will be setup to match a whole string using
   * ^ and $.
   *
   * @param text  the text to match, not null
   * @return the pattern, not null
   */
  public static Pattern wildcardsToPattern(final String text) {
    StringTokenizer tkn = new StringTokenizer(text, "?*", true);
    StringBuilder buf = new StringBuilder(text.length() + 10);
    buf.append('^');
    boolean lastStar = false;
    while (tkn.hasMoreTokens()) {
      String str = tkn.nextToken();
      if (str.equals("?")) {
        buf.append('.');
        lastStar = false;
      } else if (str.equals("*")) {
        if (lastStar == false) {
          buf.append(".*");
        }
        lastStar = true;
      } else {
        buf.append(Pattern.quote(str));
        lastStar = false;
      }
    }
    buf.append('$');
    return Pattern.compile(buf.toString(), Pattern.CASE_INSENSITIVE);
  }

}

Complete implementation of config master


package com.agiliq.android.moreappslib;

import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;

public class GridItemAdapter extends ArrayAdapter<GridItemData> {
    private final Context context;
    private final int gridCellLayoutResource;
    private final GridItemData[] gridItems;

    public GridItemAdapter(Context context, int gridCellLayoutResource, GridItemData[] gridItems) {
        super(context, gridCellLayoutResource, gridItems);
        this.context = context;
        this.gridCellLayoutResource = gridCellLayoutResource;
        this.gridItems = gridItems;
    }

    @Override
    public View getView(int position, View gridCell, ViewGroup parent) {
        GridItemHolder holder;

        if (gridCell != null) {
            holder = (GridItemHolder) gridCell.getTag();
        } else {
            LayoutInflater inflater = ((Activity) context).getLayoutInflater();
            gridCell = inflater.inflate(gridCellLayoutResource, parent, false);

            holder = new GridItemHolder();
            holder.imageView = (ImageView) gridCell.findViewById(R.id.mal_imageView);
            holder.textView = (TextView) gridCell.findViewById(R.id.mal_textView);

            gridCell.setTag(holder);
        }

        GridItemData gridItem = gridItems[position];
        holder.imageView.setImageResource(gridItem.getShowcasedAppIconDrawableResource());
        holder.textView.setText(gridItem.getShowcasedAppName());

        return gridCell;
    }

    static class GridItemHolder {
        ImageView imageView;
        TextView textView;
    }
}

Add adapter class for the custom layout


package com.catchoom.examples.glass;

import java.util.ArrayList;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;

import com.catchoom.api.CatchoomSearchResponseItem;
import com.google.android.glass.app.Card;

public class ResultActivity extends Activity{

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

		Bundle extras= getIntent().getExtras();
		ArrayList<CatchoomSearchResponseItem> results= extras.getParcelableArrayList("results");

		//In this example we just consider the best match.
		//Note that the API can return more than one match, and they are sorted by the confidence score.
		CatchoomSearchResponseItem bestMatch= results.get(0);

		//Create a card with the content of the matched image.
		Card card = new Card(this);
		card.setText(bestMatch.getItemName());
		card.setFootnote(bestMatch.getItemId());

		View cardView = card.getView();
		setContentView(cardView);

	}
}

Add activity that shows the results


package com.k13n.lt_codes;

public final class ErasureChannel {
  private final double erasureProbability;

  public static final byte[] ERASED = new byte[0];

  public ErasureChannel(double erasureProbability) {
    this.erasureProbability = erasureProbability;
  }

  public byte[] transmit(byte[] data)
  {
    if(Math.random() <= erasureProbability)
    {
      return ERASED;
    }
    else
      return data;
  }
}

Add erasure channel class, mostly for testing purposes


package leetcode.best_time_to_buy_and_sell_stock;

public class Solution {
	public int maxProfit(int[] prices) {
		int ret = 0;
		if(prices.length == 0) return 0;
		int min = prices[0], max = prices[0];
        for(int x : prices){
        	if(min > x){
        		min = x;
        		max = x;
        	}
        	if(max < x){
        		max = x;
        	}
        	if(max - min > ret){
        		ret = max - min;
        	}
        }
        return ret;
    }
}

Add java solution for 121. Best Time to Buy and Sell Stock


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

/**
 *
 * @author guberti
 */
public class View {
    // Views are "windows" into the game board
    // Views are always square, for the time being
    // Views store game tiles as an array of integers
    // -1 means empty
    // Any number that is >= 0 is the power of an alien on that tile

    private int[][] board;

    // Corner refers to top left of board

    private int topX;
    private int topY;

    public View (int topX, int topY, int[][] board) {
        this.board = board;
        this.topX = topX;
        this.topY = topY;
    }

    public boolean isAlienAtPos(int x, int y) throws CantSeeSquareException {
        if (topX + board.length > x ||
                topX < x ||
                topY + board.length > y ||
                topY < y) {
            throw new CantSeeSquareException();
        }
        return board[topX - x][topY - y] > -1;
    }

}

class CantSeeSquareException extends Exception {}

Add in some preliminary code to allow aliens to see other squares


package net.openhft.chronicle.queue;

import net.openhft.chronicle.queue.impl.single.SingleChronicleQueueBuilder;
import net.openhft.chronicle.wire.MethodReader;
import org.junit.Assert;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.IOException;

/**
 * Created on 19.10.2016.
 */
public class ChronicleQueueMethodsWithoutParameters extends ChronicleQueueTestBase {

    public interface SomeListener {

        void methodWithoutParams();

        void methodWithOneParam(int i);
    }

    public static class SomeManager implements SomeListener {

        public boolean methodWithoutParamsInvoked = false;
        public boolean methodWithOneParamInvoked = false;

        @Override
        public void methodWithoutParams() {
            methodWithoutParamsInvoked = true;
        }

        @Override
        public void methodWithOneParam(int i) {
            methodWithOneParamInvoked = true;
        }
    }

    protected static final Logger LOG = LoggerFactory.getLogger(ChronicleQueueMethodsWithoutParameters.class);

    @Test
    public void test() throws IOException, InterruptedException {
        File file = getTmpDir();

        try (ChronicleQueue queue = SingleChronicleQueueBuilder.binary(file).build()) {
            final ExcerptAppender appender = queue.acquireAppender();
            final ExcerptTailer tailer = queue.createTailer();

            SomeListener someListener = appender.methodWriter(SomeListener.class);

            SomeManager someManager = new SomeManager();
            MethodReader reader = tailer.methodReader(someManager);

            LOG.debug("Writing to queue");
            someListener.methodWithOneParam(1);
            someListener.methodWithoutParams();

            LOG.debug("Reading from queue");
            boolean run = true;
            while (run) {
                run = reader.readOne();
            }

            Assert.assertEquals(true, someManager.methodWithOneParamInvoked);
            Assert.assertEquals(true, someManager.methodWithoutParamsInvoked);

            LOG.warn(queue.dump());
        }
    }
}

Test for issue with invokation of method without parameters


package org.jdesktop.swingx.painter;

import org.jdesktop.beans.AbstractBeanInfoTest;

public class AlphaPainterBeanInfoTest extends AbstractBeanInfoTest<AlphaPainter<Object>> {
    /**
     * {@inheritDoc}
     */
    @Override
    protected AlphaPainter<Object> createInstance() {
        return new AlphaPainter<Object>();
    }
}

Add bean test for AlphaPainter.


/*
 * Java Genetic Algorithm Library (@__identifier__@).
 * Copyright (c) @__year__@ Franz Wilhelmstötter
 *
 * 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.
 *
 * Author:
 *    Franz Wilhelmstötter (franz.wilhelmstoetter@gmx.at)
 */
package org.jenetics.util;

import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.TimeUnit;

import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.State;
import org.openjdk.jmh.runner.Runner;
import org.openjdk.jmh.runner.RunnerException;
import org.openjdk.jmh.runner.options.Options;
import org.openjdk.jmh.runner.options.OptionsBuilder;

/**
 * @author Franz Wilhelmstötter
 * @version 3.0 — $Date: 2014-07-14 $
 * @since 3.0
 */
@State(Scope.Benchmark)
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
public class SeqPerf {

	private final int index = ThreadLocalRandom.current().nextInt(1000);

	private final Integer[] array = new Integer[1000];
	{
		for (int i = 0; i < array.length; ++i) {
			array[i] = i;
		}
	}
	private final MSeq<Integer> seq = MSeq.ofLength(1000);
	{
		for (int i = 0; i < seq.length(); ++i) {
			seq.set(i, i);
		}
	}

	@Benchmark
	public Integer getFromArray() {
		return array[index];
	}

	@Benchmark
	public Integer getFromSeq() {
		return seq.get(index);
	}

	public static void main(String[] args) throws RunnerException {
		final Options opt = new OptionsBuilder()
			.include(".*" + SeqPerf.class.getSimpleName() + ".*")
			.warmupIterations(3)
			.measurementIterations(5)
			.threads(1)
			.forks(1)
			.build();

		new Runner(opt).run();
	}

}

Add performance test for Seq implementation.


//
// DebugTools.java
//

/*
LOCI Common package: utilities for I/O, reflection and miscellaneous tasks.
Copyright (C) 2005-@year@ Melissa Linkert, Curtis Rueden and Chris Allan.

This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 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 General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
*/

package loci.common;

import java.io.ByteArrayOutputStream;
import java.io.PrintStream;

/**
 * A utility class with convenience methods for debugging.
 *
 *

Source code:

 *
Trac,
 * SVN

 *
 * @author Curtis Rueden ctrueden at wisc.edu
 */
public final class DebugTools {

  // -- Constructor --

  private DebugTools() { }

  // -- DebugTools methods --

  /** Extracts the given exception's corresponding stack trace to a string. */
  public static String getStackTrace(Throwable t) {
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    t.printStackTrace(new PrintStream(out));
    return new String(out.toByteArray());
  }

}

Add utility method for extracting a stack trace string from an exception.


package com.namelessmc.java_api.logger;

import java.util.logging.Level;
import java.util.logging.Logger;

public class JavaLoggerLogger extends ApiLogger {

	private final Logger logger;
	private final Level level;
	private final String prefix;

	public JavaLoggerLogger(final Logger logger, final Level level, final String prefix) {
		this.logger = logger;
		this.level = level;
		this.prefix = prefix;
	}

	@Override
	public void log(final String string) {
		this.logger.log(this.level, this.prefix + string);
	}

}

Add apilogger implementation using java logger


package session;

import javax.annotation.PostConstruct;
import javax.ejb.Singleton;
import javax.ejb.TransactionManagement;
import javax.ejb.TransactionManagementType;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import domain.Customer;
import domain.Order;

/** Create one of each entity so the database
 * is "not null" - using /import.sql only works
 * in Hibernate.
 * @author ian
 */
@Singleton
@TransactionManagement(TransactionManagementType.CONTAINER)
public class PopulateDatabaseSingletonBean {

		@PersistenceContext(name="customer") EntityManager customerEntityManager;
		@PersistenceContext(name="orders") EntityManager orderEntityManager;

		@PostConstruct
		public void initDB() {
			System.out.println("PopulateDatabaseSingletonBean.initCustomerDB()");
			Customer cust = new Customer("Idon T'kare");
			customerEntityManager.persist(cust);

			System.out.println("PopulateDatabaseSingletonBean.initOrdersDB()");
			Order order = new Order();
			orderEntityManager.persist(order);
		}
}

Create an EE6 singleton bean to pre-load the database, since /import.sql is Hibernate-specific, ignored by most. Speaking of ignored, this bean's @PostConstruct annotated methods are ignored, at least by JBoss 6.0.0.20100911-M5.


package org.openmhealth.shim.common.mapper;

import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.fasterxml.jackson.datatype.jdk8.Jdk8Module;
import com.fasterxml.jackson.datatype.jsr310.JSR310Module;
import org.openmhealth.schema.serializer.Rfc3339OffsetDateTimeSerializer;
import org.testng.annotations.BeforeClass;

import java.time.OffsetDateTime;

/**
 * @author Emerson Farrugia
 */
public abstract class DataPointMapperUnitTests {

    protected static final ObjectMapper objectMapper = new ObjectMapper();

    @BeforeClass
    public static void initializeObjectMapper() {

        // we represent JSON numbers as Java BigDecimals
        objectMapper.enable(DeserializationFeature.USE_BIG_DECIMAL_FOR_FLOATS);

        // we serialize dates, date times, and times as strings, not numbers
        objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);

        // we default to the ISO8601 format for JSR-310 and support Optional
        objectMapper.registerModule(new JSR310Module());
        objectMapper.registerModule(new Jdk8Module());

        // but we have to explicitly support the RFC3339 format over ISO8601 to make JSON Schema happy, specifically to
        // prevent the truncation of zero second fields
        SimpleModule rfc3339Module = new SimpleModule("rfc3339Module");
        rfc3339Module.addSerializer(new Rfc3339OffsetDateTimeSerializer(OffsetDateTime.class));
        objectMapper.registerModule(rfc3339Module);
    }
}

Add base class for mapper unit tests


package water.fvec;

import org.testng.AssertJUnit;
import org.testng.annotations.Test;
import water.TestUtil;

import java.util.Arrays;

public class C4SChunkTest extends TestUtil {
  @Test void test_inflate_impl() {
    for (int l=0; l<1; ++l) {
      NewChunk nc = new NewChunk(null, 0);

      // -2.147483647, 0, 0.0000215, 2.147583647, NA for l==0
      // NA, -2.147483647, 0, 0.0000215, 2.147583647, NA for l==1
      long[] man = new long[]{-2147483647, 0, 215, 188001238, 2147483647};
      int[] exp = new int[]{-9, 1, -6, -8, -9};
      if (l==1) nc.addNA(); //-2147483648
      for (int i = 0; i < man.length; ++i) nc.addNum(man[i], exp[i]);
      nc.addNA();

      Chunk cc = nc.compress();
      AssertJUnit.assertEquals(man.length + 1 + l, cc.len());
      AssertJUnit.assertTrue(cc instanceof C4SChunk);
      if (l==1) AssertJUnit.assertTrue(cc.isNA0(0));
      for (int i = 0; i < man.length; ++i)
        AssertJUnit.assertTrue("Expected: " + man[i] * Math.pow(10, exp[i]) + ", but is " + cc.at0(l+i), Math.abs((man[i] * Math.pow(10, exp[i])) - cc.at0(l+i)) < 1e-10);
      AssertJUnit.assertTrue(cc.isNA0(man.length + l));

      Chunk cc2 = cc.inflate_impl(new NewChunk(null, 0)).compress();
      AssertJUnit.assertEquals(man.length + 1 + l, cc.len());
      if (l==1) AssertJUnit.assertTrue(cc2.isNA0(0));
      for (int i = 0; i < man.length; ++i)
        AssertJUnit.assertTrue("Expected: " + man[i] * Math.pow(10, exp[i]) + ", but is " + cc2.at0(l+i), Math.abs((man[i] * Math.pow(10, exp[i])) - cc2.at0(l+i)) < 1e-10);
      AssertJUnit.assertTrue(cc2.isNA0(man.length + l));
      AssertJUnit.assertTrue(cc2 instanceof C4SChunk);

      AssertJUnit.assertTrue(Arrays.equals(cc._mem, cc2._mem));
    }
  }
}

Add inflate_impl test for C4SChunk.


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

/*
 * Test class for BinaryTCPClientImpl utility methods.
 *
 */
package org.apache.jmeter.protocol.tcp.sampler;

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

import junit.framework.TestCase;

public class LengthPrefixedBinaryTCPClientImplTest extends TestCase {

    public void testError() throws Exception {
        ByteArrayOutputStream os = null;
        ByteArrayInputStream is = null;
        LengthPrefixedBinaryTCPClientImpl lp = new LengthPrefixedBinaryTCPClientImpl();
        try {
            lp.write(os, is);
            fail("Expected java.lang.UnsupportedOperationException");
        } catch (java.lang.UnsupportedOperationException expected) {
        }
    }

    public void testValid() throws Exception {
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        LengthPrefixedBinaryTCPClientImpl lp = new LengthPrefixedBinaryTCPClientImpl();
        final String DATA = "31323334353637";
        lp.write(os, DATA);
        os.close();
        final byte[] byteArray = os.toByteArray();
        assertEquals(2+(DATA.length()/2), byteArray.length);
        ByteArrayInputStream is = new ByteArrayInputStream(byteArray);
        assertEquals(DATA, lp.read(is));
    }

}

Add some tests for LengthPrefixedBinaryTCPClientImpl


package com.samovich.cop2800.chapter8;

/**
 * Filename ReturnArray.java
 * Created by Valery Samovich
 * Written on 6/21/2016
 */
public class ReturnArray {

    /**
     * main method
     * @param args
     */
    public static void main(String[] args) {
        System.out.print("Returned array: ");
        // loop over returned array
        for (int i = 0; i < ReturnArray.getArray().length; i++)
            System.out.print(ReturnArray.getArray()[i] + " ");
    }

    /**
     * Retunr the array
     * @return
     */
    private static int[] getArray() {
        int[] scores = {90, 80, 70, 60};
        return scores;
    }
}

Add example for array a method


package net.spals.appbuilder.app.core.generic;

import com.google.inject.CreationException;
import com.google.inject.Injector;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;

import static com.googlecode.catchexception.CatchException.catchException;
import static com.googlecode.catchexception.CatchException.caughtException;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.instanceOf;
import static org.hamcrest.Matchers.is;

/**
 * A series of functional tests for {@link GenericWorkerApp}
 * which do not fit into the minimal or sample test classes.
 *
 * @author tkral
 */
public class GenericWorkerAppFTests {
    private final Logger LOGGER = LoggerFactory.getLogger(GenericWorkerAppFTests.class);

    @Test
    public void testModuleOverrideError() {
        // This doesn't really test anything in the AppBuilder code
        // but just proves out how Guice errors out on override bindings
        catchException(() -> new GenericWorkerApp.Builder("testModuleOverrideError", LOGGER)
            .addModule(binder -> binder.bind(MySingletonService.class)
                .toInstance(new MySingletonServiceA()))
            .addModule(binder -> binder.bind(MySingletonService.class)
                .toInstance(new MySingletonServiceB()))
            .build());

        assertThat(caughtException(), instanceOf(CreationException.class));
    }

    @DataProvider
    Object[][] enableBindingOverridesProvider() {
        final MySingletonService serviceA = new MySingletonServiceA();
        final MySingletonService serviceB = new MySingletonServiceB();

        return new Object[][] {
                // Ensure that binding order is honored. The last one in is chosen
                {serviceA, serviceB},
                {serviceB, serviceA},
        };
    }

    @Test(dataProvider = "enableBindingOverridesProvider")
    public void testEnableBindingOverrides(final MySingletonService firstService,
                                           final MySingletonService secondService) {
        final GenericWorkerApp app = new GenericWorkerApp.Builder(
                "testEnableBindingOverrides", LOGGER)
            .addModule(binder -> binder.bind(MySingletonService.class)
                .toInstance(firstService))
            .addModule(binder -> binder.bind(MySingletonService.class)
                .toInstance(secondService))
            .enableBindingOverrides()
            .build();

        final Injector serviceInjector = app.getServiceInjector();
        assertThat(serviceInjector.getInstance(MySingletonService.class), is(secondService));
    }

    private interface MySingletonService {  }

    private class MySingletonServiceA implements MySingletonService {  }

    private class MySingletonServiceB implements MySingletonService {  }
}

Add functional tests for enableBindingOverrides option


package net.greypanther.fastutil.tests;

import org.junit.Test;

import it.unimi.dsi.fastutil.ints.IntBigArrayBigList;

public final class IntBigList {
  @Test(expected=IndexOutOfBoundsException.class)
  public void testListIterator_tooLow() {
    new IntBigArrayBigList().listIterator(-1L);
  }

  @Test(expected=IndexOutOfBoundsException.class)
  public void testListIterator_tooHigh() {
    new IntBigArrayBigList().listIterator(1L);
  }
}

Add failing test for IntBigArrayBigList.listIterator


/*
 * Zorbage: an algebraic data hierarchy for use in numeric processing.
 *
 * Copyright (C) 2016-2019 Barry DeZonia
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * 1. Redistributions of source code must retain the above copyright notice,
 *    this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright notice,
 *    this list of conditions and the following disclaimer in the documentation
 *    and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */
package nom.bdezonia.zorbage.algorithm;

import static org.junit.Assert.assertEquals;

import org.junit.Test;

import nom.bdezonia.zorbage.algebras.G;
import nom.bdezonia.zorbage.type.data.float64.real.Float64Member;
import nom.bdezonia.zorbage.type.storage.array.ArrayStorage;
import nom.bdezonia.zorbage.type.storage.array.ArrayStorageBigDecimal;
import nom.bdezonia.zorbage.type.storage.datasource.IndexedDataSource;

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

	@Test
	public void test1() {

		Float64Member value = G.DBL.construct();
		IndexedDataSource<Float64Member> nums = ArrayStorage.allocateDoubles(
				new double[] {1.1, 1.1, 1.2, 3, 3, 3, 1.1, 4, 5, 5, 5});
		// Unique expects a sorted list as input
		Sort.compute(G.DBL, nums);
		IndexedDataSource<Float64Member> uniqueNums =
				Unique.compute(G.DBL, nums);

		assertEquals(5, uniqueNums.size());

		uniqueNums.get(0, value);
		assertEquals(1.1, value.v(), 0);

		uniqueNums.get(1, value);
		assertEquals(1.2, value.v(), 0);

		uniqueNums.get(2, value);
		assertEquals(3, value.v(), 0);

		uniqueNums.get(3, value);
		assertEquals(4, value.v(), 0);

		uniqueNums.get(4, value);
		assertEquals(5, value.v(), 0);
	}
}

Define a test for the Unique algorithm


package cgeo.geocaching.models;

import cgeo.geocaching.connector.trackable.TrackableBrand;
import cgeo.geocaching.enumerations.LogTypeTrackable;

import org.apache.commons.lang3.StringUtils;

public final class TrackableLog {
    public TrackableLog(final String geocode, final String trackCode, final String name, final int id, final int ctl, final TrackableBrand brand) {
        this.geocode = geocode;
        this.trackCode = trackCode;
        this.name = name;
        this.id = id;
        this.ctl = ctl;
        this.brand = brand;
    }

    public final int ctl;
    public final int id;
    public final String geocode;
    public final String trackCode;
    public final String name;
    public final TrackableBrand brand;
    public LogTypeTrackable action = LogTypeTrackable.DO_NOTHING; // base.logTrackablesAction - no action

    public void setAction(final LogTypeTrackable logTypeTrackable) {
        action = logTypeTrackable;
    }

    @Override
    public int hashCode() {
        return StringUtils.defaultString(trackCode).hashCode();
    }

    @Override
    public boolean equals(final Object obj) {
        if (!(obj instanceof TrackableLog)) {
            return false;
        }
        final TrackableLog tb = (TrackableLog) obj;
        return StringUtils.defaultString(tb.trackCode).equals(trackCode);
    }
}

package cgeo.geocaching.models;

import cgeo.geocaching.connector.trackable.TrackableBrand;
import cgeo.geocaching.enumerations.LogTypeTrackable;

import org.apache.commons.lang3.StringUtils;

public final class TrackableLog {
    public final int ctl;
    public final int id;
    public final String geocode;
    public final String trackCode;
    public final String name;
    public final TrackableBrand brand;
    public LogTypeTrackable action = LogTypeTrackable.DO_NOTHING; // base.logTrackablesAction - no action

    public TrackableLog(final String geocode, final String trackCode, final String name, final int id, final int ctl, final TrackableBrand brand) {
        this.geocode = geocode;
        this.trackCode = trackCode;
        this.name = name;
        this.id = id;
        this.ctl = ctl;
        this.brand = brand;
    }

    public void setAction(final LogTypeTrackable logTypeTrackable) {
        action = logTypeTrackable;
    }

    @Override
    public int hashCode() {
        return StringUtils.defaultString(trackCode).hashCode();
    }

    @Override
    public boolean equals(final Object obj) {
        if (!(obj instanceof TrackableLog)) {
            return false;
        }
        final TrackableLog tb = (TrackableLog) obj;
        return StringUtils.defaultString(tb.trackCode).equals(trackCode);
    }
}

Fix codacy: Fields should be declared at the top of the class