package android.graphics;

import static com.google.common.truth.Truth.assertThat;

import androidx.test.runner.AndroidJUnit4;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.annotation.internal.DoNotInstrument;

/** Compatibility test for {@link Matrix} */
@DoNotInstrument
@RunWith(AndroidJUnit4.class)
public final class MatrixTest {

  @Test
  public void mapRadius() throws Exception {
    Matrix matrix = new Matrix();

    assertThat(matrix.mapRadius(100f)).isEqualTo(100f);
    assertThat(matrix.mapRadius(Float.MAX_VALUE)).isEqualTo(Float.POSITIVE_INFINITY);
    assertThat(matrix.mapRadius(Float.MIN_VALUE)).isEqualTo(0f);

    matrix.postScale(2.0f, 2.0f);
    assertThat(matrix.mapRadius(1.0f)).isWithin(0.01f).of(2.0f);
  }

  @Test
  public void mapPoints() {
    float[] value = new float[9];
    value[0] = 100f;
    new Matrix().mapPoints(value);
    assertThat(value[0]).isEqualTo(100f);
  }

  @Test(expected = Exception.class)
  public void mapPointsNull() {
    new Matrix().mapPoints(null);
  }

  @Test
  public void mapPoints2() {
    float[] dst = new float[9];
    dst[0] = 100f;
    float[] src = new float[9];
    src[0] = 200f;
    new Matrix().mapPoints(dst, src);
    assertThat(dst[0]).isEqualTo(200f);
  }

  @Test(expected = Exception.class)
  public void mapPointsArraysMismatch() {
    new Matrix().mapPoints(new float[8], new float[9]);
  }

  @Test
  public void mapPointsWithIndices() {
    float[] dst = new float[9];
    dst[0] = 100f;
    float[] src = new float[9];
    src[0] = 200f;
    new Matrix().mapPoints(dst, 0, src, 0, 9 >> 1);
    assertThat(dst[0]).isEqualTo(200f);
  }

  @Test(expected = Exception.class)
  public void mapPointsWithIndicesNull() {
    new Matrix().mapPoints(null, 0, new float[9], 0, 1);
  }
}

Add CTEsque tests for Matrix.mapPoints()

PiperOrigin-RevId: 220894752


package org.granite.base;

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

import java.util.Comparator;

public class KeyValue<K, V> {

    private K key;
    private V value;

    public KeyValue() {
    }

    public KeyValue(K key, V value) {
        this.key = key;
        this.value = value;
    }

    public K getKey() {
        return key;
    }

    public V getValue() {
        return value;
    }

    public void setKey(K key) {
        this.key = key;
    }

    public void setValue(V value) {
        this.value = value;
    }

    @Override
    public boolean equals(Object obj) {
        return obj instanceof KeyValue
            && getKey().equals(((KeyValue) obj).getKey());
    }

    @Override
    public int hashCode() {
        return getKey().hashCode();
    }

    public static class ValueComparator<K, V> implements Comparator<KeyValue<K, V>> {

        private final Comparator<V> valueComparator;

        public ValueComparator(final Comparator<V> valueComparator) {
            this.valueComparator = checkNotNull(valueComparator, "valueComparator");
        }

        @Override
        public int compare(KeyValue<K, V> o1, KeyValue<K, V> o2) {
            return valueComparator.compare(o1.getValue(), o2.getValue());
        }
    }

    public static class KeyComparator<K, V> implements Comparator<KeyValue<K, V>> {

        private Comparator<K> keyComparator;

        public KeyComparator(final Comparator<K> keyComparator) {
            this.keyComparator = checkNotNull(keyComparator, "keyComparator");
        }

        @Override
        public int compare(KeyValue<K, V> o1, KeyValue<K, V> o2) {
            return keyComparator.compare(o1.getKey(), o2.getKey());
        }
    }
}

Add a basic key-value class

Add a basic key-value class


package tehnut.resourceful.crops.api.util.cache;

import com.google.common.collect.Lists;
import cpw.mods.fml.common.FMLCommonHandler;

import java.io.File;
import java.util.List;

/**
 * @author tterrag
 */
public class PermanentCache<I> extends WorldCache<I> {

    private static final List<PermanentCache<?>> allCaches = Lists.newArrayList();

    public PermanentCache(String ident) {
        super(ident);
        loadData(getSaveFile());
    }

    @Override
    protected File getSaveFile() {
        return FMLCommonHandler.instance().getSide().isServer() ? new File(ident + ".dat") : new File("saves", ident + ".dat");
    }

    @Override
    protected void blockOldIDs() {
        if (!objToName.isEmpty()) {
            super.blockOldIDs();
        }
    }

    @Override
    protected void mergeNewIDs() {
        if (!objToName.isEmpty()) {
            super.mergeNewIDs();
        }
    }

    @Override
    public void addObject(I object, String name) {
        super.addObject(object, name);
        setID(name);
    }

    public static void saveCaches() {
        for (PermanentCache<?> c : allCaches) {
            c.saveData(c.getSaveFile());
        }
    }
}

Revert "Fix build error by deleting unused API class"

This reverts commit 383f43de8d244f96c30ddeaf48e9be3be094e2a2.


package com.alexrnl.jbetaseries.request.episodes;

import com.alexrnl.jbetaseries.request.APIAddresses;
import com.alexrnl.jbetaseries.request.Request;
import com.alexrnl.jbetaseries.request.Verb;
import com.alexrnl.jbetaseries.request.parameters.Id;

/**
 * Request for removing the grade of the specified episode.

 * @author Alex
 */
public class EpisodeUnote extends Request {

	/**
	 * Constructor #1.

	 * @param episodeId
	 *        the id of the episode to ungrade.
	 */
	public EpisodeUnote (final Integer episodeId) {
		super(Verb.DELETE, APIAddresses.EPISODES_NOTE);
		addParameter(new Id(episodeId));
	}
}

Add the episode/note (DELETE) request

Add the episode/note (DELETE) request


package com.github.sparkcaller.preprocessing;

import org.apache.spark.api.java.function.Function;
import picard.sam.SortSam;

import java.io.File;
import java.util.ArrayList;

public class SamToSortedBam implements Function<File, File> {
    public File call(File file) throws Exception {
        final String ext = "sam";
        String newFileName = file.getPath().substring(0, file.getPath().length() - ext.length()) + "bam";
        File outputSamFile = new File(newFileName);

        ArrayList<String> sorterArgs = new ArrayList<String>();
        sorterArgs.add("INPUT=");
        sorterArgs.add(file.getPath());

        sorterArgs.add("OUTPUT=");
        sorterArgs.add(outputSamFile.getPath());

        sorterArgs.add("SORT_ORDER=coordinate");
        SortSam samSorter = new SortSam();
        samSorter.instanceMain(sorterArgs.toArray(new String[0]));

        return outputSamFile;
    }
}

Add a class used to convert a SAM file to a sorted BAM file.

All the input files in the rest of the pipeline is required to be sorted BAM
files.


/*
 * The Alluxio Open Foundation licenses this work under the Apache License, version 2.0
 * (the “License”). You may not use this work except in compliance with the License, which is
 * available at www.apache.org/licenses/LICENSE-2.0
 *
 * This software is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
 * either express or implied, as more fully set forth in the License.
 *
 * See the NOTICE file distributed with this work for information regarding copyright ownership.
 */

package alluxio.master.file.options;

import org.junit.Assert;
import org.junit.Test;

/**
 * Unit tests for {@link MountOptionsTest}.
 */
public class MountOptionsTest {
  /**
   * Tests the {@link MountOptions#defaults()} method.
   */
  @Test
  public void defaultsTest() {
    MountOptions options = MountOptions.defaults();
    Assert.assertFalse(options.isReadOnly());
  }

  /**
   * Tests getting and setting fields.
   */
  @Test
  public void fieldsTest() {
    MountOptions options = MountOptions.defaults().setReadOnly(true);
    Assert.assertTrue(options.isReadOnly());

    options = MountOptions.defaults().setReadOnly(false);
    Assert.assertFalse(options.isReadOnly());
  }
}

Add test for master MountOptions

Add test for master MountOptions


/***************************************************************************
 * Copyright 2015 Kieker Project (http://kieker-monitoring.net)
 *
 * 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 kieker.monitoring.writer.influxdb;

import org.junit.Test;

import kieker.common.configuration.Configuration;
import kieker.common.record.controlflow.OperationExecutionRecord;

/**
 * @author tp
 *
 * @since 1.13
 */
public class InfluxDBWriterFailingTest {

	public InfluxDBWriterFailingTest() {
		super();
	}

	/**
	 * Test method for {@link kieker.monitoring.writer.influxdb.InfluxDBWriter#connectToInfluxDB()}.
	 */
	@Test(expected = RuntimeException.class)
	public void testConnectToInfluxDB() {
		final Configuration configuration = new Configuration();
		configuration.setProperty(InfluxDBWriter.CONFIG_PROPERTY_DB_URL, "http://localhost");
		configuration.setProperty(InfluxDBWriter.CONFIG_PROPERTY_DB_PORT, "80");
		configuration.setProperty(InfluxDBWriter.CONFIG_PROPERTY_DB_USERNAME, "root");
		configuration.setProperty(InfluxDBWriter.CONFIG_PROPERTY_DB_PASSWORD, "root");
		configuration.setProperty(InfluxDBWriter.CONFIG_PROPERTY_DB_NAME, "kieker");
		final InfluxDBWriter influxDBWriter = new InfluxDBWriter(configuration);
		influxDBWriter.connectToInfluxDB();
	}

	/**
	 * Test method for {@link kieker.monitoring.writer.influxdb.InfluxDBWriter#writeMonitoringRecord(kieker.common.record.IMonitoringRecord)}.
	 */
	@Test(expected = RuntimeException.class)
	public void testWriteMonitoringRecord() {
		final Configuration configuration = new Configuration();
		configuration.setProperty(InfluxDBWriter.CONFIG_PROPERTY_DB_URL, "http://localhost");
		configuration.setProperty(InfluxDBWriter.CONFIG_PROPERTY_DB_PORT, "80");
		configuration.setProperty(InfluxDBWriter.CONFIG_PROPERTY_DB_USERNAME, "root");
		configuration.setProperty(InfluxDBWriter.CONFIG_PROPERTY_DB_PASSWORD, "root");
		configuration.setProperty(InfluxDBWriter.CONFIG_PROPERTY_DB_NAME, "kieker");
		final InfluxDBWriter influxDBWriter = new InfluxDBWriter(configuration);
		final OperationExecutionRecord operationExecutionRecord = new OperationExecutionRecord("signature", "sessionId", 1, 1, 2, "hostname", 1, 1);
		influxDBWriter.writeMonitoringRecord(operationExecutionRecord);
	}

}

