/*
 * #%L
 * BroadleafCommerce Common Libraries
 * %%
 * Copyright (C) 2009 - 2015 Broadleaf Commerce
 * %%
 * 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.
 * #L%
 */
package org.broadleafcommerce.common.web.resource.transformer;

import org.springframework.core.io.Resource;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.resource.ResourceTransformer;
import org.springframework.web.servlet.resource.ResourceTransformerChain;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;

/**
 * A {@link org.springframework.web.servlet.resource.ResourceTransformer} that replaces the
 * //BLC-SERVLET-CONTEXT and //BLC-SITE-BASEURL" tokens before serving the BLC.js file.
 *
 * @since 4.0
 */
@Component("blBLCJsTranformer")
public class BLCJSResourceTransformer implements ResourceTransformer {

    @Override
    public Resource transform(HttpServletRequest request, Resource resource, ResourceTransformerChain transformerChain)
            throws IOException {

        // TODO: Only resolve BLC.js

        return null;
    }

}

Check in template for BLC Js ResourceTransformer.


package net.restlesscoder.sandbox;

import java.util.function.Predicate;

public class EqualsPredicate {

	public static void main(final String... args) {
		// Why do we need Predicate.isEqual anyway?
		// Why not just use obj::equals?
		// Here's why!

		final Object obj = null;

		Predicate<Object> objEqualsSafe = Predicate.isEqual(obj);
		System.out.println(objEqualsSafe.test(null));

		Predicate<Object> objEquals = obj::equals;
		System.out.println(objEquals.test(null));
	}

}

Add illustration where Predicate.isEqual is useful


package jamex.common;

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

/**
 * Annotate a type or method as being an "entry point".
 *
 * Mainly used so that IDEA can identify dynamically accessed classes as
 * entry points and not mark them as unused.
 */
@Retention( RetentionPolicy.CLASS )
@Target( { ElementType.TYPE, ElementType.METHOD } )
public @interface EntryPoint
{
}

Add an annotation to mark types/methods as entry points


package org.monospark.spongematchers.parser.type;

import static org.hamcrest.CoreMatchers.not;
import static org.junit.Assert.assertThat;
import static org.monospark.spongematchers.testutil.HamcrestSpongeMatchers.matches;

import java.util.List;

import org.junit.Test;
import org.monospark.spongematchers.matcher.SpongeMatcher;
import org.monospark.spongematchers.parser.SpongeMatcherParseException;
import org.monospark.spongematchers.parser.element.StringElement;
import org.monospark.spongematchers.parser.element.StringElementParser;
import org.monospark.spongematchers.testutil.ExceptionChecker;

import com.google.common.collect.Lists;

public class ListTypeMatcher {

    @Test
    public void parseMatcher_NonListElement_ThrowsException() throws SpongeMatcherParseException {
        StringElement element = StringElementParser.parseStringElement("empty");
        ExceptionChecker.check(SpongeMatcherParseException.class,
                () -> MatcherType.list(MatcherType.BOOLEAN).parseMatcher(element));
    }

    @Test
    public void parseMatcher_ValidListElement_ReturnsCorrectSpongeMatcher() throws SpongeMatcherParseException {
        StringElement element = StringElementParser.parseStringElement("[true,false]");

        SpongeMatcher<List<Boolean>> matcher = MatcherType.list(MatcherType.BOOLEAN).parseMatcher(element);

        assertThat(matcher, matches(Lists.newArrayList(true, false)));
        assertThat(matcher, not(matches(Lists.newArrayList(false, true))));
    }

    @Test
    public void parseMatcher_ListMatchAnyElement_ReturnsCorrectSpongeMatcher() throws SpongeMatcherParseException {
        StringElement element = StringElementParser.parseStringElement("any:false");

        SpongeMatcher<List<Boolean>> matcher = MatcherType.list(MatcherType.BOOLEAN).parseMatcher(element);

        assertThat(matcher, matches(Lists.newArrayList(true, false)));
        assertThat(matcher, not(matches(Lists.newArrayList(true, true))));
    }

    @Test
    public void parseMatcher_ListMatchAllElement_ReturnsCorrectSpongeMatcher() throws SpongeMatcherParseException {
        StringElement element = StringElementParser.parseStringElement("all:false");

        SpongeMatcher<List<Boolean>> matcher = MatcherType.list(MatcherType.BOOLEAN).parseMatcher(element);

        assertThat(matcher, matches(Lists.newArrayList(false, false)));
        assertThat(matcher, not(matches(Lists.newArrayList(false, true))));
    }
}

Add unit tests for list matcher parsing


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

import static org.junit.Assert.assertEquals;

import org.junit.Test;

import nom.bdezonia.zorbage.groups.G;
import nom.bdezonia.zorbage.procedure.Ramp;
import nom.bdezonia.zorbage.type.data.float64.real.Float64Group;
import nom.bdezonia.zorbage.type.data.float64.real.Float64Member;
import nom.bdezonia.zorbage.type.storage.IndexedDataSource;
import nom.bdezonia.zorbage.type.storage.Storage;

/**
 *
 * @author Barry DeZonia
 *
 */
public class TestFill {

	@Test
	public void test() {
		long size = 10000;
		Float64Member type = new Float64Member();
		IndexedDataSource<?, Float64Member> data = Storage.allocate(size, type);
		Ramp<Float64Group, Float64Member> rampProc = new Ramp<Float64Group, Float64Member>(G.DBL, new Float64Member(0.5), new Float64Member(3));
		Fill.compute(G.DBL, data, rampProc);
		assertEquals(size, data.size());
		for (long i = 0; i < size; i++) {
			data.get(i, type);
			assertEquals(0.5+3*i, type.v(), 0);
		}
	}
}

Define a test for Fill and Ramp


package beaform.dao;

import static org.junit.Assert.assertNotNull;

import org.junit.Test;

/**
 * Test for the GraphDbHandler.
 *
 * @author Steven Post
 *
 */
public class GraphDbHandlerTest {

	@Test(expected=IllegalStateException.class)
	public void testClearInstanceException() {
		GraphDbHandler.clearInstance();
	}

	@Test(expected=IllegalStateException.class)
	public void testGetInstanceException() {
		GraphDbHandler.getInstance();
	}

	@Test
	public void testGetInstance() {
		GraphDbHandler.initInstance("test");
		final GraphDbHandler handler = GraphDbHandler.getInstance();

		assertNotNull("The handler is null", handler);

		GraphDbHandler.clearInstance();
	}

}

Add some unit tests for the GraphDBHandler


package arez.component;

import javax.annotation.Nonnull;
import org.testng.annotations.Test;
import static org.testng.Assert.*;

public class IdentifiableTest
  extends AbstractArezComponentTest
{
  static class TestElement
    implements Identifiable<String>
  {
    @Nonnull
    @Override
    public String getArezId()
    {
      return "X";
    }
  }

  @Test
  public void identifiableElement()
  {
    final TestElement element = new TestElement();
    assertEquals( Identifiable.getArezId( element ), "X" );
    assertEquals( Identifiable.<String>asIdentifiable( element ), element );
  }

  @Test
  public void nonIdentifiableElement()
  {
    final Object element = new Object();
    assertNull( Identifiable.getArezId( element ) );
    final IllegalStateException exception =
      expectThrows( IllegalStateException.class, () -> Identifiable.asIdentifiable( element ) );
    assertEquals( exception.getMessage(),
                  "Object passed to asIdentifiable does not implement Identifiable. Object: " + element );
  }
}

Add minimal tests to Identifiable


package seedu.taskman.logic.logicmanager;

import org.junit.Test;
import seedu.taskman.logic.commands.CommandResult;
import seedu.taskman.logic.commands.TagsCommand;
import seedu.taskman.model.TaskMan;
import seedu.taskman.model.event.Event;
import seedu.taskman.model.event.Task;
import seedu.taskman.model.tag.Tag;

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

import static org.junit.Assert.assertTrue;

/**
 * Created by jiayee on 11/1/16.
 */
public class TagsTests extends LogicManagerTestBase {
    @Test
    public void execute_tags_emptyArgsFormat() throws Exception {
        // no args
        assertCommandNoStateChange("tags");

        logic.execute("clear");
        CommandResult result = logic.execute("tags");
        assertTrue(result.feedbackToUser.equals(TagsCommand.TAG_STRING_HEADER
                + TagsCommand.TAG_STRING_EMPTY_PLACEHOLDER));
        // this is similar to assertCommandBehaviour, will be bringing it back

        // TODO: Tidy up

        LogicManagerTestBase.TestDataHelper helper = new LogicManagerTestBase.TestDataHelper();
        Task toBeAdded = helper.generateFullTask(1);

        TaskMan expectedTaskMan = new TaskMan();
        expectedTaskMan.addActivity(toBeAdded); // expected

        List<Task> tasks = new ArrayList<>();
        tasks.add(toBeAdded);
        helper.addToModel(model, tasks); // actual

        result = logic.execute("tags");
        StringBuilder tags = new StringBuilder();
        for (Tag tag : toBeAdded.getTags()) {
            tags.append(tag);
            tags.append(" ");
        }
        assertTrue(result.feedbackToUser.equals(TagsCommand.TAG_STRING_HEADER
                + tags.toString().trim()));
    }
}

Add tests for tags command


package io.github.droidkaigi.confsched2017.view.helper;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.support.annotation.NonNull;

import timber.log.Timber;

public class IntentHelper {

