/*
 * Licensed to the University of California, Berkeley 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 tachyon;

import java.io.InputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.List;

import tachyon.conf.TachyonConf;

/**
 * dummy UnderFilesystem implementation.
 *
 * This is used when we use Tachyon as pure cache without any backing store
 */
public class UnderFileSystemDummy extends UnderFileSystem {

  protected UnderFileSystemDummy(TachyonConf tachyonConf) {
    super(tachyonConf);
  }

  public static UnderFileSystem getClient(TachyonConf tachyonConf) {
    return new UnderFileSystemDummy(tachyonConf);
  }

  @Override
  public void close() throws IOException {}

  @Override
  public OutputStream create(String path) throws IOException {
    return null;
  }

  @Override
  public OutputStream create(String path, int blockSizeByte) throws IOException {
    return null;
  }

  @Override
  public OutputStream create(String path, short replication, int blockSizeByte) throws IOException {
    return null;
  }

  @Override
  public boolean delete(String path, boolean recursive) throws IOException {
    return true;
  }

  @Override
  public boolean exists(String path) throws IOException {
    return false;
  }

  @Override
  public long getBlockSizeByte(String path) throws IOException {
    return -1;
  }

  @Override
  public Object getConf() {
    return null;
  }

  @Override
  public List<String> getFileLocations(String path) throws IOException {
    return null;
  }

  @Override
  public List<String> getFileLocations(String path, long offset) throws IOException {
    return null;
  }

  @Override
  public long getFileSize(String path) throws IOException {
    return -1;
  }

  @Override
  public long getModificationTimeMs(String path) throws IOException {
    return -1;
  }

  @Override
  public long getSpace(String path, SpaceType type) throws IOException {
    return -1;
  }

  @Override
  public boolean isFile(String path) throws IOException {
    return false;
  }

  @Override
  public String[] list(String path) throws IOException {
    return null;
  }

  @Override
  public boolean mkdirs(String path, boolean createParent) throws IOException {
    return true;
  }

  @Override
  public InputStream open(String path) throws IOException {
    return null;
  }

  @Override
  public boolean rename(String src, String dst) throws IOException {
    return true;
  }

  @Override
  public void setConf(Object conf) {}

  @Override
  public void setPermission(String path, String posixPerm) throws IOException {}
}

Create Dummy UnderFS: This is used when we use Tachyon as pure cache without any backing store


/*
 * Java Genetic Algorithm Library (@__identifier__@).
 * Copyright (c) @__year__@ Franz Wilhelmstötter
 *
 * 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.
 *
 * Author:
 *    Franz Wilhelmstötter (franz.wilhelmstoetter@gmx.at)
 */
package org.jenetics.engine;

/**
 * @author Franz Wilhelmstötter
 * @version !__version__!
 * @since !__version__!
 */
public class EngineExecutorTest {
}

Add test case for different executors used by the evolution engine.


package com.growthbeat.model;

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

import org.junit.Test;

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

public class AccountTest extends BaseTest {

	@Test
	public void findById() {
		Account account = Account.findById("GfgtutZ09JDesWQs", CREDENTIAL_ID);
		assertEquals("GfgtutZ09JDesWQs", account.getId());
	}

	@Test
	public void create() {
		Account account = Account.create(CREDENTIAL_ID);
		assertNotNull(account);
		assertNotNull(account.getId());
	}

	@Test
	public void deleteById() {
		try {
			Account.deleteById("Dummy", CREDENTIAL_ID);
			fail();
		} catch (GrowthbeatException e) {
		}
	}

}

Add test of Account model

Add test of Account model


package leetcode;

/**
 * https://leetcode.com/problems/serialize-and-deserialize-binary-tree/
 */
public class Problem297 {
    public static class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

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

    public static class Codec {
        // Encodes a tree to a single string.
        public String serialize(TreeNode root) {
            return "";
        }

        // Decodes your encoded data to tree.
        public TreeNode deserialize(String data) {
            return null;
        }
    }

    public static void main(String[] args) {
        Codec codec = new Codec();
        TreeNode root = new TreeNode(1);
        String serializedTree = codec.serialize(root);
        System.out.println(serializedTree);
        codec.deserialize(serializedTree);
    }
}

Create a skeleton for problem 297

Create a skeleton for problem 297


import java.util.Scanner;

/**
 * This program computes and prints the nth Fibonacci term
 **/
public class Fibonacci {
    public static void main(String[] args) {
        int a = 0, b = 1, c = 0, count = 2;
        System.out.println("Input the value of N");
        Scanner m = new Scanner(System.in);
        int limit = m.nextInt();

        if (limit == 1) {
            c = 0;
        } else if (limit == 2) {
            c = 1;
        } else {
            while (count < limit) {
                c = a + b;
                a = b;
                b = c;
                count++;
            }
        }
        System.out.println("The #" + limit + " term in the Fibonacci Sequence is " + c);
    }
}

Add problem 10 to unit 1

Add problem 10 to unit 1


package gql.ratpack.exec;

import java.util.concurrent.CompletableFuture;
import java.util.function.Supplier;

import ratpack.exec.Execution;

/**
 * Creates instances of {@link CompletableFuture} honoring Ratpack's executors
 *
 * @since 0.1.0
 */
public class Futures {

  /**
   * Creates a {@link CompletableFuture} using the blocking executor
   *
   * @param supplier code providing a value
   * @return a blocking instance of {@link CompletableFuture}
   * @since 0.1.0
   */
  public static <T> CompletableFuture<T> blocking(Supplier<T> supplier) {
    return CompletableFuture.supplyAsync(supplier, Execution.current().getController().getBlockingExecutor());
  }

  /**
   * Creates a {@link CompletableFuture} using the non blocking executor (event loop)
   *
   * @param supplier code providing a value
   * @return a non blocking instance of {@link CompletableFuture}
   * @since 0.1.0
   */
  public static <T> CompletableFuture<T> async(Supplier<T> supplier) {
    return CompletableFuture.supplyAsync(supplier, Execution.current().getController().getExecutor());
  }
}

Add integration between CompletableFuture and Ratpack's execution model


package com.zaxxer.hikari.pool;

import com.zaxxer.hikari.HikariConfig;
import org.junit.Test;

import com.zaxxer.hikari.HikariDataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

/**
 * @author Matthew Tambara (matthew.tambara@liferay.com)
 */
public class ConcurrentCloseConnectionTest
{
   @Test
   public void testConcurrentClose() throws Exception
   {
	  HikariConfig config = new HikariConfig();
      config.setDataSourceClassName("com.zaxxer.hikari.mocks.StubDataSource");

	  try (HikariDataSource ds = new HikariDataSource(config);
	      final Connection connection = ds.getConnection()) {

		  ExecutorService executorService = Executors.newFixedThreadPool(10);

		  List<Future> futures = new ArrayList<>();

		  for (int i = 0; i < 500; i++) {
			  final PreparedStatement preparedStatement =
				  connection.prepareStatement("");

			  futures.add(executorService.submit(new Callable<Void>() {

				  @Override
				  public Void call() throws Exception {
					  preparedStatement.close();

					  return null;
				  }

			  }));
		  }

		  executorService.shutdown();

		  for (Future future : futures) {
			  future.get();
		  }
	  }
   }
}

Add test to demonstrate concurrency problem


package net.openhft.chronicle.bytes;

import org.junit.Test;

import java.io.IOException;

import static org.junit.Assert.assertTrue;

/**
 * Created by peter on 17/05/2017.
 */
public class BytesUtilTest {
    @Test
    public void fromFileInJar() throws IOException {
        Bytes bytes = BytesUtil.readFile("/net/openhft/chronicle/core/onoes/Google.properties");
        long n = bytes.indexOf(Bytes.from("Apache License"));
        assertTrue(n > 0);
    }
}

Fix Bytes.fromFile to read from JARs.

Fix Bytes.fromFile to read from JARs.


package com.abhi.fyberdemo.fragments;

import android.support.v4.app.Fragment;
import android.view.View;

import com.abhi.fyberdemo.BuildConfig;
import com.abhi.fyberdemo.MainActivity;
import com.abhi.fyberdemo.R;
import com.abhi.fyberdemo.models.OfferResponse;

import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mockito;
import org.robolectric.Robolectric;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.annotation.Config;

/**
 * Created by abhi on 28/10/16.
 */

@RunWith(RobolectricTestRunner.class)
@Config(constants = BuildConfig.class, sdk = 23)
public class OffersFragmentTest {
    private MainActivity mMainActivity;
    private OffersFragment mOffersFragment;

    @Before
    public void setUp() throws Exception {
        OfferResponse _offerResponse = Mockito.mock(OfferResponse.class);
        mMainActivity = Robolectric.setupActivity(MainActivity.class);
        mOffersFragment = OffersFragment.newInstance(mMainActivity, _offerResponse);
        startFragment(mOffersFragment);
    }

    private void startFragment(Fragment fragment) {
        mMainActivity.getSupportFragmentManager()
                .beginTransaction()
                .add(R.id.frag_container, fragment)
                .commit();
    }

    @Test
    public void newInstance() throws Exception {
        /*OfferResponse _offerResponse = Mockito.mock(OfferResponse.class);
        MainActivity _mainActivity = Mockito.mock(MainActivity.class);
        OffersFragment _offersFragment = OffersFragment.newInstance(_mainActivity,_offerResponse);*/
        Assert.assertNotNull(mOffersFragment);
        Assert.assertNotNull(mMainActivity);
    }

    @Test
    public void setupUI() throws Exception {

    }

    @Test
    public void loadOffers() throws Exception {
        OfferResponse _offerResponse = mOffersFragment.getOfferResponse();
        Mockito.when(_offerResponse.containsOffers()).thenReturn(false);
        mOffersFragment.loadOffers(_offerResponse);
        Assert.assertEquals("No Offers Test is not displayed when there are no offers", mOffersFragment.mNoOffersTextView.getVisibility(), View.VISIBLE);
        Assert.assertEquals("RecyclerView is displayed when there are no offers", mOffersFragment.mOffersRecyclerView.getVisibility(), View.GONE);

        Mockito.when(_offerResponse.containsOffers()).thenReturn(true);
        mOffersFragment.loadOffers(_offerResponse);
        Assert.assertEquals("No Offers Test is displayed when there are offers", mOffersFragment.mNoOffersTextView.getVisibility(), View.GONE);
        Assert.assertEquals("RecyclerView is not displayed when there are offers", mOffersFragment.mOffersRecyclerView.getVisibility(), View.VISIBLE);
    }