Add test for InfluxDB failing

Add test for InfluxDB failing


package io.paymenthighway.model.request;

import io.paymenthighway.json.JsonGenerator;
import org.junit.Test;

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

import static org.junit.Assert.assertTrue;

public class MobilePayInitRequestTest {
  @Test
  public void serializeUriAndUrls() throws Exception {
    MobilePayInitRequest request = MobilePayInitRequest.Builder(1000, "EUR")
            .setWebhookSuccessUrl(new URL("https://myapp.server/success"))
            .setWebhookCancelUrl("https://myapp.server/cancel")
            .setReturnUri(new URI("myapp://view"))
            .build();

    JsonGenerator jsonGenerator = new JsonGenerator();
    String json = jsonGenerator.createTransactionJson(request);

    assertTrue(json.contains("https://myapp.server/success"));
    assertTrue(json.contains("https://myapp.server/cancel"));
    assertTrue(json.contains("myapp://view"));
  }
}

Test that URI and URLs are correctly included in json.


package ru.stqa.pft.addressbook;

public class GroupData {
  private final String name;
  private final String header;
  private final String footer;

  public GroupData(String name, String header, String footer) {
    this.name = name;
    this.header = header;
    this.footer = footer;
  }

  public String getName() {
    return name;
  }

  public String getHeader() {
    return header;
  }

  public String getFooter() {
    return footer;
  }
}

Test refactoring (extracted class for group data)


package info.u_team.u_team_core.screen;

import com.mojang.blaze3d.matrix.MatrixStack;

import net.minecraft.entity.player.PlayerInventory;
import net.minecraft.inventory.container.Container;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.text.ITextComponent;

public class UBasicContainerScreen<T extends Container> extends UContainerScreen<T> {

	public UBasicContainerScreen(T container, PlayerInventory playerInventory, ITextComponent title, ResourceLocation background) {
		super(container, playerInventory, title, background);
	}

	@Override
	public void func_230430_a_(MatrixStack matrixStack, int mouseX, int mouseY, float partialTicks) {
		func_230446_a_(matrixStack);
		super.func_230430_a_(matrixStack, mouseX, mouseY, partialTicks);
		field_230710_m_.forEach(widget -> widget.func_230443_a_(matrixStack, mouseX, mouseY));
		func_230459_a_(matrixStack, mouseX, mouseY);
	}

}

Call the basic methods in the render method for convenience


package cucumber.runtime.java.picocontainer;

import cucumber.junit.Cucumber;
import org.junit.runner.RunWith;

@RunWith(Cucumber.class)
//@Cucumber.Options(features = "cucumber/runtime/java/picocontainer/dates.feature:2:10")
public class RunCukesTest {
}

package cucumber.runtime.java.picocontainer;

import cucumber.junit.Cucumber;
import org.junit.runner.RunWith;

@RunWith(Cucumber.class)
//@Cucumber.Options(features = "classpath:cucumber/runtime/java/picocontainer/dates.feature:3:11")
public class RunCukesTest {
}

Update explicit feature path (but keep it commented out)


package com.farmerbb.taskbar.service;

import com.farmerbb.taskbar.ui.DashboardController;
import com.farmerbb.taskbar.ui.StartMenuController;
import com.farmerbb.taskbar.ui.TaskbarController;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.Robolectric;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.android.controller.ServiceController;

import static org.junit.Assert.assertTrue;

@RunWith(RobolectricTestRunner.class)
public class UIHostServiceNewControllerTest {
    @Test
    public void testDashboardService() {
        ServiceController<DashboardService> dashboardService =
                Robolectric.buildService(DashboardService.class);
        assertTrue(dashboardService.get().newController() instanceof DashboardController);
    }

    @Test
    public void testStartMenuService() {
        ServiceController<StartMenuService> startMenuService =
                Robolectric.buildService(StartMenuService.class);
        assertTrue(startMenuService.get().newController() instanceof StartMenuController);
    }

    @Test
    public void testTaskbarService() {
        ServiceController<TaskbarService> taskbarService =
                Robolectric.buildService(TaskbarService.class);
        assertTrue(taskbarService.get().newController() instanceof TaskbarController);
    }
}

Add tests for specific UIHostService newController

Test: ./gradlew test

Signed-off-by: utzcoz <bf4fcb59289e9979ebf7a02b1609ee526a91bd2d@outlook.com>


package com.github.zhongl.hs4j.kit.util;

import java.lang.reflect.*;

/**
 * {@link ClassUtils}
 *
 * @author zhongl
 * @created 2011-6-5
 *
 */
public class ClassUtils {
  public static void assertMethodReturnType(Method method, Class<?> returnType) {
    if (method.getReturnType().equals(returnType)) return;
    throw new IllegalArgumentException(returnType + " should return by method: " + method);
  }

  @SuppressWarnings("unchecked")
  public static <T> Class<T> getOnlyOneTypeArgumentClassFrom(ParameterizedType parameterizedType) {
    final Type[] actualTypeArguments = parameterizedType.getActualTypeArguments();
    if (actualTypeArguments.length > 1)
      throw new IllegalArgumentException(parameterizedType + " has more than one type arguments");
    return (Class<T>) actualTypeArguments[0];
  }

  public static boolean isIterable(Class<?> rawType) {
    return Iterable.class.isAssignableFrom(rawType);
  }

  public static boolean isParameterizedType(Type type) {
    return type instanceof ParameterizedType;
  }

  public static ParameterizedType parameterized(Type type) {
    return (ParameterizedType) type;
  }

  private ClassUtils() {}
}

Add pull requests from zhongl

Add pull requests from zhongl


package de.christinecoenen.code.zapp.utils;

import android.annotation.TargetApi;
import android.content.Context;
import android.content.pm.ShortcutInfo;
import android.content.pm.ShortcutManager;
import android.graphics.drawable.Icon;
import android.os.Build;

import java.util.Collections;

import de.christinecoenen.code.zapp.ChannelDetailActivity;
import de.christinecoenen.code.zapp.model.ChannelModel;

/**
 * Collection of helper functions to access the ShortcutManager API
 * in a safe way.
 */
public class ShortcutHelper {

	/**
	 * Adds the given channel as shortcut to the launcher icon.
	 * Only call on api level >= 25.
	 * @param context to access system services
	 * @param channel channel to create a shortcut for
	 * @return true if the channel could be added
     */
	@TargetApi(25)
	public boolean addShortcutForChannel(Context context, ChannelModel channel) {
		ShortcutManager shortcutManager = context.getSystemService(ShortcutManager.class);
		ShortcutInfo shortcut = new ShortcutInfo.Builder(context, channel.getId())
			.setShortLabel(channel.getName())
			.setLongLabel(channel.getName())
			.setIcon(Icon.createWithResource(context, channel.getDrawableId()))
			.setIntent(ChannelDetailActivity.getStartIntent(context, channel.getId()))
			.build();

		return shortcutManager.addDynamicShortcuts(Collections.singletonList(shortcut));
	}

	/**
	 * Removes the given channel as shortcut from the launcher icon.
	 * Only call on api level >= 25.
	 * @param context    to access system services
	 * @param channelId  id of the channel you want to remove from shorcut menu
     */
	@TargetApi(25)
	public void removeShortcutForChannel(Context context, String channelId) {
		ShortcutManager shortcutManager = context.getSystemService(ShortcutManager.class);
		shortcutManager.removeDynamicShortcuts(Collections.singletonList(channelId));
	}

	/**
	 * Call to report a shortcut used.
	 * You may call this using any api level.
	 * @param context   to access system services
	 * @param channelId id of the channel that has been selected
     */
	public void reportShortcutUsageGuarded(Context context, String channelId) {
		if (areShortcutsSupported()) {
			ShortcutManager shortcutManager = context.getSystemService(ShortcutManager.class);
			shortcutManager.reportShortcutUsed(channelId);
		}
	}

	/**
	 * @return true if the current api level supports shortcuts
     */
	public boolean areShortcutsSupported() {
		return Build.VERSION.SDK_INT >= Build.VERSION_CODES.N_MR1;
	}
}

Create helper class to easily use shortcuts


//
// PanActivator.java
//

/*
ImageJ software for multidimensional image processing and analysis.

Copyright (c) 2010, ImageJDev.org.
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 names of the ImageJDev.org developers 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 HOLDERS OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/

package imagej.core.tools.global;

import imagej.display.event.key.KyPressedEvent;
import imagej.display.event.key.KyReleasedEvent;
import imagej.tool.AbstractTool;
import imagej.tool.ITool;
import imagej.tool.Tool;
import imagej.tool.ToolService;

/**
 * Tool for activating the pan tool in response to the space bar.
 *
 * @author Curtis Rueden
 */
@Tool(name = "Pan Activator", global = true)
public class PanActivator extends AbstractTool {

	/** Key used to activate pan tool. */
	private static final char KEY = ' ';

	/** Previously active tool, from before pan key was held. */
	private ITool priorTool;

	@Override
	public void onKeyDown(final KyPressedEvent evt) {
		if (evt.getCharacter() != KEY) return;
		final ToolService toolService =
			evt.getContext().getService(ToolService.class);
		final ITool activeTool = toolService.getActiveTool();
		final ITool panTool = toolService.getTool("Pan");
		if (activeTool == panTool) return;
		priorTool = activeTool;
		toolService.setActiveTool(panTool);
	}

	@Override
	public void onKeyUp(final KyReleasedEvent evt) {
		if (evt.getCharacter() != KEY) return;
		final ToolService toolService =
			evt.getContext().getService(ToolService.class);
		toolService.setActiveTool(priorTool);
	}

}

Enable pan tool when space is pressed.

Enable pan tool when space is pressed.

This used to be revision r3588.


/*
 *
 *
 * Copyright (C) 2006 SIPfoundry Inc.
 * Licensed by SIPfoundry under the LGPL license.
 *
 * Copyright (C) 2006 Pingtel Corp.
 * Licensed to SIPfoundry under a Contributor Agreement.
 *
 * $
 */
package org.sipfoundry.sipxconfig.site;

import org.sipfoundry.sipxconfig.admin.commserver.imdb.ReplicationManagerImpl;
import org.sipfoundry.sipxconfig.domain.DomainInitializer;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationListener;

/**
 * Hook to mimic what a real system does when it starts up, and that is to create
 * initial, required, system data.
 */