    public static Intent buildActionViewIntent(@NonNull Context context, @NonNull String htmlUrl) {
        Timber.i("buildActionViewIntent: url: %s", htmlUrl);

        Uri uri = Uri.parse(htmlUrl);
        Intent intent = new Intent(Intent.ACTION_VIEW, uri);

        if (intent.resolveActivity(context.getPackageManager()) == null) {
            return null;
        }

        return intent;
    }
}

Add build action view intent in intent helper


package cz.scholz.aliaskeymanager;

import org.testng.Assert;
import org.testng.annotations.Test;

import java.security.Security;

/**
 * Created by schojak on 31.5.16.
 */
public class AliasProviderTest {
    @Test
    public void testSetAlias()
    {
        AliasProvider.setAlias("myAlias");
        Assert.assertEquals(System.getProperty("cz.scholz.aliaskeymanager.alias"), "myAlias", "System property was not properly set");
        AliasProvider.unSetAlias();
        Assert.assertNotEquals(System.getProperty("cz.scholz.aliaskeymanager.alias"), "myAlias", "System property was not properly cleared");
    }

    @Test
    public void testEnableProvider()
    {
        AliasProvider.enable();
        Assert.assertNotNull(Security.getProvider("aliaskm"), "The provide doesn't seem to exist");

        AliasProvider.disable();
        Assert.assertNull(Security.getProvider("aliaskm"), "The provide doesn't seem to be disabled");
    }

    @Test
    public void testSetAsDefaultProvider()
    {
        AliasProvider.setAsDefault();
        Assert.assertEquals(Security.getProperty("ssl.KeyManagerFactory.algorithm"), "aliaskm", "The new key manager has been set as default");

        AliasProvider.unsetAsDefault();
        Assert.assertNotEquals(Security.getProperty("ssl.KeyManagerFactory.algorithm"), "aliaskm", "The new key manager is still the default");
    }
}

Add tests for the AliasProvider


/*
 * Copyright 2016 Attribyte, 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
 *
 * 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.attribyte.wp.model;

import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;

/**
 * A post that represents an image attachment.
 */
public class ImageAttachment extends Post {

   /**
    * Creates an image attachment with unassigned id.
    * @param parent The parent post.
    * @param path The image path.
    * @param slug The image slug.
    * @param mimeType The associated mime type.
    */
   public ImageAttachment(final Post parent, final String path, final String slug, final String mimeType) {
      this(parent, 0L, path, slug, mimeType);
   }

   /**
    * Creates an image attachment with assigned id.
    * @param parent The parent post.
    * @param id The id.
    * @param path The image path.
    * @param slug The image slug.
    * @param mimeType The associated mime type.
    */
   public ImageAttachment(final Post parent, final long id, final String path, final String slug, final String mimeType) {
      super(id, slug, slug, "", "", parent.authorId, parent.author, parent.publishTimestamp, parent.publishTimestamp,
              parent.status, parent.id, path, 0, ImmutableList.of(), Type.ATTACHMENT, mimeType,
              ImmutableMap.of(), ImmutableList.of());
   }
}

Add derived post for image attachment.


package com.novoda.sqlite.impl;

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

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

public class SQLFileTest {
    private final static String STATEMENT_CREATE_TABLE = "CREATE TABLE banana(_id INTEGER);";
    private final static String STATEMENT_ALTER_TABLE = "ALTER TABLE banana ADD COLUMN colour TEXT;";
    private final static String NEW_LINE = "\n";
    private final static String SPACE = " ";
    private final static String LINE_COMMENT = "-- this is a line comment";
    private final static String[] EXPECTED_STATEMENTS = new String[]{STATEMENT_CREATE_TABLE, STATEMENT_ALTER_TABLE};
    private static final String BLOCK_COMMENT = "/* this is a \n block comment \n spanning over \n multiple lines */";

    @Test
    public void givenSQLFile_whenParseAndGetStatements_thenGetCorrectStatements() throws IOException {
        SQLFile file = givenSQLFileParsedFromString(STATEMENT_CREATE_TABLE + NEW_LINE + STATEMENT_ALTER_TABLE);

        String[] actual = getStatementsFromFile(file);

        Assert.assertArrayEquals(actual, EXPECTED_STATEMENTS);
    }

    @Test
    public void givenSQLFileWithSpaces_whenParseAndGetStatements_thenGetCorrectTrimmedStatements() throws IOException {
        SQLFile file = givenSQLFileParsedFromString(SPACE + STATEMENT_CREATE_TABLE + SPACE + NEW_LINE + SPACE + STATEMENT_ALTER_TABLE + SPACE);

        String[] actual = getStatementsFromFile(file);

        Assert.assertArrayEquals(actual, EXPECTED_STATEMENTS);
    }

    @Test
    public void givenSQLFileWithLineComments_whenParseAndGetStatements_thenIgnoreComments() throws IOException {
        SQLFile file = givenSQLFileParsedFromString(
                STATEMENT_CREATE_TABLE + SPACE + LINE_COMMENT + NEW_LINE + STATEMENT_ALTER_TABLE + SPACE + LINE_COMMENT);

        String[] actual = getStatementsFromFile(file);

        Assert.assertArrayEquals(actual, EXPECTED_STATEMENTS);
    }

    @Test
    public void givenSQLFileWithBlockComments_whenParseAndGetStatements_thenIgnoreComments() throws IOException {
        SQLFile file = givenSQLFileParsedFromString(
                STATEMENT_CREATE_TABLE + NEW_LINE + BLOCK_COMMENT + NEW_LINE + STATEMENT_ALTER_TABLE);

        String[] actual = getStatementsFromFile(file);

        Assert.assertArrayEquals(actual, EXPECTED_STATEMENTS);
    }

    private SQLFile givenSQLFileParsedFromString(String sql) throws IOException {
        SQLFile file = new SQLFile();
        file.parse(new StringReader(sql));
        return file;
    }

    private String[] getStatementsFromFile(SQLFile file) {
        List<String> statements = file.getStatements();
        return statements.toArray(new String[statements.size()]);
    }
}

Test SQLFile with all the possible (handled) use cases


package org.realityforge.arez;

import java.util.ArrayList;
import javax.annotation.Nonnull;
import static org.testng.Assert.*;

final class TestReaction
  implements Reaction
{
  private final ArrayList<Observer> _observers = new ArrayList<>();

  @Override
  public void react( @Nonnull final Observer observer )
    throws Exception
  {
    observer.getDependencies().forEach( Observable::reportObserved );
    _observers.add( observer );
  }

  void assertObserver( final int index, @Nonnull final Observer observer )
  {
    assertTrue( _observers.size() > index );
    assertEquals( _observers.get( index ), observer );
  }

  int getCallCount()
  {
    return _observers.size();
  }
}

Add reaction useful during testing


package leetcode.construct_binary_tree_from_inorder_and_postorder_traversal;

import common.TreeNode;

public class Solution {
	public TreeNode buildTree(int[] inorder, int[] postorder, int in_from, int in_to, int post_from, int post_to){
		if(in_from == in_to || post_from == post_to) return null;
		int rootval = postorder[post_to - 1];
		TreeNode root = new TreeNode(rootval);
		int rootidx;
		for(rootidx = in_from; rootidx < in_to && inorder[rootidx] != rootval; rootidx++);
		root.left = buildTree(inorder, postorder, in_from, rootidx, post_from, post_from + (rootidx - in_from));
		root.right = buildTree(inorder, postorder, rootidx + 1, in_to, post_to - (in_to - rootidx), post_to - 1);
		return root;
	}
    public TreeNode buildTree(int[] inorder, int[] postorder) {
    	if(inorder == null || postorder == null) return null;
    	return buildTree(inorder, postorder, 0, inorder.length, 0, postorder.length);
    }

    public static void inOrder(TreeNode cur){
    	if(cur != null){
    		inOrder(cur.left);
    		System.err.print(cur.val + "->");
    		inOrder(cur.right);
    	}
    }

    public static void postOrder(TreeNode cur){
    	if(cur != null){
    		postOrder(cur.left);
    		postOrder(cur.right);
    		System.err.print(cur.val + "->");
    	}
    }

    public static void main(String[] args){
    	int[] inorder = new int[]{4, 9, 5, 1, 8, 3, 7, 6};
    	int[] postorder = new int[]{9, 4, 5, 8, 7, 6, 3, 1};
    	TreeNode ret = new Solution().buildTree(inorder, postorder);
    	inOrder(ret);
    	System.err.println("");
    	postOrder(ret);
    	System.err.println("");
    }
}

Add java solution for 106. Construct Binary Tree from Inorder and Postorder Traversal


package org.egorlitvinenko.other;

import java.nio.ByteBuffer;

/**
 *
 * https://docs.oracle.com/javase/specs/jls/se11/html/jls-3.html#jls-3.10.1
 * https://docs.oracle.com/javase/specs/jls/se11/html/jls-4.html#jls-4.2.1
 * https://docs.oracle.com/javase/specs/jvms/se11/html/jvms-2.html#jvms-2.11.1
 *
 * **/
public class ByteCoercion {

    public static void main(String[] args) {
        byte a = -83;
        int b = a;
        byte c = (byte) b;
//        int d = 0x800000CD;
        int d = 0x8000004D;
        byte e = (byte) d;
        System.out.println("a = " + a);
        System.out.println("b = " + b);
        System.out.println("c = " + c);
        System.out.println("b as binary: " + Integer.toBinaryString(b));
        System.out.println("b as bytes:"); print(intToByteArray(b));
        System.out.println("b as bytesBB:"); print(intToByteArrayBB(b));
        System.out.println("d = " + d);
        System.out.println("e = " + e);
        System.out.println("d as binary: " + Integer.toBinaryString(d));
        System.out.println("d as bytes:"); print(intToByteArray(d));
        System.out.println("d as bytesBB:"); print(intToByteArrayBB(d));
    }

