package com.webtimer.timer;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class ClearUserComments
 */
@WebServlet("/ClearUserComments")
public class ClearUserComments extends HttpServlet {
	private static final long serialVersionUID = 1L;

    /**
     * @see HttpServlet#HttpServlet()
     */
    public ClearUserComments() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		CountdownTimer.clearComments();
		RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/timer");
		dispatcher.forward(request,response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}

}

Add url to clear user comments

Add url to clear user comments


public class LongestSubstringWithoutRepeatingCharacters {
    public static int lengthOfLongestSubstring(String s) {
        // keep track of the index of the last occured character
        int[] lastIndexOf = new int[256];
        for (int i = 0; i < 255; i++) lastIndexOf[i] = -1;
        // keep track of the left bound of the current longest substring
        int left = 0;
        int maxLen = 0, curLen = 0;

        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            if (lastIndexOf[c] >= left) left = lastIndexOf[c] + 1;
            curLen = i - left + 1;
            if (maxLen < curLen) maxLen = curLen;
            lastIndexOf[c] = i;
        }
        return maxLen;
    }

    public static void main(String[] args) {
        System.out.println(lengthOfLongestSubstring("hello world"));
        System.out.println(lengthOfLongestSubstring("aaaaa"));
    }
}

Complete Longest Substring Without Repeating Characters


package study.hard.javalib.nativelib;

import java.math.BigDecimal;

import org.junit.Test;

public class BicDecimal {

	@Test
	public void testToDevide() {
		BigDecimal a = new BigDecimal(110000);
		BigDecimal b = new BigDecimal(1.1);
		System.out.println(a.divide(b, 3, BigDecimal.ROUND_UP)); // 100000.000
		System.out.println(a.divide(b, 3, BigDecimal.ROUND_DOWN)); // 99999.999
	}

}

Add a test case to check BigDecimal

Add a test case to check BigDecimal


package leetcode.interleaving_string;

import java.util.LinkedList;
import java.util.Queue;

public class Solution {
	public static class PossibleState{
		int len1;
		int len2;
		public PossibleState(int len1, int len2){
			this.len1 = len1;
			this.len2 = len2;
		}
	}
    public boolean isInterleave(String s1, String s2, String s3) {
    	if(s1.length() + s2.length() != s3.length()) return false;
    	boolean[][] possible = new boolean[s1.length() + 1][s2.length() + 1];
    	Queue<PossibleState> queue = new LinkedList<PossibleState>();
    	possible[0][0] = true;
    	queue.offer(new PossibleState(0, 0));
    	while(!queue.isEmpty()){
    		PossibleState state = queue.remove();
    		int totalLen = state.len1 + state.len2;
    		if(totalLen == s3.length()) return true;
    		if(state.len1 < s1.length()){
    			if(!possible[state.len1 + 1][state.len2]){
    				if(s1.charAt(state.len1) == s3.charAt(totalLen)){
    					possible[state.len1 + 1][state.len2] = true;
    					queue.offer(new PossibleState(state.len1 + 1, state.len2));
    				}
    			}
    		}
    		if(state.len2 < s2.length()){
    			if(!possible[state.len1][state.len2 + 1]){
    				if(s2.charAt(state.len2) == s3.charAt(totalLen)){
    					possible[state.len1][state.len2 + 1] = true;
    					queue.offer(new PossibleState(state.len1, state.len2 + 1));
    				}
    			}
    		}
    	}
    	return false;
    }

    public static void main(String[] args){
    	System.err.println(new Solution().isInterleave("abccc", "deffg", "adeffgbccc"));
    }
}

Add java solution for 97. Interleaving String

97. Interleaving String: https://leetcode.com/problems/interleaving-string/


package com.m3rcuriel.controve.util;

import static org.junit.Assert.assertEquals;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;

import org.junit.Test;

public class CSVWriterTest {