    @Test
    public void getLayoutId() throws Exception {
        int layoutId = mOffersFragment.getLayoutId();
        Assert.assertTrue("Layout Id can not be 0 ", layoutId != 0);
        Assert.assertTrue("Layout Id can not be negative ", layoutId > 0);
    }
}

Add Unit test for OffersFragment using Roboelectric


package com.sinyuk.yuk.utils;

import android.content.Context;
import android.graphics.Typeface;

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

/**
 * Adapted from github.com/romannurik/muzei/
 * <p>
 * Also see https://code.google.com/p/android/issues/detail?id=9904
 */
public class FontUtil {

    private static final Map<String, Typeface> sTypefaceCache = new HashMap<>();

    private FontUtil() { }

    public static Typeface get(Context context, String font) {
        synchronized (sTypefaceCache) {
            if (!sTypefaceCache.containsKey(font)) {
                Typeface tf = Typeface.createFromAsset(
                        context.getApplicationContext().getAssets(), font + ".ttf");
                sTypefaceCache.put(font, tf);
            }
            return sTypefaceCache.get(font);
        }
    }
}

Add util to use custom font

Add util to use custom font


/**
 *
 */
package dr.evomodel.newtreelikelihood;

import dr.evomodel.newtreelikelihood.GeneralLikelihoodCore;

/**
 * @author Marc Suchard
 *
 */
public class LikelihoodCoreFactory {

	public static LikelihoodCore getLikelihoodCore(int stateCount) {

		return new GeneralLikelihoodCore(stateCount);
	}

}

Move complicated parsing of dataType and available JNI libraries into a factory class

git-svn-id: 67bc77c75b8364e4e9cdff0eb6560f5818674cd8@1213 ca793f91-a31e-0410-b540-2769d408b6a1


/**
 * Project Distributed Transactions.
 * Copyright Michał Szczygieł, 2013.
 * Created at Jan 2, 2014.
 */
package com.m4gik.business.dao;

import com.m4gik.business.model.WarehousePoland;

/**
 * Interface for WarehousePoland Data Access Object.
 *
 * @author m4gik <michal.szczygiel@wp.pl>
 *
 */
public interface WarehousePolandDAO {

    /**
     * The persistence context needed to persist entity identity as a unique
     * entity instance.
     *
     * @param warehousePoland
     * @throws Exception
     */
    void persistEmployee(WarehousePoland warehousePoland) throws Exception;
}

Add interface for WarehousePoland Data Access Object


package peergos.server.tests;

import org.junit.*;
import org.junit.runner.*;
import org.junit.runners.*;
import peergos.server.sql.*;
import peergos.server.storage.*;
import peergos.server.util.*;
import peergos.shared.crypto.hash.*;
import peergos.shared.io.ipfs.cid.*;
import peergos.shared.io.ipfs.multihash.*;
import peergos.shared.storage.*;

import java.security.*;
import java.util.*;

@RunWith(Parameterized.class)
public class TransactionsStoreTests {

    private final TransactionStore store;

    public TransactionsStoreTests(TransactionStore store) {
        this.store = store;
    }

    @Parameterized.Parameters()
    public static Collection<Object[]> parameters() throws Exception {
        TransactionStore ram = JdbcTransactionStore.build(Sqlite.build(":memory:"), new SqliteCommands());
        return Arrays.asList(new Object[][] {
                {ram}
        });
    }

    public static byte[] hash(byte[] input) {
        try {
            MessageDigest md = MessageDigest.getInstance("SHA-256");
            md.update(input);
            return md.digest();
        } catch (NoSuchAlgorithmException e) {
            throw new IllegalStateException("couldn't find hash algorithm");
        }
    }

    public static Cid hashToCid(byte[] input, boolean isRaw) {
        byte[] hash = hash(input);
        return new Cid(1, isRaw ? Cid.Codec.Raw : Cid.Codec.DagCbor, Multihash.Type.sha2_256, hash);
    }

    @Test
    public void singleTransaction() {
        Cid multihash = hashToCid(new byte[2], true);
        PublicKeyHash owner = new PublicKeyHash(multihash);
        TransactionId tid = store.startTransaction(owner);
        List<Multihash> pending = new ArrayList<>();
        for (int i=0; i < 20; i++) {
            Cid block = hashToCid(new byte[]{(byte) i}, false);
            pending.add(block);
            store.addBlock(block, tid, owner);
        }
        List<Multihash> uncommitted = store.getOpenTransactionBlocks();
        Assert.assertTrue("All blocks present", uncommitted.containsAll(pending));

        store.closeTransaction(owner, tid);
        List<Multihash> empty = store.getOpenTransactionBlocks();
        Assert.assertTrue("All blocks removed", empty.isEmpty());
    }
}

Add a transaction store test

Add a transaction store test


package com.vmware.vim25.mo.samples.vm;

import java.rmi.RemoteException;

import com.vmware.vim25.mo.HostSystem;
import com.vmware.vim25.mo.InventoryNavigator;
import com.vmware.vim25.mo.ResourcePool;
import com.vmware.vim25.mo.ServiceInstance;
import com.vmware.vim25.mo.VirtualMachine;
import com.vmware.vim25.mo.samples.SampleUtil;

public class VmConvert {

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

	VmConvert vmConvert = new VmConvert();
	vmConvert.convertToTemplate(si, "vm1");
	vmConvert.convertToVm(si, "vm1", "rp1", null);

	si.getServerConnection().logout();
    }

    public void convertToTemplate(ServiceInstance si, String vmName) throws Exception {
	VirtualMachine vm = (VirtualMachine) new InventoryNavigator(si.getRootFolder()).searchManagedEntity("VirtualMachine", vmName);
	if (vm == null) {
	    System.out.println("Not found vm " + vmName);
	    return;
	}
	if (vm.getConfig().isTemplate()) {
	    System.out.println("The vm " + vmName + " is already a template!");
	    return;
	}
	vm.markAsTemplate();
	System.out.println("Convert vm " + vmName + " to template successfully!");
    }

    /**
     * @param hostName The target host on which the virtual machine is intended to run. If it is set to null, the default host will be used.
     */
    public void convertToVm(ServiceInstance si, String vmName, String poolName, String hostName) throws RemoteException {
	VirtualMachine vm = (VirtualMachine) new InventoryNavigator(si.getRootFolder()).searchManagedEntity("VirtualMachine", vmName);
	if (vm == null) {
	    System.out.println("Not found vm " + vmName);
	    return;
	}
	ResourcePool pool = (ResourcePool) new InventoryNavigator(si.getRootFolder()).searchManagedEntity("ResourcePool", poolName);
	if (pool == null) {
	    System.out.println("Not found resource pool " + poolName);
	    return;
	}
	HostSystem host = null;
	if (hostName != null) {
	    host = (HostSystem) new InventoryNavigator(si.getRootFolder()).searchManagedEntity("HostSystem", hostName);
	    if (host == null) {
		System.out.println("Not found host " + hostName);
		return;
	    }
	}
	vm.markAsVirtualMachine(pool, host);
	System.out.println("Convert vm " + vmName + " from template successfully!");
    }

}

Add sample code for vm/template convertion.


package uk.gov.migration;

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

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

public class V__12_Drop_unused_tables extends BaseJdbcMigration implements MigrationChecksumProvider {
    @Override
    public void migrate(Connection connection) throws Exception {
        Statement stmt = connection.createStatement();
        try {
            stmt.execute("drop table total_records");
            stmt.execute("drop table current_keys");
        } finally {
            stmt.close();
        }
    }

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

Drop total_records and current_keys tables

These tables were used before we moved to store records as indexes, and
are therefore no longer required.

This migration removes them from the schema.


/**
 *
 */
package com.github.ansell.csvsum;

import static org.junit.Assert.*;

import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;

import joptsimple.OptionException;

/**
 * Tests for {@link CSVSummariser}.
 *
 * @author Peter Ansell p_ansell@yahoo.com
 */
public class CSVSummariserTest {

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

	/**
	 * Test method for
	 * {@link com.github.ansell.csvsum.CSVSummariser#main(java.lang.String[])}.
	 */
	@Test
	public final void testMainNoArgs() throws Exception {
		thrown.expect(OptionException.class);
		CSVSummariser.main();
	}

}

Add stub test for CSVSummariser

Add stub test for CSVSummariser


package org.jpos.core;

import org.junit.jupiter.api.Test;

import static org.junit.jupiter.api.Assertions.*;

public class EnvironmentTest {
    @Test
    public void testEmptyDefault() {
        assertEquals("", Environment.get("${test:}"));
    }
}

Add test for empty Environment default

Add test for empty Environment default


/*
# Licensed Materials - Property of IBM
# Copyright IBM Corp. 2015
 */
package com.ibm.streamsx.topology.test.jcp;

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

import java.util.Collections;
import java.util.concurrent.TimeUnit;

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

import com.ibm.streamsx.topology.TStream;
import com.ibm.streamsx.topology.Topology;
import com.ibm.streamsx.topology.context.StreamsContext;
import com.ibm.streamsx.topology.test.TestTopology;
import com.ibm.streamsx.topology.tester.Condition;

public class JCPTest extends TestTopology {

    @Before
    public void ensureDistributed() {
        assumeTrue(getTesterType() == StreamsContext.Type.DISTRIBUTED_TESTER);
        assumeTrue(SC_OK);
    }

    @Test
    public void testJCP() throws Exception {

        Topology topology = newTopology("testSingleJCP");
        topology.addJobControlPlane();

        submitAndCheckJCPIsThere(topology);
    }

    /**
     * TODO - Add some mechanism to check that the JCP is indeed there!
     */
    private void submitAndCheckJCPIsThere(Topology topology) throws Exception {

        TStream<String> strings = topology.constants(Collections.singletonList("Hello JCP!"));

        Condition<Long> end = topology.getTester().tupleCount(strings, 1);
        complete(topology.getTester(), end, 10, TimeUnit.SECONDS);
    }

    /**
     * Test that calling addJobControlPlane doesn't result
     * in multiple invocations of the SPL JobControlPlane operator.
     * @throws Exception
     */
    @Test
    public void testMultiJCPCalls() throws Exception {

        Topology topology = newTopology("testMultiJCPCalls");

        for (int i = 0 ; i < 10; i++)
            topology.addJobControlPlane();

        submitAndCheckJCPIsThere(topology);
    }
}

Add (minimal) testing of JCP

Add (minimal) testing of JCP


public class Solution {

