package org.sil.bloom.reader.models;

import org.junit.Test;

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

import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertThat;

public class BookTest {

    @Test
    public void alphabeticalComparator_sortsAlphabetically() {

        List<Book> books = Arrays.asList(
            new Book("/dummypath/c"),
            new Book("/dummypath/a"),
            new Book("/dummypath/B")
        );
        Collections.sort(books, Book.AlphabeticalComparator);
        assertThat(books.get(0).name, is("a"));
        assertThat(books.get(1).name, is("B"));
        assertThat(books.get(2).name, is("c"));
    }
}

Add our first simple unit test

Add our first simple unit test


/**
 * END USER LICENSE AGREEMENT (“EULA”)
 *
 * READ THIS AGREEMENT CAREFULLY (date: 9/13/2011):
 * http://www.akiban.com/licensing/20110913
 *
 * BY INSTALLING OR USING ALL OR ANY PORTION OF THE SOFTWARE, YOU ARE ACCEPTING
 * ALL OF THE TERMS AND CONDITIONS OF THIS AGREEMENT. YOU AGREE THAT THIS
 * AGREEMENT IS ENFORCEABLE LIKE ANY WRITTEN AGREEMENT SIGNED BY YOU.
 *
 * IF YOU HAVE PAID A LICENSE FEE FOR USE OF THE SOFTWARE AND DO NOT AGREE TO
 * THESE TERMS, YOU MAY RETURN THE SOFTWARE FOR A FULL REFUND PROVIDED YOU (A) DO
 * NOT USE THE SOFTWARE AND (B) RETURN THE SOFTWARE WITHIN THIRTY (30) DAYS OF
 * YOUR INITIAL PURCHASE.
 *
 * IF YOU WISH TO USE THE SOFTWARE AS AN EMPLOYEE, CONTRACTOR, OR AGENT OF A
 * CORPORATION, PARTNERSHIP OR SIMILAR ENTITY, THEN YOU MUST BE AUTHORIZED TO SIGN
 * FOR AND BIND THE ENTITY IN ORDER TO ACCEPT THE TERMS OF THIS AGREEMENT. THE
 * LICENSES GRANTED UNDER THIS AGREEMENT ARE EXPRESSLY CONDITIONED UPON ACCEPTANCE
 * BY SUCH AUTHORIZED PERSONNEL.
 *
 * IF YOU HAVE ENTERED INTO A SEPARATE WRITTEN LICENSE AGREEMENT WITH AKIBAN FOR
 * USE OF THE SOFTWARE, THE TERMS AND CONDITIONS OF SUCH OTHER AGREEMENT SHALL
 * PREVAIL OVER ANY CONFLICTING TERMS OR CONDITIONS IN THIS AGREEMENT.
 */

package com.akiban.sql.optimizer.plan;

import java.util.List;

public class GroupLoopScan extends BaseScan
{
    private TableSource insideTable, outsideTable;
    private List<ConditionExpression> joinConditions;

    public GroupLoopScan(TableSource insideTable, TableSource outsideTable,
                         List<ConditionExpression> joinConditions) {
        this.insideTable = insideTable;
        this.outsideTable = outsideTable;
        this.joinConditions = joinConditions;
    }

    public TableSource getInsideTable() {
        return insideTable;
    }
    public TableSource getOutsideTable() {
        return outsideTable;
    }

    public List<ConditionExpression> getJoinConditions() {
        return joinConditions;
    }

    @Override
    public boolean accept(PlanVisitor v) {
        if (v.visitEnter(this)) {
            // Don't own tables, right?
        }
        return v.visitLeave(this);
    }

    @Override
    public String summaryString() {
        StringBuilder str = new StringBuilder(super.summaryString());
        str.append('(');
        str.append(outsideTable.summaryString());
        str.append(" - ");
        str.append(insideTable.summaryString());
        if (getCostEstimate() != null) {
            str.append(", ");
            str.append(getCostEstimate());
        }
        str.append(")");
        return str.toString();
    }

}

Add a new scan that represents the outer loop coming into the inner for group operations.


/**
 * The {@code distancemetrics} package contains strategy classes to parametrize
 * the way self-organizing maps measure the distance from a neuron to an input
 * vector.  The classes are intended to be created by the user and given to a
 * self-organizing map, which will assume control.  These classes all derive
 * from {@link cs437.som.DistanceMetric} in {@link cs437.som}.
 */
package cs437.som.distancemetrics;

Add a package annotation to distancemetrics.


/*
 * Copyright (C) 2013 Klaus Reimer <k@ailis.de>
 * See LICENSE.md for licensing information.
 */

package de.ailis.usb4java.libusb;

import static de.ailis.usb4java.test.UsbAssume.assumeUsbTestsEnabled;

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

/**
 * Tests the {@link SSEndpointCompanionDescriptor} class.
 *
 * @author Klaus Reimer (k@ailis.de)
 */
public class SSEndpointCompanionDescriptorTest
{
    /** The test subject. */
    private SSEndpointCompanionDescriptor descriptor;

    /**
     * Setup test.
     */
    @Before
    public void setUp()
    {
        assumeUsbTestsEnabled();
        LibUsb.init(null);
        this.descriptor = new SSEndpointCompanionDescriptor();
    }

    /**
     * Tear down test.
     */
    @After
    public void tearDown()
    {
        LibUsb.exit(null);
    }

    /**
     * Tests uninitialized access to
     * {@link SSEndpointCompanionDescriptor#bLength()}
     */
    @Test(expected = IllegalStateException.class)
    public void testUninitializedLength()
    {
        assumeUsbTestsEnabled();
        this.descriptor.bLength();
    }

    /**
     * Tests uninitialized access to
     * {@link SSEndpointCompanionDescriptor#bDescriptorType()}
     */
    @Test(expected = IllegalStateException.class)
    public void testUninitializedDescriptorType()
    {
        assumeUsbTestsEnabled();
        this.descriptor.bDescriptorType();
    }

    /**
     * Tests uninitialized access to
     * {@link SSEndpointCompanionDescriptor#bMaxBurst()}
     */
    @Test(expected = IllegalStateException.class)
    public void testUninitializedDescriptorMaxBurst()
    {
        assumeUsbTestsEnabled();
        this.descriptor.bMaxBurst();
    }

    /**
     * Tests uninitialized access to
     * {@link SSEndpointCompanionDescriptor#bmAttributes()}
     */
    @Test(expected = IllegalStateException.class)
    public void testUninitializedDescriptorAttributes()
    {
        assumeUsbTestsEnabled();
        this.descriptor.bmAttributes();
    }

    /**
     * Tests uninitialized access to
     * {@link SSEndpointCompanionDescriptor#wBytesPerInterval()}
     */
    @Test(expected = IllegalStateException.class)
    public void testUninitializedDescriptorBytesPerInterval()
    {
        assumeUsbTestsEnabled();
        this.descriptor.wBytesPerInterval();
    }
}

Add unit test for SuperSpeed Endpoint Companion Descriptor


package imagej.core.plugins.debug;

import java.util.Arrays;

import net.imglib2.meta.Axes;
import net.imglib2.meta.AxisType;
import imagej.ImageJ;
import imagej.data.ChannelCollection;
import imagej.data.Dataset;
import imagej.data.DatasetService;
import imagej.data.DrawingTool;
import imagej.data.DrawingTool.TextJustification;
import imagej.ext.module.ItemIO;
import imagej.ext.plugin.ImageJPlugin;
import imagej.ext.plugin.Parameter;
import imagej.ext.plugin.Plugin;

@Plugin(menuPath = "Plugins>Sandbox>Multidimensional Test Image")
public class MultidimImage implements ImageJPlugin {

	@Parameter
	ImageJ context;

	@Parameter
	DatasetService service;

	@Parameter(type=ItemIO.OUTPUT)
	Dataset ds;

	@Override
	public void run() {
		long[] dims = new long[]{80,30,4,5,6,7};
		String name = "Multidimensional Example";
		AxisType[] axes = new AxisType[]{Axes.X, Axes.Y, Axes.CHANNEL, Axes.FREQUENCY, Axes.Z, Axes.TIME};
		int bitsPerPixel = 8;
		boolean signed = false;
		boolean floating = false;
		ds = service.create(dims, name, axes, bitsPerPixel, signed, floating);
		long[] pos = new long[dims.length];
		DrawingTool tool = new DrawingTool(ds);
		ChannelCollection channels = new ChannelCollection(Arrays.asList(new Double[]{255.0,255.0,255.0,255.0}));
		tool.setChannels(channels);
		for (int c = 0; c < dims[2]; c++) {
			for (int f = 0; f < dims[3]; f++) {
				for (int z = 0; z < dims[4]; z++) {
					for (int t = 0; t < dims[5]; t++) {
						pos[2] = c;
						pos[3] = f;
						pos[4] = z;
						pos[5] = t;
						tool.setPosition(pos);
						tool.setPreferredChannel(c);
						String label = "c " + c + " f " + f + " z " + z + " t " + t;
						tool.drawText(0, 0, label, TextJustification.LEFT);
					}
				}
			}
		}
	}

}

Make a multidim test image plugin

Make a multidim test image plugin


package com.ibm.watson.developer_cloud.http;

import java.net.Proxy;

/**
 * Options class for configuring the HTTP client.
 */
public class HttpConfigOptions {
  private boolean disableSslVerification;
  private Proxy proxy;

  boolean shouldDisableSslVerification() {
    return this.disableSslVerification;
  }

  Proxy getProxy() {
    return this.proxy;
  }

  public static class Builder {
    private boolean disableSslVerification;
    private Proxy proxy;

    public HttpConfigOptions build() {
      return new HttpConfigOptions(this);
    }

    /**
     * Sets flag to disable any SSL certificate verification during HTTP requests. This should ONLY be used if truly
     * intended, as it's unsafe otherwise.
     *
     * @param disableSslVerification whether to disable SSL verification or not
     * @return the builder
     */
    public Builder disableSslVerification(boolean disableSslVerification) {
      this.disableSslVerification = disableSslVerification;
      return this;
    }

    /**
     * Sets HTTP proxy to be used by connections with the current client.
     *
     * @param proxy the desired {@link Proxy}
     * @return the builder
     */
    public Builder proxy(Proxy proxy) {
      this.proxy = proxy;
      return this;
    }
  }

