package net.restlesscoder.sandbox.scijava;

import javax.swing.JOptionPane;

import org.scijava.MenuPath;
import org.scijava.SciJava;
import org.scijava.command.Command;
import org.scijava.command.CommandInfo;
import org.scijava.menu.ShadowMenu;

/**
 * Adds some commands to the SciJava menu which are backed by {@link Runnable}
 * objects.
 */
public class RunnableCommands {

	public static void main(final String... args) throws Exception {
		// Create a SciJava application context.
		final SciJava sj = new SciJava();

		// Create some simple Runnable objects, as a demo.
		final Runnable hello = new Runnable() {
			@Override
			public void run() {
				JOptionPane.showMessageDialog(null, "Hello world");
			}
		};
		final Runnable aloha = new Runnable() {
			@Override
			public void run() {
				JOptionPane.showMessageDialog(null, "Aloha");
			}
		};

		// Create Command wrappers for the Runnable objects, and register them.
		final CommandInfo helloCommand = new RunnableCommandInfo(hello);
		helloCommand.setMenuPath(new MenuPath("Greetings>Hello World"));
		sj.module().addModule(helloCommand);

		final CommandInfo alohaCommand = new RunnableCommandInfo(aloha);
		alohaCommand.setMenuPath(new MenuPath("Greetings>Aloha"));
		sj.module().addModule(alohaCommand);

		// Verify that the SciJava menu has been updated accordingly.
		final ShadowMenu greetingsMenu = sj.menu().getMenu().getMenu("Greetings");
		sj.log().info("greetings menu:\n" + greetingsMenu);

		// Display the UI, to test out the commands!
		sj.ui().showUI();
	}

	public static class RunnableCommandInfo extends CommandInfo {
		private Runnable r;

		public RunnableCommandInfo(final Runnable r) {
			super(RunnableCommand.class);
			this.r = r;
		}
		@Override
		public RunnableCommand createInstance() {
			return new RunnableCommand(r);
		}
	}

	public static class RunnableCommand implements Command {
		private final Runnable r;
		public RunnableCommand(Runnable r) {
			this.r = r;
		}
		@Override
		public void run() {
			r.run();
		}
	}
}

Add runnable SciJava command experiment


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

package imagej.ui.console;

import imagej.console.AbstractConsoleArgument;
import imagej.console.ConsoleArgument;
import imagej.ui.UIService;
import imagej.ui.UserInterface;

import java.util.LinkedList;

import org.scijava.log.LogService;
import org.scijava.plugin.Parameter;
import org.scijava.plugin.Plugin;

/**
 * Handles the {@code --ui} command line argument.
 *
 * @author Curtis Rueden
 */
@Plugin(type = ConsoleArgument.class)
public class UIArgument extends AbstractConsoleArgument {

	@Parameter
	private UIService uiService;

	@Parameter
	private LogService log;

	// -- ConsoleArgument methods --

	@Override
	public void handle(final LinkedList<String> args) {
		if (!supports(args)) return;

		args.removeFirst(); // --ui
		final String uiName = args.removeFirst();

			final UserInterface ui = uiService.getUI(uiName);
			if (ui == null) {
				log.error("No such UI: " + uiName);
			}
			else {
				uiService.setDefaultUI(ui);
			}
	}

	// -- Typed methods --

	@Override
	public boolean supports(final LinkedList<String> args) {
		return args != null && args.size() >= 2 && args.getFirst().equals("--ui");
	}

}

Add --ui command line argument


package com.interview.string;

/**
 * Remove consecutive duplicate characters
 * e.g
 * AABBCDDAAB -> ABCDAB
 * ABBBCCD -> ABCD
 * Test cases
 * Empty string
 * all unique
 * all duplicates
 * duplicates at certain different places
 */
public class RemoveConsecutiveDuplicate {

    public int removeDuplicates(char input[]){
        int slow = 0;
        int fast = 0;
        int index = 0;
        while(fast < input.length){
            while(fast < input.length && input[slow] == input[fast]){
                fast++;
            }
            input[index++] = input[slow];
            slow = fast;
        }
        return index;
    }

    public static void main(String args[]){
        String str = "AAABBCCDDDEFGH";
        char input[] = str.toCharArray();
        RemoveConsecutiveDuplicate rcd = new RemoveConsecutiveDuplicate();
        int len = rcd.removeDuplicates(input);
        for(int i=0; i < len; i++){
            System.out.print(input[i] + " ");
        }
    }
}

Remove consecutive duplicate characters in string


package org.apache.jmeter.functions;

import java.util.Collection;
import java.util.LinkedList;

import org.apache.jmeter.engine.util.CompoundVariable;
import org.apache.jmeter.junit.JMeterTestCase;

public class TestXPathFunction extends JMeterTestCase {

    private XPath setupXPath(String file, String expr) throws Exception{
        Collection parms = new LinkedList();
        parms.add(new CompoundVariable(file));
        parms.add(new CompoundVariable(expr));
        XPath xp = new XPath();
        xp.setParameters(parms);
        return xp;
    }

    public void testEmpty() throws Exception{
        XPath xp = setupXPath("","");
        String val=xp.execute();
        assertEquals("",val);
        val=xp.execute();
        assertEquals("",val);
        val=xp.execute();
        assertEquals("",val);
    }

    public void testNoFile() throws Exception{
        XPath xp = setupXPath("no-such-file","");
        String val=xp.execute();
        assertEquals("",val); // TODO - should check that error has been logged...
    }

    public void testFile1() throws Exception{
        XPath xp = setupXPath("testfiles/XPathTest.xml","//user/@username");
        assertEquals("u1",xp.execute());
        assertEquals("u2",xp.execute());
        assertEquals("u1",xp.execute());
    }

    public void testFile2() throws Exception{
        XPath xp1  = setupXPath("testfiles/XPathTest.xml","//user/@username");
        XPath xp1a = setupXPath("testfiles/XPathTest.xml","//user/@username");
        XPath xp2  = setupXPath("testfiles/XPathTest.xml","//user/@password");
        XPath xp2a = setupXPath("testfiles/XPathTest.xml","//user/@password");
        assertEquals("u1",xp1.execute());
        assertEquals("p1",xp2.execute());
        assertEquals("p2",xp2.execute());
        assertEquals("u2",xp1a.execute());
        assertEquals("u1",xp1.execute());
        assertEquals("u2",xp1.execute());
        assertEquals("p1",xp2a.execute());

    }
}

Add some tests for XPath function


package leetcode.validate_binary_search_tree;

import common.TreeNode;

public class Solution {

	public boolean isValidBST(TreeNode root, Integer lower, Integer upper){
		if(root.left != null){
			if(root.left.val >= root.val) return false;
			if(lower != null && root.left.val <= lower.intValue()) return false;
			if(!isValidBST(root.left, lower, root.val)) return false;
		}
		if(root.right != null){
			if(root.right.val <= root.val) return false;
			if(upper != null && root.right.val >= upper.intValue()) return false;
			if(!isValidBST(root.right, root.val, upper)) return false;
		}
		return true;
	}

    public boolean isValidBST(TreeNode root) {
    	if(root == null) return true;
        return isValidBST(root, null, null);
    }
}

Add java solution for 98. Validate Binary Search Tree


package edu.pdx.cs410J;

import org.junit.Test;

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.equalTo;

public class InvokeMainTest extends InvokeMainTestCase {

  @Test
  public void commandLineArgsWrittenToStandardOutAreCaptured() {
    String[] args = { "One", "Two", "Three"};
    MainMethodResult result = invokeMain(InvokeMainTest.class, args);
    assertThat(result.getExitCode(), equalTo(0));

    String out = result.getTextWrittenToStandardOut();
    for(String arg : args) {
      assertThat(out, containsString(arg));
    }
  }

  public static void main(String... args) {
    for (String arg : args) {
      System.out.println(arg);
    }

    System.exit(0);
  }
}

Add a new test so that we do not have an empty set of unit tests. That situation now causes the build to fail.


/*
 * Copyright 2008 The Kuali Foundation.
 *
 * Licensed under the Educational Community License, Version 1.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.opensource.org/licenses/ecl1.php
 *
 * 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.kuali.kra.s2s;

import java.sql.Connection;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.kuali.kra.KraTestBase;
/**
 *
 * This class is to test the database connectivity for coeus s2s engine.
 */
public class KualiDataSourceConnectionManagerTest extends KraTestBase {
    @Before
	public void setUp() throws Exception{
		super.setUp();
	}
    @After
	public void tearDown() throws Exception {
		super.tearDown();
	}
    @Test
	public final void getDatabaseConnectionTest() throws Exception{
        KualiDataSourceConnectionManager cnnMgr = new KualiDataSourceConnectionManager();
        assertNotNull(cnnMgr.getDatabaseConnection());
    }
    @Test
    public final void freeDatabaseConnectionTest() throws Exception{
        KualiDataSourceConnectionManager cnnMgr = new KualiDataSourceConnectionManager();
        Connection conn = cnnMgr.getDatabaseConnection();
        cnnMgr.freeDatabaseConnection(conn);
        assertTrue(conn.isClosed());
    }
}

Test class for coeus-s2s engine


package com.lucene;

public class LuceneConstants {

	public static final String DATA_DIRECTORY 			= "/Users/Hurricanc/Documents/Projects/WJLucene-Server/MetaData/Data";
	public static final String INDEX_DIRECTORY 			= "/Users/Hurricanc/Documents/Projects/WJLucene-Server/MetaData/Index";

	public static final String DEFAULT_FIELD 			= "core_newsurl";

