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

import uk.ac.ebi.quickgo.annotation.AnnotationREST;
import uk.ac.ebi.quickgo.rest.metadata.MetaDataConfigProperties;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.FileSystemResource;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.ResultActions;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;

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

/**
 * Test the failure to load the metadata information.
 *
 * @author Tony Wardell
 * Date: 09/03/2017
 * Time: 13:53
 * Created with IntelliJ IDEA.
 */
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = {AnnotationREST.class})
@WebAppConfiguration
public class AnnotationControllerMetaDataSourceFailIT {
    private static final String RESOURCE_URL = "/annotation";
    private MockMvc mockMvc;

    @Autowired
    private WebApplicationContext webApplicationContext;

    @Before
    public void setup() {
        mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();

    }

    // ------------------------------- Check about information -------------------------------

    @Test
    public void about() throws Exception {
        ResultActions response = mockMvc.perform(get(RESOURCE_URL + "/about"));

        response.andDo(print())
                .andExpect(status().isInternalServerError());
    }

    /**
     * Configure properties used by co-term generation, using test values.
     */
    @Configuration
    public static class TestConfig {
        @Primary
        @Bean
        public MetaDataConfigProperties primaryMetaDataConfigProperties() {
            MetaDataConfigProperties properties = new MetaDataConfigProperties();
            FileSystemResource fileSystemResource = new FileSystemResource("/does/not/exist");
            properties.setSource(fileSystemResource);
            return properties;
        }
    }

}

Test the failure to load the source of metadata information for annotations.


/* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*-
 *
 * The contents of this file are subject to the Netscape Public
 * License Version 1.1 (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.mozilla.org/NPL/
 *
 * Software distributed under the License is distributed on an "AS
 * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
 * implied. See the License for the specific language governing
 * rights and limitations under the License.
 *
 * The Original Code is Rhino code, released
 * May 6, 1998.
 *
 * The Initial Developer of the Original Code is Netscape
 * Communications Corporation.  Portions created by Netscape are
 * Copyright (C) 1997-1999 Netscape Communications Corporation. All
 * Rights Reserved.
 *
 * Contributor(s):
 * Norris Boyd
 *
 * Alternatively, the contents of this file may be used under the
 * terms of the GNU Public License (the "GPL"), in which case the
 * provisions of the GPL are applicable instead of those above.
 * If you wish to allow use of your version of this file only
 * under the terms of the GPL and not to allow others to use your
 * version of this file under the NPL, indicate your decision by
 * deleting the provisions above and replace them with the notice
 * and other provisions required by the GPL.  If you do not delete
 * the provisions above, a recipient may use your version of this
 * file under either the NPL or the GPL.
 */

import org.mozilla.javascript.*;

/**
 * An example WrapFactory that can be used to avoid wrapping of Java types
 * that can be converted to ECMA primitive values.
 * So java.lang.String is mapped to ECMA string, all java.lang.Numbers are
 * mapped to ECMA numbers, and java.lang.Booleans are mapped to ECMA booleans
 * instead of being wrapped as objects. Additionally java.lang.Characters are
 * converted to ECMA strings. Other types have the default behavior.
 *

 * Note that calling "new java.lang.String('foo')" in JavaScript with this
 * wrap factory enabled will still produce a wrapped Java object since the
 * WrapFactory.wrapNewObject method is not overridden.
 *

 * The PrimitiveWrapFactory is enabled on a Context by calling setWrapFactory
 * on that context.
 */
public class PrimitiveWrapFactory extends WrapFactory {

  public Object wrap(Context cx, Scriptable scope, Object obj,
                     Class staticType)
  {
    if (obj instanceof String || obj instanceof Number ||
        obj instanceof Boolean)
    {
      return obj;
    } else if (obj instanceof Character) {
      char[] a = { ((Character)obj).charValue() };
      return new String(a);
    }
    return super.wrap(cx, scope, obj, staticType);
  }
}

Add example of the use of a WrapFactory.


/**
 * 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.
 *
 * Copyright 2012-2014 the original author or authors.
 */
package org.assertj.db.api.assertions;

import org.assertj.core.api.Assertions;
import org.assertj.db.api.ChangesAssert;
import org.assertj.db.common.AbstractTest;
import org.assertj.db.common.NeedReload;
import org.assertj.db.type.Changes;
import org.assertj.db.type.Request;
import org.assertj.db.type.Table;
import org.junit.Test;

import static org.assertj.db.api.Assertions.assertThat;
import static org.junit.Assert.fail;

/**
 * Tests on {@link org.assertj.db.api.assertions.AssertOnNumberOfChanges} class :
 * {@link org.assertj.db.api.assertions.AssertOnNumberOfChanges#hasNumberOfChanges(int)} method.
 *
 * @author Régis Pouiller
 *
 */
public class AssertOnNumberOfChanges_HasNumberOfChanges_Test extends AbstractTest {

  /**
   * This method tests the {@code hasNumberOfChanges} assertion method.
   */
  @Test
  @NeedReload
  public void test_has_number_of_changes() throws Exception {
    Table table = new Table(source, "actor");
    Changes changes = new Changes(table).setStartPointNow();
    updateChangesForTests();
    changes.setEndPointNow();

    ChangesAssert changesAssert = assertThat(changes);
    ChangesAssert changesAssert2 = changesAssert.hasNumberOfChanges(3);
    Assertions.assertThat(changesAssert).isSameAs(changesAssert2);
  }

  /**
   * This method should fail because the number of changes is different.
   */
  @Test
  @NeedReload
  public void should_fail_because_number_of_changes_is_different() throws Exception {
    Request request = new Request(source, "select * from actor");
    Changes changes = new Changes(request).setStartPointNow();
    updateChangesForTests();
    changes.setEndPointNow();

    try {
      assertThat(changes).hasNumberOfChanges(9);
      fail("An exception must be raised");
    } catch (AssertionError e) {
      Assertions.assertThat(e.getMessage()).isEqualTo("[Changes on 'select * from actor' request of 'sa/jdbc:h2:mem:test' source] \n"
                                                      + "Expecting size (number of changes) to be equal to :\n"
                                                      + "   <9>\n"
                                                      + "but was:\n"
                                                      + "   <4>");
    }
  }
}

Add tests on AssertOnNumberOfChanges assertion method


package com.yahoo.config.model.api.container;

import org.junit.Test;

import static com.yahoo.config.model.api.container.ContainerServiceType.CLUSTERCONTROLLER_CONTAINER;
import static com.yahoo.config.model.api.container.ContainerServiceType.CONTAINER;
import static com.yahoo.config.model.api.container.ContainerServiceType.LOGSERVER_CONTAINER;
import static com.yahoo.config.model.api.container.ContainerServiceType.METRICS_PROXY_CONTAINER;
import static com.yahoo.config.model.api.container.ContainerServiceType.QRSERVER;
import static org.junit.Assert.assertEquals;

/**
 * @author gjoranv
 */
public class ContainerServiceTypeTest {

    @Test
    public void new_values_are_not_added_without_updating_tests() {
        assertEquals(5, ContainerServiceType.values().length);
    }

    @Test
    public void service_names_do_not_change() {
        assertEquals("container", CONTAINER.serviceName);
        assertEquals("qrserver", QRSERVER.serviceName);
        assertEquals("container-clustercontroller", CLUSTERCONTROLLER_CONTAINER.serviceName);
        assertEquals("logserver-container", LOGSERVER_CONTAINER.serviceName);
        assertEquals("metrics-proxy-container", METRICS_PROXY_CONTAINER.serviceName);
    }

}

Add unit test to ensure names don't change.


package org.realityforge.replicant.client.gwt;

import com.google.gwt.user.client.rpc.AsyncCallback;
import java.util.Objects;
import javax.annotation.Nonnull;

public final class ReplicantGwtRpcAsyncCallback<T>
  implements AsyncCallback<T>
{
  @Nonnull
  private final replicant.Request _r;
  @Nonnull
  private final AsyncCallback<T> _callback;

  public ReplicantGwtRpcAsyncCallback( @Nonnull final replicant.Request r, @Nonnull final AsyncCallback<T> callback )
  {
    _r = Objects.requireNonNull( r );
    _callback = Objects.requireNonNull( callback );
  }

  @Override
  public void onSuccess( final T result )
  {
    _r.onSuccess( false, () -> _callback.onSuccess( result ) );
  }

  @Override
  public void onFailure( final Throwable caught )
  {
    _r.onFailure( () -> _callback.onFailure( caught ) );
  }
}

Add an adapter for gwt-rpc calls


package de.fu_berlin.cdv.chasingpictures.api;

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;

import java.util.List;

/**
 * @author Simon Kalt
 */
@JsonIgnoreProperties(value = {"data"}, ignoreUnknown = true)
public class PictureApiResult extends ApiResult<List<Picture>> {
    public List<Picture> getPictures() {
        return getData();
    }

    public void setPictures(List<Picture> pictures) {
        setData(pictures);
    }
}

Add API result object for picture requests


package org.svetovid.util;

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

public class CompoundList<E> extends AbstractList<E> {

    private List<List<E>> lists = new ArrayList<>();

    public CompoundList() {
    }

    @SafeVarargs
    public CompoundList(List<E>... lists) {
        for (List<E> list : lists) {
            this.lists.add(list);
        }
    }

    public List<E> getSublist(int index) {
        return lists.get(index);
    }

    public void setSublist(int index, List<E> list) {
        lists.set(index, list);
    }

    public int addSublist(List<E> list) {
        lists.add(list);
        return lists.size() - 1;
    }

    public int insertSublist(int index, List<E> list) {
        lists.add(index, list);
        return index;
    }

    public List<E> removeSublist(int index) {
        return lists.remove(index);
    }