public class InitializeTestSystem implements ApplicationListener {
    private DomainInitializer m_domainInitializer;
    private ReplicationManagerImpl m_replicationManagerImpl;

    public DomainInitializer getDomainInitializer() {
        return m_domainInitializer;
    }

    public void setDomainInitializer(DomainInitializer domainInitializer) {
        m_domainInitializer = domainInitializer;
    }

    public void onApplicationEvent(ApplicationEvent event) {
        // decided to pick a ficticious name rather than allowing default hostname to be used
        // this should simplify unit tests by letting them validate against exact values.
        m_domainInitializer.setInitialDomain("example.org");
        m_domainInitializer.onInitTask(null);

        m_replicationManagerImpl.setEnabled(false);
    }

    public void setReplicationManagerImpl(ReplicationManagerImpl replicationManagerImpl) {
        m_replicationManagerImpl = replicationManagerImpl;
    }
}

FIX BUILD - Add nec. file

FIX BUILD - Add nec. file

git-svn-id: f26ccc5efe72c2bd8e1c40f599fe313f2692e4de@9174 a612230a-c5fa-0310-af8b-88eea846685b


package ch.uzh.ddis.katts.utils;

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

import org.apache.zookeeper.ZooKeeper;

import backtype.storm.Config;

public final class Cluster {

	public static ZooKeeper createZooKeeper(Map conf) throws IOException {

		@SuppressWarnings("unchecked")
		List<String> zooKeeperServers = (List<String>)conf.get(Config.STORM_ZOOKEEPER_SERVERS);

		Integer port = (Integer)conf.get(Config.STORM_ZOOKEEPER_PORT);

		StringBuilder connection = new StringBuilder();

		for (String server : zooKeeperServers) {
			connection.append(server).append(":").append(port).append(",");
		}

		return new ZooKeeper(connection.toString(), 3000, null);
	}

}

Add missing Util class for constructing ZooKeeper instances from storm configuration.


/*-
 * Copyright 2016 Diamond Light Source Ltd.
 *
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 */

package org.eclipse.dawnsci.analysis.api.image;

import org.eclipse.dawnsci.analysis.api.dataset.IDataset;

public interface IImageTracker {

	/**
	 * Initialise the tracker given a default location of a region of interest, an input data and a {@link TrackerType}.
	 * <br>
	 * The location is a double array of size 8.
	 *
	 * @param input
	 * @param location
	 * @param type
	 * @throws Exception
	 */
	public void initialize(IDataset input, double[] location, TrackerType type) throws Exception;

	/**
	 * Track a region of interest on an input data
	 *
	 * @param data
	 * @return new location of tracked region
	 * @throws Exception
	 */
	public double[] track(IDataset data) throws Exception;

	/**
	 * TrackerType:
	 *
	 */
	public enum TrackerType {
		TLD,
		CIRCULANT,
		SPARSEFLOW,
		MEANSHIFTCOMANICIU2003;
	}
}

Add new image tracker service

Add new image tracker service


package leetcode.remove_duplicates_from_sorted_list_ii;

import java.util.ArrayList;
import java.util.Random;

import common.ListNode;

public class Solution {
	public ListNode deleteDuplicates(ListNode head) {
		if(head == null) return null;
		ListNode cur = head;
		ListNode prev = null;
		while(cur != null){
			boolean dup = false;
			while(cur.next != null && cur.next.val == cur.val){
				cur.next = cur.next.next;
				dup = true;
			}
			ListNode nxt = cur.next;
			if(dup){
				if(prev == null){
					head = nxt;
				}else{
					prev.next = nxt;
				}
			}else{
				prev = cur;
			}
			cur = nxt;
		}
		return head;
	}

	public static void dump(ListNode head){
		ListNode cur = head;
		while(cur != null){
			System.err.print(cur.val + ", ");
			cur = cur.next;
		}
		System.err.println("");
	}

	public static void main(String[] args){
		final int N = 3;
		Random r = new Random();
		ArrayList<ListNode> ary = new ArrayList<ListNode>();
		for(int i = 0; i < N; i++){
			int v = 0;
			if(i > 0) v = ary.get(i - 1).val;
			ary.add(new ListNode(v + r.nextInt(2)));
			if(i > 0) ary.get(i - 1).next = ary.get(i);
		}
		dump(ary.get(0));
		dump(new Solution().deleteDuplicates(ary.get(0)));
	}
}

Add java solution for 82. Remove Duplicates from Sorted List II

82. Remove Duplicates from Sorted List II: https://leetcode.com/problems/remove-duplicates-from-sorted-list-ii/


package com.nesscomputing.jackson;

import static org.junit.Assert.assertEquals;

import java.util.Map.Entry;

import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.type.TypeReference;
import org.junit.Before;
import org.junit.Test;

import com.google.common.collect.Maps;
import com.google.inject.Guice;
import com.google.inject.Inject;
import com.nesscomputing.config.ConfigModule;

public class TestMapEntryDeserialization
{
    @Inject
    ObjectMapper mapper;

    @Before
    public void setUp()
    {
        Guice.createInjector(ConfigModule.forTesting(), new NessJacksonModule()).injectMembers(this);
    }

    @Test
    public void testMapEntrySerialization() throws Exception
    {
        Entry<String, Integer> entry = Maps.immutableEntry("hi", 3);
        assertEquals(entry, mapper.readValue(mapper.writeValueAsString(entry), new TypeReference<Entry<String, Integer>>() {}));
    }

    @Test
    public void testMapEntryNullValueSerialization() throws Exception
    {
        Entry<String, Integer> entry = Maps.immutableEntry("hi", null);
        assertEquals(entry, mapper.readValue(mapper.writeValueAsString(entry), new TypeReference<Entry<String, Integer>>() {}));
    }

    @Test
    public void testMapEntryNullKeySerialization() throws Exception
    {
        Entry<String, Integer> entry = Maps.immutableEntry(null, 3);
        assertEquals(entry, mapper.readValue(mapper.writeValueAsString(entry), new TypeReference<Entry<String, Integer>>() {}));
    }
}

Add (failing) test case for Map.Entry<K, V> deserialization


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

package org.apache.commons.lang3.mutable;

import java.util.concurrent.atomic.AtomicInteger;

import org.apache.commons.lang3.time.DurationUtils;

/**
 * Prints out the difference time working with {@link MutableInt} and {@link AtomicInteger}.
 */
public class PrintAtomicVsMutable {

    public static void main(String[] args) {
        MutableInt mInt = new MutableInt();
        final int max = 100_000_000;
        System.out.println("MutableInt " + DurationUtils.of(() -> {
            for (int i = 0; i < max; i++) {
                mInt.incrementAndGet();
            }
        }));
        AtomicInteger aInt = new AtomicInteger();
        System.out.println("AtomicInteger " + DurationUtils.of(() -> {
            for (int i = 0; i < max; i++) {
                aInt.incrementAndGet();
            }
        }));
    }
}

Add a main test class to prints out the difference time working with MutableInt AtomicInteger.


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

package com.akiban.server.encoding;

import org.junit.Test;

import static org.junit.Assert.assertEquals;

abstract public class LongEncoderTestBase {
    static protected class TestElement {
        private final long longVal;
        private final Number number;
        private final String string;

        public TestElement(String s, Number n) {
            this.longVal = n.longValue();
            this.number = n;
            this.string = s;
        }

        @Override
        public String toString() {
            return String.format("(%d, %s, %s)", longVal, number, string);
        }
    }

    protected final LongEncoderBase ENCODER;
    protected final TestElement[] TEST_CASES;

    public LongEncoderTestBase(LongEncoderBase encoder, TestElement[] testElements) {
        this.ENCODER = encoder;
        this.TEST_CASES = testElements;
    }

    protected String encodeAndDecode(String str) {
        final long val = ENCODER.encodeFromObject(str);
        return ENCODER.decodeToString(val);
    }

    @Test
    public void encodingToLong() {
        for(TestElement t : TEST_CASES) {
            final long encodeFromNum = ENCODER.encodeFromObject(t.number);
            final long encodeFromStr = ENCODER.encodeFromObject(t.string);
            assertEquals("Number->long: " + t, t.longVal, encodeFromNum);
            assertEquals("String->long: " + t, t.longVal, encodeFromStr);
        }
    }

    @Test
    public void decodingToString() {
        for(TestElement t : TEST_CASES) {
            final String decoded = ENCODER.decodeToString(t.longVal);
            assertEquals("long->String: " + t, t.string, decoded);
        }
    }

    @Test
    public void nullIsZero() {
        assertEquals(0, ENCODER.encodeFromObject(null));
        assertEquals("0000", ENCODER.decodeToString(0));
    }
}

Add base class for LongEncoder based tests.


/*
 * Copyright 2016 Serge Silaev aka iSergio <s.serge.b@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.ol3cesium.client.ol;

/**
 *
 * @author Serge Silaev aka iSergio <s.serge.b@gmail.com>
 */
public enum OverlayPositioning {
    BOTTOM_LEFT("bottom-left"), BOTTOM_CENTER("bottom-center"), BOTTOM_RIGHT("bottom-right"),
    CENTER_LEFT("center-left"), CENTER_CENTER("center-center"), CENTER_RIGHT("center-right"),
    TOP_LEFT("top-left"), TOP_CENTER("top-center"), TOP_RIGHT("top-right"),
    UNKNOWN("unknown");

    private final String _value;

    private OverlayPositioning(String value) {
        _value = value;
    }

    public static OverlayPositioning fromString(String string) {
        if (BOTTOM_LEFT.toString().equalsIgnoreCase(string)) {
            return BOTTOM_LEFT;
        }
        else if (BOTTOM_CENTER.toString().equalsIgnoreCase(string)) {
            return BOTTOM_CENTER;
        }
        else if (BOTTOM_RIGHT.toString().equalsIgnoreCase(string)) {
            return BOTTOM_RIGHT;
        }
        else if (CENTER_LEFT.toString().equalsIgnoreCase(string)) {
            return CENTER_LEFT;
        }
        else if (CENTER_CENTER.toString().equalsIgnoreCase(string)) {
            return CENTER_CENTER;
        }
        else if (CENTER_RIGHT.toString().equalsIgnoreCase(string)) {
            return CENTER_RIGHT;
        }
        else if (TOP_LEFT.toString().equalsIgnoreCase(string)) {
            return TOP_LEFT;
        }
        else if (TOP_CENTER.toString().equalsIgnoreCase(string)) {
            return TOP_CENTER;
        }
        else if (TOP_RIGHT.toString().equalsIgnoreCase(string)) {
            return TOP_RIGHT;
        } else {
            return UNKNOWN;
        }
    }