	public static final String CORE_NEWSURL 			= "core_news_url";
	public static final String CORE_NEWSNUMBER 			= "core_news_number";
	public static final String CORE_NEWSTITLE 			= "core_new_title";
	public static final String CORE_NEWSBODY			= "core_news_body";
	public static final String CORE_NEWSDATE			= "core_news_date";
	public static final String CORE_NEWSSOURCE 			= "core_news_source";

	public static final String COMMENT_ID 				= "comment_id";
	public static final String COMMENT_PARENTID 		= "comment_parentId";
	public static final String COMMENT_COMMENTER 		= "comment_commenter";
	public static final String COMMENT_LOCATION 		= "comment_location";
	public static final String COMMENT_DATE 			= "comment_date";
	public static final String COMMENT_LIKECOMMENT 		= "comment_like_comment";
	public static final String COMMENT_DISLIKECOMMENT	= "comment_dislike_comment";
	public static final String COMMENT_RESPONSECOUNT 	= "comment_response_count";
	public static final String COMMENT_BODY 			= "comment_body";

	public static final String CATEGORY_NEWS 			= "core_category";
	public static final String LABEL_NEWS 				= "core_label";

	public static final String FILE_NAME				= "filename";
	public static final String FILE_PATH				= "filepath";

	public static final String FILE_PATH_CORENEWS 		= "/Users/Hurricanc/Documents/Projects/WJLucene-Server/MetaData/Data/Core.xls";
	public static final String FILE_PATH_COMMENTS		= "/Users/Hurricanc/Documents/Projects/WJLucene-Server/MetaData/Data/Comments.xls";
	public static final String FILE_PATH_CATEGORY		= "/Users/Hurricanc/Documents/Projects/WJLucene-Server/MetaData/Data/Category.xls";
	public static final String FILE_PATH_LABELS			= "/Users/Hurricanc/Documents/Projects/WJLucene-Server/MetaData/Data/Label.xls";

	public static final int MAX_SEARCH = 50000;

	public static final String MESSAGE_INDEXING 		= "Wait for Merging raw data and Indexing!";
	public static final String MESSAGE_INDEXED 			= "Ready to Use, Give it a try!";
	public static final String MESSAGE_SEARCH 			= " Documents Found in ";

}

Create Constants Class for All Hardcoded Texts and URLs


//19) Use Case: Load Relevant Comments

public class LoadRelevantCommentsTests extend
    ActivityInstrumentationTestCase2<BrowseCommentsActivity> {

    public LoadRelevantCommentsTests() {
	super(LoadRelevantComments.class);
    }

    //Test that comments are by default sorted and displayed by location and then date
    public void testNewAndNear() {
	double lat1 = 53.5222;
	double long1 = 113.6228;
	double lat2 = 53.5244;
	double long2 = 113.5244;
	double lat3 = 53.6303;
	double long3 = 113.6258;
	Location location1 = new Location(MOCK_PROVIDER);
	location1.setLatitude(lat1);
	location1.setLongitude(long1);
	Location location2 = new Location(MOCK_PROVIDER);
	location2.setLatitude(lat2);
	location2.setLongitude(long2);
	Location location3 = new Location(MOCK_PROVIDER);
	location3.setLatitude(lat3);
	location3.setLongitude(long3);
	TopLevelCommentModel topComment1 = new TopLevelCommentModel("name1", location1, System.currentTimeMillis());
	TopLevelCommentModel topComment3 = new TopLevelCommentModel("name3", location2, System.currentTimeMillis());
	TopLevelCommentModel topComment2 = new TopLevelCommentModel("name2", location1, System.currentTimeMillis());
	TopLevelCommentModel topComment4 = new TopLevelCommentModel("name4", location2, System.currentTimeMillis());
	TopLevelCommentModel topComment5 = new TopLevelCommentModel("name5", location3, System.currentTimeMillis());
	ArrayList<TopLevelCommentModel> arrayList1 = new ArrayList<TopLevelCommentModel>;
	ArrayList<TopLevelCommentModel> arrayList2 = new ArrayList<TopLevelCommentModel>;
	arrayList1.add(topComment2);
	arrayList1.add(topComment1);
	arrayList1.add(topComment5);
	arrayList1.add(topComment4);
	arrayList1.add(topComment3);
	arrayList2.add(topComment1);
	arrayList2.add(topComment2);
	arrayList2.add(topComment3);
	arrayList2.add(topComment4);
	arrayList2.add(topComment5);
	Sort.sortByDefault(arrayList1);
	assertTrue("The arraylists should be the same after the sort", (arrayList1 == arrayList2));
    }

    //Test that location is updated after internet connection loss
    public void testChangeLocation() {
	Location initial_loc = new Location(LOCATION_PROVIDER);
	// Tester should disconnect from internet and move locations, then reconnect to internet
	Location final_loc = new Location(LOCATION_PROVIDER);
	boolean latEquals = FALSE;
	boolean longEquals = FALSE;
	if (initial_loc.getLatitude == final_loc.getLatitude)
	    latEquals = TRUE;
	if (initial_loc.getLongitude == final_loc.getLongitude)
	    longEquals = TRUE;
	boolean CoordEquals = latEquals && longEquals;
	assertFalse(CoordEquals);
   }
}

Add tests for use case 19


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

import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Sets;
import io.atomix.primitives.DistributedPrimitive;
import io.atomix.protocols.raft.proxy.RaftProxy;

import java.util.Collection;
import java.util.Set;
import java.util.function.Consumer;
import java.util.function.Function;

import static com.google.common.base.MoreObjects.toStringHelper;
import static com.google.common.base.Preconditions.checkNotNull;

/**
 * Abstract base class for primitives that interact with Raft replicated state machines via proxy.
 */
public abstract class AbstractRaftPrimitive implements DistributedPrimitive {
    private final Function<RaftProxy.State, Status> mapper = state -> {
        switch (state) {
            case CONNECTED:
                return Status.ACTIVE;
            case SUSPENDED:
                return Status.SUSPENDED;
            case CLOSED:
                return Status.INACTIVE;
            default:
                throw new IllegalStateException("Unknown state " + state);
        }
    };

    protected final RaftProxy proxy;
    private final Set<Consumer<Status>> statusChangeListeners = Sets.newCopyOnWriteArraySet();

    public AbstractRaftPrimitive(RaftProxy proxy) {
        this.proxy = checkNotNull(proxy, "proxy cannot be null");
        proxy.addStateChangeListener(this::onStateChange);
    }

    @Override
    public String name() {
        return proxy.name();
    }

    /**
     * Handles a Raft session state change.
     *
     * @param state the updated Raft session state
     */
    private void onStateChange(RaftProxy.State state) {
        statusChangeListeners.forEach(listener -> listener.accept(mapper.apply(state)));
    }

    @Override
    public void addStatusChangeListener(Consumer<Status> listener) {
        statusChangeListeners.add(listener);
    }

    @Override
    public void removeStatusChangeListener(Consumer<Status> listener) {
        statusChangeListeners.remove(listener);
    }

    @Override
    public Collection<Consumer<Status>> statusChangeListeners() {
        return ImmutableSet.copyOf(statusChangeListeners);
    }

    @Override
    public String toString() {
        return toStringHelper(this)
                .add("proxy", proxy)
                .toString();
    }
}

Add abstract base class for Raft primitives.


/*
 * Copyright 2016 Ross Nicoll.
 *
 * 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.libdohj.cate;

import org.bitcoinj.core.Context;
import org.bitcoinj.params.TestNet3Params;
import org.libdohj.params.DogecoinTestNet3Params;

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

/**
 * Unit test for NetworkThreadFactory
 * @author Ross Nicoll
 */
public class NetworkThreadFactoryTest {
    /**
     * Generate a thread and confirm the context is set on it.
     */
    @Test
    public void shouldSetContextOnThread() throws InterruptedException {
        final Context expected = new Context(TestNet3Params.get());
        final Context broken = new Context(DogecoinTestNet3Params.get());
        final NetworkThreadFactory factory = new NetworkThreadFactory(expected);

        // Progagate the wrong context onto this thread
        Context.propagate(broken);
        assertEquals(broken, Context.get());

        final ThreadMonitor monitor = new ThreadMonitor();
        final Thread thread = factory.newThread(monitor);
        thread.run();
        thread.join();

        assertEquals(expected, monitor.actual);
    }

    public static class ThreadMonitor implements Runnable {
        Context actual = null;
        public void run() {
            actual = Context.get();
        }
    }
}

Add unit test for NetworkThreadFactory


/*
Copyright 2016, Johannes Mulder (Fraunhofer IOSB)

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package de.fraunhofer.iosb.ivct;

import java.util.List;

public class CommandCache {
	private List<String> testcases;
	private static int i = 0;

	CommandCache(final List<String> testcases) {
		this.testcases = testcases;
	}

	public String getNextTestCase() {
        System.out.println("getNextTestCase ENTER");

		if (i < testcases.size()) {
		return testcases.get(i);
		} else {
			return null;
		}
	}
}

Add command cache to handle test case lists


/*
 * Copyright 2000-2012 JetBrains s.r.o.
 *
 * 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.intellij.openapi.project;

import com.intellij.openapi.Disposable;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.util.Disposer;

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

/**
 * User: ksafonov
 */
public abstract class ModuleNameTracker extends ModuleAdapter {
  private Map<Module, String> myModulesNames = new HashMap<Module, String>();
  private final Project myProject;

  public ModuleNameTracker(Project project) {
    myProject = project;
    Disposer.register(project, new Disposable() {
      @Override
      public void dispose() {
        myModulesNames.clear();
      }
    });
  }

  @Override
  public void moduleAdded(final Project project, final Module module) {
    if (myProject == project) {
      myModulesNames.put(module, module.getName());
    }
  }

  @Override
  public void moduleRemoved(final Project project, final Module module) {
    if (myProject == project) {
      myModulesNames.remove(module);
    }
  }