    @Override
    public int size() {
        int size = 0;
        for (List<E> list : lists) {
            if (list == null) {
                continue;
            }
            size = size + list.size();
        }
        return size;
    }

    @Override
    public E get(int index) {
        if (index < 0) {
            throw new IndexOutOfBoundsException("Index: " + index);
        }
        int totalSize = 0;
        for (List<E> list : lists) {
            if (list == null) {
                continue;
            }
            int size = list.size();
            if (index < size) {
                return list.get(index);
            }
            index = index - size;
            totalSize = totalSize + size;
        }
        throw new IndexOutOfBoundsException("Index: " + index + ", Size: " + totalSize);
    }

    @Override
    public Object[] toArray() {
        Object[][] arrays = new Object[lists.size()][];
        int size = 0;
        for (int i = 0; i < lists.size(); i++) {
            List<E> list = lists.get(i);
            if (list == null) {
                continue;
            }
            arrays[i] = list.toArray();
            size = size + arrays[i].length;
        }
        Object[] array = new Object[size];
        int index = 0;
        for (Object[] arr : arrays) {
            System.arraycopy(arr, 0, array, index, arr.length);
            index = index + arr.length;
        }
        return array;
    }

    @SuppressWarnings("unchecked")
    @Override
    public <T> T[] toArray(T[] a) {
        Object[] array = toArray();
        if (a.length < array.length) {
            return (T[]) array;
        }
        System.arraycopy(array, 0, a, 0, array.length);
        return a;
    }
}

Add a list implementation that is a live view of concatenation of multiple lists


package com.codenvy.ide.ext.datasource.client.properties;

import com.google.gwt.i18n.client.Constants;

public interface DataEntityPropertiesConstants extends Constants {

    @DefaultStringValue("Product name")
    String productNameLabel();

    @DefaultStringValue("Product version")
    String productVersionLabel();

    @DefaultStringValue("User name")
    String usernameLabel();

    @DefaultStringValue("Primary key")
    String primaryKeyLabel();

    @DefaultStringValue("Table type")
    String tableTypeLabel();

    @DefaultStringValue("Data type")
    String dataTypeLabel();

    @DefaultStringValue("Column size")
    String columnSizeLabel();

    @DefaultStringValue("Decimal digits")
    String decimalDigitsLabel();

    @DefaultStringValue("Nullable")
    String nullableLabel();

    @DefaultStringValue("Default value")
    String defaultValueLabel();

    @DefaultStringValue("None")
    String noValue();
}

Add a constant class for database entity properties


/*-
 * Copyright 2017 Diamond Light Source Ltd.
 *
 * 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
 */

package org.eclipse.dawnsci.analysis.dataset;

import java.lang.ref.SoftReference;
import java.util.IdentityHashMap;
import java.util.Map;

import org.eclipse.dawnsci.analysis.dataset.impl.function.DatasetToDatasetFunction;
import org.eclipse.january.dataset.Dataset;
import org.eclipse.january.dataset.DatasetUtils;
import org.eclipse.january.dataset.IDataset;

/**
 * Cache of computed dataset values
 */
public class DatasetCache {

	private DatasetToDatasetFunction function;
	private Map<IDataset, SoftReference<Dataset>> map;

	/**
	 * Create a cache for given function
	 * @param function
	 */
	public DatasetCache(DatasetToDatasetFunction function) {
		this.function = function;
		map = new IdentityHashMap<IDataset, SoftReference<Dataset>>();
	}

	/**
	 * Retrieve computed value (evaluate if not cached)
	 * @param input
	 * @return computed value
	 */
	public Dataset get(IDataset input) {
		SoftReference<Dataset> ref = map.get(input);
		Dataset output;
		if (ref == null || ref.get() == null) {
			output = DatasetUtils.convertToDataset(function.value(input).get(0));
			map.put(input, new SoftReference<Dataset>(output));
		} else {
			output = ref.get();
		}
		return output;
	}

	/**
	 * Remove entry from cache
	 * @param input
	 * @return true if was cached
	 */
	public boolean remove(Dataset input) {
		SoftReference<Dataset> ref = map.remove(input);
		if (ref == null || ref.get() == null) {
			return false;
		}
		ref.clear();
		return true;
	}

	/**
	 * Clear cache
	 */
	public void clear() {
		map.clear();
	}
}

Add new cache to store computed datasets


package benchmarking;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.reflect.Field;
import java.util.Date;

public class CpuMonitor {
    private boolean continueMonitoring = true;
    private StringBuilder commandOutput;
    private Date date;

    public void startMonitoring(){
        boolean firstAppearance = true;

        Thread cpuMonit = new Thread(new Runnable() {
            @Override
            public void run() {
                String line;
                Process process;
                commandOutput = new StringBuilder();

                String processPid = getPid();
                String[] cmd = {
                        "/bin/sh",
                        "-c",
                        " atop 1 -a | unbuffer -p awk '/" + processPid + "|nmap/ {print $1 \" \" $11}'"
                };

                try {
                    process = Runtime.getRuntime().exec(cmd);
                    Field pid = process.getClass().getDeclaredField("pid");
                    pid.setAccessible(true);
                    BufferedReader br = new BufferedReader(new InputStreamReader(process.getInputStream()));

                    while ( continueMonitoring && (line = br.readLine()) != null) {
                        if (firstAppearance  && line.contains(processPid)) {
                            date = new Date();
                        }
                        commandOutput.append(line + "\n");
                    }
                    process.destroy();
                } catch (IOException e) {
                    System.err.println(e.getStackTrace());
                } catch (NoSuchFieldException e) {
                    e.printStackTrace();
                }

                //System.out.println("Command output: " + commandOutput.toString());
            }
        });
        cpuMonit.start();
    }

    public String parseForPid(long pid) {
        stopMonitoring();
        String cmdOut = commandOutput.toString();
        StringBuilder parsedResultsAfterPid = new StringBuilder();

        String[] outputLines = cmdOut.split(System.getProperty("line.separator"));
        for (String line : outputLines) {
            String[] processData = line.split(" ");
            try {
                long resultsPid = Long.parseLong(processData[0]);
                String cpuUsage = processData[1];
                if (resultsPid == pid) {
                    parsedResultsAfterPid.append(resultsPid + "," + cpuUsage + "\n");
                }
            } catch (NumberFormatException e) {
                e.printStackTrace();
            }
        }

        return parsedResultsAfterPid.toString();
    }

    private static String getPid() {
        String processName = java.lang.management.ManagementFactory.getRuntimeMXBean().getName();
        return processName.split("@")[0];
    }

    public void stopMonitoring() {
        continueMonitoring = false;
    }
}

Add monitoring class for CPU usage.


// Use continue with a label.
class ContToLabel {
	public static void main(String args[]) {

outerloop:
		for(int i=1; i < 10; i++) {
			System.out.print("\nOuter loop pass " + i + ", Inner loop: ");

			for(int j = 1; j < 10; j++) {
				if(j == 5) continue outerloop; // continue outer loop
				System.out.print(j);
			}
		}
	}
}

Use continue with a label


// Copyright 2009 Google 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.google.enterprise.connector.util.diffing;

import com.google.enterprise.connector.spi.TraversalSchedule;
import com.google.enterprise.connector.util.diffing.ChangeQueue;
import com.google.enterprise.connector.util.diffing.ChangeQueue.DefaultCrawlActivityLogger;

import java.sql.Timestamp;
import java.util.ArrayList;
import junit.framework.TestCase;

/**
 * Tests for {@link DocumentSnapshotRepositoryMonitorManagerImpl}.
 */
public class DocumentSnapshotRepositoryMonitorManagerImplTest extends TestCase {

  // Borrowed from filesystem connector's  MockTraversalSchedule.java
  public class MockTraversalSchedule implements TraversalSchedule {
    private final int load;
    private final int retryDelay;
    private final boolean isDisabled;
    private final boolean inInterval;

    public MockTraversalSchedule() {
      this(500, -1, false, true);
    }

    public MockTraversalSchedule(int load, int retryDelay, boolean isDisabled,
                                 boolean inInterval) {
      this.load = load;
      this.retryDelay = retryDelay;
      this.isDisabled = isDisabled;
      this.inInterval = inInterval;
    }

    /** Returns the target traversal rate in documents per minute. */
    /* @Override */
    public int getTraversalRate() {
      return load;
    }

    /** Returns the number of seconds to delay after finding no new content. */
    /* @Override */
    public int getRetryDelay() {
      return retryDelay;
    }

    /** Returns {@code true} if the traversal schedule is disabled. */
    /* @Override */
    public boolean isDisabled() {
      return isDisabled;
    }

    /**
     * Returns {@code true} if the current time is within a scheduled travesal
     * interval.
     */
    /* @Override */
    public boolean inScheduledInterval() {
      return inInterval;
    }

    /* @Override */
    public int nextScheduledInterval() {
      return -1;
    }

    /**
     * Returns {@code true} if traversals could run at this time,
     * equivalent to <pre>!isDisabled() && inScheduledInterval()</pre>.
     */
    /* @Override */
    public boolean shouldRun() {
      return !isDisabled() && inScheduledInterval();
    }
  }

  public void testSetTraversalSchedule() {
    ChangeQueue queue;
    queue = new ChangeQueue(10, 0L, null);

    DocumentSnapshotRepositoryMonitorManagerImpl manager =
        new DocumentSnapshotRepositoryMonitorManagerImpl(
            new ArrayList<SnapshotRepository<? extends DocumentSnapshot>>(), null, null, null,
            queue, null);

    assertEquals(0, queue.getSleepInterval());
    manager.setTraversalSchedule(new MockTraversalSchedule(500, 8074, false, false));
    assertEquals(8074000, queue.getSleepInterval());
  }
}

Add a new test for DocumentSnapshotRepositoryMonitorManagerImpl


