import java.io.FileInputStream;

import org.docx4j.convert.in.Doc;
import org.docx4j.openpackaging.packages.WordprocessingMLPackage;

public class DocToPDFConverter extends DocxToPDFConverter {

	public DocToPDFConverter(String inputFilePath, String outputFilePath) {
		super(inputFilePath, outputFilePath);
	}

	@Override
	protected WordprocessingMLPackage getMLPackage(FileInputStream iStream) throws Exception{
	    WordprocessingMLPackage mlPackage = Doc.convert(iStream);
		return mlPackage;
	}

}

import java.io.FileInputStream;
import java.io.OutputStream;
import java.io.PrintStream;

import org.docx4j.convert.in.Doc;
import org.docx4j.openpackaging.packages.WordprocessingMLPackage;

public class DocToPDFConverter extends DocxToPDFConverter {

	public DocToPDFConverter(String inputFilePath, String outputFilePath) {
		super(inputFilePath, outputFilePath);
	}

	@Override
	protected WordprocessingMLPackage getMLPackage(FileInputStream iStream) throws Exception{
		PrintStream originalStdout = System.out;

		//Disable stdout temporarily as Doc convert produces alot of output
		System.setOut(new PrintStream(new OutputStream() {
			public void write(int b) {
				//DO NOTHING
			}
		}));
		WordprocessingMLPackage mlPackage = Doc.convert(iStream);

		System.setOut(originalStdout);
		return mlPackage;
	}

}

Disable stdout when convert doc to docx

Disable stdout when convert doc to docx


package com.tlswe.awsmock.ec2.servlet;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;

import com.tlswe.awsmock.ec2.control.MockEC2QueryHandler;

@RunWith(PowerMockRunner.class)
@PrepareForTest({MockEC2QueryHandler.class, HttpServletRequest.class, HttpServletResponse.class})
public class MockEc2EndpointServletTest {

    @Mock
    HttpServletRequest request;

    @Mock
    HttpServletResponse response;

    @Mock
    MockEC2QueryHandler handler;

    Map<String, String[]> queryParams = new HashMap<String, String[]>();

    @Before
    public void doSetup(){
      PowerMockito.mockStatic(MockEC2QueryHandler.class);
      Mockito.when(MockEC2QueryHandler.getInstance()).thenReturn(handler);
      Mockito.when(request.getParameterMap()).thenReturn(queryParams);
    }

    @Test
    public void Test_doPost() throws IOException{
        MockEc2EndpointServlet mockEc2EndpointServlet = new MockEc2EndpointServlet();
        mockEc2EndpointServlet.doPost(request, response);
    }

    @Test
    public void Test_doGet() throws IOException{
        MockEc2EndpointServlet mockEc2EndpointServlet = new MockEc2EndpointServlet();
        mockEc2EndpointServlet.doPost(request, response);
    }

}

Add JUnit tests for MockEc2EndpointServlet


/*
Copyright (c) 2014, Colorado State University
All rights reserved.

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 holder 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 galileo.test.graph;

import org.junit.runner.RunWith;
import org.junit.runners.Suite;
import org.junit.runners.Suite.SuiteClasses;

@RunWith(Suite.class)
@SuiteClasses({
    FeaturePathQuery.class,
})
public class TestSuite { }

Add test suite for graph classes

Add test suite for graph classes


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

package com.exorath.service.treasurehunt.test;

import com.amazonaws.services.dynamodbv2.AmazonDynamoDBClient;
import com.amazonaws.services.dynamodbv2.document.DynamoDB;
import com.exorath.service.commons.dynamoDBProvider.DynamoDBProvider;
import com.exorath.service.treasurehunt.Service;
import com.exorath.service.treasurehunt.Treasure;
import com.exorath.service.treasurehunt.dynamodb.DynamoDBService;
import org.junit.Assert;
import org.junit.Test;

import java.util.UUID;

public class DynamoDBServiceTest {

	@Test
	public void testGetTreasuresEqualsSetTreasures() {
		UUID playerId = UUID.randomUUID();
		Service srv = new DynamoDBService(getDynamoDBProvider());
		srv.setTreasure(playerId, "testTreasure1");
		srv.setTreasure(playerId, "testTreasure2");
		srv.setTreasure(playerId, "testTreasure3");
		srv.setTreasure(playerId, "testTreasure4");

		Treasure[] treasures = srv.getTreasures(playerId);
		Assert.assertEquals(treasures.length, 4);

		boolean testTreasuse1AccountFor = false;
		boolean testTreasuse2AccountFor = false;
		boolean testTreasuse3AccountFor = false;
		boolean testTreasuse4AccountFor = false;
		for (Treasure t : treasures) {
			if (t.getId().equals("testTreasure1")) {
				testTreasuse1AccountFor = true;
			} else if (t.getId().equals("testTreasure2")) {
				testTreasuse2AccountFor = true;
			} else if (t.getId().equals("testTreasure3")) {
				testTreasuse3AccountFor = true;
			} else if (t.getId().equals("testTreasure4")) {
				testTreasuse4AccountFor = true;
			}
		}
		Assert.assertTrue(testTreasuse1AccountFor && testTreasuse2AccountFor && testTreasuse3AccountFor && testTreasuse4AccountFor);
	}

	private DynamoDBProvider getDynamoDBProvider() {
		AmazonDynamoDBClient client = new AmazonDynamoDBClient().withEndpoint("http://localhost:8000");
		DynamoDB db = new DynamoDB(client);
		return () -> db;
	}
}

Create test for DynamoDBService functionality


package org.pdxfinder.controllers;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class ShutDownHook implements ApplicationContextAware {

    private ApplicationContext context;

    @PostMapping("/shutdown")
    public void shutdownContext() {
        ((ConfigurableApplicationContext) context).close();
    }

    @Override
    public void setApplicationContext(ApplicationContext ctx) throws BeansException {
        this.context = ctx;

    }
}

Add shut down hook for properly shutting down the admin app


/*
 * See LICENSE file in distribution for copyright and licensing information.
 */
package seph.lang.ast;

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

import seph.lang.SephObject;
import seph.lang.Text;

/**
 * @author Ola Bini
 */
public class LiteralMessageTest {
    @Test
    public void ensure_class_exists() {
        assertEquals("seph.lang.ast.LiteralMessage", seph.lang.ast.LiteralMessage.class.getName());
    }

    @Test
    public void is_a_seph_object() {
        assertTrue("A LiteralMessage should be a SephObject", new LiteralMessage(null, null) instanceof SephObject);
    }

    @Test
    public void is_a_message() {
        assertTrue("A LiteralMessage should be a Message", new LiteralMessage(null, null) instanceof Message);
    }

    @Test
    public void has_a_next_pointer() {
        Message one = new LiteralMessage(null, null);
        LiteralMessage two = new LiteralMessage(null, one);
        assertSame(one, two.next());
    }

    @Test
    public void has_a_name_based_one_the_literal_class() {
        LiteralMessage msg = new LiteralMessage(new Text("foo"), null);
        assertEquals("<literal:seph.lang.Text>", msg.name());
    }

    @Test
    public void has_an_empty_list_of_arguments() {
        LiteralMessage msg = new LiteralMessage(null, null);
        assertArrayEquals(new Message[0], msg.arguments());
    }

    @Test
    public void with_next_returns_a_new_object_with_the_same_literal() {
        SephObject lit = new Text("bar");
        LiteralMessage msg = new LiteralMessage(lit, null);
        assertSame(lit, msg.withNext(null).literal());
    }

    @Test
    public void with_next_returns_a_new_object_with_a_new_next() {
        Message expected = new LiteralMessage(null, null);
        LiteralMessage msg = new LiteralMessage(null, null);
        assertSame(expected, msg.withNext(expected).next());
    }

    @Test
    public void literal_returns_the_literal_given() {
        SephObject lit = new Text("bar");
        LiteralMessage msg = new LiteralMessage(lit, null);
        assertSame(lit, msg.literal());
    }

    @Test
    public void is_literal_returns_true() {
        LiteralMessage msg = new LiteralMessage(null, null);
        assertTrue(msg.isLiteral());
    }
}// LiteralMessageTest

Add tests for literal messages

Add tests for literal messages


//
// Mass_Importer.java
//

import ij.IJ;
import ij.gui.YesNoCancelDialog;
import ij.io.DirectoryChooser;
import ij.plugin.PlugIn;
import java.io.File;
import java.util.HashSet;
import java.util.Vector;
import loci.formats.FilePattern;
import loci.formats.ImageReader;
import loci.plugins.LociImporter;

/**
 * Processes all image files in the chosen directory,
 * grouping files with similar names.
 *
 * @author Curtis Rueden ctrueden at wisc.edu
 */
public class Mass_Importer implements PlugIn {

  public void run(String arg) {
    // prompt user for directory to process
    DirectoryChooser dc = new DirectoryChooser("Bio-Formats Mass Importer");
    String dirPath = dc.getDirectory();

    // create a list of files we have already processed
    HashSet done = new HashSet();

    // image reader object, for testing whether a file is in a supported format
    ImageReader tester = new ImageReader();

    // list of files to actually open with Bio-Formats Importer
    Vector filesToOpen = new Vector();

    // process all files in the chosen directory
    File dir = new File(dirPath);
    File[] files = dir.listFiles();
    IJ.showStatus("Scanning directory");
    for (int i=0; i<files.length; i++) {
      String id = files[i].getAbsolutePath();
      IJ.showProgress((double) i / files.length);

      // skip files that have already been processed
      if (done.contains(id)) continue;

      // skip unsupported files
      if (!tester.isThisType(id, false)) continue;

      // use FilePattern to group files with similar names
      String name = files[i].getName();
      FilePattern fp = new FilePattern(name, dirPath);

      // get a list of all files part of this group, and mark them as done
      String[] used = fp.getFiles();
      for (int j=0; j<used.length; j++) done.add(used[j]);

      filesToOpen.add(id);
    }
    IJ.showProgress(1.0);
    IJ.showStatus("");

    // confirm that user wants to proceed in opening the file groups
    int numToOpen = filesToOpen.size();
    if (numToOpen == 0) {
      IJ.showMessage("No file groups found.");
      return;
    }
    String groups = numToOpen == 1 ?
      "1 file group" : (numToOpen + " file groups");
    YesNoCancelDialog confirm = new YesNoCancelDialog(IJ.getInstance(),
      "Bio-Formats Mass Importer", "Found " + groups + " in directory '" +
      dirPath + "'; proceed?");
    if (!confirm.yesPressed()) return;

    // launch the Bio-Formats Importer plugin to open each group of files
    for (int i=0; i<numToOpen; i++) {
      String id = (String) filesToOpen.get(i);
      String params =
        "location=[Local machine] " +
        "windowless=true " +
        "group_files=true " +
        "open=[" + id + "] ";
      new LociImporter().run(params);
    }
    IJ.showStatus("");
  }

}