    @Override
    public String toString() {
        return _value;
    }
}

Add enumiration for overlay positioning.


package devopsdistilled.operp.client.items.model;

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

import javax.inject.Inject;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import devopsdistilled.operp.client.context.AppContext;
import devopsdistilled.operp.client.items.models.ItemModel;
import devopsdistilled.operp.server.data.entity.items.Item;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = { AppContext.class })
public class ItemModelTest {

	@Inject
	private ItemModel itemModel;

	private Item item;

	@Before
	public void setUp() throws Exception {
		item = new Item();

		assertNotNull(itemModel);
	}

	@Test
	public void testSaveAndUpdateModel() {

		// This test won't run if Unique constraints are set in Item Entity.
		// Unique Constraints were removed to test this Test.

		itemModel.update();
		int initialItemsSize = itemModel.getEntities().size();
		item.setItemName("Test Item");
		Item savedItem = itemModel.saveAndUpdateModel(item);
		assertNotNull(savedItem);
		System.out.println(savedItem.getItemId());
		int afterUpdateSize = itemModel.getEntities().size();
		// assertThat(initialItemsSize, is(afterUpdateSize - 1));
		assertEquals(new Long(initialItemsSize), new Long(afterUpdateSize - 1));
	}

}

Add Unit Test to test ItemModel.saveAndUpdateModel()


package com.zzsoft.githubandroidclientsample;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

public class UserListActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_user_list);
    }
}

Revert "adding userinfo presenter and view imp"

This reverts commit f39a7d54f759611ea85303fef851be48b53bf218.


package org.orekit.attitudes;

import org.orekit.errors.OrekitException;
import org.orekit.frames.Frame;
import org.orekit.time.AbsoluteDate;
import org.orekit.utils.PVCoordinatesProvider;

/** This class is a bridge between an {@link AttitudeLaw AttitudeLaw} and an {@link AttitudeProvider AttitudeProvider} .
 *
An attitude law wrapper provider provides a way to implement an {@link AttitudeProvider AttitudeProvider}
 * from an {@link AttitudeLaw AttitudeLaw}.

 * @author Véronique Pommier-Maurussane
 * @version $Revision:1665 $ $Date:2008-06-11 12:12:59 +0200 (mer., 11 juin 2008) $
 */

public class AttitudeLawWrapperProvider implements AttitudeProvider {

    /** Serializable UID. */
    private static final long serialVersionUID = -5959598401777708386L;

    /** Attitude provider. */
    AttitudeLaw attLaw;

    /** Create new instance.
     * @param referenceFrame reference frame from which attitude is defined
     * @param attProvider attitude provider
     * @param pvProvider position-velocity provider
    */
    public AttitudeLawWrapperProvider(final AttitudeLaw attLaw) {
        this.attLaw = attLaw;
    }

    /** @inherit */
    public Attitude getAttitude(PVCoordinatesProvider pvProv,
                                AbsoluteDate date, Frame frame)
        throws OrekitException {

        return attLaw.getAttitude(date);
    }

}

Add Attitude law wrapper provider.

Add Attitude law wrapper provider.


package org.robockets.tshirtcannon.subsystems.cannon;

import edu.wpi.first.wpilibj.command.Command;
import org.robockets.tshirtcannon.RobotMap;
import org.robockets.tshirtcannon.ZAxisRelativeDirection;

/**
 * Move the cannon up or down
 */
public class AdjustCannon extends Command {
    ZAxisRelativeDirection dir;
    public AdjustCannon(ZAxisRelativeDirection dir) {
        requires(RobotMap.cannonSubsystem);
        this.dir = dir;
    }
    protected void initialize() {
    }

    // Called repeatedly when this Command is scheduled to run
    protected void execute() {
        RobotMap.cannonSubsystem.adjustAngle(dir);
    }

    // Make this return true when this Command no longer needs to run execute()
    protected boolean isFinished() {
        return false; //TODO: get a real value here
    }

    // Called once after isFinished returns true
    protected void end() {
    }

    // Called when another command which requires one or more of the same
    // subsystems is scheduled to run
    protected void interrupted() {
    }
}

Add command for adjusting the cannon

Add command for adjusting the cannon

isFinished() probably shouldn't return false, but we'll leave it at that until we have something better.


package org.uma.jmetal.util.pseudorandom;

/**
 * A {@link BoundedRandomGenerator} aims to provide a random value within a
 * specific range. The range is inclusive, such that the lower bound and upper
 * bound can be generated. Because lower and upper bounds make no sense if
 * values cannot be compared, only {@link Comparable} values can be generated
 * through this kind of generator.

 *

 * A {@link BoundedRandomGenerator} is a {@link FunctionalInterface}. It is not
 * intended to be directly implemented by a class, but instead to request a
 * method for generating random values, usually by using lambda expressions.
 *
 * @author Matthieu Vergne <matthieu.vergne@gmail.com>
 *
 * @param <Value>
 *            The type of value to generate
 */
@FunctionalInterface
public interface BoundedRandomGenerator<Value extends Comparable<Value>> {
	/**
	 * Generate a random value within the provided range.
	 *
	 * @param lowerBound
	 *            the minimal value which can be generated
	 * @param upperBound
	 *            the maximal value which can be generated
	 * @return the value generated
	 */
	public Value getRandomValue(Value lowerBound, Value upperBound);
}

Add a functional interface for bounded random generators.


package com.elytradev.movingworld.common.network.marshallers;

import io.github.elytra.concrete.Marshaller;
import io.netty.buffer.ByteBuf;
import net.minecraftforge.fml.common.network.ByteBufUtils;

/**
 * Code from Concrete that's not available in 0.0.6 builds.
 */
public class ByteBufMarshaller implements Marshaller<ByteBuf> {

    public static final String MARSHALLER_NAME = "com.elytradev.movingworld.common.network.marshallers.ByteBufMarshaller";
    public static final ByteBufMarshaller INSTANCE = new ByteBufMarshaller();

    @Override
    public ByteBuf unmarshal(ByteBuf in) {
        int length = ByteBufUtils.readVarInt(in, 5);

        return in.readBytes(length);
    }

    @Override
    public void marshal(ByteBuf out, ByteBuf t) {
        if (t != null) {
            ByteBufUtils.writeVarInt(out, t.readableBytes(), 5);
            out.writeBytes(t.readBytes(t.readableBytes()));
        } else {
            ByteBufUtils.writeVarInt(out, 0, 5);
        }
    }
}

Add a byte buf marshaller for use until Concrete 0.0.7+ is on maven.


package com.alexrnl.jbetaseries.request.episodes;

import com.alexrnl.jbetaseries.request.APIAddresses;
import com.alexrnl.jbetaseries.request.Request;
import com.alexrnl.jbetaseries.request.Verb;
import com.alexrnl.jbetaseries.request.parameters.Id;

/**
 * Request which allow to mark episodes as unseen.

 * @author Alex
 */
public class EpisodeUnwatched extends Request {

	/**
	 * Constructor #1.

	 * @param episodeId
	 *        the id of the episode to mark as unseen.
	 */
	public EpisodeUnwatched (final Integer episodeId) {
		super(Verb.DELETE, APIAddresses.EPISODES_WATCHED);
		addParameter(new Id(episodeId));
	}
}

Add the episodes/watched (DELETE) request


/*
 * Copyright 2015 Rackspace
 *
 *    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.rackspacecloud.blueflood.utils;

import com.rackspacecloud.blueflood.io.DiscoveryIO;
import com.rackspacecloud.blueflood.service.Configuration;
import com.rackspacecloud.blueflood.service.CoreConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;

public class DiscoveryModuleLoader {
    private static final Logger log = LoggerFactory.getLogger(DiscoveryModuleLoader.class);
    private static DiscoveryIO discoveryInstance;

    public static synchronized void loadDiscoveryModule() {
        if (discoveryInstance != null) {
            log.warn("Discovery module %s already loaded", discoveryInstance.getClass());
            return;
        }
        List<String> modules = Configuration.getInstance().getListProperty(CoreConfig.DISCOVERY_MODULES);

        if (!modules.isEmpty() && modules.size() != 1) {
            throw new RuntimeException("Cannot load query service with more than one discovery module");
        }

        ClassLoader classLoader = DiscoveryIO.class.getClassLoader();
        for (String module : modules) {
            log.info("Loading metric discovery module " + module);
            try {
                Class discoveryClass = classLoader.loadClass(module);
                discoveryInstance = (DiscoveryIO) discoveryClass.newInstance();
                log.info("Registering metric discovery module " + module);
            } catch (InstantiationException e) {
                log.error("Unable to create instance of metric discovery class for: " + module, e);
            } catch (IllegalAccessException e) {
                log.error("Error starting metric discovery module: " + module, e);
            } catch (ClassNotFoundException e) {
                log.error("Unable to locate metric discovery module: " + module, e);
            } catch (RuntimeException e) {
                log.error("Error starting metric discovery module: " + module, e);
            } catch (Throwable e) {
                log.error("Error starting metric discovery module: " + module, e);
            }
        }

    }

    public static DiscoveryIO getDiscoveryInstance() {
        return discoveryInstance;
    }
}

Move discovery module loader to core, to avoid cyclic dependencies


public class TestaMenorPreco {

  public static void main(String[] args) {

    double precos[] = new double[5];
    precos[0] = 1000000;
    precos[1] = 46000;
    precos[2] = 16000;
    precos[3] = 46000;
    precos[4] = 17000;

    int maisBarato = 0;
    //int atual = 0;

    for(int atual = 0; atual < precos.length; atual++) {
      if(precos[atual] < precos[maisBarato]) {
        maisBarato = atual;
      }
    }

    System.out.println(maisBarato);
    System.out.println("O carro mais barato custa " + precos[maisBarato]);

  }

}

Insert new files, Alura, Projeto de Algoritmos 1, Aula 6


package com.github.dnault.therapi.core;

import com.github.dnault.therapi.core.annotation.Remotable;
import org.junit.Before;
import org.junit.Test;

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

public class ReturnValueNotSlicedTest extends AbstractMethodRegistryTest {

    @Before
    public void setup() {
        registry.scan(new SlicingServiceImpl());
    }

    @Remotable("")
    @SuppressWarnings("unused")
    private interface SlicingService {
        Base get();

        List<Base> list();
    }

    private static class SlicingServiceImpl implements SlicingService {
        @Override
        public Base get() {
            return new Subclass("foo", "bar");
        }

        @Override
        public List<Base> list() {
            return Arrays.asList(new Subclass("foo", "bar"), new Subclass("baz", "zot"));
        }
    }

    private static class Base {
        private final String base;

        public Base(String base) {
            this.base = base;
        }

        public String getBase() {
            return base;
        }
    }

    private static class Subclass extends Base {
        private final String subclass;

        public Subclass(String base, String subclass) {
            super(base);
            this.subclass = subclass;
        }

        public String getSubclass() {
            return subclass;
        }
    }

    @Test
    public void subclassPropertiesAreIncludedEvenThoughDeclaredReturnTypeIsBase() throws Exception {
        check("get", "[]", "{base:'foo',subclass:'bar'}");
    }

    @Test
    public void subclassPropertiesAreIncludedInListEvenThoughDeclaredReturnTypeIsBase() throws Exception {
        check("list", "[]", "[{base:'foo',subclass:'bar'},{base:'baz',subclass:'zot'}]");
    }
}

Add unit test to make sure return values are not sliced


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

import com.ushahidi.android.BuildConfig;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.RobolectricGradleTestRunner;
import org.robolectric.annotation.Config;

import static com.google.common.truth.Truth.assertThat;

/**
 * Tests {@link GeoJson}
 *
 * @author Ushahidi Team <team@ushahidi.com>
 */