package com.github.rnowling.bps.datagenerator.datareaders;

import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;

import java.util.List;

import org.junit.Test;

import com.github.rnowling.bps.datagenerator.Constants;
import com.github.rnowling.bps.datagenerator.datamodels.inputs.ZipcodeRecord;

public class TestZipcodeReader
{

	@Test
	public void testRead() throws Exception
	{
		ZipcodeReader reader = new ZipcodeReader();
		reader.setCoordinatesFile(Constants.COORDINATES_FILE);
		reader.setIncomesFile(Constants.INCOMES_FILE);
		reader.setPopulationFile(Constants.POPULATION_FILE);

		List<ZipcodeRecord> zipcodes = reader.readData();

		assertTrue(zipcodes.size() > 0);

		assertNotNull(zipcodes.get(0));
		assertNotNull(zipcodes.get(0).getCoordinates());
		assertNotNull(zipcodes.get(0).getMedianHouseholdIncome());
		assertNotNull(zipcodes.get(0).getPopulation());
		assertNotNull(zipcodes.get(0).getZipcode());
	}

}

Add unit test for ZipcodeReader


package com.intellij.debugger.streams.action;

import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.project.Project;

/**
 * @author Vitaliy.Bibaev
 */
public class TraceStreamAction extends AnAction {
  private static class Holder {
    private static final JvmStreamDebuggerActionHandler HANDLER = new JvmStreamDebuggerActionHandler();
  }

  @Override
  public void actionPerformed(AnActionEvent e) {
    final Project project = e.getProject();
    if (project != null && Holder.HANDLER.isEnabled(project)) {
      Holder.HANDLER.perform(project);
    }
  }
}

package com.intellij.debugger.streams.action;

import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.project.Project;

/**
 * @author Vitaliy.Bibaev
 */
public class TraceStreamAction extends AnAction {
  private static class Holder {
    private static final JvmStreamDebuggerActionHandler HANDLER = new JvmStreamDebuggerActionHandler();
  }

  @Override
  public void update(AnActionEvent e) {
    final Project project = e.getProject();
    if (project != null) {
      e.getPresentation().setEnabled(Holder.HANDLER.isEnabled(project));
      return;
    }
    e.getPresentation().setEnabled(false);
  }

  @Override
  public void actionPerformed(AnActionEvent e) {
    final Project project = e.getProject();
    if (project != null && Holder.HANDLER.isEnabled(project)) {
      Holder.HANDLER.perform(project);
    }
  }
}

Disable the action on the debug toolbar if there is no stream call


package com.haxademic.core.hardware.kinect;

import java.util.ArrayList;

import com.haxademic.core.data.FloatBuffer;

public class KinectBufferedData {

	protected float _pixelSize;
	protected float _kinectClose;
	protected float _kinectFar;
	protected ArrayList<FloatBuffer> _gridBuffer;
	protected int[] _bufferedData;

	public KinectBufferedData( float pixelSize, float kinectClose, float kinectFar, int bufferSize ) {
		_pixelSize = pixelSize;
		_kinectClose = kinectClose;
		_kinectFar = kinectFar;
		buildGridBuffer(bufferSize);
	}

	protected void buildGridBuffer(int bufferSize) {
		_gridBuffer = new ArrayList<FloatBuffer>();
		for ( int x = 0; x < KinectSize.WIDTH; x += _pixelSize ) {
			for ( int y = 0; y < KinectSize.HEIGHT; y += _pixelSize ) {
				_gridBuffer.add( new FloatBuffer(bufferSize) );
			}
		}
	}

	public void update( IKinectWrapper kinectWrapper ) {
		if(_bufferedData == null) {
			_bufferedData = kinectWrapper.getDepthData().clone();
		}

		int gridIndex = 0;
		float depth = 0;

		for ( int x = 0; x < KinectSize.WIDTH; x += _pixelSize ) {
			for ( int y = 0; y < KinectSize.HEIGHT; y += _pixelSize ) {
				depth = kinectWrapper.getMillimetersDepthForKinectPixel( x, y );
//				if( depth > 0 ) {
					_gridBuffer.get( gridIndex ).update( depth );
//				}

				int offset = x + y * KinectSize.WIDTH;
				if( offset < _bufferedData.length ) {
					_bufferedData[offset] = (int) _gridBuffer.get( gridIndex ).average();
				}

				gridIndex += 1;
			}
		}
	}

	public int getBufferedDepthForKinectPixel( int x, int y ) {
		int offset = x + y * KinectSize.WIDTH;
		if( offset >= _bufferedData.length ) {
			return 0;
		} else {
			return _bufferedData[offset];
		}
	}
}

Add Kinect buffered data class


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

/**
 * Given an AVL (self balanced binary search tree), find the median. Remember you can't just take
 * the root element even if the tree is balanced because even with the tree balanced you don't know
 * if the median is exactly the root element on a left or right son.
 */
public class AvlTreeMedian {
}

Add statement to problem 36


package info.u_team.u_team_core.data;

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

import org.apache.logging.log4j.*;

import com.google.gson.*;
import com.google.gson.internal.Streams;
import com.google.gson.stream.JsonWriter;

import net.minecraft.data.*;

public abstract class CommonProvider implements IDataProvider {

	protected static final Logger LOGGER = LogManager.getLogger("DataGenerator");
	protected static final Gson GSON = new GsonBuilder().setPrettyPrinting().create();

	protected final Marker marker;

	private final String name;
	protected final DataGenerator generator;
	protected final Path path;

	public CommonProvider(String name, DataGenerator generator) {
		this.generator = generator;
		this.name = name;
		this.path = resolvePath(generator.getOutputFolder());
		marker = MarkerManager.getMarker(name);
	}

	protected abstract Path resolvePath(Path outputFolder);

	protected Path resolveAssets(Path outputFolder, String modid) {
		return outputFolder.resolve("assets").resolve(modid);
	}

	protected Path resolveData(Path outputFolder, String modid) {
		return outputFolder.resolve("data").resolve(modid);
	}

	@Override
	public String getName() {
		return name;
	}

	protected void write(DirectoryCache cache, JsonElement element, Path path) throws IOException {
		final StringWriter writer = new StringWriter();
		try {
			final JsonWriter jsonWriter = GSON.newJsonWriter(Streams.writerForAppendable(writer));
			jsonWriter.setIndent("	"); // Use tab instead of two spaces
			GSON.toJson(element, jsonWriter);
		} catch (IOException e) {
			throw new JsonIOException(e);
		}
		write(cache, writer.toString(), path);
	}

	protected void write(DirectoryCache cache, String string, Path path) throws IOException {
		final String hash = HASH_FUNCTION.hashUnencodedChars(string).toString();
		if (!Objects.equals(cache.getPreviousHash(path), hash) || !Files.exists(path)) {
			Files.createDirectories(path.getParent());
			try (final BufferedWriter writer = Files.newBufferedWriter(path)) {
				writer.write(string);
			}
		}
		cache.func_208316_a(path, hash);
	}
}

Add common provider with some basic utility features


package org.jdesktop.swingx;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.event.ActionEvent;

import javax.swing.AbstractAction;
import javax.swing.JButton;
import javax.swing.JFrame;

import org.jdesktop.swingx.JXHeader;
import org.jdesktop.swingx.JXMultiSplitPane;
import org.jdesktop.swingx.JXPanel;
import org.jdesktop.swingx.MultiSplitLayout;
import org.jdesktop.swingx.MultiSplitLayout.Node;

public class JXMultiSplitPaneVisualIssues extends InteractiveTestCase {

    private static void prepare(JFrame f) {
        prepare(f, MultiSplitLayout.parseModel("(ROW (COLUMN weight=0.5 left.top left.bottom)" +
                " (LEAF name=middle)" +
                " (COLUMN weight=0.5 right.top right.bottom))"));

    }

    private static void prepare(JFrame f, Node model) {
        final JXMultiSplitPane msp;
        JXPanel p = new JXPanel(new BorderLayout());
        JXHeader header = new JXHeader();
        header.setTitle("<html><B>JXMultiSplitPaneIssue</b>");
        header.setDescription("<html>This is a bit tricky ... To reproduce the issue move one of the dividers and then click reset. Expected behavior is that original layout is restored. Actual behavior (bug) is that only two cells stay displayed and no divider is visible.");
        p.add(header, BorderLayout.NORTH);
        msp = new JXMultiSplitPane();
        msp.setModel(model);
        p.add(msp);
        JButton green = new JButton("mid");
        green.setBackground(Color.GREEN);
        msp.add(green, "middle");
        msp.add(new JButton("l.t"), "left.top");
        msp.add(new JButton("l.b"), "left.bottom");
        msp.add(new JButton("r.t"), "right.top");
        msp.add(new JButton("r.b"), "right.bottom");
        f.add(p);
        JButton b = new JButton(new AbstractAction("Reset") {

            public void actionPerformed(ActionEvent e) {
                // just reset the model
                msp.setModel(MultiSplitLayout.parseModel("(ROW (COLUMN weight=0.5 left.top left.bottom)" +
                " (LEAF name=middle)" +
                " (COLUMN weight=0.5 right.top right.bottom))"));
                msp.revalidate();
                msp.repaint();
            }

        });
        f.add(b, BorderLayout.SOUTH);
        f.setPreferredSize(new Dimension(400, 400));
    }

    public void interactiveModelChange() {
        JFrame f = new JFrame();
        prepare(f);
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.pack();
        f.setVisible(true);
    }

    /**
     * @param args
     */
    public static void main(String[] args) {
        JXMultiSplitPaneVisualIssues test = new JXMultiSplitPaneVisualIssues();
        try {
            test.runInteractiveTests();
          } catch (Exception e) {
              System.err.println("exception when executing interactive tests:");
              e.printStackTrace();
          }
    }

}

