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

package com.akiban.server.expression.std;

import com.akiban.server.error.OverflowException;
import com.akiban.server.expression.Expression;
import com.akiban.server.expression.ExpressionEvaluation;
import com.akiban.server.types.AkType;
import com.akiban.server.types.NullValueSource;
import com.akiban.server.types.ValueSource;
import com.akiban.server.types.util.ValueHolder;

public class TruncateStringExpression extends AbstractUnaryExpression
{
    public TruncateStringExpression(int length, Expression operand) {
        super(AkType.DECIMAL, operand);
        this.length = length;
    }

    @Override
    protected String name() {
        return "TruncateString";
    }

    @Override
    public String toString() {
        return name() + "(" + operand() + "," + length + ")";
    }

    @Override
    public ExpressionEvaluation evaluation() {
        return new InnerEvaluation(length, operandEvaluation());
    }

    private final int length;

    private static final class InnerEvaluation extends AbstractUnaryExpressionEvaluation {
        public InnerEvaluation(int length, ExpressionEvaluation ev) {
            super(ev);
            this.length = length;
        }

        @Override
        public ValueSource eval() {
            ValueSource operandSource = operand();
            if (operandSource.isNull())
                return NullValueSource.only();
            String value = operandSource.getString();
            if (value.length() > length)
                value = value.substring(0, length);
            return hold(value);
        }

        private ValueSource hold(String value) {
            if (holder == null) {
                holder = new ValueHolder();
            }
            holder.putString(value);
            return holder;
        }

        private final int length;
        private ValueHolder holder;
    }
}

Add an expression for truncating strings as part of full CAST.


package com.futurice.freesound.utils;

import org.junit.Test;

import java.util.Collection;
import java.util.Collections;

import rx.Observable;

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

public class CollectionUtilsTest {

    @Test
    public void areEqual_returnsTrue_whenTheCollectionsContainSameElementsInSameOrder() {
        Collection collection1 = createRangeCollection(0, 5);
        Collection collection2 = createRangeCollection(0, 5);

        boolean areEqual = CollectionUtils.areEqual(collection1, collection2);

        assertThat(areEqual).isTrue();
    }

    @Test
    public void areEqual_returnsFalse_whenTheCollectionsHaveSameElementsInDifferentOrder() {
        Collection collection1 = createRangeCollection(0, 5);
        Collection collection2 = createRangeCollection(5, 0);

        boolean areEqual = CollectionUtils.areEqual(collection1, collection2);

        assertThat(areEqual).isFalse();
    }

    @Test
    public void areEqual_returnsFalse_whenTheCollectionsContainDifferentElements() {
        Collection collection1 = createRangeCollection(0, 5);
        Collection collection2 = createRangeCollection(5, 10);

        boolean areEqual = CollectionUtils.areEqual(collection1, collection2);

        assertThat(areEqual).isFalse();
    }

    @Test
    public void areEqual_returnsFalse_whenTheCollectionsHaveDifferentSizes() {
        Collection collection1 = createRangeCollection(0, 5);
        Collection collection2 = createRangeCollection(0, 4);

        boolean areEqual = CollectionUtils.areEqual(collection1, collection2);

        assertThat(areEqual).isFalse();
    }

    @Test
    public void areEqual_returnsFalse_whenOneCollectionIsNull() {
        Collection collection1 = createRangeCollection(0, 5);
        Collection collection2 = null;

        boolean areEqual = CollectionUtils.areEqual(collection1, collection2);

        assertThat(areEqual).isFalse();
    }

    @Test
    public void areEqual_returnsFalse_whenBothCollectionsAreNull() {
        Collection collection1 = null;
        Collection collection2 = null;

        boolean areEqual = CollectionUtils.areEqual(collection1, collection2);

        assertThat(areEqual).isFalse();
    }

    @Test
    public void areEqual_returnsTrue_whenTheTwoCollectionsAreEmpty() {
        Collection collection1 = Collections.EMPTY_LIST;
        Collection collection2 = Collections.EMPTY_LIST;

        boolean areEqual = CollectionUtils.areEqual(collection1, collection2);

        assertThat(areEqual).isTrue();
    }

    private static Collection<Integer> createRangeCollection(final int start, final int end) {
        if (start <= end) {
            return Observable.range(start, end - start)
                             .toList()
                             .toBlocking()
                             .first();
        } else {
            return Observable.range(end, start - end)
                             .map(it -> (start + end) - it - 1)
                             .toList()
                             .toBlocking()
                             .first();
        }
    }
}

Add tests to collection utils


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

/**
 * Names of init parameters that can be used in web.xml to configure Weld's Servlet integration.
 *
 * @author Jozef Hartinger
 *
 */
public interface InitParameters {

    String CONTEXT_FORWARD_IGNORE = "org.jboss.weld.context.ignore.forward";
    String CONTEXT_INCLUDE_IGNORE = "org.jboss.weld.context.ignore.include";
    String CONTEXT_MAPPING = "org.jboss.weld.context.mapping";
}

Add names of init parameters to an interface


public class Solution {

    public static int searchInsert(int[] nums, int target) {

        int low = 0;
        int high = nums.length;

        while (low < high) {

            int mid = low + (high - low) / 2;

            if (nums[mid] == target) {
                return mid;
            }

            if (nums[mid] < target) {
                low = mid + 1;
            } else {
                high = mid;
            }

        }

        return low;

    }

}

Create : 35 Search Insert Position


public class Solution {
    /**
     * @param matrix, a list of lists of integers
     * @param target, an integer
     * @return a boolean, indicate whether matrix contains target
     */
    public boolean searchMatrix(int[][] matrix, int target) {
        // write your code here
        if (matrix.length == 0 || matrix[0].length == 0) {
            return false;
        }

        int nrows =  matrix.length;
        int ncols = matrix[0].length;
        int l = 0;
        int r = nrows * ncols - 1;
        int m;
        int i;
        int j;

        while (l <= r) {
            m = (l + r) / 2;
            i = m / ncols;
            j = m % ncols ;
            if (matrix[i][j] == target) {
                return true;
            } else if (matrix[i][j] < target) {
                l = m + 1;
            } else {
                r = m - 1;
            }
        }

        return false;
    }
}

Create Search a 2D Matrix for LintCode


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

import static java.lang.invoke.MethodHandles.lookup;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.api.condition.OS.LINUX;
import static org.slf4j.LoggerFactory.getLogger;

import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.condition.EnabledOnOs;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import org.openqa.selenium.WebDriver;
import org.slf4j.Logger;

import io.github.bonigarcia.wdm.WebDriverManager;

/**
 * Test with Chrome in Docker.
 *
 * @author Boni Garcia
 * @since 4.0.0
 */
@EnabledOnOs(LINUX)
class DockerChromeVersionsTest {

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

    WebDriver driver;

    @AfterEach
    void teardown() {
        if (driver != null) {
            driver.quit();
        }
    }

    @ParameterizedTest
    @ValueSource(strings = { "", "91", "91.0" })
    void test(String browserVersion) {
        driver = WebDriverManager.chromedriver().browserInDocker()
                .browserVersion(browserVersion).create();

        String sutUrl = "https://github.com/bonigarcia/webdrivermanager";
        driver.get(sutUrl);
        String title = driver.getTitle();
        log.debug("The title of {} is {}", sutUrl, title);

        assertThat(title)
                .contains("Automated driver management for Selenium WebDriver");
    }

}

Include Docker tests with custom versions


/*******************************************************************************
 *  Copyright (c) 2011 GitHub Inc.
 *  All rights reserved. This program and the accompanying materials
 *  are made available under the terms of the Eclipse Public License v1.0
 *  which accompanies this distribution, and is available at
 *  http://www.eclipse.org/legal/epl-v10.html
 *
 *  Contributors:
 *    Kevin Sawicki (GitHub Inc.) - initial API and implementation
 *******************************************************************************/
package org.eclipse.egit.ui.internal.commit;

import org.eclipse.jface.action.IAction;
import org.eclipse.jface.window.Window;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.IWorkbenchWindowActionDelegate;
import org.eclipse.ui.actions.ActionDelegate;

/**
 * Open commit action
 */
public class OpenCommitAction extends ActionDelegate implements
		IWorkbenchWindowActionDelegate {

	private Shell shell;

	@Override
	public void run(IAction action) {
		CommitSelectionDialog dialog = new CommitSelectionDialog(shell, true);
		if (Window.OK == dialog.open())
			for (Object result : dialog.getResult())
				CommitEditor.openQuiet((RepositoryCommit) result);
	}

	public void init(IWorkbenchWindow window) {
		shell = window.getShell();
	}

}

/*******************************************************************************
 *  Copyright (c) 2011 GitHub Inc.
 *  All rights reserved. This program and the accompanying materials
 *  are made available under the terms of the Eclipse Public License v1.0
 *  which accompanies this distribution, and is available at
 *  http://www.eclipse.org/legal/epl-v10.html
 *
 *  Contributors:
 *    Kevin Sawicki (GitHub Inc.) - initial API and implementation
 *******************************************************************************/
package org.eclipse.egit.ui.internal.commit;

import org.eclipse.jface.action.IAction;
import org.eclipse.jface.window.Window;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.IWorkbenchWindowActionDelegate;
import org.eclipse.ui.actions.ActionDelegate;

/**
 * Open commit action
 */
public class OpenCommitAction extends ActionDelegate implements
		IWorkbenchWindowActionDelegate {

	private Shell shell;

	@Override
	public void run(IAction action) {
		CommitSelectionDialog dialog = new CommitSelectionDialog(shell, true);
		if (Window.OK != dialog.open())
			return;
		Object[] results = dialog.getResult();
		if (results == null || results.length == 0)
			return;
		for (Object result : results)
			CommitEditor.openQuiet((RepositoryCommit) result);
	}

	public void init(IWorkbenchWindow window) {
		shell = window.getShell();
	}

}

Add check for null/empty results in commit selection dialog.


package org.jdesktop.beans.editors;