  @Override
  public void modulesRenamed(final Project project, final List<Module> modules) {
    if (myProject != project) {
      return;
    }

    Map<String, String> old2newNames = new HashMap<String, String>(modules.size());
    for (Module module : modules) {
      String newName = module.getName();
      String oldName = myModulesNames.put(module, newName);
      old2newNames.put(oldName, newName);
    }
    modulesRenamed(project, old2newNames);
  }

  protected abstract void modulesRenamed(final Project project, final Map<String, String> old2newNames);
}

Update run configuration reference on module and build configuration rename (IDEA-74823)


/*
 Copyright (C) 2004 EBI, GRL

 This library 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 library is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 Lesser General Public License for more details.

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

package org.ensembl.healthcheck.testcase.generic;

import java.sql.Connection;

import org.ensembl.healthcheck.DatabaseRegistryEntry;
import org.ensembl.healthcheck.ReportManager;
import org.ensembl.healthcheck.testcase.SingleDatabaseTestCase;

/**
 * Check if protein_coding genes have a canonical transcript that has a valid translation. See also canonical_transcript checks in
 * CoreForeignKeys.
 */
public class CanonicalTranscriptCoding extends SingleDatabaseTestCase {

	/**
	 * Create a new instance of CanonicalTranscriptCoding.
	 */
	public CanonicalTranscriptCoding() {

		addToGroup("release");
		addToGroup("post_genebuild");
		setDescription("Check if protein_coding genes have a canonical transcript that has a valid translation. See also canonical_transcript checks in CoreForeignKeys.");
		setTeamResponsible("compara");

	}

	/**
	 * Run the test.
	 *
	 * @param dbre
	 *          The database to use.
	 * @return true if the test passed.
	 *
	 */
	public boolean run(DatabaseRegistryEntry dbre) {

		boolean result = true;

		Connection con = dbre.getConnection();

		int rows = getRowCount(con, "SELECT COUNT(*) FROM gene g LEFT JOIN translation tr ON g.canonical_transcript_id=tr.transcript_id WHERE g.biotype='protein_coding' AND tr.transcript_id IS NULL");

		if (rows > 0) {

			result = false;
			ReportManager.problem(this, con, rows + " protein_coding genes have canonical transcripts that do not have valid translations");

		} else {

			ReportManager.correct(this, con, "All protein_coding genes have canonical_transcripts that translate");
		}

		return result;

	} // run

} // CanonicalTranscriptCoding

Check for protein coding genes with invalid translations


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

package org.apache.commons.text.lookup;

import javax.script.ScriptEngineFactory;
import javax.script.ScriptEngineManager;

/** Helper to see what ScriptEngineFactory are the classpath. */
public class ScriptEngineFactoryHelper {

    public static void main(String[] args) {
        final String indent = "  ";
        for (ScriptEngineFactory factory : new ScriptEngineManager().getEngineFactories()) {
            System.out.println(factory);
            System.out.println(indent + factory.getEngineName());
            System.out.println(indent + factory.getEngineVersion());
            System.out.println(indent + factory.getLanguageName());
            System.out.println(indent + factory.getLanguageVersion());
            System.out.println(indent + factory.getClass());
            System.out.println(indent + factory.getExtensions());
            System.out.println(indent + factory.getMimeTypes());
            System.out.println(indent + factory.getNames());
        }
    }

}

Add helper to see what ScriptEngineFactory are the classpath.


/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package org.mitre.taxii.messages.xml11;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.Writer;
import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.Unmarshaller;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;

/**
 *
 * @author jasenj1
 */

@RunWith(Parameterized.class)
public class PythonTextOutputFileTests {
    private static TaxiiXml taxiiXml;
    private static Unmarshaller unmarshaller;

    private static final String inputPath = "src/test/resources/python_output/1.1";
    private static final String outputPath = "build/test-results";

    @Parameterized.Parameter(0)
    public File file;

    private static File outDir;

    @BeforeClass
    public static void init() throws Exception {
        TaxiiXmlFactory txf = new TaxiiXmlFactory();
        taxiiXml = txf.createTaxiiXml();
        unmarshaller = taxiiXml.getJaxbContext().createUnmarshaller();
        outDir = new File(outputPath);
    }

    @Parameterized.Parameters(name="{index} - {0}")
    public static Iterable<File[]> data() throws IOException {
        final List<File[]> data = new ArrayList<>();
        Files.walkFileTree(
                Paths.get(inputPath),
                new SimpleFileVisitor<Path>() {
                    @Override
                    public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                        if (!file.toFile().isHidden()) {
                            data.add(new File[] { file.toFile() });
                        }
                        return FileVisitResult.CONTINUE;
                    }
                });
        return data;
    }

    @Test
    public void testFile() throws Exception {
        MessageType m = (MessageType) unmarshaller.unmarshal(file);
        String s = PythonTextOutput.toText(m);
        String outName = file.getName().replaceFirst("[.][^.]+$", "");
        File outFile = new File(outDir,outName + ".txt");

        Writer writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile), "utf-8"));
        System.out.println(s);
        writer.write(s);
        writer.close();
    }

}

Use XML files as input for Python output tests. Write Python output from the XML file tests to other files for comparison with the Python output.


package com.webcohesion.ofx4j.domain.data.tax1099;

import com.webcohesion.ofx4j.io.AggregateMarshaller;
import com.webcohesion.ofx4j.io.v2.OFXV2Writer;

import junit.framework.TestCase;

import java.io.IOException;
import java.io.StringWriter;
import java.util.Arrays;

public class TestTax1099R extends TestCase {

    public void testMarshallMultipleDistributionCodes() throws IOException {
        Tax1099R tax1099R = new Tax1099R();

        //Required
        tax1099R.setSrvrtId("test");
        tax1099R.setTaxYear("2020");
        tax1099R.setGrossDist("10");
        tax1099R.setIraSepSimp("N");
        tax1099R.setPayerId("testing");

        PayerAddress payerAddress = new PayerAddress();
        payerAddress.setAddress1("testing");
        payerAddress.setPayerName1("testing");
        payerAddress.setCity("testing");
        payerAddress.setState("TEST");
        payerAddress.setPostalCode("12341");
        tax1099R.setPayerAddress(payerAddress);
        tax1099R.setRecId("1234567");
        tax1099R.setRecAcct("1234567");

        tax1099R.setDistCodes(Arrays.asList("A", "G"));

        StringWriter sw = new StringWriter();
        AggregateMarshaller marshaller = new AggregateMarshaller();

        marshaller.marshal(tax1099R, new OFXV2Writer(sw));

        String output = sw.toString();
        assertTrue(output.contains("<DISTCODE>A</DISTCODE>"));
        assertTrue(output.contains("<DISTCODE>G</DISTCODE>"));
    }
}

Add test for correctly unmarshalling multiple distribution codes


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

import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertNotNull;

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

import org.jsmpp.DefaultPDUReader;
import org.jsmpp.DefaultPDUSender;
import org.jsmpp.PDUSender;
import org.jsmpp.SMPPConstant;
import org.jsmpp.bean.Command;
import org.jsmpp.bean.GenericNack;
import org.jsmpp.util.DefaultDecomposer;
import org.jsmpp.util.PDUDecomposer;
import org.testng.annotations.Test;

/**
 * Simulating sending and receive data from client to server (vice versa) by
 * simple compose and decomposing the PDU.
 *
 * @author uudashr
 *
 */
public class ComposeDecompose {
    private PDUSender pduSender = new DefaultPDUSender();
    private DefaultPDUReader pduReader = new DefaultPDUReader();
    private PDUDecomposer decomposer = new DefaultDecomposer();

    /**
     * Test the composed PDU can decomposed properly.
     *
     * @throws Exception if an unexpected error found.
     */
    @Test(groups="checkintest")
    public void sendGenericNack() throws Exception {
        ByteArrayOutputStream out = new ByteArrayOutputStream();

        pduSender.sendGenericNack(out, SMPPConstant.STAT_ESME_RINVBNDSTS, 10);

        DataInputStream in = new DataInputStream(new ByteArrayInputStream(out.toByteArray()));
        Command header = pduReader.readPDUHeader(in);
        assertEquals(header.getCommandId(), SMPPConstant.CID_GENERIC_NACK, "Unexpected command_id");

        byte[] pdu = pduReader.readPDU(in, header);
        GenericNack nack = decomposer.genericNack(pdu);
        assertNotNull(nack);
    }

}

Add test case for composing and decomposing trough pduSender


package org.wikipedia.analytics;

import android.text.TextUtils;

import org.json.JSONException;
import org.json.JSONObject;
import org.wikipedia.PageTitle;
import org.wikipedia.Site;
import org.wikipedia.WikipediaApp;

import java.util.List;

public class SuggestedPagesFunnel extends Funnel {
    private static final String SCHEMA_NAME = "MobileWikiAppArticleSuggestions";
    private static final int REV_ID = 10590869;

    private final String appInstallID;
    private final Site site;

    public SuggestedPagesFunnel(WikipediaApp app, Site site) {
        super(app, SCHEMA_NAME, REV_ID);

        //Retrieve this app installation's unique ID, used to record unique users of features
        appInstallID = app.getAppInstallID();

        this.site = site;
    }

    @Override
    protected JSONObject preprocessData(JSONObject eventData) {
        try {
            eventData.put("appInstallID", appInstallID);
        } catch (JSONException e) {
            throw new RuntimeException(e);
        }
        return eventData;
    }

    protected void log(Object... params) {
        super.log(site, params);
    }

    public void logSuggestionsShown(PageTitle currentPageTitle, List<PageTitle> suggestedTitles) {
        log(
                "action", "shown",
                "pageTitle", currentPageTitle.getDisplayText(),
                "readMoreList", TextUtils.join("|", suggestedTitles)
        );
    }