Add "Bio-Formats Mass Importer" example plugin.


package sonata.kernel.placement.monitor;

import com.fasterxml.jackson.annotation.JsonProperty;

public class MonitorStats {

    /* current
    {"NET_out": "648 B", "MEM_used": "1.07 MiB", "PIDS": "3", "NET_in": "1.596 kB",
    "MEM_limit": "15.67 GiB", "CPU": "0.00%", "MEM_%": "0.01%"}
    */
    /* experimental
    {'NET_out': [], 'CPU_%': 0.0, 'MEM_used': 1101824, 'PIDS': 4,
    'NET_in': ['Total', '0'], 'SYS_time': 1479224676000000000L, 'MEM_limit': 16827117568, 'MEM_%': 6.54790694572272e-05}
    */
    /* new
    {'MEM_used': 790528, 'PIDS': 2, 'BLOCK_out': [], 'NET_out': 648,
     'SYS_time': 1479522691737230080L, 'MEM_limit': 16827117568,
     'NET_in': 648, 'BLOCK_in': ['Total', '0'], 'MEM_%': 4.6979406710947397e-05, 'CPU_%': 0.0}
    */

    @JsonProperty("NET_out")
    String netOut;
    @JsonProperty("NET_in")
    String netIn;
    @JsonProperty("MEM_used")
    String memoryUsed;
    @JsonProperty("PIDS")
    String processIds;
    @JsonProperty("MEM_limit")
    String memoryLimit;
    @JsonProperty("CPU")
    String cpu;
    @JsonProperty("MEM_%")
    String memoryPercentage;

    public String getNetOut() {
        return netOut;
    }

    public void setNetOut(String netOut) {
        this.netOut = netOut;
    }

    public String getNetIn() {
        return netIn;
    }

    public void setNetIn(String netIn) {
        this.netIn = netIn;
    }

    public String getMemoryUsed() {
        return memoryUsed;
    }

    public void setMemoryUsed(String memoryUsed) {
        this.memoryUsed = memoryUsed;
    }

    public String getProcessIds() {
        return processIds;
    }

    public void setProcessIds(String processIds) {
        this.processIds = processIds;
    }

    public String getMemoryLimit() {
        return memoryLimit;
    }

    public void setMemoryLimit(String memoryLimit) {
        this.memoryLimit = memoryLimit;
    }

    public String getCpu() {
        return cpu;
    }

    public void setCpu(String cpu) {
        this.cpu = cpu;
    }

    public String getMemoryPercentage() {
        return memoryPercentage;
    }

    public void setMemoryPercentage(String memoryPercentage) {
        this.memoryPercentage = memoryPercentage;
    }
}

Add monitor statistics class for json mapping


package com.github.dkanellis.fikey.storage;

import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import com.yubico.u2f.data.DeviceRegistration;

import java.util.*;

/**
 * @author Dimitris
 */
public class DataStorage<T, K, V> {

    private LoadingCache<T, Map<K, V>> users;
    private Map<K, V> requests;

    public DataStorage() {
        this.requests = new HashMap<>();
        this.users = CacheBuilder.newBuilder().build(new CacheLoader<T, Map<K, V>>() {
            @Override
            public Map<K, V> load(T key) throws Exception {
                return new HashMap<>();
            }
        });
    }

    public void addRequest(K key, V value) {
        requests.put(key, value);
    }

    public V removeRequest(K key) {
        return requests.remove(key);
    }

    public void addDeviceToUser(T username, K key, V value) {
        users.getUnchecked(username).put(key, value);
    }

    public Iterable<DeviceRegistration> getDevicesFromUser(T username) {
        List<DeviceRegistration> registrations = new ArrayList<>();
        for (V serialized : getSerializedDevices(username)) {
            registrations.add(DeviceRegistration.fromJson((String) serialized));
        }
        return registrations;
    }

    private Collection<V> getSerializedDevices(T username) {
        return users.getUnchecked(username).values();
    }

}

Add user and device storage

Add user and device storage


package leetcode.candy;

import java.util.ArrayList;

public class Solution {
    public int candy(int[] ratings) {
        if(ratings == null || ratings.length == 0) return 0;
        int n = ratings.length;
        ArrayList<Integer> minimals = new ArrayList<Integer>();
        for(int i = 0; i < n; i++){
        	if((i == 0 || ratings[i - 1] >= ratings[i]) && (i == n - 1 || ratings[i + 1] >= ratings[i])){
        		minimals.add(i);
        	}
        }
        int[] candies = new int[n];
        for(int minimal : minimals){
        	candies[minimal] = 1;
        	for(int i = minimal + 1; i < n && ratings[i] > ratings[i - 1]; i++){
        		if(candies[i] < candies[i - 1] + 1){
        			candies[i] = candies[i - 1] + 1;
        		}
        	}
        	for(int i = minimal - 1; i >= 0 && ratings[i] > ratings[i + 1]; i--){
        		if(candies[i] < candies[i + 1] + 1){
        			candies[i] = candies[i + 1] + 1;
        		}
        	}
        }
        int sum = 0;
        for(int x : candies){
        	sum += x;
        }
        return sum;
    }

    public static void main(String[] args){
    	System.err.println(new Solution().candy(new int[]{-1, 0, 1, 2, 3, 4, 4, 2, 1, 0}));
    }
}

Add java solution for 135. Candy

Add java solution for 135. Candy

135. Candy: https://leetcode.com/problems/candy/


package org.jboard.jboard.sandbox;

public class Uncaught
{

	public static void main(String[] args)
	{
		Thread.currentThread().setUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler()
		{

			@Override
			public void uncaughtException(Thread t, Throwable e)
			{
				System.out.println("Hello world!");

			}
		});

		throw new RuntimeException("Hello kitty.");

		//System.out.println("Bye Bye");

	}

}

Add a class to the sandbox

Add a class to the sandbox


package de.retest.recheck.ui.diff;

import static de.retest.recheck.ui.diff.ElementDifferenceFinder.getNonEmptyDifferences;
import static java.util.Collections.singletonList;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;

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

import org.junit.Test;

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

public class ElementDifferenceFinderTest {

	@Test
	public void getNonEmptyDifferences_should_be_robust() {
		getNonEmptyDifferences( null );
		getNonEmptyDifferences( new ArrayList<>() );
	}

	@Test
	public void getNonEmptyDifferences_should_handle_empty_element_diffs() {
		final List<Difference> empty = new ArrayList<>();
		empty.add( new ElementDifference() );
		assertThat( getNonEmptyDifferences( empty ) ).hasSize( 0 );
	}

	@Test
	public void getNonEmptyDifferences_should_ignore_attribute_diffs() {
		final List<AttributeDifference> attributeDiff = new ArrayList<>();
		attributeDiff.add( new AttributeDifference( "text", "Mark", "Karl" ) );
		final AttributesDifference attributeDifference = new AttributesDifference( attributeDiff );
		assertThat( getNonEmptyDifferences( singletonList( attributeDifference ) ) ).hasSize( 0 );
	}

	@Test
	public void getNonEmptyDifferences_should_return_nonempty_differences() throws Exception {
		final List<AttributeDifference> attributeDiff = new ArrayList<>();
		attributeDiff.add( new AttributeDifference( "text", "Mark", "Karl" ) );
		final AttributesDifference attributeDifference = new AttributesDifference( attributeDiff );
		final List<Difference> nonempty = new ArrayList<>();
		nonempty.add( new ElementDifference( mock( Element.class ), attributeDifference, null, null, null,
				new ArrayList<>() ) );
		assertThat( getNonEmptyDifferences( nonempty ) ).hasSize( 1 );
	}

}

Add test and move easy to move methods...


package org.uma.jmetal.qualityIndicator;

import org.uma.jmetal.util.VectorUtils;
import org.uma.jmetal.util.checking.Check;

/**
 * @author Antonio J. Nebro <antonio@lcc.uma.es>
 *
 */
public abstract class QualityIndicator {
  protected double[][] referenceFront = null;

  /**
   * Default constructor
   */
  public QualityIndicator() {
  }

  /**
   * Constructor
   * @param referenceFrontFile
   */
  public QualityIndicator(String referenceFrontFile) {
    setReferenceFront(referenceFrontFile);
  }

  /**
   * Constructor
   * @param referenceFront
   */
  public QualityIndicator(double[][] referenceFront) {
    this.referenceFront = referenceFront;
  }

  public abstract double compute(double[][] front) ;

  public void setReferenceFront(String referenceFrontFile) {
    Check.isNotNull(referenceFrontFile);

    referenceFront = VectorUtils.readVectors(referenceFrontFile);
  }

  public void setReferenceFront(double[][] referenceFront) {
    this.referenceFront = referenceFront;
  }

  /**
   * This method returns true if lower indicator values are preferred and false otherwise
   *
   * @return
   */
  public abstract boolean isTheLowerTheIndicatorValueTheBetter();

  public double[][] getReferenceFront() {
    return referenceFront;
  }

  public abstract String getName() ;
  public abstract String getShortName() ;
}

Add new package in jmetal-experimental

Add new package in jmetal-experimental


package com.easternedgerobotics.rov.io.joystick;

import com.easternedgerobotics.rov.test.TestEventPublisher;
import com.easternedgerobotics.rov.value.VideoFlipValueA;
import com.easternedgerobotics.rov.value.VideoFlipValueB;