import javax.swing.JFrame;
import javax.swing.SwingUtilities;

/**
 * A demo program to showcase {@link PaintPicker}.
 *
 * @author Karl Schaefer
 */
@SuppressWarnings("all")
public class ImagePickerDemo extends JFrame {
    /**
     * {@inheritDoc}
     */
    @Override
    protected void frameInit() {
        super.frameInit();

        setTitle("ImagePicker Demo");
        setDefaultCloseOperation(EXIT_ON_CLOSE);

        add(new ImagePicker());

        pack();
    }

    /**
     * Demo entry point.
     *
     * @param args
     *            unused
     */
    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                new ImagePickerDemo().setVisible(true);
            }
        });
    }
}

Add a demo for the image picker.


/*
 * Copyright 2015 The Closure Compiler 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 com.google.gson;

/**
 * A minimal supersource API for the real `Gson` class.
 *
 * <p>This class is not intended to really work. Methods are added as needed.
 */
public final class Gson {

  public Gson() {}

  public String toJson(Object x) {
    throw new UnsupportedOperationException();
  }
}

Create basic J2CL supersources for GSON.


/**
 * <License>
 */
package edu.colorado.csdms.wmt.client.ui.widgets;

import com.google.gwt.dom.client.Style.Unit;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.HasHorizontalAlignment;
import com.google.gwt.user.client.ui.HorizontalPanel;

/**
 * Makes a {@link HorizontalPanel} with a centered "Close" button. Reusable!
 *
 * @author Mark Piper (mark.piper@colorado.edu)
 */
public class ClosePanel extends HorizontalPanel {

  private Button button;

  /**
   * Makes a new {@link ClosePanel} with a centered "Close" button.
   */
  public ClosePanel() {

    this.setWidth("100%");
    this.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_CENTER);

    button = new Button("<i class='fa fa-times'></i> Close");
    button.getElement().getStyle().setMarginTop(1, Unit.EM);
    button.getElement().getStyle().setMarginBottom(0.5, Unit.EM);

    this.add(button);
  }

  public Button getButton() {
    return button;
  }

  public void setButton(Button button) {
    this.button = button;
  }
}

Make a reusable panel with a centered "Close" button


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

package com.pyamsoft.pydroid.widget;

import android.content.Context;
import android.support.annotation.CallSuper;
import android.support.v7.widget.AppCompatCheckedTextView;
import android.support.v7.widget.AppCompatTextView;
import android.util.AttributeSet;

/**
 * Attempts to fix TextView memory leak
 *
 * https://github.com/square/leakcanary/issues/180
 */
public class NoLeakCheckedTextView extends AppCompatCheckedTextView {

  public NoLeakCheckedTextView(Context context) {
    super(context);
  }

  public NoLeakCheckedTextView(Context context, AttributeSet attrs) {
    super(context, attrs);
  }

  public NoLeakCheckedTextView(Context context, AttributeSet attrs, int defStyleAttr) {
    super(context, attrs, defStyleAttr);
  }

  @CallSuper @Override protected void onDetachedFromWindow() {
    getViewTreeObserver().removeOnPreDrawListener(this);
    super.onDetachedFromWindow();
  }
}

Add no leak checked textview


package uk.ac.abdn.foodsafety.sensordata;

import java.time.ZonedDateTime;

/**
 *
 * @author nhc
 *
 * Represents one ID'ed and timestamped temperature reading from a meat probe.
 */
public final class MeatProbeReading {
    /** ID from the meat probe */
    public final int id;

    /** Timestamp of the reading */
    public final ZonedDateTime time;

    /** Temperature in Celsius, e.g. 31.3 */
    public final Double temperature;

    /**
     * @param id ID from the meat probe
     * @param time Timestamp of the reading
     * @param temperature e.g. 31.3
     */
    public MeatProbeReading(
            final int id,
            final ZonedDateTime time,
            final Double temperature) {
        this.id = id;
        this.time = time;
        this.temperature = temperature;
    }
}

Add class for representing a single meat probe reading


package uk.ac.ebi.quickgo.annotation;

import java.util.function.Function;

/**
 * A helper class containing a set of utility methods to help generate ids for different fields of the annotation.
 *
 * @author Ricardo Antunes
 */
public class IdGeneratorUtil {
    /**
     * Generates a gene product identifier based on the number provided as an argument
     *
     * @param idNum a number to base the id generation on
     * @return a gene product identifier
     */
    public static String createGPId(int idNum) {
        return String.format("A0A%03d", idNum);
    }

    /**
     * Generate an evidence code based on the number provided as an argument
     *
     * @param idNum a number to base the evidence code generation on
     * @return an evidence code identifier
     */
    public static String createEvidenceCode(int idNum) {
        return String.format("ECO:%07d", idNum);
    }

    /**
     * Generate a GO_REF code based on the number provided as an argument
     *
     * @param idNum a number to base the GO_REF generation on
     * @return an GO_REF identifier
     */
    public static String createGoRef(int idNum) {
        return String.format("GO_REF:%07d", idNum);
    }

    /**
     * Generate a GO term identifier based on the number provided as an argument
     *
     * @param idNum a number to base the Go term identifier generation on
     * @return a GO identifier
     */
    public static String createGoId(int idNum) {
        return String.format("GO:%07d", idNum);
    }

    /**
     * Method that takes in the number of values to generate, and a value generator and returns an array of generated
     * values.
     *
     * @param valueGenerator contains the logic to generate a specific value
     * @param numberOfValues number of values to generate
     * @return an array of generated values
     */
    public static String[] generateValues(Function<Integer, String> valueGenerator, int numberOfValues) {
        String[] values = new String[numberOfValues];

        for (int i = 0; i < numberOfValues; i++) {
            values[i] = valueGenerator.apply(i);
        }

        return values;
    }
}

Create utility class that generates IDs.


package forklift.concurrent;

import static org.mockito.Mockito.any;
import static org.mockito.Mockito.times;

import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mockito;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.Executors;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;

public class BlockingRejectedExecutionHandlerTests {
    private ThreadPoolExecutor pool;
    private BlockingQueue<Runnable> queue;
    private RejectedExecutionHandler handler;

    @Before
    public void setup() {
        this.queue = new ArrayBlockingQueue<>(1);
        this.pool = new ThreadPoolExecutor(1, 1, 10, TimeUnit.MILLISECONDS, this.queue);
        this.handler = Mockito.spy(new BlockingRejectedExecutionHandler());
        this.pool.setRejectedExecutionHandler(handler);
    }

    @After
    public void shutdown() throws Exception {
        pool.shutdownNow();
        pool.awaitTermination(100, TimeUnit.MILLISECONDS);
    }

    @Test
    public void testRejectedExecutionTriggered() {
        final AtomicBoolean blockCondition = new AtomicBoolean(false);
        final AtomicBoolean finishCondition = new AtomicBoolean(false);

        // fill up the queue and executing threads - nothing should be rejected yet
        startBlockedTask(blockCondition, pool);
        startBlockedTask(blockCondition, pool);
        Mockito.verify(handler, times(0)).rejectedExecution(any(), any());

        doAsync(() -> {
            pool.execute(() -> {
                synchronized (finishCondition) {
                    finishCondition.set(true);
                    finishCondition.notifyAll();
                }
            });
        });

        // make sure that the third task on the pool doesn't get executed yet, but the rejected execution handler has started
        synchronized (finishCondition) {
            try {
                finishCondition.wait(100);
            } catch (InterruptedException ignored) {}
        }
        Assert.assertFalse(finishCondition.get());
        Mockito.verify(handler, times(1)).rejectedExecution(any(), any());

        // unblock the queued threads
        synchronized (blockCondition) {
            blockCondition.set(true);
            blockCondition.notifyAll();
        }

        // check that the queued task eventually gets ran
        synchronized (finishCondition) {
            try {
                finishCondition.wait(100);
            } catch (InterruptedException ignored) {}
        }
        Assert.assertTrue(finishCondition.get());
        Mockito.verify(handler, times(1)).rejectedExecution(any(), any());
    }

    private void startBlockedTask(AtomicBoolean condition, ExecutorService executor) {
        executor.submit(() -> {
            while (!condition.get()) {
                synchronized (condition) {
                    try {
                        condition.wait();
                    } catch (InterruptedException ignored) {}
                }
            }
        });
    }

    private void doAsync(Runnable action) {
        final ExecutorService service =  Executors.newSingleThreadExecutor();
        service.execute(action);
        service.shutdown();
    }
}

Test that the blocking execution handler actually blocks


package learntocode.javaapi.io_and_nio.io;

import java.io.ByteArrayInputStream;

public class ByteArrayInputStreamsExample {

    public static void main (String[] args) {

        /*  ------------------------------
            ------------------------------
                Print letters of alphabet from 10th letter to 20th.
            ------------------------------
            ------------------------------
        */
        /* Alphabet */
        String abc = "abcdefghijklmnopqrstuvwzyx";
        byte[] arr = abc.getBytes();

        /* This will contain letters from 10th to 20th (The inputs are: start from here and then include 10 more bytes to input stream */
        ByteArrayInputStream inputStream = new ByteArrayInputStream(arr, 10,10);
        int b;
        while ((b = inputStream.read()) != -1) {
            System.out.print((char) b + " ");
        }
        System.out.println("\n");

        /*  ------------------------------
            ------------------------------
                Mark after 5 bytes, mark, continue reading, than reset to mark and output in upper register
            ------------------------------
            ------------------------------
        */
        inputStream = new ByteArrayInputStream(arr, 10,10);

        int i =0;
        while ((b = inputStream.read()) != -1) {
            ++i;
            System.out.print((char) b + " ");
            if (i == 5) {
                inputStream.mark(i);
            }
        }
        System.out.println();
        inputStream.reset();
        while ((b = inputStream.read()) != -1) {
            System.out.print(Character.toUpperCase((char) b) + " ");
        }
    }
}

Add byte array input stream example


package com.google.sps.servlets;