Test exposing MultiSplitPane model reset issue.


package com.sunny.grokkingalgorithms.fasttrack.treesandgraphs;

import com.sunny.grokkingalgorithms.ctci.c4.util.BinaryTreeNode;
import com.sunny.grokkingalgorithms.ctci.c4.util.TreeUtils;

/**
 * Created by sundas on 6/9/2018.
 */
public class CheckIfATreeIsABSTOrNot {

  /*
  Check if a given binary tree is a BST or not.
   */

  /**
   *
   * @param root
   * @return
   */
  public static boolean isBSTBruteForce(BinaryTreeNode root){
    /*
    Empty tree is a BST
     */
    if(root == null){
      return true;
    }
    int maxOfLeftSubTree = findMax(root.left);
    int minOfRightSubTree = findMin(root.right);
    if(root.data >= maxOfLeftSubTree
        && root.data < minOfRightSubTree){
      /*
      Check if subtrees are bst or not, bST condition for this node has been validated.The BST condition should hold true
       for every node in the tree.
       */
      return (isBSTBruteForce(root.left) && isBSTBruteForce(root.right));
    }
    /*
    Failed BST condistion so false,no need to check further.
     */
    return false;
  }

  /**
   *
   * @param root
   * @return
   */
  public static int findMax(BinaryTreeNode root){
    if(root == null){
      return Integer.MIN_VALUE;
    }
    int left = findMax(root.left);
    int right = findMax(root.right);
    int max = Math.max(left,right);
    max = Math.max(root.data,max);
    return max;
  }

  /**
   *
   * @param root
   * @return
   */
  public static int findMin(BinaryTreeNode root){
    if(root == null){
      return Integer.MAX_VALUE;
    }
    int left = findMin(root.left);
    int right = findMin(root.right);
    int min = Math.min(left,right);
    min = Math.min(root.data,min);
    return min;
  }

  /**
   *
   * @param args
   */
  public static void main(String[] args) {
    BinaryTreeNode root = TreeUtils.createBST();
    TreeUtils.performBfsLevelMarker(root);
    System.out.println(isBSTBruteForce(root));
    System.out.println("########");
    root = TreeUtils.createUnBalancedBinaryTree();
    TreeUtils.performBfsLevelMarker(root);
    System.out.println(isBSTBruteForce(root));
  }

}

Check if a tree is BST or not using brute force.O(Nsquared)


// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

package org.chromium.chrome.browser.tabmodel.document;

import android.test.InstrumentationTestCase;
import android.test.UiThreadTest;
import android.test.suitebuilder.annotation.SmallTest;

import org.chromium.content_public.browser.LoadUrlParams;

/**
 * Tests that the AsyncTabCreationParamsManager works as expected.
 */
public class AsyncTabCreationParamsManagerTest extends InstrumentationTestCase {
    @SmallTest
    @UiThreadTest
    public void testBasicAddingAndRemoval() throws Exception {
        AsyncTabCreationParams asyncParams =
                new AsyncTabCreationParams(new LoadUrlParams("http://google.com"));
        AsyncTabCreationParamsManager.add(11684, asyncParams);

        AsyncTabCreationParams retrievedParams = AsyncTabCreationParamsManager.remove(11684);
        assertEquals("Removed incorrect parameters from the map", asyncParams, retrievedParams);

        AsyncTabCreationParams failedParams = AsyncTabCreationParamsManager.remove(11684);
        assertNull("Removed same parameters twice", failedParams);
    }
}

Add a simple test for AsyncTabCreationParamsManager


/*
 *  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.directory.server.core.interceptor.context;

import org.apache.directory.shared.ldap.name.LdapDN;

/**
 * A ModifyDN context used for Interceptors. It contains all the informations
 * needed for the modify DN operation, and used by all the interceptors
 *
 * @author Apache Directory Project
 * @version $Rev$, $Date$
 */
public class ModifyDNServiceContext extends AbstractServiceContext
{
    /** The new DN */
    private String newDn;

    /** The flag to remove the old DN Attribute  */
    private boolean delOldDn;

    /**
     *
     * Creates a new instance of ModifyDNServiceContext.
     *
     */
    public ModifyDNServiceContext()
    {
    	super();
    }

    /**
     *
     * Creates a new instance of ModifyDNServiceContext.
     *
     */
    public ModifyDNServiceContext( LdapDN oldDn, String newDn, boolean delOldDn )
    {
        super( oldDn );
        this.newDn = newDn;
        this.delOldDn = delOldDn;
    }

    /**
     * @return The delete old DN flag
     */
	public boolean getDelOldDn()
	{
		return delOldDn;
	}

	/**
	 * Set the flag to delete the old DN
	 * @param delOldDn the flag to set
	 */
	public void setDelOldDn( boolean delOldDn )
	{
		this.delOldDn = delOldDn;
	}

	/**
	 * @return The new DN
	 */
	public String getNewDn()
	{
		return newDn;
	}

	/**
	 * Set the new DN
	 * @param newDn The new Dn
	 */
	public void setNewDn( String newDn )
	{
		this.newDn = newDn;
	}

	/**
     * @see Object#toString()
     */
    public String toString()
    {
        return "ModifyDNContext for old DN '" + getDn().getUpName() + "'" +
        ", newDn '" + newDn + "'" +
        ( delOldDn ? ", delete old Dn" : "" ) ;
    }
}

Add a serviceContext for the modifyDn operation


package io.quarkus.it.hibernate.validator.enums;

import javax.validation.constraints.NotNull;

/**
 * Simply adding this class to the code, without even referencing it from anywhere,
 * used to make Quarkus startup fail because of an error in Hibernate Validator.
 * See https://github.com/quarkusio/quarkus/issues/3284
 */
public enum MyEnumWithValidatorAnnotation {
    VALUE1,
    VALUE2;

    public static MyEnumWithValidatorAnnotation fromCode(@NotNull String code) {
        return MyEnumWithValidatorAnnotation.valueOf(code);
    }
}

Test enums annotated with Hibernate Validator annotations


package com.stephenramthun.algorithms.graph;

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

import org.junit.jupiter.api.Test;

class TopologicalSortTest {

    @Test
    void testTopSort() {
        int n = 10;
        int expectedSize = n;
        Integer[] values = new Integer[n];

        for (int i = 0; i < n; i++) {
            values[i] = i;
        }

        Graph<Integer> graph = new Graph<Integer>(values);
    }
}

Add tests for top sort.


/**

   Copyright 2010 OpenEngSB Division, Vienna University of Technology

   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.openengsb.ui.web.editor.fields;

import org.apache.wicket.markup.html.form.FormComponent;
import org.apache.wicket.markup.html.form.PasswordTextField;
import org.apache.wicket.model.IModel;
import org.openengsb.core.config.descriptor.AttributeDefinition;

@SuppressWarnings("serial")
public class PasswordField extends AbstractField {

    public PasswordField(String id, IModel<String> model, AttributeDefinition attribute) {
        super(id, model, attribute);
    }

    @Override
    protected FormComponent<String> createFormComponent(AttributeDefinition attribute, IModel<String> model) {
        PasswordTextField field = new PasswordTextField("field", model);
        return field;
    }
}

Add new field for passwords.


package io.quarkus.hibernate.orm;

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

import java.io.File;
import java.io.IOException;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.net.URL;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.hibernate.Hibernate;
import org.jboss.jandex.AnnotationInstance;
import org.jboss.jandex.ClassInfo;
import org.jboss.jandex.DotName;
import org.jboss.jandex.Index;
import org.junit.jupiter.api.Test;

import io.quarkus.deployment.index.IndexingUtil;
import io.quarkus.hibernate.orm.deployment.HibernateOrmAnnotations;

/**
 * Test that hardcoded lists of Hibernate ORM annotations stay up-to-date.
 */
public class HibernateOrmAnnotationsTest {

    private static final DotName RETENTION = DotName.createSimple(Retention.class.getName());
    private static final DotName TARGET = DotName.createSimple(Target.class.getName());

    @Test
    public void testNoMissingPackageLevelAnnotation() throws IOException {
        Index index = indexHibernateJar();

        Set<DotName> packageLevelHibernateAnnotations = findRuntimeAnnotationsByTargetType(index, ElementType.PACKAGE);
        packageLevelHibernateAnnotations.removeIf(name -> name.toString().contains(".internal."));

        assertThat(HibernateOrmAnnotations.PACKAGE_ANNOTATIONS)
                .containsExactlyInAnyOrderElementsOf(packageLevelHibernateAnnotations);
    }

    private Set<DotName> findRuntimeAnnotationsByTargetType(Index index, ElementType targetType) {
        Set<DotName> annotations = new HashSet<>();
        for (AnnotationInstance retentionAnnotation : index.getAnnotations(RETENTION)) {
            ClassInfo annotation = retentionAnnotation.target().asClass();
            if (RetentionPolicy.RUNTIME.name().equals(retentionAnnotation.value().asEnum())
                    && allowsTargetType(annotation, targetType)) {
                annotations.add(annotation.name());
            }
        }
        return annotations;
    }

    private boolean allowsTargetType(ClassInfo annotation, ElementType targetType) {
        AnnotationInstance targetAnnotation = annotation.classAnnotation(TARGET);
        if (targetAnnotation == null) {
            // Can target anything
            return true;
        }

        List<String> allowedTargetTypes = Arrays.asList(targetAnnotation.value().asEnumArray());
        return allowedTargetTypes.contains(targetType.name());
    }

    private Index indexHibernateJar() throws IOException {
        return IndexingUtil.indexJar(determineHibernateJarLocation());
    }