@RunWith(RobolectricGradleTestRunner.class)
@Config(sdk = 21, constants = BuildConfig.class)
public class GeoJsonTest {

    private GeoJson mGeoJson;

    private static final Long DUMMY_ID = 1l;

    private static final Long DUMMY_DEPLOYMENT_ID = 1l;

    private static final String DUMMY_STRING = "Dummy Deployment Title";

    @Before
    public void setUp() {
        mGeoJson = new GeoJson();
    }

    @Test
    public void shouldCreateGeoJson() {
        mGeoJson._id = DUMMY_ID;
        mGeoJson.setDeploymentId(DUMMY_DEPLOYMENT_ID);
        mGeoJson.setGeoJson(DUMMY_STRING);

        assertThat(mGeoJson).isNotNull();
        assertThat(mGeoJson).isInstanceOf(GeoJson.class);
        assertThat(mGeoJson._id).isEqualTo(DUMMY_ID);
        assertThat(mGeoJson.getDeploymentId()).isEqualTo(DUMMY_DEPLOYMENT_ID);
        assertThat(mGeoJson.getGeoJson()).isEqualTo(DUMMY_STRING);
    }
}

Add test for geojson entity

Add test for geojson entity


package si.mazi.rescu;

import org.testng.annotations.Test;

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

public class RestProxyFactoryImplTest {

    @Test
    public void testCreateProxy() {
        IRestProxyFactory f = new RestProxyFactoryImpl();
        ExampleService proxy = f.createProxy(ExampleService.class, "http://example.com/api");

        assertThat(proxy).isNotNull();
    }

    @Test
    public void testCreateProxy1() {
        IRestProxyFactory f = new RestProxyFactoryImpl();
        ExampleService proxy = f.createProxy(ExampleService.class, "http://example.com/api", new ClientConfig());

        assertThat(proxy).isNotNull();
    }
}

Add a simple test for RestProxyFactoryImpl


/*
 * Copyright (c) 2016 Stichting Yona Foundation
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at https://mozilla.org/MPL/2.0/.
 */

package nu.yona.app.api.model;

import android.content.ContentValues;

/**
 * Created by bhargavsuthar on 23/06/16.
 */
public class YonaHeaderTheme extends BaseEntity {

    private int header_rightIcon;

    private int header_leftIcon;

    private String header_title;

    private int toolbar;

    private int headercolor;

    private String fetchUrl;

    private boolean isBuddyFlow;

    public boolean isBuddyFlow() {
        return isBuddyFlow;
    }

    public void setBuddyFlow(boolean buddyFlow) {
        isBuddyFlow = buddyFlow;
    }

    public String getFetchUrl() {
        return fetchUrl;
    }

    public void setFetchUrl(String fetchUrl) {
        this.fetchUrl = fetchUrl;
    }

    public int getHeader_rightIcon() {
        return header_rightIcon;
    }

    public void setHeader_rightIcon(int header_rightIcon) {
        this.header_rightIcon = header_rightIcon;
    }

    public int getHeader_leftIcon() {
        return header_leftIcon;
    }

    public void setHeader_leftIcon(int header_leftIcon) {
        this.header_leftIcon = header_leftIcon;
    }

    public String getHeader_title() {
        return header_title;
    }

    public void setHeader_title(String header_title) {
        this.header_title = header_title;
    }

    public int getToolbar() {
        return toolbar;
    }

    public void setToolbar(int toolbar) {
        this.toolbar = toolbar;
    }

    public int getHeadercolor() {
        return headercolor;
    }

    public void setHeadercolor(int headercolor) {
        this.headercolor = headercolor;
    }

    @Override
    public ContentValues getDbContentValues() {
        return null;
    }
}

[APPDEV-442] Create class for data transferring between two fragments


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

package com.google.android.libraries.remixer.ui.widget;

import android.support.annotation.Keep;
import android.support.annotation.NonNull;
import com.google.android.libraries.remixer.Variable;
import com.google.android.libraries.remixer.ui.view.RemixerFragment;

/**
 * An interface that all remixer widgets must implement.
 *
 *
This lets the {@link RemixerFragment} bind them to a {@link Variable} when they are
 * inflated.
 */
@Keep
public interface RemixerWidget<T extends Variable> {
  /**
   * Binds the variable item to the widget in question.
   *
   *
Subclasses need to set up all the callbacks from the UI to set the appropriate value on the
   * backing Variable.
   */
  void bindVariable(@NonNull T variable);
}

Add missing new file, remixer widget

Add missing new file, remixer widget


/*
 * Copyright 2018 Daniel Gredler
 *
 * 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 uk.org.okapibarcode.backend;

import org.junit.Assert;
import org.junit.Test;

/**
 * Unit tests for {@link AddOn}.
 */
public class AddOnTest {

    @Test
    public void testCalcAddOn() {
        AddOn addOn = new AddOn();
        Assert.assertEquals("",                                addOn.calcAddOn(""));
        Assert.assertEquals("1123211111222",                   addOn.calcAddOn("1"));
        Assert.assertEquals("1122221112122",                   addOn.calcAddOn("12"));
        Assert.assertEquals("1121123111123112221112122111411", addOn.calcAddOn("123"));
        Assert.assertEquals("1123211111222112212111411111132", addOn.calcAddOn("1234"));
        Assert.assertEquals("1121222112122111141111132111231", addOn.calcAddOn("12345"));
        Assert.assertEquals("",                                addOn.calcAddOn("123456"));
        Assert.assertEquals("",                                addOn.calcAddOn("1234567"));
    }
}

Add basic test for the AddOn class

Add basic test for the AddOn class


package com.chimbori.crux.urls;

import org.junit.Test;

import static org.junit.Assert.assertEquals;

public class RedirectorsTest {
  @Test
  public void testGoogleRedirectors() {
    assertEquals("https://www.facebook.com/permalink.php?id=111262459538815&story_fbid=534292497235807&ct=ga&cd=CAEYACoTOTQxMTQ5NzcyMzExMjAwMTEyMzIcZWNjZWI5M2YwM2E5ZDJiODpjb206ZW46VVM6TA&usg=AFQjCNFSwGsQjcbeVCaSO2rg90RgBpQvzA&source=gmail&ust=1589164930980000&usg=AFQjCNF37pEGpMAz7azFCry-Ib-hwR0VVw",
        CruxURL.parse("https://www.google.com/url?q=https://www.google.com/url?rct%3Dj%26sa%3Dt%26url%3Dhttps://www.facebook.com/permalink.php%253Fid%253D111262459538815%2526story_fbid%253D534292497235807%26ct%3Dga%26cd%3DCAEYACoTOTQxMTQ5NzcyMzExMjAwMTEyMzIcZWNjZWI5M2YwM2E5ZDJiODpjb206ZW46VVM6TA%26usg%3DAFQjCNFSwGsQjcbeVCaSO2rg90RgBpQvzA&source=gmail&ust=1589164930980000&usg=AFQjCNF37pEGpMAz7azFCry-Ib-hwR0VVw").resolveRedirects().toString());
  }
}

Add a test, currently failing, for the google.com redirectors.


package junit.org.rapidpm.frp.model;

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

import org.junit.jupiter.api.Test;
import org.rapidpm.frp.model.Triple;

public class TripleTest {

  @Test
  public void testEquals() {
    final Triple triple = new Triple(0, 1, 2);

    assertTrue(triple.equals(triple));
    assertFalse(triple.equals(null));
    assertFalse(triple.equals(new Triple(null, 1, 2)));
    assertFalse(triple.equals(new Triple(0, null, 2)));
  }

  @Test
  public void testEqualsT1() {
    final Triple triple = new Triple(null, 1, 2);

    assertTrue(triple.equals(new Triple(null, 1, 2)));
    assertFalse(triple.equals(new Triple(0, 1, 2)));
  }

  @Test
  public void testEqualsT2() {
    final Triple triple = new Triple(0, null, 2);

    assertTrue(triple.equals(new Triple(0, null, 2)));
    assertFalse(triple.equals(new Triple(0, 1, 2)));
  }

  @Test
  public void testEqualsT3() {
    final Triple triple = new Triple(0, 1, null);

    assertTrue(triple.equals(new Triple(0, 1, null)));
    assertFalse(triple.equals(new Triple(0, 1, 2)));
  }

  @Test
  public void testHashCode() {
    final Triple triple = new Triple(0, 1, 2);

    assertEquals(33, triple.hashCode());
  }

  @Test
  public void testHashCodeT1() {
    final Triple triple = new Triple(null, 1, 2);

    assertEquals(33, triple.hashCode());
  }

  @Test
  public void testHashCodeT2() {
    final Triple triple = new Triple(0, null, 2);

    assertEquals(2, triple.hashCode());
  }

  @Test
  public void testHashCodeT3() {
    final Triple triple = new Triple(0, 1, null);

    assertEquals(31, triple.hashCode());
  }

  @Test
  public void testNext() {
    final Triple triple = Triple.next(0, 1, 2);

    assertNotNull(triple);
    assertEquals(0, triple.getT1());
    assertEquals(1, triple.getT2());
    assertEquals(2, triple.getT3());
  }

  @Test
  public void testToString() {
    final Triple triple = new Triple(0, 1, 2);

    assertEquals("Triple{t1=0, t2=1, t3=2}", triple.toString());
  }
}

Add unit tests for org.rapidpm.frp.model.Triple These tests were written using Diffblue Cover.