import com.google.sps.data.VolunteeringOpportunity;
import com.google.sps.utilities.CommonUtils;
import com.google.sps.utilities.DatabaseConstants;
import com.google.sps.utilities.DatabaseWrapper;
import java.io.IOException;
import java.util.Set;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/** Servlet to get all volunteering data for a given event */
@WebServlet("/")
public class EventVolunteeringDataServlet extends HttpServlet {
  private static final String HARDCODED_EVENT_ID = "0883de79-17d7-49a3-a866-dbd5135062a8";
  private static final DatabaseWrapper databaseWrapper =
      new DatabaseWrapper(DatabaseConstants.INSTANCE_ID, DatabaseConstants.DATABASE_ID);

  @Override
  public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
    // TO DO: change eventId to parameter value
    Set<VolunteeringOpportunity> opportunities =
        databaseWrapper.getVolunteeringOpportunitesForEventId(HARDCODED_EVENT_ID);

    response.setContentType("application/json;");
    response.getWriter().println(CommonUtils.convertToJson(opportunities));
  }
}

Add servlet to retrieve opportunities given event id.


package org.matrix.androidsdk.lazyloading;

import android.support.test.InstrumentationRegistry;

import junit.framework.Assert;

import org.junit.BeforeClass;
import org.junit.FixMethodOrder;
import org.junit.Test;
import org.junit.runners.MethodSorters;
import org.matrix.androidsdk.RestClient;
import org.matrix.androidsdk.common.CommonTestHelper;
import org.matrix.androidsdk.common.TestApiCallback;
import org.matrix.androidsdk.rest.model.search.SearchResponse;

import java.util.Collections;
import java.util.concurrent.CountDownLatch;

@FixMethodOrder(MethodSorters.JVM)
public class SearchTest {

    private CommonTestHelper mTestHelper = new CommonTestHelper();
    private LazyLoadingTestHelper mLazyLoadingTestHelper = new LazyLoadingTestHelper(mTestHelper);

    @BeforeClass
    public static void init() {
        RestClient.initUserAgent(InstrumentationRegistry.getContext());
    }

    @Test
    public void Search_CheckMessageSearch_LazyLoadedMembers() throws Exception {
        Search_CheckMessageSearch_(true);
    }

    @Test
    public void Search_CheckMessageSearch_LoadAllMembers() throws Exception {
        Search_CheckMessageSearch_(false);
    }

    private void Search_CheckMessageSearch_(boolean withLazyLoading) throws Exception {
        final LazyLoadingScenarioData data = mLazyLoadingTestHelper.createScenario(withLazyLoading);
        final CountDownLatch lock = new CountDownLatch(1);
        data.aliceSession.pauseEventStream();
        data.aliceSession.resumeEventStream();
        data.aliceSession.getDataHandler().clear();
        data.aliceSession.searchMessageText("Bob message", Collections.singletonList(data.roomId), 0, 0, null, new TestApiCallback<SearchResponse>(lock) {
            @Override
            public void onSuccess(SearchResponse info) {
                Assert.assertEquals(1, info.searchCategories.roomEvents.results.size());
                super.onSuccess(info);
            }
        });
        mTestHelper.await(lock);
    }

}

Test lazyloading : Add search test


package org.osiam.resources.scim;

import com.fasterxml.jackson.databind.annotation.JsonSerialize;

import java.util.Arrays;

@JsonSerialize(include = JsonSerialize.Inclusion.NON_EMPTY)
public class ErrorResponse {
    public static final String ERROR_URN = "urn:ietf:params:scim:api:messages:2.0:Error";
    private String[] schemas = {ERROR_URN};
    private String status;
    private String detail;

    public ErrorResponse(int statusCode, String message) {
        status = Integer.toString(statusCode);
        detail = message;
    }

    public String[] getSchemas() {
        return Arrays.copyOf(schemas, schemas.length);
    }

    public String getStatus() {
        return status;
    }

    public String getDetail() {
        return detail;
    }
}

Move error response to scim schema


/* This file is part of SableCC ( http://sablecc.org ).
 *
 * See the NOTICE file distributed with this work for copyright information.
 *
 * 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.sablecc.sablecc.exception;

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

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

public class InvalidArgumentRuntimeExceptionTest {

    InvalidArgumentRuntimeException exception;

    String message;

    Throwable cause;

    @Before
    public void setUp() {

        this.message = "valid message";
        this.cause = new Throwable();
    }

    @Test
    public void testInvalidArgumentRuntimeExceptionString() {

        // Case with null message
        String nullMessage = null;
        try {
            this.exception = new InvalidArgumentRuntimeException(nullMessage);
            fail("message may not be null");
        }
        catch (InternalException e) {
            // Expected
        }

        // Typical case
        this.exception = new InvalidArgumentRuntimeException(this.message);
        assertEquals("Invalid exception message", this.message, this.exception
                .getMessage());
    }

    @Test
    public void testInvalidArgumentRuntimeExceptionStringThrowable() {

        // Case with null message
        String nullMessage = null;

        try {
            this.exception = new InvalidArgumentRuntimeException(nullMessage,
                    this.cause);
            fail("message may not be null");
        }
        catch (InternalException e) {
            // Expected
        }

        // Case with null cause
        Throwable nullCause = null;
        try {
            this.exception = new InvalidArgumentRuntimeException(this.message,
                    nullCause);
            fail("a cause may not be null");
        }
        catch (InternalException e) {
            // Expected
        }

        // Typical case
        this.exception = new InvalidArgumentRuntimeException(this.message,
                this.cause);
        assertEquals("Invalid exception message", this.message, this.exception
                .getMessage());
        assertEquals("Invalid exception cause", this.cause, this.exception
                .getCause());
    }

}

Add JUnit tests. See ticket:63.


package eu.stratuslab.marketplace.server.resources;

import java.util.logging.Level;

import org.openrdf.query.QueryLanguage;
import org.restlet.data.Form;
import org.restlet.data.MediaType;
import org.restlet.representation.Representation;
import org.restlet.representation.StringRepresentation;
import org.restlet.resource.Get;

/**
 * This resource represents a query on the rdf data
 */
public class QueryResource extends BaseResource {

	/**
     * Returns a listing of all endorsers.
     */
	@Get("xml")
	public Representation toXml() {
		Form queryForm = getRequest().getResourceRef().getQueryAsForm();
		String queryString = queryForm.getFirstValue("query");
		String queryLanguage = queryForm.getFirstValue("language", "sparql");

		logger.log(Level.INFO, queryString);

		// Generate the right representation according to its media type.
		String results = "";
		if(queryLanguage.equals("sparql")){
		    results = query(queryString, QueryLanguage.SPARQL);
		} else if (queryLanguage.equals("serql")){
			results = query(queryString, QueryLanguage.SERQL);
		}

		StringRepresentation representation = new StringRepresentation(results,
				MediaType.APPLICATION_XML);

		// Returns the XML representation of this document.
		return representation;
     }

}

Add some more html output and a Query resource


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

package org.spine3.server.storage.datastore;

import com.google.common.util.concurrent.MoreExecutors;
import org.spine3.server.event.EventStore;
import org.spine3.server.event.EventStoreShould;

/**
 * @author Dmytro Dashenkov
 */
public class DsBasedEventStoreShould extends EventStoreShould {

    @Override
    protected EventStore creteStore() {
        return EventStore.newBuilder()
                         .setStreamExecutor(MoreExecutors.directExecutor())
                         .setStorageFactory(TestDatastoreStorageFactory.getDefaultInstance())
                         .withDefaultLogger()
                         .build();
    }
}

Add tests for the EventStore based on GAE Storage.


package org.robolectric.shadows;

import static android.os.Build.VERSION_CODES.O;

import android.graphics.Typeface;
import android.provider.FontRequest;
import android.provider.FontsContract;
import org.robolectric.annotation.Implementation;
import org.robolectric.annotation.Implements;

@Implements(value = FontsContract.class, minSdk = O)
public class ShadowFontsContract {

  /** Returns a stub typeface immediately. */
  @Implementation
  public static Typeface getFontSync(FontRequest request) {
    return Typeface.create(request.getQuery(), Typeface.NORMAL);
  }
}

Fix timeout in FontsContract.getFontSync() caused because Context.canLoadUnsafeResources() now returns false since the context isn't a system context.


package org.springframework.roo.support.util;

import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.logging.Level;
import java.util.logging.Logger;

import org.springframework.roo.support.logging.HandlerUtils;

/**
 * Retrieves text files from the classloader and displays them on-screen.
 *
 *

 * Respects normal Roo conventions such as all resources should appear under the same
 * package as the bundle itself etc.
 *
 * @author Ben Alex
 * @since 1.1.1
 *
 */
public abstract class MessageDisplayUtils {
	public static Logger logger = HandlerUtils.getLogger(MessageDisplayUtils.class);

	/**
	 * Displays the requested file via the logger API.
	 *
	 *

	 * Each file must available from the classloader of the "owner". It must also be in the same
	 * package as the class of the "owner". So if the owner is com.foo.Bar, and the file is called
	 * "hello.txt", the file must appear in the same bundle as com.foo.Bar and be available from
	 * the resource path "/com/foo/Hello.txt".
	 *
	 * @param fileName the simple filename (required)
	 * @param owner the class which owns the file (required)
	 * @param important if true, it will display with a higher importance color where possible
	 */
	public static void displayFile(String fileName, Class<?> owner, boolean important) {
		Level level = Level.FINE;
		if (important) {
			level = Level.SEVERE;
		}
		String owningPackage = owner.getPackage().getName().replace('.', '/');
		String fullResourceName = "/" + owningPackage + "/" + fileName;
		InputStream stream = owner.getClassLoader().getResourceAsStream(fullResourceName);
		if (stream == null) {
			throw new IllegalStateException("Could not locate '" + fileName + "'");
		}
		try {
			String message = FileCopyUtils.copyToString(new InputStreamReader(stream));
			logger.log(level, message);
		} catch (Exception e) {
			throw new IllegalStateException(e);
		}
	}