    private static void print(byte[] array) {
        StringBuilder sb = new StringBuilder();
        sb.append("array=(");
        for (int i = 0; i < array.length; i++) {
            sb.append(array[i]).append(",");
        }
        sb.deleteCharAt(sb.length() - 1).append(")");
        System.out.println(sb);
    }

    private static byte[] intToByteArray(int a) {
        byte[] result = new byte[4];
        result[0] = (byte) (a & 0x000000FF);
        result[1] = (byte) ((a & 0x0000FF00) >> 8);
        result[2] = (byte) ((a & 0x00FF0000) >> 16);
        result[3] = (byte) ((a & 0xFF000000) >> 24);
        return result;
    }

    private static byte[] intToByteArrayBB(int a) {
        ByteBuffer bb = ByteBuffer.allocate(4);
        bb.putInt(a);
        return bb.array();
    }
}

Add example with byte int manipulations


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

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

    private final int id;
    private final String moduleId;
    private final String moduleName;

    public Class(int id, String moduleId, String moduleName) {
        this.id = id;
        this.moduleId = moduleId;
        this.moduleName = moduleName;
    }

    public int getId() {
        return id;
    }

    public String getModuleId() {
        return moduleId;
    }

    public String getModuleName() {
        return moduleName;
    }

}

Add a model for class table


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

/**
 * Given two integers passed as argument, can you implement the subtract operator using just "+" as
 * arithmetic operator?
 *
 * @author Pedro Vicente Gómez Sánchez.
 */
public class SubtractAdding {

}

Add statement to problem 73


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

/* $Id$ */

package org.apache.fop.render.ps;

import java.util.List;

import org.apache.fop.render.gradient.Function;
import org.apache.fop.render.gradient.Function.SubFunctionRenderer;
import org.apache.fop.render.gradient.GradientMaker.DoubleFormatter;
import org.apache.fop.render.gradient.Pattern;
import org.apache.fop.render.gradient.Shading;

/**
 * Helper class to draw gradients in PostScript.
 */
public final class Gradient {

    private Gradient() { }

    public static String outputPattern(Pattern pattern, DoubleFormatter doubleFormatter) {
        StringBuilder p = new StringBuilder(64);
        p.append("/Pattern setcolorspace\n");
        p.append("<< \n/Type /Pattern \n");

        p.append("/PatternType " + pattern.getPatternType() + " \n");

        if (pattern.getShading() != null) {
            p.append("/Shading ");
            outputShading(p, pattern.getShading(), doubleFormatter);
            p.append(" \n");
        }
        p.append(">> \n");
        List<Double> matrix = pattern.getMatrix();
        if (matrix == null) {
            p.append("matrix ");
        } else {
            p.append("[ ");
            for (double m : pattern.getMatrix()) {
                p.append(doubleFormatter.formatDouble(m));
                p.append(" ");
            }
            p.append("] ");
        }
        p.append("makepattern setcolor\n");

        return p.toString();
    }

    private static void outputShading(StringBuilder out, Shading shading, final DoubleFormatter doubleFormatter) {
        final Function function = shading.getFunction();
        Shading.FunctionRenderer functionRenderer = new Shading.FunctionRenderer() {

            public void outputFunction(StringBuilder out) {
                SubFunctionRenderer subFunctionRenderer = new Function.SubFunctionRenderer() {

                    public void outputFunction(StringBuilder out, int functionIndex) {
                        Function subFunction = function.getFunctions().get(functionIndex);
                        assert subFunction.getFunctions().isEmpty();
                        subFunction.output(out, doubleFormatter, null);
                    }
                };
                function.output(out, doubleFormatter, subFunctionRenderer);
            }
        };
        shading.output(out, doubleFormatter, functionRenderer);
    }

}

Support PDF shading to PS


/*
 * #%L
 * ImageJ software for multidimensional image processing and analysis.
 * %%
 * Copyright (C) 2014 - 2015 Board of Regents of the University of
 * Wisconsin-Madison, University of Konstanz and Brian Northan.
 * %%
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * 1. Redistributions of source code must retain the above copyright notice,
 *    this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright notice,
 *    this list of conditions and the following disclaimer in the documentation
 *    and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 * #L%
 */

package net.imagej.ops;

/**
 * Interface for objects which can be initialized.
 *
 * @author Curtis Rueden
 */
public interface Initializable {

	/** Initializes the object. */
	void initialize();

}

Add interface for things which can be initialized


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

package com.google.sps.data;
import com.google.auto.value.AutoValue;

/**
 * Class representing user data for ranking purposes only
 */
@AutoValue
public abstract class BasicCompetitor {
  public static BasicCompetitor create(long userId, long netWorth, int rankYesterday) {
    return new AutoValue_BasicCompetitor(userId, netWorth, rankYesterday);
  }
  /** The id of the competitor */
  public abstract long userId();
  /** The networth of the competitor */
  public abstract long netWorth();
  /** The user's rank yesterday */
  public abstract int rankYesterday();
}

Add basic object for ranking purposes


package com.andreistraut.gaps.datamodel.translator;

import com.andreistraut.gaps.datamodel.genetics.EdgeGene;
import com.andreistraut.gaps.datamodel.genetics.GeneticConfiguration;
import com.andreistraut.gaps.datamodel.genetics.PathChromosome;
import com.andreistraut.gaps.datamodel.graph.DirectedWeightedEdge;
import com.andreistraut.gaps.datamodel.graph.Node;
import java.util.ArrayList;
import org.jgrapht.GraphPath;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.*;

public class GraphGeneticsTranslatorTest {

    public GraphGeneticsTranslatorTest() {
    }

    @Before
    public void setUp() {
    }

    @Test
    public void testToPathChromosome() throws Exception {
	System.out.println("toPathChromosome");
	GraphPath<Node, DirectedWeightedEdge> path = null;
	GeneticConfiguration configuration = null;
	PathChromosome expResult = null;
	PathChromosome result = GraphGeneticsTranslator.toPathChromosome(path, configuration);
	assertEquals(expResult, result);
	// TODO review the generated test code and remove the default call to fail.
	fail("The test case is a prototype.");
    }

    @Test
    public void testToEdgeGeneList() throws Exception {
	System.out.println("toEdgeGeneList");
	GraphPath<Node, DirectedWeightedEdge> edgeList = null;
	GeneticConfiguration configuration = null;
	ArrayList<EdgeGene> expResult = null;
	ArrayList<EdgeGene> result = GraphGeneticsTranslator.toEdgeGeneList(edgeList, configuration);
	assertEquals(expResult, result);
	// TODO review the generated test code and remove the default call to fail.
	fail("The test case is a prototype.");
    }

}

Add new unit test class stub


package org.cipres.treebase.domain.nexus;

import junit.framework.Assert;

import org.cipres.treebase.dao.AbstractDAOTest;
import org.cipres.treebase.domain.matrix.CharacterMatrix;
import org.cipres.treebase.domain.nexus.nexml.NexmlMatrixConverter;
import org.cipres.treebase.domain.nexus.NexusDataSet;
import org.cipres.treebase.domain.study.Study;
import org.cipres.treebase.domain.taxon.TaxonLabelHome;
import org.nexml.model.DocumentFactory;
import org.nexml.model.Document;

public class NexmlMatrixConverterTest extends AbstractDAOTest {
	private TaxonLabelHome mTaxonLabelHome;

	/**
	 * Test  for {@link org.cipres.treebase.domain.nexus.nexml.NexmlMatrixConverter#fromTreeBaseToXml(CharacterMatrix)}.
	 */
	public void testNexmlMatrixConverter() {
		String testName = "testNexmlMatrixConverter";
		//signal beginning of test
		if (logger.isInfoEnabled()) {
			logger.info("\n\t\tRunning Test: " + testName);
		}

		long studyId = 1787;
		Study study = (Study)loadObject(Study.class, studyId);
		NexusDataSet nexusDataSet = new NexusDataSet();

		Document doc = DocumentFactory.safeCreateDocument();
		nexusDataSet.setNexmlProject(doc);
		NexmlMatrixConverter nmc = new NexmlMatrixConverter(study,getTaxonLabelHome(),doc);
		for (org.cipres.treebase.domain.matrix.Matrix matrix : nexusDataSet.getMatrices() ) {
			if ( matrix instanceof CharacterMatrix ) {
				//fromTreeBaseToXml(CharacterMatrix) is main method being tested here--it uses populateXmlMatrix() function
				String xml = ((Document) nmc.fromTreeBaseToXml((CharacterMatrix)matrix)).getXmlString();
				System.out.println(xml);
				Assert.assertNotNull(xml);
			}
		}
		//signal that test is over
		if (logger.isInfoEnabled()) {
			logger.info(testName + " - end ");
		}
	}

	/**
	 * Return the TaxonLabelHome field.
	 *
	 * @return TaxonLabelHome mTaxonLabelHome
	 */
	public TaxonLabelHome getTaxonLabelHome() {
		return mTaxonLabelHome;
	}