    public void logSuggestionClicked(PageTitle currentPageTitle, List<PageTitle> suggestedTitles,
                                     int clickedIndex) {
        log(
                "action", "clicked",
                "pageTitle", currentPageTitle.getDisplayText(),
                "readMoreList", TextUtils.join("|", suggestedTitles),
                "readMoreIndex", clickedIndex
        );
    }

}

Add event logging for suggested pages.


package com.cloudera.dataflow.spark;

import com.google.cloud.dataflow.sdk.Pipeline;
import com.google.cloud.dataflow.sdk.coders.StringUtf8Coder;
import com.google.cloud.dataflow.sdk.options.PipelineOptionsFactory;
import com.google.cloud.dataflow.sdk.transforms.Create;
import com.google.cloud.dataflow.sdk.transforms.RemoveDuplicates;
import com.google.cloud.dataflow.sdk.values.PCollection;
import com.google.common.collect.ImmutableSet;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.junit.Assert;
import org.junit.Test;

/**
 * A test based on {@code DeDupExample} from the SDK.
 */
public class DeDupTest {

  private static final String[] LINES_ARRAY = {
      "hi there", "hello", "hi there",
      "hi", "hello"};
  private static final List<String> LINES = Arrays.asList(LINES_ARRAY);
  private static final Set<String> EXPECTED_SET =
      ImmutableSet.of("hi there", "hi", "hello");

  @Test
  public void testRun() throws Exception {
    Pipeline p = Pipeline.create(PipelineOptionsFactory.create());
    PCollection<String> input = p.apply(Create.of(LINES)).setCoder(StringUtf8Coder.of());
    PCollection<String> output = input.apply(RemoveDuplicates.<String>create());
    EvaluationResult res = SparkPipelineRunner.create().run(p);
    Set<String> actualSet = new HashSet<>();
    for (String s : res.get(output)) {
      actualSet.add(s);
    }

    Assert.assertEquals(String.format("Actual lines [%s] does not equal expected [%s].",
            actualSet, EXPECTED_SET), EXPECTED_SET, actualSet);
    res.close();
  }
}

Add test that uses DeDupExample from the SDK.


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

package imagej.module.process;

import imagej.module.Module;
import imagej.module.ModuleItem;
import imagej.widget.InputHarvester;

import org.scijava.log.LogService;
import org.scijava.plugin.Parameter;
import org.scijava.plugin.Plugin;

/**
 * A preprocessor plugin that does a final check of input parameters,
 * complaining if any required ones are null.
 *
 * @author Curtis Rueden
 */
@Plugin(type = PreprocessorPlugin.class,
	priority = InputHarvester.PRIORITY - 1)
public class CheckInputsPreprocessor extends AbstractPreprocessorPlugin {

	@Parameter(required = false)
	private LogService log;

	// -- ModuleProcessor methods --

	@Override
	public void process(final Module module) {
		for (final ModuleItem<?> input : module.getInfo().inputs()) {
			if (input.isRequired() && input.getValue(module) == null) {
				cancel("'" + input.getName() + "' is required but unset.");
			}
		}
	}

}

Add preprocessor which cancels on null inputs


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

package com.google.gerrit.server.project;

import com.google.common.base.Strings;
import com.google.gerrit.extensions.restapi.RestReadView;
import com.google.gerrit.reviewdb.client.Project;

class GetParent implements RestReadView<ProjectResource> {
  @Override
  public Object apply(ProjectResource resource) {
    Project project = resource.getControl().getProject();
    return Strings.nullToEmpty(project.getParentName());
  }
}

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

package com.google.gerrit.server.project;

import com.google.gerrit.extensions.restapi.RestReadView;
import com.google.gerrit.reviewdb.client.Project;
import com.google.gerrit.server.config.AllProjectsName;
import com.google.inject.Inject;

class GetParent implements RestReadView<ProjectResource> {
  private final AllProjectsName allProjectsName;

  @Inject
  GetParent(AllProjectsName allProjectsName) {
    this.allProjectsName = allProjectsName;
  }

  @Override
  public Object apply(ProjectResource resource) {
    Project project = resource.getControl().getProject();
    Project.NameKey parentName = project.getParent(allProjectsName);
    return parentName != null ? parentName.get() : "";
  }
}

Return via REST 'All-Projects' as parent name for projects under root


package de.philipphager.disclosure.database;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import de.philipphager.disclosure.database.migration.Migrator;
import javax.inject.Inject;

public class DatabaseOpenHelper extends SQLiteOpenHelper {
  private static final String DB_NAME = "disclosure.db";
  private static final int DB_VERSION = 3;
  private final Migrator migrator;

  @Inject public DatabaseOpenHelper(Context context, Migrator migrator) {
    super(context, DB_NAME, null, DB_VERSION);
    this.migrator = migrator;
  }

  @Override public void onCreate(SQLiteDatabase db) {
    //Initial SQL schema creation
  }

  @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    migrator.migrate(db, oldVersion, newVersion);
  }
}

Add a DBOpenHelper to run manage the database schema


/*
 * Copyright 2016-present Facebook, 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.facebook.buck.parser;

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

import com.facebook.buck.cli.BuckConfig;
import com.facebook.buck.cli.FakeBuckConfig;
import com.facebook.buck.io.ProjectFilesystem;
import com.facebook.buck.model.BuildTarget;
import com.facebook.buck.model.BuildTargetException;
import com.facebook.buck.model.BuildTargetFactory;
import com.facebook.buck.parser.PipelineNodeCache.Cache;
import com.facebook.buck.rules.Cell;
import com.facebook.buck.rules.TestCellBuilder;
import com.facebook.buck.testutil.integration.TemporaryPaths;

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

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

public class DaemonicCellStateTest {

  @Rule
  public TemporaryPaths tempDir = new TemporaryPaths();

  private ProjectFilesystem filesystem;
  private Cell cell;
  private DaemonicCellState state;

  @Before
  public void setUp() throws IOException, InterruptedException {
    Path root = tempDir.getRoot().toRealPath();
    filesystem = new ProjectFilesystem(root);
    BuckConfig config = FakeBuckConfig.builder()
        .setFilesystem(filesystem)
        .build();
    cell = new TestCellBuilder()
        .setFilesystem(filesystem)
        .setBuckConfig(config)
        .build();
    state = new DaemonicCellState(cell, 1);
  }

  @Test
  public void testPutComputedNodeIfNotPresent()
      throws BuildTargetException, IOException, InterruptedException {
    Cache<BuildTarget, Boolean> cache = state.getOrCreateCache(Boolean.class);
    BuildTarget target = BuildTargetFactory.newInstance(filesystem, "//path/to:target");

    cache.putComputedNodeIfNotPresent(cell, target, false);
    assertEquals(
        "Cached node was not found",
        Optional.of(false),
        cache.lookupComputedNode(cell, target));

    assertFalse(cache.putComputedNodeIfNotPresent(cell, target, true));
    assertEquals(
        "Previously cached node should not be updated",
        Optional.of(false),
        cache.lookupComputedNode(cell, target));
  }

}

Add some unit tests for DaemonicCellState


package com.miguelgaeta.media_picker;

import android.os.Environment;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

@SuppressWarnings("UnusedDeclaration")
public class MediaPickerFile {

    /**
     * Create a file in the devices external storage.
     *
     * @param directory Target directory.
     * @param name Target file name.
     * @param suffix Target file suffix.
     *
     * @return Created file.
     *
     * @throws IOException
     */
    private static File create(final String directory, final String name, final String suffix) throws IOException {

        final File dir = new File(Environment.getExternalStorageDirectory() + File.separator + directory);

        if (!dir.exists()) {

            boolean result = dir.mkdirs();

            if (!result) {

                throw new IOException("Unable to create directory.");
            }
        }

        return File.createTempFile(name, suffix, dir);
    }

    /**
     * @see #create(String, String, String)
     */
    private static File create(final String directory, final String name) throws IOException {

        return create(directory, name, null);
    }

    /**
     * @see #create(String, String)
     */
    private static File create(final String directory) throws IOException {

        return create(directory, UUID.randomUUID().toString());
    }

    /**
     * @see #create(String)
     */
    private static File create() throws IOException {

        return create("media_picker");
    }
}

Add a file utility to create new files.


package com.stefanhoth.ropasclisp.achievements;

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

import java.text.DateFormat;
import java.util.Date;
import java.util.Locale;

import static android.content.Context.MODE_PRIVATE;

public final class DAILY_STATE {

    private static final DateFormat DATE_FORMAT = DateFormat.getDateInstance(DateFormat.SHORT, Locale.US);
    public static final int NO_STARTS = 0;

    public static DAILY_STATE with(Context context) {
        return new DAILY_STATE(context);
    }

    private static String PREFERENCE_NAME = "DAILY_STATE";
    private static String KEY_TODAYS_DATE = DAILY_STATE.class.getName() + ".TODAYS_DATE";
    private static String KEY_TODAYS_STARTS = DAILY_STATE.class.getName() + ".TODAYS_STARTS";

    private final Context context;

    private DAILY_STATE(Context context) {
        this.context = context;
    }

    public boolean isTodaysFirstStart() {

        if(! hasPreviousEntriesFromToday()){
            return false;
        }

        return NO_STARTS == getTodaysStarts();
    }

    int getTodaysStarts() {
        return getSharedPreferences().getInt(KEY_TODAYS_STARTS, NO_STARTS);
    }

    public void countAppStart() {
        SharedPreferences preferences = getSharedPreferences();
        int starts = getTodaysStarts();

        preferences.edit()
                .putInt(KEY_TODAYS_STARTS, starts + 1)
                .apply();
    }