	@Test
	public void testWriter() throws IOException {
		File f = new File("test.txt");
		CSVWriter writer = new CSVWriter(f, "head1", "head2");
		BufferedReader fr = new BufferedReader(new FileReader(f));
		assertEquals(fr.readLine(), "head1,head2");
		writer.writeLine(0, 1);
		assertEquals(fr.readLine(), "0,1");
		f.delete();
	}

}

Add unit test for CSVWriter

Add unit test for CSVWriter


package leetcode.edit_distance;

public class Solution {
    public int minDistance(String word1, String word2) {
    	char[] char1 = word1.toCharArray();
    	char[] char2 = word2.toCharArray();
    	int[][] table = new int[char1.length + 1][char2.length + 1];
    	for(int i = 0; i < char1.length + 1; i++){
    		for(int j = 0; j < char2.length + 1; j++){
    			if(i == 0){
    				if(j == 0){
    					table[i][j] = 0;
    				}else{
    					table[i][j] = table[i][j - 1] + 1;
    				}
    			}else{
    				if(j == 0){
    					table[i][j] = table[i - 1][j] + 1;
    				}else{
    					if(char1[i - 1] == char2[j - 1]){
    						table[i][j] = table[i - 1][j - 1];
    					}else{
    						int min = table[i - 1][j - 1] + 1;
    						if(min > table[i - 1][j] + 1) min = table[i - 1][j] + 1;
    						if(min > table[i][j - 1] + 1) min = table[i][j - 1] + 1;
    						table[i][j] = min;
    					}
    				}
    			}
    		}
    	}
    	return table[char1.length][char2.length];
    }

    public static void main(String[] args){
    	System.err.println(new Solution().minDistance("ahello", "hello"));
    }
}

Add java solution for 72. Edit Distance

Add java solution for 72. Edit Distance

72. Edit Distance: https://leetcode.com/problems/edit-distance/


package arez.integration.computed_value;

import arez.Arez;
import arez.ArezContext;
import arez.annotations.ArezComponent;
import arez.annotations.Computed;
import arez.annotations.DepType;
import arez.integration.AbstractArezIntegrationTest;
import arez.integration.util.TestSpyEventHandler;
import arez.spy.ActionCompletedEvent;
import arez.spy.ActionStartedEvent;
import arez.spy.ComputableValueDeactivatedEvent;
import arez.spy.ComputeCompletedEvent;
import arez.spy.ComputeStartedEvent;
import arez.spy.ObservableValueChangedEvent;
import arez.spy.TransactionCompletedEvent;
import arez.spy.TransactionStartedEvent;
import javax.annotation.Nonnull;
import org.testng.annotations.Test;
import static org.testng.Assert.*;

public class ComputedNoReportResultTest
  extends AbstractArezIntegrationTest
{
  @Test
  public void scenario()
    throws Throwable
  {
    final ArezContext context = Arez.context();

    final Element element = Element.create();

    final TestSpyEventHandler recorder = new TestSpyEventHandler();
    context.getSpy().addSpyEventHandler( recorder );

    safeAction( element::getComputed );

    recorder.assertEventCount( 10 );
    recorder.assertNextEvent( ActionStartedEvent.class );
    recorder.assertNextEvent( TransactionStartedEvent.class );

    recorder.assertNextEvent( ComputeStartedEvent.class );
    recorder.assertNextEvent( TransactionStartedEvent.class );

    recorder.assertNextEvent( ObservableValueChangedEvent.class );

    recorder.assertNextEvent( TransactionCompletedEvent.class );
    recorder.assertNextEvent( ComputeCompletedEvent.class, a -> assertNull( a.getResult() ) );
    recorder.assertNextEvent( ComputableValueDeactivatedEvent.class );

    recorder.assertNextEvent( TransactionCompletedEvent.class );
    recorder.assertNextEvent( ActionCompletedEvent.class );
  }

  @ArezComponent
  static abstract class Element
  {
    @Nonnull
    static Element create()
    {
      return new ComputedNoReportResultTest_Arez_Element();
    }

    @Computed( reportResult = false, depType = DepType.AREZ_OR_NONE )
    @Nonnull
    String getComputed()
    {
      return "";
    }
  }
}

Add integration test to verify no results are reported if asked not to