import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;
import org.mockito.Matchers;
import org.mockito.Mockito;
import rx.Observable;
import rx.observers.TestSubscriber;
import rx.schedulers.TestScheduler;
import rx.subjects.TestSubject;

import java.util.Arrays;
import java.util.Collection;
import java.util.function.Function;

@RunWith(Parameterized.class)
public final class JoystickControllerButtonTest {
    @Parameters(name = "Joystick button #{0} should emit a value of {1}")
    public static Collection<Object[]> data() {
        return Arrays.asList(new Object[][] {
            {JoystickController.CAMERA_A_VIDEO_FLIP_JOYSTICK_BUTTON, VideoFlipValueA.class},
            {JoystickController.CAMERA_B_VIDEO_FLIP_JOYSTICK_BUTTON, VideoFlipValueB.class},
        });
    }

    private final int index;

    private final Class clazz;

    public JoystickControllerButtonTest(final int index, final Class clazz) {
        this.index = index;
        this.clazz = clazz;
    }

    @SuppressWarnings("unchecked")
    @Test
    public void buttonPressDoesEmitSingleValueOfCorrectType() {
        final TestScheduler scheduler = new TestScheduler();
        final TestSubscriber subscriber = new TestSubscriber();
        final TestSubject subj = TestSubject.create(scheduler);
        final TestEventPublisher eventPublisher = new TestEventPublisher(scheduler);
        final JoystickController joystickController = new JoystickController(eventPublisher, Function.identity());

        final Joystick joystick = Mockito.mock(Joystick.class);
        Mockito.when(joystick.axes())
            .thenReturn(Observable.never());
        Mockito.when(joystick.button(Matchers.intThat(argument -> !argument.equals(index))))
            .thenReturn(Observable.never());
        Mockito.when(joystick.button(Mockito.eq(index)))
            .thenReturn(subj);

        joystickController.onNext(joystick);

        eventPublisher.valuesOfType(clazz).subscribe(subscriber);
        subj.onNext(Joystick.BUTTON_DOWN);
        subj.onNext(Joystick.BUTTON_UP);
        scheduler.triggerActions();

        subscriber.assertValueCount(1);
        Assert.assertTrue("Emitted type is not correct", subscriber.getOnNextEvents().get(0).getClass().equals(clazz));
    }
}

Add joystick controller button tests

Add joystick controller button tests


/**
 *
 */
package com.github.podd.sensors.test;

import static org.junit.Assert.*;

import java.io.ByteArrayOutputStream;
import java.io.IOException;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.restlet.representation.Representation;
import org.restlet.resource.ClientResource;

/**
 * @author ans025
 *
 */
public class SensorGetTest
{

    /**
     * @throws java.lang.Exception
     */
    @Before
    public void setUp() throws Exception
    {
    }

    /**
     * @throws java.lang.Exception
     */
    @After
    public void tearDown() throws Exception
    {
    }

    @Test
    public void testGet() throws Exception
    {
        final ClientResource clientResource = new ClientResource("http://152.83.198.37/TC_LOG00.CSV");

        final Representation representation = clientResource.get();

        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        representation.write(outputStream);

    }

}

Add experimental sensor access test code


package com.davidmogar.njc.syntactic;

import java.lang.reflect.Field;

public abstract class Tokens {

    /* Primitive types */
    public static final int CHARACTER = 257;
    public static final int DOUBLE = 258;
    public static final int INTEGER = 259;
    public static final int VOID = 260;

    /* Control flow */
    public static final int IF = 270;
    public static final int WHILE = 271;

    /* Other reserved words */
    public static final int MAIN = 290;
    public static final int RETURN = 291;

    public static String getTokenNameByValue(int value) {
        String token = "";

        try {
            for (Field field : Tokens.class.getFields()) {
                if ((int) field.get(new Integer(0)) == value) {
                    token = field.getName();
                }
            }
        } catch (IllegalAccessException e) {
            // Just ignore it
        }

        return token;
    }
}

Add a class to hold all possible tokens

Add a class to hold all possible tokens


package edu.usc.glidein.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

import org.globus.gsi.GlobusCredential;
import org.globus.gsi.GlobusCredentialException;

public class CredentialUtil
{
	public static void save(GlobusCredential credential, File file)
	throws IOException
	{
		// Create the file if it doesn't exist
		file.createNewFile();

		// Change file permissions
		CommandLine chmod = new CommandLine();
		chmod.setExecutable(new File("/bin/chmod"));
		chmod.addArgument("600");
		chmod.addArgument(file.getAbsolutePath());
		chmod.execute();
		int exitCode = chmod.getExitCode();
		if(exitCode != 0){
			throw new IOException(
					"Unable to change proxy permissions\n\n"+
					"Stdout:\n"+chmod.getOutput()+
					"Stderr:\n"+chmod.getError());
		}

		// Save the credential to the file
		FileOutputStream pstream =
			new FileOutputStream(file);
		credential.save(pstream);
		pstream.close();
	}

	public static GlobusCredential load(File file)
	throws IOException
	{
		try {
			FileInputStream fis = new FileInputStream(file);
			GlobusCredential cred = new GlobusCredential(fis);
			fis.close();
			return cred;
		} catch (GlobusCredentialException gce) {
			IOException ioe = new IOException("Invalid credential");
			ioe.initCause(gce);
			throw ioe;
		}
	}
}

Add credential util to store and load GlobusCredentials from files. Automatically changes permissions of file.

git-svn-id: bdb5f82b9b83a1400e05d69d262344b821646179@1380 e217846f-e12e-0410-a4e5-89ccaea66ff7


package com.raychenon.licensedroid.license;

/**
 * @author Raymond Chenon
 * https://opensource.org/licenses/BSD-2-Clause
 */
public class BSD2License extends LicenseInfos{
    @Override
    public String getName() {
        return "SD 2-Clause \"Simplified\" or \"FreeBSD\" license";
    }

    @Override
    public String getShortDescription() {
        return "All rights reserved.\n" +
                "\n" +
                "Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:\n" +
                "\n" +
                "1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.\n" +
                "\n" +
                "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.\n" +
                "\n" +
                "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 HOLDER 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.";
    }

    public String getCopyrightFormat() {
        return String.format("Copyright (c) %s, %s", YEAR, COPYRIGHT_HOLDER);
    }

}

Add the BSD 2-Clause "Simplified" or "FreeBSD" license


package com.jayway.maven.plugins.android.standalonemojos;

import com.jayway.maven.plugins.android.*;
import io.takari.maven.testing.TestResources;
import io.takari.maven.testing.executor.MavenExecutionResult;
import io.takari.maven.testing.executor.MavenInstallations;
import io.takari.maven.testing.executor.MavenRuntime;
import io.takari.maven.testing.executor.MavenVersions;
import io.takari.maven.testing.executor.junit.MavenJUnitTestRunner;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;

import java.io.File;

/**
 * Test the lint mojo. Tests options' default values and parsing. Tests the parameters passed to lint.
 *
 * @author Stéphane Nicolas <snicolas@octo.com>
 * @author Benoit Billington
 *
 */
@RunWith( MavenJUnitTestRunner.class )
@MavenInstallations( {"target/maven-installation/apache-maven-3.2.3"} )
@MavenVersions( {"3.0.5", "3.2.3"} )
public class LintMojoIntegrationTest
{
    @Rule
    public final TestResources resources = new TestResources();

    public final MavenRuntime verifier;

    public LintMojoIntegrationTest(MavenRuntime.MavenRuntimeBuilder builder)
    throws Exception
    {
        this.verifier = builder.withCliOptions( "-X" ).build();
    }

    /**
     * Test project with skip lint flag to true
     *
     * @throws Exception
     */
    @Test
    public void testSkipConfig() throws Exception
    {
        File basedir = resources.getBasedir( "lint-config-project0" );
        MavenExecutionResult result = verifier
                .forProject(basedir)
                .execute( PluginInfo.getQualifiedGoal( "lint" ) );

        result.assertErrorFreeLog();

        result.assertLogText( "Skipping lint analysis" );
    }

    /**
     * Tests execution of Lint
     *
     * @throws Exception
     */
    @Test
    public void testDefaultUnskippedLintConfig() throws Exception
    {
        File basedir = resources.getBasedir( "lint-config-project1" );
        MavenExecutionResult result = verifier
                .forProject(basedir)
                .execute( PluginInfo.getQualifiedGoal( "lint" ) );

        result.assertErrorFreeLog();

        result.assertLogText( "Lint analysis completed successfully" );
    }

}

Add basic Lint integration tests

Add basic Lint integration tests


/*
 * 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.beam.sdk.util;

import static org.hamcrest.Matchers.containsString;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;

import org.junit.Test;

/**
 * Tests for {@link ReleaseInfo}.
 */
public class ReleaseInfoTest {

  @Test
  public void getReleaseInfo() throws Exception {
    ReleaseInfo info = ReleaseInfo.getReleaseInfo();

    // Validate name
    assertThat(info.getName(), containsString("Beam"));

    // Validate semantic version
    String version = info.getVersion();
    String pattern = "\\d+\\.\\d+\\.\\d+.*";
    assertTrue(
        String.format("%s does not match pattern %s", version, pattern),
        version.matches(pattern));
  }
}

Add a test of ReleaseInfo

Add a test of ReleaseInfo


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

import com.google.common.collect.ImmutableMap;
import io.trino.testing.BaseDynamicPartitionPruningTest;
import io.trino.testing.QueryRunner;
import org.intellij.lang.annotations.Language;

import java.util.List;

import static java.lang.String.format;
import static java.util.stream.Collectors.joining;

public class TestHiveDynamicPartitionPruningTest
        extends BaseDynamicPartitionPruningTest
{
    @Override
    protected QueryRunner createQueryRunner()
            throws Exception
    {
        return HiveQueryRunner.builder()
                .setExtraProperties(EXTRA_PROPERTIES)
                .setHiveProperties(ImmutableMap.of("hive.dynamic-filtering-probe-blocking-timeout", "1h"))
                .setInitialTables(REQUIRED_TABLES)
                .build();
    }

    @Override
    protected void createLineitemTable(String tableName, List<String> columns, List<String> partitionColumns)
    {
        @Language("SQL") String sql = format(
                "CREATE TABLE %s WITH (format = 'TEXTFILE', partitioned_by=array[%s]) AS SELECT %s FROM tpch.tiny.lineitem",
                tableName,
                partitionColumns.stream().map(column -> "'" + column + "'").collect(joining(",")),
                String.join(",", columns));
        getQueryRunner().execute(sql);
    }
}