  private HttpConfigOptions(Builder builder) {
    this.disableSslVerification = builder.disableSslVerification;
    this.proxy = builder.proxy;
  }
}

feat(core): Add model for specifying client config options


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

package edu.harvard.iq.dataverse;

import java.util.List;
import javax.ejb.Stateless;
import javax.ejb.TransactionAttribute;
import javax.ejb.TransactionAttributeType;
import javax.inject.Named;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

/**
 *
 * @author skraffmiller
 */
@Stateless
@Named
public class DatasetServiceBean {

    @PersistenceContext(unitName = "VDCNet-ejbPU")
    private EntityManager em;

    @TransactionAttribute(TransactionAttributeType.REQUIRED)
    public Dataset save(Dataset dataset) {
         return em.merge(dataset);
    }

    public Dataset find(Object pk) {
        return (Dataset) em.find(Dataset.class, pk);
    }

    public List<Dataset> findByOwnerId(Long ownerId) {
         Query query = em.createQuery("select object(o) from Dataset as o where o.owner.id =:ownerId order by o.name");
         query.setParameter("ownerId", ownerId);
         return query.getResultList();
    }

}

Add simple dataset service bean

Add simple dataset service bean

save, find (by id) and find by owner


package npe;

public class IdentifyCorrectBranchPlease {

	int f(boolean b) {
		Object x = null;
		if (b) {
			x = new Object();
		} else {
			b = true;
		}
		return x.hashCode();
	}
	int f(boolean b1, boolean b2) {
		Object x = null;
		if (b1) {
			x = new Object();
		} else {
			b1 = true;
		}
		if (b2)
			System.out.println("b2 is true");
		return x.hashCode();
	}

}

Test cases for whether we can correctly identify the path leading to the NPE

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


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

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

public class ArraysTest {
    @Test
    public void testMerge0() {
        try {
            Integer[] result = Arrays.merge();
            Assert.fail("should throw IllegalArgumentException");
        } catch (IllegalArgumentException e) {
            Assert.assertTrue(e.getMessage().contains("arrays should not be empty"));
        }
    }

    @Test
    public void testMerge1() {
        Integer[] a = new Integer[] {1, 2};
        Integer[] result = Arrays.merge(a);
        Assert.assertArrayEquals(new Integer[] {1, 2}, result);
    }

    @Test
    public void testMerge2() {
        Integer[] a = new Integer[] {1, 2};
        Integer[] b = new Integer[] {3, 4};
        Integer[] result = Arrays.merge(a, b);
        Assert.assertArrayEquals(new Integer[] {1, 2, 3, 4}, result);
    }

    @Test
    public void testMerge3() {
        Integer[] a = new Integer[] {1, 2};
        Integer[] b = new Integer[] {3, 4};
        Integer[] c = new Integer[] {5, 6, 7, 8, 9};
        Integer[] result = Arrays.merge(a, b, c);
        Assert.assertArrayEquals(new Integer[] {1, 2, 3, 4, 5, 6, 7, 8, 9}, result);
    }
}

Add a test for `Arrays`

Add a test for `Arrays`


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

/**
 * Given an array full of integers, can you write a method returning other array without duplicated
 * elements? The elements order doesn't care. For example:
 *
 * Input: [1,2,3,1] Output: [1,1,12]
 * Input: [1,1,1,1,1] Output: [1]
 *
 * @author Pedro Vicente Gómez Sánchez.
 */
public class RemoveDuplicates {
}

Add statement for problem 10

Add statement for problem 10


package com.vladmihalcea.book.hpjp.hibernate.query;

import com.vladmihalcea.book.hpjp.util.AbstractTest;
import com.vladmihalcea.book.hpjp.util.providers.Database;
import org.junit.Test;

import javax.persistence.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Properties;
import java.util.stream.Collectors;

import static org.junit.Assert.assertEquals;

/**
 * @author Vlad Mihalcea
 */
public class InQueryTest extends AbstractTest {

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

    @Override
    protected void additionalProperties(Properties properties) {
        properties.put("hibernate.jdbc.batch_size", "50");
        properties.put("hibernate.order_inserts", "true");
        properties.put("hibernate.query.in_clause_parameter_padding", "true");
    }

    @Test
    public void testPadding() {
        doInJPA(entityManager -> {
            for (int i = 1; i <= 15; i++) {
                Post post = new Post();
                post.setId(i);
                post.setTitle(String.format("Post no. %d", i));

                entityManager.persist(post);
            }
        });

        doInJPA(entityManager -> {
            assertEquals(3, getPostByIds(entityManager, 1, 2, 3).size());
            assertEquals(4, getPostByIds(entityManager, 1, 2, 3, 4).size());
            assertEquals(5, getPostByIds(entityManager, 1, 2, 3, 4, 5).size());
            assertEquals(6, getPostByIds(entityManager, 1, 2, 3, 4, 5, 6).size());
        });
    }

    List<Post> getPostByIds(EntityManager entityManager, Integer... ids) {
        return entityManager.createQuery(
            "select p " +
            "from Post p " +
            "where p.id in :ids", Post.class)
        .setParameter("ids", Arrays.asList(ids))
        .getResultList();
    }

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

        @Id
        private Integer id;

        private String title;

        public Post() {}

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

        public Integer getId() {
            return id;
        }

        public void setId(Integer id) {
            this.id = id;
        }

        public String getTitle() {
            return title;
        }

        public void setTitle(String title) {
            this.title = title;
        }
    }
}

Add in clause parameter padding

Add in clause parameter padding


import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.apphosting.api.DatastorePb;
import com.google.sps.data.Marker;
import org.junit.Before;
import org.junit.Test;
import  org.junit.jupiter.api.Assertions;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import com.google.appengine.api.datastore.Entity;
import static org.mockito.Mockito;

import java.util.Optional;

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

@RunWith(JUnit4.class)
public final class MarkerTest {
    private Marker marker;

    @Before
    public void setUp() {
        marker = new Marker.Builder()
                .setId(1111)
                .setLat(1)
                .setLng(1)
                .setAnimal("animal")
                .setReporter("reporter")
                .setDescription("description")
                .setUserId(Optional.of("userId"))
                .setBlobKey("blobKey")
                .build();
    }

    @Test
    public void createMarker() {
        assertTrue(marker != null);
    }

    @Test
    public void initializeMarker() {
        assertEquals(1111, marker.getId());
        assertEquals(1, marker.getLat());
        assertEquals(1, marker.getLng());
        assertEquals("animal", marker.getAnimal());
        assertEquals("reporter", marker.getReporter());
        assertEquals("description", marker.getDescription());
        assertEquals(Optional.of("userId"), marker.getUserId());
        assertEquals("blobKey", marker.getBlobKey());
    }

    @Test
    public void entityToMarker() {
        Entity entit = mock(Entity)
        Entity markerEntity = new Entity("Marker",1111);
        markerEntity.setProperty("lat", 1);
        markerEntity.setProperty("lng", 1);
        markerEntity.setProperty("animal", "animal");
        markerEntity.setProperty("reporter", "reporter");
        markerEntity.setProperty("description", "description");
        markerEntity.setProperty("blobKey", "blobKey");
        markerEntity.setProperty("userId", "userId");

    }
}

Test creation and initialization of a Marker instance


package leetcode.partition_list;

import common.ListNode;

public class Solution {
	public ListNode partition(ListNode head, int x) {
		if(head == null) return head;
		ListNode prewall = null;
		ListNode wall = head;
		while(wall != null && wall.val < x){
			prewall = wall;
			wall = wall.next;
		}
		if(wall == null) return head;
		ListNode cur = wall.next;
		ListNode prev = wall;
		while(cur != null){
			ListNode nxt = cur.next;
			if(cur.val < x){
				prev.next = nxt;
				cur.next = wall;
				if(prewall == null){
					prewall = cur;
					head = cur;
				}else{
					prewall.next = cur;
					prewall = cur;
				}
			}else{
				prev = cur;
			}
			cur = nxt;
		}
		return head;
	}

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

	public static void main(String[] args){
		final int N = 6;
		int[] vals = new int[]{1, 1, 1, 2, 1, 2};
		ListNode[] ary = new ListNode[N];
		for(int i = 0; i < N; i++){
			ary[i] = new ListNode(vals[i]);
			if(i > 0) ary[i - 1].next = ary[i];
		}
		dump(new Solution().partition(ary[0], 3));
	}
}

Add java solution for 86. Partition List

86. Partition List: https://leetcode.com/problems/partition-list/


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

import java.util.Optional;
import org.junit.Test;

/**
 * A unit test class for {@link JavaProcessManagerFactory}.
 *
 * @author Viktor Csomor
 */
public class JavaProcessManagerFactoryTest extends TestCase {

  @Test
  public void testThrowsIllegalArgumentExceptionIfConfigNull() {
    exceptionRule.expect(IllegalArgumentException.class);
    new JavaProcessManagerFactory<>(null);
  }

  @Test
  public void testThrowsIllegalArgumentExceptionIfJavaLauncherCommandNull() {
    exceptionRule.expect(IllegalArgumentException.class);
    new JavaProcessManagerFactory<>(new SimpleJavaProcessConfig(null));
  }

  @Test
  public void testThrowsIllegalArgumentExceptionIfJavaLauncherCommandEmpty() {
    exceptionRule.expect(IllegalArgumentException.class);
    new JavaProcessManagerFactory<>(new SimpleJavaProcessConfig(""));
  }

  @Test
  public void testThrowsIllegalArgumentExceptionIfInitHeapSizeZero() {
    exceptionRule.expect(IllegalArgumentException.class);
    new JavaProcessManagerFactory<>(new SimpleJavaProcessConfig(0, 1, 1));
  }

  @Test
  public void testThrowsIllegalArgumentExceptionIfInitHeapSizeLessThanZero() {
    exceptionRule.expect(IllegalArgumentException.class);
    new JavaProcessManagerFactory<>(new SimpleJavaProcessConfig(-1, 1, 1));
  }

  @Test
  public void testThrowsIllegalArgumentExceptionIfMaxHeapSizeZero() {
    exceptionRule.expect(IllegalArgumentException.class);
    new JavaProcessManagerFactory<>(new SimpleJavaProcessConfig(1, 0, 1));
  }