    private synchronized SharedPreferences getSharedPreferences() {

        return context.getSharedPreferences(PREFERENCE_NAME, MODE_PRIVATE);
    }

    private boolean hasPreviousEntriesFromToday() {

        String currentDate = getCurrentDateString();
        SharedPreferences preferences = getSharedPreferences();

        if(currentDate.equals(preferences.getString(KEY_TODAYS_DATE, "NEVER_MATCH"))){
            return true;
        }

        cleanupOldData(preferences);
        createNewDayEntry(preferences);
        return false;
    }

    private void createNewDayEntry(SharedPreferences preferences) {
        preferences.edit()
                .putString(KEY_TODAYS_DATE, getCurrentDateString())
                .apply();
    }

    private String getCurrentDateString() {

        return DATE_FORMAT.format(new Date());
    }

    private void cleanupOldData(SharedPreferences preferences) {

        preferences.edit()
                .clear()
                .apply();
    }

}

Add class for encapsulating state for daily session data


// Licensed to the Software Freedom Conservancy (SFC) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The SFC 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.openqa.selenium.logging.profiler;

import org.openqa.selenium.json.Json;

import java.util.TreeMap;

public class HttpProfilerLogEntry extends ProfilerLogEntry {

  public HttpProfilerLogEntry(String commandName, boolean isStart) {
    super(EventType.HTTP_COMMAND, constructMessage(EventType.HTTP_COMMAND, commandName, isStart));
  }

  private static String constructMessage(EventType eventType, String commandName, boolean isStart) {
    TreeMap<Object, Object> map = new TreeMap<>();
    map.put("event", eventType.toString());
    map.put("command", commandName);
    map.put("startorend", isStart ? "start" : "end");
    return new Json().toJson(map);
  }

}

// Licensed to the Software Freedom Conservancy (SFC) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The SFC 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.openqa.selenium.logging.profiler;

public class HttpProfilerLogEntry extends ProfilerLogEntry {

  public HttpProfilerLogEntry(String commandName, boolean isStart) {
    super(EventType.HTTP_COMMAND, constructMessage(EventType.HTTP_COMMAND, commandName, isStart));
  }

  private static String constructMessage(EventType eventType, String commandName, boolean isStart) {
    // We're going to make the assumption that command name is a simple string which doesn't need
    // escaping.
    return String.format(
        "{\"event\": \"%s\", \"command\": \"%s\", \"startorend\": \"%s\"}",
        eventType.toString(),
        commandName,
        isStart ? "start" : "end");
  }
}

Break dependency on profiler to the json package


/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package de.charite.compbio.exomiser.common;

import org.junit.Test;
import static org.junit.Assert.*;

/**
 *
 * @author Jules Jacobsen <jules.jacobsen@sanger.ac.uk>
 */
public class FilterTypeTest {

    public FilterTypeTest() {
    }

    /**
     * Test of valueOf method, of class FilterType.
     */
    @Test
    public void testValueOf() {
        String name = "PHENODIGM_MGI_PRIORITY";
        FilterType expResult = FilterType.PHENODIGM_MGI_PRIORITY;
        FilterType result = FilterType.valueOf(name);
        assertEquals(expResult, result);

    }

    /**
     * Test of getCommandLineValue method, of class FilterType.
     */
    @Test
    public void testGetCommandLineValue() {
        FilterType instance = FilterType.BED_FILTER;
        String expResult = "bed";
        String result = instance.getCommandLineValue();
        assertEquals(expResult, result);
    }

    /**
     * Test of valueOfCommandLine method, of class FilterType.
     */
    @Test
    public void testValueOfCommandLineUnrecognisedDefault() {
        String value = "pweep!";
        FilterType expResult = FilterType.PHENODIGM_MGI_PRIORITY;
        FilterType result = FilterType.valueOfCommandLine(value);
        assertEquals(expResult, result);
    }

    /**
     * Test of valueOfCommandLine method, of class FilterType.
     */
    @Test
    public void testValueOfCommandLine() {
        String value = "boqa";
        FilterType expResult = FilterType.BOQA_PRIORITY;
        FilterType result = FilterType.valueOfCommandLine(value);
        assertEquals(expResult, result);
    }

}

Test for new command-line functionality of FilterType.


package fr.mashbarth.hascode.qualificationround;

public final class Launcher {

    public static void main(String[] args) {
        System.out.println("#### Qualification Round ####");
    }

    // Non instantiability.
    private Launcher() {
    }
}

Add a launcher with a main method.


package org.obolibrary.robot;

import java.io.IOException;
import org.junit.Test;
import org.obolibrary.robot.providers.CURIEShortFormProvider;
import org.semanticweb.owlapi.apibinding.OWLManager;
import org.semanticweb.owlapi.model.IRI;
import org.semanticweb.owlapi.model.OWLClass;
import org.semanticweb.owlapi.model.OWLDataFactory;

public class CURIEShortFormProviderTest extends CoreTest {

  @Test
  public void testProvider() throws IOException {
    IOHelper ioHelper = new IOHelper();
    CURIEShortFormProvider sfp = new CURIEShortFormProvider(ioHelper.getPrefixes());
    OWLDataFactory df = OWLManager.getOWLDataFactory();

    // Short form 1 should return GO (longer than OBO namespace)
    OWLClass c1 = df.getOWLClass(IRI.create("http://purl.obolibrary.org/obo/GO_123"));
    String sf1 = sfp.getShortForm(c1);
    assert sf1.equals("GO:123");

    // Short form 2 will default to base OBO since UNKNOWN is not registered
    OWLClass c2 = df.getOWLClass(IRI.create("http://purl.obolibrary.org/obo/UNKNOWN_123"));
    String sf2 = sfp.getShortForm(c2);
    assert sf2.equals("obo:UNKNOWN_123");

    // The example NS is not in prefixes so full IRI will be returned
    OWLClass c3 = df.getOWLClass(IRI.create("http://example.com/UNKNOWN_456"));
    String sf3 = sfp.getShortForm(c3);
    assert sf3.equals("http://example.com/UNKNOWN_456");
  }
}

Add test for CURIE short form provider


package org.jenkinsci.plugins.ghprb.rules;

import java.io.IOException;

import org.jvnet.hudson.test.JenkinsRule;

import com.cloudbees.plugins.flow.BuildFlow;

/**
 * @author mdelapenya (Manuel de la Peña)
 */
public class JenkinsRuleWithBuildFlow extends JenkinsRule {

	public BuildFlow createBuildFlowProject() throws IOException {
		return createBuildFlowProject(createUniqueProjectName());
	}

	public BuildFlow createBuildFlowProject(String name)
		throws IOException {

		return jenkins.createProject(BuildFlow.class, name);
	}

}

Support creating BuildFlow projects using a TestRule


package org.jdesktop.beans.editors;

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

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

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

        add(new PaintPicker());

        pack();
    }

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

Add demo for paint picker.


package net.imagej.ops.views;

import net.imagej.ops.view.ViewOps;
import net.imagej.ops.view.ViewOps.FlatIterable;
import net.imglib2.IterableInterval;
import net.imglib2.RandomAccessibleInterval;
import net.imglib2.view.Views;

import org.scijava.plugin.Plugin;

@Plugin(type = ViewOps.FlatIterable.class, name = ViewOps.FlatIterable.NAME)
public class DefaultFlatIterable<T> extends
		AbstractView<RandomAccessibleInterval<T>, IterableInterval<T>>
		implements
		FlatIterable<RandomAccessibleInterval<T>, IterableInterval<T>> {

	@Override
	public IterableInterval<T> compute(RandomAccessibleInterval<T> input) {
		return Views.flatIterable(input);
	}

}

Add default implementation of FlatIterable interface.


package bugIdeas;

import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;

import javax.annotation.meta.TypeQualifier;

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

public class Ideas_2011_01_17 {
    @Documented
    @TypeQualifier(applicableTo = Integer.class)
    @Retention(RetentionPolicy.RUNTIME)
    public @interface PK {
    }

    @PK int key = 17;
    @NoWarning("TQ")
    @PK int getKeyAsInt() {
        return key;
    }
    @NoWarning("TQ")
    @PK Integer getKeyAsInteger() {
        return key;
    }
    @NoWarning("TQ")
    void setKeyAsInt(@PK int key) {
        this.key = key;
    }
    @NoWarning("TQ")
    void setKeyAsInteger(@PK Integer key) {
        this.key = key;
    }
    @NoWarning("TQ")
    static void test(Ideas_2011_01_17 x, Ideas_2011_01_17 y) {
        x.setKeyAsInt(y.getKeyAsInt());
        x.setKeyAsInt(y.getKeyAsInteger());
        x.setKeyAsInteger(y.getKeyAsInt());
        x.setKeyAsInteger(y.getKeyAsInteger());
    }

}

Add test case for type qualifiers flowing across boxing/unboxing


package uk.org.taverna.scufl2.rdfxml;

import static org.junit.Assert.assertNotNull;

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

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

import uk.org.taverna.scufl2.api.ExampleWorkflow;
import uk.org.taverna.scufl2.api.container.WorkflowBundle;

public class TestProfileParser {
	private static final String PROFILE_RDF = "example/profile/tavernaWorkbench.rdf";

	protected ProfileParser profileParser = new ProfileParser();

	private URL profileUrl;

	private WorkflowBundle bundle;

	@Before
	public void loadProfileDocument() {
		profileUrl = getClass().getResource(PROFILE_RDF);
		assertNotNull("Could not find profile document " + PROFILE_RDF,
				profileUrl);
	}