/*
 * 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.usergrid.rest.exceptions;

import com.google.android.gcm.server.InvalidRequestException;

import javax.ws.rs.NotFoundException;
import javax.ws.rs.core.Response;
import javax.ws.rs.ext.Provider;

import static javax.ws.rs.core.Response.Status.*;

@Provider
public class GCMInvalidRequestExceptionMapper extends AbstractExceptionMapper<InvalidRequestException> {

    @Override
    public Response toResponse( InvalidRequestException e ) {

        Response.Status status;
        String message;
        // purposely overwrite the 401 case
        if(e.getHttpStatusCode() == 401){

            status = UNAUTHORIZED;
            message = "Invalid GCM API Key or Registration ID(s)";

        }else{
            // let's handle the status codes ourselves and pass-through the details from GCM
            if (e.getHttpStatusCode() >= 400 && e.getHttpStatusCode() <= 499){
                status = BAD_REQUEST;
            }else{
                status = INTERNAL_SERVER_ERROR;
            }
            message = "GCM Status Code: "+ e.getHttpStatusCode()+", Detail: "+e.getMessage();
        }

        return toResponse( status, message );
    }
}

Add exception mapper for GCM library InvalidRequest exception.


package me.alivecode.algs4;

import edu.princeton.cs.algs4.StdIn;

public class Quick3way {

    private Quick3way() {}

    private static void sort(Comparable[] a, int lo, int hi) {
        if (hi <= lo) return;
        int i = lo + 1;
        int lt = lo, gt = hi;
        Comparable v = a[lo];

        while(i <= gt) {
            int cmp = a[i].compareTo(v);
            // lt always points to the left most item valued 'v'.
            // Move smaller items to the left side of 'v'.
            // This operation inserted an item to the left of lt and i,
            // increase lt and i to give one slot to that item.
            if (cmp < 0) { SortUtil.exch(a, lt++, i++); }
            // Move larger items to the right side of 'v'
            else if (cmp > 0) { SortUtil.exch(a, i, gt--); }
            // current item equal to 'v', move to the next item.
            else { i++; }
        }

        sort(a, lo, lt-1);
        sort(a, gt+1, hi);

        assert SortUtil.isSorted(a, lo, hi);
    }

    public static void sort(Comparable[] a) {
        StdRandom.shuffle(a);
        sort(a, 0, a.length-1);
        assert SortUtil.isSorted(a);
    }

    public static void main(String[] args) {
        String[] a = StdIn.readAllStrings();
        SortUtil.show(a);
        sort(a);
        SortUtil.show(a);
    }
}

Add quick 3 way sort.

Add quick 3 way sort.


package leetcode.sum_root_to_leaf_numbers;

import common.TreeNode;

public class Solution {
	int ans;

	public void dfs(TreeNode cur, int val){
		val = val * 10 + cur.val;
		if(cur.left == null && cur.right == null){
			ans += val;
		}else{
			if(cur.left != null){
				dfs(cur.left, val);
			}
			if(cur.right != null){
				dfs(cur.right, val);
			}
		}
	}

	public int sumNumbers(TreeNode root) {
		if(root == null) return 0;
		ans = 0;
		dfs(root, 0);
		return ans;
	}

	public static void main(String[] args){
		TreeNode root = new TreeNode(1);
		root.left = new TreeNode(3);
		root.right = new TreeNode(5);
		root.left.left = new TreeNode(7);
		System.err.println(new Solution().sumNumbers(root));
	}
}

Add java solution for 129. Sum Root to Leaf Numbers

129. Sum Root to Leaf Numbers: https://leetcode.com/problems/sum-root-to-leaf-numbers/


package org.picocontainer.doc.tutorial.blocks;

import junit.framework.TestCase;

import org.picocontainer.MutablePicoContainer;
import org.picocontainer.defaults.CachingComponentAdapter;
import org.picocontainer.defaults.ConstructorInjectionComponentAdapter;
import org.picocontainer.defaults.DefaultPicoContainer;
import org.picocontainer.defaults.InstanceComponentAdapter;
import org.picocontainer.doc.introduction.Apple;
import org.picocontainer.doc.introduction.Juicer;
import org.picocontainer.doc.introduction.Peeler;

/**
 * Test case for the snippets used in "Component Adapters and Factories"
 * @author Jörg Schaible
 */