  @Test
  public void testThrowsIllegalArgumentExceptionIfMaxHeapSizeLessThanZero() {
    exceptionRule.expect(IllegalArgumentException.class);
    new JavaProcessManagerFactory<>(new SimpleJavaProcessConfig(1, -1, 1));
  }

  @Test
  public void testThrowsIllegalArgumentExceptionIfStackSizeZero() {
    exceptionRule.expect(IllegalArgumentException.class);
    new JavaProcessManagerFactory<>(new SimpleJavaProcessConfig(1, 1, 0));
  }

  @Test
  public void testThrowsIllegalArgumentExceptionIfStackSizeLessThanZero() {
    exceptionRule.expect(IllegalArgumentException.class);
    new JavaProcessManagerFactory<>(new SimpleJavaProcessConfig(1, 1, -1));
  }

  @Test
  public void testThrowsIllegalArgumentExceptionIfClassPathEmpty() {
    exceptionRule.expect(IllegalArgumentException.class);
    new JavaProcessManagerFactory<>(new SimpleJavaProcessConfig() {

      @Override
      public Optional<String> getClassPath() {
        return Optional.of("");
      }
    });
  }

}

Add unit tests for JavaProcessManagerFactory


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

/**
 * Implement an algorithm to delete a node in the middle of a singly linked list, given only access
 * to that node.
 *
 * @author Pedro Vicente Gómez Sánchez.
 */
public class DeleteListNode {

}

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

import com.github.pedrovgs.linkedlist.ListNode;

/**
 * Implement an algorithm to delete a node in the middle of a singly linked list, given only access
 * to that node.
 *
 * @author Pedro Vicente Gómez Sánchez.
 */
public class DeleteListNode {

  /**
   * Iterative algorithm to solve this problem. We don't have access to the head of the list, and
   * the only thing we can do is to move the data from the next node to the current one, the data
   * and the pointer to the next node. This approach doesn't work with the last element in the
   * list, but there is no another valid approach to solve this algorithm without access to the
   * head of the list.
   */
  public void delete(ListNode node) {
    validateInputData(node);

    if (node.getNext() == null) {
      return;
    }
    ListNode next = node.getNext();
    node.setData(next.getData());
    node.setNext(next.getNext());
  }

  private void validateInputData(ListNode node) {
    if (node == null) {
      throw new IllegalArgumentException(
          "You can't pass a null instance of ListNode as parameter.");
    }
  }
}

Add solution to problem 59

Add solution to problem 59


// Copyright (c) 2006  Dustin Sallings <dustin@spy.net>

package net.spy.memcached.transcoders;

import java.io.ObjectStreamClass;

import net.spy.SpyObject;
import net.spy.util.CloseUtil;

import net.spy.memcached.CachedData;

/**
 * Transcoder that serializes and unserializes longs.
 */
public final class LongTranscoder extends SpyObject
    implements Transcoder<Long> {

    private static final int flags = TranscoderUtils.hashForFlags(ObjectStreamClass.lookup(Long.class).getSerialVersionUID());

    public CachedData encode(java.lang.Long l) {
        return new CachedData(flags, TranscoderUtils.encodeLong(l));
    }

    public Long decode(CachedData d) {
        if (flags == d.getFlags()) {
            return TranscoderUtils.decodeLong(d.getData());
        } else {
            return null;
        }
    }

}

Add a new transcoder for Long's.

Add a new transcoder for Long's.


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

package org.apache.james.transport.mailets;

import java.io.UnsupportedEncodingException;
import java.util.Arrays;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.ParseException;

import junit.framework.TestCase;

import org.apache.james.test.mock.mailet.MockMail;
import org.apache.mailet.Mail;
import org.apache.mailet.MailAddress;
import org.apache.mailet.Mailet;

public class NullTest extends TestCase {

    private MimeMessage mockedMimeMessage;

    private Mail mockedMail;

    private Mailet mailet;

    private final String PROCESSOR = "ghost";

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

    private void setupMockedMail(MimeMessage m) throws ParseException {
        mockedMail = new MockMail();
        mockedMail.setMessage(m);
        mockedMail.setRecipients(Arrays.asList(new MailAddress[] {
                new MailAddress("test@james.apache.org"),
                new MailAddress("test2@james.apache.org") }));

    }

    private void setupMailet() throws MessagingException {
        mailet = new Null();
    }

    // test if ToProcessor works
    public void testValidToProcessor() throws MessagingException {
        setupMockedMail(mockedMimeMessage);
        setupMailet();

        mailet.service(mockedMail);

        assertEquals(PROCESSOR, mockedMail.getState());
    }

}

Add junit test for Null Mailet

Add junit test for Null Mailet

git-svn-id: 88158f914d5603334254b4adf21dfd50ec107162@420596 13f79535-47bb-0310-9956-ffa450edef68


/*                                                                      *\
**                    SICU Stress Measurement System                    **
**                      Project P04  |  C380 Team A                     **
**          EBME 380: Biomedical Engineering Design Experience          **
**                    Case Western Reserve University                   **
**                          2016 Fall Semester                          **
\*                                                                      */

package edu.cwru.sicu_sms.util;

import org.junit.jupiter.api.*;

import java.util.Arrays;

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

/**
 * Test class for {@link EKGSerialPort}.
 *
 * @since December 14, 2016
 * @author Ted Frohlich <ttf10@case.edu>
 * @author Abby Walker <amw138@case.edu>
 */
class EKGSerialPortTest {

    private static long READ_DURATION = (long) 3e9;  // 3 seconds, expressed in nanoseconds

    private EKGSerialPort serialPort;

    @BeforeEach
    void openPort() {
        serialPort = new EKGSerialPort();
        serialPort.openPort();
    }

    @Test
    void readData() {
        byte[] data;

        long startTime = System.nanoTime();
        do {
            data = serialPort.readData();

            if (data != null && data.length > 0) {
                System.out.println(Arrays.toString(data));
            }
        } while (System.nanoTime() - startTime < READ_DURATION);
    }

    @AfterEach
    void closePort() {
        serialPort.closePort();
    }

}

Create test class for 'EKGSerialPort'

Create test class for 'EKGSerialPort'


package seedu.todo.guitests;

import static org.junit.Assert.*;
import static seedu.todo.testutil.AssertUtil.assertSameDate;

import java.time.LocalDate;
import java.time.LocalDateTime;

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

import seedu.todo.commons.util.DateUtil;
import seedu.todo.guitests.guihandles.TaskListDateItemHandle;
import seedu.todo.guitests.guihandles.TaskListEventItemHandle;
import seedu.todo.guitests.guihandles.TaskListTaskItemHandle;
import seedu.todo.models.Task;
import seedu.todo.models.TodoListDB;

/**
 * @@author A0093907W
 */
public class UndoRedoCommandTest extends GuiTest {

    private final LocalDateTime oneDayFromNow = LocalDateTime.now().plusDays(1);
    private final String oneDayFromNowString = DateUtil.formatDate(oneDayFromNow);
    private final String oneDayFromNowIsoString = DateUtil.formatIsoDate(oneDayFromNow);
    private final LocalDateTime twoDaysFromNow = LocalDateTime.now().plusDays(2);
    private final String twoDaysFromNowString = DateUtil.formatDate(twoDaysFromNow);
    private final String twoDaysFromNowIsoString = DateUtil.formatIsoDate(twoDaysFromNow);

    String commandAdd1 = String.format("add task Buy KOI by \"%s 8pm\"", oneDayFromNowString);
    Task task1 = new Task();
    String commandAdd2 = String.format("add task Buy Milk by \"%s 9pm\"", twoDaysFromNowString);
    Task task2 = new Task();

    public UndoRedoCommandTest() {
        task1.setName("Buy KOI");
        task1.setCalendarDateTime(DateUtil.parseDateTime(String.format("%s 20:00:00", oneDayFromNowIsoString)));
        task2.setName("Buy Milk");
        task2.setDueDate(DateUtil.parseDateTime(String.format("%s 21:00:00", twoDaysFromNowIsoString)));
    }

    @Before
    public void resetDB() {
        TodoListDB db = TodoListDB.getInstance();
        db.destroyAllEvent();
        db.destroyAllTask();
    }
}

Set up for undo/redo tests

Set up for undo/redo tests


package org.pinae.timon.cache.decorator.memcached;

import org.apache.log4j.Logger;
import org.junit.Before;
import org.junit.Test;
import org.pinae.timon.cache.Cache;
import org.pinae.timon.cache.CacheException;
import org.pinae.timon.cache.CacheFactory;
import org.pinae.timon.cache.KVCacheTestCase;

/**
 * 基于memcached缓存测试
 *
 * @author Huiyugeng
 *
 */
public class MemcachedCacheTest extends KVCacheTestCase {
	protected final Logger log = Logger.getLogger(MemcachedCacheTest.class);

	private CacheFactory cacheFactory = CacheFactory.getInstance();

	private Cache cache;

	private String memcachedServer = "localhost:11211";

	@Before
	public void before() throws CacheException {
		MemcachedCacheConfiguration config = new MemcachedCacheConfiguration();

		config.setServer(memcachedServer);

		config.setExpire(0);
		config.setMaxHeapSize(10);

		this.cache = cacheFactory.createCache("testCache", config);
	}

	@Test
	public void testCache() throws CacheException {
		super.testBasicCache(cache, false);
		cache.close();
	}

}

Add MemcachedCache unit test case

Add MemcachedCache unit test case


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

/**
 * Given a matrix of integers, can you write a method to go through this matrix using an spiral
 * movement?
 *
 * @author Pedro Vicente Gómez Sánchez.
 */
public class GoThroughMatrixInSpiral {
}

Add statement to problem 41

Add statement to problem 41


package openmods.utils;

import javax.annotation.Nullable;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.EnumFacing;
import net.minecraftforge.fluids.capability.CapabilityFluidHandler;
import net.minecraftforge.fluids.capability.IFluidHandler;
import net.minecraftforge.fluids.capability.wrappers.FluidHandlerWrapper;

@SuppressWarnings("deprecation")
public class CompatibilityUtils {