Add back test for Hive dynamic filtering of partition


package cgeo.geocaching.utils;

import java.net.URLEncoder;

/**
 * Utilities used for translating
 */
public final class TranslationUtils {

    private static final String translationWebsite = "http://translate.google.com/";
    private static final String translationAutoSelect = "#auto";
    private static final String translationFieldSeparator = "|";

    /**
     * Build a URI for Google Translate
     *
     * @param toLang
     *            The two-letter lowercase ISO language codes as defined by ISO 639-1
     * @param text
     *            The text to be translated
     * @return URI ready to be parsed
     */
    public static String buildTranslationURI(final String toLang, final String text) {
        return translationWebsite + translationAutoSelect + translationFieldSeparator + toLang + translationFieldSeparator + URLEncoder.encode(text).replace("+", "%20");
    }

}

Add translation utility class. Adds method to build a URI for Google Translate.


package io.github.Cnly.Crafter.Crafter.utils;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Collection;

import org.bukkit.Bukkit;
import org.bukkit.entity.Player;

public class CompatUtils
{

    @SuppressWarnings("unchecked")
    public static Collection<Player> getOnlinePlayers()
    {

        Method m;
        Object obj = null;
        try
        {
            m = Bukkit.class.getMethod("getOnlinePlayers");
            obj = m.invoke(null, (Object[])null);
        }
        catch (NoSuchMethodException | SecurityException
                | IllegalAccessException | IllegalArgumentException
                | InvocationTargetException e)
        {
            throw new RuntimeException(
                    "Cannot invoke Bukkit.getOnlinePlayers()", e);
        }

        if (obj instanceof Player[])
        {
            return Arrays.asList((Player[])obj);
        }
        else if (obj instanceof Collection)
        {
            return (Collection<Player>)obj;
        }
        else
        {
            throw new RuntimeException(
                    "Unknown getOnlinePlayers() return type!");
        }

    }

}

Add a getOnlinePlayers() that support both old and new ones


/**
 * Copyright (C) 2016 Joshua Auerbach
 *
 * 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 test;

import java.io.BufferedReader;
import java.io.File;
import java.io.InputStream;
import java.io.InputStreamReader;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.FileEntity;
import org.apache.http.impl.client.HttpClients;

/**
 * Just a test that we are able to communicate with the EncodingService at localhost:9879
 */
public class TestEncodingService {
	public static void main(String[] args) throws Exception {
		FileEntity entity = new FileEntity(new File(args[0]));
		HttpClient client = HttpClients.createDefault();
		HttpPost post = new HttpPost("http://localhost:9879");
		entity.setContentType("text/plain");
		post.setEntity(entity);
		HttpResponse resp = client.execute(post);
		int code = resp.getStatusLine().getStatusCode();
		if (code == HttpStatus.SC_OK) {
			HttpEntity answer = resp.getEntity();
			InputStream s = answer.getContent();
			BufferedReader rdr = new BufferedReader(new InputStreamReader(s));
			String line = rdr.readLine();
			while (line != null) {
				System.out.println(line);
				line = rdr.readLine();
			}
			rdr.close();
			s.close();
		} else
			System.out.println(resp.getStatusLine());
	}
}

Add Java test for encoding service (only for testing).


package edu.northwestern.bioinformatics.studycalendar.domain;

import edu.northwestern.bioinformatics.studycalendar.testing.StudyCalendarTestCase;
import org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean;
import org.hibernate.mapping.PersistentClass;
import org.hibernate.annotations.GenericGenerator;
import org.hibernate.annotations.Parameter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Iterator;

/**
 * @author Rhett Sutphin
 */
public class OracleCompatibilityTest extends StudyCalendarTestCase {
    private final Logger log = LoggerFactory.getLogger(getClass());

    @SuppressWarnings({ "unchecked" })
    public void testAllConfiguredSequencesLessThan30Characters() throws Exception {
        AnnotationSessionFactoryBean sessionFactoryBean
            = (AnnotationSessionFactoryBean) getDeployedApplicationContext().getBean("&sessionFactory");
        Iterator<PersistentClass> mappedClasses = sessionFactoryBean.getConfiguration().getClassMappings();
        while (mappedClasses.hasNext()) {
            PersistentClass pc =  mappedClasses.next();
            Class<?> clazz = pc.getMappedClass();
            GenericGenerator generator = clazz.getAnnotation(GenericGenerator.class);
            if (generator == null) {
                log.debug("{} has no declared generator", clazz.getName());
                continue;
            }
            Parameter sequence = null;
            for (Parameter parameter : generator.parameters()) {
                if ("sequence".equals(parameter.name())) {
                    sequence = parameter; break;
                }
            }
            if (sequence == null) {
                fail("Generator for " + clazz.getName() + " has no sequence parameter");
            }
            assertTrue("Oracle sequence for " + clazz.getName() + " is too long: " + sequence.value() + " (" + sequence.value().length() + " chars). It must be no more than 30 characters. Bering will generate an appropriately named sequence; be sure to configure the same one in the class annotation.",
                sequence.value().length() <= 30);
        }
    }
}

Test for checking that all configured (in the annotations) sequences for oracle are less than 30 characters


package edu.ntnu.idi.goldfish;

import edu.ntnu.idi.goldfish.configurations.Config;
import edu.ntnu.idi.goldfish.configurations.Lynx;
import edu.ntnu.idi.goldfish.mahout.DBModel;
import edu.ntnu.idi.goldfish.preprocessors.Preprocessor;
import edu.ntnu.idi.goldfish.preprocessors.PreprocessorStat;
import org.apache.mahout.cf.taste.model.DataModel;
import org.apache.mahout.cf.taste.recommender.Recommender;

public class Timing {

    public int i = 1;

    public static DataSet set;

	// disable Mahout logging output
	static {
		 System.setProperty("org.apache.commons.logging.Log",
		 "org.apache.commons.logging.impl.NoOpLog");
	}

	public static void main(String[] args) throws Exception {
        new Timing(args);
    }

    public Timing(String[] args) throws Exception {
        // start timing of rebuild
        StopWatch.start("totalRebuild");

        // load dataset from database into DataModel
        StopWatch.start("getModel");

        DBModel.startServer();
        DataModel model = DataSet.MovielensMock1M.getModel();

//
        System.out.format("%s (%d users, %d items)\n", StopWatch.str("getModel"), model.getNumUsers(), model.getNumItems());

        // set configuration parameters and preprocessor
        Config config = new Lynx()
                .set("model", model)
                .set("minTimeOnPage", 25000)
                .set("correlationLimit", 0.3)
                .set("rating", 4)
                .set("predictionMethod", PreprocessorStat.PredictionMethod.ClosestNeighbor);

        // preprocess dataModel
        StopWatch.start("preprocess");
        Preprocessor preprocessor = new PreprocessorStat();
        model = preprocessor.preprocess(config);
        System.out.format("%s (%d users, %d items)\n", StopWatch.str("preprocess"), model.getNumUsers(), model.getNumItems());

        // build Recommendation model
        StopWatch.start("buildRecommender");
        Recommender newRecommender = ((Lynx) config).getBuilder().buildRecommender(model);
        StopWatch.print("buildRecommender");

    }
}

Add timing class to evaluate the preprocessor performance on a large synthesized dataset


// Author: Param Singh <paramsingh258@gmail.com>
// http://www.spoj.com/problems/PHONELST/

import java.io.*;
class Trie {
    private class Node {
        Node children[];
        boolean flag;
        Node() {
            children = new Node[10];
            for (int i = 0; i < 10; i++)
                children[i] = null;
            flag = false;
        }
    }

    private Node root;

    Trie() {
        root = new Node();
    }

    private void insert(Node vertex, String s) {
        if (s.equals("")) {
            vertex.flag = true;
            return;
        }
        else {
            int next = s.charAt(0) - '0';
            if (vertex.children[next] == null) {
                vertex.children[next] = new Node();
            }
            insert(vertex.children[next], s.substring(1, s.length()));
        }
    }

    public void insert(String s) {
        insert(root, s);
    }

    private boolean query(Node vertex, String s) {
        if (s.equals("")) {
            return false;
        }
        if (vertex.flag) {
            return true;
        }
        else {
            int c = s.charAt(0) - '0';
            return query(vertex.children[c], s.substring(1, s.length()));
        }
    }

    public boolean query(String s) {
        return query(root, s);
    }
}

class PhoneLST {
        public static void main(String[] args) throws IOException {
        InputStreamReader isr = new InputStreamReader(System.in);
        BufferedReader in = new BufferedReader(isr);
        int t = Integer.parseInt(in.readLine());
        for (int term = 0; term < t; term++) {
            int n = Integer.parseInt(in.readLine());
            String a[] = new String[n];
            Trie tr = new Trie();
            int i;
            for (i = 0; i < n; i++) {
                a[i] = in.readLine();
                tr.insert(a[i]);
            }
            boolean flag = false;
            for (i = 0; i < n; i++) {
                if (tr.query(a[i])) {
                    flag = true;
                    break;
                }
            }
            if (flag)
                System.out.println("NO");
            else
                System.out.println("YES");
        }
    }
}

Solve PHONELST for practice of tries

Solve PHONELST for practice of tries


/*
 * Hivemall: Hive scalable Machine Learning Library
 *
 * Copyright (C) 2013-2014
 *   National Institute of Advanced Industrial Science and Technology (AIST)
 *   Registration Number: H25PRO-1520
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 */
package hivemall.mix.server;

import hivemall.io.DenseModel;
import hivemall.io.PredictionModel;
import hivemall.io.WeightValue;
import hivemall.mix.MixMessage.MixEventName;
import hivemall.mix.client.MixClient;
import hivemall.utils.lang.CommandLineUtils;

import java.util.Random;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import junit.framework.Assert;

import org.apache.commons.cli.CommandLine;
import org.junit.Test;