	/**
	 * Set the TaxonLabelHome field.
	 */
	public void setTaxonLabelHome(TaxonLabelHome pNewTaxonLabelHome) {
		mTaxonLabelHome = pNewTaxonLabelHome;
	}

}

Test for NexmlMatrixConverter class for function fromTreeBaseToXml(CharacterMatrix). This is the function that calls the poplulateXmlMatrix() function


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

/**
 * FIXME: This class should be removed once the dependency management function that the pom.xml found in the fcrepo-jcr
 * module serves has been satisfied in some other way.
 * See: https://www.pivotaltracker.com/story/show/68680222
 *
 * @author Andrew Woods
 *         Date: 4/1/14
 */
public class Empty {
}

Add placeholder java class to fcrepo-jcr


// Copyright 2014 Tool Inc.

package com.tool.emailbot.application.command;

import com.tool.emailbot.common.application.command.Command;

import java.util.Date;

/**
 * Command that specifies that a new email request should be created.
 *
 * @author Jovani Rico (jovanimtzrico@gmail.com)
 */
public class RegisterEmailCommand implements Command {

    private String name;
    private String fatherLastName;
    private String motherLastName;
    private Date fechaNacimiento;
    private String homoclave;
    private String numeroTrabajador;
    private String email;
    private String telephone;
    private String username;