	@Nullable
	public static IFluidHandler getFluidHandler(TileEntity te) {
		final IFluidHandler nativeCapability = te.getCapability(CapabilityFluidHandler.FLUID_HANDLER_CAPABILITY, EnumFacing.UP);
		if (nativeCapability != null) return nativeCapability;

		if (te instanceof net.minecraftforge.fluids.IFluidHandler) return new FluidHandlerWrapper((net.minecraftforge.fluids.IFluidHandler)te, EnumFacing.UP);

		return null;
	}

}

Add utility for handling legacy tanks

Add utility for handling legacy tanks


package org.realityforge.jeo.geolatte.jpa.eclipselink;

import java.util.Properties;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;

public class DatabaseTestUtil
{
  static Properties initDatabaseProperties()
  {
    final Properties properties = new Properties();
    properties.put( "javax.persistence.jdbc.driver", "org.postgis.DriverWrapperAutoprobe" );
    final String databaseUrl = "jdbc:postgresql_autogis://127.0.0.1:5432/geolatte_test";
    setProperty( properties, "javax.persistence.jdbc.url", "test.db.url", databaseUrl );
    setProperty( properties, "javax.persistence.jdbc.user", "test.db.user", "geolatte" );
    setProperty( properties, "javax.persistence.jdbc.password", "test.db.password", null );
    properties.put( "eclipselink.session-event-listener", GeolatteExtension.class.getName() );
    return properties;
  }

  private static void setProperty( final Properties properties,
                                   final String key,
                                   final String systemPropertyKey, final String defaultValue )
  {
    final String value = System.getProperty( systemPropertyKey, defaultValue );
    if ( null != value )
    {
      properties.put( key, value );
    }
  }

  public static EntityManager createEntityManager( final String persistenceUnitName )
  {
    final Properties properties = initDatabaseProperties();
    final EntityManagerFactory factory = Persistence.createEntityManagerFactory( persistenceUnitName, properties );
    return factory.createEntityManager();
  }
}

Add utility for testing database

Add utility for testing database


package com.m4gik;

/**
 *
 * This class contains static fields, attributes for {@link Haval} class.
 *
 * @author Michał Szczygieł <michal.szczygiel@wp.pl>
 *
 */
public class HavalAttributes {

    /**
     * The value for produce hashes in lengths of 128 bits.
     */
    public static final int HAVAL_128_BIT = 16;

    /**
     * The value for produce hashes in lengths of 160 bits.
     */
    public static final int HAVAL_160_BIT = 20;

    /**
     * The value for produce hashes in lengths of 192 bits.
     */
    public static final int HAVAL_192_BIT = 24;

    /**
     * The value for produce hashes in lengths of 224 bits.
     */
    public static final int HAVAL_224_BIT = 28;

    /**
     * The value for produce hashes in lengths of 256 bits.
     */
    public static final int HAVAL_256_BIT = 32;

    /**
     * The value specify the number of 3 rounds which are used to generate the
     * hash.
     */
    public static final int HAVAL_3_ROUND = 3;

    /**
     * The value specify the number of 4 rounds which are used to generate the
     * hash.
     */
    public static final int HAVAL_4_ROUND = 4;

    /**
     * The value specify the number of 5 rounds which are used to generate the
     * hash.
     */
    public static final int HAVAL_5_ROUND = 5;

    /**
     * The value specify the version of algorithm.
     */
    public static final int HAVAL_VERSION = 1;

}

Create class with attributes for haval algorithm,


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

package com.googlesource.gerrit.plugins.xdocs.formatter;

import static org.easymock.EasyMock.*;
import static org.junit.Assert.assertEquals;

import com.googlesource.gerrit.plugins.xdocs.ConfigSection;

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

import org.apache.commons.lang.StringUtils;
import org.easymock.IAnswer;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;

public class AsciidoctorFormatterTest {

  private ConfigSection cfg;
  private AsciidoctorFormatter formatter;

  @Rule
  public TemporaryFolder tmp = new TemporaryFolder();

  @Before
  public void setUp() throws IOException {
    FormatterUtil util = createNiceMock(FormatterUtil.class);

    // To simplify things, make applyCss() a no-op and return the HTML code as-is.
    expect(util.applyCss(anyString(), anyString(), anyString())).andAnswer(
      new IAnswer<String>() {
        @Override
        public String answer() throws Throwable {
          // The first argument is the HTML code.
          return (String) getCurrentArguments()[0];
        }
      }
    );

    replay(util);

    cfg = createNiceMock(ConfigSection.class);

    // Do not expect any behavior from the ConfigSection itself.
    replay(cfg);

    Formatters formatters = createNiceMock(Formatters.class);

    // Avoid a NPE by just returning the ConfigSection mock object.
    expect(formatters.getFormatterConfig(anyString(), anyString())).andReturn(cfg);

    replay(formatters);

    formatter = new AsciidoctorFormatter(tmp.newFolder(), util, formatters);
  }

  @Test
  public void basicTextFormattingWorks() throws IOException {
    String raw = "_italic_ *bold* `monospace`";
    String formatted = "italic bold monospace";
    assertEquals(StringUtils.countMatches(formatter.format(null, null, null, null, cfg, raw), formatted), 1);
  }
}

Add a unit test for the AsciidoctorFormatter

Change-Id: Iceff1d61512b9489e3a0a2bee9e3c5b208635853


package mjc.types;

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

import org.junit.Test;

public class ClassTypeTest {

    final ClassType classA1 = new ClassType("ClassA");
    final ClassType classA2 = new ClassType("ClassA");
    final ClassType classB = new ClassType("ClassB");

    @Test
    public void testIsClass() {
        assertThat(classA1.isClass(), is(true));
    }

    @Test
    public void testIsAssignableTo() {
        assertThat(classA1.isAssignableTo(BuiltInType.Boolean), is(false));
        assertThat(classA1.isAssignableTo(BuiltInType.Int), is(false));
        assertThat(classA1.isAssignableTo(BuiltInType.IntArray), is(false));
        assertThat(classA1.isAssignableTo(BuiltInType.Long), is(false));
        assertThat(classA1.isAssignableTo(BuiltInType.LongArray), is(false));
        assertThat(classA1.isAssignableTo(UndefinedType.Instance), is(true));
        assertThat(classA1.isAssignableTo(UnsupportedType.Void), is(false));
        assertThat(classA1.isAssignableTo(UnsupportedType.StringArray), is(false));
        assertThat(classA1.isAssignableTo(classA2), is(true)); // Same class
        assertThat(classA1.isAssignableTo(classB), is(false)); // Different class
    }

    @Test
    public void testIsEqualComparableTo() {
        assertThat(classA1.isEqualComparableTo(BuiltInType.Boolean), is(false));
        assertThat(classA1.isEqualComparableTo(BuiltInType.Int), is(false));
        assertThat(classA1.isEqualComparableTo(BuiltInType.IntArray), is(false));
        assertThat(classA1.isEqualComparableTo(BuiltInType.Long), is(false));
        assertThat(classA1.isEqualComparableTo(BuiltInType.LongArray), is(false));
        assertThat(classA1.isEqualComparableTo(UndefinedType.Instance), is(true));
        assertThat(classA1.isEqualComparableTo(UnsupportedType.Void), is(false));
        assertThat(classA1.isEqualComparableTo(UnsupportedType.StringArray), is(false));
        assertThat(classA1.isEqualComparableTo(classA2), is(true)); // Same class
        assertThat(classA1.isEqualComparableTo(classB), is(false)); // Different class
    }

}

Add unit test for ClassType.

Add unit test for ClassType.


package com.ezardlabs.dethsquare.multiplayer;

import java.nio.ByteBuffer;

public class NetworkTransform extends NetworkBehaviour {

	@Override
	protected ByteBuffer onSend() {
		data.putFloat(0, transform.position.x); // 0 - 3
		data.putFloat(4, transform.position.y); // 4 - 7
		return data;
	}

	@Override
	protected void onReceive(ByteBuffer data, int index) {
		transform.position.x = data.getFloat(index);
		transform.position.y = data.getFloat(index + 4);
	}

	@Override
	public int getSize() {
		return 8;
	}
}

Add component for automatically synchronising a Transform component between multiplayer clients


package org.commonwl.view.workflow;

import org.apache.jena.base.Sys;
import org.commonwl.view.git.GitDetails;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.data.mongo.DataMongoTest;
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
import org.springframework.test.context.junit4.SpringRunner;

import static org.junit.Assert.*;

@DataMongoTest
@RunWith(SpringRunner.class)
public class QueuedWorkflowRepositoryTest {

    @Autowired
    public QueuedWorkflowRepository repository;

    @Test
    public void deleteQueuedWorkflowByRetrievedFromTest() {

        assertNotNull(repository);

        // create stub queued workflow
        GitDetails gitDetails = new GitDetails("test_repo_url", "test_branch", "test_path");
        gitDetails.setPackedId("test_packedId");

        Workflow workflow = new Workflow();
        workflow.setRetrievedFrom(gitDetails);

        QueuedWorkflow queuedWorkflow = new QueuedWorkflow();
        queuedWorkflow.setTempRepresentation(workflow);

        // save queued workflow
        repository.save(queuedWorkflow);

        // retrieve saved queued workflow by workflow git details
        QueuedWorkflow retrievedQueuedWorkflowAfterSave = repository
                .findByRetrievedFrom(queuedWorkflow.getTempRepresentation().getRetrievedFrom());
        assertNotNull(retrievedQueuedWorkflowAfterSave);

        // delete saved queued workflow by workflow git details
        repository.deleteByTempRepresentation_RetrievedFrom(queuedWorkflow.getTempRepresentation().getRetrievedFrom());

        // retrieve deleted queued workflow by workflow git details
        QueuedWorkflow retrievedQueuedWorkflowAfterDelete = repository
                .findByRetrievedFrom(queuedWorkflow.getTempRepresentation().getRetrievedFrom());
        assertNull(retrievedQueuedWorkflowAfterDelete);

    }

}

Implement unit test for QueuedWorkflow delete by git details functionality


package io.github.yurloc.autostring;

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

import org.junit.Test;

public class FieldOrderingTest {

    /**
     * Reflection API does not define the order but it appears that order in which fields are declared is kept. Let's
     * have a test to confirm that.
     */
    @Test
    public void shouldKeepOrderOfDeclaration() {
        assertThat(new Dummy().toString()).isEqualTo("Dummy[zzz=zzz,a=1,b=-1]");
    }