    private File determineHibernateJarLocation() {
        URL url = Hibernate.class.getProtectionDomain().getCodeSource().getLocation();
        if (!url.getProtocol().equals("file")) {
            throw new IllegalStateException("Hibernate JAR is not a local file? " + url);
        }
        return new File(url.getPath());
    }
}


/**
 *
 */
package de.terrestris.shogun2.security.access.entity;

import static org.hamcrest.CoreMatchers.equalTo;
import static org.junit.Assert.assertThat;

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

import org.junit.Test;

import de.terrestris.shogun2.helper.IdHelper;
import de.terrestris.shogun2.model.User;
import de.terrestris.shogun2.model.UserGroup;
import de.terrestris.shogun2.model.security.Permission;

/**
 * @author Nils Bühner
 *
 */
public class UserGroupPermissionEvaluatorTest extends
	AbstractSecuredObjectPermissionEvaluatorTest<UserGroup> {

	public UserGroupPermissionEvaluatorTest() {
		super(UserGroup.class, new UserGroupPermissionEvaluator<>(), new UserGroup());
	}

	@Test
	public void hasPermission_shouldAlwaysGrantReadOnGroupsWhereUserIsMember() throws NoSuchFieldException, IllegalAccessException {
		Permission readPermission = Permission.READ;

		// prepare a user that is member of the group
		final User user = new User("First name", "Last Name", "accountName");
		IdHelper.setIdOnPersistentObject(user, 42);

		// prepare a secured group
		UserGroup userGroup = new UserGroup();
		IdHelper.setIdOnPersistentObject(user, 17);

		// add the user to the group
		userGroup.getMembers().add(user);

		// we do not add any permissions to the user, but expect that he is allowed to READ himself
		// call method to test
		boolean permissionResult = persistentObjectPermissionEvaluator.hasPermission(user , userGroup, readPermission);

		assertThat(permissionResult, equalTo(true));

	}

	@Test
	public void hasPermission_shouldNeverGrantAdminDeleteOrWriteOnOwnUserObject() throws NoSuchFieldException, IllegalAccessException {

		// prepare a user that
		final User user = new User("First name", "Last Name", "accountName");
		IdHelper.setIdOnPersistentObject(user, 42);

		// prepare a secured group
		UserGroup userGroup = new UserGroup();
		IdHelper.setIdOnPersistentObject(user, 17);

		// add the user to the group
		userGroup.getMembers().add(user);

		Set<Permission> permissions = new HashSet<Permission>(Arrays.asList(Permission.values()));
		permissions.remove(Permission.READ); // everything but READ

		for (Permission permission : permissions) {
			// call method to test
			boolean permissionResult = persistentObjectPermissionEvaluator.hasPermission(user, userGroup, permission);

			assertThat(permissionResult, equalTo(false));
		}

	}

}

Add a test for the UserGroupPermissionEvaluator


package com.coding4people.mosquitoreport.api.exceptionmappers;

import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;

@Path("/")
public class ExceptionMapperTestController {

    @POST
    @Consumes("application/json")
    @Produces("application/json;charset=UTF-8")
    public String post(@Valid Data data) {
        return "\"Parameter is " + data.getParameter() + "\"";
    }

    public static class Data {
        @NotNull
        private String parameter;

        public String getParameter() {
            return parameter;
        }

        public void setParameter(String parameter) {
            this.parameter = parameter;
        }
    }

}

Add exception mapper test controller


package com.vmware.vim25.mo.samples;

import com.vmware.vim25.AboutInfo;
import com.vmware.vim25.mo.ServiceInstance;

public class VCenterServerInfo {

   public static void main(String[] args) throws Exception {
      ServiceInstance si = SampleUtil.createServiceInstance();

      AboutInfo info = si.getAboutInfo();
      System.out.println("=== vCenter Server Summary ===");
      System.out.println("Name: " + info.getFullName());
      System.out.println("UUID: " + info.getInstanceUuid());
      System.out.println("Vendor: " + info.getVendor());
      System.out.println("Version: " + info.getVersion());
      System.out.println("OS Type: " + info.getOsType());
      System.out.println("API Version: " + info.getApiVersion());
      System.out.println("Cookie: " + si.getServerConnection().getSessionStr());

      si.getServerConnection().logout();
   }

}

Add sample for displaying vCenter Server info.


package com.github.havarunner.rules;

import com.github.havarunner.HavaRunner;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TestRule;
import org.junit.runner.Description;
import org.junit.runner.notification.Failure;
import org.junit.runners.model.Statement;

import static com.github.havarunner.TestHelper.runAndRecordFailure;
import static org.junit.Assert.assertEquals;

public class WhenRuleFailsTest {

    @Test
    public void HavaRunner_will_give_a_helpful_error_message_if_a_rule_throws_an_exception() {
        Failure failure = runAndRecordFailure(new HavaRunner(TestWithRule.class));
        assertEquals("Fail!", failure.getMessage());
        assertEquals(IllegalStateException.class, failure.getException().getClass());
    }

    static class TestWithRule {
            @Rule
            TestRule rule = new TestRule() {
                @Override
                public Statement apply(Statement base, Description description) {
                    throw new IllegalStateException("Fail!");
                }
            };

            @Test
            void hello() {
            }
        }
}

Add spec for failing @Rule


/*
 * Copyright 2001-2015 Aspose Pty Ltd. All Rights Reserved.
 *
 * This file is part of Aspose.Email. The source code in this file
 * is only intended as a supplement to the documentation, and is provided
 * "as is", without warranty of any kind, either expressed or implied.
 */

//This feature is available from Aspose.Email for Java 5.4.0 onwards
package programmersguide.programmingoutlook.WorkingWithPSTFiles.SplitPSTFiles.Java;

import com.aspose.email.*;

import java.io.File;

public class SplitPSTFiles
{
    static String currentFolder;
    static int messageCount;

    public static void main(String[] args) throws Exception
    {
        // The path to the documents directory.
        String dataDir = "src/programmersguide/programmingoutlook/WorkingWithPSTFiles/SplitPSTFiles/Data";

        // Display Status.
        System.out.println("MSG file created and saved successfully.");
    }
    public void split()
    {
        String path = "Emailnet_33397";
        String sourceFileName = dataDir + "Outlook.pst";

        final PersonalStorage pst = PersonalStorage.fromFile(sourceFileName);
        try /*JAVA: was using*/
        {
            pst.StorageProcessed.add( new StorageProcessedEventHandler() {
                public void invoke(Object sender, StorageProcessedEventArgs e) {
                    pstSplit_OnStorageProcessed(sender, e);
                }
            });
            pst.ItemMoved.add( new ItemMovedEventHandler() {
                public void invoke(Object sender, ItemMovedEventArgs e) {
                    pstSplit_OnItemMoved(sender, e);
                }
            });
            pst.splitInto(5000000, dataDir + "chunks\");
        }
        finally { if (pst != null) (pst).dispose(); }
    }
    private void pstSplit_OnStorageProcessed(Object sender, StorageProcessedEventArgs e)
    {
        if (currentFolder != null)
        {
            System.out.println(" Added " + messageCount + " messages to " + currentFolder);
        }

        messageCount = 0;
        currentFolder = null;
        System.out.println("*** The chunk is processed: " + e.getFileName());
    }

    private void pstSplit_OnItemMoved(Object sender, ItemMovedEventArgs e)
    {
        if (currentFolder == null)
        {
            currentFolder = e.getDestinationFolder().retrieveFullPath();
        }

        String folderPath = e.getDestinationFolder().retrieveFullPath();

        if (!folderPath.equals(currentFolder))
        {
            System.out.println(" Added " + messageCount + " messages to " + currentFolder);
            messageCount = 0;
            currentFolder = folderPath;
        }

        messageCount++;
    }
}

Split PST File into multiple PST files example


package com.github.aureliano.evtbridge.core.config;

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

import com.github.aureliano.evtbridge.common.helper.ReflectionHelper;
import com.github.aureliano.evtbridge.common.helper.StringHelper;
import com.github.aureliano.evtbridge.core.filter.IEventFielter;
import com.github.aureliano.evtbridge.core.formatter.IOutputFormatter;
import com.github.aureliano.evtbridge.core.helper.DataHelper;
import com.github.aureliano.evtbridge.core.listener.DataWritingListener;
import com.github.aureliano.evtbridge.core.parser.IParser;

public abstract class AbstractConfigOutputConverter<T> implements IConfigurationConverter<T> {

	@SuppressWarnings("unchecked")
	protected void configureObject(IConfigOutput conf, Map<String, Object> data) {
		String value = StringHelper.parse(data.get("parser"));
		if (!StringHelper.isEmpty(value)) {
			conf.withParser((IParser<?>) ReflectionHelper.newInstance(value));
		}

		value = StringHelper.parse(data.get("filter"));
		if (!StringHelper.isEmpty(value)) {
			conf.withFilter((IEventFielter) ReflectionHelper.newInstance(value));
		}

		value = StringHelper.parse(data.get("formatter"));
		if (!StringHelper.isEmpty(value)) {
			conf.withOutputFormatter((IOutputFormatter) ReflectionHelper.newInstance(value));
		}

		if (data.get("dataWritingListeners") != null) {
			List<String> listeners = (List<String>) data.get("dataWritingListeners");
			for (String listener : listeners) {
				conf.addDataWritingListener((DataWritingListener) ReflectionHelper.newInstance(listener));
			}
		}

		if (data.get("metadata") != null) {
			Properties properties = DataHelper.mapToProperties((Map<String, Object>) data.get("metadata"));
			for (Object key : properties.keySet()) {
				conf.putMetadata(key.toString(), properties.getProperty(key.toString()));
			}
		}
	}
}

Create abstract config output converter.


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

/**
 * The exception thrown when the bundling process is stopped during its process
 * @author Ibrahim Chaehoi
 */
public class InterruptBundlingProcessException extends BundlingProcessException {