public class BuildingBlocksTestCase extends TestCase {
    public void testRegisterConvenient() {
        // START SNIPPET: register-convenient
        MutablePicoContainer picoContainer = new DefaultPicoContainer();
        picoContainer.registerComponentImplementation(Juicer.class);
        picoContainer.registerComponentImplementation("My Peeler", Peeler.class);
        picoContainer.registerComponentInstance(new Apple());
        // END SNIPPET: register-convenient
        // START SNIPPET: register-direct
        picoContainer.registerComponent(new InstanceComponentAdapter("Another Apple", new Apple()));
        // END SNIPPET: register-direct
    }

    public void testRegisterEquivalentConvenient() {
        MutablePicoContainer picoContainer = new DefaultPicoContainer();
        // START SNIPPET: register-equivalent-convenient
        picoContainer.registerComponentImplementation(Juicer.class);
        // END SNIPPET: register-equivalent-convenient
    }

    public void testRegisterEquivalentAtLength() {
        MutablePicoContainer picoContainer = new DefaultPicoContainer();
        // START SNIPPET: register-equivalent-at-length
        picoContainer.registerComponent(
                new CachingComponentAdapter(
                        new ConstructorInjectionComponentAdapter(
                                Juicer.class, Juicer.class, null)));
        // END SNIPPET: register-equivalent-at-length
    }
}

Add first version of tutorial for CAs.

Add first version of tutorial for CAs.

git-svn-id: 39c93fb42c3fce26a4768237af3b74bd47e2a670@2558 ac66bb80-72f5-0310-8d68-9f556cfffb23


package leetcode.spiral_matrix_ii;

public class Solution {
    public int[][] generateMatrix(int n) {
    	int[][] ans = new int[n][n];
    	if(n == 0) return ans;
    	int height = n;
    	int width = n;
    	int number = 1;
        int x = 0, y = 0;
        ans[0][0] = number++;
        int boundl = -1, boundr = width;
        int boundu = -1, boundd = height;
        while(boundl <= boundr && boundu <= boundd){
        	while(y + 1 < boundr){
        		ans[x][y + 1] = number++;
        		y++;
        	}
        	boundu++;
        	if(boundu + 1 == boundd) break;
        	while(x + 1 < boundd){
        		ans[x + 1][y] = number++;
        		x++;
        	}
        	boundr--;
        	if(boundr - 1 == boundl) break;
        	while(y - 1 > boundl){
        		ans[x][y - 1] = number++;
        		y--;
        	}
        	boundd--;
        	if(boundd - 1 == boundu) break;
        	while(x - 1 > boundu){
        		ans[x - 1][y] = number++;
        		x--;
        	}
        	boundl++;
        	if(boundl + 1 == boundr) break;
        }
    	return ans;
    }

    public static void main(String[] args){
    	int[][] ans = new Solution().generateMatrix(10);
    	for(int[] x : ans){
    		for(int y : x){
    			System.err.print(y + " ");
    		}
    		System.err.println("");
    	}
    }
}

Add java solution for 59. Spiral Matrix II

59. Spiral Matrix II: https://leetcode.com/problems/spiral-matrix-ii/


/*
 * #%L
 * ImageJ software for multidimensional image processing and analysis.
 * %%
 * Copyright (C) 2014 - 2015 Board of Regents of the University of
 * Wisconsin-Madison, University of Konstanz and Brian Northan.
 * %%
 * 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 net.imagej.ops.eval;

import static org.junit.Assert.assertEquals;

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

import net.imagej.ops.AbstractOpTest;
import net.imagej.ops.Ops.Eval;

import org.junit.Test;

/**
 * Tests {@link Eval}.
 *
 * @author Curtis Rueden
 */
public class EvalTest extends AbstractOpTest {