    private static class Dummy {

        @AutoString
        private String zzz = "zzz";

        @AutoString
        private final int a, b;

        public Dummy() {
            this.a = 1;
            this.b = -1;
        }

        @Override
        public String toString() {
            return AutoStringBuilder.build(this);
        }
    }
}

Test that field declaration order is kept


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

import junit.framework.TestCase;

import org.apache.jmeter.report.core.Sample;
import org.apache.jmeter.report.core.SampleMetadata;
import org.junit.Test;

public class FieldSampleComparatorTest extends TestCase {

    private SampleMetadata sampleMetadata;
    private FieldSampleComparator comparator;

    @Override
    protected void setUp() throws Exception {
        super.setUp();
        sampleMetadata = new SampleMetadata(',', "test");
        comparator = new FieldSampleComparator("test");
        comparator.initialize(sampleMetadata);
    }

    @Test
    public void testCompare() {
        Sample s1 = new Sample(0, sampleMetadata, "1");
        Sample s2 = new Sample(1, sampleMetadata, "2");
        assertTrue(comparator.compare(s1, s2) < 0);
        assertTrue(comparator.compare(s2, s1) > 0);
        assertTrue(comparator.compare(s2, s2) == 0);
        assertTrue(comparator.compare(s1, s1) == 0);
    }

}

Use simple test case for FieldSampleComparator.

git-svn-id: https://svn.apache.org/repos/asf/jmeter/trunk@1719686 13f79535-47bb-0310-9956-ffa450edef68

Former-commit-id: 81c1a02bcf426c48985909c4104d67c02346447f


package nl.dvberkel.layout;

import nl.dvberkel.box.BoundingBox;
import nl.dvberkel.box.Translation;

import static nl.dvberkel.box.BoundingBox.mergeAll;

public class ConstantAngleLayouter implements Layouter {
    private static final Aligner HORIZONTAL_ALIGNER = new HorizontalAligner();
    private final double factor;

    public ConstantAngleLayouter(double angle) {
        this.factor = Math.sin(angle);
    }

    @Override
    public Translation[] layout(BoundingBox parent, BoundingBox[] children) {
        Translation[] translations = new Translation[] { new Translation(0, 0), new Translation(0, 0) };
        BoundingBox[] alignedChildren = HORIZONTAL_ALIGNER.align(children);
        for (int index = 0; index < children.length; index++){
            translations[index] = translations[index].translateBy(children[index].to(alignedChildren[index]));
        }

        BoundingBox merged = mergeAll(alignedChildren);
        int height = (int) (this.factor * merged.width/4);

        Translation verticalTranslation = new Translation(0, height);
        for (int index = 0; index < translations.length; index++){
            translations[index] = translations[index].translateBy(verticalTranslation);
        }

        return translations;
    }
}

Create a constant angle layouter

Create a constant angle layouter


/**
 * Check that return in main method is not accepted.
 *
 * @author Elvis Stansvik <elvstone@gmail.com>
 */
class ReturnInMainMethod {
    public static void main(String[] args) {
        int foo;
        return foo;
    }
}

Add another shared noncompile test.

Add another shared noncompile test.


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

import com.github.daytron.revworks.data.AnnouncementType;
import java.time.LocalDateTime;

/**
 * Announcement model class for Announcement table.
 *
 * @author Ryan Gilera
 */
public class Announcement {

    private final int id;
    private final String title;
    private final String message;
    private final LocalDateTime dateTimeSubmitted;
    private final AnnouncementType announcementType;
    private final String announcementSource;
    private final String moduleId;
    private final String modulename;

    public Announcement(int id, String title, String message,
            LocalDateTime dateTimeSubmitted, AnnouncementType announcementType,
            String announcementSource) {
        this(id, title, message, dateTimeSubmitted, announcementType,
                announcementSource, null, null);
    }

    public Announcement(int id, String title, String message,
            LocalDateTime dateTimeSubmitted, AnnouncementType announcementType,
            String announcementSource, String moduleId, String moduleName) {
        this.id = id;
        this.title = title;
        this.message = message;
        this.dateTimeSubmitted = dateTimeSubmitted;
        this.announcementType = announcementType;
        this.announcementSource = announcementSource;
        this.moduleId = moduleId;
        this.modulename = moduleName;
    }

    public int getId() {
        return id;
    }

    public String getTitle() {
        return title;
    }

    public String getMessage() {
        return message;
    }

    public LocalDateTime getDateTimeSubmitted() {
        return dateTimeSubmitted;
    }

    public AnnouncementType getAnnouncementType() {
        return announcementType;
    }

    public boolean isClassWideAnnouncement() {
        return announcementType == AnnouncementType.CLASS_WIDE;
    }

    public boolean isSystemWideAnnouncement() {
        return announcementType == AnnouncementType.SYSTEM_WIDE;
    }

    public String getAnnouncementSource() {
        return announcementSource;
    }

    public String getModuleId() {
        return moduleId;
    }

    public String getModulename() {
        return modulename;
    }

}

Add announcement class as a model for announcement table


/*
 * Copyright 2020 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.android.gnd.ui.editobservation;

import android.content.Context;
import com.google.android.gnd.model.form.MultipleChoice;
import com.google.android.gnd.model.observation.Response;
import com.google.auto.value.AutoValue;
import java8.util.Optional;
import java8.util.function.Consumer;

@AutoValue
public abstract class SelectDialogFactory {

  public static Builder builder() {
    return new AutoValue_SelectDialogFactory.Builder();
  }

  public abstract Context getContext();

  public abstract String getTitle();

  public abstract MultipleChoice getMultipleChoice();

  public abstract Optional<Response> getCurrentValue();

  public abstract Consumer<Optional<Response>> getValueConsumer();

  @AutoValue.Builder
  public abstract static class Builder {

    public abstract Builder setContext(Context context);

    public abstract Builder setTitle(String title);

    public abstract Builder setMultipleChoice(MultipleChoice multipleChoice);

    public abstract Builder setCurrentValue(Optional<Response> response);

    public abstract Builder setValueConsumer(Consumer<Optional<Response>> consumer);

    public abstract SelectDialogFactory build();
  }
}

Add abstract builder for select dialogs

Add abstract builder for select dialogs


package focusedCrawler.tools;

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

import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.hash.Hashing;

import focusedCrawler.target.model.TargetModelJson;
import focusedCrawler.target.repository.FilesTargetRepository;
import focusedCrawler.target.repository.FilesTargetRepository.RepositoryIterator;
import focusedCrawler.util.CliTool;
import io.airlift.airline.Command;
import io.airlift.airline.Option;

@Command(name="DumpMetadataFromRepository")
public class DumpMetadataFromRepository extends CliTool {

    @Option(name = "--input-path",
            required = true,
            description = "Path to directory containing a FILES repository")
    private String inputPath;

    @Option(name = "--output-file",
            required = true,
            description = "Text file containing metadata")
    private String outputFile;

    public static void main(String[] args) throws Exception {
        CliTool.run(args, new DumpMetadataFromRepository());
    }

    @Override
    public void execute() throws Exception {

        System.out.println("Reading URLs from path: " + inputPath);

        FilesTargetRepository repository = new FilesTargetRepository(inputPath);
        ObjectMapper jsonMapper = new ObjectMapper();

        PrintStream out = System.out;
        if(outputFile != null) {
            out  = new PrintStream(outputFile);
        }

        int totalPages = 0;
        RepositoryIterator it = repository.iterator();
        while(it.hasNext()) {
            TargetModelJson page = it.next();

            String id = Hashing.sha256().hashBytes(page.getUrl().getBytes()).toString();
            String signature = Hashing.md5().hashBytes(page.getContent()).toString();

            Map<String, Object> obj = new HashMap<String, Object>();
            obj.put("id", id);
            obj.put("url", page.getUrl());
            obj.put("signature", signature);
            obj.put("score", page.getRelevance().getRelevance());
            obj.put("team", "NYU");
            obj.put("timestamp_fetch", page.getFetchTime());

            out.println(jsonMapper.writeValueAsString(obj));

            totalPages++;
            if (totalPages % 1000 == 0) {
                System.out.printf("Processed %s pages...\n", totalPages);
            }
        }
        repository.close();
        System.out.println("done.");
    }

}

Add tool for dumping some metadata from repository


/*
 * JBoss, Home of Professional Open Source.
 * Copyright 2011, Red Hat, Inc., and individual contributors
 * as indicated by the @author tags. See the copyright.txt file in the
 * distribution for a full listing of individual contributors.
 *
 * This is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License as
 * published by the Free Software Foundation; either version 2.1 of
 * the License, or (at your option) any later version.
 *
 * This software is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this software; if not, write to the Free
 * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
 * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
 */

package org.jboss.as.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import org.jboss.as.protocol.StreamUtils;
import org.jboss.dmr.ModelNode;
import org.jboss.staxmapper.XMLElementReader;
import org.jboss.staxmapper.XMLElementWriter;

import javax.xml.namespace.QName;

/**
 * An XML configuration persister which backs up the old file before overwriting it.
 *
 * @author David M. Lloyd
 */
public final class BackupXmlConfigurationPersister extends XmlConfigurationPersister {

    /**
     * Construct a new instance.
     *
     * @param fileName the configuration base file name
     * @param rootElement the root element of the configuration file
     * @param rootParser the root model parser
     * @param rootDeparser the root model deparser
     */
    public BackupXmlConfigurationPersister(final File fileName, final QName rootElement, final XMLElementReader<ModelNode> rootParser, final XMLElementWriter<ModelNode> rootDeparser) {
        super(fileName, rootElement, rootParser, rootDeparser);
    }

    /** {@inheritDoc} */
    protected void backup(final File fileName) throws ConfigurationPersistenceException {
        File backup = new File(fileName.getParent(), fileName.getName() + ".last-known-good");
        try {
            moveFile(fileName, backup);
        } catch (IOException e) {
            throw new ConfigurationPersistenceException("Failed to back up " + fileName, e);
        }
    }