    public RegisterEmailCommand(String name, String fatherLastName, String motherLastName,
            Date fechaNacimiento, String homoclave, String numeroTrabajador, String email,
            String telephone, String username) {
        this.name = name;
        this.fatherLastName = fatherLastName;
        this.motherLastName = motherLastName;
        this.fechaNacimiento = fechaNacimiento;
        this.homoclave = homoclave;
        this.numeroTrabajador = numeroTrabajador;
        this.email = email;
        this.telephone = telephone;
        this.username = username;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getFatherLastName() {
        return fatherLastName;
    }

    public void setFatherLastName(String fatherLastName) {
        this.fatherLastName = fatherLastName;
    }

    public String getMotherLastName() {
        return motherLastName;
    }

    public void setMotherLastName(String motherLastName) {
        this.motherLastName = motherLastName;
    }

    public Date getFechaNacimiento() {
        return fechaNacimiento;
    }

    public void setFechaNacimiento(Date fechaNacimiento) {
        this.fechaNacimiento = fechaNacimiento;
    }

    public String getHomoclave() {
        return homoclave;
    }

    public void setHomoclave(String homoclave) {
        this.homoclave = homoclave;
    }

    public String getNumeroTrabajador() {
        return numeroTrabajador;
    }

    public void setNumeroTrabajador(String numeroTrabajador) {
        this.numeroTrabajador = numeroTrabajador;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getTelephone() {
        return telephone;
    }

    public void setTelephone(String telephone) {
        this.telephone = telephone;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }
}

Define a new command to register an email request


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

import static java.lang.invoke.MethodHandles.lookup;
import static org.slf4j.LoggerFactory.getLogger;

import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.RuleChain;
import org.junit.rules.TestRule;
import org.junit.runner.Description;
import org.junit.runners.model.Statement;
import org.slf4j.Logger;

public class TestRuleChain {

    static final Logger log = getLogger(lookup().lookupClass());

    @Rule
    public TestRule chain = RuleChain.outerRule(new BasicRule("outer"))
            .around(new BasicRule("middle")).around(new BasicRule("inner"));

    @BeforeClass
    public static void beforeclass() {
        log.debug("@BeforeClass");
    }

    @Before
    public void before() {
        log.debug("@Before");
    }

    @Test
    public void test() {
        log.debug("@Test");
    }

    @AfterClass
    public static void afterclass() {
        log.debug("@AfterClass");
    }

    @After
    public void after() {
        log.debug("@After");
    }

    private static class BasicRule implements TestRule {

        private String name;

        public BasicRule(String name) {
            this.name = name;
        }

        public Statement apply(final Statement base,
                final Description description) {
            log.debug("Rule {} applied", name);
            return base;
        }

    }

}

Include test using JUnit 4's RuleChain


package com.woorea.openstack.examples.compute;

import com.woorea.openstack.examples.ExamplesConfiguration;
import com.woorea.openstack.keystone.Keystone;
import com.woorea.openstack.keystone.model.Access;
import com.woorea.openstack.keystone.model.authentication.UsernamePassword;
import com.woorea.openstack.nova.Nova;
import com.woorea.openstack.nova.api.ServersResource;
import com.woorea.openstack.nova.model.Servers;

public class NovaStopStartServer {
    public static void main(String[] args) throws InterruptedException {
        Keystone keystone = new Keystone(ExamplesConfiguration.KEYSTONE_AUTH_URL);
        Access access = keystone.tokens().authenticate(new UsernamePassword(ExamplesConfiguration.KEYSTONE_USERNAME, ExamplesConfiguration.KEYSTONE_PASSWORD))
                .withTenantName(ExamplesConfiguration.TENANT_NAME)
                .execute();

        //use the token in the following requests
        keystone.token(access.getToken().getId());

        Nova novaClient = new Nova(ExamplesConfiguration.NOVA_ENDPOINT.concat("/").concat(access.getToken().getTenant().getId()));
        novaClient.token(access.getToken().getId());

        Servers servers = novaClient.servers().list(true).execute();
        if(servers.getList().size() > 0) {

            ServersResource.StopServer stopServer = novaClient.servers().stop(servers.getList().get(0).getId());
            stopServer.endpoint(ExamplesConfiguration.NOVA_ENDPOINT);
            stopServer.execute();

            // Wait until server shutdown.
            Thread.sleep(5000);

            ServersResource.StartServer startServer = novaClient.servers().start(servers.getList().get(0).getId());
            startServer.endpoint(ExamplesConfiguration.NOVA_ENDPOINT);
            startServer.execute();
        }
    }
}

Add Stop and Start Nova Compute Server Example. Implemented example code of shutdown and srart nova compute server(instance).


package com.google.sps.authentication;

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

import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.FetchOptions;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.appengine.api.datastore.PreparedQuery;
import com.google.appengine.api.datastore.Query;
import com.google.appengine.api.datastore.Query.FilterOperator;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseAuthException;
import com.google.firebase.auth.FirebaseToken;
import com.google.sps.firebase.FirebaseAppManager;
import com.google.appengine.api.datastore.Query.FilterPredicate;

public class Authenticator {
  private FirebaseAuth auth;
  private DatastoreService datastore;

  public Authenticator() throws IOException {
    this(FirebaseAuth.getInstance(FirebaseAppManager.getApp()));
  }

  protected Authenticator(FirebaseAuth auth) {
    this.auth = Objects.requireNonNull(auth);
    datastore = DatastoreServiceFactory.getDatastoreService();
  }

  public boolean verifyTaOrOwner(String idToken, Key classKey) {
    try {
      FirebaseToken tok = auth.verifyIdToken(idToken);
      PreparedQuery q = datastore.prepare(new Query("User").setFilter(
        new FilterPredicate("userEmail", FilterOperator.EQUAL, tok.getEmail())
      ));

      if(q.countEntities(FetchOptions.Builder.withLimit(1)) > 0) {
        return ((List<Key>) q.asSingleEntity().getProperty("taClasses")).contains(classKey) ||
               ((List<Key>) q.asSingleEntity().getProperty("ownedClasses")).contains(classKey);
      } else {
        return false;
      }
    } catch (FirebaseAuthException | IllegalArgumentException e) {
      return false;
    }

  }
}

Add authenticator class to handle servlet authentication.


import org.realityforge.arez.annotations.Container;
import org.realityforge.arez.annotations.Observable;

@Container
public class BasicObservableModel
{
  private long _time;

  @Observable
  public long getTime()
  {
    return _time;
  }

  @Observable
  public void setTime( final long time )
  {
    _time = time;
  }
}

Add another future test data point


/*
* 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.tomcat.buildutil.translate;

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

/**
 * Generates a set of English property files to back-port updates to a previous
 * version. Where a key exists in the source and target versions the value is
 * copied from the source to the target, overwriting the value in the target.
 * The expectation is that the changes will be manually reviewed before
 * committing them.
 */
public class BackportEnglish {

    private static final Map<String,Properties> sourceTranslations = new HashMap<>();
    private static final Map<String,Properties> targetTranslations = new HashMap<>();

    public static void main(String... args) throws IOException {
        if (args.length != 1) {
            throw new IllegalArgumentException("Missing back-port target");
        }
        File targetRoot = new File(args[0]);

        if (!targetRoot.isDirectory()) {
            throw new IllegalArgumentException("Back-port target not a directory");
        }

        File sourceRoot = new File(".");
        for (String dir : Constants.SEARCH_DIRS) {
            File directory = new File(dir);
            Utils.processDirectory(sourceRoot, directory, sourceTranslations);
        }

        for (String dir : Constants.SEARCH_DIRS) {
            File directory = new File(targetRoot, dir);
            Utils.processDirectory(targetRoot, directory, targetTranslations);
        }

        Properties sourceEnglish = sourceTranslations.get("");
        Properties targetEnglish = targetTranslations.get("");

        for (Object key : sourceEnglish.keySet()) {
            if (targetEnglish.containsKey(key)) {
                targetEnglish.put(key, sourceEnglish.get(key));
            }
        }

        File storageDir = new File(targetRoot, Constants.STORAGE_DIR);

        Utils.export("", targetEnglish, storageDir);
    }
}

Add a tool for back-porting English translations


package openmods.liquids;

import javax.annotation.Nullable;
import net.minecraft.item.ItemStack;
import net.minecraftforge.fluids.Fluid;
import net.minecraftforge.fluids.FluidRegistry;
import net.minecraftforge.fluids.FluidStack;
import net.minecraftforge.fluids.capability.FluidTankProperties;
import net.minecraftforge.fluids.capability.IFluidHandler;
import net.minecraftforge.fluids.capability.IFluidTankProperties;

public class SingleFluidBucketHandler implements IFluidHandler {

	private final ItemStack container;

	private final int volume;

	private final Fluid fluid;

	private final ItemStack emptyContainer;

	private final FluidStack contents;

	private final IFluidTankProperties properties;

	public SingleFluidBucketHandler(ItemStack container, String fluidId, int volume, ItemStack emptyContainer) {
		this.container = container;
		this.fluid = FluidRegistry.getFluid(fluidId);
		this.volume = volume;
		this.emptyContainer = emptyContainer.copy();

		this.contents = new FluidStack(fluid, volume);
		this.properties = new FluidTankProperties(contents, volume);
	}

	@Override
	public IFluidTankProperties[] getTankProperties() {
		return new IFluidTankProperties[] { properties };
	}

	@Override
	public int fill(FluidStack resource, boolean doFill) {
		return 0;
	}

	protected void switchToEmptyBucket() {
		container.deserializeNBT(emptyContainer.serializeNBT());
	}

	@Override
	@Nullable
	public FluidStack drain(FluidStack resource, boolean doDrain) {
		if (container.stackSize != 1 || resource == null || resource.amount < volume)
			return null;

		if (resource.getFluid() == fluid)
			if (doDrain)
				switchToEmptyBucket();

		return contents;
	}

	@Override
	@Nullable
	public FluidStack drain(int maxDrain, boolean doDrain) {
		if (container.stackSize != 1 || maxDrain < Fluid.BUCKET_VOLUME)
			return null;

		if (doDrain)
			switchToEmptyBucket();

		return contents;
	}

}

Add IFluidHandler for simple bucket items


package online.pizzacrust.lukkitplus;

import org.bukkit.ChatColor;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;

import online.pizzacrust.lukkitplus.api.LuaPlugin;
import online.pizzacrust.lukkitplus.environment.Environment;

public class CommandPluginList implements CommandExecutor {
    @Override
    public boolean onCommand(CommandSender commandSender, Command command, String s, String[] strings) {
        if (command.getName().equals("plugins")) {
            if (!commandSender.hasPermission("lukkitplus.listpl")) {
                commandSender.sendMessage(ChatColor.RED + "Sorry, you don't have permission.");
                return true;
            }
            StringBuilder pluginSentence = new StringBuilder();
            int index = 0;
            for (LuaPlugin plugin : Environment.PLUGINS) {
                if (index != (Environment.PLUGINS.size() - 1)) {
                    pluginSentence.append(plugin.getName() + ", ");
                } else {
                    pluginSentence.append(plugin.getName() + "");
                }
                index++;
            }
            commandSender.sendMessage("Plugins: " + ChatColor.GREEN + pluginSentence.toString());
            return true;
        }
        return false;
    }
}

Make the plugin list command


package de.teiesti.postie;

import org.pmw.tinylog.Logger;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Set;

public class Office {

	private ServerSocket serverSocket;

	private Postman blueprint;

	private Set<Postman> postmen;

	private Thread acceptor;

	public Office bind(ServerSocket socket) {
		// FIXME
		return this;
	}

	public Office spawn(Postman blueprint) {
		// FIXME
		return this;
	}

	public Office start() {
		acceptor = new Acceptor();
		acceptor.start();

		return this;
	}

	public Office stop() {
		// FIXME how to do this?
		return this;
	}

	private class Acceptor extends Thread {

	 	@Override
		public void run() {
			Socket socket;
			Postman postman;
			while (!isInterrupted()) {
				try {
					socket = serverSocket.accept();
					postman = blueprint.clone().bind(socket).start();
					postmen.add(postman);
				} catch (IOException e) {
					Logger.error(e);
					System.exit(1);
				}
			}

		}

	}

}

Revert "Prepare for the 0.2.0 release."


package guitests;

//@@author A0125221Y
import static org.junit.Assert.assertTrue;

import org.junit.Test;

import seedu.address.testutil.TestTask;
import seedu.address.testutil.TestUtil;

public class UndoCommandTest extends AddressBookGuiTest{

	@Test
	public void undoWithOneModification_Success(){

		TestTask[] currentList = td.getTypicalTasks();

		//Begin by adding one task
		TestTask taskToAdd = td.hoon;
		commandBox.runCommand(taskToAdd.getAddCommand());
		assertListSize(currentList.length + 1);

		//Next undo the previous add command
		commandBox.runCommand("undo");
		assertListSize(currentList.length);
		assertTrue(taskListPanel.isListMatching(currentList));

		//Now test deletion of one single task
		commandBox.runCommand("delete 1");
		assertListSize(currentList.length - 1);
		currentList = TestUtil.removeTaskFromList(currentList, 1);

		//Try to undo the previous delete command
		commandBox.runCommand("undo");
		currentList = TestUtil.addTasksToListAtIndex(currentList, 0, td.alice);
		assertListSize(currentList.length);
		assertTrue(taskListPanel.isListMatching(currentList));

	}

}

Test cases for Undo Command


package week_of_code_30;

import java.util.Scanner;

public class FindTheMinimumNumber {

  private static String findMin(int n) {
    return findMin(0, n);
  }

  private static String findMin(int i, int n) {
    StringBuilder builder = new StringBuilder();
    if (i == n - 1) {
      return "int";
    } else {
      builder.append("min(int, ").append(findMin(i + 1, n)).append(")");
      return builder.toString();
    }
  }

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

Add solution for another Easy problem week of code 30


package com.nexmo.quickstart.voice;

import com.nexmo.client.NexmoClient;
import com.nexmo.client.auth.AuthMethod;
import com.nexmo.client.auth.JWTAuthMethod;
import com.nexmo.client.voice.Call;
import com.nexmo.client.voice.CallEvent;

import java.nio.file.FileSystems;

import static com.nexmo.quickstart.Util.configureLogging;
import static com.nexmo.quickstart.Util.envVar;

public class SendTalkToCall {
    public static void main(String[] args) throws Exception {
        configureLogging();

        String APPLICATION_ID = envVar("APPLICATION_ID");
        String PRIVATE_KEY = envVar("PRIVATE_KEY");
        String FROM_NUMBER = envVar("FROM_NUMBER");
        String TO_NUMBER = envVar("TO_NUMBER");

        AuthMethod auth = new JWTAuthMethod(
                APPLICATION_ID,
                FileSystems.getDefault().getPath(PRIVATE_KEY)
        );
        NexmoClient client = new NexmoClient(auth);
        CallEvent call = client.getVoiceClient().createCall(new Call(
                TO_NUMBER,
                FROM_NUMBER,
                "https://gist.githubusercontent.com/ChrisGuzman/d6add5b23a8cf913dcdc5a8eabc223ef/raw/a1eb52e0ce2d3cef98bab14d27f3adcdff2af881/long_talk.json"
        ));

        Thread.sleep(20000);

        client.getVoiceClient().startTalk(call.getUuid(), "Hello World! Would you like to know more? I bet you would", 0);
        Thread.sleep(5000);
        client.getVoiceClient().stopTalk(call.getUuid());
    }
}

Add Talk example for Voice API


/*
 * Zorbage: an algebraic data hierarchy for use in numeric processing.
 *
 * Copyright (C) 2016-2019 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.algorithm;

import static org.junit.Assert.assertEquals;

import org.junit.Test;

import nom.bdezonia.zorbage.algebras.G;
import nom.bdezonia.zorbage.type.data.float64.real.Float64Member;
import nom.bdezonia.zorbage.type.storage.array.ArrayStorage;
import nom.bdezonia.zorbage.type.storage.datasource.IndexedDataSource;

/**
 *
 * @author Barry DeZonia
 *
 */
public class TestNonNanValues {

	@Test
	public void test1() {

		Float64Member value = G.DBL.construct();

		IndexedDataSource<Float64Member> nums = ArrayStorage.allocateDoubles(
				new double[] {1,Double.NaN, 2, 3, Double.NaN, Double.NaN, 4, Double.NaN, Double.NaN, Double.NaN});

		IndexedDataSource<Float64Member> nonnan = NonNanValues.compute(G.DBL, nums);

		assertEquals(10, nums.size());
		assertEquals(4, nonnan.size());
		nonnan.get(0, value);
		assertEquals(1, value.v(), 0);
		nonnan.get(1, value);
		assertEquals(2, value.v(), 0);
		nonnan.get(2, value);
		assertEquals(3, value.v(), 0);
		nonnan.get(3, value);
		assertEquals(4, value.v(), 0);
	}
}

Define a test for the NonNanValues algorithm


/*
 * 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.harmony.text.tests.java.text;

import java.text.DateFormat;
import java.text.ParseException;

@SuppressWarnings("nls")
public class ParseExceptionTest extends junit.framework.TestCase {

    /**
     * @tests java.text.ParseException#ParseException(java.lang.String, int)
     */
    public void test_ConstructorLjava_lang_StringI() {
        try {
            DateFormat df = DateFormat.getInstance();
            df.parse("HelloWorld");
            fail("ParseException not created/thrown.");
        } catch (ParseException e) {
            // expected
        }
    }

    /**
     * @tests java.text.ParseException#getErrorOffset()
     */
    public void test_getErrorOffset() {
        try {
            DateFormat df = DateFormat.getInstance();
            df.parse("1999HelloWorld");
        } catch (ParseException e) {
            assertEquals("getErrorOffsetFailed.", 4, e.getErrorOffset());
        }
    }
}

Test case tidy-up, no functional changes.


package com.genymobile.pr.bus;

import com.genymobile.pr.model.Issue;

public class IssueRetrievedEvent {

    public IssueRetrievedEvent(Issue issue) {
        this.issue = issue;
    }

    private Issue issue;

    public Issue getIssue() {
        return issue;
    }
}

Add the event for the IssueRetrieved


package net.craftstars.general.money;

import net.craftstars.general.General;

import org.bukkit.entity.Player;
import org.bukkit.plugin.Plugin;

public class iConomyEconomyHandler implements EconomyBase {
	EconomyBase actualEconomy;
	boolean wasLoaded;

	public iConomyEconomyHandler() {
		Plugin test = General.plugin.getServer().getPluginManager().getPlugin("iConomy");

		if(test != null) {
			String versionString = test.getDescription().getVersion();
			String majorRev = versionString.substring(0, versionString.indexOf('.'));
			int version = Integer.valueOf(majorRev);
			if(version < 5) {
				actualEconomy = new iConomy4EconomyHandler();
				wasLoaded = actualEconomy.wasLoaded();
			} else if(version < 6) {
				actualEconomy = new iConomy5EconomyHandler();
				wasLoaded = actualEconomy.wasLoaded();
			}
		} else wasLoaded = false;
	}

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

	@Override
	public String getVersion() {
		return actualEconomy.getVersion();
	}

	@Override
	public String getName() {
		return actualEconomy.getName();
	}

	@Override
	public double getBalance(Player who) {
		return actualEconomy.getBalance(who);
	}

	@Override
	public String getBalanceForDisplay(Player who) {
		return actualEconomy.getBalanceForDisplay(who);
	}

	@Override
	public String formatCost(double amount) {
		return actualEconomy.formatCost(amount);
	}

	@Override
	public boolean takePayment(Player fromWhom, double amount) {
		return actualEconomy.takePayment(fromWhom, amount);
	}

	@Override
	public void givePayment(Player toWhom, double amount) {
		actualEconomy.givePayment(toWhom, amount);
	}

	@Override
	public String getCurrency() {
		return actualEconomy.getCurrency();
	}

}

Add an iConomy handler that automatically detects the version. More intuitive, no?


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

package io.github.bonigarcia.wdm.test;

import static java.lang.Thread.sleep;
import static java.util.concurrent.TimeUnit.SECONDS;

import org.junit.After;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;

import io.github.bonigarcia.wdm.ChromeDriverManager;

/**
 * WebRTC test with Chrome.
 *
 * @author Boni Garcia (boni.gg@gmail.com)
 * @since 1.0.0
 */
public class WebRtcTest {

    private WebDriver driver;

    @BeforeClass
    public static void setupClass() {
        ChromeDriverManager.getInstance().setup();
    }

    @Before
    public void setupTest() {
        ChromeOptions options = new ChromeOptions();
        // This flag avoids to grant the user media
        options.addArguments("--use-fake-ui-for-media-stream");

        // This flag fakes user media with synthetic video (green with spinner
        // and timer)
        options.addArguments("--use-fake-device-for-media-stream");
        driver = new ChromeDriver(options);
    }

    @After
    public void teardown() {
        if (driver != null) {
            driver.quit();
        }
    }

    @Test
    public void test() throws InterruptedException {
        // Test data
        int timeout = 30;
        String sutUrl = "http://localhost:8080";

        // Implicit timeout
        driver.manage().timeouts().implicitlyWait(timeout, SECONDS);
        driver.manage().timeouts().implicitlyWait(timeout, SECONDS);

        // Open page
        driver.get(sutUrl);

        // Wait 5 seconds
        sleep(5000);
    }

}

Add example test for WebRTC and Chrome


package tools.vitruv.framework.correspondence;

/**
 * Generic interface for factories generating {@link CorrespondenceModelView}s
 * for special correspondence types.
 *
 * @author Heiko Klare
 *
 */
public interface CorrespondenceModelViewFactory<T extends CorrespondenceModelView<?>> {
	public T createCorrespondenceModelView(InternalCorrespondenceModel correspondenceModel);
	public T createEditableCorrespondenceModelView(InternalCorrespondenceModel correspondenceModel);
}

Add factory for creating specific correspondence model views


package io.github.classgraph.issues.issue350;

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

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

import org.junit.Test;

import io.github.classgraph.ClassGraph;
import io.github.classgraph.ScanResult;

/**
 * Unit test.
 */
public class Issue350 {
    /** */
    @Retention(RetentionPolicy.RUNTIME)
    public static @interface SuperclassAnnotation {
    }

    /** */
    public static class Pub {
        /** */
        @SuperclassAnnotation
        public int annotatedPublicField;

        /** */
        @SuperclassAnnotation
        public void annotatedPublicMethod() {
        }
    }

    /** */
    public static class Priv {
        /** */
        @SuperclassAnnotation
        private int annotatedPrivateField;

        /** */
        @SuperclassAnnotation
        private void annotatedPrivateMethod() {
        }
    }

    /** */
    public static class PubSub extends Pub {
    }

    /** */
    public static class PrivSub extends Priv {
    }

    /** Test finding subclasses of classes with annotated methods or fields. */
    @Test
    public void test() {
        try (ScanResult scanResult = new ClassGraph().whitelistPackages(Issue350.class.getPackage().getName())
                .enableClassInfo().enableFieldInfo().enableMethodInfo().enableAnnotationInfo().scan()) {
            assertThat(scanResult.getClassesWithFieldAnnotation(SuperclassAnnotation.class.getName()).getNames())
                    .containsExactlyInAnyOrder(Pub.class.getName(), PubSub.class.getName());
            assertThat(scanResult.getClassesWithMethodAnnotation(SuperclassAnnotation.class.getName()).getNames())
                    .containsExactlyInAnyOrder(Pub.class.getName(), PubSub.class.getName());
        }
        try (ScanResult scanResult = new ClassGraph().whitelistPackages(Issue350.class.getPackage().getName())
                .enableClassInfo().enableFieldInfo().enableMethodInfo().enableAnnotationInfo()
                .ignoreFieldVisibility().ignoreMethodVisibility().scan()) {
            assertThat(scanResult.getClassesWithFieldAnnotation(SuperclassAnnotation.class.getName()).getNames())
                    .containsExactlyInAnyOrder(Pub.class.getName(), PubSub.class.getName(), Priv.class.getName());
            assertThat(scanResult.getClassesWithMethodAnnotation(SuperclassAnnotation.class.getName()).getNames())
                    .containsExactlyInAnyOrder(Pub.class.getName(), PubSub.class.getName(), Priv.class.getName());
        }
    }
}

Add unit test for 350


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

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.vertx.core.json.JsonObject;
import net.kuujo.vertigo.VertigoException;

import java.io.IOException;

/**
 * JSON utilities.
 *
 * @author Jordan Halterman
 */
public final class Json {
  private static final ObjectMapper mapper = new ObjectMapper();

  /**
   * JSON serializable interface.
   */
  @JsonIgnoreProperties(ignoreUnknown=true)
  @JsonInclude(JsonInclude.Include.ALWAYS)
  @JsonAutoDetect(
    creatorVisibility= JsonAutoDetect.Visibility.NONE,
    fieldVisibility=JsonAutoDetect.Visibility.ANY,
    getterVisibility=JsonAutoDetect.Visibility.NONE,
    isGetterVisibility=JsonAutoDetect.Visibility.NONE,
    setterVisibility=JsonAutoDetect.Visibility.NONE
  )
  public static interface Serializable {
  }

  /**
   * Serializes an object to JSON.
   *
   * @param object The object to serialize.
   * @param <T> The serializable type.
   * @return The serialized object.
   */
  public static <T extends Json.Serializable> JsonObject serialize(T object) {
    try {
      return new JsonObject(mapper.writeValueAsString(object));
    } catch (IOException e) {
      throw new VertigoException(e);
    }
  }

  /**
   * Deserializes an object from JSON.
   *
   * @param json The JSON from which to deserialize the object.
   * @param type The object type to deserialize.
   * @param <T> The deserialized object type.
   * @return The deserialized object.
   */
  public static <T extends Json.Serializable> T deserialize(JsonObject json, Class<T> type) {
    try {
      return mapper.readValue(json.encode(), type);
    } catch (IOException e) {
      throw new VertigoException(e);
    }
  }

}

Add JSON serializion support for definitions and contexts.


package com.google.sps.servlets;

import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceConfig;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.EntityNotFoundException;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseAuthException;
import com.google.firebase.auth.FirebaseToken;
import com.google.gson.Gson;
import com.google.sps.firebase.FirebaseAppManager;
import java.io.IOException;
import java.util.ArrayList;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/check-student")
public class CheckStudentStatus extends HttpServlet {
  FirebaseAuth authInstance;
  DatastoreService datastore;

  @Override
  public void init(ServletConfig config) throws ServletException {
    try {
      authInstance = FirebaseAuth.getInstance(FirebaseAppManager.getApp());

      datastore = DatastoreServiceFactory.getDatastoreService();
      System.setProperty(
          DatastoreServiceConfig.DATASTORE_EMPTY_LIST_SUPPORT, Boolean.TRUE.toString());
    } catch (IOException e) {
      throw new ServletException(e);
    }
  }

  @Override
  public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
    try {
      // Find user ID
      String idToken = request.getParameter("userToken");
      FirebaseToken decodedToken = authInstance.verifyIdToken(idToken);
      String uID = decodedToken.getUid();

      // Retrive entity
      String classCode = request.getParameter("classCode").trim();
      Key classKey = KeyFactory.stringToKey(classCode);
      Entity classEntity = datastore.get(classKey);

      // Find position in queue
      ArrayList<String> queue = (ArrayList) classEntity.getProperty("studentQueue");
      String pos = Integer.toString(queue.indexOf(uID));

      Gson gson = new Gson();
      response.setContentType("application/json;");
      response.getWriter().println(gson.toJson(pos));

    } catch (EntityNotFoundException e) {
      response.sendError(HttpServletResponse.SC_NOT_FOUND);
    } catch (IllegalArgumentException e) {
      response.sendError(HttpServletResponse.SC_BAD_REQUEST);
    } catch (FirebaseAuthException e) {
      response.sendError(HttpServletResponse.SC_FORBIDDEN);
    }
  }
}

Create servlet that returns student position on queue


package com.minelittlepony.settings;

import com.minelittlepony.common.client.gui.IField.IChangeCallback;

/**
 * A sensible config container that actually lets us programmatically index values by a key.
 *
 * Reflection because Mumfrey pls.
 *
 */
// Mumfrey pls.
public abstract class SensibleConfig {