    public int countPrimes(int n) {

        boolean[] notPrime = new boolean[n];

        int count = 0;

        for (int i = 2; i < n; i++) {

            if (notPrime[i]) {
                continue;
            }

            count++;

            for (int j = i; j < n; j = i + j) {
                notPrime[j] = true;
            }

        }

        return count;

    }

}

Create : 204 Count Primes

Create : 204 Count Primes


package org.graphstream.gama.extension;

import msi.gama.common.interfaces.IKeyword;

public class IKeywordGSAdditional implements IKeyword {
	// New commands

	public static final String ADD = "gs_add";
	public static final String ADD_ATTRIBUTE = "gs_add_attribute";
	public static final String ADD_SENDER = "gs_add_sender";
	public static final String CLEAR = "gs_clear";
	public static final String CLEAR_SENDER = "gs_clear_sender";
	public static final String REMOVE = "gs_remove";
	public static final String REMOVE_ATTRIBUTE = "gs_remove_attribute";
	public static final String STEP = "gs_step";

	// Facets associated to a command

	public static final String SENDERID = "gs_sender_id";
}

Add a file describing the new keywords of the gs plugin


package leetcode.repeated_dna_sequences;

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

public class Solution {
	public String toATCG(int n){
		StringBuilder sb = new StringBuilder();
		String ATCG = "ATCG";
		for(int i = 9; i >= 0; i--){
			int v = (n >> (2 * i)) & 3;
			sb.append(ATCG.charAt(v));
		}
		return sb.toString();
	}
    public List<String> findRepeatedDnaSequences(String s) {
        List<String> ret = new ArrayList<String>();
        byte[] appeared = new byte[0x100000];
        s = s.replace("A", "0").replace("T", "1").replace("C", "2").replace("G", "3");
        if(s.length() < 10){
        	return ret;
        }
        int n = 0;
        for(int i = 0; i < 9; i++){
        	n *= 4;
        	n += s.charAt(i) - '0';
        }
        for(int i = 9; i < s.length(); i++){
        	n *= 4;
        	n += s.charAt(i) - '0';
        	n &= 0xFFFFF;
        	if(appeared[n] < 2){
        		if(appeared[n] == 1){
        			ret.add(toATCG(n));
        		}
        		appeared[n]++;
        	}
        }
        return ret;
    }
    public static void main(String[] args){
    	System.err.println(new Solution().findRepeatedDnaSequences("AAAAACCCCCAAAAACCCCCCAAAAAGGGTTT"));
    }
}

Add java solution for 187. Repeated DNA Sequences

187. Repeated DNA Sequences: https://leetcode.com/problems/repeated-dna-sequences/


package com.interview.tree;

import java.util.Deque;
import java.util.LinkedList;

/**
 * http://www.geeksforgeeks.org/check-two-nodes-cousins-binary-tree/
 * Assumption that both a and b are unique in tree.
 * Test cases:
 * Empty tree
 * Tree with only root
 * Tree and input with a and b as cousin node
 * Tree and input with a and b not cousin node
 */
public class CousinNodes {

	public boolean areCousins(Node root,int a, int b){
		Deque<Node> queue = new LinkedList<Node>();
		queue.offerFirst(root);
		int levelSize=1;
		int tempLevelSize = 1;
		boolean foundFirst = false;
		while(!queue.isEmpty()){
			levelSize = 0;
			while(tempLevelSize > 0){
				Node node = queue.pollLast();
				if(node.data == a || node.data == b){
					if(foundFirst){
						return true;
					}
					foundFirst = true;
				}
				if(node.left!=null){
					queue.offerFirst(node.left);
					levelSize++;
				}
				if(node.right != null){
					queue.offerFirst(node.right);
					levelSize++;
				}
				tempLevelSize--;
			}
			if(foundFirst){
				return false;
			}
			tempLevelSize = levelSize;
		}
		return false;
	}

	public static void main(String args[]){
		BinaryTree bt = new BinaryTree();
		Node head = null;
		head = bt.addNode(10, head);
		head = bt.addNode(15, head);
		head = bt.addNode(5, head);
		head = bt.addNode(7, head);
		head = bt.addNode(19, head);
		head = bt.addNode(20, head);
		head = bt.addNode(-1, head);
		head = bt.addNode(21, head);
		head = bt.addNode(-6, head);
		CousinNodes cn = new CousinNodes();
		System.out.println(cn.areCousins(head, 10, 19));
		System.out.println(cn.areCousins(head, 19, 7));
		System.out.println(cn.areCousins(head, 19, -1));
		System.out.println(cn.areCousins(head, 19, -6));
	}
}

Check if two nodes are cousins

Check if two nodes are cousins


package com.kryptnostic.rhizome.hazelcast.processors;

import java.util.Map.Entry;

import com.google.common.collect.Sets;

import java.util.Set;

public abstract class SetContainsAnyEntryProcessor<T> extends AbstractRhizomeEntryProcessor<T, Set<T>> {

    private static final long serialVersionUID = -1578286848277056995L;
    private final Set<T>      objectsToCheck;

    public SetContainsAnyEntryProcessor( Set<T> objectsToCheck ) {
        super( false /* don't apply on backup nodes */ );
        this.objectsToCheck = objectsToCheck;
    }

    public Set<T> getObjectsToCheck() {
        return objectsToCheck;
    }

    @Override
    public Object process( Entry<T, Set<T>> entry ) {
        Set<T> value = entry.getValue();
        if ( value == null || value.isEmpty() ) {
            return null;
        }
        return !Sets.intersection( value, objectsToCheck ).isEmpty();
    }

}

Add EntryProcessor for checking set intersections

- To be used in the implementation of ObjectAuthorizationService


package com.sinyuk.yuk.utils;

import android.content.Context;
import android.util.AttributeSet;
import android.widget.ViewAnimator;

/**
 * Custom View Animator which is more easier to be uesd
 */
public class BetterViewAnimator extends ViewAnimator {
  public BetterViewAnimator(Context context, AttributeSet attrs) {
    super(context, attrs);
  }

  public void setDisplayedChildId(int id) {
    if (getDisplayedChildId() == id) {
      return;
    }
    for (int i = 0, count = getChildCount(); i < count; i++) {
      if (getChildAt(i).getId() == id) {
        setDisplayedChild(i);
        return;
      }
    }
    String name = getResources().getResourceEntryName(id);
    throw new IllegalArgumentException("No view with ID " + name);
  }

  public int getDisplayedChildId() {
    return getChildAt(getDisplayedChild()).getId();
  }
}

Add a custom view animator implement

Add a custom view animator implement


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

package de.muspellheim.flowdesign;

/**
 * Zeigt wie Functional-Units in Methoden überführt werden können.
 *
 * @author Falko Schumann <falko.schumann@muspellheim.de>
 */
public class MethodsCheatSheet {

    /**
     * Ein einfaches Beispiel einer Functional-Unit mit einem Input T und einem Output U.
     */
    public <U, T> U a(T input) {
        U u = null;
        // ...
        return u;
    }

    /**
     * Ein zusammengesetzten Beispiel. Die beiden Parts A und B werden zum Board X zusammengesteckt.
     */
    public <U, S, T> U x(T input) {
        S s = a(input);
        U u = b(s);
        return u;
    }

    private <U, T> U b(T input) {
        U u = null;
        // ...
        return u;
    }

    /**
     * Eine Functional-Unit mit zwei Input-Pins zu einem Tuple vereint.
     */
    public <T, U> void a(Tuple<T, U> input) {
        // ...
    }

    /**
     * Eine Functional-Unit mit zwei Output-Pins zu einem Tuple vereint.
     */
    public <T, U> Tuple<T, U> a() {
        // ...
        return null;
    }

    /**
     * Eine Functional-Unit mit zwei Output-Pins als Output-Parameter.
     */
    public <T, U> void a(T outputT, U outputU) {
        // ...
    }

    /**
     * Split von A auf B und C sowie Join von B und C auf D.
     */
    public <T, U, S, V> void foo() {
        T t = null;
        U u = null;
        a(t, u);

        S s = b(t);
        V v = c(u);

        d(Tuple.of(s, v));
    }

    private <U, T> U c(T input) {
        U u = null;
        // ...
        return u;
    }

    private <U, T> void d(Tuple<T, U> input) {
        // ...
    }

}

Create cheat sheet for translating to methods


// Copyright 2021 Google LLC
//
// 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
//
//     https://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.sps.data;

/**
 * Class representing user data specific to a competition
 */
public class CompetitorInfo {

    /** The current ranking of the user in this competition based on networth */
    private int rank;

    /** The rank of the user yesterday for purposes of displaying rises/falls in leaderboard */
    private int rankYesterday;

    /** The competitor's name */
    private String name;

    /** The competitor's idap */
    private String idap;

    /** The networth of the competitor */
    private long networth;

    /** The amount the user has available for additional investments */
    private long amtAvailable;

    public CompetitorInfo(int rank, int rankYesterday, String name, String idap, long networth, long amtAvailable) {
        this.rank = rank;
        this.rankYesterday = rankYesterday;
        this.name = name;
        this.idap = idap;
        this.networth = networth;
        this.amtAvailable = amtAvailable;
    }
}

Add class representing user data for a single competition


package info.u_team.u_team_core.gui.render;

import com.mojang.blaze3d.matrix.MatrixStack;
import com.mojang.blaze3d.systems.RenderSystem;

import info.u_team.u_team_core.util.RGBA;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.AbstractGui;
import net.minecraft.client.renderer.texture.TextureAtlasSprite;
import net.minecraft.inventory.container.PlayerContainer;
import net.minecraft.util.ResourceLocation;
import net.minecraftforge.fluids.FluidStack;

public class FluidInventoryRenderer extends AbstractGui {

	private static final ResourceLocation ATLAS = PlayerContainer.LOCATION_BLOCKS_TEXTURE;

	@SuppressWarnings("deprecation")
	public void drawFluid(MatrixStack matrixStack, int x, int y, FluidStack stack) {
		if (stack == null || stack.isEmpty()) {
			return;
		}

		final TextureAtlasSprite sprite = getFluidSprite(stack);
		Minecraft.getInstance().getTextureManager().bindTexture(ATLAS);

		RenderSystem.enableBlend();
		RenderSystem.enableAlphaTest();

		final RGBA rgba = RGBA.fromARGB(stack.getFluid().getAttributes().getColor(stack));
		RenderSystem.color4f(rgba.getRedComponent(), rgba.getGreenComponent(), rgba.getBlueComponent(), rgba.getAlphaComponent());

		blit(matrixStack, x, y, 100, 16, 16, sprite);

		RenderSystem.color4f(1, 1, 1, 1);

		RenderSystem.disableAlphaTest();
		RenderSystem.disableBlend();
	}