	@Before
	public void prepareParserState() throws URISyntaxException {
		bundle = new ExampleWorkflow().makeWorkflowBundle();
		bundle.getProfiles().clear();
		bundle.setMainProfile(null);

		profileParser.getParserState().setLocation(URI.create("/"));
		profileParser.getParserState().push(bundle);
	}

	@Test
	public void testname() throws Exception {
		profileParser.readProfile(URI.create("/profile/tavernaWorkbench/"),
				URI.create("profile/tavernaWorkbench.rdf"),
				profileUrl.openStream());
	}
}

Test ProfileParser independently (by cheating on parserState)


/*
 * Copyright 2015 Adam Speakman
 *
 * 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 speakman.whatsshakingnz.network;

import android.test.AndroidTestCase;

/**
 * Created by Adam on 15-06-07.
 */
public class RequestManagerTest extends AndroidTestCase {

    public void testRequestLastNDaysWhenNoMostRecentEventDateIsAvailable() {

    }

    public void testRequestOnlyEventsSinceLastEventDate() {

    }

    public void testAllEventsAreProvidedToStore() {

    }

    public void testSpecificEventIsRetrieved() { // We can request updated/detailed info on a specific event, maybe?

    }

    public void testAllPagedEventsAreRetrieved() {

    }

    public void testLastEventTimeIsStored() {

    }

    public void testLastEventTimeIsNotUpdatedWhenFirstPageFails() {

    }

    public void testLastEventTimeIsStoredWhenASubsequentPageFails() {

    }

}

Test stubs for request manager


package replicant.spy;

import arez.Arez;
import java.util.HashMap;
import org.testng.annotations.Test;
import replicant.AbstractReplicantTest;
import static org.testng.Assert.*;

public class DataLoaderMessageProcessFailureEventTest
  extends AbstractReplicantTest
{
  @Test
  public void basicOperation()
  {
    final DataLoaderMessageProcessFailureEvent event =
      new DataLoaderMessageProcessFailureEvent( G.class, new Error( "Some ERROR" ) );

    assertEquals( event.getSystemType(), G.class );

    final HashMap<String, Object> data = new HashMap<>();
    Arez.context().safeAction( () -> event.toMap( data ) );

    assertEquals( data.get( "type" ), "DataLoader.MessageProcessFailure" );
    assertEquals( data.get( "systemType" ), "G" );
    assertEquals( data.get( "message" ), "Some ERROR" );
    assertEquals( data.size(), 3 );
  }

  @Test
  public void basicOperation_ThrowableNoMessage()
  {
    final DataLoaderMessageProcessFailureEvent event =
      new DataLoaderMessageProcessFailureEvent( G.class, new NullPointerException() );

    assertEquals( event.getSystemType(), G.class );

    final HashMap<String, Object> data = new HashMap<>();
    Arez.context().safeAction( () -> event.toMap( data ) );

    assertEquals( data.get( "type" ), "DataLoader.MessageProcessFailure" );
    assertEquals( data.get( "systemType" ), "G" );
    assertEquals( data.get( "message" ), "java.lang.NullPointerException" );
    assertEquals( data.size(), 3 );
  }

  enum G
  {
    G1
  }
}

Add test for DataLoaderMessageProcessFailureEvent spy event


package org.svetovid.demo;

import org.svetovid.io.Svetovid;
import org.svetovid.util.Stopwatch;

public class Laps {

    public static void main(String[] args) {

        // Start the stopwatch
        Stopwatch stopwatch = new Stopwatch();

        // Ask for numbers
        Double number;
        do {
            number = Svetovid.in.readDoubleBoxed("Enter a number [ENTER to stop]: ");
            stopwatch.lap();
        } while (number != null);

        // Print the statistics
        double[] times = stopwatch.getLapTimes();
        Svetovid.out.writeln("Time it took to enter individual numbers:");
        Svetovid.out.writeln(times);
        times = stopwatch.getTotalTimes();
        Svetovid.out.writeln("Total time it took before entering each number:");
        Svetovid.out.writeln(times);

    }
}

Add a demo for the Stopwatch lap measurement class


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

package com.polytech4A.cuttingstock.core.solver;

import com.polytech4A.cuttingstock.core.model.Solution;
import com.polytech4A.cuttingstock.core.resolution.util.Context;
import com.sun.istack.internal.NotNull;

/**
 * Created by Adrien CHAUSSENDE on 13/03/2015.
 *
 * @author Adrien CHAUSSENDE
 * @version 1.0
 *          <p/>
 *          Implementation of Simulated Annealing algorithm for the Cutting Stock problem. See more about the algorithm :
 *          http://en.wikipedia.org/wiki/Simulated_annealing
 */
public class SimulatedAnnealing extends Solver {

    /**
     * Limit number of iterations of the algorithm.
     */
    private long nbIterations;

    /**
     * Common ratio for decreasing the temperature through geometric progression.
     */
    private double mu;

    /**
     * Global time-varying parameter used in the algorithm.
     * See : http://en.wikipedia.org/wiki/Simulated_annealing#Acceptance_probabilities
     */
    private double temperature;

    @Override
    public Solution getSolution(@NotNull Solution solution, @NotNull Context context) {
        return null;
    }
}

Add Simulated Annealing structure. Not implemented.


package leetcode.two_sum;

import java.util.HashMap;

public class Solution {
    public int[] twoSum(int[] numbers, int target) {
    	HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
    	for(int i = 0; i < numbers.length; i++){
    		Integer pos = map.get(target - numbers[i]);
    		if(pos != null){
    			return new int[]{pos + 1, i + 1};
    		}else{
    			map.put(numbers[i], i);
    		}
    	}
    	return null;
    }

    public static void main(String[] args){
    	int[] ans = new Solution().twoSum(new int[]{6, 1, 999, 2, 5}, 3);;
    	System.err.println(ans[0] + ", " + ans[1]);
    }
}

Add java solution for 1. Two Sum


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

import rationals.properties.TraceEquivalent;
import junit.framework.TestCase;

public class TraceEquivalentTest extends TestCase {

    /**
     * Constructor for TraceEquivalentTest.
     * @param arg0
     */
    public TraceEquivalentTest(String arg0) {
        super(arg0);
    }

    public void testTraceEquivalentAutomata() {

    }

    public void testNonTraceEquivalentAutomata() throws NoSuchStateException {
    	Automaton<String, Transition<String>, TransitionBuilder<String>> a1 = new Automaton<>();
    	State s10 = a1.addState(true, false);
    	State s11 = a1.addState(false, true);
    	State s12 = a1.addState(false, false);
    	a1.addTransition(new Transition<>(s10, "P", s11));
    	a1.addTransition(new Transition<>(s11, "Q", s12));
    	a1.addTransition(new Transition<>(s11, "S", s11));
    	a1.addTransition(new Transition<>(s12, "R", s11));

    	Automaton<String, Transition<String>, TransitionBuilder<String>> a2 = new Automaton<>();
    	State s20 = a2.addState(true, false);
    	State s21 = a2.addState(false, true);
    	State s22 = a2.addState(false, false);
    	State s23 = a2.addState(false, false);
    	State s24 = a2.addState(false, false);
    	a2.addTransition(new Transition<>(s20, "P", s21));
    	a2.addTransition(new Transition<>(s21, "Q", s22));
    	a2.addTransition(new Transition<>(s23, "Q", s24));
    	a2.addTransition(new Transition<>(s22, "R", s23));
    	a2.addTransition(new Transition<>(s21, "S", s21));
    	a2.addTransition(new Transition<>(s23, "S", s21));
    	a2.addTransition(new Transition<>(s24, "R", s21));

    	// Note that a1 and a2 do not recognise the same languages, but are trace equivalent
    	TraceEquivalent<String, Transition<String>, TransitionBuilder<String>> equiv = new TraceEquivalent<>();
        assertTrue(equiv.test(a1, a2));
    }

}

Add MWE that for TraceEquivalence as a unit test.


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

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assume.assumeFalse;

import java.util.Collection;

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

import de.inetsoftware.jwebassembly.ScriptEngine;
import de.inetsoftware.jwebassembly.WasmRule;
import de.inetsoftware.jwebassembly.api.annotation.Export;

/**
 * Run some tests which not return static/fix values likes times or random value and which are difficult to compare.
 *
 * @author Volker Berlin
 *
 */
@RunWith( Parameterized.class )
public class DynamicValues {

    @ClassRule
    public static WasmRule rule = new WasmRule( TestClass.class );

    private final ScriptEngine script;

    public DynamicValues( ScriptEngine script ) {
        this.script = script;
    }

    @Parameters( name = "{0}" )
    public static Collection<ScriptEngine[]> data() {
        return ScriptEngine.testParams();
    }

    @Test
    public void currentTimeMillis() {
        assumeFalse( script == ScriptEngine.SpiderMonkey || script == ScriptEngine.SpiderMonkeyWat );
        long before = System.currentTimeMillis();
        String result = rule.evalWasm( script, "currentTimeMillis" );
        long after = System.currentTimeMillis();
        long val = Long.parseLong( result );
        assertTrue( before + "<=" + val + "<=" + after, before <= val && val <= after );
    }

    static class TestClass {

        @Export
        static long currentTimeMillis() {
            return System.currentTimeMillis();
        }
    }
}

Add a test for System.currentTimeMillis()


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

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

    private PDUByteBuffer byteBuffer;

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

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

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

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

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

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

Add unit test for PDUByteBuffer


package uk.gov.migration;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;

import org.flywaydb.core.api.migration.MigrationChecksumProvider;
import org.flywaydb.core.api.migration.jdbc.BaseJdbcMigration;