	/** The serial version UID */
	private static final long serialVersionUID = -1968057965587405979L;

	/**
	 * Constructor
	 * @param message the message
	 */
	public InterruptBundlingProcessException() {
		super("Bundling process stopped");
	}

}

Add interrupt bundling process exception


package info.u_team.u_team_core.api.fluid;

import net.minecraftforge.fluids.FluidStack;
import net.minecraftforge.fluids.capability.IFluidHandler;

public interface IFluidHandlerModifiable extends IFluidHandler {

	void setFluidInTank(int tank, FluidStack stack);

}

Add interface for modifiable fluid handlers with setFluidInTank method


/**
 * Copyright 2017 Pivotal Software, 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 io.micrometer.spring.jdbc;

import javax.sql.DataSource;

import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import io.micrometer.core.instrument.MeterRegistry;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Test;

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

/**
 * Tests for {@link DataSourcePoolMetricsAutoConfiguration}.
 *
 * @author Johnny Lim
 */
class DataSourcePoolMetricsAutoConfigurationTest {

    private AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();

    @AfterEach
    void cleanUp() {
        if (this.context != null) {
            this.context.close();
        }
    }

    @Test
    void backsOffWhenMeterRegistryIsMissing() {
        registerAndRefresh(DataSourceConfiguration.class,
                DataSourcePoolMetricsAutoConfiguration.class);

        assertThatThrownBy(() -> this.context.getBean(DataSourcePoolMetricsAutoConfiguration.class))
            .isInstanceOf(NoSuchBeanDefinitionException.class);
    }

    @Test
    void backsOffWhenDataSourceIsMissing() {
        registerAndRefresh(MeterRegistryConfiguration.class,
                DataSourcePoolMetricsAutoConfiguration.class);

        assertThatThrownBy(() -> this.context.getBean(DataSourcePoolMetricsAutoConfiguration.class))
            .isInstanceOf(NoSuchBeanDefinitionException.class);
    }

    @Test
    void autoConfigurationKicksIn() {
        registerAndRefresh(DataSourceConfiguration.class, MeterRegistryConfiguration.class,
                DataSourcePoolMetricsAutoConfiguration.class);

        assertThat(this.context.getBean(DataSourcePoolMetricsAutoConfiguration.class)).isNotNull();
    }

    private void registerAndRefresh(Class<?>... configurationClasses) {
        this.context.register(configurationClasses);
        this.context.refresh();
    }

    @Configuration
    static class DataSourceConfiguration {

        @Bean
        public DataSource dataSource() {
            return mock(DataSource.class);
        }

    }

    @Configuration
    static class MeterRegistryConfiguration {

        @Bean
        public MeterRegistry meterRegistry() {
            return mock(MeterRegistry.class);
        }

    }

}

Add tests for DataSourcePoolMetricsAutoConfiguration ConditionalOnBean


package problems;

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

public class MergeKSortedLists {

    public class ListNode {
        int val;
        ListNode next;

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

    class Pair implements Comparable<Pair> {
        ListNode node;
        int idx;

        Pair(ListNode ln, int index) {
            node = ln;
            idx = index;
        }

        public int compareTo(Pair p) {
            return node.val - p.node.val;
        }
    }

    public ListNode mergeKLists(List<ListNode> lists) {
        if (lists == null || lists.size() == 0)
            return null;

        ListNode head = null, p = null;
        PriorityQueue<Pair> pq = new PriorityQueue<Pair>();
        List<ListNode> A = new ArrayList<ListNode>(lists);

        for (int i = 0; i < A.size(); i++) {
            if (A.get(i) != null)
                pq.add(new Pair(A.get(i), i));
        }

        while (pq.size() > 0) {
            Pair t = pq.poll();
            if (head == null) {
                head = t.node;
                p = head;
            } else {
                p.next = t.node;
                p = p.next;
            }
            A.set(t.idx, A.get(t.idx).next);
            if (A.get(t.idx) != null) {
                pq.add(new Pair(A.get(t.idx), t.idx));
            }
        }
        return head;
    }
}

Add Merge K Sorted Lists


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

import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;

import sample.mybatis.xml.domain.City;

/**
 * @author Eddú Meléndez
 */
@Mapper
public interface CityMapper {

  @Select("select id, name, state, country from city where state = #{state}")
  City findByState(@Param("state") String state);

}

Add missing cityMapper (was being picked up elsewhere on original classpath)


package org.judal.examples.java.jdbc;

import org.junit.Test;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.judal.examples.java.model.Course;
import org.judal.storage.query.relational.RelationalQuery;
import org.judal.storage.table.RecordSet;

public class E31_ConvertToXMLJSON {

	@SuppressWarnings("unused")
	@Test
	public void demo() throws Exception {

		setUp();

		Course c = new Course();

		c.load(1);

		Map<String,String> attribs = new HashMap<String,String>();
		attribs.put("timestamp", new Date().toString());

		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-DD");

		String courseAsXML = c.toXML("  ", attribs, dateFormat, null, null);

		try (RelationalQuery<Course> qry = new RelationalQuery<>(Course.class)) {
			qry.setResult("*");
			qry.setFilter("1=1");

			RecordSet<Course> courses = qry.fetch();

			String coursesAsXML = courses.toXML("  ", dateFormat, null, null);

			String coursesAsJSON = courses.toJSON();
		}

		tearDown();
	}

	public static void setUp() throws Exception {
		E10_WriteCSVDataIntoTheDatabase.setUp();
		E10_WriteCSVDataIntoTheDatabase.insertCoursesIntoDatabase();
	}

	public static void tearDown() throws Exception {
		E10_WriteCSVDataIntoTheDatabase.tearDown();
	}

}

Add JSON and XML printers


package net.stickycode.stile.version.component;

import net.stickycode.exception.PermanentException;

@SuppressWarnings("serial")
public class InvalidVersionStringException
    extends PermanentException {

  public InvalidVersionStringException(CharSequence source, int start) {
    super("Character '{}' is not valid in version specification '{}'. ", source, source.charAt(start));
  }

}

Verify that the spliterator excepts on various invalid characters with a useful message, and the exception too


package org.opendatakit.consts;

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

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

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

}

Generalize request code constants out of Tables


package org.realityforge.ssf;

import javax.annotation.Nonnull;

/**
 * A basic interface defining a session.
 */
public interface SessionInfo
{
  /**
   * @return an opaque ID representing session.
   */
  @Nonnull
  String getSessionID();

  /**
   * @return the username for session if available.
   */
  @Nonnull
  String getUsername();

  /**
   * @return the time at which session was created.
   */
  long getCreatedAt();

  /**
   * @return the time at which session was last accessed.
   */
  long getLastAccessedAt();
}

Add basic interface to define session


package info.u_team.u_team_test.data.provider;

import java.util.function.BiConsumer;

import info.u_team.u_team_core.data.*;
import net.minecraft.util.ResourceLocation;
import net.minecraft.world.storage.loot.LootTable;

public class TestLootTablesProvider extends CommonLootTablesProvider {

	public TestLootTablesProvider(GenerationData data) {
		super(data);
	}

	@Override
	protected void registerLootTables(BiConsumer<ResourceLocation, LootTable> consumer) {
	}

}

Add test loot tables provider


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

package org.springframework.web.jsf.navigation;

import javax.faces.application.NavigationHandler;
import javax.faces.context.FacesContext;

import junit.framework.TestCase;

import org.springframework.beans.BeansException;
import org.springframework.web.jsf.MockFacesContext;

/**
 * Test for DelegatingNavigationHandler
 *
 * @author Colin Sampaleanu
 */
public class DelegatingNavigationHandlerTests extends TestCase {

	public void testHandleNavigation() {

		MockFacesContext facesContext = new MockFacesContext();
		final StaticMockNavigationHandler firstHandler = new StaticMockNavigationHandler(
				new JsfChainingNavigationHandler());
		StaticMockNavigationHandler jsfHandler = new StaticMockNavigationHandler();

		DelegatingNavigationHandler delNavHandler = new DelegatingNavigationHandler(
				jsfHandler) {

			protected NavigationHandler getNavigationHandler(FacesContext facesContext)
					throws BeansException {
				return firstHandler;
			}
		};

		delNavHandler.handleNavigation(facesContext, "action", "myViewId");
		assertEquals(jsfHandler.lastFromAction, "fromAction");
		assertEquals(jsfHandler.lastOutcome, "myViewId");
	}

	public static class StaticMockNavigationHandler extends NavigationHandler {

		private NavigationHandler original;

		private String			lastFromAction;

		private String			lastOutcome;

		public StaticMockNavigationHandler() {
		}

		public StaticMockNavigationHandler(NavigationHandler original) {
			this.original = original;
		}

		/**
         * @param facesContext
         *            FacesContext for the current request
         * @param fromAction
         *            The action binding expression that was evaluated to
         *            retrieve the specified outcome (if any)
         * @param outcome
         *            The logical outcome returned by the specified action
         */
		public void handleNavigation(FacesContext facesContext, String fromAction,
				String outcome) {
			lastFromAction = fromAction;
			lastOutcome = outcome;
			if (original != null)
				original.handleNavigation(facesContext, fromAction, outcome);
		}
	}
}

Add a delegating JSF NavigationHandler implementation


/*
 *  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.
 */
/**
 * @author Pavel Dolgov
 * @version $Revision$
 */
package java.awt;

/**
 *
 * The context for nested event loop. It can be dialog, popup menu etc.
 */
class ModalContext {

    private boolean running = false;

    private final Toolkit toolkit;

    ModalContext() {
        toolkit = Toolkit.getDefaultToolkit();
    }

    /**
     * Set up and run modal loop in this context
     *
     */
    void runModalLoop() {
    	if(!running) {
    		running = true;
    		toolkit.dispatchThread.runModalLoop(this);
    	}
    }