    private void moveFile(File file, File backup) throws IOException {

        if (backup.exists())
            backup.delete();

        if (!file.renameTo(backup) && file.exists()) {
            final FileInputStream fis = new FileInputStream(file);
            try {
                final FileOutputStream fos = new FileOutputStream(backup);
                try {
                    StreamUtils.copyStream(fis, fos);
                    fos.close();
                } finally {
                    StreamUtils.safeClose(fos);
                }
            } finally {
                StreamUtils.safeClose(fis);
            }
        }
    }
}

Add persister which backs up the original file

was: bc5b18ff62f1dc71916a47a80c3fde2dd50b3bed


/*
 * Copyright 2016 Michael Rozumyanskiy
 *
 * 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.michaelrocks.lightsaber.internal;

import io.michaelrocks.lightsaber.Injector;

public abstract class AbstractInjectingProvider<T> implements InjectingProvider<T> {
  private static final ThreadLocal<Injector> currentInjector = new ThreadLocal<Injector>();

  private final Injector injector;

  protected AbstractInjectingProvider(final Injector injector) {
    this.injector = injector;
  }

  @Override
  public final T get() {
    boolean ownsCurrentInjector = false;
    Injector contextInjector = currentInjector.get();
    if (contextInjector == null) {
      contextInjector = injector;
      currentInjector.set(contextInjector);
      ownsCurrentInjector = true;
    }

    try {
      return getWithInjector(contextInjector);
    } finally {
      if (ownsCurrentInjector) {
        currentInjector.remove();
      }
    }
  }
}

Introduce a base type for providers that support injection


/*
 * Copyright (c) 2010.
 *
 * 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.broadinstitute.sting.playground.gatk.walkers;

import org.broadinstitute.sting.WalkerTest;
import org.junit.Test;

import java.util.Arrays;

public class BeagleIntegrationTest extends WalkerTest {

    private static final String beagleValidationDataLocation = validationDataLocation + "/Beagle/";
    @Test
    public void testBeagleOutput() {
        WalkerTestSpec spec = new WalkerTestSpec(
                "-T BeagleOutputToVCF -R " + oneKGLocation + "reference/human_g1k_v37.fasta " +
                        "-B variant,VCF," + beagleValidationDataLocation + "inttestbgl.input.vcf " +
                        "-B beagleR2,BEAGLE," + beagleValidationDataLocation + "inttestbgl.r2 " +
                        "-B beagleProbs,BEAGLE," + beagleValidationDataLocation + "inttestbgl.gprobs " +
                        "-B beaglePhased,BEAGLE," + beagleValidationDataLocation + "inttestbgl.phased " +
                        "-output %s", 1, Arrays.asList("e7b9aac20246f26ffcc599850f6cb2a0"));
        executeTest("test BeagleOutputToVCF", spec);
    }

    @Test
    public void testBeagleInput() {
        WalkerTestSpec spec = new WalkerTestSpec(
                "-T ProduceBeagleInput -R " + oneKGLocation + "reference/human_g1k_v37.fasta " +
                        "-B variant,VCF," + beagleValidationDataLocation + "inttestbgl.input.vcf " +
                         "-beagle %s", 1, Arrays.asList("c0d30e5dbe903874f8422a0e63a5118e"));
        executeTest("test BeagleInput", spec);
    }

}

Add an integration test for Beagle (one for ProduceBeagleInput and one for BeagleOutputToVCFWalker)

git-svn-id: 4561c0a8f080806b19201efb9525134c00b76d40@3897 348d0f76-0448-11de-a6fe-93d51630548a


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

import javax.jms.JMSException;

/**
 * JMSException derivative that defines that a TX outcome is unknown.
 */
public class JmsTransactionInDoubtException extends JMSException {

    private static final long serialVersionUID = 4937372602950141285L;

    public JmsTransactionInDoubtException(String reason, String errorCode) {
        super(reason, errorCode);
    }

    public JmsTransactionInDoubtException(String reason) {
        super(reason);
    }
}

Add a JMS exception for transaction commit being in doubt.


package io.github.uetoyo.patterns.specification;

import com.google.common.annotations.Beta;

@Beta
abstract class ValueBoundedSpecification<T, V> implements Specification<T> {

	private final V value;

	/* TODO
	public static <T, V> EqualValueSpecification<T, V> withEqualValue(V value) {
		return new EqualValueSpecification<T, V>(value);
	}*/

	protected ValueBoundedSpecification(V value) {
		this.value = value;
	}

	public V getValue() {
		return value;
	}
}

Add the sketch of value bounded specification


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

package com.google.gerrit.acceptance.rest.project;

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

import com.google.gerrit.acceptance.AbstractDaemonTest;
import com.google.gerrit.acceptance.RestResponse;
import com.google.gerrit.extensions.api.access.ProjectAccessInfo;
import com.google.gson.reflect.TypeToken;
import java.util.Map;
import org.junit.Test;

public class AccessIT extends AbstractDaemonTest {

  @Test
  public void listAccessWithoutSpecifyingProject() throws Exception {
    RestResponse r = adminRestSession.get("/access/");
    r.assertOK();
    Map<String, ProjectAccessInfo> infoByProject =
        newGson()
            .fromJson(r.getReader(), new TypeToken<Map<String, ProjectAccessInfo>>() {}.getType());
    assertThat(infoByProject).isEmpty();
  }

  @Test
  public void listAccessWithoutSpecifyingAnEmptyProjectName() throws Exception {
    RestResponse r = adminRestSession.get("/access/?p=");
    r.assertNotFound();
    assertThat(r.getEntityContent()).isEqualTo("Not Found");
  }

  @Test
  public void listAccessForNonExistingProject() throws Exception {
    RestResponse r = adminRestSession.get("/access/?project=non-existing");
    r.assertNotFound();
    assertThat(r.getEntityContent()).isEqualTo("non-existing");
  }

  @Test
  public void listAccess() throws Exception {
    RestResponse r = adminRestSession.get("/access/?project=" + project.get());
    r.assertOK();
    Map<String, ProjectAccessInfo> infoByProject =
        newGson()
            .fromJson(r.getReader(), new TypeToken<Map<String, ProjectAccessInfo>>() {}.getType());
    assertThat(infoByProject.keySet()).containsExactly(project.get());
  }
}

Add basic test for the ListAccess REST endpoint

ListAccess is forwarding calls to GetAccess which populates the data in
the JSON. Since we already have tests for GetAccess
(com.google.gerrit.acceptance.api.project.AccessIT) we do not need to
validate the JSON once again in the new test.

We don't have a Java API for ListAccess yet, hence the new test runs
against the REST API for now.

Further tests that show buggy behaviour will be added later together
with the fixes.

Signed-off-by: Edwin Kempin <d43fb6c98c97e553b671ed9a9318100f1de386e7@google.com>
Change-Id: I24636e3d1b185c0a0005baf9c969101d06139ebd


package info.u_team.u_team_test.global_loot_modifier;

import java.util.List;
import java.util.stream.Collectors;

import com.google.gson.JsonObject;

import net.minecraft.inventory.Inventory;
import net.minecraft.item.ItemStack;
import net.minecraft.item.crafting.*;
import net.minecraft.util.ResourceLocation;
import net.minecraft.world.storage.loot.LootContext;
import net.minecraft.world.storage.loot.conditions.ILootCondition;
import net.minecraftforge.common.loot.*;
import net.minecraftforge.items.ItemHandlerHelper;

public class AutoSmeltLootModifier extends LootModifier {

	private AutoSmeltLootModifier(ILootCondition[] conditions) {
		super(conditions);
	}

	@Override
	protected List<ItemStack> doApply(List<ItemStack> generatedLoot, LootContext context) {
		return generatedLoot.stream().map(stack -> smeltItem(stack, context)).collect(Collectors.toList());
	}

	private static ItemStack smeltItem(ItemStack stack, LootContext context) {
		return context.getWorld().getRecipeManager().getRecipe(IRecipeType.SMELTING, new Inventory(stack), context.getWorld()).map(FurnaceRecipe::getRecipeOutput).filter(itemStack -> !itemStack.isEmpty()).map(itemStack -> ItemHandlerHelper.copyStackWithSize(itemStack, stack.getCount() * itemStack.getCount())).orElse(stack);
	}

	public static class Serializer extends GlobalLootModifierSerializer<AutoSmeltLootModifier> {

		@Override
		public AutoSmeltLootModifier read(ResourceLocation name, JsonObject json, ILootCondition[] conditions) {
			return new AutoSmeltLootModifier(conditions);
		}
	}

}

Add auto smelt loot modifier

Add auto smelt loot modifier


public class Binom {
  private static int[][] coeff = null;

  public static void main (String[] args) {
    int threshold = 20;
    int i = 0;
    for (int n = 0; n < threshold; ++n) {
      for (i = 0; i < threshold; ++i) {
        System.out.println("n = " + n + ", i = " + i + ": binom = " + binom(n, i));
      }
    }
  }

  public static int binom (final int n, final int i) {
    coeff = new int[n + 1][i + 1];

    int l = 0, k = 0;
    for (k = 0; k <= n; ++k) {
      for (l = 0; l <= i; ++l) {
        coeff[k][l] = Integer.MAX_VALUE;
      }
    }

    for (k = 0; k <= n; ++k) {
      coeff[k][0] = 1;
      for (l = 1; l <= i; ++l) {
        coeff[0][l] = 0;
      }
    }

    return lookupBinom(n, i);
  }

  public static int lookupBinom (final int n, final int i) {
    if (coeff[n][i] == Integer.MAX_VALUE) {
      coeff[n][i] = lookupBinom(n - 1, i) + lookupBinom(n - 1, i - 1);
    }

    return coeff[n][i];
  }
}

Add quick implementation of Aufgabe 22

Add quick implementation of Aufgabe 22


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

import java.security.Principal;
import java.util.Collections;

import javax.jcr.RepositoryException;
import javax.security.auth.Subject;

import org.apache.jackrabbit.core.security.SecurityConstants;
import org.apache.jackrabbit.core.security.principal.AdminPrincipal;

public class SessionFactory {

    private final RepositoryContext context;

    public SessionFactory(RepositoryContext context) {
        this.context = context;
    }

    public SessionImpl createAdminSession(String workspace)
            throws RepositoryException {
        Principal admin = new AdminPrincipal(SecurityConstants.ADMIN_ID);
        Subject subject = new Subject(
                true, Collections.singleton(admin),
                Collections.emptySet(), Collections.emptySet());
        return context.getRepository().createSession(subject, workspace);
    }

}