	private TextureAtlasSprite getFluidSprite(FluidStack stack) {
		return Minecraft.getInstance().getAtlasSpriteGetter(ATLAS).apply(stack.getFluid().getAttributes().getStillTexture(stack));
	}
}

Copy to new class with renamed name

Copy to new class with renamed name


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

package org.whattf.datatype;

import org.relaxng.datatype.DatatypeException;

public class CharsetList extends AbstractDatatype {

    /**
     * The singleton instance.
     */
    public static final CharsetList THE_INSTANCE = new CharsetList();

    private enum State {
        WS_BEFORE_TOKEN
    }

    private CharsetList() {
        super();
    }

    @Override
    public void checkValid(CharSequence literal) throws DatatypeException {
        State state = State.WS_BEFORE_TOKEN;
        for (int i = 0; i < literal.length(); i++) {
            char c = literal.charAt(i);
            switch (state) {
            }
        }
        switch (state) {
        }
    }

    private boolean isTokenChar(char c) {
        return (c >= 'a' && c <= 'z') || (c >= '0' && c <= '9') || c == '!'
                || c == '#' || c == '$' || c == '%' || c == '&' || c == '\''
                || c == '+' || c == '-' || c == '^' || c == '_' || c == '`'
                || c == '{' || c == '}' || c == '~';
    }

    @Override
    public String getName() {
        return "character encoding list";
    }

}

Save charset list awaiting input from Hixie

--HG--
extra : convert_revision : svn%3Ae7398766-c432-0410-9565-638d39ca0058/trunk%40237


package boa.datagen.forges.github;

import java.io.File;

import boa.datagen.util.FileIO;

public class JsonSplitter {

	final private int Num_Threads;
	private String outDir;
	private String inDir;

	JsonSplitter(int threads, String outDir, String inDir){
		this.Num_Threads = threads;
		this.outDir = outDir;
		this.inDir = inDir;
	}

	public static void main(String[] args) {
		JsonSplitter JS = new JsonSplitter(Integer.parseInt(args[0]), args[1], args[2]);
		JS.split();
	}