	@Test
	public void testMath() {
		final Map<String, Object> vars = new HashMap<String, Object>();
		vars.put("a", 2);
		vars.put("b", 3);
		vars.put("c", 5);

		assertEquals(7, ops.eval("a+c", vars));
		assertEquals(3, ops.eval("c-a", vars));
		assertEquals(6, ops.eval("a*b", vars));
		assertEquals(2, ops.eval("c/a", vars));
		assertEquals(1, ops.eval("c%a", vars));
		assertEquals(17, ops.eval("a+b*c", vars));
	}

}

Add a simple unit test for eval op

Add a simple unit test for eval op


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

package imagej.ext.plugin;

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

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

	// -- Fields --

	private boolean canceled;
	private String message;

	// -- ModulePreprocessor methods --

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

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

	// -- ModuleProcessor methods --

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

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

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

}

Add preprocessor that verifies module validity

This ensures that invalid modules (e.g., with duplicate or final
parameter fields) do not pretend to run successfully.


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

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

import java.io.File;

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

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

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

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

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

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

Add standalone test to upload SOPAC site logs


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

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

import org.junit.Test;

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

public class AutoIdentifierMySQLTest extends AbstractMySQLIntegrationTest {

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

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

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

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

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

        private String title;

        public Post() {}

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

Add test for MySQL AUTO identifier

Add test for MySQL AUTO identifier


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

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

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

public class AttributeList {

	private Class clazz;
	private List<Property> attributes;

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

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

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

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

		return attributes;
	}

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

		return null;
	}

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

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

			//TODO skip explicit redefinitions

		}

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

}

Add SubclassEditorDialog, generalized from RIM clone editor.


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

import java.util.List;

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

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

public abstract class AbstractJavaType extends RegularType implements JavaType {

	protected List<Member> _implicitMemberCache;

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

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

	protected abstract List<Member> buildImplicitMembersCache();

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

}

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


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

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

import java.io.*;

public class OOperationResponseTest {

  @Test
  public void testSerialize() throws IOException {

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

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

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

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

  }
}

Add serialization tests for OOperationResponse


package eu.xenit.de.testing.actions;

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

@Component
public class TestAction {

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

}

Add action to test bundle

DEVEM-499: Add action to test bundle


package de.retest.recheck.review.ignore;

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

import org.junit.jupiter.api.Test;

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

class ExcludeFilterIT {

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

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

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

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

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

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

Add integration test to handle multiple excludes


package org.springframework.site.test;

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

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

	public FakeGithubService() {
		super(null);
	}

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

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

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

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

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


package com.salsaw.msalsa;

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

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

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

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

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

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

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

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

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

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

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

        formLayout.setSizeUndefined();

		setCompositionRoot(formLayout);
	}

}

[ADD] Add class to create UI of Salsa Parameters


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

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

    private PDUByteBuffer byteBuffer;

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

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

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

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

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

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

Add unit test for PDUByteBuffer

Add unit test for PDUByteBuffer


package reactfx;

import static org.junit.Assert.*;

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

import org.junit.Test;

public class InterceptableEventStreamTest {

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

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

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

Add tests for interceptable streams.

Add tests for interceptable streams.


import org.junit.*;

public class QueueTest {

  Queue q;

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

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

  @Test
  public void testIsEmptyOnEmpty() {

  }

  @Test
  public void testIsEmpty() {

  }

  @Test
  public void testHasCapacityOnEmpty() {

  }

  @Test
  public void testHasCapacityOnFull() {

  }

  @Test
  public void testEnqueueOnEmpty() {

  }

  @Test
  public void testEnqueueOnFull() {

  }

  @Test
  public void testDequeueOnEmpty() {

  }

  @Test
  public void testDequeueOnFull() {

  }
}

Add Queue skeleton test cases.

Add Queue skeleton test cases.


package MWC.GUI;

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

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

}

Introduce marker annotation for methods that have changed the data structure

git-svn-id: d2601f1668e3cd2de409f5c059006a6eeada0abf@2065 cb33b658-6c9e-41a7-9690-cba343611204