public class V__14_New_hashing_algorithm extends BaseJdbcMigration implements MigrationChecksumProvider {
    @Override
    public void migrate(Connection connection) throws Exception {
        Statement stmt = connection.createStatement();
        try {
            stmt.execute("alter table entry add column blob_hash varchar");
            stmt.execute("alter table entry_system add column blob_hash varchar");
            stmt.execute("alter table item add column blob_hash varchar");

            stmt.execute("update entry set blob_hash = sha256hex;");
            stmt.execute("update entry_system set blob_hash = sha256hex;");
            stmt.execute("update item set blob_hash = sha256hex;");

            stmt.execute("alter table item alter column blob_hash set not null");
        } finally {
            stmt.close();
        }
    }

    @Override
    public Integer getChecksum() {
        return 1;
    }
}

Add new column to represent the new item hashes


package com.jmatch;

import org.apache.commons.lang3.StringUtils;

/**
 * Uses single letters to represent variables in patterns.
 */
public class SingleVariablePatternMatcher implements Matcher {
    private final String pattern;

    /**
     * Constructs a new matcher with the given pattern. The pattern should consist of single letters to represent
     * variables in the pattern. E.g. "abba" is composed of the variables 'a' and 'b'.
     *
     * @param pattern the given pattern
     */
    public SingleVariablePatternMatcher(String pattern) {
        this.pattern = pattern;
    }

    @Override
    public boolean matches(String input) {
        return matchRemaining(pattern, input);
    }

    private boolean matchRemaining(String pattern, String input) {
        // If there is no more of the pattern left to match we need an empty input String to have matched the
        // original input.
        if (pattern.isEmpty()) {
            return input.isEmpty();
        }

        // Pick the first letter in the pattern as our current variable
        final String variable = Character.toString(pattern.charAt(0));
        // Count the number of times the variable occurs in the pattern
        final int numberOfVariableOccurrencesInPattern = StringUtils.countMatches(pattern, variable);

        // Greedily attempt to assign a value to the current variable
        for (int endIndex = input.length(); endIndex > 0; endIndex--) {
            final String variableAssignment = input.substring(0, endIndex);

            // Check to make sure that the proper number of occurrences of the assigned value exist in the input
            final int numberOfAssignmentOccurrencesInInput = StringUtils.countMatches(input, variableAssignment);
            if (numberOfAssignmentOccurrencesInInput == numberOfVariableOccurrencesInPattern) {
                // Check to see if the assignment leads to a valid match
                final boolean matchSuccessful = matchRemaining(pattern.replaceAll(variable, ""), input.replaceAll
                        (variableAssignment, ""));

                if (matchSuccessful) {
                    return true;
                }
            }
        }

        return false;
    }
}

Add single variable implementation of Matcher


package net.sectorsoftware.ygo.deck;

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

import java.io.Closeable;
import java.io.IOException;
import java.lang.RuntimeException;
import java.util.List;

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

public class UserTest
{
    static {
        System.loadLibrary("ygodeck-jni");
    }

    static class User_Fixture implements Closeable
    {
        public User_Fixture()
        {
            DB.setPath(System.getenv("CARD_DB_PATH"));
        }

        @Override
        public void close() throws IOException
        {
        }

    }

    private User_Fixture fixture;

    @Before
    public void setup()
    {
        fixture = new User_Fixture();
    }

    @After
    public void tearDown() throws IOException
    {
        fixture.close();
        fixture = null;
    }

    @Test
    public void Create()
    {
        User user = new User("Test", true);
        assertEquals(user.name(), "Test");
        user.delete();
    }

    @Test
    public void Open()
    {
        User user = new User("OpenTest", true);
        user.delete();
        User user2 = new User("OpenTest");
        assertEquals(user2.name(), "OpenTest");
        user.delete();
    }

    @Test
    public void Unknown()
    {
        try {
            User user = new User("NotKnown");
            assertEquals(0, 1);
        } catch (RuntimeException e) {
            assertEquals(1, 1);
        }
    }

    @Test
    public void Remove()
    {
        User user = new User("RemoveTest", true);
        assertEquals(user.name(), "RemoveTest");
        user.remove();
        user.delete();
        try {
            User user2 = new User("RemoveTest");
            assertEquals(0, 1);
        } catch (RuntimeException e) {
            assertEquals(1, 1);
        }
    }

}

Add unit tests for java User binding


package org.usfirst.frc.team2339.Barracuda.subsystems;

import edu.wpi.first.wpilibj.MotorSafety;
import edu.wpi.first.wpilibj.MotorSafetyHelper;
import edu.wpi.first.wpilibj.SpeedController;

/**
 * Class to provide swerve drive control to one wheel.
 * Wheel must have independent drive motor and steering motor.
 * A steering encoder provides feedback on wheel angle.
 * @author emiller
 *
 */
public class SwerveWheelDrive implements MotorSafety {

    protected MotorSafetyHelper m_safetyHelper;
    public static final double kDefaultExpirationTime = MotorSafety.DEFAULT_SAFETY_EXPIRATION;

    protected SpeedController m_driveController;

    SwerveWheelDrive() {
    	setupMotorSafety();
    }

    private void setupMotorSafety() {
        m_safetyHelper = new MotorSafetyHelper(this);
        this.setExpiration(kDefaultExpirationTime);
        this.setSafetyEnabled(true);
    }

	@Override
	public void setExpiration(double timeout) {
        m_safetyHelper.setExpiration(timeout);
	}

	@Override
	public double getExpiration() {
        return m_safetyHelper.getExpiration();
	}

	@Override
	public boolean isAlive() {
        return m_safetyHelper.isAlive();
	}

	@Override
	public void stopMotor() {
		m_driveController.set(0.0);
        if (m_safetyHelper != null) m_safetyHelper.feed();
	}

	@Override
	public void setSafetyEnabled(boolean enabled) {
        m_safetyHelper.setSafetyEnabled(enabled);
	}

	@Override
	public boolean isSafetyEnabled() {
        return m_safetyHelper.isSafetyEnabled();
	}

	@Override
	public String getDescription() {
		return "Swerve wheel drive";
	}

}

Create single wheel swerve drive subsystem.


package com.camillepradel.movierecommender.testscript;

import java.io.BufferedInputStream;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;

public class TestGetRecommendations {

	public static void main(String[] args) {

		String urlStart = "http://localhost:8080/MovieRecommender/recommendations?user_id=";
		int nbIterations = 100;
		int userId= 0;
		long startTime = System.nanoTime();

		for (int i= 0; i < nbIterations; i++) {

		    URL u;
		    InputStream is = null;
		    DataInputStream dis;

		    try
		    {
		      u = new URL(urlStart + userId);
		      is = u.openStream();
		      dis = new DataInputStream(new BufferedInputStream(is));
		      while ((dis.readLine()) != null)
		      {
		      }
		      System.out.println(i + "/" + nbIterations);
		    }
		    catch (MalformedURLException mue)
		    {
		      System.err.println("Ouch - a MalformedURLException happened.");
		      mue.printStackTrace();
		      System.exit(2);
		    }
		    catch (IOException ioe)
		    {
		      System.err.println("Oops- an IOException happened.");
		      ioe.printStackTrace();
		      System.exit(3);
		    }
		    finally
		    {
		      try
		      {
		        is.close();
		      }
		      catch (IOException ioe)
		      {
		      }
		    }
		}

		long endTime = System.nanoTime();
		System.out.println("Time to get " + nbIterations + " times recommendation page: " + (endTime - startTime) + "ns");

	}
}

Create script file to test app scalling capabilities.


/*
 * Copyright (C) 2015 Atanas Gegov
 *
 * 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.atanasg.fileprocessingapp.commands;

import java.util.List;

import com.atanasg.fileprocessingapp.command.status.CommandExecStatus;
import com.atanasg.fileprocessingapp.command.status.CommandFailed;
import com.atanasg.fileprocessingapp.command.status.CommandSuccessful;
import com.atanasg.fileprocessingapp.mvc.model.FileContentModel;
import com.atanasg.fileprocessingapp.mvc.view.FileProcessingAppView;

/**
 * Get the file content currently stored in the
 * {@link FileContentModel} and forward to the
 * {@link FileProcessingAppView} that shows it
 * to the user.
 *
 * @author Atanas Gegov
 */
public class PrintCommand extends AbstractCommand {

	public PrintCommand(FileContentModel fileContentModel,
			FileProcessingAppView userInterface) {
		super(fileContentModel, userInterface);
	}

	@Override
	public void execute() {
		CommandExecStatus printCommandStatus;

		userInterface.showInfoForCommandInProgress("Printing current content...");
		List<String> fileLines = fileContentModel.getFileContentAsFileLines();

		if(fileLines.isEmpty()) {
			printCommandStatus = new CommandFailed();
			printCommandStatus.appendDetailedInfo("No content found");
		} else {
			printCommandStatus = new CommandSuccessful();
			for(String line : fileLines) {
				printCommandStatus.appendDetailedInfo(line);
			}
		}
		userInterface.showCommandExecutionStatus(printCommandStatus);
	}

}

Add a new class for a print command


package com.orientechnologies.orient.graph.migration;

import java.util.List;

import com.orientechnologies.orient.core.db.document.ODatabaseDocumentTx;
import com.orientechnologies.orient.core.db.record.ridbag.ORidBag;
import com.orientechnologies.orient.core.record.impl.ODocument;
import com.orientechnologies.orient.core.sql.query.OSQLSynchQuery;
import com.orientechnologies.orient.core.type.tree.OMVRBTreeRIDSet;
import com.tinkerpop.blueprints.impls.orient.OrientVertex;

/**
 * In OrientDb 1.7-rc1 was introduced RidBag a new data structure for link management. Since OrientDB 1.7 RidBag is default data
 * structure for management relationships in graph. Use this class to upgrade graphs created under older versions of OrientDB.
 *
 * @author Artem Orobets
 */