	public void split () {
		Splitter[] workers = new Splitter[Num_Threads];
		for (int i = 0; i < Num_Threads; i++) {
			Splitter worker = new Splitter(i, outDir);
			workers[i] = worker;
		}
		File[] files = new File(inDir).listFiles();

		for (int i = 0; i < files.length; i ++) {
			if (!files[i].getPath().contains(".json"))
				continue;
			boolean assigned = false;
			while (!assigned) {
				for (int j = 0; j < Num_Threads; j++) {
					if (workers[j].isAvailable()){
						workers[j].setFile(files[i]);
						new Thread(workers[j]).start();
						try {
							Thread.sleep(10);
						} catch (InterruptedException e) {
							e.printStackTrace();
						}
						assigned = true;
						break;
					}
					try {
						Thread.sleep(100);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
			}
		}
	}

	private class Splitter implements Runnable {
		private boolean available = true;
		private File file;
		private String dir;
		private int id;
		Splitter(int id, String outDir) {
			this.id = id;
			this.dir = outDir + id;
			File output = new File(dir);
			if (!output.exists())
				output.mkdirs();
		}

		public boolean isAvailable() { return available; }

		public void setFile(File file) {
			this.file = file;
		}

		private void proccessFile(){
			String content = FileIO.readFileContents(file);
			System.out.println(id + " is processing " + file.getName());
			FileIO.writeFileContents(new File(dir +"/" + file.getName()), content);
		}

		@Override
		public void run() {
			available = false;
			proccessFile();
			try {
				Thread.sleep(150 * Num_Threads + 1);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			available = true;
		}

	}
}

Divide json metadata to be run on multiple processes.


package io.sigpipe.sing.adapters;

import io.sigpipe.sing.dataset.feature.Feature;
import io.sigpipe.sing.dataset.feature.FeatureType;
import io.sigpipe.sing.graph.FeatureHierarchy;
import io.sigpipe.sing.graph.Sketch;
import io.sigpipe.sing.query.Expression;
import io.sigpipe.sing.query.Operator;
import io.sigpipe.sing.query.RelationalQuery;
import io.sigpipe.sing.util.PerformanceTimer;
import io.sigpipe.sing.util.TestConfiguration;

public class QueryTest {

    public static void main(String[] args)
    throws Exception {
        for (String featureName : TestConfiguration.FEATURE_NAMES) {
            ReadMetaBlob.activeFeatures.add(featureName);
        }

        FeatureHierarchy fh = new FeatureHierarchy();
        for (String featureName : TestConfiguration.FEATURE_NAMES) {
            System.out.println(
                    TestConfiguration.quantizers.get(featureName).numTicks()
                    + "   " + featureName);
            fh.addFeature(featureName, FeatureType.FLOAT);
        }
        fh.addFeature("location", FeatureType.STRING);
        Sketch s = new Sketch(fh);

        for (String f : args) {
            ReadMetaBlob.loadData(f, s);
        }

        RelationalQuery mq = new RelationalQuery();
        mq.addExpression(new Expression(Operator.STR_PREFIX, new Feature("location", "9xqj")));
        mq.addExpression(
                new Expression(
                    Operator.RANGE_INC,
                    new Feature("temperature_surface", 300.0f),
                    new Feature(320.0f)));
        mq.addExpression(
                new Expression(
                    Operator.GREATER,
                    new Feature("relative_humidity_zerodegc_isotherm", 70.0f)));

        mq.execute(s.getRoot());
        PerformanceTimer statQuery = new PerformanceTimer("relQuery");
        for (int i = 0; i < 1000; ++i) {
        statQuery.start();
        s.query(mq);
        statQuery.stopAndPrint();
        }
    }
}

Add very simple query test harness

Add very simple query test harness


package com.reactlibrary;

import com.facebook.react.bridge.Promise;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.ReactContextBaseJavaModule;
import com.facebook.react.bridge.ReactMethod;
import org.tensorflow.Operation;

public class RNTensorflowGraphOperationsModule extends ReactContextBaseJavaModule {

    private Operation graphOperation;

    public RNTensorflowGraphOperationsModule(ReactApplicationContext reactContext) {
        super(reactContext);
    }

    @Override
    public String getName() {
        return "TensorflorGraphOperation";
    }

    @ReactMethod
    public void init(Operation graphOperation) {
        this.graphOperation = graphOperation;
    }

    @ReactMethod
    public void inputListLength(String s, Promise promise) {
        try {
            promise.resolve(graphOperation.inputListLength(s));
        } catch (Exception e) {
            promise.reject(e);
        }
    }

    @ReactMethod
    public void name(Promise promise) {
        try {
            promise.resolve(graphOperation.name());
        } catch (Exception e) {
            promise.reject(e);
        }
    }

    @ReactMethod
    public void numOutputs(Promise promise) {
        try {
            promise.resolve(graphOperation.numOutputs());
        } catch (Exception e) {
            promise.reject(e);
        }
    }

    @ReactMethod
    public void output(int output, Promise promise) {
        try {
            promise.resolve(graphOperation.output(output));
        } catch (Exception e) {
            promise.reject(e);
        }
    }

    @ReactMethod
    public void outputList(int i, int ii, Promise promise) {
        try {
            promise.resolve(graphOperation.outputList(i, ii));
        } catch (Exception e) {
            promise.reject(e);
        }
    }

    @ReactMethod
    public void outputListLength(String s, Promise promise) {
        try {
            promise.resolve(graphOperation.outputListLength(s));
        } catch (Exception e) {
            promise.reject(e);
        }
    }

    @ReactMethod
    public void type(Promise promise) {
        try {
            promise.resolve(graphOperation.type());
        } catch (Exception e) {
            promise.reject(e);
        }
    }
}

Implement first draft for graph operations


package com.es.lib.common.time;

import com.es.lib.common.DateUtil;
import com.es.lib.common.Pluralizer;

import java.time.Duration;
import java.time.LocalDateTime;
import java.time.Period;
import java.util.Date;

/**
 * @author Zuzoev Dmitry - zuzoev.d@ext-system.com
 * @since 10.05.2018
 */
public final class PeriodUtil {

    private static final int MINUTES_PER_HOUR = 60;
    private static final int SECONDS_PER_MINUTE = 60;
    private static final int SECONDS_PER_HOUR = SECONDS_PER_MINUTE * MINUTES_PER_HOUR;

    public static String pretty(Date date, boolean useBraces) {
        return pretty(DateUtil.convert(date), useBraces);
    }

    public static String pretty(LocalDateTime date, boolean useBraces) {
        return pretty(date, LocalDateTime.now(), useBraces);
    }

    public static String pretty(Date date, Date dateNext, boolean useBraces) {
        return pretty(DateUtil.convert(date), DateUtil.convert(dateNext), useBraces);
    }

    public static String pretty(LocalDateTime date, LocalDateTime dateNext, boolean useBraces) {
        if (date == null || dateNext == null) {
            return null;
        }
        Period period = Period.between(date.toLocalDate(), dateNext.toLocalDate());
        long[] time = getTime(date, dateNext);
        StringBuilder sb = new StringBuilder();
        if (period.getYears() > 0) {
            sb.append(period.getYears()).append(" ").append(Pluralizer.evaluate(period.getYears(), "год", "года", "лет"));
        }
        if (period.getMonths() > 0) {
            sb.append(period.getMonths()).append(" мес.");
        }
        if (period.getDays() > 0) {
            sb.append(period.getDays()).append(" дн.");
        }
        if (time[0] > 0) {
            sb.append(time[0]).append(" ч.");
        }
        if (time[1] > 0) {
            sb.append(time[1]).append(" м.");
        }
        if (time[2] > 0) {
            sb.append(time[2]).append(" c.");
        }
        String result = sb.toString();
        if (useBraces) {
            result = "(" + result + ")";
        }
        return result;
    }

    private static long[] getTime(LocalDateTime date, LocalDateTime dateNext) {
        LocalDateTime original = LocalDateTime.of(dateNext.getYear(),
            dateNext.getMonthValue(), dateNext.getDayOfMonth(), date.getHour(), date.getMinute(), date.getSecond());
        Duration duration = Duration.between(original, dateNext);

        long seconds = duration.getSeconds();

        long hours = seconds / SECONDS_PER_HOUR;
        long minutes = ((seconds % SECONDS_PER_HOUR) / SECONDS_PER_MINUTE);
        long secs = (seconds % SECONDS_PER_MINUTE);

        return new long[]{hours, minutes, secs};
    }
}

Add pretty print interval util

Add pretty print interval util


package info.u_team.u_team_core.intern.init;

import info.u_team.u_team_core.item.USpawnEggItem;
import net.minecraft.block.DispenserBlock;
import net.minecraft.entity.*;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.util.Direction;
import net.minecraftforge.client.event.ColorHandlerEvent;
import net.minecraftforge.eventbus.api.IEventBus;
import net.minecraftforge.fml.event.lifecycle.*;

public class UCoreLazySpawnEggs {

	private static void setup(FMLCommonSetupEvent event) {
		event.enqueueWork(() -> {
			USpawnEggItem.LAZY_EGGS.forEach(pair -> {
				final EntityType<?> type = pair.getKey().getValue();
				final USpawnEggItem item = pair.getValue();

				item.typeIn = type;

				DispenserBlock.registerDispenseBehavior(item, (source, stack) -> {
					final Direction direction = source.getBlockState().get(DispenserBlock.FACING);
					final EntityType<?> entityType = ((USpawnEggItem) stack.getItem()).getType(stack.getTag());
					entityType.spawn(source.getWorld(), stack, (PlayerEntity) null, source.getBlockPos().offset(direction), SpawnReason.DISPENSER, direction != Direction.UP, false);
					stack.shrink(1);
					return stack;
				});
			});
		});
	}

	private static void colorItem(ColorHandlerEvent.Item event) {
		USpawnEggItem.LAZY_EGGS.forEach(pair -> {
			final USpawnEggItem item = pair.getValue();

			event.getItemColors().register((stack, color) -> {
				return item.getColor(color);
			}, item);
		});
	}

	private static void loadComplete(FMLLoadCompleteEvent event) {
		event.enqueueWork(() -> {
			USpawnEggItem.LAZY_EGGS.forEach(pair -> {
				final EntityType<?> type = pair.getKey().getValue();
				final USpawnEggItem item = pair.getValue();

				USpawnEggItem.EGGS.put(type, item);
			});
		});
	}

	public static void registerMod(IEventBus bus) {
		bus.addListener(UCoreLazySpawnEggs::setup);
		bus.addListener(UCoreLazySpawnEggs::colorItem);
		bus.addListener(UCoreLazySpawnEggs::loadComplete);
	}

}

Add core lazy spawn eggs handler

Add core lazy spawn eggs handler


package eme.model;

import static org.junit.Assert.assertEquals;

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

public class IntermediateModelTest {

    IntermediateModel model;

    @Before
    public void setUp() throws Exception {
        model = new IntermediateModel("TestModel");
    }

    @Test
    public void testAutoAdd() {
        addMVCPackages();
        model.add(new ExtractedClass("NormalClass", false));
        model.add(new ExtractedClass("main.AbstractClass", true));
        model.add(new ExtractedInterface("main.model.Interface"));
        model.add(new ExtractedEnumeration("main.view.Enumeration"));
        model.add(new ExtractedClass("main.controller.OuterClass$InnerClass", false));
        checkTypeAmount(model.getRoot(), 1);
    }

    @Test
    public void testDuplicatePackage() {
        addMVCPackages();
        addMVCPackages();
        assertEquals(4, countPackages(model.getRoot()));
    }

    @Test(expected = RuntimeException.class)
    public void testUnknownPackage() {
        addMVCPackages();
        model.add(new ExtractedPackage("illegal.subpackage"));
        model.add(new ExtractedPackage("main.illegal.subpackage"));
    }

    private void addMVCPackages() {
        model.add(new ExtractedPackage(""));
        model.add(new ExtractedPackage("main"));
        model.add(new ExtractedPackage("main.model"));
        model.add(new ExtractedPackage("main.view"));
        model.add(new ExtractedPackage("main.controller"));
    }

    private void checkTypeAmount(ExtractedPackage fromPackage, int amountPerPackage) {
        assertEquals(amountPerPackage, fromPackage.getTypes().size());
        for (ExtractedPackage subpackage : fromPackage.getSubpackages()) {
            checkTypeAmount(subpackage, amountPerPackage);
        }
    }

    private int countPackages(ExtractedPackage inPackage) {
        int amount = 0;
        for (ExtractedPackage subpackage : inPackage.getSubpackages()) {
            amount += 1 + countPackages(subpackage);
        }
        return amount;
    }
}

Test case for the intermediate model.

ADD: Test case for the intermediate model.


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

import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;

import javax.servlet.Filter;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.samples.mvc.config.WebMvcConfiguration;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;

/**
 * @author Rob Winch
 *
 */
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes={RootConfiguration.class, WebMvcConfiguration.class})
@WebAppConfiguration
public class SecurityConfigTests {
    private MockMvc mvc;

    @Autowired
    private WebApplicationContext context;

    @Autowired
    private Filter springSecurityFilterChain;

    @Before
    public void setup() {
        mvc = MockMvcBuilders
                .webAppContextSetup(context)
                .addFilters(springSecurityFilterChain)
                .build();
    }

    @Test
    public void composeMessage() throws Exception {
        MockHttpServletRequestBuilder composeMessage =
            post("/")
                .param("summary", "New Message")
                .param("text", "This is a new message");

        mvc.perform(composeMessage)
            .andExpect(redirectedUrlPattern("/*"));
    }
}

Add MockMvc tests for insecuremvc

SEC-2633: Add MockMvc tests for insecuremvc


package com.pinterest.secor.parser;

import com.pinterest.secor.common.SecorConfig;

import java.util.Date;

public class NoDateStampJsonMessageParser extends JsonMessageParser {
    public NoDateStampJsonMessageParser(SecorConfig config) {
        super(config);
    }

    @Override
    protected String[] generatePartitions(long timestampMillis, boolean usingHourly)
        throws Exception {
            return new String[]{};
    }
}

Add prefixless overload of JsonMessageParser.


package com.redhat.ceylon.common.test;

import java.io.File;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

import com.redhat.ceylon.common.Authentication;
import com.redhat.ceylon.common.CeylonConfig;
import com.redhat.ceylon.common.ConfigParser;
import com.redhat.ceylon.common.Proxies;
import com.redhat.ceylon.common.Proxies.Proxy;

public class ProxyTool {

    public static void main(String[] args) throws Exception {
        if (args.length != 3) {
            usage("Wrong number of arguments");
        }
        String mode = args[0];

        File configFile = new File(args[1]);
        if (!configFile.exists()) {
            usage("Config file doesn't exist");
            return;
        }

        final URL url;
        try {
            url  = new URL(args[2]);
        } catch (MalformedURLException e) {
            usage("Malformed URL");
            return;
        }

        CeylonConfig config = ConfigParser.loadConfigFromFile(configFile);
        Authentication auth = Authentication.fromConfig(config);
        Proxy proxy = Proxies.withConfig(config).getProxy();
        final URLConnection conn;
        switch (mode){
        case "proxy":
            java.net.Proxy netProxy = auth.getProxy();
            conn = url.openConnection(netProxy);
            break;
        case "install":
            auth.installProxy();
            conn = url.openConnection();
            break;
        default:
            throw new RuntimeException("Unsupported mode");
        }

        InputStream in = conn.getInputStream();
        try {
            int ch = in.read();
            while (ch != -1) {
                System.out.append((char)ch);
                ch = in.read();
            }
        } finally {
            in.close();
        }

    }

    private static void usage(String error) {
        if (error != null) {
            System.err.println(error);
        }
        System.err.println("Expect 3 arguments: proxy|install <configfile> <url>");
        System.exit(1);
    }

}

Add a simple tool for manual testing of the Proxy configuration


package com.elmakers.mine.bukkit.action.builtin;

/**
 * Not deprecating this yet, but prefer to use EquipAction.
 */
public class WearAction extends EquipAction {
}

Add in a placeholder Wear action for compatibility


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

/**
 * Given two strings passed as argument, can you write a method to return true if the second
 * contains the first one?
 *
 * @author Pedro Vicente Gómez Sánchez.
 */
public class Contains {

}

Add statement to problem 32

Add statement to problem 32


package hudson.remoting;

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

/**
 * Takes a directory of jars and populates them into the given jar cache
 * directory with the correct hash names.
 *
 *
Ideally this class should exist outside hudson.remoting but unfortunately
 * it needs access to package-private methods in hudson.remoting.
 *
 * @author Akshay Dayal
 */
public class InitializeJarCacheMain {

    private static final FilenameFilter JAR_FILE_FILTER = new FilenameFilter() {
        @Override
        public boolean accept(File dir, String name) {
            return name.endsWith(".jar");
        }
    };

    /**
     * Requires 2 parameters:
     *

     *
The source jar directory.
     *
The jar cache directory.
     *

     */
    public static void main(String[] argv) throws Exception {
        if (argv.length != 2) {
            throw new IllegalArgumentException(
                    "Usage: java -cp slave.jar hudson.remoting.InitializeJarCacheMain " +
                    "<source jar dir> <jar cache dir>");
        }

        File sourceJarDir = new File(argv[0]);
        File jarCacheDir = new File(argv[1]);
        FileSystemJarCache jarCache = new FileSystemJarCache(jarCacheDir, false);

        File[] jars = sourceJarDir.listFiles(JAR_FILE_FILTER);
        for (File jar : jars) {
            Checksum checksum = Checksum.forFile(jar);
            File newJarLocation = jarCache.map(checksum.sum1, checksum.sum2);

            newJarLocation.getParentFile().mkdirs();
            copyFile(jar, newJarLocation);
        }
    }

    /**
     * Util method to copy file from one location to another.
     *
     *
We don't have access to Guava, apache or Java7, so we have to write
     * our own from scratch.
     */
    private static void copyFile(File src, File dest) throws Exception {
        FileInputStream input = null;
        FileOutputStream output = null;
        try {
            input = new FileInputStream(src);
            output = new FileOutputStream(dest);
            byte[] buf = new byte[1024 * 1024];
            int bytesRead;
            while ((bytesRead = input.read(buf)) > 0) {
                output.write(buf, 0, bytesRead);
            }
        } finally {
            if (input != null) {
                input.close();
            }
            if (output != null) {
                output.close();
            }
        }
    }
}

Add a utility main that can populate a jar cache dir given another directory of jars.

This can be used to initialze a node's jar cache ahead of time before it connects to the master. This has performance benefits for the master as it won't have to transfer jars over to the node.


/*
 * Copyright 2008 FatWire Corporation. 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 com.fatwire.gst.foundation.facade.logging;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * Utility class for Loggers.
 *
 * @author Dolf Dijkstra
 *
 */
public class LogUtil {

    /**
     * Returns the Log for the provided class based on the package name of the
     * class.
     *
     * @param clazz
     * @return
     */
    public static Log getLog(Class<?> clazz) {
        return LogFactory.getLog(clazz.getPackage().getName());
    }

}

Add utility class to work with loggers. Initial method is to help with loggers naming convention, based on package name of the class.


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

package io.soliton.protobuf.plugin;

import com.google.protobuf.DescriptorProtos;
import com.google.protobuf.Descriptors;
import com.google.protobuf.compiler.PluginProtos;
import io.soliton.protobuf.plugin.testing.Testing;
import org.junit.Assert;
import org.junit.Test;

import javax.tools.JavaCompiler;
import javax.tools.JavaFileObject;
import javax.tools.SimpleJavaFileObject;
import javax.tools.ToolProvider;
import java.io.ByteArrayOutputStream;
import java.net.URI;

public class ProtoServiceHandlerTest {

  private static class JavaSourceFromString extends SimpleJavaFileObject {

    final String code;

    /**
     * Constructs a new JavaSourceFromString.
     * @param name the name of the compilation unit represented by this file object
     * @param code the source code for the compilation unit represented by this file object
     */
    JavaSourceFromString(String name, String code) {
      super(URI.create("string:///" + name.replace('.', '/') + Kind.SOURCE.extension),
          Kind.SOURCE);
      this.code = code;
    }

    @Override
    public CharSequence getCharContent(boolean ignoreEncodingErrors) {
      return code;
    }
  }

  @Test
  public void testHandle() throws Exception {
    Descriptors.Descriptor personDescriptor = Testing.Person.getDescriptor();
    DescriptorProtos.FileDescriptorProto protoFile = personDescriptor.getFile().toProto();
    TypeMap types = TypeMap.of(protoFile);
    ByteArrayOutputStream output = new ByteArrayOutputStream();
    ProtoServiceHandler serviceHandler = new ProtoServiceHandler(
        "io.soliton.protobuf.plugin.testing", types, output);
    serviceHandler.handle(protoFile.getServiceList().get(0));
    PluginProtos.CodeGeneratorResponse response = PluginProtos.CodeGeneratorResponse.parseFrom(
        output.toByteArray());
    Assert.assertNotNull(response);
    Assert.assertEquals(1, response.getFileCount());
    Assert.assertEquals("io/soliton/protobuf/plugin/testing/PhoneBookService.java",
        response.getFile(0).getName());
    String fileContent = response.getFile(0).getContent();
    JavaFileObject file = new JavaSourceFromString
        ("io/soliton/protobuf/plugin/testing/PhoneBookService.java", fileContent);
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
  }
}

Add test code for the plugin

Add test code for the plugin


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

import io.gravitee.management.model.MemberEntity;
import io.gravitee.management.service.ApiService;
import io.gravitee.management.service.ApplicationService;

import javax.inject.Inject;
import javax.ws.rs.GET;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import java.util.Set;

/**
 * @author David BRASSELY (brasseld at gmail.com)
 */
public class ApplicationMembersResource {

    @Inject
    private ApplicationService applicationService;

    @PathParam("applicationName")
    private String applicationName;

    @GET
    @Produces(MediaType.APPLICATION_JSON)
    public Set<MemberEntity> members() {
        // Check that the API exists
        applicationService.findByName(applicationName);

        return applicationService.getMembers(applicationName, null);
    }
}

Add members list per application

feat(member): Add members list per application


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

/**
 * Created by drfish on 25/06/2017.
 */
public class _013RomanToInteger {
    public int romanToInt(String s) {
        Map<Character, Integer> map = new HashMap<Character, Integer>() {{
            put('M', 1000);
            put('D', 500);
            put('C', 100);
            put('L', 50);
            put('X', 10);
            put('V', 5);
            put('I', 1);
        }};
        int result = 0;
        for (int i = 0; i < s.length(); i++) {
            if (i > 0 && map.get(s.charAt(i)) > map.get(s.charAt(i - 1))) {
                result -= map.get(s.charAt(i - 1));
                result += map.get(s.charAt(i)) - map.get(s.charAt(i - 1));
            } else {
                result += map.get(s.charAt(i));
            }
        }
        return result;
    }

    public static void main(String[] args) {
        _013RomanToInteger solution = new _013RomanToInteger();
        assert 12 == solution.romanToInt("XII");
        assert 21 == solution.romanToInt("XXI");
        assert 99 == solution.romanToInt("XCIX");
    }
}

Add java solution for 13

Add java solution for 13


package com.boundary.metrics.vmware;

import io.dropwizard.configuration.ConfigurationFactory;
import io.dropwizard.jackson.Jackson;

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

import javax.validation.Validation;
import javax.validation.Validator;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.google.common.io.Resources;

public class VMWareTestUtils {

	public static VMwarePerfAdapterConfiguration getConfiguration(String resource) throws Exception {

		VMwarePerfAdapterConfiguration configuration = null;
		File validFile = new File(Resources.getResource(resource).toURI());
		System.out.println(resource);

		Validator validator = Validation.buildDefaultValidatorFactory()
				.getValidator();
		ConfigurationFactory<VMwarePerfAdapterConfiguration> factory = new ConfigurationFactory<VMwarePerfAdapterConfiguration>(
				VMwarePerfAdapterConfiguration.class, validator,
				Jackson.newObjectMapper(), "dw");

		try {
			configuration = factory.build(validFile);
		} catch (JsonParseException e) {

			e.printStackTrace();
		} catch (JsonMappingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

		return configuration;
	}
}

Add utility class loads VMWare adapter configuration file


package com.xtremelabs.robolectric.util;

import org.junit.Test;

import java.io.InputStream;
import java.io.StringBufferInputStream;

import static junit.framework.Assert.assertEquals;

public class StringsTest {
    @Test
    public void shouldGetStringFromStream() throws Exception {
        InputStream stream = new StringBufferInputStream("some random string");
        assertEquals("some random string", Strings.fromStream(stream));
    }
}

Test for Strings utility class

Test for Strings utility class


/*
 * Copyright 2019 Rundeck, Inc. (http://rundeck.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 com.dtolabs.rundeck.core.jobs;

import com.dtolabs.rundeck.core.execution.workflow.StepExecutionContext;
import lombok.Builder;
import lombok.Data;

@Data
@Builder
public class ExecutionLifecycleStatusImpl
        implements ExecutionLifecycleStatus
{
    private final boolean successful;
    private final String errorMessage;
    private final boolean useNewValues;
    private final StepExecutionContext executionContext;
}

Add utility impl for ExecutionLifecycleStatus


package arez.integration.verify;

import arez.Arez;
import arez.Disposable;
import arez.annotations.ArezComponent;
import arez.annotations.Reference;
import arez.annotations.ReferenceId;
import arez.annotations.Repository;
import arez.component.Identifiable;
import arez.component.TypeBasedLocator;
import arez.component.Verifiable;
import arez.integration.AbstractArezIntegrationTest;
import java.util.HashMap;
import java.util.Objects;
import javax.annotation.Nonnull;
import org.testng.annotations.Test;

public class VerifyIntegrationTest
  extends AbstractArezIntegrationTest
{
  @Test
  public void scenario()
    throws Throwable
  {
    final VerifyIntegrationTest_Model2Repository repository =
      VerifyIntegrationTest_Model2Repository.newRepository();

    final TypeBasedLocator locator = new TypeBasedLocator();
    Arez.context().registerLocator( locator );

    final HashMap<Object, Model1> entities1 = new HashMap<>();
    final HashMap<Object, Model2> entities2 = new HashMap<>();
    locator.registerLookup( Model1.class, entities1::get );
    locator.registerLookup( Model2.class, entities2::get );

    final Model2 model2a = repository.create();
    final Object model2aId = Objects.requireNonNull( Identifiable.getArezId( model2a ) );
    entities2.put( model2aId, model2a );

    final Model1 model1 = Model1.create( model2aId );
    final Object model1Id = Objects.requireNonNull( Identifiable.getArezId( model1 ) );
    entities1.put( model1Id, model1 );

    // Should verify as will link correctly
    Verifiable.verify( model1 );

    {
      entities2.clear();

      // Fail to verify as related is missing
      assertInvariant( () -> Verifiable.verify( model1 ),
                       "Reference method named 'getModel2' invoked on component named 'Model1.0' missing related entity. Id = 0" );
      entities2.put( model2aId, model2a );
    }

    {
      entities1.clear();

      // Fail to verify as missing self
      assertInvariant( () -> Verifiable.verify( model1 ),
                       "Attempted to lookup self in Locator with type VerifyIntegrationTest.Model1 and id '0' but unable to locate self. Actual value: null" );

      entities1.put( model1Id, model1 );
    }

    Disposable.dispose( model1 );

    // Fail to verify as disposed
    assertInvariant( () -> Verifiable.verify( model1 ),
                     "Method named 'verify' invoked on disposed component named 'Model1.0'" );
  }

  @ArezComponent( allowEmpty = true )
  static abstract class Model1
  {
    @Nonnull
    private final Object _model2Id;

    static Model1 create( @Nonnull final Object model2Id )
    {
      return new VerifyIntegrationTest_Arez_Model1( model2Id );
    }

    Model1( @Nonnull final Object model2Id )
    {
      _model2Id = model2Id;
    }

    @Reference
    abstract Model2 getModel2();

    @ReferenceId
    @Nonnull
    final Object getModel2Id()
    {
      return _model2Id;
    }
  }

  @Repository
  @ArezComponent( allowEmpty = true )
  static abstract class Model2
  {
  }
}

Add integration test for verify

Add integration test for verify


package org.kohsuke.args4j;

// a 'custom' exception
import javax.management.InvalidAttributeValueException;

public class CustomExceptionTest extends Args4JTestBase<CustomExceptionTest> {

    private String errMsgX = "this is a usual CLI exception";
    private String errMsgY = "this is a 'custom' exception";

    @Option(name="-x")
    public void setX(String x) {
        throw new IllegalArgumentException(errMsgX);
    }

    @Option(name="-y")
    public void setY(String y) throws InvalidAttributeValueException {
        throw new InvalidAttributeValueException(errMsgX);
    }

    @Override
    public CustomExceptionTest getTestObject() {
        return this;
    }

    protected void tryThis(String expected, Class expectedExceptionClass, String... parserArgs) {
        String expMsg = expectedExceptionClass.getName() + ": " + expected;
        try {
            parser.parseArgument(parserArgs);
            fail("Exception expected.");
        } catch (RuntimeException e) {
            // RuntimeExceptions are passed through the parser to the caller.
            assertEquals("Lost exception message.", expMsg, e.toString());
        } catch (CmdLineException e) {
            // Other Exceptions are wrapped into a CLE so we must ensure not to loose the
            // message.
            assertEquals("Lost exception message.", expMsg, e.getMessage());
        } catch (Exception e) {
            fail("Wrong exception type thrown.");
        }
    }

    public void testRuntimeException() throws Exception {
        tryThis(errMsgX, IllegalArgumentException.class, "-x", "value");
    }

    public void testCustomException() throws Exception {
        tryThis(errMsgX, InvalidAttributeValueException.class, "-y", "value");
    }

}

Add a test how to handle thrown exceptions thrown in setters.


// Copyright 2015 Google Inc. 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 com.google.devtools.build.lib.analysis.util;

import com.google.common.collect.ImmutableList;
import com.google.devtools.build.lib.analysis.config.BuildConfiguration;
import com.google.devtools.build.lib.analysis.config.BuildOptions;
import com.google.devtools.build.lib.analysis.config.DefaultsPackage;
import com.google.devtools.build.lib.analysis.config.FragmentOptions;
import com.google.devtools.common.options.OptionsBase;
import com.google.devtools.common.options.OptionsParser;
import com.google.devtools.common.options.OptionsParsingException;

/**
 * Helper class for testing {@link DefaultsPackage}.
 */
public class DefaultsPackageUtil {

  public static String getDefaultsPackageForOptions(Class<? extends FragmentOptions> optionsClass,
      String... options) throws OptionsParsingException {
    OptionsParser parser = OptionsParser.newOptionsParser(
        ImmutableList.<Class<? extends OptionsBase>>of(
            BuildConfiguration.Options.class, optionsClass));
    parser.parse(options);
    return DefaultsPackage.getDefaultsPackageContent(BuildOptions.of(
        ImmutableList.<Class<? extends FragmentOptions>>of(
            BuildConfiguration.Options.class, optionsClass), parser));
  }
}

Split up the DefaultsPackageTest into C++ and Java parts. Move some tests out
of BuildConfigurationTest into a new test class.

--
MOS_MIGRATED_REVID=89113080


/*
 * Copyright 2013 Erwin Müller <erwin.mueller@deventm.org>
 *
 * This file is part of globalpom-utils.
 *
 * globalpom-utils is free software: you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License as published by the
 * Free Software Foundation, either version 3 of the License, or (at your
 * option) any later version.
 *
 * globalpom-utils is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
 * details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with globalpom-utils. If not, see <http://www.gnu.org/licenses/>.
 */
package com.anrisoftware.globalpom.constants;

import javax.inject.Inject;
import javax.inject.Singleton;

import com.anrisoftware.globalpom.measurement.ExactAverageValueFactory;
import com.anrisoftware.globalpom.measurement.Value;
import com.google.inject.Provider;

/**
 * Provides the value of the absolute zero {@code T→0=-273.15 °C} that
 * calculates error propagation using simpler average errors.
 *
 * @author Erwin Mueller, erwin.mueller@deventm.org
 * @since 1.9
 */
@Singleton
public class AverageAbsoluteZeroProvider implements Provider<Value> {

	@Inject
	private ExactAverageValueFactory factory;

	@Override
	public Value get() {
		return factory.create(-273.15d);
	}

}

Add absolute zero constant -273.15 °C

Add absolute zero constant -273.15 °C


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

package com.example.asadkhan.sunshine.utils;

import junit.framework.Assert;

import java.util.concurrent.Callable;

public abstract class PollingCheck {
    private static final long TIME_SLICE = 50;
    private long mTimeout = 3000;

    public PollingCheck() {
    }

    public PollingCheck(long timeout) {
        mTimeout = timeout;
    }

    protected abstract boolean check();

    public void run() {
        if (check()) {
            return;
        }

        long timeout = mTimeout;
        while (timeout > 0) {
            try {
                Thread.sleep(TIME_SLICE);
            } catch (InterruptedException e) {
                Assert.fail("unexpected InterruptedException");
            }

            if (check()) {
                return;
            }

            timeout -= TIME_SLICE;
        }

        Assert.fail("unexpected timeout");
    }

    public static void check(CharSequence message, long timeout, Callable<Boolean> condition)
            throws Exception {
        while (timeout > 0) {
            if (condition.call()) {
                return;
            }

            Thread.sleep(TIME_SLICE);
            timeout -= TIME_SLICE;
        }

        Assert.fail(message.toString());
    }
}

Add Android Util Unit Test Classes

Add Android Util Unit Test Classes


package com.sleekbyte.tailor.utils;

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

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.runners.MockitoJUnitRunner;

/**
 * Tests for {@link Pair}.
 */
@RunWith(MockitoJUnitRunner.class)
public final class PairTest {

    Pair pair;

    @Before
    public void setUp() {
        pair = new Pair<>("Left", "Right");
    }

    @Test
    public void testUnequalPairs() {
        Pair candidatePair = new Pair<>(1, 2);
        assertFalse(pair.equals(candidatePair));
    }

    @Test
    public void testEqualPairs() {
        Pair candidatePair = new Pair<>("Left", "Right");
        assertEquals(pair, candidatePair);
    }

}

Add additional tests for Pair.java

Add additional tests for Pair.java


package org.libreoffice.example.helper;

import com.sun.star.frame.XDesktop;
import com.sun.star.frame.XFrame;
import com.sun.star.frame.XModel;
import com.sun.star.lang.XComponent;
import com.sun.star.lang.XMultiComponentFactory;
import com.sun.star.text.XTextDocument;
import com.sun.star.uno.UnoRuntime;
import com.sun.star.uno.XComponentContext;

public class DocumentHelper {

	/** Returns the curerent XDesktop */
	public static XDesktop getCurrentDesktop(XComponentContext xContext) {
		XMultiComponentFactory xMCF = (XMultiComponentFactory) UnoRuntime.queryInterface(XMultiComponentFactory.class,
				xContext.getServiceManager());
        Object desktop = null;
		try {
			desktop = xMCF.createInstanceWithContext("com.sun.star.frame.Desktop", xContext);
		} catch (Exception e) {
			return null;
		}
        return (XDesktop) UnoRuntime.queryInterface(com.sun.star.frame.XDesktop.class, desktop);
	}

	/** Returns the current XComponent */
    private static XComponent getCurrentComponent(XComponentContext xContext) {
        return (XComponent) getCurrentDesktop(xContext).getCurrentComponent();
    }

    /** Returns the current frame */
    public static XFrame getCurrentFrame(XComponentContext xContext) {
    	XModel xModel = (XModel) UnoRuntime.queryInterface(XModel.class, getCurrentComponent(xContext));
    	return xModel.getCurrentController().getFrame();
    }

    /** Returns the current text document (if any) */
    public static XTextDocument getCurrentDocument(XComponentContext xContext) {
        return (XTextDocument) UnoRuntime.queryInterface(XTextDocument.class, getCurrentComponent(xContext));
    }
}

Add helper to retrieve frame, document etc


package com.interview.recursion;

import java.util.*;

/**
 * Created by tushar_v_roy on 2/23/16.
 */
public class RemoveInvalidParenthesis {

    public List<String> removeInvalidParentheses(String s) {
        Set<String> res = new HashSet<>();
        int rmL = 0, rmR = 0;
        for(int i = 0; i < s.length(); i++) {
            if(s.charAt(i) == '(') rmL++;
            if(s.charAt(i) == ')') {
                if(rmL != 0) rmL--;
                else rmR++;
            }
        }
        DFS(res, s, 0, rmL, rmR, 0, new StringBuilder());
        return new ArrayList<String>(res);
    }

    public void DFS(Set<String> res, String s, int i, int rmL, int rmR, int open, StringBuilder sb) {
        if(i == s.length() && rmL == 0 && rmR == 0 && open == 0) {
            res.add(sb.toString());
            return;
        }
        if(i == s.length() || rmL < 0 || rmR < 0 || open < 0) return;

        char c = s.charAt(i);
        int len = sb.length();

        if(c == '(') {
            DFS(res, s, i + 1, rmL - 1, rmR, open, sb);
            DFS(res, s, i + 1, rmL, rmR, open + 1, sb.append(c));

        } else if(c == ')') {
            DFS(res, s, i + 1, rmL, rmR - 1, open, sb);
            DFS(res, s, i + 1, rmL, rmR, open - 1, sb.append(c));

        } else {
            DFS(res, s, i + 1, rmL, rmR, open, sb.append(c));
        }

        sb.setLength(len);
    }

    public static void main(String args[]) {

        String s = "(r(()()(";
        RemoveInvalidParenthesis rmp = new RemoveInvalidParenthesis();
        List<String> result = rmp.removeInvalidParentheses(s);
        result.forEach(s1 -> System.out.println(s1));
    }
}

Remove invalid parentheses to get all combinations of result


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

/**
 * You have two numbers represented by a linked list, where each node contains a single digit.The
 * digit are stored in reverse order,such that the 1's digit is at the head of the list. Write a
 * function that adds the two numbers and returns the sum as a linked list.
 *
 * Suppose the digits are stored in forward order. Repeat the above problem.
 *
 * Negative numbers are not allowed.
 *
 * @author Pedro Vicente Gómez Sánchez.
 */
public class SumLists {

}

Add statement to problem 61

Add statement to problem 61


package io.castle.client;

import io.castle.client.model.*;
import okhttp3.mockwebserver.MockResponse;
import okhttp3.mockwebserver.RecordedRequest;
import org.assertj.core.api.Assertions;
import org.junit.Assert;
import org.junit.Test;
import org.springframework.mock.web.MockHttpServletRequest;

import javax.servlet.http.HttpServletRequest;

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

import static okhttp3.mockwebserver.SocketPolicy.NO_RESPONSE;

public class CastleArchiveDevicesHttpTest extends AbstractCastleHttpLayerTest {

    public CastleArchiveDevicesHttpTest() {
        super(new AuthenticateFailoverStrategy(AuthenticateAction.CHALLENGE));
    }

    @Test public void archiveDevices() throws Exception {
        MockResponse mockResponse = new MockResponse();
        mockResponse.setBody("{\"id\":\"userId\",\"created_at\":null,\"updated_at\":\"2019-03-26T11:31:19.968Z\",\"last_seen_at\":\"2019-03-26T09:38:43.339Z\",\"flagged_at\":null,\"risk\":0.0,\"leaks_count\":3,\"devices_count\":2,\"email\":\"admin@example.com\",\"name\":\"Doe\",\"username\":null,\"phone\":null,\"address\":{\"street\":null,\"city\":null,\"postal_code\":null,\"region\":null,\"country\":null},\"custom_attributes\":{}}");
        server.enqueue(mockResponse);

        // And a mock Request
        HttpServletRequest request = new MockHttpServletRequest();

        // And an devices request is made
        CastleUser result = sdk.onRequest(request).archiveUserDevices("userId");

        // Then
        RecordedRequest recordedRequest = server.takeRequest();
        Assert.assertEquals(testServerBaseUrl.resolve("v1/users/userId/archive_devices"), recordedRequest.getRequestUrl());
        Assert.assertEquals("PUT", recordedRequest.getMethod());

        // and the correct Success model object is extracted
        CastleUser expected = new CastleUser();
        expected.setId("userId");
        expected.setUpdatedAt("2019-03-26T11:31:19.968Z");
        expected.setLastSeenAt("2019-03-26T09:38:43.339Z");
        expected.setLeaksCount(3);
        expected.setDevicesCount(2);
        expected.setEmail("admin@example.com");
        expected.setName("Doe");
        expected.setAddress(new CastleUserAddress());
        expected.setCustomAttributes(new HashMap<String, String>());

        Assertions.assertThat(result).isEqualToComparingFieldByFieldRecursively(expected);
    }

    @Test(expected = CastleRuntimeException.class)
    public void archiveDevicesTimeoutTest() {

        // given backend request timeouts
        server.enqueue(new MockResponse().setSocketPolicy(NO_RESPONSE));
        HttpServletRequest request = new MockHttpServletRequest();
        String userId = "userId";

        //when a review request is made
        sdk.onRequest(request).archiveUserDevices(userId);
    }
}

Add tests for archive devices api

Add tests for archive devices api


package seedu.tache.logic.parser;

import static org.junit.Assert.assertTrue;

import org.junit.Test;

import seedu.tache.logic.commands.AddCommand;
import seedu.tache.logic.commands.Command;
import seedu.tache.logic.commands.IncorrectCommand;

public class AddCommandParserTest {

    @Test
    public void parse_emptyArgument_failure() {
        Command invalidFormat = new AddCommandParser().parse("");
        assertIncorrectCommandType(invalidFormat);
    }

    @Test
    public void parse_correctArgument_success() {
        Command correctArgument = new AddCommandParser().parse("study form 10am to 10pm everday");
        assertAddCommandType(correctArgument);
    }

    private void assertIncorrectCommandType(Command command) {
        boolean isSameType = false;
        isSameType = command instanceof IncorrectCommand;
        assertTrue(isSameType);
    }

    private void assertAddCommandType(Command command) {
        boolean isSameType = false;
        isSameType = command instanceof AddCommand;
        assertTrue(isSameType);
    }
}

Add Test case for AddCommandParser

Add Test case for AddCommandParser


package com.google.sps.servlets;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/newEnvironment")
public class NewEnvironment extends HttpServlet {

  @Override
  protected void doPost(HttpServletRequest req, HttpServletResponse resp)
      throws ServletException, IOException {}
}

Add a servlet to pull an image and tag it.


package com.novoda.downloadmanager;

import android.app.Notification;

import static com.novoda.downloadmanager.NotificationCustomizer.NotificationStackState.SINGLE_PERSISTENT_NOTIFICATION;
import static org.mockito.Mockito.mock;

class NotificationInformationFixtures {

    private int id = 0;
    private Notification notification = mock(Notification.class);
    private NotificationCustomizer.NotificationStackState notificationStackState = SINGLE_PERSISTENT_NOTIFICATION;

    static NotificationInformationFixtures notificationInformation() {
        return new NotificationInformationFixtures();
    }

    NotificationInformationFixtures withId(int id) {
        this.id = id;
        return this;
    }

    NotificationInformationFixtures withNotification(Notification notification) {
        this.notification = notification;
        return this;
    }

    NotificationInformationFixtures withNotificationStackState(NotificationCustomizer.NotificationStackState notificationStackState) {
        this.notificationStackState = notificationStackState;
        return this;
    }

    NotificationInformation build() {
        return new NotificationInformation() {
            @Override
            public int getId() {
                return id;
            }

            @Override
            public Notification getNotification() {
                return notification;
            }

            @Override
            public NotificationCustomizer.NotificationStackState notificationStackState() {
                return notificationStackState;
            }
        };
    }
}

Create NotificationInformation fixtures for testing.


/*-
 * Copyright © 2016 Diamond Light Source Ltd.
 *
 * This file is part of GDA.
 *
 * GDA is free software: you can redistribute it and/or modify it under the
 * terms of the GNU General Public License version 3 as published by the Free
 * Software Foundation.
 *
 * GDA is distributed in the hope that it will be useful, but WITHOUT ANY
 * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
 * details.
 *
 * You should have received a copy of the GNU General Public License along
 * with GDA. If not, see <http://www.gnu.org/licenses/>.
 */

package org.eclipse.scanning.api.ui;

import java.beans.PropertyChangeListener;

public interface IStageScanConfiguration {

	void addPropertyChangeListener(PropertyChangeListener listener);

	void removePropertyChangeListener(PropertyChangeListener listener);

	String getActiveFastScanAxis();

	String getActiveSlowScanAxis();

}

Add interface for mapping stage configuration


package com.basho.riak.client.core.query.UserMetadata;

import com.basho.riak.client.core.util.BinaryValue;
import org.junit.Test;

import java.nio.charset.Charset;

import static junit.framework.TestCase.assertEquals;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;

public class RiakUserMetadataTest
{
    final Charset utf16 = Charset.forName("UTF-16");
    final String oddKey = "\uD834\uDD1E\uD835\uDD65";
    final String oddValue = "\uD835\uDFF6\uD840\uDC8A";
    final BinaryValue oddKeyBV = BinaryValue.create(oddKey, utf16);
    final BinaryValue oddValueBV = BinaryValue.create(oddValue, utf16);

    @Test
    public void getSetMetadata_string_altCharset()
    {
        RiakUserMetadata md = new RiakUserMetadata();
        md.put(oddKey, oddValue, utf16);
        final String gotValue = md.get(oddKey, utf16);

        assertEquals(oddValue, gotValue);
        assertNotEquals(gotValue, md.get(oddKey));
    }

    @Test
    public void getSetMetadata_binaryValue_altCharset()
    {
        RiakUserMetadata md = new RiakUserMetadata();
        md.put(oddKeyBV, oddValueBV);
        final BinaryValue gotValue = md.get(oddKeyBV);

        assertEquals(oddValueBV, gotValue);
        assertNotEquals(gotValue, md.get(oddKey));
    }

    @Test
    public void getSetMetadata_mixedInterfaces_altCharset()
    {
        RiakUserMetadata md = new RiakUserMetadata();
        md.put(oddKeyBV, oddValueBV);

        final String gotValue = md.get(oddKey, utf16);

        assertEquals(oddValue, gotValue);
    }
}

Add a few tests for charset options in RiakUserMetadata


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

package io.spine.server.trace.stackdriver;

import com.google.common.testing.NullPointerTester;
import io.spine.core.BoundedContextName;
import io.spine.core.MessageId;
import io.spine.system.server.EntityTypeName;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;

import static com.google.common.testing.NullPointerTester.Visibility.PROTECTED;

@DisplayName("SignalSpan should")
class SignalSpanTest {

    @Test
    @DisplayName("not accept nulls on construction")
    void nulls() {
        NullPointerTester tester = new NullPointerTester();
        tester.setDefault(BoundedContextName.class, BoundedContextName.getDefaultInstance())
              .setDefault(MessageId.class, MessageId.getDefaultInstance())
              .setDefault(EntityTypeName.class, EntityTypeName.getDefaultInstance());
        tester.testAllPublicInstanceMethods(SignalSpan.newBuilder());
        tester.testConstructors(SignalSpan.class, PROTECTED);
    }
}

Add a null tolerance test

Add a null tolerance test


package com.itmill.toolkit.tests;

import com.itmill.toolkit.ui.*;
import com.itmill.toolkit.ui.Button.ClickEvent;
import com.itmill.toolkit.ui.Button.ClickListener;

public class TestSetVisibleAndCaching extends com.itmill.toolkit.Application {

	Panel panelA = new Panel("Panel A");
	Panel panelB = new Panel("Panel B");
	Panel panelC = new Panel("Panel C");

	Button buttonNextPanel = new Button("Show next panel");

	int selectedPanel = 0;

	public void init() {
		Window mainWindow = new Window("TestSetVisibleAndCaching");
		setMainWindow(mainWindow);

		panelA.addComponent(new Label(
				"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"));
		panelB.addComponent(new Label(
				"BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB"));
		panelC.addComponent(new Label(
				"CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC"));

		mainWindow.addComponent(new Label(
				"Inspect transfered data from server to "
						+ "client and see how widgets are re-used,"
						+ " after each panel is once shown in GUI then"
						+ " their contents are not resend."));
		mainWindow.addComponent(buttonNextPanel);
		mainWindow.addComponent(panelA);
		mainWindow.addComponent(panelB);
		mainWindow.addComponent(panelC);

		selectPanel(selectedPanel);

		buttonNextPanel.addListener(new ClickListener() {
			public void buttonClick(ClickEvent event) {
				selectedPanel++;
				if (selectedPanel > 2)
					selectedPanel = 0;
				selectPanel(selectedPanel);
			}
		});

	}

	private void selectPanel(int selectedPanel) {
		System.err.println("Selecting panel " + selectedPanel);
		switch (selectedPanel) {
		case 0:
			panelA.setVisible(true);
			panelB.setVisible(false);
			panelC.setVisible(false);
			break;
		case 1:
			panelA.setVisible(false);
			panelB.setVisible(true);
			panelC.setVisible(false);
			break;
		case 2:
			panelA.setVisible(false);
			panelB.setVisible(false);
			panelC.setVisible(true);
			break;
		}
	}
}

Test that caching widgets works.
Inspect transfered data from server to
client and see how widgets are re-used
after each panel is once shown in GUI then"
their contents are not resend.

svn changeset:2579/svn branch:trunk