package net.openhft.chronicle.wire;

import net.openhft.chronicle.bytes.Bytes;
import net.openhft.chronicle.bytes.HexDumpBytes;
import org.junit.Test;

import static junit.framework.TestCase.assertEquals;

public class HexDumpTest {
    @Test
    public void testEndian() {
        Bytes b = new HexDumpBytes();
        b.writeInt(0x0a0b0c0d);
        assertEquals("0d 0c 0b 0a\n", b.toHexString());
    }
}

Add a test showing HexDumpBytes is little endian (on machines which are little endian)


package org.museautomation.builtins.value.string;

import org.junit.jupiter.api.*;
import org.museautomation.builtins.value.file.*;
import org.museautomation.core.*;
import org.museautomation.core.mocks.*;
import org.museautomation.core.resource.*;
import org.museautomation.core.values.*;

import java.io.*;

/**
 * @author Christopher L Merrill (see LICENSE.txt for license details)
 */
public class StringUtilitySourceTests
    {
    @Test
    public void cutString() throws MuseInstantiationException, ValueSourceResolutionError
        {
        ValueSourceConfiguration config = ValueSourceConfiguration.forType(CutStringSource.TYPE_ID);
        config.addSource(CutStringSource.SOURCE_PARAM, ValueSourceConfiguration.forValue("https://a.1stdibscdn.com/classical-marble-bust-of-hermes-holding-dionysus-after-the-antique-by-praxiteles-for-sale-picture-2/f_10590/1579695197244/Large_Marble_Sculpture_Male_Bust03_master.jpg?width=768"));
        config.addSource(CutStringSource.MAX_LENGTH_PARAM, ValueSourceConfiguration.forValue(12));
        config.addSource(CutStringSource.FROM_END_PARAM, ValueSourceConfiguration.forValue(true));
        MuseValueSource source = config.createSource();
        Assertions.assertEquals("https://a.1s", source.resolveValue(new MockStepExecutionContext()));

        config.removeSource(CutStringSource.FROM_END_PARAM);
        config.addSource(CutStringSource.FROM_END_PARAM, ValueSourceConfiguration.forValue(false));
        source = config.createSource();
        Assertions.assertEquals("pg?width=768", source.resolveValue(new MockStepExecutionContext()));
        }
    }

Add unit test for Cut String source

[core] Add unit test for Cut String source


/***********************************************************************
 * Copyright (c) 2006 The Apache Software Foundation.                  *
 * All rights reserved.                                                *
 * ------------------------------------------------------------------- *
 * 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.apache.james.transport.matchers;

import java.io.UnsupportedEncodingException;
import java.util.Collection;

import javax.mail.MessagingException;

import org.apache.mailet.MailAddress;
import org.apache.mailet.Matcher;

public class UserIsTest extends AbstractRecipientIsTest {

    private final String USER = "test";

    public UserIsTest(String arg0) throws UnsupportedEncodingException {
        super(arg0);
    }

    protected String getRecipientName() {
        return USER;
    }

    // test if the recipients get returned as matched
    public void testHostIsMatchedAllRecipients() throws MessagingException {
        setRecipients(new MailAddress[] { new MailAddress(
                "test@james.apache.org") });

        setupMockedMail();
        setupMatcher();

        Collection matchedRecipients = matcher.match(mockedMail);

        assertNotNull(matchedRecipients);
        assertEquals(matchedRecipients.size(), mockedMail.getRecipients()
                .size());
    }

    // test if one recipients get returned as matched
    public void testHostIsMatchedOneRecipient() throws MessagingException {
        setRecipients(new MailAddress[] {
                new MailAddress("test@james.apache.org"),
                new MailAddress("test2@james.apache.org") });

        setupAll();

        Collection matchedRecipients = matcher.match(mockedMail);

        assertNotNull(matchedRecipients);
        assertEquals(matchedRecipients.size(), 1);
    }

    // test if no recipient get returned cause it not match
    public void testHostIsNotMatch() throws MessagingException {
        setRecipients(new MailAddress[] {
                new MailAddress("test2@james2.apache.org"),
                new MailAddress("test2@james.apache.org") });

        setupMockedMail();
        setupMatcher();

        Collection matchedRecipients = matcher.match(mockedMail);

        assertEquals(matchedRecipients.size(), 0);
    }

    protected Matcher createMatcher() {
        return new UserIs();
    }
}

Add UserIs matcher junit test

Add UserIs matcher junit test

git-svn-id: de9d04cf23151003780adc3e4ddb7078e3680318@416435 13f79535-47bb-0310-9956-ffa450edef68


/*
 * 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.apache.karaf.cellar.obr.shell;

import org.apache.felix.bundlerepository.RepositoryAdmin;
import org.apache.karaf.cellar.core.shell.CellarCommandSupport;

public abstract class ObrCommandSupport extends CellarCommandSupport {

    protected RepositoryAdmin obrService;

    public RepositoryAdmin getObrService() {
        return this.obrService;
    }

    public void setObrService(RepositoryAdmin obrService) {
        this.obrService = obrService;
    }

    public abstract Object doExecute() throws Exception;

}

Add the OBR command support.

[KARAF-857] Add the OBR command support.

git-svn-id: 23a5554d8b20ee894ad801d0a5fe136f33ef549e@1170640 13f79535-47bb-0310-9956-ffa450edef68


package codesample.algorithms.mix;

import java.util.List;

public class BinarySearch<T extends Comparable<T>> {

    public static <T> List<T> search (List<T> array) {
        return null;
    }
}

Add stub for binary search example

Add stub for binary search example


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

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

import static org.junit.Assert.assertEquals;

/**
 * @author Pedro Vicente Gómez Sánchez.
 */
public class ReverseSentenceTest {

  private ReverseSentence reverseSentence;

  @Before public void setUp() {
    reverseSentence = new ReverseSentence();
  }

  @Test(expected = IllegalArgumentException.class) public void shouldNotAcceptNullStringsAsInput() {
    reverseSentence.reverse(null);
  }

  @Test public void shouldReturnEmptyIfInputIsEmpty() {
    assertEquals("", reverseSentence.reverse(""));
  }

  @Test public void shouldReverseOneSentenceWithJustOneWord() {
    String input = "pedro";

    String result = reverseSentence.reverse(input);

    assertEquals("pedro", result);
  }

  @Test public void shouldReverseSentenceWithMoreThanOneWord() {
    String input = "pedro vicente gómez";

    String result = reverseSentence.reverse(input);

    assertEquals("gómez vicente pedro", result);
  }
}

Add some tests to problem 27

Add some tests to problem 27


package com.fasterxml.jackson.dataformat.xml.deser;

import java.math.BigDecimal;

import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonRootName;
import com.fasterxml.jackson.annotation.JsonSubTypes;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.fasterxml.jackson.annotation.JsonUnwrapped;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.dataformat.xml.XmlMapper;
import com.fasterxml.jackson.dataformat.xml.XmlTestBase;

// Tests copied from databind "JDKNumberDeserTest" (only a small subset)
public class NumberDeserWithXMLTest extends XmlTestBase
{
    // [databind#2644]
    @JsonRootName("Root")
    static class NodeRoot2644 {
        public String type;

        @JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.EXTERNAL_PROPERTY, property = "type")
        @JsonSubTypes(value = {
                @JsonSubTypes.Type(value = NodeParent2644.class, name = "NodeParent")
        })
        public Node2644 node;
    }

    public static class NodeParent2644 extends Node2644 { }

    public static abstract class Node2644 {
        @JsonProperty("amount")
        BigDecimal val;

        public BigDecimal getVal() {
            return val;
        }

        public void setVal(BigDecimal val) {
            this.val = val;
        }
    }

    // [databind#2784]
    static class BigDecimalHolder2784 {
        public BigDecimal value;
    }

    @JsonRootName("Nested")
    static class NestedBigDecimalHolder2784 {
        @JsonUnwrapped
        public BigDecimalHolder2784 holder;
    }

    /*
    /**********************************************************************
    /* Test methods
    /**********************************************************************
     */

    private final XmlMapper MAPPER = newMapper();

    // [databind#2644]
    public void testBigDecimalSubtypes() throws Exception
    {
        ObjectMapper mapper = mapperBuilder()
                .registerSubtypes(NodeParent2644.class)
                .build();
        NodeRoot2644 root = mapper.readValue("<Root>\n"
                +"<type>NodeParent</type>"
                +"<node><amount>9999999999999999.99</amount></node>\n"
                +"</Root>\n",
                NodeRoot2644.class
        );

        assertEquals(new BigDecimal("9999999999999999.99"), root.node.getVal());
    }

    // [databind#2784]
    public void testBigDecimalUnwrapped() throws Exception
    {
        // mapper.enable(DeserializationFeature.USE_BIG_DECIMAL_FOR_FLOATS);
        final String DOC = "<Nested><value>5.00</value></Nested>";
        NestedBigDecimalHolder2784 result = MAPPER.readValue(DOC, NestedBigDecimalHolder2784.class);
        assertEquals(new BigDecimal("5.00"), result.holder.value);
    }
}

Add BigDecimal-related test (wrt holding precision)


package sg.ncl.testbed_interface.repositories.jpa.entities;

import org.apache.commons.lang3.RandomStringUtils;
import org.junit.Test;

import java.time.ZonedDateTime;
import java.util.Random;

import static org.hamcrest.Matchers.*;
import static org.junit.Assert.assertThat;

/**
 * @author Christopher Zhong
 */
public class LoginActivityEntityTest {

    @Test
    public void testGetId() throws Exception {
        final LoginActivityEntity loginActivityEntity = new LoginActivityEntity();

        assertThat(loginActivityEntity.getId(), is(nullValue()));
    }

    @Test
    public void testSetId() throws Exception {
        final LoginActivityEntity loginActivityEntity = new LoginActivityEntity();
        final Long id = new Random().nextLong();
        loginActivityEntity.setId(id);

        assertThat(loginActivityEntity.getId(), is(equalTo(id)));
    }

    @Test
    public void testGetIpAddress() throws Exception {
        final LoginActivityEntity loginActivityEntity = new LoginActivityEntity();

        assertThat(loginActivityEntity.getIpAddress(), is(nullValue()));
    }

    @Test
    public void testSetIpAddress() throws Exception {
        final LoginActivityEntity loginActivityEntity = new LoginActivityEntity();
        final String ipAddress = RandomStringUtils.randomAlphanumeric(20);
        loginActivityEntity.setIpAddress(ipAddress);

        assertThat(loginActivityEntity.getIpAddress(), is(equalTo(ipAddress)));
    }