    /**
     * Leave the modal loop running in this context
     * This method doesn't stops the loop immediately,
     * it just sets the flag that says the modal loop to stop
     *
     */
    void endModalLoop() {
        running = false;
    }

    /**
     *
     * @return modal loop is currently running in this context
     */
    boolean isModalLoopRunning() {
        return running;
    }

}

Patch for HARMONY-4838 "[classlib][swing] hang up when call JDialog.setVisible"


package dfs;

/*
	This class defines a Vertex for Depth First Searcg Algorithm
*/

class Vertex{

	private int name = -1;				// Vertex name
	private int d = -1; 					// Discovery timestamp
	private int f = -1; 				// Finishing timestamp
	private int parent = -1; 			// Parent vertex name in BFS forest
	private char color = 'w'; 			// Color (w - white, g - gray, b - black)

	// Constructs a vertex with specified name

	public Vertex(int name){
		this.name = name;
	}

	// Sets discovery time

	public void setD(int d){
		this.d = d;
	}

	// Sets Finishing time

	public void setF(int f){
		this.f = f;
	}

	// Sets Color

	public void setColor(char c){
		color = c;
	}

	// Sets parent

	public void setParent(int p){
		parent = p;

	}

	// Returns name

	public int getName(){
		return name;
	}

	// Returns d

	public int getD(){
		return d;
	}

	// Returns f

	public int getF(){
		return f;
	}

	// Returns Color

	public int getColor(){
		return color;
	}

	// Returns parent

	public int getParent(){
		return parent;
	}

}

Add vertex class for dfs


import org.junit.Test;

import static org.junit.Assert.assertTrue;

public class JvmCaching {

  @Test
  public void testCache() {

    assertTrue(Integer.valueOf(512) == Integer.valueOf(512));

  }
}

Add small testcase for JVM internal caching By default, from -128 to 127 for Integer


package org.voltdb.utils;

import org.voltdb.ServerThread;
import org.voltdb.VoltDB;
import org.voltdb.VoltTable;
import org.voltdb.VoltDB.Configuration;
import org.voltdb.client.Client;
import org.voltdb.client.ClientFactory;
import org.voltdb.compiler.VoltProjectBuilder;

import junit.framework.TestCase;

public class TestCSVLoader extends TestCase {
	public void testSimple() throws Exception {
        String simpleSchema =
            "create table BLAH (" +
            "IVAL bigint default 0 not null, " +
            //"TVAL timestamp default null," +
            "DVAL decimal default null," +
            "VVAL varchar(10) default null, " +
            "PRIMARY KEY(IVAL));";

        String pathToCatalog = Configuration.getPathToCatalogForTest("csv.jar");
        String pathToDeployment = Configuration.getPathToCatalogForTest("csv.xml");

        VoltProjectBuilder builder = new VoltProjectBuilder();
        builder.addLiteralSchema(simpleSchema);
        builder.addPartitionInfo("BLAH", "IVAL");
        builder.addStmtProcedure("Insert", "insert into blah values (?, ?, ?);", null);
        builder.addStmtProcedure("InsertWithDate", "INSERT INTO BLAH VALUES (974599638818488300, 5, 'nullchar');");
        boolean success = builder.compile(pathToCatalog, 2, 1, 0);
        assertTrue(success);
        MiscUtils.copyFile(builder.getPathToDeployment(), pathToDeployment);

        VoltDB.Configuration config = new VoltDB.Configuration();
        config.m_pathToCatalog = pathToCatalog;
        config.m_pathToDeployment = pathToDeployment;
        ServerThread localServer = new ServerThread(config);

        Client client = null;
        try {
            localServer.start();
            localServer.waitForInitialization();

            String []paras = {"/Users/xinjia/testdb.csv","Insert"};
            CSVLoader.main(paras);

            // do the test
            client = ClientFactory.createClient();
            client.createConnection("localhost");

          //VoltTable modCount = client.callProcedure("@AdHoc", "INSERT INTO BLAH VALUES (1, 1, 1, 1);").getResults()[0];
            //assertTrue(modCount.getRowCount() == 1);
            //assertTrue(modCount.asScalarLong() == 1);

        }
        finally {
            if (client != null) client.close();
            client = null;

            if (localServer != null) {
                localServer.shutdown();
                localServer.join();
            }
            localServer = null;

            // no clue how helpful this is
            System.gc();
        }

	}

}

Add a test file to test the CSVLoder class


package leetcode;

/**
 * https://oj.leetcode.com/problems/swap-nodes-in-pairs/
 */
public class Problem24 {
    static class ListNode {
        int val;
        ListNode next;

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

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

    public ListNode swapPairs(ListNode head) {
        // TODO: to be implemented
        return head;
    }

    private static void print(ListNode head) {
        for (ListNode n = head; n != null; n = n.next) {
            System.out.print(n + " ");
        }
        System.out.println();
    }

    public static void main(String[] args) {
        Problem24 prob = new Problem24();
        ListNode head = new ListNode(1);
        head.next = new ListNode(2);
        head.next.next = new ListNode(3);
        head.next.next.next = new ListNode(4);
        print(prob.swapPairs(head));
    }
}

Put the problem 24 skeleton


/*
+++++++++++++++++++++++++++++++++++++++++++
title     Package Info                    +
project   icecore-hashids                 +
file      package-info.java               +
version                                   +
author    Arctic Ice Studio               +
email     development@arcticicestudio.com +
website   http://arcticicestudio.com      +
copyright Copyright (C) 2016              +
created   2016-06-05 17:51 UTC+0200       +
modified  2016-06-05 17:53 UTC+0200       +
+++++++++++++++++++++++++++++++++++++++++++

[Description]
Represents the public API of the "IceCore - Hashids" library.
The main entry point of the package is the "Hashids" class to generate short, unique, non-sequential
and decodable hashids from positive unsigned (long) integer numbers.

[Copyright]
Copyright (C) 2016 Arctic Ice Studio <development@arcticicestudio.com>

[References]
Hashids
  (http://hashids.org)
Java 8 API Documentation
  (https://docs.oracle.com/javase/8/docs/api/)
Arctic Versioning Specification (ArcVer)
  (http://specs.arcticicestudio.com/arcver)
*/
/**
 * Represents the public API of the
 * "IceCore - Hashids" library.
 *

 *   The main entry point of the package is the {@link com.arcticicestudio.icecore.hashids.Hashids} class to to generate
 *   short, unique, non-sequential and decodable hashids from positive unsigned (long) integer numbers.
 *

 *
 * @author Arctic Ice Studio <development@arcticicestudio.com>
 * @see Hashids
 * @version 0.2.0
 */
package com.arcticicestudio.icecore.hashids;

Create package info class for "com.arcticicestudio.icecore.hashids"


package it.uniroma3.dia.alfredmpi.xpath;

import static org.junit.Assert.*;

import model.Page;
import org.junit.Before;
import org.junit.Test;

public class XPathHandlerTest {

	private XPathHandler xpathhandler;

	@Before
	public void setUp() throws Exception {
		xpathhandler = XPathHandler.getInstance();
	}

	@Test
	public void test_create_page_from_string() {
		String content = "<root>#BBB##CCC##DDD#</root>";
		Page page = this.xpathhandler.createPage(content);
		assertEquals(content, page.getContent());
		page.setTitle("Titolo di prova");
		assertEquals("Titolo di prova", page.getTitle());
	}

	@Test
	public void test_apply_xpath_to_page() {
		String content = "<root>#BBB##CCC##DDD#</root>";
		Page page = this.xpathhandler.createPage(content);
		page.setTitle("Titolo di prova");
		XPathHandler.getInstance().print_executeQuery(page, "//a");
		//TOCOMPLETE
	}

}

Refactor of test class.. no need for underscore in name


package com.spotify.docker.client.messages;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.api.client.util.NullValue;
import com.spotify.docker.client.ObjectMapperProvider;
import org.junit.Test;

import static com.spotify.docker.FixtureUtil.fixture;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.*;

/**
 * Test cases around the deserialization of the docker info object.
 */
public class DockerInfoTest {

    private final ObjectMapper objectMapper = ObjectMapperProvider.objectMapper();

    /**
     * Test that when we deserialize the docker info response we properly parse the Plugins.Network json path.
     * @throws Exception when we fail to deserialize
     */
    @Test
    public void dockerInfoNetworkDesirializerTest_1_23() throws Exception {
        Info info = objectMapper.readValue(fixture("fixtures/1.23/docker_info.json"), Info.class);
        assertThat(info.plugins(), is(not(nullValue())));
        assertThat(info.plugins().networks(), is(not(nullValue())));
        assertThat(info.plugins().networks().size() , is(greaterThan(0)));
    }
}

Add tests for the path of the network


/*
 *  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.easyant.core.ant;

import static org.hamcrest.CoreMatchers.hasItem;
import static org.hamcrest.CoreMatchers.isA;
import static org.junit.Assert.assertThat;

import org.apache.easyant.core.ant.listerners.MultiModuleLogger;
import org.apache.tools.ant.Project;
import org.apache.tools.ant.types.Path;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;

public class MetaBuildExecutorTest {

    private Project project = new Project();
    private MetaBuildExecutor executor = new MetaBuildExecutor();

    @Rule
    public ExpectedException expectedException = ExpectedException.none();

    @Test
    public void shouldFailIfNoBuildPathIsFound() {
        expectedException.expectMessage("build-path is required to use MetaBuildExecutor");
        executor.executeTargets(project, new String[] {});
    }

    @Test
    public void shouldNotFailIfNoSubModulesAreFound() {
        createPath();
        executor.executeTargets(project, new String[] {});
        verifyBuildListener();
    }

    private void createPath() {
        Path path = new Path(project);
        project.addReference("build-path", path);
    }

    private void verifyBuildListener() {
        assertThat(project.getBuildListeners(), hasItem(isA(MultiModuleLogger.class)));
    }

}

Add basic tests on metabuild executor


/*
 * See the NOTICE file distributed with this work for additional
 * information regarding copyright ownership.
 *
 * This is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License as
 * published by the Free Software Foundation; either version 2.1 of
 * the License, or (at your option) any later version.
 *
 * This software is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this software; if not, write to the Free
 * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
 * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
 */
package org.xwiki.rendering.renderer.printer;

import java.io.IOException;
import java.io.Writer;

/**
 * Printer using a {@link Writer} as the underlying output target.
 *
 * @version $Id$
 * @since 6.2M1
 */
public class WriterWikiPrinter implements WikiPrinter
{
    /**
     * The buffer where to put the provided {@link String}s.
     */
    private Writer writer;