public class MixServerTest {

    @Test
    public void testScenario1() throws InterruptedException {
        CommandLine cl = CommandLineUtils.parseOptions(new String[] { "-port", "11212",
                "-sync_threshold", "3" }, MixServer.getOptions());
        MixServer server = new MixServer(cl);
        ExecutorService serverExec = Executors.newSingleThreadExecutor();
        serverExec.submit(server);

        PredictionModel model = new DenseModel(16777216, false);
        model.configureClock();
        MixClient client = new MixClient(MixEventName.average, "scenario1", "localhost:11212", false, 2, model);
        model.setUpdateHandler(client);

        final Random rand = new Random(43);
        for(int i = 0; i < 100000; i++) {
            Integer feature = Integer.valueOf(rand.nextInt(100));
            float weight = (float) rand.nextGaussian();
            model.set(feature, new WeightValue(weight));
        }

        Thread.sleep(10 * 1000);
        int numMixed = model.getNumMixed();
        //System.out.println("number of mix events: " + numMixed);
        Assert.assertTrue("number of mix events: " + numMixed, numMixed > 0);

        serverExec.shutdown();
    }

}

Add a unit test for MixServer

Add a unit test for MixServer


/*
 * 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.jena.atlas.web.auth;

import java.net.URI;
import java.util.HashMap;
import java.util.Map;

import org.apache.http.impl.client.AbstractHttpClient;
import org.apache.http.protocol.HttpContext;

/**
 * A scoped authenticator which is actually a wrapper around other
 * authenticators and thus can be used to mix and match different authentication
 * mechanisms to different services as desired
 *
 */
public class DelegatingAuthenticator extends AbstractScopedAuthenticator<HttpAuthenticator> {

    private Map<URI, HttpAuthenticator> authenticators = new HashMap<URI, HttpAuthenticator>();

    /**
     * Creates a new delegating authenticator
     *
     * @param target
     *            Target URI
     * @param authenticator
     *            Authenticator to delegate to
     */
    public DelegatingAuthenticator(URI target, HttpAuthenticator authenticator) {
        if (target == null)
            throw new IllegalArgumentException("Target URI cannot be null");
        this.authenticators.put(target, authenticator);
    }

    /**
     * Creates a new delegating authenticator
     *
     * @param authenticators
     *            Mapping between URIs and authenticators
     */
    public DelegatingAuthenticator(Map<URI, HttpAuthenticator> authenticators) {
        this.authenticators.putAll(authenticators);
    }

    public void apply(AbstractHttpClient client, HttpContext context, URI target) {
        HttpAuthenticator authenticator = this.findCredentials(target);
        if (authenticator != null) {
            authenticator.apply(client, context, target);
        }
    }

    @Override
    protected HttpAuthenticator getCredentials(URI target) {
        return this.authenticators.get(target);
    }

    @Override
    protected String getUserNameFromCredentials(HttpAuthenticator credentials) {
        // Not used by this implementation because we override apply() so this
        // will never be needed and regardless isn't available
        return null;
    }

    @Override
    protected char[] getPasswordFromCredentials(HttpAuthenticator credentials) {
        // Not used by this implementation because we override apply() so this
        // will never be needed and regardless isn't available
        return null;
    }

}

Add a delegating authenticator which can be used to map different authenticators to different URIs (JENA-480)

git-svn-id: bc509ec38c1227b3e85ea1246fda136342965d36@1498721 13f79535-47bb-0310-9956-ffa450edef68


package nl.sikken.bertrik.hab.habitat;

import java.time.Duration;
import java.time.Instant;
import java.util.Arrays;

import nl.sikken.bertrik.hab.Sentence;

public final class RunMultiReceiverTest {

    public static void main(String[] args) {
        RunMultiReceiverTest test = new RunMultiReceiverTest();
        test.run();
    }

    private void run() {
        String url = "http://habitat.habhub.org";
        Duration timeout = Duration.ofSeconds(30);
        HabitatUploader uploader = new HabitatUploader(HabitatUploader.newRestClient(url, timeout));
        uploader.start();
        try {
            Instant now = Instant.now();
            Sentence sentence = new Sentence("TTNTEST", 1, now);
            HabReceiver receiver1 = new HabReceiver("BERTRIK1", new Location(52.022887, 4.69, 0.0));
            HabReceiver receiver2 = new HabReceiver("BERTRIK2", new Location(52.022887, 4.70, 0.0));

            uploader.schedulePayloadTelemetryUpload(sentence.format(), Arrays.asList(receiver1, receiver2), now);
        } finally {
            uploader.stop();
        }
    }

}

Add runner to verify multi-receiver support of habitat API.


package client.shareserver;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.AbstractExecutorService;
import java.util.concurrent.Callable;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;

/**
 *
 *
 *
 * @param <T> The type of the resource that this manages.
 */
public class ResourcePoolExecutor<T> extends AbstractExecutorService {

	public interface ResourceUser<T> extends Runnable {

		/** Returns the resource */
		T getResource();
	}

	private final ConcurrentMap<T, ExecutorService> resourceMap = new ConcurrentHashMap<T, ExecutorService>();

	public ResourcePoolExecutor(Iterable<T> resources) {
		for (T resource : resources) {
			resourceMap.put(resource, Executors.newFixedThreadPool(1));
		}
	}

	public ResourcePoolExecutor(Iterable<T> resources, ThreadFactory factory) {
		for (T resource : resources) {
			resourceMap.put(resource, Executors.newFixedThreadPool(1, factory));
		}
	}

	@Override
	public boolean awaitTermination(final long timeout, final TimeUnit unit) throws InterruptedException {
		ExecutorService pool = Executors.newCachedThreadPool();
		for (final ExecutorService ex : resourceMap.values()) {
			pool.submit(new Callable<Boolean>() {
				public Boolean call() throws InterruptedException {
					return ex.awaitTermination(timeout, unit);
				}
			});
		}
		pool.shutdown();
		return pool.awaitTermination(timeout, unit);
	}

	@Override
	public boolean isShutdown() {
		boolean shutdown = true;
		for (ExecutorService ex : resourceMap.values()) {
			shutdown = shutdown && ex.isShutdown();
		}
		return shutdown;
	}

	@Override
	public boolean isTerminated() {
		boolean terminated = true;
		for (ExecutorService ex : resourceMap.values()) {
			terminated = terminated && ex.isTerminated();
		}
		return terminated;
	}

	@Override
	public void shutdown() {
		for (ExecutorService ex : resourceMap.values()) {
			ex.shutdown();
		}
	}

	@Override
	public List<Runnable> shutdownNow() {
		List<Runnable> list = new ArrayList<Runnable>();
		for (ExecutorService ex : resourceMap.values()) {
			list.addAll(ex.shutdownNow());
		}
		return list;
	}

	@Override
	public void execute(Runnable command) {
		if (command instanceof ResourceUser<?>) {
			ResourceUser<?> user = (ResourceUser<?>) command;
			Object resource = user.getResource();
			if (resourceMap.containsKey(resource)) {
				resourceMap.get(resource).execute(user);
			}
		}
	}

}

Create new executor to handle resource pools


package dr.inference.operators;

import dr.inference.model.Parameter;
import dr.math.MathUtils;
import dr.xml.*;

/**
 * @author Chieh-Hsi Wu
 * Operator that performs independent random walks on k elements in a parameter
 */
public class MultipleRandomWalkIntegerOperator extends RandomWalkIntegerOperator{
    public static final String SAMPLE_SIZE = "sampleSize";
    private int sampleSize = 1;
    public MultipleRandomWalkIntegerOperator(Parameter parameter, int windowSize, int sampleSize, double weight) {
        super(parameter,windowSize, weight);
        this.sampleSize = sampleSize;
    }

    public double doOperation() {

        int[] shuffledInd = MathUtils.shuffled(parameter.getDimension());
        int index;
        for(int i = 0; i < sampleSize; i++){

            index = shuffledInd[i];

            // a random non zero integer around old value within windowSize * 2
            int oldValue = (int) parameter.getParameterValue(index);
            int newValue;
            int roll = MathUtils.nextInt(2 * windowSize);
            if (roll >= windowSize) {
                newValue = oldValue + 1 + roll - windowSize;

                if (newValue > parameter.getBounds().getUpperLimit(index))
                    newValue = 2 * (int)(double)parameter.getBounds().getUpperLimit(index) - newValue;
            } else {
                newValue = oldValue - 1 - roll;

                if (newValue < parameter.getBounds().getLowerLimit(index))
                    newValue = 2 * (int)(double)parameter.getBounds().getLowerLimit(index) - newValue;
            }

            parameter.setParameterValue(index, newValue);

        }

        return 0.0;
    }

    public static dr.xml.XMLObjectParser PARSER = new AbstractXMLObjectParser() {

        public String getParserName() {
            return "multipleRandomWalkIntegerOperator";
        }

        public Object parseXMLObject(XMLObject xo) throws XMLParseException {

            double weight = xo.getDoubleAttribute(WEIGHT);

            double w = xo.getDoubleAttribute(WINDOW_SIZE);
            if (w != Math.floor(w)) {
                throw new XMLParseException("The window size of a randomWalkIntegerOperator should be an integer");
            }

            double s = xo.getDoubleAttribute(SAMPLE_SIZE);
            if (s != Math.floor(s)) {
                throw new XMLParseException("The window size of a randomWalkIntegerOperator should be an integer");
            }

            int windowSize = (int)w;
            int sampleSize = (int)s;
            Parameter parameter = (Parameter) xo.getChild(Parameter.class);

            return new MultipleRandomWalkIntegerOperator(parameter, windowSize, sampleSize, weight);
        }

        //************************************************************************
        // AbstractXMLObjectParser implementation
        //************************************************************************

        public String getParserDescription() {
            return "This element returns a random walk operator on a given parameter.";
        }

        public Class getReturnType() {
            return MCMCOperator.class;
        }

        public XMLSyntaxRule[] getSyntaxRules() {
            return rules;
        }

        private XMLSyntaxRule[] rules = new XMLSyntaxRule[]{
                AttributeRule.newDoubleRule(WINDOW_SIZE),
                AttributeRule.newDoubleRule(SAMPLE_SIZE),
                AttributeRule.newDoubleRule(WEIGHT),
                new ElementRule(Parameter.class)
        };

    };

}