	/**
	 * Same as {@link #displayFile(String, Class, boolean)} except it passes false as the
	 * final argument.
	 *
	 * @param fileName the simple filename (required)
	 * @param owner the class which owns the file (required)
	 */
	public static void displayFile(String fileName, Class<?> owner) {
		displayFile(fileName, owner, false);
	}
}

Create utility class for displaying text files to console


package jp.ac.utokyo.rcast.karkinos.readssummary;

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

import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;

import java.util.stream.Stream;

public class IntervalTest {
  private static boolean isSameInterval(final Interval a, final Interval b) {
    return a.getChr().equals(b.getChr())
      && a.getStart() == b.getStart()
      && a.getEnd() == b.getEnd()
      && a.getDepth() == b.getDepth()
      && a.getRefseqid().equals(b.getRefseqid())
      && a.getGeneSymbol().equals(b.getGeneSymbol());
  }

  @Test
  void extendIntervalTest() {
    final Interval iv = new Interval("chr1", 2, 4, "NR_037415", "MIR3620");
    iv.depth = 0;

    //      12345
    // iv    ===
    // pos  .
    //  =>   ===  doesn't extend
    assertFalse(iv.extendInterval("chr1", 1, 0));

    //      12345
    // iv    ===
    // pos     .
    //  =>   ===  doesn't extend
    assertFalse(iv.extendInterval("chr1", 4, 0));

    //      12345
    // iv    ===
    // pos      .
    //  =>   ====  extend
    assertTrue(iv.extendInterval("chr1", 5, 0));
    final Interval expected = new Interval("chr1", 2, 5, "NR_037415", "MIR3620");
    expected.depth = 0;
    assertTrue(isSameInterval(expected, iv));
  }

  private static Stream<Arguments> containArgs() {
    return Stream.of(
        Arguments.of(false, "chr1", 1),
        Arguments.of(true, "chr1", 2),
        Arguments.of(true, "chr1", 4),
        Arguments.of(false, "chr1", 5),
        Arguments.of(false, "chr2", 2));
  }

  @ParameterizedTest
  @MethodSource("containArgs")
  void containTest(final boolean expected, final String chr, final int pos) {
    final Interval iv = new Interval("chr1", 2, 4, "NR_037415", "MIR3620");
    assertEquals(expected, iv.contain(chr, pos));
  }
}

Add test codes to test readssummary/Interval


package com.kiselev.dataframework.example.main;

import com.kiselev.dataframework.core.loader.impl.ConfigLoader;
import com.kiselev.dataframework.core.loader.impl.DataSourceLoader;
import com.kiselev.dataframework.core.resource.api.ResourceManager;
import com.kiselev.dataframework.core.resource.impl.ConfigManager;
import com.kiselev.dataframework.core.resource.impl.ConnectionManager;
import com.kiselev.dataframework.example.entity.EntityExample;
import com.kiselev.dataframework.example.handler.QueryExecutorExample;
import com.kiselev.dataframework.example.handler.QueryUpdaterExample;

import java.util.List;

/**
 * @author Vadim Kiselev
 * @version 1.0
 * @since 02/05/2017
 */

public class Main {

    public static void main(String[] args) {

        ////////////////////////////////////////////////////////////
        ///Framework initialization/////////////////////////////////
        ResourceManager configManager = new ConfigManager();
        ResourceManager connectionManager = new ConnectionManager();

        ConfigLoader configLoader = new ConfigLoader();
        configLoader.setConfigManager(configManager);
        configLoader.load();

        DataSourceLoader dataSourceLoader = new DataSourceLoader();
        dataSourceLoader.setConfigManager(configManager);
        dataSourceLoader.setConnectionManager(connectionManager);
        dataSourceLoader.load();
        ////////////////////////////////////////////////////////////

        QueryExecutorExample executor = new QueryExecutorExample();
        executor.setConnectionManager(connectionManager);

        List<EntityExample> result = executor
                .executeQuery("SELECT * FROM test WHERE id < 8");

        for (EntityExample entity : result) {
            System.out.println("Table's row : " + entity.getId() + " " + entity.getName());
        }

        QueryUpdaterExample updater = new QueryUpdaterExample();
        updater.setConnectionManager(connectionManager);

        Integer affectedRows = updater
                .executeQuery("INSERT INTO test VALUES(8, 'Vadim')");
        System.out.println("Affected rows : " + affectedRows);
    }
}

Add first version of framework's execution


package com.github.sarxos.webcam.util.jh;

import java.awt.image.BufferedImage;

import org.assertj.core.api.Assertions;
import org.junit.Test;

public class JHBlurFilterTest {

	@Test
	public void test_filterNonPremultiplied() {

		final JHBlurFilter filter = new JHBlurFilter();
		filter.setPremultiplyAlpha(false);

		final BufferedImage bi1 = new BufferedImage(10, 10, BufferedImage.TYPE_INT_ARGB);
		final BufferedImage bi2 = filter.filter(bi1, null);

		Assertions
			.assertThat(bi1.getWidth())
			.isEqualTo(bi2.getWidth());
		Assertions
			.assertThat(bi1.getHeight())
			.isEqualTo(bi2.getHeight());
		Assertions
			.assertThat(bi1.getType())
			.isEqualTo(bi2.getType());
	}

	@Test
	public void test_filterPremultiplied() {

		final JHBlurFilter filter = new JHBlurFilter();
		filter.setPremultiplyAlpha(true);

		final BufferedImage bi1 = new BufferedImage(10, 10, BufferedImage.TYPE_INT_ARGB);
		final BufferedImage bi2 = filter.filter(bi1, null);

		Assertions
			.assertThat(bi1.getWidth())
			.isEqualTo(bi2.getWidth());
		Assertions
			.assertThat(bi1.getHeight())
			.isEqualTo(bi2.getHeight());
		Assertions
			.assertThat(bi1.getType())
			.isEqualTo(bi2.getType());
	}

	@Test
	public void test_setGetPremultiplyAlpha() {

		final JHBlurFilter filter = new JHBlurFilter();

		filter.setPremultiplyAlpha(true);
		Assertions
			.assertThat(filter.getPremultiplyAlpha())
			.isTrue();

		filter.setPremultiplyAlpha(false);
		Assertions
			.assertThat(filter.getPremultiplyAlpha())
			.isFalse();
	}
}

Add unit test for JHBlurFilter


/*******************************************************************************
 * Copyright 2015 Alexander Casall, Manuel Mauky
 *
 * 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 de.saxsys.mvvmfx.utils.validation;

import nl.jqno.equalsverifier.EqualsVerifier;
import nl.jqno.equalsverifier.Warning;
import org.junit.Test;

public class ValidationMessageTest {

	/**
	 * Verify that the {@link ValidationMessage} class implements the
	 * {@link Object#equals(Object)} and {@link Object#hashCode()} methods
	 * correctly.
	 */
	@Test
	public void testEqualsAndHashcode() {

		EqualsVerifier.forClass(ValidationMessage.class)
				.suppress(Warning.STRICT_INHERITANCE) // others can create subclasses but it's their task to properly override equals and hashcode
				.suppress(Warning.NULL_FIELDS) // class is immutable and checks arguments for non-null in the constructor
				.verify();

	}

}

Add Test for equals and hashcode method of ValidationMessage class


package com.github.blindpirate.gogradle.core.exceptions;

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

public class BuildException extends RuntimeException {
    private BuildException(Throwable e) {
        super(e);
    }

    private BuildException(String msg, Throwable e) {
        super(msg, e);
    }

    public static BuildException cannotCreateSymbolicLink(Path path, IOException e) {
        return new BuildException("Create symbolic link at " + path.toString()
                + " failed, does your system support it?", e);
    }
}

Add exception class for build process


package com.insightfullogic.java8.examples.chapter5;

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

import static org.junit.Assert.*;

public class StringCombinerTest {
    private StringCombiner combiner;

    @Before
    public void before() {
        this.combiner = new StringCombiner(", ", "[", "]");

        combiner.add("A").add("B").add("C").add("D");
    }

    @Test
    public void add() throws Exception {
        assertEquals("[A, B, C, D]", combiner.toString());
    }

    @Test
    public void mergeWithOther() throws Exception {
        StringCombiner other = new StringCombiner(", ", "[", "]");

        other.add("E").add("F").add("G");

        this.combiner.merge(other);

        assertEquals("[A, B, C, D, E, F, G]", this.combiner.toString());
    }

    @Test
    public void mergeWithEmpty() {
        this.combiner.merge(new StringCombiner(", ", "[", "]"));

        assertEquals("[A, B, C, D]", this.combiner.toString());
    }

    @Test
    public void mergeSelf() throws Exception {
        assertEquals("[A, B, C, D]", this.combiner.merge(this.combiner).toString());
    }

    @Test
    public void twiceCallToString() throws Exception {
        assertEquals("[A, B, C, D]", this.combiner.toString());
        assertEquals("[A, B, C, D]", this.combiner.toString());
    }
}

Add test case for StringCombiner


package org.stepic.droid.web;

import com.google.gson.annotations.SerializedName;

import org.stepic.droid.model.Meta;
import org.stepic.droid.model.SearchResult;

import java.util.List;

public class SearchResultResponse extends StepicResponseBase {

    @SerializedName("search-results")
    List<SearchResult> searchResultList;

    public SearchResultResponse(Meta meta, List<SearchResult> searchResultList) {
        super(meta);
        this.searchResultList = searchResultList;
    }

    public List<SearchResult> getSearchResultList() {
        return searchResultList;
    }
}

Add web response with search results


package org.apache.velocity.test.util.introspection;

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

import junit.framework.Test;
import junit.framework.TestSuite;

import org.apache.velocity.test.BaseTestCase;
import org.apache.velocity.util.introspection.ClassMap;

/**
 * Test the ClassMap Lookup
 */