public class ORidBagMigration {
  private final ODatabaseDocumentTx database;

  public ORidBagMigration(ODatabaseDocumentTx database) {
    this.database = database;
  }

  public void execute() {
    List<ODocument> vertexes = database.query(new OSQLSynchQuery<ODocument>("select from V"));

    for (ODocument vertex : vertexes) {
      for (String fieldName : vertex.fieldNames()) {
        if (fieldName.startsWith(OrientVertex.CONNECTION_IN_PREFIX) || fieldName.startsWith(OrientVertex.CONNECTION_OUT_PREFIX)) {
          Object oldValue = vertex.field(fieldName);
          if (oldValue instanceof OMVRBTreeRIDSet) {
            OMVRBTreeRIDSet oldTree = (OMVRBTreeRIDSet) oldValue;
            ORidBag bag = new ORidBag();
            bag.addAll(oldTree);

            vertex.field(fieldName, bag);
          }
        }
      }
    }
  }
}

Create migration from older version of graph


package net.imagej.ops.views;

import net.imagej.ops.view.ViewOps;
import net.imagej.ops.view.ViewOps.AddDimension;
import net.imglib2.RandomAccessible;
import net.imglib2.view.MixedTransformView;
import net.imglib2.view.Views;

import org.scijava.plugin.Plugin;

@Plugin(type = ViewOps.AddDimension.class, name = ViewOps.AddDimension.NAME)
public class DefaultAddDimension<T> extends
		AbstractView<RandomAccessible<T>, MixedTransformView<T>> implements
		AddDimension<RandomAccessible<T>, MixedTransformView<T>> {

	@Override
	public MixedTransformView<T> compute(RandomAccessible<T> input) {
		return Views.addDimension(input);
	}

}

Add default implementation of AddDimension interface.


package com.sharefile.api;

import com.sharefile.api.entities.*;

/**
 * The entities have non-static get* functions to build the queries. The auto-generated SDK does not want to change this.
 * lets simplify building the queries with the query builder class which holds static entity references so that the app does
 * not haver to  create a new entity object every time it needs to build a query.
 */
public class SFQueryBuilder
{
	public static final SFAccessControlsEntity ACCESS_CONTROL = new SFAccessControlsEntity();
	public static final SFAccountsEntity ACCOUNTS = new SFAccountsEntity();
	public static final SFAsyncOperationsEntity ASYNC_OPERATION = new SFAsyncOperationsEntity();
	public static final SFCapabilitiesEntity CAPABILITIES = new SFCapabilitiesEntity();
	public static final SFConfigsEntity CONFIG = new SFConfigsEntity();
	public static final SFFavoriteFoldersEntity FAVORITE_FOLDERS = new SFFavoriteFoldersEntity();
	public static final SFGroupsEntity GROUPS = new SFGroupsEntity();
	public static final SFItemsEntity ITEMS = new SFItemsEntity();
	public static final SFMetadataEntity METADATA = new SFMetadataEntity();
	public static final SFSessionsEntity SESSIONS = new SFSessionsEntity();
	public static final SFSharesEntity SHARES = new SFSharesEntity();
	public static final SFUsersEntity USERS = new SFUsersEntity();
}

Add the Query builder to the SDK


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

import android.os.Bundle;
import de.tel.moccha.entities.course.Course;
import de.tel.moccha.entities.course.CourseCategory;
import de.zell.android.util.fragments.EntityListFragment;
import java.util.List;

/**
 * Represents a factory for the course category list and course list fragments.
 * For a given content category the corresponding entity list fragment will be created
 * with the given list values.
 *
 * @author Christopher Zell <zelldon91@googlemail.com>
 */
public class ListFragmentFactory {

  /**
   * Creates for the given content category the corresponding entity list fragment.
   *
   * @param category the category which is chosen
   * @param values the values for the list view
   * @return the corresponding list view
   */
  public static EntityListFragment createListFragment(ContentCategories category, List values) {
    if (category == ContentCategories.CourseOfStudies) {
      return createCourseCategoryListFragment(values);
    } else if (category == ContentCategories.Courses) {
      return createCourseListFragment(values);
    } else {
      return null;
    }
  }

  /**
   * Creates for the course category list the corresponding course category list
   * fragment.
   *
   * @param categories the course categories
   * @return the corresponding list fragment
   */
  private static EntityListFragment createCourseCategoryListFragment(List categories) {
    EntityListFragment frg = new CourseCategoryListFragment();
    if (categories != null) {
      Bundle args = new Bundle();
      args.putSerializable(EntityListFragment.ARG_ENTITIES, categories.toArray(new CourseCategory[categories.size()]));
      frg.setArguments(args);
    }
    return frg;
  }

  /**
   * Creates for the course list the corresponding course list fragment.
   *
   * @param courses the courses
   * @return the corresponding list fragment
   */
  private static EntityListFragment createCourseListFragment(List courses) {
    EntityListFragment frg = new CourseListFragment();
    if (courses != null) {
      Bundle args = new Bundle();
      args.putSerializable(EntityListFragment.ARG_ENTITIES, courses.toArray(new Course[courses.size()]));
      frg.setArguments(args);
    }
    return frg;
  }

}

Create a list fragment view factory


package org.cache2k.impl;

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

/**
 * Specialization for 64 bit systems.
 */
public final class ClockProPlus64Cache<K, T>  extends ClockProPlusCache<K, T> {

  /**
   * Just increment the hit counter on 64 bit systems. Writing a 64 bit value is atomic on 64 bit systems
   * but not on 32 bit systems. Of course the counter update itself is not an atomic operation, which will
   * cause some missed hits. The 64 bit counter is big enough that it never wraps around in my projected
   * lifetime...
   */
  @Override
  protected void recordHit(Entry e) {
    e.hitCnt++;
  }

}

Switch to 64 bit implementation if 64 bit VM is detected. Fix previous commit.


package hex.tree.drf;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

import hex.tree.drf.DRFModel.DRFParameters;
import org.junit.Assume;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import water.*;
import water.fvec.Frame;
import water.parser.ParseSetup;

import static org.junit.Assert.assertNotNull;

/**
 * Based on a reproducer of a bug PUBDEV-7193 kindly provided by https://github.com/SimonSchmid
 */
@RunWith(Parameterized.class)
public class DRFConcurrent2Test extends TestUtil {

  private static final int REPEAT_N = 3;

  @Parameterized.Parameters
  public static Object[] repeated() { // emulating multiple runs
    return new Object[REPEAT_N];
  }

  @Parameterized.Parameter
  public Object run;

  @BeforeClass
  public static void setup() {
    stall_till_cloudsize(1);
  }

  @Test
  public void testConcurrent() throws Exception {
    Assume.assumeTrue(H2O.getCloudSize() == 1); // don't test in multi-node, not worth it - this tests already takes a long time
    Frame fr = null;
    try {
      fr = parse_test_file("./smalldata/jira/pubdev_7193.csv", new TestUtil.ParseSetupTransformer() {
        @Override
        public ParseSetup transformSetup(ParseSetup guessedSetup) {
          return guessedSetup.setCheckHeader(1);
        }
      });

      ExecutorService executor = Executors.newFixedThreadPool(2);
      List<Callable<DRFModel>> runnables = new ArrayList<>();
      for (int i = 0; i < 50; i++) {
        runnables.add(new DRFBuilder(fr));
      }
      for (Future<DRFModel> future : executor.invokeAll(runnables)) {
        assertNotNull(future.get());
      }
    } finally {
      if (fr != null)
        fr.delete();
    }
  }

  private static class DRFBuilder implements Callable<DRFModel> {

    private final Key<Frame> _train;

    private DRFBuilder(Frame trainingFrame) {
      _train = trainingFrame._key;
    }

    public DRFModel call() {
      DRFParameters params = new DRFParameters();
      params._response_column = "C2";
      params._train = _train;
      DRF builder = new DRF(params);
      DRFModel model = null;
      try {
        model = builder.trainModel().get();
      } finally {
        if (model != null) {
          model.delete();
        }
      }
      return model;
    }
  }
}

Add a test for race condition when DRF models are trained concurrently


package com.intellij.plugin.buck.actions;

import com.intellij.icons.AllIcons;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.project.DumbAwareAction;
import com.intellij.openapi.project.Project;
import com.intellij.plugin.buck.build.BuckBuildCommandHandler;
import com.intellij.plugin.buck.build.BuckBuildManager;
import com.intellij.plugin.buck.build.BuckCommand;

/**
 * Run buck kill command
 * It will force terminate all running buck commands and shut down the buck local http server
 */
public class BuckProjectAction extends DumbAwareAction {

    public static final String ACTION_TITLE = "Run buck project";
    public static final String ACTION_DESCRIPTION = "Run buck project command";

    public BuckProjectAction() {
        super(ACTION_TITLE, ACTION_DESCRIPTION, AllIcons.Actions.Compile);
    }

    @Override
    public void update(AnActionEvent e) {
        Project project = e.getProject();
        if (project != null) {
            e.getPresentation().setEnabled(!BuckBuildManager.getInstance(project).isBuilding());
        }
    }

    @Override
    public void actionPerformed(final AnActionEvent e) {
        BuckBuildManager buildManager = BuckBuildManager.getInstance(e.getProject());
        String target = buildManager.getCurrentSavedTarget(e.getProject());

        if (target == null) {
            buildManager.showNoTargetMessage(e.getProject());
            return;
        }

        BuckBuildCommandHandler handler = new BuckBuildCommandHandler(
                e.getProject(),
                e.getProject().getBaseDir(),
                BuckCommand.PROJECT);
        handler.command().addParameter(target);
        buildManager.runBuckCommand(handler, ACTION_TITLE);
    }
}

Add support for buck project command