Allow multiple independent random walks for different indices of the same parameter.


package javaStaticInitializerBlock;

import java.util.Scanner;

public class Solution {

	static boolean flag = false;
	static int B, H;
	static{
		Scanner scanner = new Scanner(System.in);
		B = scanner.nextInt();
		H = scanner.nextInt();
		Exception e = new Exception();
		if( B <= 0 || H <= 0)
			System.out.println(e.toString() + ": Breadth and height must be positive");
		else
			flag = true;
		scanner.close();
	}

	public static void main(String[] args){
		if(flag){
			int area = B * H;
			System.out.print(area);
		}
	}
}

Add solution for problem Java Static Initializer Block

Java Static Initializer Block from HackerRank/Introduction/Java Static Initializer Block


/*
 * The MIT License
 *
 * Copyright 2017 Fernando van Loenhout.
 *
 * 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.
 */
/**
 * A repository is a manager for entities, all repositories support getting by
 * id and by unresolved entities.
 */
package me.ferrybig.javacoding.teamspeakconnector.repository;

Add simple package info file

Add simple package info file


/*
 * Copyright (c) 2015 Ushahidi Inc
 *
 * This program is free software: you can redistribute it and/or modify it under
 *  the terms of the GNU Affero General Public License as published by the Free
 *  Software Foundation, either version 3 of the License, or (at your option)
 *  any later version.
 *
 *  This program is distributed in the hope that it will be useful, but WITHOUT
 *  ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 *  FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details.
 *
 *  You should have received a copy of the GNU Affero General Public License
 *  along with this program in the file LICENSE-AGPL. If not, see
 *  https://www.gnu.org/licenses/agpl-3.0.html
 */

package com.ushahidi.android.data.repository.datasource;

import com.ushahidi.android.data.entity.mapper.UserAccountEntityDataMapper;
import com.ushahidi.android.data.repository.datasource.useraccount.UserAccountDataSource;
import com.ushahidi.android.data.repository.datasource.useraccount.UserAccountDataSourceFactory;
import com.ushahidi.android.domain.entity.Tag;
import com.ushahidi.android.domain.entity.UserAccount;
import com.ushahidi.android.domain.repository.UserAccountRepository;

import android.support.annotation.NonNull;

import rx.Observable;

/**
 * @author Ushahidi Team <team@ushahidi.com>
 */
public class UserAccountDataRepository implements UserAccountRepository {

    private final UserAccountDataSourceFactory mUserAccountDataSourceFactory;

    private final UserAccountEntityDataMapper mUserAccountEntityDataMapper;

    public UserAccountDataRepository(
            @NonNull UserAccountDataSourceFactory userAccountDataSourceFactory, @NonNull
    UserAccountEntityDataMapper userAccountEntityDataMapper) {
        mUserAccountDataSourceFactory = userAccountDataSourceFactory;
        mUserAccountEntityDataMapper = userAccountEntityDataMapper;
    }

    @Override
    public Observable login(UserAccount userAccount) {
        final UserAccountDataSource userAccountDataSource = mUserAccountDataSourceFactory
                .createApiDataSource();
        return userAccountDataSource
                .loginUserAccountEntity(mUserAccountEntityDataMapper.map(userAccount));
    }

    @Override
    public Observable<Long> putUserAccount(Tag entity) {
        // Do nothing
        return null;
    }

    @Override
    public Observable<Long> deleteUserAccount(Long id) {
        // Do nothing
        return null;
    }
}

Implement data repository for user account


package org.cstamas.vertx.content.impl;

import io.vertx.core.Vertx;
import io.vertx.core.buffer.Buffer;
import io.vertx.core.http.HttpClient;
import io.vertx.core.http.HttpServer;
import io.vertx.core.json.JsonObject;
import io.vertx.core.logging.Logger;
import io.vertx.core.logging.LoggerFactory;
import io.vertx.core.streams.ReadStream;
import org.cstamas.vertx.content.FlowControl;
import org.cstamas.vertx.content.Transport;

import static com.google.common.base.Preconditions.checkNotNull;
import static org.cstamas.vertx.content.ContentManager.txId;

/**
 * {@link Transport} implementation that uses {@link HttpServer} and {@link HttpClient} for transport.
 */
public class HttpTransport
    implements Transport
{
  private static final Logger log = LoggerFactory.getLogger(HttpTransport.class);

  private static final String NAME = "http";

  private final Vertx vertx;

  public HttpTransport(final Vertx vertx) {
    this.vertx = checkNotNull(vertx);
  }

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

  @Override
  public void send(final JsonObject contentHandle,
                   final FlowControl flowControl,
                   final ReadStream<Buffer> stream)
  {
    String txId = txId(contentHandle);
    // TODO: HTTP Server should publish resource (copied to tmp or just as "single shot"?) and send the URL
  }

  @Override
  public ReadStream<Buffer> receive(final JsonObject contentHandle, final FlowControl flowControl)
  {
    String txId = txId(contentHandle);
    // TODO: client should GET the content
    return null;
  }
}

Add HTTP transport, scratch for now

Add HTTP transport, scratch for now


package fgis.server.support.geojson;

import java.util.Arrays;
import org.testng.annotations.Test;
import static org.testng.Assert.*;

public final class GjGeometryCollectionTest
  extends AbstractGjElementTest
{
  @Test
  public void basic()
    throws Exception
  {
    final GjGeometry g = new GjGeometry( fromWkT( "POINT (1 1)" ), null, null, null );
    final GjGeometryCollection e = new GjGeometryCollection( Arrays.asList( g ), null, null, null );
    assertEquals( e.getCollection().size(), 1 );
    assertTrue( e.getCollection().contains( g ) );
    assertPropertyAllowed( e, "X" );
    assertPropertyNotAllowed( e, "geometries" );
    try
    {
      e.getCollection().add( g );
    }
    catch ( Exception e1 )
    {
      return;
    }
    fail( "Expected collection list to be immutable but an edit was allowed" );
  }

  @SuppressWarnings( "ConstantConditions" )
  @Test
  public void nullGeometryCollectionPassed()
    throws Exception
  {
    try
    {
      new GjGeometryCollection( null, null, null, null );
    }
    catch ( final IllegalArgumentException e )
    {
      return;
    }
    fail( "Expected to fail when passing null collection" );
  }
}

Create a test for geometry collection

Create a test for geometry collection


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

package net.uncontended.precipice.metrics;

public class SimpleCountMetrics<T extends Enum<T>> implements TotalCountMetrics<T> {

    private final MetricCounter<T> totalCounter;
    private final Class<T> type;

    public SimpleCountMetrics(Class<T> type) {
        this.type = type;
        totalCounter = new MetricCounter<>(type);
    }

    @Override
    public void incrementMetricCount(T metric) {
        totalCounter.incrementMetric(metric);
    }

    @Override
    public void incrementMetricCount(T metric, long nanoTime) {
        totalCounter.incrementMetric(metric);

    }

    @Override
    public long getTotalMetricCount(T metric) {
        return totalCounter.getMetricCount(metric);
    }

    @Override
    public MetricCounter<T> totalCountMetricCounter() {
        return totalCounter;
    }

    @Override
    public Class<T> getMetricType() {
        return type;
    }
}

Add basic impl for total counts

Add basic impl for total counts


/**
 * Copyright (C) 2016 Bruno Candido Volpato da Cunha (brunocvcunha@gmail.com)
 *

 * 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.brunocvcunha.instagram4j.requests;

import lombok.AllArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.log4j.Log4j;
import org.brunocvcunha.instagram4j.requests.payload.InstagramFriendshipStatus;

/**
 * Request for getting a user's friendship status
 *
 * @author Akhmad Syaikhul Hadi (akhmad.hadi@gmail.com)
 */
@AllArgsConstructor
@Log4j
public class InstagramGetFriendshipRequest extends InstagramGetRequest<InstagramFriendshipStatus> {
    private long userId;

    @Override
    public String getUrl() {
        return "friendships/show/" + userId;
    }

    @Override
    @SneakyThrows
    public InstagramFriendshipStatus parseResult(int statusCode, String content) {
        return this.parseJson(content, InstagramFriendshipStatus.class);
    }
}

Add a user's friendship status request

Add a user's friendship status request


/*
 * SIP Communicator, the OpenSource Java VoIP and Instant Messaging client.
 *
 * Distributable under LGPL license.
 * See terms of license at gnu.org.
 */
package net.java.sip.communicator.service.gui;

/**
 *
 * @author Yana Stamcheva
 */
public interface CreateAccountWindow
{
    /**
     * Shows or hides this create account window.
     *
     * @param visible <tt>true</tt> to show this window, <tt>false</tt> -
     * otherwise
     */
    public void setVisible(boolean visible);

    /**
     * Sets the selected wizard.
     *
     * @param wizard the wizard to select
     */
    public void setSelectedWizard(AccountRegistrationWizard wizard);
}

Check for create form for all account registration wizards before sending the user to the web registration page.


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

import org.xwiki.stability.Unstable;

/**
 * Represents text content that has a syntax.
 *
 * @version $Id$
 * @since 8.2RC1
 */
@Unstable
public class SyntaxContent
{
    /**
     * The syntax of the content.
     */
    private final Syntax syntax;

    /**
     * The text content.
     */
    private final String content;

    /**
     * Creates a new instance that wraps the given text content and its syntax.
     *
     * @param content the text content
     * @param syntax the syntax of the content
     */
    public SyntaxContent(String content, Syntax syntax)
    {
        this.syntax = syntax;
        this.content = content;
    }

    /**
     * @return the syntax of the content
     */
    public Syntax getSyntax()
    {
        return syntax;
    }

    /**
     * @return the text content
     */
    public String getContent()
    {
        return content;
    }
}

XWIKI-13528: Add support for replacing the default WYSIWYG editor
* We need to be able to edit the raw wiki syntax and for this we need a new data type (besides XDOM)


package edu.oregonstate.cope.eclipse.listeners;

import static org.junit.Assert.assertTrue;