    /**
     * @param writer the writer
     */
    public WriterWikiPrinter(Writer writer)
    {
        this.writer = writer;
    }

    /**
     * @return the writer
     */
    public Writer getWriter()
    {
        return this.writer;
    }

    /**
     * This method is protected to allow classes extending this one to override what a new line is.
     *
     * @return a new line symbols
     */
    protected String getEOL()
    {
        return "\n";
    }

    @Override
    public void print(String text)
    {
        try {
            this.writer.write(text);
        } catch (IOException e) {
            throw new RuntimeException("Failed to write", e);
        }
    }

    @Override
    public void println(String text)
    {
        print(text);
        print(getEOL());
    }

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

Introduce helper to deletgate WikiPrinter calls to a Writer


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

package org.jenkinsci.plugins.credentialsbinding.masking;

import hudson.Extension;
import org.kohsuke.accmod.Restricted;
import org.kohsuke.accmod.restrictions.NoExternalUse;

import javax.annotation.Nonnull;
import java.util.Collection;
import java.util.Collections;

/**
 * Almquist shell, aka ash, is the default shell in Alpine distribution
 */
@Extension
@Restricted(NoExternalUse.class)
public class AlmquistShellSecretPatternFactory implements SecretPatternFactory {

    private static final char SINGLE_QUOTE = '\'';
    private static final String START_FRAGMENT = "'\"";
    private static final String END_FRAGMENT = "\"'";

    private @Nonnull String getQuotedForm(@Nonnull String input) {
        StringBuilder sb = new StringBuilder(input.length());
        for (int i = 0; i < input.length(); i++) {
            char c = input.charAt(i);
            if (c == SINGLE_QUOTE) {
                // a single quote is replaced by '"'"' which is the concatenation of
                // '[part before...]' + "'" + '[...part after]'
                // if there are multiple single quotes successively, they are included in the double quotes together
                sb.append(START_FRAGMENT);
                // the first one, at index i
                sb.append(SINGLE_QUOTE);
                for (int j = i + 1; j < input.length() && input.charAt(j) == SINGLE_QUOTE; j++) {
                    sb.append(SINGLE_QUOTE);
                    i++;
                }
                sb.append(END_FRAGMENT);
            } else {
                sb.append(c);
            }
        }
        return sb.toString();
    }

    @Override
    public @Nonnull Collection<String> getEncodedForms(@Nonnull String input) {
        return Collections.singleton(getQuotedForm(input));
    }
}

Add support for Almquist shell in masking


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

package org.scijava.io;

import java.io.File;
import java.net.URI;

/**
 * {@link Location} backed by a {@link File} on disk.
 *
 * @author Curtis Rueden
 */
public class FileLocation extends AbstractLocation {

	private final File file;

	public FileLocation(final File file) {
		this.file = file;
	}

	public FileLocation(final String path) {
		this(new File(path));
	}

	// -- FileLocation methods --

	/** Gets the associated {@link File}. */
	public File getFile() {
		return file;
	}

	// -- Location methods --

	@Override
	public URI getURI() {
		return getFile().toURI();
	}

}

Add a location type backed by a file on disk


package net.devrieze.chatterbox.shared;

import java.io.Serializable;
import java.security.Principal;
import java.util.Calendar;
import java.util.GregorianCalendar;

public class MessagePojo implements Serializable{

  private static final long serialVersionUID = 5641483443503015088L;

  private Long aIndex;

  private String aMessageBody;

  private Long aMsgTime;

  private String aSender;

  public MessagePojo() {}

  public MessagePojo(long pIndex, String pMessageBody, long pEpoch, String pSenderEmail) {
    aIndex = pIndex;
    aMessageBody = pMessageBody;
    aMsgTime = pEpoch;
    aSender = pSenderEmail;

  }

  public Long getIndex() {
    return aIndex;
  }

  public String getMessageBody() {
    return aMessageBody;
  }

  public long getMsgTime() {
    return aMsgTime;
  }

  public String getSender() {
    return aSender;
  }

}

Create a pojo class for easier transfer of data between the server and gwt


package com.example.podcastplayer;

import java.io.IOException;
import java.io.StringReader;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;

public class Parser {

	public Parser(){}

	public void Parse (String strXML)
			throws XmlPullParserException, IOException
	{
		XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
		factory.setNamespaceAware(true);
		XmlPullParser xpp = factory.newPullParser();

		xpp.setInput( new StringReader ( strXML ) );
		int eventType = xpp.getEventType();

		while (eventType != XmlPullParser.END_DOCUMENT) {
			if(eventType == XmlPullParser.START_DOCUMENT) {
				System.out.println("Start document");
			} else if(eventType == XmlPullParser.START_TAG) {
				System.out.println("Start tag "+xpp.getName());
			} else if(eventType == XmlPullParser.END_TAG) {
				System.out.println("End tag "+xpp.getName());
			} else if(eventType == XmlPullParser.TEXT) {
				System.out.println("Text "+xpp.getText());
			}
			eventType = xpp.next();
		}
		System.out.println("End document");
	}
}

Add partially implemented parser class


package net.cbojar.spinner;

import net.cbojar.spinner.spinners.*;

public final class Main
{
	public static void main(final String[] args) {
		final SpinnerFactory spinFactory = new BinarySpinnerFactory();

		Spinner spin = spinFactory.getInstance();
		for(byte i = 1; i < 8; i++) {
			spin = spinFactory.getInstance(spin);
		}

		while(spin.hasNext()) {
			System.out.println(spin.next().toString());
		}
	}
}

Add driver with main method to run a Spinner.


package cc.mrlda;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IOUtils;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.SequenceFile;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapred.JobConf;

public class TopicUtils {
	public static int[] sortedIndices(double[] vals){
		int[] indices = new int[vals.length];
		Set<Integer> availIndices = new HashSet<Integer>(vals.length);
		for(int i = 0; i < vals.length; i++){
			availIndices.add(new Integer(i));
		}
		int key = 0;
		while(!availIndices.isEmpty()){
			Integer maxIdx = new Integer(-1);
			Iterator<Integer> j = availIndices.iterator();
			while(j.hasNext()){
				Integer idx = j.next();
				if(maxIdx.intValue() < 0 || vals[idx.intValue()] > vals[maxIdx.intValue()]){
					maxIdx = idx;
				}
			}
			indices[key]=maxIdx.intValue();
			key++;
			availIndices.remove(maxIdx);
		}
		return indices;
	}

	public static int maxIndex(double[] vals){
		int maxIdx = -1;
		for(int i = 0; i < vals.length; i++){
			if(maxIdx < 0 || vals[maxIdx] < vals[i]){
				maxIdx = i;
			}
		}
		return maxIdx;
	}
	public static Map<Integer,String> initializeIndex(FileSystem fs, JobConf conf, Path indexPath) throws Exception{
		SequenceFile.Reader sequenceFileReader = null;
		Map<Integer, String> index = new HashMap<Integer, String>();
		try {
			IntWritable intWritable = new IntWritable();
			Text text = new Text();
			sequenceFileReader = new SequenceFile.Reader(fs, indexPath, conf);
			while (sequenceFileReader.next(intWritable, text)) {
				index.put(intWritable.get(),text.toString());
			}
		} catch (Exception e){
			System.err.println("Error loading index "+e.getMessage());
		} finally {
			IOUtils.closeStream(sequenceFileReader);
		}
		return index;
	}

}

Put some common function into a Utils class for better reuse


package leetcode;

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

public class Problem113 {
    public static class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode(int x) {
            val = x;
        }
    }

    public List<List<Integer>> pathSum(TreeNode root, int sum) {
        List<List<Integer>> paths = new ArrayList<>();
        return paths;
    }

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

        TreeNode root = new TreeNode(5);
        root.left = new TreeNode(4);
        root.left.left = new TreeNode(11);
        root.left.left.left = new TreeNode(7);
        root.left.left.right = new TreeNode(2);
        root.right = new TreeNode(8);
        root.right.left = new TreeNode(13);
        root.right.right = new TreeNode(4);
        root.right.right.left = new TreeNode(5);
        root.right.right.right = new TreeNode(1);

        for (List<Integer> path : prob.pathSum(root, 22)) {
            System.out.println(path);
        }
    }
}

Create a skeleton for problem 113


package leetcode;

/**
 * https://leetcode.com/problems/range-sum-query-mutable/
 */
public class Problem307 {
    public static class NumArray {

        public NumArray(int[] nums) {

        }

        void update(int i, int val) {

        }

        public int sumRange(int i, int j) {
            // TODO:
            return 0;
        }
    }

    public static void main(String[] args) {
        int[] nums = new int[]{1, 3, 5};
        NumArray numArray = new NumArray(nums);
        numArray.sumRange(0, 1);
        numArray.update(1, 10);
        numArray.sumRange(1, 2);
    }
}

Create skeleton for problem 307