Add a factory for creating new sessions

JCR-3072: Add a factory for creating new sessions

Add an initial SessionFactory class. Work in progress.

git-svn-id: 02b679d096242155780e1604e997947d154ee04a@1176586 13f79535-47bb-0310-9956-ffa450edef68


/*
 * Copyright (c) 2016 Qiscus.
 *
 * 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.qiscus.sdk.data.remote;

import com.schinizer.rxunfurl.RxUnfurl;
import com.schinizer.rxunfurl.model.PreviewData;

import rx.Observable;
import rx.schedulers.Schedulers;

/**
 * Created on : December 09, 2016
 * Author     : zetbaitsu
 * Name       : Zetra
 * GitHub     : https://github.com/zetbaitsu
 */
public enum QiscusUrlScraper {
    INSTANCE;

    private final RxUnfurl rxUnfurl;

    QiscusUrlScraper() {
        rxUnfurl = new RxUnfurl.Builder()
                .scheduler(Schedulers.io())
                .build();
    }

    public static QiscusUrlScraper getInstance() {
        return INSTANCE;
    }

    public Observable<PreviewData> generatePreviewData(String url) {
        return rxUnfurl.generatePreview(url);
    }
}

Add singleton for getting link preview data


/*
 * Copyright (C) 2015 Archie L. Cobbs. All rights reserved.
 */

package org.jsimpledb.cli.cmd;

import java.util.Map;

import org.jsimpledb.SessionMode;
import org.jsimpledb.cli.CliSession;
import org.jsimpledb.parse.EnumNameParser;
import org.jsimpledb.parse.ParseContext;
import org.jsimpledb.parse.Parser;

@Command(modes = { SessionMode.KEY_VALUE, SessionMode.CORE_API, SessionMode.JSIMPLEDB })
public class SetSessionModeCommand extends AbstractCommand {

    public SetSessionModeCommand() {
        super("set-session-mode mode:mode");
    }

    @Override
    public String getHelpSummary() {
        return "Sets the CLI session mode";
    }

    @Override
    public String getHelpDetail() {
        return "Changes the current CLI session mode. Specify JSIMPLEDB, CORE_API, or KEY_VALUE.";
    }

    @Override
    protected Parser<?> getParser(String typeName) {
        return "mode".equals(typeName) ? new EnumNameParser<SessionMode>(SessionMode.class, false) : super.getParser(typeName);
    }

    @Override
    public CliSession.Action getAction(CliSession session, ParseContext ctx, boolean complete, Map<String, Object> params) {
        final SessionMode mode = (SessionMode)params.get("mode");
        return new CliSession.Action() {
            @Override
            public void run(CliSession session) throws Exception {
                session.setMode(mode);
                session.getWriter().println("Set session mode to " + mode);
            }
        };
    }
}

Add new file accidentally forgotten in 7b297f45.


package se.kth.csc.controller;

import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;

@ResponseStatus(HttpStatus.NOT_FOUND)
public class BadNameException extends Exception {
    public BadNameException() {
    }

    public BadNameException(String message) {
        super(message);
    }

    public BadNameException(String message, Throwable cause) {
        super(message, cause);
    }

    public BadNameException(Throwable cause) {
        super(cause);
    }

    public BadNameException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
        super(message, cause, enableSuppression, writableStackTrace);
    }
}

Add new kind of exception

Add new kind of exception


/*
 * Copyright 2013 Daniel Kurka
 *
 * 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.gwt.resources;

import com.google.gwt.resources.converter.DefCollectorVisitorTest;
import com.google.gwt.resources.converter.ElseNodeCreatorTest;
import com.google.gwt.resources.gss.ExternalClassesCollectorTest;

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

@RunWith(Suite.class)
@SuiteClasses({
    DefCollectorVisitorTest.class, ElseNodeCreatorTest.class, ExternalClassesCollectorTest.class})
public class AllJUnitTests {
}

Add a testsuite for JUnit tests.

Add a testsuite for JUnit tests.


package fr.alecharp.picshare.repository;

import fr.alecharp.picshare.domain.Event;

import javax.inject.Singleton;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;

/**
 * @author Adrien Lecharpentier
 */
@Singleton
public class EventRepository {
    private final Map<String, Event> eventStore = new HashMap<>();

    public Event save(Event event) {
        eventStore.put(event.id(), event);
        return event;
    }

    public void delete(String id) {
        eventStore.remove(id);
    }

    public Event findById(String id) {
        return eventStore.get(id);
    }
}

Create dumb repository for events

Create dumb repository for events


package info.u_team.u_team_core.util.registry;

import java.util.function.Supplier;

import net.minecraft.block.Block;
import net.minecraft.item.Item;
import net.minecraftforge.fml.RegistryObject;

public class BlockRegistryObject<B extends Block, I extends Item> implements Supplier<B> {

	private final RegistryObject<B> block;
	private final RegistryObject<I> item;

	public BlockRegistryObject(RegistryObject<B> block, RegistryObject<I> item) {
		this.block = block;
		this.item = item;
	}

	@Override
	public B get() {
		return block.get();
	}

	public boolean hasItem() {
		return item.isPresent();
	}

	public I getItem() {
		return item.get();
	}

}

Add basic block registry object

Add basic block registry object


/*
 * Zorbage: an Algebraic data hierarchy for use in numeric processing.
 *
 * Copyright (C) 2016-2018 Barry DeZonia
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * 1. Redistributions of source code must retain the above copyright notice,
 *    this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright notice,
 *    this list of conditions and the following disclaimer in the documentation
 *    and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */
package nom.bdezonia.zorbage.type.storage;

/**
 *
 * @author Barry DeZonia
 *
 */
public class TrimmedStorage<T extends IndexedDataSource<T,U>, U>
	implements
		IndexedDataSource<T,U>
{
	private final IndexedDataSource<T,U> list;
	private final long first;
	private final long last;

	/**
	 *
	 * @param list
	 * @param first
	 * @param last
	 */
	public TrimmedStorage(IndexedDataSource<T,U> list, long first, long last) {
		if (first < 0 || last < 0 || first > last ||
				first >= list.size() || last >= list.size() ||
				(last - first) >= list.size())
			throw new IllegalArgumentException("poor definition of first/last/list size");
		this.list = list;
		this.first = first;
		this.last = last;
	}

	@Override
	public T duplicate() {
		// shallow copy
		// TODO: WTH? Why does this warning keep cropping up?
		return (T) new TrimmedStorage<>(list, first, last);
	}

	@Override
	public void set(long index, U value) {
		if (index < 0)
			throw new IllegalArgumentException("negative index exception");
		if (index > size())
			throw new IllegalArgumentException("out of bounds index exception");
		list.set(index+first, value);
	}

	@Override
	public void get(long index, U value) {
		if (index < 0)
			throw new IllegalArgumentException("negative index exception");
		if (index > size())
			throw new IllegalArgumentException("out of bounds index exception");
		list.get(index+first, value);
	}

	@Override
	public long size() {
		return last - first + 1;
	}

}

Add a list trimming storage container

Add a list trimming storage container


package net.restlesscoder.sandbox.imagej;

import net.imagej.Dataset;
import net.imagej.ImageJ;
import net.imagej.ops.Ops;
import net.imagej.ops.special.computer.Computers;
import net.imagej.ops.special.computer.UnaryComputerOp;
import net.imglib2.algorithm.neighborhood.DiamondShape;
import net.imglib2.algorithm.neighborhood.HyperSphereShape;
import net.imglib2.algorithm.neighborhood.RectangleShape;
import net.imglib2.algorithm.neighborhood.Shape;
import net.imglib2.img.Img;
import net.imglib2.type.numeric.integer.UnsignedByteType;
import net.imglib2.type.numeric.real.FloatType;

public class MedianBySlice {

	public static void main(final String... args) throws Exception {
		final ImageJ ij = new ImageJ();
		ij.ui().showUI();

		Dataset mriStack = ij.scifio().datasetIO().open("/Users/curtis/data/mri-stack.tif");
		ij.ui().show("Original", mriStack);

		final Img<UnsignedByteType> img = mriStack.typedImg(new UnsignedByteType());
		final Img<FloatType> in = ij.op().convert().float32(img);
		final Img<FloatType> out = ij.op().create().img(in);

		ij.ui().show("Rectangle", median(ij, in, out, new RectangleShape(5, false)));
		ij.ui().show("Circle", median(ij, in, out, new HyperSphereShape(5)));
		ij.ui().show("Diamond", median(ij, in, out, new DiamondShape(5)));
	}

	private static Object median(ImageJ ij, Img<FloatType> in, Img<FloatType> out,
		Shape shape)
	{
		UnaryComputerOp op = Computers.unary(ij.op(), Ops.Filter.Median.class, out, in, shape);
		return ij.op().slice(out, in, op, new int[] {0, 1});
	}
}

Add example of slicewise op with median filter


package com.github.pgasync.impl;

import com.github.pgasync.ConnectionPool;
import com.github.pgasync.SqlException;
import org.junit.Test;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.TimeUnit;

import static com.github.pgasync.impl.DatabaseRule.createPoolBuilder;
import static org.junit.Assert.assertEquals;

public class AuthenticationTest {

    @Test
    public void shouldThrowExceptionOnInvalidCredentials() throws Exception {
        try (ConnectionPool pool = createPoolBuilder(1).password("_invalid_").build()) {
            BlockingQueue<Throwable> result = new ArrayBlockingQueue<>(1);
            pool.query("SELECT 1", System.out::println, result::add);
            SqlException sqle = (SqlException) result.poll(5, TimeUnit.SECONDS);
            assertEquals("28P01", sqle.getCode());
        }
    }

}

Add test for authentication failure

Add test for authentication failure


package com.antew.redditinpictures.library.image;

import android.content.res.Resources;

import com.antew.redditinpictures.library.R;

public class ThumbnailInfo {
    private int thumbnailSize    = 0;
    private int thumbnailSpacing = 0;

    private ThumbnailInfo(Resources resources) {
        thumbnailSize = resources.getDimensionPixelSize(R.dimen.image_thumbnail_size);
        thumbnailSpacing = resources.getDimensionPixelSize(R.dimen.image_thumbnail_spacing);
    }