    private static SensibleConfig instance;

    public SensibleConfig() {
        instance = this;
    }

    public abstract void save();

    public interface Setting extends IChangeCallback<Boolean> {
        String name();

        /**
         * Gets the config value associated with this entry.
         */
        default boolean get() {
            return instance.getValue(this);
        }

        /**
         * Sets the config value associated with this entry.
         */
        default void set(boolean value) {
            instance.setValue(this, value);
        }

        @Override
        default Boolean perform(Boolean v) {
            set(v);
            return v;
        }
    }

    public boolean getValue(Setting key) {
        try {
            return getClass().getField(key.name().toLowerCase()).getBoolean(this);
        } catch (IllegalArgumentException | IllegalAccessException | NoSuchFieldException | SecurityException ignored) {
            return true;
        }
    }

    public boolean setValue(Setting key, boolean value) {
        try {
            getClass().getField(key.name().toLowerCase()).setBoolean(this, value);
        } catch (IllegalArgumentException | IllegalAccessException | NoSuchFieldException | SecurityException ignored) {
        }
        return value;
    }
}

Move sensibleConfig back into MineLP. This was a mistake. The static makes it less useful to other projects


package io.sigpipe.sing.stat;

import io.sigpipe.sing.serialization.ByteSerializable;
import io.sigpipe.sing.serialization.SerializationInputStream;
import io.sigpipe.sing.serialization.SerializationOutputStream;

public class SerializableReservoir<T extends ByteSerializable>
extends Reservoir<T> implements ByteSerializable {

    @Deserialize
    public SerializableReservoir(SerializationInputStream in) {
        super(0);
    }

    @Override
    public void serialize(SerializationOutputStream out) {

    }
}

Add stub for serializable reservoir


package com.jmb.springfactory.model.bo;

import java.util.Date;

import com.jmb.springfactory.model.enumeration.TaskStatusEnum;

import lombok.Builder;
import lombok.Data;

@Data
@Builder
public class QueryTaskObject {