    @Test
    public void testGetDate() throws Exception {
        final LoginActivityEntity loginActivityEntity = new LoginActivityEntity();

        assertThat(loginActivityEntity.getDate(), is(nullValue()));
    }

    @Test
    public void testSetDate() throws Exception {
        final LoginActivityEntity loginActivityEntity = new LoginActivityEntity();
        final ZonedDateTime now = ZonedDateTime.now();
        loginActivityEntity.setDate(now);

        assertThat(loginActivityEntity.getDate(), is(equalTo(now)));
    }

    @Test
    public void testToString() throws Exception {
        final LoginActivityEntity loginActivityEntity = new LoginActivityEntity();
        final Long id = new Random().nextLong();
        loginActivityEntity.setId(id);
        final String ipAddress = RandomStringUtils.randomAlphanumeric(20);
        loginActivityEntity.setIpAddress(ipAddress);
        final ZonedDateTime now = ZonedDateTime.now();
        loginActivityEntity.setDate(now);

        final String toString = loginActivityEntity.toString();

        assertThat(toString, containsString(id.toString()));
        assertThat(toString, containsString(ipAddress));
        assertThat(toString, containsString(now.toString()));
    }

}

Add unit test for LoginActivityEntity (DEV-15)


package de.darthpumpkin.pkmnlib;

/**
 * Thrown to indicate that a {@link Team} has been expanded above its allowed
 * maximum size.
 *
 * @author dominik
 *
 */
public class MaximumSizeExceededException extends RuntimeException {

	private final Integer maxSize;
	private final Integer previousSize;
	private final Integer newElements;

	/**
	 * Constructs a MaximumSizeExceededException with a message telling what was
	 * the allowed maximum size.
	 *
	 * @param maxSize
	 *            the exceeded maximum size.
	 */
	public MaximumSizeExceededException(Integer maxSize) {
		super("Maximum size of " + maxSize + " exceeded");
		this.maxSize = maxSize;
		this.previousSize = null;
		this.newElements = null;
	}

	/**
	 * Constructs a MaximumSizeExceededException with a message telling what was
	 * the allowed maximum size and how many elements were added to the team as
	 * well as how large the team was before the addition.
	 *
	 * @param maxSize
	 *            the exceeded maximum size.
	 * @param previousSize
	 *            the size before the insertion.
	 * @param newElements
	 *            the amount of new elements added to the team.
	 */
	public MaximumSizeExceededException(Integer maxSize, Integer previousSize,
			Integer newElements) {
		super("Maximum size of " + maxSize + " exceeded when trying to add "
				+ newElements + (newElements == 1 ? " element" : " elements")
				+ " to a team of size " + previousSize);
		this.maxSize = maxSize;
		this.previousSize = previousSize;
		this.newElements = newElements;
	}

	/**
	 * Returns the maximum size of the Collection whose size was exceeded.
	 *
	 * @return the maximum size
	 */
	public Integer maxSize() {
		return this.maxSize;
	}

	/**
	 * Returns the amount of elements in the Collection before the attempt to
	 * perform the manipulation that caused this Exception.
	 *
	 * @return the amount of elements in the Collection or null if it has not
	 *         been set
	 */
	public Integer previousSize() {
		return this.previousSize;
	}

	/**
	 * Returns the amount of elements that were attempted to insert into the
	 * Collection that cauesed this Exception.
	 *
	 * @return the amount of elements attempted to insert or null if it has not
	 *         been set
	 */
	public Integer newElements() {
		return this.newElements;
	}
}

Define exception for exceeding the maximum size of a UniqueBoundedList


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

import com.github.daytron.revworks.ui.AdminLoginPopup;
import com.vaadin.ui.OptionGroup;
import com.vaadin.ui.PasswordField;
import com.vaadin.ui.TextField;

/**
 * EventBus events used in the application as inner final classes
 *
 * @author Ryan Gilera
 */
public abstract class AppEvent {

    public static final class UserLoginRequestEvent {

        private final OptionGroup userTypeOptionGroup;
        private final TextField userField;
        private final PasswordField passwordField;

        public UserLoginRequestEvent(TextField userField,
                PasswordField passwordField,
                OptionGroup userType) {
            this.userTypeOptionGroup = userType;
            this.userField = userField;
            this.passwordField = passwordField;
        }

        public OptionGroup getUserTypeOptionGroup() {
            return userTypeOptionGroup;
        }

        public TextField getUserField() {
            return userField;
        }

        public PasswordField getPasswordField() {
            return passwordField;
        }

    }

    public static final class AdminLoginRequestEvent {

        private final TextField userField;
        private final PasswordField passwordField;
        private final AdminLoginPopup adminLoginPopup;

        public AdminLoginRequestEvent(TextField userField,
                PasswordField passwordField,
                AdminLoginPopup adminLoginPopup) {
            this.userField = userField;
            this.passwordField = passwordField;
            this.adminLoginPopup = adminLoginPopup;
        }

        public PasswordField getPasswordField() {
            return passwordField;
        }

        public TextField getUserField() {
            return userField;
        }

        public AdminLoginPopup getAdminLoginPopup() {
            return adminLoginPopup;
        }

    }

    public static final class UserLogoutRequestEvent {
    }

    public static final class WebmasterLinkClickEvent {
    }

    public static final class OptionChangeValueEvent {

        private final TextField usernameField;
        private final String value;

        public OptionChangeValueEvent(TextField userField, String value) {
            this.usernameField = userField;
            this.value = value;
        }

        public TextField getUsernameField() {
            return usernameField;
        }

        public String getValue() {
            return value;
        }

    }
}

Add custom EventBus events for Guava

Add custom EventBus events for Guava


// Use for-each style for on a two-dimensional array.
class ForEach2 {
	public static void main(String args[]) {
		int sum = 0;
		int nums[][] = new int[3][5];

		// give nums some values
		for(int i = 0; i < 3; i++)
			for(int j=0; j < 5; j++)
				nums[i][j] = (i+1)*(j+1);

		// Use for-each for loop to display and sum the values.
		for(int x[] : nums) {
			for(int y : x) {
				System.out.println("Value is: " + y);
				sum += y;
			}
		}
		System.out.println("Summation: " + sum);
	}
}


package de.craften.craftenlauncher.logic.auth;

import org.junit.Test;

import static org.junit.Assert.*;

public class MinecraftUserTest {

    @Test
    public void testEquals() throws Exception {
        MinecraftUser user1 = new MinecraftUser("email_one@test.de", "54bnb5br_profileid_berb4b3","one","b43v4bvbvt_accesstoken_bhbghtr","km787men56_clienttoken_45nbbntvb");
        MinecraftUser user2 = new MinecraftUser("email_one@test.de", "54bnb5br_profileid_berb4b3","one","b43v4bvbvt_accesstoken_bhbghtr","km787men56_clienttoken_45nbbntvb");

        assertEquals(user1,user2);
    }

    @Test
    public void testNotEquals() throws Exception {
        MinecraftUser user1 = new MinecraftUser("email_one@test.de", "54bnb5br_profileid_berb4b3","one","b43v4bvbvt_accesstoken_bhbghtr","km787men56_clienttoken_45nbbntvb");
        MinecraftUser user2 = new MinecraftUser("email_two@test.de", "7m67mnb_profileid_kmmmnu","two","wj5wzw5_accesstoken_sdnmenb5","7mnmn5nbbnt_clienttoken_ws5mnza");

        assertNotEquals(user1,user2);
    }
}

Test for MinecraftUser equals Method

Test for MinecraftUser equals Method


/*
 * Copyright (C) 2015 Jasper Huzen
 *
 * 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.feaster83.elasticsearch.river.jdbc.strategy.rebuild;

public class RebuildRiverMouthTest {
}

Add test class (still empty)

Add test class (still empty)


package brooklyn.cli.commands;

/**
 * Exception that can happen during the execution of a {@link BrooklynCommand}
 */
public class CommandExecutionException extends Exception {

    CommandExecutionException(String s) {
        super(s);
    }

    CommandExecutionException(String s, Throwable cause) {
        super(s, cause);
    }
}

Add custom exception class for problems during command execution


package org.ensembl.healthcheck.testcase.eg_core;

import static org.ensembl.healthcheck.DatabaseType.CDNA;
import static org.ensembl.healthcheck.DatabaseType.CORE;
import static org.ensembl.healthcheck.DatabaseType.EST;
import static org.ensembl.healthcheck.DatabaseType.ESTGENE;
import static org.ensembl.healthcheck.DatabaseType.OTHERFEATURES;
import static org.ensembl.healthcheck.DatabaseType.RNASEQ;
import static org.ensembl.healthcheck.DatabaseType.SANGER_VEGA;

/**
 * @author mnuhn
 *
 * <p>
 * 	Test for correctness of core schemas, suggests a patch, if the schemas
 * differ.
 * </p>
 *
 */
public class EGCompareCoreSchema extends EGAbstractCompareSchema {

	@Override
	protected String getDefinitionFileKey() {
		return "schema.file";
	}

	@Override
	protected String getMasterSchemaKey() {
		return "master.schema";
	}

	@Override
	public void types() {
		addAppliesToType(CORE);
		addAppliesToType(CDNA);
		addAppliesToType(EST);
		addAppliesToType(ESTGENE);
		addAppliesToType(OTHERFEATURES);
		addAppliesToType(RNASEQ);
		addAppliesToType(SANGER_VEGA);
	}
}

Test for correctness of core schemas, suggests a patch, if the schemas differ.


package fi.nls.oskari.control.view;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;

import org.json.JSONException;

import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.core.JsonGenerator;

import fi.nls.oskari.annotation.OskariActionRoute;
import fi.nls.oskari.control.ActionException;
import fi.nls.oskari.control.ActionParameters;
import fi.nls.oskari.domain.map.view.View;
import fi.nls.oskari.map.view.ViewService;
import fi.nls.oskari.map.view.ViewServiceIbatisImpl;
import fi.nls.oskari.service.ServiceException;
import fi.nls.oskari.util.ResponseHelper;

@OskariActionRoute("GetSystemDefaultViews")
public class GetSystemDefaultViews {

    private static final JsonFactory JSONF = new JsonFactory();

    private ViewService viewService;

    public void init() {
        viewService = new ViewServiceIbatisImpl();
    }

    public void handleAction(ActionParameters params) throws ActionException {
        List<Long> viewIds = getDefaultViewIds();
        List<View> views = getViews(viewIds);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        writeResponseJSON(views, baos);
        ResponseHelper.writeResponse(params, 200, ResponseHelper.CONTENT_TYPE_JSON_UTF8, baos);
    }