    public static ThumbnailInfo getThumbnailInfo(Resources resources) {
        return new ThumbnailInfo(resources);
    }

    public int getSize() {
        return thumbnailSize;
    }

    public void setSize(int thumbnailSize) {
        this.thumbnailSize = thumbnailSize;
    }

    public int getSpacing() {
        return thumbnailSpacing;
    }

    public void setSpacing(int thumbnailSpacing) {
        this.thumbnailSpacing = thumbnailSpacing;
    }

}

Add utility class for handling thumbnail size/spacing.


package com.gmail.nossr50.util.blockmeta;

public class PrimitiveChunkletStore implements ChunkletStore {
    private static final long serialVersionUID = -3453078050608607478L;

    /** X, Z, Y */
    protected boolean[][][] store = new boolean[16][16][64];

    @Override
    public boolean isTrue(int x, int y, int z) {
        return store[x][z][y];
    }

    @Override
    public void setTrue(int x, int y, int z) {
        store[x][z][y] = true;
    }

    @Override
    public void setFalse(int x, int y, int z) {
        store[x][z][y] = false;
    }

    @Override
    public boolean isEmpty() {
        for(int x = 0; x < 16; x++) {
            for(int z = 0; z < 16; z++) {
                for(int y = 0; y < 64; y++) {
                    if(store[x][z][y]) return false;
                }
            }
        }
        return true;
    }

    @Override
    public void copyFrom(ChunkletStore otherStore) {
        for(int x = 0; x < 16; x++) {
            for(int z = 0; z < 16; z++) {
                for(int y = 0; y < 64; y++) {
                    store[x][z][y] = otherStore.isTrue(x, y, z);
                }
            }
        }
    }
}

package com.gmail.nossr50.util.blockmeta;

public class PrimitiveChunkletStore implements ChunkletStore {
    private static final long serialVersionUID = -3453078050608607478L;

    /** X, Z, Y */
    private boolean[][][] store = new boolean[16][16][64];

    @Override
    public boolean isTrue(int x, int y, int z) {
        return store[x][z][y];
    }

    @Override
    public void setTrue(int x, int y, int z) {
        store[x][z][y] = true;
    }

    @Override
    public void setFalse(int x, int y, int z) {
        store[x][z][y] = false;
    }

    @Override
    public boolean isEmpty() {
        for(int x = 0; x < 16; x++) {
            for(int z = 0; z < 16; z++) {
                for(int y = 0; y < 64; y++) {
                    if(store[x][z][y]) return false;
                }
            }
        }
        return true;
    }

    @Override
    public void copyFrom(ChunkletStore otherStore) {
        for(int x = 0; x < 16; x++) {
            for(int z = 0; z < 16; z++) {
                for(int y = 0; y < 64; y++) {
                    store[x][z][y] = otherStore.isTrue(x, y, z);
                }
            }
        }
    }
}

Change this back to private

Change this back to private


package me.alivecode.algs4;

import edu.princeton.cs.algs4.StdIn;
import edu.princeton.cs.algs4.StdOut;

public class WeightedQuickUnionUF {
    private int[] parent;
    private int[] size;
    private int count;

    public WeightedQuickUnionUF(int n) {
        parent = new int[n];
        size = new int[n];
        for (int i = 0; i < n; i++) {
            parent[i] = i;
            size[i] = 1;
        }
        count = n;
    }

    public int count() {
        return count;
    }

    public void validate(int p) {
        int n = parent.length;
        if (p < 0 || p >= n) {
            throw new IndexOutOfBoundsException("Index " + p + " is not between 0 and " + (n - 1) + ".");
        }
    }

    public int find(int p) {
        validate(p);
        while (p != parent[p]) {
            parent[p] = parent[parent[p]];
            p = parent[p];
        }
        return p;
    }

    public boolean connected(int p, int q) {
        return find(p) == find(q);
    }

    public void union(int p, int q) {
        int pRoot = find(p);
        int qRoot = find(q);
        if (pRoot == qRoot) {
            return;
        }
        if (size[pRoot] <= size[qRoot]) {
            parent[pRoot] = qRoot;
            size[qRoot] += size[pRoot];
        } else {
            parent[qRoot] = pRoot;
            size[pRoot] += size[qRoot];
        }
        count--;
    }

    // Print the structure for testing reason.
    void printStructure(){
        int n = parent.length;
        StdOut.printf("%-8s", "site:");
        for(int i = 0; i < n; i++) {
            StdOut.printf("%4d", i);
        }
        StdOut.printf("\n%-8s", "linked:");
        for(int i = 0; i < n; i++) {
            StdOut.printf("%4d", parent[i]);
        }
        StdOut.printf("\n%-8s", "size:");
        for(int i = 0; i < n; i++) {
            StdOut.printf("%4d", size[i]);
        }
        StdOut.println();
    }

    public static void main(String[] args) {
        int n = StdIn.readInt();
        WeightedQuickUnionUF uf = new WeightedQuickUnionUF(n);
        uf.printStructure();
        while (!StdIn.isEmpty()) {
            int p = StdIn.readInt();
            int q = StdIn.readInt();
            if (uf.connected(p, q)) {
                continue;
            }
            uf.union(p, q);
            uf.printStructure();
            StdOut.println(p + " + " + q);
        }
        uf.printStructure();
        StdOut.println(uf.count() + " components.");
    }
}

Add weighted quick union union find.

Add weighted quick union union find.


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

import javax.script.ScriptEngine;
import javax.script.ScriptException;
import org.scijava.Context;
import org.scijava.script.ScriptLanguage;
import org.scijava.script.ScriptService;

/**
 *
 * @author Hadrien Mary
 */
public class TestScriptEngine {

    public static void main(String[] args) throws ScriptException {
        // Only for testing purpose

        Context context = new Context();
        ScriptService scriptService = context.getService(ScriptService.class);
        ScriptLanguage scriptLanguage = scriptService.getLanguageByName("python");
        ScriptEngine engine = scriptLanguage.getScriptEngine();

        engine.eval("print('Hello'");

        context.dispose();
    }

}

Move test code to ... test

Move test code to ... test


// 6. ZigZag Conversion
/**
 * The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like this:
 * (you may want to display this pattern in a fixed font for better legibility)
 *
 * P   A   H   N
 * A P L S I I G
 * Y   I   R
 *
 * And then read line by line: "PAHNAPLSIIGYIR"
 * Write the code that will take a string and make this conversion given a number of rows:
 *
 * string convert(string text, int nRows);
 *
 * convert("PAYPALISHIRING", 3) should return "PAHNAPLSIIGYIR".
 *
 * Tags: String
 *
 * Author: Xinyue Zhang
 */

public class Solution {
    public String convert(String s, int nRows) {
        if (s == null || s.isEmpty()) {
            return s;
        }

        int length = s.length();
        if (length <= nRows || nRows <= 1) {
            return s;
        }

        StringBuilder sb = new StringBuilder();

        int step = 2 * (nRows - 1);
        int count = 0;

        for (int i = 0; i < nRows; i++){
            int interval = step - 2 * i;

            for (int j = i; j < length; j += step){
                   sb.append(s.charAt(j));
                count++;
                if (interval > 0 && interval < step
                    && j + interval < length
                    && count <  length) {
                    sb.append(s.charAt(j + interval));
                    count++;
                }
            }
        }
        return sb.toString();
    }

    public static void main(String args[]) {
        String s = "PAYPALISHIRING";
        Solution sol = new Solution();
        String res = sol.convert(s, 3);
        System.out.println(res);
    }
}

Add solution for 6. ZigZag Conversion

Add solution for 6. ZigZag Conversion


import java.io.*;
import java.util.*;

// https://www.hackerrank.com/challenges/countingsort3
public class CountingSort3 {

    private Integer[] getNumbersArray() throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        int lines = Integer.parseInt(br.readLine());
        Integer[] numbers = new Integer[lines];
        for (int i = 0; i < lines; i++) {
            String[] splitArray = br.readLine().split(" ");
            numbers[i] = Integer.parseInt(splitArray[0]);
        }
        br.close();
        return numbers;
    }

    private Map<Integer, Integer> getNumberFrequencyMap(Integer[] numbers) {
        int zero = 0;
        Map<Integer, Integer> numberFrequencyMap = new Hashtable<>();
        for (Integer number : numbers) {
            Integer frequency = numberFrequencyMap.getOrDefault(number, zero);
            frequency++;
            numberFrequencyMap.put(number, frequency);
        }
        return numberFrequencyMap;
    }

    private String getCounterNumberFrequencyString(Map<Integer, Integer> numberFrequencyMap) {
        String counterNumberFrequency = "";
        int zero = 0;
        int counter = 0;
        int limit = 100;
        for (int i = 0; i < limit; i++) {
            Integer frequency = numberFrequencyMap.getOrDefault(i, zero);
            counter += frequency;
            counterNumberFrequency += counter + " ";
        }
        return counterNumberFrequency.trim();
    }

    public static void main(String[] args) throws IOException {
        CountingSort3 countingSort3 = new CountingSort3();
        Integer[] numbers = countingSort3.getNumbersArray();
        Map<Integer, Integer> numberFrequencyMap = countingSort3.getNumberFrequencyMap(numbers);
        String counterNumberFrequency = countingSort3.getCounterNumberFrequencyString(numberFrequencyMap);
        System.out.println(counterNumberFrequency);
    }
}

Solve the counting sort 3 problem.

Solve the counting sort 3 problem.


package com.github.aureliano.achmed.resources.exec;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

import com.github.aureliano.achmed.exception.ExecResourceException;

public final class CommandFacade {

	private CommandFacade() {
		super();
	}

	public static int executeCommand(CommandBuilder command) {
		boolean verbose = command.getVerbose() != null ? command.getVerbose() : true;
		CommandRunner runner = new CommandRunner(command.getCommand(), command.getWorkingDir(), verbose);

		ExecutorService executor = Executors.newSingleThreadExecutor();
		Future<Integer> future = executor.submit(runner);

		try {
			return future.get(command.getTimeout(), TimeUnit.MILLISECONDS);
		} catch (ExecutionException|TimeoutException|InterruptedException ex) {
			throw new ExecResourceException(ex);
		}
	}
}

Create command facade to encapsulate command execution.