package com.github.booknara.cryptographic;

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

public class CryptographicHashFunction {

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

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

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

    }

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

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

        return formatter.toString();
    }
}

Add a cryptographic hash function main file


/*******************************************************************************
 * Mission Control Technologies, Copyright (c) 2009-2012, United States Government
 * as represented by the Administrator of the National Aeronautics and Space
 * Administration. All rights reserved.
 *
 * The MCT platform is licensed under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * http://www.apache.org/licenses/LICENSE-2.0.
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 *
 * MCT includes source code licensed under additional open source licenses. See
 * the MCT Open Source Licenses file included with this distribution or the About
 * MCT Licenses dialog available at runtime from the MCT Help menu for additional
 * information.
 *******************************************************************************/
package gov.nasa.arc.mct.scenario.component;

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

import java.util.Collections;

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

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

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

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

		return created;
	}

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

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

Add decorator for repository save

[Scenario] Add decorator for repository save

Activity Type and Tag components created via the Create
menu need to appear in specific repositories by default.
The added class can be used to decorate their wizard
UIs to ensure that this happens.


package com.thegongoliers.output;

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

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

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

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

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

}

Add several driving control functions

Add several driving control functions


public class Solution {

    public int hammingDistance(int x, int y) {

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

        while (xor != 0) {

            xor &= xor - 1;
            distance++;

        }

        return distance;

    }

}

Create : 461 Hamming Distance

Create : 461 Hamming Distance


package org.graphwalker.core.model;

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

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

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

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


package ieg.util.xml;

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

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

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

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

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

    private GregorianCalendar cal;
    private DatatypeFactory factory;

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

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

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

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

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

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

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

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


package com.google.sps.servlets;

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

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

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

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

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

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

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

  }
}

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


package beaform.search;

import java.util.concurrent.Callable;

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

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

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

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

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

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

}

Add test for searching a formula by name


package me.prettyprint.cassandra.service;

import static org.junit.Assert.*;

import org.junit.Test;

public class CassandraClientTest {

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

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

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

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

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

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

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

}

Add a basic test case, that just fails

Add a basic test case, that just fails


public class Solution {

    public int singleNumber(int[] nums) {

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

		        singleNum ^= nums[i];

        }

	      return singleNum;

    }

}

Create : 136 Single Number

Create : 136 Single Number


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

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

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

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

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

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

    private final HttpServerAuthenticationMechanismFactory delegate;

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

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

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

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

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

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

[ELY-1984] Add a wrapper HttpServerAuthenticationMechanismFactory that sets the peer address using the current authentication request


package org.mutabilitydetector;

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

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

public class TestMatchers {

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

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

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

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

		};
	}

}

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

git-svn-id: ed609ce04ec9e3c0bc25e071e87814dd6d976548@228 c7a0535c-eda6-11de-83d8-6d5adf01d787


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

package org.gradle.integtests.fixtures;

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

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

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

This is intended to be temporarily applied to tests for features that should work both with and without instant execution, and should be removed once there is some cross-cutting coverage for all integration tests.


package it.near.sdk;

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

import com.google.common.collect.Maps;

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

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

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

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

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

@RunWith(MockitoJUnitRunner.class)
public class RecipeCoolerTest {

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

    Recipe criticalRecipe;

    @Before
    public void init() {

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

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

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

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

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

    }

    @Test
    public void whenRecipeShown_historyUpdated() {

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

    }

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

}

Add unit test class for recipe cooler.

Add unit test class for recipe cooler.


package com.verybadalloc.designlib.adapters;

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

import com.verybadalloc.designlib.views.BooksListFragmentBuilder;

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

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

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

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

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

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

Add adapter used for tab layout

Add adapter used for tab layout


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