  private String name;
  private TaskStatusEnum status;
  private Date startDate;
  private Date finishDate;
  private String priority;
  private String creator;
}

Create a class to pass all parameter to search tasks


/*
 * Copyright 2010 Ning, Inc.
 *
 * Ning 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 com.ning.http.client.async;

import com.ning.http.client.AsyncHandler;
import com.ning.http.client.AsyncHttpClient;
import com.ning.http.client.AsyncHttpClientConfig;
import com.ning.http.client.HttpResponseBodyPart;
import com.ning.http.client.HttpResponseHeaders;
import com.ning.http.client.HttpResponseStatus;
import org.testng.annotations.Test;

import java.io.IOException;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeoutException;

/**
 * Simple stress test for exercising the follow redirect.
 */
public class FollowingThreadTest extends AbstractBasicTest {

    private final static int COUNT = 10;

    @Test(timeOut = 30 * 1000, groups = "scalability")
    public void testFollowRedirect() throws IOException, ExecutionException, TimeoutException, InterruptedException {

        final CountDownLatch countDown = new CountDownLatch(COUNT);
        ExecutorService pool = Executors.newCachedThreadPool();
        for (int i = 0; i < COUNT; i++) {
            pool.submit(new Runnable() {

                private int status;

                public void run() {
                    final CountDownLatch l = new CountDownLatch(1);
                    AsyncHttpClient ahc = new AsyncHttpClient(
                            new AsyncHttpClientConfig.Builder().setFollowRedirects(true).build());
                    try {
                        ahc.prepareGet("http://www.google.com/").execute(new AsyncHandler<Integer>() {

                            public void onThrowable(Throwable t) {
                                t.printStackTrace();
                            }

                            public STATE onBodyPartReceived(HttpResponseBodyPart bodyPart) throws Exception {
                                System.out.println(new String(bodyPart.getBodyPartBytes()));
                                return STATE.CONTINUE;
                            }

                            public STATE onStatusReceived(HttpResponseStatus responseStatus) throws Exception {
                                status = responseStatus.getStatusCode();
                                System.out.println(responseStatus.getStatusText());
                                return STATE.CONTINUE;
                            }

                            public STATE onHeadersReceived(HttpResponseHeaders headers) throws Exception {
                                return STATE.CONTINUE;
                            }

                            public Integer onCompleted() throws Exception {
                                l.countDown();
                                return status;
                            }
                        });

                        l.await();
                    } catch (Exception e) {
                        e.printStackTrace();
                    } finally {
                        ahc.close();
                        countDown.countDown();
                    }
                }
            });
        }
        countDown.await();
    }

}

Add a unit test trying to reproduce the issue related on the mailling list


/*
 * The MIT License (MIT)
 *
 * Copyright (c) 2015 Lachlan Dowding
 *
 * 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 permafrost.tundra.data;

import org.junit.Test;

import static org.junit.Assert.*;

public class IDataComparisonTypeTest {

    @Test
    public void testNormalizeNullString() throws Exception {
        IDataComparisonType type = IDataComparisonType.normalize((String)null);
        assertEquals(IDataComparisonType.DEFAULT_COMPARISON_TYPE, type);
    }

    @Test
    public void testNormalizeLowercaseString() throws Exception {
        IDataComparisonType type = IDataComparisonType.normalize("string");
        assertEquals(IDataComparisonType.STRING, type);
    }

    @Test
    public void testNormalizeStringWithLeadingWhitespace() throws Exception {
        IDataComparisonType type = IDataComparisonType.normalize("  string");
        assertEquals(IDataComparisonType.STRING, type);
    }

    @Test
    public void testNormalizeNullType() throws Exception {
        IDataComparisonType type = IDataComparisonType.normalize((IDataComparisonType)null);
        assertEquals(IDataComparisonType.DEFAULT_COMPARISON_TYPE, type);
    }

    @Test
    public void testNormalizeNonNullType() throws Exception {
        IDataComparisonType type = IDataComparisonType.normalize(IDataComparisonType.DATETIME);
        assertEquals(IDataComparisonType.DATETIME, type);
    }
}

Add unit tests for IDataComparisonType


/*
 * Copyright 2006 ProductiveMe Inc.
 * Copyright 2013 JetBrains s.r.o.
 *
 * 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.pme.exe.res.vi;

import com.pme.exe.Bin;

public class StringTable extends VersionInfoBin {

  public StringTable(String name) {
    super(name, null, new VersionInfoFactory() {
      @Override
      public VersionInfoBin createChild(int index) {
        return new StringTableEntry();
      }
    });
  }

  public void setStringValue(String key, String value) {
    for (Bin bin : getMembers()) {
      if (bin.getName().equals(key)) {
        StringTableEntry entry = (StringTableEntry) bin;
        ((WChar) entry.getMember("Value")).setValue(value);
        ((Word) entry.getMember("wValueLength")).setValue(value.length() + 1);
        return;
      }
    }
    assert false: "Could not find string with key " + key;
  }
}

/*
 * Copyright 2006 ProductiveMe Inc.
 * Copyright 2013 JetBrains s.r.o.
 *
 * 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.pme.exe.res.vi;

import com.pme.exe.Bin;

public class StringTable extends VersionInfoBin {

  public StringTable(String name) {
    super(name, null, new VersionInfoFactory() {
      @Override
      public VersionInfoBin createChild(int index) {
        return new StringTableEntry();
      }
    });
  }

  public void setStringValue(String key, String value) {
    for (Bin bin : getMembers()) {
      if (bin.getName().equals(key)) {
        StringTableEntry entry = (StringTableEntry) bin;
        ((WChar) entry.getMember("Value")).setValue(value);
        ((Word) entry.getMember("wValueLength")).setValue(value.length());
        return;
      }
    }
    assert false: "Could not find string with key " + key;
  }
}

Correct length in exe resource string tables the change done by Matt Ellis (citizenmatt)


package data;

import static org.junit.Assert.assertSame;

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

import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;

import org.omg.CORBA.StringHolder;

@RunWith(Parameterized.class)
public class MemberValidatorEmailTest {

	String email;
	boolean expected;
	StringHolder messageHolder = new StringHolder();

	public MemberValidatorEmailTest(boolean expected, String email) {
		this.email = email;
		this.expected = expected;
	}

	@Parameters
	public static List<Object[]> getParams() {
		return Arrays.asList(new Object[][]{
				// Null or Empty are valid for us, might not be for you.
				{true, null },
				{true, "" },
				// From short to long, roughly
				{true, "a@b.co"},
				{false, "a at b.co" },
				{true, "a.b.c@d.e.f.com"},
				{true, "ketchup@mcdonalds.infomaterial"},
				{false, "a-b@c.com"},
		});
	}

	@Test
	public void test() {
		assertSame(expected, MemberHome.validateEmail(email, messageHolder));
	}

}

Bring in the email validation test too.


package chapter_5;

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.collection.IsIterableContainingInOrder.contains;

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

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

import datastructures.util.InputUtil;

public class TestDrawLine {
  private static String basePath = "input_files/chapter_5/draw_line/";
  private static String[] testCases = new String[] { "test_case_1", "test_case_2", "test_case_3", "test_case_4" };
  private static DrawLine drawLine;
  private static List<String[]> inputList = new ArrayList<String[]>();

  @BeforeClass
  public static void setup() {
    drawLine = new DrawLine();
    for (String testCase : testCases) {
      String inputFile = basePath + testCase;
      inputList.add(InputUtil.readContents(inputFile));
    }
  }

  @AfterClass
  public static void teardown() {
    drawLine = null;
    inputList = null;
  }

  @Test
  public void testDrawLineTestCase1() {
    assertDrawLine(inputList.get(0));
  }

  @Test
  public void testDrawLineTestCase2() {
    assertDrawLine(inputList.get(1));
  }

  @Test
  public void testDrawLineTestCase3() {
    assertDrawLine(inputList.get(2));
  }

  @Test
  public void testDrawLineTestCase4() {
    assertDrawLine(inputList.get(3));
  }

  private void assertDrawLine(String[] input) {
    String[] values = input[0].split(" ");
    int i = 2;
    int width = Integer.parseInt(values[0]);
    int x1 = Integer.parseInt(values[1]);
    int x2 = Integer.parseInt(values[2]);
    int y = Integer.parseInt(values[3]);

    byte[] screen = new byte[Integer.parseInt(input[1])];
    readByteArray(i, input, width, screen);

    byte[] output = new byte[screen.length];
    readByteArray(i + ((screen.length * 8) / width) + 1, input, width, output);

    assertThat(Arrays.asList(output), contains(drawLine.drawLine(screen, width, x1, x2, y)));
  }

  private void readByteArray(int i, String[] input, int width, byte[] screen) {
    int j = 0;
    String line = "";
    while (!(line = input[i]).equals("---")) {
      int start = 0, end = 8;
      while (end <= width && j < screen.length) {
        screen[j] = (byte) Integer.parseInt(line.substring(start, end), 2);
        start += 8;
        end += 8;
        j++;
      }
      i++;
    }
  }
}

Add Test runner for DrawLine, TODO: Cleanup


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

package com.dtolabs.rundeck.core;

import org.apache.tools.ant.BuildException;

/**
 * CoreException, base exception class for the core framework
 */
public class CoreException extends BuildException {
    public CoreException(final String msg) {
        super(msg);
    }