public class ClassMapTestCase
        extends BaseTestCase
{
    public ClassMapTestCase(final String name)
    	throws Exception
    {
        super(name);
    }

    public static Test suite()
    {
        return new TestSuite(ClassMapTestCase.class);
    }

    public void setUp()
            throws Exception
    {
    }

    public void tearDown()
    {
    }

    public void testPrimitives()
    	throws Exception
    {
        ClassMap c = new ClassMap(TestClassMap.class);
        assertNotNull(c.findMethod("setBoolean",   new Object[] { Boolean.TRUE }));
        assertNotNull(c.findMethod("setByte",      new Object[] { new Byte((byte) 4)}));
        assertNotNull(c.findMethod("setCharacter", new Object[] { new Character('c')}));
        assertNotNull(c.findMethod("setDouble",    new Object[] { new Double(8.0) }));
        assertNotNull(c.findMethod("setFloat",     new Object[] { new Float(15.0) }));
        assertNotNull(c.findMethod("setInteger",   new Object[] { new Integer(16) }));
        assertNotNull(c.findMethod("setLong",      new Object[] { new Long(23) }));
        assertNotNull(c.findMethod("setShort",     new Object[] { new Short((short)42)}));
    }

    public static final class TestClassMap
    {
        public void setBoolean(boolean b)
        {
        }

        public void setByte(byte b)
        {
        }

        public void setCharacter(char c)
        {
        }

        public void setDouble(double d)
        {
        }

        public void setFloat(float f)
        {
        }

        public void setInteger(int i)
        {
        }

        public void setLong(long l)
        {
        }

        public void setShort(short s)
        {
        }
    }
}

Add some class map tests.


package net.kencochrane.raven.event.interfaces;

import java.io.PrintStream;
import java.io.PrintWriter;
import java.util.Arrays;

/**
 * Wrapper for {@code Throwable} to make it immutable.
 */
public class ImmutableThrowable extends Throwable {
    private final Throwable actualThrowable;

    /**
     * Creates an immutable wrapper for the given throwable.
     *
     * @param actualThrowable exception wrapped.
     */
    public ImmutableThrowable(Throwable actualThrowable) {
        this.actualThrowable = actualThrowable;
    }

    @Override
    public String getMessage() {
        return actualThrowable.getMessage();
    }

    @Override
    public String getLocalizedMessage() {
        return actualThrowable.getLocalizedMessage();
    }

    @Override
    public Throwable getCause() {
        return actualThrowable.getCause();
    }

    @Override
    public Throwable initCause(Throwable cause) {
        throw new UnsupportedOperationException();
    }

    @Override
    public String toString() {
        return actualThrowable.toString();
    }

    @Override
    public void printStackTrace() {
        throw new UnsupportedOperationException();
    }

    @Override
    public void printStackTrace(PrintStream s) {
        throw new UnsupportedOperationException();
    }

    @Override
    public void printStackTrace(PrintWriter s) {
        throw new UnsupportedOperationException();
    }

    @Override
    public Throwable fillInStackTrace() {
        throw new UnsupportedOperationException();
    }

    @Override
    public StackTraceElement[] getStackTrace() {
        StackTraceElement[] stackTrace = actualThrowable.getStackTrace();
        return Arrays.copyOf(stackTrace, stackTrace.length);
    }

    @Override
    public void setStackTrace(StackTraceElement[] stackTrace) {
        throw new UnsupportedOperationException();
    }
}

Add a class to make Throwable immutable


package info.u_team.u_team_core.util;

import java.io.*;
import java.nio.file.*;
import java.util.function.Function;

import com.google.gson.Gson;
import com.google.gson.stream.JsonWriter;

public class ConfigUtil {

	public static <T> T loadConfig(Path directory, String name, Gson gson, Function<JsonWriter, T> write, Function<BufferedReader, T> read) throws IOException {
		final Path path = directory.resolve(name + ".json");
		if (Files.exists(path) && Files.isReadable(path) && Files.isReadable(path)) {
			try (BufferedReader reader = Files.newBufferedReader(path)) {
				return read.apply(reader);
			}
		} else {
			Files.deleteIfExists(path);
			Files.createDirectories(directory);
			Files.createFile(path);
			try (BufferedWriter bufferedWriter = Files.newBufferedWriter(path); JsonWriter writer = GsonUtil.createTabWriter(gson, bufferedWriter)) {
				return write.apply(writer);
			}
		}
	}
}

Add config util to load json files and create default ones


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

import com.datastax.driver.osgi.api.MailboxException;
import org.ops4j.pax.exam.Configuration;
import org.ops4j.pax.exam.Option;
import org.ops4j.pax.exam.options.MavenArtifactProvisionOption;
import org.ops4j.pax.exam.testng.listener.PaxExam;
import org.testng.SkipException;
import org.testng.annotations.Listeners;
import org.testng.annotations.Test;

import static com.datastax.driver.osgi.BundleOptions.*;
import static org.ops4j.pax.exam.CoreOptions.options;

@Listeners({CCMBridgeListener.class, PaxExam.class})
public class MailboxServiceGuava21IT extends MailboxServiceTests {

    @Configuration
    public Option[] guava21Config() {
        MavenArtifactProvisionOption guavaBundle = guavaBundle();
        String javaVersion = System.getProperty("java.version");
        // Only bring in 21.0 if java version >= 1.8.  If this is not done the framework
        // will fail to load for < 1.8 and we plan on skipping the test anyways.
        if (javaVersion.compareTo("1.8") >= 0) {
            guavaBundle = guavaBundle.version("21.0");
        }

        return options(
                defaultOptions(),
                nettyBundles(),
                guavaBundle,
                driverBundle(),
                extrasBundle(),
                mappingBundle(),
                mailboxBundle()
        );
    }

    /**
     * Exercises a 'mailbox' service provided by an OSGi bundle that depends on the driver with
     * Guava 21 explicitly enforced.
     *
     * @test_category packaging
     * @expected_result Can create, retrieve and delete data using the mailbox service.
     * @jira_ticket JAVA-620
     * @since 2.0.10, 2.1.5
     */
    @Test(groups = "short")
    public void test_guava_21() throws MailboxException {
        String javaVersion = System.getProperty("java.version");
        if (javaVersion.compareTo("1.8") < 0) {
            throw new SkipException("Guava 21 requires Java 1.8");
        }
        checkService();
    }
}

Add OSGi test for Guava 21 support


package org.parallelj.launching.internal;

import org.parallelj.Programs;

public class DefaultLauncher {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		System.out.println("********************");
		for (String string : args) {
			System.out.println(string);

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

		String className = args[0];
		try {
			Class<?> programClass = Class.forName(className);
			Object programInstance = programClass.newInstance();

			Programs.as(programInstance).execute().join();

		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (InstantiationException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		}

	}
}

Add this simple internal launcher ot be able to launch ParallelJ Program from Eclipse.


package net.kencochrane.raven.getsentry;

import net.kencochrane.raven.DefaultRavenFactory;
import net.kencochrane.raven.connection.Connection;
import net.kencochrane.raven.dsn.Dsn;
import net.kencochrane.raven.getsentry.connection.GetSentryHttpsConnection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Raven factory capable of handling 'getsentry' scheme, using the HTTPS connection to GetSentry.com.
 */
public class GetSentryRavenFactory extends DefaultRavenFactory {
    private static final Logger logger = LoggerFactory.getLogger(GetSentryRavenFactory.class);

    @Override
    protected Connection createConnection(Dsn dsn) {
        String protocol = dsn.getProtocol();
        Connection connection;

        if (protocol.equalsIgnoreCase("getsentry")) {
            logger.info("Using an HTTP connection to Sentry.");
            connection = createHttpConnection(dsn);

            // Enable async unless its value is 'false'.
            if (!Boolean.FALSE.toString().equalsIgnoreCase(dsn.getOptions().get(ASYNC_OPTION))) {
                connection = createAsyncConnection(dsn, connection);
            }
        } else {
            connection = super.createConnection(dsn);
        }

        return connection;
    }

    /**
     * Creates an HTTPS connection to the GetSentry server.
     *
     * @param dsn Data Source Name of the Sentry server.
     * @return a {@link GetSentryHttpsConnection} to the server.
     */
    protected Connection createHttpConnection(Dsn dsn) {
        GetSentryHttpsConnection httpConnection = new GetSentryHttpsConnection(dsn.getProjectId(), dsn.getPublicKey(),
                dsn.getSecretKey());
        httpConnection.setMarshaller(createMarshaller(dsn));

        // Set the HTTP timeout
        if (dsn.getOptions().containsKey(TIMEOUT_OPTION))
            httpConnection.setTimeout(Integer.parseInt(dsn.getOptions().get(TIMEOUT_OPTION)));
        return httpConnection;
    }
}

Add RavenFactory capable of creating connections to getSentry


package com.maddenabbott.jenny.command.help;

import com.maddenabbott.jenny.cli.Summary;
import com.maddenabbott.jenny.command.Command;
@Summary("Pass the name of a command for help with that command.")
public class CommandHelpCommand implements Command {
  @Override
  public void run() {
  }
  }

Add skeleton for command help command.


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

import junit.framework.TestCase;
import junit.framework.Test;
import junit.framework.TestSuite;

import org.apache.commons.beanutils.TestBean;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * Test Case for {@link LocaleBeanUtils}.
 *
 * @version $Revision$ $Date$
 */
public class LocaleBeanUtilsTestCase extends TestCase {

    private static Log log = LogFactory.getLog(LocaleBeanUtilsTestCase.class);

    /**
     * Construct a new instance of this test case.
     *
     * @param name Name of the test case
     */
    public LocaleBeanUtilsTestCase(String name) {
        super(name);
    }

    // -------------------------------------------------- Overall Test Methods

    /**
     * Set up instance variables required by this test case.
     */
    public void setUp() {
    }

    /**
     * Return the tests included in this test suite.
     * @return Test Suite
     */
    public static Test suite() {
        return (new TestSuite(LocaleBeanUtilsTestCase.class));
    }

    /**
     * Tear down instance variables required by this test case.
     */
    public void tearDown() {
    }

    // ------------------------------------------------ Individual Test Methods