package de.muspellheim.flowdesign;

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

 *
{@link #build()}

 *
{@link #bind()}

 *
{@link #inject()}

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

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

 *

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

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

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

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

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

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

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

}

Add template to create flow

Add template to create flow


package committools.data;

import org.eclipse.jgit.lib.PersonIdent;

import com.google.common.base.Objects;

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

	public final String name;

	public final String emailUsername;

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

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

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

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

}

Use git blame to find faction mememberships


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

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

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

		return head;
	}

	public class ListNode {
		int val;
		ListNode next;

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

}

Remove Duplicates From Sorted List

AC: Remove Duplicates From Sorted List

linkedlist delete.


package slicktest;

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

public class SlickTest extends BasicGame
{
    private TiledMap testMap;

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

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

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

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

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

Add test for Slick graphics library.

Add test for Slick graphics library.


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

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

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

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

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

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

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

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

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

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

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

    System.out.println();

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

Use accessor methods to set and get private members

http://ideone.com/zGwg4G


package pinterest;

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

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

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

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

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

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

        return uriBuilder.build();
    }

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

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

        return uriBuilder.build();
    }

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

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

        return uriBuilder.build();
    }

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

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

        return uriBuilder.build();
    }

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

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

        return uriBuilder.build();
    }
}

Move end point URI builder to separate class


package net.restlesscoder.sandbox;

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

public class ZipArrays {

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

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

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

Add Java implementation of Python's zip function


package org.msf.records.ui.userlogin;

import android.test.ActivityInstrumentationTestCase2;

import org.msf.records.R;

import java.util.Date;

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

public class UserLoginActivityTest extends
        ActivityInstrumentationTestCase2<UserLoginActivity> {

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

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

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

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


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

package com.dmdirc.util.annotations.observable;

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

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

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

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

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

}

Add annotation for observable generation.

Change-Id: Ie9fb9bb54b9f7e97a8538de7970795eb13955c32


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

package io.spine.core;

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

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

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

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

Add a test for message origins

Add a test for message origins


package net.restlesscoder.sandbox;

import java.io.IOException;

public class GenericThrows {

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

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

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

Add example of throws clause w/ generic parameter


package com.growthbeat.model;

import static org.junit.Assert.fail;

import org.junit.Test;

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

public class ActionTest extends BaseTest {

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

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

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

}

Add test of Action model

Add test of Action model


package org.twig.functional;

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

import java.util.HashMap;

public class RenderTests {
    private Environment environment;

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

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

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

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

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

Add functional tests for text & basic print statement


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

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

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

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

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

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

   * The question mark (?) matches one character.

   *

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

}

[CFG-7] Complete implementation of config master

Add regex utils for wildcard handling


package com.agiliq.android.moreappslib;

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

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

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

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

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

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

            gridCell.setTag(holder);
        }

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

        return gridCell;
    }

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

Add adapter class for the custom layout

Add adapter class for the custom layout


package com.catchoom.examples.glass;

import java.util.ArrayList;

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

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

public class ResultActivity extends Activity{

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

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

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

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

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

	}
}

Add activity that shows the results

Add activity that shows the results


package com.k13n.lt_codes;

public final class ErasureChannel {
  private final double erasureProbability;

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

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

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

Add erasure channel class, mostly for testing purposes


package leetcode.best_time_to_buy_and_sell_stock;

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

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

121. Best Time to Buy and Sell Stock: https://leetcode.com/problems/best-time-to-buy-and-sell-stock/


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

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

    private int[][] board;

    // Corner refers to top left of board

    private int topX;
    private int topY;

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

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

}

class CantSeeSquareException extends Exception {}

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


package net.openhft.chronicle.queue;

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

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

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

    public interface SomeListener {

        void methodWithoutParams();

        void methodWithOneParam(int i);
    }

    public static class SomeManager implements SomeListener {

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

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

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

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

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

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

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

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

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

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

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

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

Test for issue with invokation of method without parameters


package org.jdesktop.swingx.painter;

import org.jdesktop.beans.AbstractBeanInfoTest;

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

Add bean test for AlphaPainter.

Add bean test for AlphaPainter.

git-svn-id: 9c6ef37dfd7eaa5a3748af7ba0f8d9e7b67c2a4c@3838 1312f61e-266d-0410-97fa-c3b71232c9ac