    private List<Long> getDefaultViewIds() throws ActionException {
        try {
            return viewService.getSystemDefaultViewIds();
        } catch (ServiceException e) {
            throw new ActionException(e.getMessage(), e);
        }

    }

    private List<View> getViews(List<Long> viewIds) {
        List<View> views = new ArrayList<>(viewIds.size());
        for (long viewId : viewIds) {
            views.add(viewService.getViewWithConf(viewId));
        }
        return views;
    }

    private void writeResponseJSON(List<View> views, OutputStream out) throws ActionException {
        try (JsonGenerator json = JSONF.createGenerator(out)) {
            json.writeStartArray();
            for (View view : views) {
                writeView(view, json);
            }
            json.writeEndArray();
        } catch (JSONException | IOException e) {
            throw new ActionException(e.getMessage(), e);
        }

    }

    private void writeView(View view, JsonGenerator json) throws JSONException, IOException {
        String uuid = view.getUuid();
        String srsName = view.getBundleByName("mapfull")
                .getConfigJSON()
                .getJSONObject("mapConfig")
                .getString("srsName");

        json.writeStartObject();
        json.writeStringField("uuid", uuid);
        json.writeStringField("srsName", srsName);
        json.writeEndObject();
    }

}

Add ActionHandler for getting systems default views


// Copyright Verizon Media. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package ai.vespa.util.http.hc5;

import org.apache.hc.client5.http.HttpRoute;
import org.apache.hc.client5.http.config.RequestConfig;
import org.apache.hc.client5.http.protocol.HttpClientContext;
import org.apache.hc.core5.http.HttpException;
import org.apache.hc.core5.http.HttpHost;
import org.junit.Test;

import static org.junit.Assert.assertEquals;

/**
 * @author jonmv
 */
public class HttpToHttpsRoutePlannerTest {

    final HttpToHttpsRoutePlanner planner = new HttpToHttpsRoutePlanner();

    @Test
    public void verifySchemeMustBeHttp() throws HttpException {
        try {
            planner.determineRoute(new HttpHost("https", "host", 1), new HttpClientContext());
        }
        catch (IllegalArgumentException e) {
            assertEquals("Scheme must be 'http' when using HttpToHttpsRoutePlanner", e.getMessage());
        }
    }

    @Test
    public void verifyPortMustBeSet() throws HttpException {
        try {
            planner.determineRoute(new HttpHost("http", "host", -1), new HttpClientContext());
        }
        catch (IllegalArgumentException e) {
            assertEquals("Port must be set when using HttpToHttpsRoutePlanner", e.getMessage());
        }
    }

    @Test
    public void verifyProxyIsDisallowed() throws HttpException {
        HttpClientContext context = new HttpClientContext();
        context.setRequestConfig(RequestConfig.custom().setProxy(new HttpHost("proxy")).build());
        try {
            planner.determineRoute(new HttpHost("http", "host", 1), context);
        }
        catch (IllegalArgumentException e) {
            assertEquals("Proxies are not supported with HttpToHttpsRoutePlanner", e.getMessage());
        }
    }

    @Test
    public void verifySchemeIsRewritten() throws HttpException {
        assertEquals(new HttpRoute(new HttpHost("https", "host", 1)),
                     planner.determineRoute(new HttpHost("http", "host", 1), new HttpClientContext()));
    }

}

Add test for route planner

Add test for route planner


package com.github.gabrielruiu.spring.cloud.config.redis;

import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.embedded.LocalServerPort;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.cloud.config.environment.Environment;
import org.springframework.cloud.config.environment.PropertySource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.test.context.junit4.SpringRunner;

import java.util.List;
import java.util.Set;

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.*;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;

/**
 * @author Gabriel Mihai Ruiu (gabriel.ruiu@mail.com)
 */
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class RedisEnvironmentRepositoryTest {

    @LocalServerPort
    int port;

    @MockBean
    StringRedisTemplate stringRedisTemplate;

    @Autowired
    TestRestTemplate testRestTemplate;

    @Test
    public void shouldRetrieveEnvironment() {
        String pattern = "application:default:master:*";
        List<String> properties = Lists.newArrayList("http://localhost:8080/url", "dd/MM/yyyy");
        Set<String> keys = Sets.newHashSet("application:default:master:url", "application:default:master:format:date");
        ValueOperations<String, String> valueOps = mock(ValueOperations.class);
        given(stringRedisTemplate.keys(pattern)).willReturn(keys);
        given(stringRedisTemplate.opsForValue()).willReturn(valueOps);
        given(valueOps.multiGet(keys)).willReturn(properties);
        String url = String.format("http://localhost:%d/application/default/master", port);

        Environment env = testRestTemplate.getForObject(url, Environment.class);

        assertThat(env, notNullValue());
        assertThat(env.getName(), is("application"));
        assertThat(env.getVersion(), nullValue());
        assertThat(env.getProfiles(), arrayWithSize(1));
        assertThat(env.getLabel(), is("master"));
        assertThat(env.getPropertySources(), hasSize(1));
        PropertySource propertySource = env.getPropertySources().get(0);
        assertThat(propertySource, notNullValue());
        assertThat(propertySource.getName(), is("application"));
        assertThat(propertySource.getSource(), notNullValue());
        assertThat(propertySource.getSource(), hasEntry("format.date", "dd/MM/yyyy"));
        assertThat(propertySource.getSource(), hasEntry("url", "http://localhost:8080/url"));
    }
}

Add basic integration test that checks a simple retrieval of an Environment object. Several other tests will be added later


package com.github.aureliano.edocs.app.cmd;

import com.github.aureliano.edocs.app.EdocsApp;
import com.github.aureliano.edocs.app.gui.LicenseDialog;

public class OpenLicenseDialogCommand implements ICommand {

	@Override
	public void execute() {
		if (!this.canExecute()) {
			return;
		}

		new LicenseDialog(EdocsApp.instance().getFrame()).setVisible(true);
	}

	@Override
	public boolean canExecute() {
		return true;
	}
}

Create open license dialog command.

Create open license dialog command.


package com.bkromhout.minerva.data;

import nl.siegmann.epublib.domain.Author;
import nl.siegmann.epublib.domain.Book;
import org.junit.Test;

/**
 * Tests the {@link SuperBook} class.
 */
public class SuperBookTest {

    @Test(expected = IllegalArgumentException.class)
    public void nullBookThrows() {
        new SuperBook(null, "fake", "null book".getBytes());
    }

    @Test(expected = IllegalArgumentException.class)
    public void emptyBookThrows() {
        new SuperBook(new Book(), "fake", "empty book".getBytes());
    }

    @Test(expected = IllegalArgumentException.class)
    public void emptyTitleBookThrows() {
        Book book = new Book();
        book.getMetadata().addTitle("");
        new SuperBook(book, "fake", "empty title book".getBytes());
    }

    @Test(expected = IllegalArgumentException.class)
    public void noAuthorBookThrows() {
        String title = "Book without author";
        Book book = new Book();
        book.getMetadata().addTitle(title);
        new SuperBook(book, "fake", title.getBytes());
    }

    @Test(expected = IllegalArgumentException.class)
    public void emptyAuthorBookThrows() {
        String title = "Book with empty author";
        Book book = new Book();
        book.getMetadata().addTitle(title);
        book.getMetadata().addAuthor(new Author(""));
        new SuperBook(book, "fake", title.getBytes());
    }

    @Test(expected = IllegalArgumentException.class)
    public void noPathBookThrows() {
        String title = "Book without path";
        Book book = new Book();
        book.getMetadata().addTitle(title);
        book.getMetadata().addAuthor(new Author("Book", "Author"));
        new SuperBook(book, null, title.getBytes());
    }

    @Test(expected = IllegalArgumentException.class)
    public void emptyPathBookThrows() {
        String title = "Book with empty path";
        Book book = new Book();
        book.getMetadata().addTitle(title);
        book.getMetadata().addAuthor(new Author("Book", "Author"));
        new SuperBook(book, "", title.getBytes());
    }
}

Add tests for SuperBook class

Add tests for SuperBook class


package org.apache.helix.integration.task;

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

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

public class TestRetrieveWorkflows extends TaskTestBase {
  @Test
  public void testGetAllWorkflows() throws Exception {
    List<Workflow> workflowList = new ArrayList<Workflow>();
    for (int i = 0; i < 4; i++) {
      Workflow workflow = WorkflowGenerator.generateDefaultRepeatedJobWorkflowBuilder(TestHelper.getTestMethodName() + i).build();
      _driver.start(workflow);
      workflowList.add(workflow);
    }

    for (Workflow workflow : workflowList) {
      //TaskTestUtil.pollForWorkflowState(_driver, workflow.getName(), TaskState.COMPLETED);
    }

    _manager = HelixManagerFactory
        .getZKHelixManager("ESPRESSO_TEST_NUAGE", "Admin", InstanceType.ADMINISTRATOR, "zk-ei1-espresso.stg.linkedin.com:12913");
    _manager.connect();
    TaskDriver taskDriver = new TaskDriver(_manager);

    Map<String, WorkflowConfig> workflowConfigMap = taskDriver.getWorkflows();
    Assert.assertEquals(workflowConfigMap.size(), workflowList.size());

    for(Map.Entry<String, WorkflowConfig> workflow :  workflowConfigMap.entrySet()) {
      WorkflowConfig workflowConfig = workflow.getValue();
      WorkflowContext workflowContext = _driver.getWorkflowContext(workflow.getKey());
      Assert.assertNotNull(workflowContext);

      for(String job : workflowConfig.getJobDag().getAllNodes()) {
        JobConfig jobConfig = _driver.getJobConfig(job);
        JobContext jobContext = _driver.getJobContext(job);

        Assert.assertNotNull(jobConfig);
        Assert.assertNotNull(jobContext);
      }
    }
  }
}

Add unit test to retrieve workflow and job configurations.


package com.github.conradoqg.studydsa.hackerrank.challenges.ctci;

import java.util.Scanner;

public class FibonacciNumbers {
    public static int fibonacci(int n) {
        if (n <= 0)
            return 0;
        else if (n == 1)
            return 1;
        else {
            return fibonacci(n - 1) + fibonacci(n - 2);
        }

    }

    public static void main(String[] args) {
        try (Scanner scanner = new Scanner(System.in)) {
            int n = scanner.nextInt();
            scanner.close();
            System.out.println(fibonacci(n));
        }
    }
}

Add fibonacci numbers CTCI challenge

Add fibonacci numbers CTCI challenge