    /**
     * Test setting a nested simple property
     */
    public void testSetNestedPropertySimple() {
        TestBean bean = new TestBean();
        bean.getNested().setIntProperty(5);
        assertEquals("Initial value 5", 5, bean.getNested().getIntProperty());
        try {
            LocaleBeanUtils.setProperty(bean, "nested.intProperty", "123", null);
        } catch (Throwable t) {
            log.error(t);
            fail("Threw " + t);
        }
        assertEquals("Check Set Value", 123, bean.getNested().getIntProperty());
    }

    /**
     * Test setting a nested indexed property
     */
    public void testSetNestedPropertyIndexed() {
        TestBean bean = new TestBean();
        bean.getNested().setIntIndexed(1, 51);
        assertEquals("Initial value[1] 51", 51, bean.getNested().getIntIndexed(1));
        try {
            LocaleBeanUtils.setProperty(bean, "nested.intIndexed[1]", "123", null);
        } catch (Throwable t) {
            log.error(t);
            fail("Threw " + t);
        }
        assertEquals("Check Set Value", 123, bean.getNested().getIntIndexed(1));
    }
}

Add test for BEANUTILS-140 - LocaleBeanUtils setProperty does not work on nested property - reposted by Marco La Porta


package com.battlelancer.seriesguide.loaders;

import android.content.Context;
import android.support.v4.content.AsyncTaskLoader;

import java.util.List;

/**
 * A generic {@link AsyncTaskLoader} loading any {@link List} of things. It
 * takes care of delivering and reseting results, so you only have to implement
 * loadInBackground().
 */
public abstract class GenericListLoader<T> extends AsyncTaskLoader<List<T>> {

    protected List<T> mItems;

    public GenericListLoader(Context context) {
        super(context);
    }

    /**
     * Called when there is new data to deliver to the client. The super class
     * will take care of delivering it; the implementation here just adds a
     * little more logic.
     */
    @Override
    public void deliverResult(List<T> items) {
        if (isReset()) {
            // An async query came in while the loader is stopped. We
            // don't need the result.
            if (items != null) {
                onReleaseResources(items);
            }
        }
        List<T> oldItems = items;
        mItems = items;

        if (isStarted()) {
            // If the Loader is currently started, we can immediately
            // deliver its results.
            super.deliverResult(items);
        }

        if (oldItems != null) {
            onReleaseResources(oldItems);
        }
    }

    @Override
    protected void onStartLoading() {
        if (mItems != null) {
            deliverResult(mItems);
        } else {
            forceLoad();
        }
    }

    /**
     * Handles a request to stop the Loader.
     */
    @Override
    protected void onStopLoading() {
        // Attempt to cancel the current load task if possible.
        cancelLoad();
    }

    /**
     * Handles a request to cancel a load.
     */
    @Override
    public void onCanceled(List<T> items) {
        super.onCanceled(items);

        onReleaseResources(items);
    }

    /**
     * Handles a request to completely reset the Loader.
     */
    @Override
    protected void onReset() {
        super.onReset();

        // Ensure the loader is stopped
        onStopLoading();

        // At this point we can release resources
        if (mItems != null) {
            onReleaseResources(mItems);
            mItems = null;
        }
    }

    /**
     * Helper function to take care of releasing resources associated with an
     * actively loaded data set.
     */
    protected void onReleaseResources(List<T> apps) {
        // For a simple List<> there is nothing to do. For something
        // like a Cursor, we would close it here.
    }

}

Introduce a generic list loader.


/*******************************************************************************
 * Copyright (c) 2005-2008 VecTrace (Zingo Andersen) and others.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 * Bastian Doetsch	implementation
 *******************************************************************************/
package com.vectrace.MercurialEclipse.synchronize;

import org.eclipse.core.resources.IStorage;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.team.core.TeamException;
import org.eclipse.team.core.variants.IResourceVariant;

import com.vectrace.MercurialEclipse.team.IStorageMercurialRevision;

public class MercurialResourceVariant implements IResourceVariant {
	private IStorageMercurialRevision rev;

	public MercurialResourceVariant(IStorageMercurialRevision rev) {
		this.rev = rev;
	}

	public byte[] asBytes() {
		return getContentIdentifier().getBytes();
	}

	public String getContentIdentifier() {
		return rev.getGlobal();
	}

	public String getName() {
		return rev.getName();
	}

	public IStorage getStorage(IProgressMonitor monitor) throws TeamException {
		return rev;
	}

	public boolean isContainer() {
		return false;
	}

    /**
     * @return the rev
     */
    public IStorageMercurialRevision getRev() {
        return rev;
    }

}

/*******************************************************************************
 * Copyright (c) 2005-2008 VecTrace (Zingo Andersen) and others.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 * Bastian Doetsch	implementation
 *******************************************************************************/
package com.vectrace.MercurialEclipse.synchronize;

import org.eclipse.core.resources.IStorage;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.team.core.TeamException;
import org.eclipse.team.core.variants.IResourceVariant;

import com.vectrace.MercurialEclipse.team.IStorageMercurialRevision;

public class MercurialResourceVariant implements IResourceVariant {
    private final IStorageMercurialRevision rev;

    public MercurialResourceVariant(IStorageMercurialRevision rev) {
        this.rev = rev;
    }

    public byte[] asBytes() {
        return getContentIdentifier().getBytes();
    }

    public String getContentIdentifier() {
        return rev.getGlobal();
    }

    public String getName() {
        return rev.getResource().getName();
    }

    public IStorage getStorage(IProgressMonitor monitor) throws TeamException {
        return rev;
    }

    public boolean isContainer() {
        return false;
    }

    /**
     * @return the rev
     */
    public IStorageMercurialRevision getRev() {
        return rev;
    }

}

Enable right content types (based on file types) in compare editor opened from Synchronization view


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

/**
 * Can you write a method to print a hello world without use a semicolon?.
 *
 * @author Pedro Vicente Gómez Sánchez.
 */
public class HelloWorldWithoutSemicolon {

}

Add statement to problem 77


import static com.google.appengine.api.datastore.FetchOptions.Builder.withLimit;
import static org.junit.Assert.assertEquals;
import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.EntityNotFoundException;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.appengine.api.datastore.Query;
import com.google.appengine.tools.development.testing.LocalDatastoreServiceTestConfig;
import com.google.appengine.tools.development.testing.LocalServiceTestHelper;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

public class DataServletTests {

  // Maximum eventual consistency.
  private final LocalServiceTestHelper helper =
      new LocalServiceTestHelper(new LocalDatastoreServiceTestConfig()
          .setDefaultHighRepJobPolicyUnappliedJobPercentage(100));

    @Before
    public void setUp() {
        helper.setUp();
    }

    @After
    public void tearDown() {
        helper.tearDown();
    }

    @Test
    public void EntitiesArePutInDatastore(){
        DatastoreService ds = DatastoreServiceFactory.getDatastoreService();
        Entity dummy = new Entity("Dummy");
        ds.put(dummy);
        assertEquals(1, ds.prepare(new Query("Dummy")).countEntities(withLimit(10)));
  }

    @Test
    public void EntitiesCanHaveParentsUsingKeys(){
        DatastoreService ds = DatastoreServiceFactory.getDatastoreService();
        Entity dummyParent = new Entity("DummyParent");
        ds.put(dummyParent);
        Key dummyParentKey = dummyParent.getKey();
        Entity dummy = new Entity("Dummy", dummyParentKey);
        ds.put(dummy);
        Key queriedDummyParentKey = dummy.getParent();
        Entity queriedDummyParent;
        try {
            queriedDummyParent = ds.get(queriedDummyParentKey);
        } catch(EntityNotFoundException e){
            fail("Entity not found in Database")
        }
        assertEquals(true, queriedDummyParent == dummyParent);
    }

    @Test
    public void EntityPropertiesArePutInDatastore(){
        DatastoreService ds = DatastoreServiceFactory.getDatastoreService();
        dummyString = "Bananas";
        Entity dummy = new Entity("Dummy");
        dummy.setProperty("Fruit", dummyString);
        ds.put(dummy);
        Key dummyKey = dummy.getKey();
        Entity queriedDummy;
        try {
            queriedDummy = ds.get(dummyKey);
        } catch(EntityNotFoundException e){
            fail("Entity not found in Database")
        }
        assertEquals(true, queriedDummy.getProperty("Fruit").toString().equals(dummyString));
    }
}

Add basic unit tests for datastore


package org.realityforge.replicant.client.transport;

import javax.annotation.Nonnull;
import javax.annotation.Nullable;

final class AreaOfInterestAction<T extends Enum>
{
  enum Action
  {
    ADD, REMOVE, UPDATE
  }

  @Nonnull
  private final T _graph;
  @Nonnull
  private final Action _action;
  @Nullable
  private final String _cacheKey;
  @Nullable
  private final Object _id;
  @Nullable
  private final Object _filterParameter;
  @Nullable
  private final Runnable _userAction;
  private boolean _inProgress;

  AreaOfInterestAction( @Nonnull final T graph,
                        @Nonnull final Action action,
                        @Nullable final String cacheKey,
                        @Nullable final Object id,
                        @Nullable final Object filterParameter,
                        @Nullable final Runnable userAction )
  {
    _graph = graph;
    _action = action;
    _cacheKey = cacheKey;
    _id = id;
    _filterParameter = filterParameter;
    _userAction = userAction;
  }

  @Nonnull
  T getGraph()
  {
    return _graph;
  }

  @Nonnull
  Action getAction()
  {
    return _action;
  }

  @Nullable
  String getCacheKey()
  {
    return _cacheKey;
  }

  @Nullable
  Object getId()
  {
    return _id;
  }

  @Nullable
  Object getFilterParameter()
  {
    return _filterParameter;
  }

  @Nullable
  Runnable getUserAction()
  {
    return _userAction;
  }

  boolean isInProgress()
  {
    return _inProgress;
  }

  void markAsInProgress()
  {
    _inProgress = true;
  }

  void markAsComplete()
  {
    _inProgress = false;
  }