    public CoreException(final String msg, final Throwable e) {
        super(msg, e);
    }

    public CoreException(final Throwable e) {
        super(e.getMessage(), e);
    }
}

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

package com.dtolabs.rundeck.core;

/**
 * CoreException, base exception class for the core framework
 */
public class CoreException extends RuntimeException {
    public CoreException(final String msg) {
        super(msg);
    }

    public CoreException(final String msg, final Throwable e) {
        super(msg, e);
    }

    public CoreException(final Throwable e) {
        super(e.getMessage(), e);
    }
}

Change to extend RTE not ant exception


/*
 * Copyright 2016 EuregJUG.
 *
 * 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 eu.euregjug.site.events;

import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertThat;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import org.springframework.context.MessageSource;
import org.springframework.mail.javamail.JavaMailSender;

/**
 * @author Michael J. Simons, 2016-08-26
 */
@RunWith(MockitoJUnitRunner.class)
public class RegistrationServiceTest {

    @Mock
    private EventRepository eventRepository;

    @Mock
    private RegistrationRepository registrationRepository;

    @Mock
    private JavaMailSender mailSender;

    @Mock
    private MessageSource messageSource;

    @Test
    public void htmlTextToPlainTextShouldWork() {
        final RegistrationService service = new RegistrationService(eventRepository, registrationRepository, mailSender, null, messageSource, "info@euregjug.eu");
        final String plainText = service.htmlTextToPlainText("Hallo
das ist ein
test.
Auf wiedersehen.");
        assertThat(plainText, is("Hallo\ndas ist ein\ntest.\nAuf wiedersehen."));
    }

}

Add a test for htmlTextToPlainText


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

import dr.evomodel.newtreelikelihood.GeneralLikelihoodCore;

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

	public static LikelihoodCore getLikelihoodCore(int stateCount) {

		return new GeneralLikelihoodCore(stateCount);
	}

}

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


package com.ljs.ai.search.hillclimbing;

import com.google.common.base.Predicate;
import com.google.common.base.Predicates;

/**
 *
 * @author lstephen
 */
public final class Validators {

    public static <S> Validator<S> alwaysTrue() {
        return from(Predicates.<S>alwaysTrue());
    }

    private static <S> Validator<S> from(Predicate<S> predicate) {
        return new PredicateValidator<S>(predicate);
    }

    private static final class PredicateValidator<S> implements Validator<S> {

        private final Predicate<S> predicate;

        public PredicateValidator(Predicate<S> predicate) {
            this.predicate = predicate;
        }

        public Boolean apply(S state) {
            return predicate.apply(state);
        }
    }

}

Add some helpful construction functions


package com.skcraft.plume.module.perf;

import com.sk89q.intake.Command;
import com.sk89q.intake.Require;
import com.skcraft.plume.command.Sender;
import com.skcraft.plume.common.util.module.Module;
import com.skcraft.plume.util.Messages;
import net.minecraft.command.ICommandSender;
import net.minecraft.entity.Entity;
import net.minecraft.entity.monster.EntityMob;
import net.minecraft.entity.passive.EntityAnimal;
import net.minecraft.server.MinecraftServer;
import net.minecraft.world.World;

import static com.skcraft.plume.common.util.SharedLocale.tr;

@Module(name = "mob-commands", desc = "Commands to work with the number of mobs")
public class MobCommands {

    @Command(aliases = "removemobs", desc = "Kill mobs")
    @Require("plume.removemobs")
    public void removeMobs(@Sender ICommandSender sender) {
        int removed = 0;
        for (World world : MinecraftServer.getServer().worldServers) {
            for (Object object : world.loadedEntityList) {
                Entity entity = (Entity) object;
                if (entity instanceof EntityAnimal || entity instanceof EntityMob) {
                    entity.setDead();
                    removed++;
                }
            }
        }

        sender.addChatMessage(Messages.info(tr("butcher.mobsRemoved", removed)));
    }

}

Add simple command to kill mobs of a certain type.


package leetcode;

/**
 * https://leetcode.com/problems/minimum-window-substring/
 */
public class Problem76 {
    public String minWindow(String s, String t) {
        // TODO
        return "";
    }

    public static void main(String[] args) {
        Problem76 prob = new Problem76();
        System.out.println(prob.minWindow("ADOBECODEBANC", "ABC")); // BANC
    }
}

Create a skeleton for problem 76


/**
 * @file Introductions.java
 * @author Valery Samovich
 * @version 1
 * @date 2015/04/07
 */

package com.samovich.basics.introduction;

/**
 * Created by Samovich on 4/7/2015.
 */
public class Introductions {
}

Add Introduction.java example from Team Treehouse Tutorial.


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

package com.cueup.hegemon;

import com.google.common.base.Charsets;
import com.google.common.io.Files;

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

/**
 * Simple script locator that just loads scripts under a sub-path.
 * This is useful for development environments.  For production code,
 * you almost certainly want ResourceScriptLocator.
 */
public class PathScriptLocator extends ScriptLocator {

  private final File root;

  /**
   * Creates a path locator with the given root path.
   * @param root the root path
   */
  public PathScriptLocator(String root) {
    this(new File(root));
  }

  /**
   * Creates a path locator with the given root path.
   * @param root the root path
   */
  public PathScriptLocator(File root) {
    this.root = root;
  }

  @Override
  public String getFile(String name) throws LoadError {
    File script = new File(this.root, name);
    try {
      if (script.getCanonicalPath().startsWith(this.root.getCanonicalPath())
          && script.exists()) {
        return Files.toString(script, Charsets.UTF_8);
      }
    } catch (IOException e) {
      throw new LoadError(e);
    }
    throw new LoadError("Could not find " + name + " under " + this.root);
  }

}

Add simple script locator that reads files from a path


package starpunk.services;

import com.badlogic.gdx.audio.Music;

public final class MusicReference
{
  private final String _filename;
  private Music _resource;

  public MusicReference( final String filename )
  {
    _filename = filename;
  }

  public String getFilename()
  {
    return _filename;
  }

  Music getResource()
  {
    return _resource;
  }

  void setResource( final Music resource )
  {
    _resource = resource;
  }
}

Add class representing a music resource