import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.util.Arrays;
import java.util.Random;

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.binary.Base64InputStream;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import edu.oregonstate.cope.eclipse.FileUtil;

public class ResourceListenerTest {

	private static final int FILE_SIZE_BYTES = 10000;
	private IProject project;
	private IFile file;
	private byte[] randomBytes;

	@Before
	public void before() throws Exception {
		project = FileUtil.createProject("TestProject");
		file = FileUtil.createFile("bla.jar", project);
		randomBytes = new byte[FILE_SIZE_BYTES];
		new Random().nextBytes(randomBytes);
		file.appendContents(new ByteArrayInputStream(randomBytes), true, false, new NullProgressMonitor());
	}

	@After
	public void after() throws Exception {
		FileUtil.deleteProject(project);
	}

	@Test
	public void testReadBinaryFile() throws Exception {
		ResourceListener listener = new ResourceListener();
		String contents = listener.getFileContents(file);

		byte[] actualBytes = Base64.decodeBase64(contents.getBytes());

		System.out.println(randomBytes.length + " " + actualBytes.length);

		assertTrue(Arrays.equals(randomBytes, actualBytes));
	}

}

Test for the binary file recording

Test for the binary file recording


import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.Iterator;

import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;

import edu.wustl.catissuecore.actionForm.InstitutionForm;

/*
 * Created on Mar 31, 2005
 *
 * TODO To change the template for this generated file go to
 * Window - Preferences - Java - Code Style - Code Templates
 */

/**
 * @author kapil_kaveeshwar
 *
 * TODO To change the template for this generated type comment go to
 * Window - Preferences - Java - Code Style - Code Templates
 */
public class TestURL
{
	public static void maina(String[] args) throws Exception
	{
		System.out.println(String.class.getName());

	}
	public static void main(String[] args) throws Exception
	{
		InstitutionForm insForm = new InstitutionForm();
		insForm.setName("Test3");
		insForm.setOperation("add");

		URL aURL = new URL("http://localhost:8080/catissuecore/InstituteAddHTTP.do");
		URLConnection aConn = aURL.openConnection();

		aConn.setDoOutput(true);
		aConn.setRequestProperty("CONTENT-TYPE","BI");
		System.out.println(aConn.getRequestProperties());
		ObjectOutputStream oos = new ObjectOutputStream (aConn.getOutputStream());
		oos.writeObject(insForm);
		oos.flush();
		oos.close();

		ObjectInputStream ois = new ObjectInputStream(aConn.getInputStream());
		Object obj = ois.readObject();
		ois.close();
		System.out.println(obj);

		ActionMessages msgs = (ActionMessages)obj;

		Iterator it = msgs.get();
		while(it.hasNext())
		{
			ActionMessage msg = (ActionMessage)it.next();
			System.out.println(msg);
			System.out.println(msg.getKey());
			Object[] objects = msg.getValues();
			for (int i = 0; i < objects.length; i++)
			{
				System.out.println(objects[i]);
			}
			System.out.println();
		}
//		oos.flush();
//		oos.close();

//		BufferedReader aBuffReader = new BufferedReader(new InputStreamReader(aConn.getInputStream()));
//		String str = "";
//		while((str=aBuffReader.readLine())!=null)
//		{
//			System.out.println(str);
//		}
	}
}

Test Application for HTTP API

Test Application for HTTP API

SVN-Revision: 2577


public class findMode{
    public static void main(String[] args){

    }
    public static int mode(int[] array){
        ArrayList<Integer> r = new ArrayList<>();

    }
    public static int find(List<Value> list, target){

    }
}
class Value {
    private int value;
    private int counter;
    public Value(int v) {
        value=v;
        count=0;
    }
    public int getValue(){

    }
    public int getCounter(){

    }
    //increment counter by 1
    public void increment(){

    }
}

Update after organising some files

Update after organising some files


package leetcode.valid_anagram;

public class Solution {
    public boolean isAnagram(String s, String t) {
        if(s.length() != t.length()) return false;
        int[] bucket = new int[26];
        for(char c : s.toCharArray()){
            bucket[c - 'a']++;
        }
        for(char c : t.toCharArray()){
            bucket[c - 'a']--;
        }
        for(int i = 0; i < 26; i++){
            if(bucket[i] != 0) return false;
        }
        return true;
    }
}

Add java solution for 242. Valid Anagram

242. Valid Anagram: https://leetcode.com/problems/valid-anagram/


/**
 * Twist in the Tale 2.2 from the OCA Java SE 7 book by Mala Gupta (Manning Publications)
 * Created by Josef on 12/17/13.
 */
public class TwistInTheTale2_2 {
    static void main (String[] args) {
        boolean b1, b2, b3, b4, b5, b6;
        b1 = b2 = b3 = true;
        b4 = 0;
        b5 = 'false';
        b6 = yes;
    }
}

Add code for Twist in the Tale 2.2

Add code for Twist in the Tale 2.2


package com.poiji.util;

import static org.junit.Assert.assertNotNull;
import static org.junit.Assume.assumeTrue;

import java.lang.reflect.ReflectPermission;

import org.junit.BeforeClass;
import org.junit.Test;

public class ReflectUtilTest {

    @BeforeClass
    public static void ensureSecurityManagerPermits() {
        SecurityManager securityManager = System.getSecurityManager();
        boolean permitted = true;
        if (securityManager != null) {
            try {
                securityManager.checkPermission(new ReflectPermission("suppressAccessChecks"));
            } catch (SecurityException e) {
                permitted = false;
            }
        }
        assumeTrue(permitted);
    }

    @Test
    public void newInstanceOfPackageModel() {
        PackageModel obj = ReflectUtil.newInstanceOf(PackageModel.class);
        assertNotNull(obj);
    }

    @Test
    public void newInstanceOfPackageModelWithPrivateConstructor() {
        PackageModelWithPrivateConstructor obj = ReflectUtil.newInstanceOf(PackageModelWithPrivateConstructor.class);
        assertNotNull(obj);
    }

    @Test
    public void newInstanceOfPrivateModel() {
        PrivateModel obj = ReflectUtil.newInstanceOf(PrivateModel.class);
        assertNotNull(obj);
    }

    static class PackageModel {
    }

    static class PackageModelWithPrivateConstructor {
        private PackageModelWithPrivateConstructor() {
        }
    }

    static private class PrivateModel {
    }

}

Add unit test for ReflectUtil.newInstanceOf


package org.xbean.terminal.console;

import org.xbean.command.CommandShell;

public class Main {

    public static void main(String[] args) {
        CommandShell shell = new CommandShell("localhost");
        System.exit(shell.main(new String[]{}, System.in, System.out));
    }
}

Add a terminal type that just uses the console.

git-svn-id: c55cfc7c8893d43c3333f2d886128b43c8520716@380518 13f79535-47bb-0310-9956-ffa450edef68


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

import org.apache.mesos.Protos.CommandInfo;
import org.apache.mesos.Protos.ExecutorID;
import org.apache.mesos.Protos.ExecutorInfo;
import org.apache.mesos.Protos.FrameworkID;
import org.apache.mesos.Protos.Offer;
import org.apache.mesos.Protos.OfferID;
import org.apache.mesos.Protos.SlaveID;
import org.apache.mesos.Protos.TaskID;
import org.apache.mesos.Protos.TaskInfo;
import org.junit.Test;

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

public final class LaunchTaskTest
{

  /**
   * Testing target.
   */
  private final LaunchTask target;

  private final TaskInfo sampleTaskInfo;

  private final Offer sampleOffer;

  /**
   * Setup testing target & sample data.
   */
  public LaunchTaskTest()
  {
    SlaveID slaveID = SlaveID.newBuilder().setValue("s1").build();
    this.sampleTaskInfo =
        TaskInfo.newBuilder()
                .setName("t1").setSlaveId(slaveID)
                .setTaskId(TaskID.newBuilder().setValue("id2"))
                .setExecutor(
                    ExecutorInfo.newBuilder()
                                .setExecutorId(ExecutorID.newBuilder().setValue("e1"))
                                .setCommand(CommandInfo.getDefaultInstance()))
                .build();
    this.sampleOffer =
        Offer.newBuilder()
             .setHostname("h1").setSlaveId(slaveID)
             .setId(OfferID.newBuilder().setValue("id1"))
             .setFrameworkId(FrameworkID.newBuilder().setValue("f1").build())
             .build();
    this.target = new LaunchTask(sampleTaskInfo, sampleOffer);
  }

  @Test
  public void getTask()
  {
    assertSame(
        "The return value should be the same as the value passed in the argument of the constructor",
        sampleTaskInfo, target.getTask()
    );
  }

  @Test
  public void getOffer()
  {
    assertSame(
        "The return value should be the same as the value passed in the argument of the constructor",
        sampleOffer, target.getOffer()
    );
  }

  @Test
  public void objectToString()
  {
    assertEquals(
        "Offer: {\"offer_id\":\"id1\",\"hostname\":\"h1\"} TaskInfo: {\"task_id\":\"id2\",\"slave_id\":\"s1\",\"executor_id\":\"e1\"}",
        target.toString()
    );
  }

}

Add test cases for LaunchTask

Add test cases for LaunchTask


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

package org.glyptodon.guacamole.net.basic.properties;

import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.regex.Pattern;
import org.glyptodon.guacamole.GuacamoleException;
import org.glyptodon.guacamole.properties.GuacamoleProperty;

/**
 * A GuacamoleProperty whose value is a Set of unique Strings. The string value
 * parsed to produce this set is a comma-delimited list. Duplicate values are
 * ignored, as is any whitespace following delimiters. To maintain
 * compatibility with the behavior of Java properties in general, only
 * whitespace at the beginning of each value is ignored; trailing whitespace
 * becomes part of the value.
 *
 * @author Michael Jumper
 */
public abstract class StringSetProperty implements GuacamoleProperty<Set<String>> {

    /**
     * A pattern which matches against the delimiters between values. This is
     * currently simply a comma and any following whitespace. Parts of the
     * input string which match this pattern will not be included in the parsed
     * result.
     */
    private static final Pattern DELIMITER_PATTERN = Pattern.compile(",\\s*");