  @Override
  public String toString()
  {
    return "AOI[" +
           "Graph=" + _graph +
           ",id=" + _id +
           ",CacheKey=" + _cacheKey +
           ",filter=" + _filterParameter +
           "]" + ( _inProgress ? "(InProgress)" : "" );
  }
}

Add a simple class to contian information pertaining to subscription actions


/*
 * Copyright (c) 2009 Kathryn Huxtable and Kenneth Orr.
 *
 * This file is part of the SeaGlass Pluggable Look and Feel.
 *
 * 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.
 *
 * $Id$
 */
package com.seaglasslookandfeel.state;

import java.awt.Component;
import java.awt.Container;

import javax.swing.JComponent;
import javax.swing.JToolBar;

/**
 * Is the control in a toolbar?
 */
public class ControlInToolBarState extends State {
    public ControlInToolBarState() {
        super("InToolBar");
    }

    public boolean isInState(JComponent c) {
        for (Component comp = (Component) c; comp != null; comp = ((Container) comp).getParent()) {
            if (comp instanceof JToolBar) {
                return true;
            } else if (!(comp instanceof Container)) {
                break;
            }
        }
        return false;
    }
}

Check in state to determine if a control is in a toolbar.


package gjb.experimental;

import com.qualcomm.robotcore.eventloop.opmode.Autonomous;
import com.qualcomm.robotcore.eventloop.opmode.LinearOpMode;

import gjb.interfaces.RuntimeSupportInterface;
import gjb.utils.AndroidRuntimeSupport;

/**
 * New version of auton code - with most of the logic moved to helper class
 * AutonWizard
  */

@Autonomous(name="AOpMode_DepotMoveTestTensorFlow", group="Pushbot")
//@Disabled
public class AOpMode_MoveTestTensorFlow extends LinearOpMode {

    /* Declare OpMode members. */

    private final RuntimeSupportInterface rt = new AndroidRuntimeSupport(this);

    AutonRoverRuckusWizard apu = null;

    @Override
    public void runOpMode() {
        double timeoutS;

        apu = new AutonRoverRuckusWizard(rt) ;
        apu.init();

        // Wait for the game to start (driver presses PLAY)
        waitForStart();
        //TODO: apu.tensorVuforiaInit();

        // Work the wand, detect jewel color and move forward/backward to dislodge
        // the jewel - this is code specific to the BLUE alliance
        apu.firstPath();
    }

}

Update the obsolete Vison sub system to initialize tensor flow.


package net.explorviz.landscape.repository.persistence;

import net.explorviz.landscape.model.application.AggregatedClazzCommunication;
import net.explorviz.landscape.model.application.Application;
import net.explorviz.landscape.model.application.ApplicationCommunication;
import net.explorviz.landscape.model.application.Clazz;
import net.explorviz.landscape.model.application.ClazzCommunication;
import net.explorviz.landscape.model.application.Component;
import net.explorviz.landscape.model.application.DatabaseQuery;
import net.explorviz.landscape.model.application.TraceStep;
import net.explorviz.landscape.model.helper.EProgrammingLanguage;
import net.explorviz.landscape.model.landscape.Landscape;
import net.explorviz.landscape.model.landscape.Node;
import net.explorviz.landscape.model.landscape.NodeGroup;
import net.explorviz.landscape.model.landscape.System;
import org.nustaq.serialization.FSTConfiguration;

/**
 * Helper class for FST.
 *
 *
 */
public class FstHelper {

  /**
   * Creates a new {@link FSTConfiguration} and registers all available model classes.
   *
   * @return the configuration.
   */
  public static FSTConfiguration createFstConfiguration() {
    final FSTConfiguration result = FSTConfiguration.createDefaultConfiguration();
    result.registerClass(Landscape.class);
    result.registerClass(System.class);
    result.registerClass(NodeGroup.class);
    result.registerClass(Node.class);
    result.registerClass(Application.class);
    result.registerClass(ApplicationCommunication.class);
    result.registerClass(AggregatedClazzCommunication.class);
    result.registerClass(DatabaseQuery.class);
    result.registerClass(EProgrammingLanguage.class);
    result.registerClass(Component.class);
    result.registerClass(Clazz.class);
    result.registerClass(ClazzCommunication.class);
    result.registerClass(TraceStep.class);

    return result;
  }

  /**
   * Converts a landscape object to bytes.
   *
   * @param landscape the landscape object
   *
   * @return the given landscape as byte array
   */
  public static byte[] convertLandscapeToBytes(final Landscape landscape,
      final FSTConfiguration conf) {
    // TODO: Move to "ExportHelper"
    return conf.asByteArray(landscape);
  }

}

Create helper class for basic FST operations


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

import java.io.IOException;
import java.io.OutputStream;

/**
 * Define how to dispatch an object.
 *
 * @author Tony Wardell
 * Date: 27/09/2017
 * Time: 14:19
 * Created with IntelliJ IDEA.
 */
public interface DispatchWriter {

    void write(Object object, OutputStream out) throws IOException;
}

Define how to dispatch an object.


/**
 * This Source Code Form is subject to the terms of the Mozilla Public License,
 * v. 2.0. If a copy of the MPL was not distributed with this file, You can
 * obtain one at http://mozilla.org/MPL/2.0/. OpenMRS is also distributed under
 * the terms of the Healthcare Disclaimer located at http://openmrs.org/license.
 *
 * Copyright (C) OpenMRS Inc. OpenMRS is a registered trademark and the OpenMRS
 * graphic logo is a trademark of OpenMRS Inc.
 */
package org.openmrs.customdatatype.datatype;

import org.apache.commons.lang.StringUtils;
import org.openmrs.Provider;
import org.openmrs.api.context.Context;

/**
 * This is a class for custom datatypes for providers
 *
 * @since 2.0
 */
public class ProviderDatatype extends BaseMetadataDatatype<Provider> {

	/**
	 * @see org.openmrs.customdatatype.SerializingCustomDatatype#deserialize(String)
	 * @override
	 */
	public Provider deserialize(String uuid) {
		if (StringUtils.isBlank(uuid)) {
			return null;
		}
		return Context.getProviderService().getProviderByUuid(uuid);
	}
}

Create a custom data type and its associated handler for providers - TRUNK-3623


package es.litesolutions.sonar.grappa;

import com.sonar.sslr.api.Grammar;
import com.sonar.sslr.impl.Parser;
import org.sonar.colorizer.Tokenizer;
import org.sonar.sslr.toolkit.AbstractConfigurationModel;
import org.sonar.sslr.toolkit.ConfigurationProperty;

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

public final class SampleToolkit
{
    private SampleToolkit()
    {
        throw new Error("nice try!");
    }

    public static void main(final String... args)
    {
        /*
         * Initialize your language parser and your rule
         */

        /*
        final MyParser parser
            = Parboiled.createParser(MyParser.class);
        final Rule rule = parser.someRule();
        final Channel<Lexer> channel = new GrappaChannel(rule);
        */

        /*
         * Initialize the lexer; only one channel!
         */

        /*
        final Lexer lexer = Lexer.builder()
            .withFailIfNoChannelToConsumeOneCharacter(true)
            .withChannel(channel)
            .build();
        */

        /*
         * Initialize your rules; here we take the example of a grammar which
         * has no root rule, but which we inject into a builder.
         *
         * Match the GrammarRuleKey with the grappa parser rule.
         */

        /*
        final LexerfulGrammarBuilder builder = LexerfulGrammarBuilder.create();
        MyGrammar.injectInto(builder);
        builder.setRootRule(MyGrammar.MY_RULE_KEY);
        */

        /*
         * Finally, create the Grammar object, the Parser object, initialize
         * the toolkit and run it
         */

        /*
        final Grammar grammar = builder.build();

        final Parser<Grammar> grammarParser = Parser.builder(grammar)
            .withLexer(lexer).build();

        final Toolkit toolkit = new Toolkit("test",
            new DummyConfigurationModel(grammarParser));

        toolkit.run();
        */
    }

    private static final class DummyConfigurationModel
        extends AbstractConfigurationModel
    {
        private final Parser<Grammar> parser;

        private DummyConfigurationModel(final Parser<Grammar> parser)
        {
            this.parser = parser;
        }

        @Override
        public Parser doGetParser()
        {
            return parser;
        }

        @Override
        public List<Tokenizer> doGetTokenizers()
        {
            return Collections.emptyList();
        }

        @Override
        public List<ConfigurationProperty> getProperties()
        {
            return Collections.emptyList();
        }
    }
}

Add a sample ToolKit file


package com.github.aureliano.edocs.app.gui.menu;

import javax.swing.JMenuItem;

public class FindDocumentMenuItem extends JMenuItem {

	private static final long serialVersionUID = -2048071523465789664L;

	public FindDocumentMenuItem() {
		super.setText("Find document...");
	}
}

Create find document menu item.


package org.xdi.service.cdi.event;

import javax.enterprise.util.AnnotationLiteral;
import javax.inject.Qualifier;
import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;

import static java.lang.annotation.ElementType.*;
import static java.lang.annotation.RetentionPolicy.RUNTIME;

/**
 * @author Yuriy Movchan Date: 04/13/2017
 */
@Qualifier
@Retention(RUNTIME)
@Target({ METHOD, FIELD, PARAMETER, TYPE })
@Documented
public @interface ApplicationInitialized {

    public static final class Literal extends AnnotationLiteral<ApplicationInitialized> implements ApplicationInitialized {

        private static final long serialVersionUID = 4891987789146132930L;

        public static final Literal INSTANCE = new Literal();
    }

}

Add event to notify plugins about finish application initialization


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

package org.onosproject.vtnrsc.virtualport;

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

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

import com.google.common.testing.EqualsTester;

/**
 * Unit tests for SecurityGroup class.
 */
public class SecurityGroupTest {

    final SecurityGroup securityGroup1 = SecurityGroup.securityGroup("1");
    final SecurityGroup sameAssecurityGroup = SecurityGroup.securityGroup("1");
    final SecurityGroup securityGroup2 = SecurityGroup.securityGroup("2");

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

    /**
     * Checks the operation of equals().
     */
    @Test
    public void testEquals() {
        new EqualsTester().addEqualityGroup(securityGroup1, sameAssecurityGroup)
                .addEqualityGroup(securityGroup2).testEquals();
    }

    /**
     * Checks the construction of a SecurityGroup object.
     */
    @Test
    public void testConstruction() {
        final String securityGroupValue = "1";
        final SecurityGroup securityGroup = SecurityGroup.securityGroup(securityGroupValue);
        assertThat(securityGroup, is(notNullValue()));
        assertThat(securityGroup.securityGroup(), is(securityGroupValue));

    }
}

Add the junit test code of SecurityGroup


package de.unistuttgart.iste.rss.bugminer.api;

import de.unistuttgart.iste.rss.bugminer.api.exceptions.NotFoundException;
import de.unistuttgart.iste.rss.bugminer.model.entities.Bug;
import de.unistuttgart.iste.rss.bugminer.model.entities.IssueTracker;
import de.unistuttgart.iste.rss.bugminer.model.entities.LineChange;
import de.unistuttgart.iste.rss.bugminer.model.entities.Project;
import de.unistuttgart.iste.rss.bugminer.model.repositories.BugRepository;
import de.unistuttgart.iste.rss.bugminer.model.repositories.IssueTrackerRepository;
import de.unistuttgart.iste.rss.bugminer.model.repositories.LineChangeRepository;
import de.unistuttgart.iste.rss.bugminer.model.repositories.ProjectRepository;
import de.unistuttgart.iste.rss.bugminer.tasks.Task;
import de.unistuttgart.iste.rss.bugminer.tasks.TaskManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.support.PagedListHolder;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.Collection;

@RestController
@RequestMapping(value = "/api")
public class TaskController {

    public static final int BUG_LIST_PAGE_SIZE = 10;

	@Autowired
	private TaskManager taskManager;

	protected TaskController() {
		// managed bean
	}

	/**
	 * Returns all tasks of any state
	 */
	@RequestMapping(value = "/tasks", method = RequestMethod.GET)
	public Collection<Task> tasks() {
		return taskManager.getTasks();
	}
}

Add REST API for listing tasks


package org.monospark.spongematchers.type;

import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import static org.monospark.spongematchers.testutil.HamcrestSpongeMatchers.matches;

import java.util.Map;

import org.junit.Test;
import org.monospark.spongematchers.matcher.SpongeMatcher;
import org.monospark.spongematchers.parser.SpongeMatcherParseException;
import org.monospark.spongematchers.parser.element.StringElement;
import org.monospark.spongematchers.parser.element.StringElementParser;
import org.spongepowered.api.block.BlockState;
import org.spongepowered.api.block.BlockType;
import org.spongepowered.api.block.trait.BlockTrait;
import org.spongepowered.api.data.DataContainer;
import org.spongepowered.api.data.DataQuery;
import org.spongepowered.api.data.MemoryDataContainer;

import com.google.common.collect.Maps;

public class BlockStateTypeTest {

    @Test
    public void canMatch_NonBlockStateObject_ReturnsFalse() throws SpongeMatcherParseException {
        Object o = 5;

        boolean canMatch = MatcherType.BLOCK_STATE.canMatch(o);

        assertThat(canMatch, is(false));
    }

    @Test
    public void canMatch_BlockStateObject_ReturnsTrue() throws Exception {
        Object o = mock(BlockState.class);

        boolean canMatch = MatcherType.BLOCK_STATE.canMatch(o);

        assertThat(canMatch, is(true));
    }

    @SuppressWarnings({"unchecked", "rawtypes"})
    @Test
    public void parseMatcher_ValidMapElement_ReturnsCorrectSpongeMatcher() throws SpongeMatcherParseException {
        StringElement element = StringElementParser.parseStringElement("{'type':{'id':'minecraft:appl.'},"
                + "'traits':{'trait1':1,'trait2':false},'data':{'boolean':true,'integer':>0}}");

        SpongeMatcher<BlockState> matcher = MatcherType.BLOCK_STATE.parseMatcher(element);

        BlockType type = mock(BlockType.class);
        when(type.getId()).thenReturn("minecraft:apple");
        BlockState state = mock(BlockState.class);
        when(state.getType()).thenReturn(type);
        BlockTrait<Integer> trait1 = mock(BlockTrait.class);
        when(trait1.getId()).thenReturn("trait1");
        when(trait1.getValueClass()).thenReturn(Integer.class);
        BlockTrait<Boolean> trait2 = mock(BlockTrait.class);
        when(trait2.getId()).thenReturn("trait2");
        when(trait2.getValueClass()).thenReturn(Boolean.class);
        Map traits = Maps.newHashMap();
        traits.put(trait1, 1);
        traits.put(trait2, false);
        when(state.getTraitMap()).thenReturn(traits);
        DataContainer container = new MemoryDataContainer();
        container.set(DataQuery.of("UnsafeData","boolean"), true);
        container.set(DataQuery.of("UnsafeData","integer"), 1);
        when(state.toContainer()).thenReturn(container);
        assertThat(matcher, matches(state));
    }
}

Add tests for parsing BlockState matchers


package study.hard.javalib.nativelib;

public class CloserTest {

	public static void main(String[] args) {
        int counter = 0;
//        counter++; // compile error!
        Thread thread1 = new Thread(new Runnable() {
            @Override
            public void run() {
//                counter++; // compile error!
                System.out.println(counter);
            }
        });
        Thread thread2 = new Thread(new Runnable() {
            @Override
            public void run() {
//                counter++; // compile error!
                System.out.println(counter);
            }
        });
        thread1.start();
        thread2.start();
	}

}

Add a test case for Closer in Java8.


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

public class DefaultStatusReceiver implements StatusReceiver {
    @Override
    public void updateMessageWorkerStatus(int messageWorkerId, MessageWorkerStatus messageWorkerStatus) {
    }
}

Add default implementation for status receiver


package me.christine.housewifesolution;

import android.test.ActivityInstrumentationTestCase2;
import android.test.TouchUtils;
import android.test.ViewAsserts;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.ImageButton;
import android.widget.EditText;
import android.widget.ListView;

/**
 * Created by christine on 15-5-18.
 */
public class MainActivityTest extends ActivityInstrumentationTestCase2<MainActivity>{
    private MainActivity mainActivity;
    private ImageButton imageButton;
    private EditText editText;
    private ListView listView;

    public MainActivityTest() {
        super(MainActivity.class);
    }

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

        setActivityInitialTouchMode(true);

        mainActivity = getActivity();
        imageButton = (ImageButton) mainActivity.findViewById(R.id.add_shopping_cart);
        editText = (EditText) mainActivity.findViewById(R.id.add_shopping_items);
        listView = (ListView) mainActivity.findViewById(R.id.shopping_list);
    }

    public void testPreconditions() {
        assertNotNull("MainActivity is null", mainActivity);
        assertNotNull("ImageButton is null", imageButton);
        assertNotNull("EditText is null", editText);
        assertNotNull("ListView is null", listView);
    }

    //Verify that button is displayed correctly.
    public void testImageButton_layout() {
        final View decorView = mainActivity.getWindow().getDecorView();
        ViewAsserts.assertOnScreen(decorView, imageButton);
        final ViewGroup.LayoutParams layoutParams = imageButton.getLayoutParams();
        assertNotNull(layoutParams);
        assertEquals(layoutParams.width, WindowManager.LayoutParams.WRAP_CONTENT);
        assertEquals(layoutParams.height, WindowManager.LayoutParams.WRAP_CONTENT);
    }
}

Build simple test cases to test the app and UI components.


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

import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import io.trino.plugin.jdbc.BaseAutomaticJoinPushdownTest;
import io.trino.testing.MaterializedRow;
import io.trino.testing.QueryRunner;
import org.jdbi.v3.core.Handle;
import org.jdbi.v3.core.Jdbi;
import org.testng.SkipException;

import static io.trino.plugin.mysql.MySqlQueryRunner.createMySqlQueryRunner;
import static java.lang.String.format;

public class TestMySqlAutomaticJoinPushdown
        extends BaseAutomaticJoinPushdownTest
{
    private TestingMySqlServer mySqlServer;

    @Override
    protected QueryRunner createQueryRunner()
            throws Exception
    {
        // Using MySQL 8.0.15 because test is sensitive to quality of NDV estimation and 5.5.46 we use
        // in other places does very poor job; for 10000 row table with 1000 distinct keys it estimates NDV at ~2500
        mySqlServer = closeAfterClass(new TestingMySqlServer("mysql:8.0.15", false));

        return createMySqlQueryRunner(
                mySqlServer,
                ImmutableMap.of(),
                ImmutableMap.<String, String>builder()
                        .put("metadata.cache-ttl", "0m")
                        .put("metadata.cache-missing", "false")
                        .buildOrThrow(),
                ImmutableList.of());
    }

    @Override
    public void testJoinPushdownWithEmptyStatsInitially()
    {
        throw new SkipException("MySQL statistics are automatically collected");
    }

    @Override
    protected void gatherStats(String tableName)
    {
        for (MaterializedRow row : computeActual("SHOW COLUMNS FROM " + tableName)) {
            String columnName = (String) row.getField(0);
            String columnType = (String) row.getField(1);
            if (columnType.startsWith("varchar")) {
                // varchar index require length
                continue;
            }
            onRemoteDatabase(format("CREATE INDEX \"%2$s\" ON %1$s (\"%2$s\")", tableName, columnName).replace("\"", "`"));
        }
        onRemoteDatabase("ANALYZE TABLE " + tableName.replace("\"", "`"));
    }

    protected void onRemoteDatabase(String sql)
    {
        try (Handle handle = Jdbi.open(() -> mySqlServer.createConnection())) {
            handle.execute("USE tpch");
            handle.execute(sql);
        }
    }
}

Add MySQL automatic Join pushdown test