    @Override
    public Set<String> parseValue(String values) throws GuacamoleException {

        // If no property provided, return null.
        if (values == null)
            return null;

        // Split string into a set of individual values
        List<String> valueList = Arrays.asList(DELIMITER_PATTERN.split(values));
        return new HashSet<String>(valueList);

    }

}

GUAC-1345: Add simple property type which parses to a set of strings.


package net.imagej.ops.viewOp;

import org.scijava.plugin.Plugin;

import net.imagej.ops.view.ViewOps;
import net.imagej.ops.view.ViewOps.Raster;
import net.imglib2.RealRandomAccessible;
import net.imglib2.type.Type;
import net.imglib2.view.RandomAccessibleOnRealRandomAccessible;
import net.imglib2.view.Views;

@Plugin(type = ViewOps.Raster.class, name = ViewOps.Raster.NAME)
public class DefaultRaster<T extends Type<T>>
		extends
		AbstractView<RealRandomAccessible<T>, RandomAccessibleOnRealRandomAccessible<T>>
		implements
		Raster<RealRandomAccessible<T>, RandomAccessibleOnRealRandomAccessible<T>> {

	@Override
	public RandomAccessibleOnRealRandomAccessible<T> compute(
			RealRandomAccessible<T> input) {
		return Views.raster(input);
	}

}

Add default implementation of Raster interface.


package com.kaching.platform.testing;

import static com.kaching.platform.testing.VisibilityTestRunner.Intent.PRIVATE;
import static org.junit.Assert.*;

import org.junit.Test;

public class VisibilityTestRunnerTest {

  @Test
  public void privateFieldMustBeVisibleByOwner() {
    VisibilityTestRunner runner = new VisibilityTestRunner(getClass());
    assertTrue(runner.isVisible(
        new ParsedElements.ParsedField(
            new ParsedElements.ParsedClass("java/util/HashMap"), "size"),
        new ParsedElements.ParsedClass("java/util/HashMap"), PRIVATE));
  }

  @Test
  public void privateFieldMustBeVisibleByInnerClass() {
    VisibilityTestRunner runner = new VisibilityTestRunner(getClass());
    assertTrue(runner.isVisible(
        new ParsedElements.ParsedField(
            new ParsedElements.ParsedClass("java/util/HashMap"), "size"),
        new ParsedElements.ParsedClass("java/util/HashMap$Entry"), PRIVATE));
  }

  @Test
  public void privateFieldMustBeVisibleByOuterClass() {
    VisibilityTestRunner runner = new VisibilityTestRunner(getClass());
    assertTrue(runner.isVisible(
        new ParsedElements.ParsedField(
            new ParsedElements.ParsedClass("java/util/HashMap$Entry"), "key"),
        new ParsedElements.ParsedClass("java/util/HashMap"), PRIVATE));
  }

  @Test
  public void privateFieldMustBeVisibleByAnonymousClass() {
    VisibilityTestRunner runner = new VisibilityTestRunner(getClass());
    assertTrue(runner.isVisible(
        new ParsedElements.ParsedField(
            new ParsedElements.ParsedClass("java/util/HashMap"), "size"),
        new ParsedElements.ParsedClass("java/util/HashMap$1"), PRIVATE));
  }

  @Test
  public void privateFieldMustNotBeVisibleByDifferentClass() {
    VisibilityTestRunner runner = new VisibilityTestRunner(getClass());
    assertFalse(runner.isVisible(
        new ParsedElements.ParsedField(
            new ParsedElements.ParsedClass("java/util/HashMap"), "size"),
        new ParsedElements.ParsedClass("java/util/ArrayList"), PRIVATE));
  }

  @Test
  public void privateFieldMustNotBeVisibleBySubclass() {
    VisibilityTestRunner runner = new VisibilityTestRunner(getClass());
    assertFalse(runner.isVisible(
        new ParsedElements.ParsedField(
            new ParsedElements.ParsedClass("java/util/HashMap"), "size"),
        new ParsedElements.ParsedClass("org/apache/commons/collections/MultiHashMap"), PRIVATE));
  }

  @Test
  public void privateInnerClassMustBeVisibleByOwner() {
    VisibilityTestRunner runner = new VisibilityTestRunner(getClass());
    assertTrue(runner.isVisible(
        new ParsedElements.ParsedClass("java/util/HashMap$Entry"),
        new ParsedElements.ParsedClass("java/util/HashMap"), PRIVATE));
  }

  @Test
  public void privateInnerClassMustBeVisibleByOtherInnerClass() {
    VisibilityTestRunner runner = new VisibilityTestRunner(getClass());
    assertTrue(runner.isVisible(
        new ParsedElements.ParsedClass("java/util/HashMap$Entry"),
        new ParsedElements.ParsedClass("java/util/HashMap$KeySet"), PRIVATE));
  }

  @Test
  public void privateInnerClassMustNotBeVisibleByDifferentClass() {
    VisibilityTestRunner runner = new VisibilityTestRunner(getClass());
    assertFalse(runner.isVisible(
        new ParsedElements.ParsedClass("java/util/HashMap$Entry"),
        new ParsedElements.ParsedClass("java/util/ArrayList"), PRIVATE));
  }

}

Test the visibility check itself

Test the visibility check itself


/**
 * 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.camel.itest.karaf;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.ops4j.pax.exam.junit.PaxExam;

@RunWith(PaxExam.class)
public class CamelAwsEcsTest extends BaseKarafTest {

    public static final String COMPONENT = extractName(CamelAwsEcsTest.class);

    @Test
    public void test() throws Exception {
    	testComponent(COMPONENT);
    }

}

Camel-AWS: Create single Karaf feature tests for single components, aws-ecs test


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

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import static org.mockito.Matchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
/**
 * Configuration to allow integration testing of validation.
 *
 * @author Tony Wardell
 * Date: 22/11/2016
 * Time: 09:44
 * Created with IntelliJ IDEA.
 */
@Configuration
public class MockValidationConfig {

    public static final String DB_REF_VALIDATION_SUCCEEDS= "dbXrefValidationSucceeds";

    @Bean
    public DBXRefEntityValidation dBXRefEntityValidation(){
        DBXRefEntityValidation dbxRefEntityValidation = mock(DBXRefEntityValidation.class);
        when(dbxRefEntityValidation.isValid(any(String.class))).thenReturn(true);
        return dbxRefEntityValidation;
    }

    @Bean
    public ReferenceValuesValidation validator(){
        return new ReferenceValuesValidation();
    }
}

Test for validation of Reference values for annotation filtering.


/*
 * Copyright 2005 Joe Walker
 *
 * 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.directwebremoting.io;

import java.util.Map;

/**
 * DwrConvertedException are automatically exported by DWR along with the
 * message and (optionally) a map of data. It is the developers job to ensure
 * that all the objects in the data map are marked for conversion.
 * @author Joe Walker [joe at getahead dot ltd dot uk]
 */
public class DwrConvertedException extends RuntimeException
{
    /**
     * @param message The message to pass to the exceptionHandler in JavaScript
     */
    public DwrConvertedException(String message)
    {
        super(message);
    }

    /**
     * @param message The message to pass to the exceptionHandler in JavaScript
     */
    public DwrConvertedException(String message, Map<?, ?> data)
    {
        super(message);
        this.data = data;
    }

    /**
     * @return the data
     */
    public Map<?, ?> getData()
    {
        return data;
    }

    private Map<?, ?> data;
}

Create a new exception that people can throw if they know they want it to go to the outside world without any further need for DWR configuration

git-svn-id: b371d604c7577be4609d70acd88b8a3995ce0a58@2054 3a8262b2-faa5-11dc-8610-ff947880b6b2


/*
 * Copyright (c) 2011, Regents of the University of Colorado
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
 * 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.
 * Neither the name of the University of Colorado at Boulder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */
package org.cleartk.classifier.encoder.outcome;

import java.io.File;

/**
 *

 * Copyright (c) 2011, Regents of the University of Colorado

 * All rights reserved.
 *
 * @author Steven Bethard
 */
public class DoubleToDoubleOutcomeEncoder implements OutcomeEncoder<Double, Double> {

  private static final long serialVersionUID = 2604679955222082261L;

  public Double encode(Double input) {
    return input;
  }

  public Double decode(Double outcome) {
    return outcome;
  }

  public void finalizeOutcomeSet(File outputDirectory) {
  }
}

Add do-nothing double-to-double outcome encoder. Necessary for regression.

git-svn-id: 34a63cff78c965ed7296912184cd0e3b6b7dc1c0@2899 2f4ce1e4-9571-11dd-93b2-6d14b300b761


public class ArrayToString {

	private static final String[] gargs = new String[] {"1", "2"};

	public static void main(String[] args) {
		ArrayToString a = new ArrayToString();
		a.print0(args);
		a.print1();
		a.print2();
		a.print3();
	}

	public void print0(String args[]) {
		System.out.println(args.toString());
	}

	public void print1() {
		String [] args2 = new String[] {"Hello", "there"};
		System.out.println(args2.toString());
	}

	public void print2() {
		System.out.println((new String[] {"one","two"}).toString());
	}

	public void print3() {
		System.out.println(gargs.toString());
	}
}

Test case for the array toString() detector

git-svn-id: e7d6bde23f017c9ff4efd468d79d66def666766b@9118 eae3c2d3-9b19-0410-a86e-396b6ccb6ab3


package io.aeron;

import org.junit.jupiter.api.Test;

class PrintEnvInfo
{
    @Test
    void test()
    {
        System.out.println("=========================");
        System.out.println("[PrintEnvInfo] System properties:");
        System.out.println("=========================");
        System.getProperties().entrySet().stream()
            .filter(e -> ((String)e.getKey()).startsWith("java."))
            .forEach(e -> System.out.println("- " + e.getKey() + ": " + e.getValue()));

        System.out.println("\n=========================");
        System.out.println("[PrintEnvInfo] ENV variables:");
        System.out.println("=========================");
        for (final String env : new String[]{ "JAVA_HOME", "BUILD_JAVA_HOME", "BUILD_JAVA_VERSION", "PATH" })
        {
            System.out.println("- " + env + ": " + System.getenv(env));
        }
    }
}

[Java] Print Java-related ENV and system properties.