/*
 * Copyright (c) 2006-2014 DMDirc Developers
 *
 * 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 com.dmdirc.util.validators;

public class OptionalEmailAddressValidator extends EmailAddressValidator {

    @Override
    public ValidationResponse validate(final String object) {
        if (object == null || object.isEmpty()) {
            return new ValidationResponse();
        }
        return super.validate(object);
    }

}

Add Optional email address validator.


package com.nexmo.quickstart.voice;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.nexmo.client.NexmoClient;
import com.nexmo.client.auth.JWTAuthMethod;
import com.nexmo.client.voice.CallInfoPage;
import com.nexmo.client.voice.CallsFilter;

import java.nio.file.FileSystems;
import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;

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

public class RetrieveInfoForAllCalls {
    public static void main(String... args) throws Exception {
        configureLogging();

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

        NexmoClient nexmo = new NexmoClient(
                new JWTAuthMethod(APPLICATION_ID, FileSystems.getDefault().getPath(PRIVATE_KEY))
        );

        CallsFilter filter = new CallsFilter();
        filter.setDateStart(getYesterdaysDate());
        filter.setDateEnd(getTodaysDate());

        CallInfoPage calls = nexmo.getVoiceClient().listCalls(filter);
        System.out.println(
                new ObjectMapper().writer().writeValueAsString(calls)
        );
    }

    private static Date getTodaysDate() {
        return Calendar.getInstance(TimeZone.getTimeZone("UTC")).getTime();
    }

    private static Date getYesterdaysDate() {
        Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
        calendar.add(Calendar.DATE, -1);
        return calendar.getTime();
    }
}

Add retrieve info for all calls example.


/*
 * Copyright 2016 The Closure Compiler 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.google.javascript.jscomp;

/**
 * A warnings guard that suppresses warnings for a particular diagnostic group for a file that
 * contains the specified substring.
 * @author nicksantos@google.com (Nick Santos)
 */
public class DiagnosticGroupPathSuppressingWarningsGuard extends DiagnosticGroupWarningsGuard {
  private final String part;

  public DiagnosticGroupPathSuppressingWarningsGuard(DiagnosticGroup type, String part) {
    super(type, CheckLevel.OFF);
    this.part = part;
  }

  /** Does not suppress all warnings of any type. */
  @Override public boolean disables(DiagnosticGroup type) {
    return false;
  }

  /** Does not touch warnings in other paths. */
  @Override public CheckLevel level(JSError error) {
    return error.sourceName != null && error.sourceName.contains(part)
        ? super.level(error) /** suppress */
        : null /** proceed */;
  }

  @Override public String toString() {
    return super.toString() + "(" + part + ")";
  }
}

Make the warnings guard that allow suppressing specific groups by path public


package de.cinovo.cloudconductor.api.interfaces;

import java.util.Set;

import javax.annotation.security.RolesAllowed;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;

import de.cinovo.cloudconductor.api.MediaType;
import de.cinovo.cloudconductor.api.enums.UserPermissions;

/**
 * Copyright 2017 Cinovo AG

 *

 *
 * @author mweise
 */
@Path("/permission")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public interface IPermission {

	/**
	 * @return set of all possible permissions
	 */
	@GET
	@RolesAllowed({"VIEW_USERS", "EDIT_USERS"})
	Set<UserPermissions> getPermissions();

}

Add interface to get the names of all possible permissions.


package leveledit;

import java.util.ArrayList;

public class ArbitraryCode {
	/**
	 * You can write your own code here to generate patterns programmatically.
	 * Just return an array of patterns and the runtime will allow you to add
	 * it to the contents of the level patterns by typing r! */
	public static ArrayList<Pattern> runCode() {
		ArrayList<Pattern> patterns = new ArrayList<>();

		//Write code here

		return patterns;
	}
}

Allow the execution of arbitrary code in runtime.


package cucumber.demo;

public class Hello {
    public String greet(String who, String from) {
        return "Hi, " + who + ". I'm " + from;
    }

    public boolean isFriend(String who) {
        return true;
    }

    public String getPhoneNumber(String who) {
        return "99999";
    }
}

package cucumber.demo;

public class Hello {
    public String greet(String who, String from) {
        return "Hi, " + who + ". I'm " + from;
    }

    public boolean isFriend(String who) {
        return true;
    }

    public String getPhoneNumber(String who) {
        throw new RuntimeException("My phone is secret!");
    }
}

Make java example fail. More fun.


/*
 * 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.logging.log4j.jdk;

import java.util.logging.Level;

/**
 * Custom JUL Level for unit tests.
 */
public class CustomJdkLevel extends Level {

    private static final long serialVersionUID = 4681718777617726164L;

    protected CustomJdkLevel(final String name, final int value) {
        super(name, value);
    }

    // inside CONFIG range; should map to INFO
    public static final Level TEST = new CustomJdkLevel("TEST", 600);

    // just 1 below Level.SEVERE; should map to ERROR
    public static final Level DEFCON_2 = new CustomJdkLevel("DEFCON_2", 999);

    // above Level.SEVERE; should map to FATAL
    public static final Level DEFCON_1 = new CustomJdkLevel("DEFCON_1", 10000);
}

Add custom jul.Level for unit tests.


/*
 * Grapht, an open source dependency injector.
 * Copyright 2010-2012 Regents of the University of Minnesota and contributors
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as
 * published by the Free Software Foundation; either version 2.1 of the
 * License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
 * details.
 *
 * You should have received a copy of the GNU General Public License along with
 * this program; if not, write to the Free Software Foundation, Inc., 51
 * Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
 */
package org.grouplens.grapht;

import javax.inject.Named;

import org.grouplens.grapht.util.AnnotationBuilder;

/**
 * Names is a utility class to create {@link Named} annotation instances when
 * configuring an injector that relies on named qualifiers. Qualifiers with
 * other attributes can by instantiated using the {@link AnnotationBuilder}.
 *
 * @author Michael Ludwig <mludwig@cs.umn.edu>
 */
public class Names {
    /**
     * Get a Named annotation instance whose value equals the provided String.
     * The returned annotation is equal to annotations created by a declaration
     * matching: <code>@Named(name)</code>, where name is the input String.
     *
     * @param name The name value for the returned annotation
     * @return A Named instance wrapping the given name
     */
    public static Named named(String name) {
        return new AnnotationBuilder<Named>(Named.class)
            .set("value", name)
            .build();
    }
}

Add @Named utility class that wraps AnnotationBuilder.


package net.kencochrane.raven.servlet;

import mockit.Injectable;
import mockit.NonStrictExpectations;
import mockit.Tested;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.Test;

import javax.servlet.ServletRequest;
import javax.servlet.ServletRequestEvent;
import javax.servlet.http.HttpServletRequest;

import static mockit.Deencapsulation.getField;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.nullValue;

public class RavenServletRequestListenerTest {
    @Tested
    private RavenServletRequestListener ravenServletRequestListener = null;
    @Injectable
    private ServletRequestEvent mockServletRequestEvent = null;

    @AfterMethod
    public void tearDown() throws Exception {
        // Reset the threadLocal value
        ((ThreadLocal) getField(RavenServletRequestListener.class, "THREAD_REQUEST")).remove();
    }

    @Test
    public void requestListenerEmptyByDefault() throws Exception {
        assertThat(RavenServletRequestListener.getServletRequest(), is(nullValue()));
    }

    @Test
    public void requestListenerContainsTheCurrentRequest(@Injectable final HttpServletRequest mockHttpServletRequest)
            throws Exception {
        new NonStrictExpectations() {{
            mockServletRequestEvent.getServletRequest();
            result = mockHttpServletRequest;
        }};

        ravenServletRequestListener.requestInitialized(mockServletRequestEvent);

        assertThat(RavenServletRequestListener.getServletRequest(), is(mockHttpServletRequest));
    }

    @Test
    public void requestListenerDoesntWorkWithNonHttpRequests(@Injectable final ServletRequest mockServletRequest)
            throws Exception {
        new NonStrictExpectations() {{
            mockServletRequestEvent.getServletRequest();
            result = mockServletRequest;
        }};

        ravenServletRequestListener.requestInitialized(mockServletRequestEvent);

        assertThat(RavenServletRequestListener.getServletRequest(), is(nullValue()));
    }

    @Test
    public void requestListenerDestroyRemovesTheCurrentRequest(@Injectable final HttpServletRequest mockHttpServletRequest)
            throws Exception {
        new NonStrictExpectations() {{
            mockServletRequestEvent.getServletRequest();
            result = mockHttpServletRequest;
        }};
        ravenServletRequestListener.requestInitialized(mockServletRequestEvent);

        ravenServletRequestListener.requestDestroyed(mockServletRequestEvent);

        assertThat(RavenServletRequestListener.getServletRequest(), is(nullValue()));
    }

    @Test
    public void requestListenerSpecificToLocalThread(@Injectable final HttpServletRequest mockHttpServletRequest)
            throws Exception {
        new NonStrictExpectations() {{
            mockServletRequestEvent.getServletRequest();
            result = mockHttpServletRequest;
        }};

        new Thread(){
            @Override
            public void run() {
                ravenServletRequestListener.requestInitialized(mockServletRequestEvent);
            }
        }.start();

        assertThat(RavenServletRequestListener.getServletRequest(), is(nullValue()));
    }
}

Add test coverage for the ServletRequestListener


package io.github.xxyy.quietcord.filter;

import org.junit.Test;

import java.util.logging.Filter;
import java.util.logging.Level;
import java.util.logging.LogRecord;
import java.util.logging.Logger;

import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;

public class PropagatingFilterTest {

    public static final String ARBITRARY_TEXT = "arbitrary text";
    public static final String IGNORED_BY_A = "ignored by A";
    public static final String IGNORED_BY_B = "ignored by B";

    @Test
    public void testInject__alone() throws Exception {
        Logger logger = Logger.getLogger("testing");

        new PropagatingFilterA(logger).inject();

        Filter injected = logger.getFilter();

        assertThat("filter wrongly matched arbitrary message alone",
                injected.isLoggable(rec(ARBITRARY_TEXT)), is(true));

        assertThat("filter A didn't match ignored message alone",
                injected.isLoggable(rec(IGNORED_BY_A)), is(false));
    }

    @Test
    public void testInject__multiple() throws Exception {
        Logger logger = Logger.getLogger("testing");

        new PropagatingFilterA(logger).inject();
        new PropagatingFilterB(logger).inject();

        Filter injected = logger.getFilter();

        assertThat("filter wrongly matched arbitrary message multiple",
                injected.isLoggable(rec(ARBITRARY_TEXT)), is(true));

        assertThat("filter didn't match ignored message A multiple",
                injected.isLoggable(rec(IGNORED_BY_A)), is(false));

        assertThat("filter didn't match ignored message B multiple",
                injected.isLoggable(rec(IGNORED_BY_B)), is(false));
    }

    private LogRecord rec(String message) {
        return new LogRecord(Level.INFO, message);
    }

    private class PropagatingFilterA extends PropagatingFilter {
        protected PropagatingFilterA(Logger logger) {
            super(logger);
        }

        @Override
        public boolean isLoggable(LogRecord record) {
            return !record.getMessage().equals(IGNORED_BY_A);
        }
    }

    private class PropagatingFilterB extends PropagatingFilter {
        protected PropagatingFilterB(Logger logger) {
            super(logger);
        }

        @Override
        public boolean isLoggable(LogRecord record) {
            return !record.getMessage().equals(IGNORED_BY_B);
        }
    }
}

Add some tests for compound filter mechanics


package com.github.aureliano.achmed.resources;

import com.github.aureliano.achmed.resources.properties.IResourceProperties;

public interface IResource {

	public abstract void make(IResourceProperties properties);
}

Create interface to resource types.


package com.maraudersapp.android;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.text.InputType;
import android.util.Log;
import android.widget.EditText;

/**
 * Created by Michael on 10/28/2015.
 */
public class InputDialog extends AlertDialog.Builder {

    public interface OnTextEntered {
        public void onTextEntered(String text);
    }

    public InputDialog(Context ctx, String title, final OnTextEntered callback) {
        super(ctx);
        setTitle(title);
        final EditText input = new EditText(ctx);
        input.setInputType(InputType.TYPE_CLASS_TEXT);
        setView(input);
        setPositiveButton("Send", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                Log.i("Input dialog", "Text entered: " + input.getText().toString());
                callback.onTextEntered(input.getText().toString());
            }
        });
    }

}

Add create friends and groups


package nl.hsac.fitnesse.fixture.slim;

import fitnesse.testsystems.slim.results.SlimExceptionResult;
import org.junit.Test;

import static org.junit.Assert.*;

public class SlimFixtureExceptionTest {

    @Test
    public void testNoStackTrace() {
        SlimFixtureException e = new SlimFixtureException(false, "Hallo");
        SlimExceptionResult exceptionResult = new SlimExceptionResult("key", e.getMessage());
        assertTrue(exceptionResult.hasMessage());
        assertEquals("Hallo", exceptionResult.getMessage());
    }

    @Test
    public void testStackTrace() {
        SlimFixtureException e = new SlimFixtureException("Hallo");
        SlimExceptionResult exceptionResult = new SlimExceptionResult("key", e.getMessage());
        assertFalse(exceptionResult.hasMessage());
    }
}

Add test for exception escaping


/*
 * Copyright (c) 2016 Instituto Atlântico Development Company, L.P. and others. All rights reserved.
 *
 * This program and the accompanying materials are made available under the
 * terms of the Eclipse Public License v1.0 which accompanies this distribution,
 * and is available at http://www.eclipse.org/legal/epl-v10.html
 */

package org.opendaylight.nic.of.renderer.strategy;

import static org.mockito.Mockito.when;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.opendaylight.controller.md.sal.binding.api.DataBroker;
import org.opendaylight.nic.of.renderer.impl.QosConstraintManager;
import org.opendaylight.nic.of.renderer.utils.TopologyUtils;
import org.opendaylight.nic.utils.FlowAction;
import org.opendaylight.yang.gen.v1.urn.opendaylight.intent.rev150122.intents.Intent;
import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeId;
import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.node.NodeConnector;
import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.Node;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;

/**
 * @author victor. Created on 17/11/16.
 */
@PrepareForTest({ TopologyUtils.class })
@RunWith(PowerMockRunner.class)
public class QoSExecutorTest {

    @InjectMocks
    private QoSExecutor qoSExecutorMock;

    @Mock
    private QosConstraintManager qosConstraintManagerMock;

    @Mock
    private DataBroker dataBroker;

    @Mock
    private Intent intentMock;

    @Mock
    private Node node;

    @Mock
    private NodeConnector nodeConnector;

    @Mock
    private NodeId nodeIdDeprecatedMock;

    private Map<Node, List<NodeConnector>> nodeMap;

    private List<NodeConnector> nodeConnectorList;

    @Before
    public void setUp() throws Exception {
        nodeConnectorList = Arrays.asList(nodeConnector);

        when(node.getId()).thenReturn(nodeIdDeprecatedMock);

        nodeMap = new HashMap<>();
        nodeMap.put(node, nodeConnectorList);

        PowerMockito.mockStatic(TopologyUtils.class);

        when(TopologyUtils.getNodes(dataBroker)).thenReturn(nodeMap);

        qoSExecutorMock = new QoSExecutor(qosConstraintManagerMock, dataBroker);
    }

    @Test
    public void testExecuteIntentAddFlow() throws Exception {
        qoSExecutorMock.execute(intentMock, FlowAction.ADD_FLOW);
    }
}

Increase of-renderer coverage on QoSExecutor.


package eu.europa.esig.dss.token;

import java.util.List;

import org.apache.commons.codec.binary.Base64;

import eu.europa.esig.dss.DigestAlgorithm;
import eu.europa.esig.dss.SignatureValue;
import eu.europa.esig.dss.ToBeSigned;

public class MSCAPISignatureTokenApp {

	public static void main(String[] args){

		MSCAPISignatureToken token = new MSCAPISignatureToken();

		List<DSSPrivateKeyEntry> keys = token.getKeys();
		for (DSSPrivateKeyEntry entry : keys) {
			System.out.println(entry.getCertificate().getCertificate());
		}

		ToBeSigned toBeSigned = new ToBeSigned("Hello world".getBytes());
		SignatureValue signatureValue = token.sign(toBeSigned, DigestAlgorithm.SHA256, keys.get(0));

		System.out.println("Signature value : " + Base64.encodeBase64String(signatureValue.getValue()));
	}

}

Add simple application test to interact with MSCAPI


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

package org.jsimpledb.kv.spanner;

import com.google.cloud.spanner.SpannerOptions;

import org.jsimpledb.kv.KVDatabase;
import org.jsimpledb.kv.KVTransaction;
import org.jsimpledb.kv.test.KVTestSupport;
import org.jsimpledb.util.ByteUtil;
import org.testng.Assert;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Optional;
import org.testng.annotations.Parameters;
import org.testng.annotations.Test;

public class DeleteTest extends KVTestSupport {

    private SpannerKVDatabase db;

    @BeforeClass(groups = "configure")
    @Parameters({ "spannerProject", "spannerInstance" })
    public void setSpannerConfig(@Optional String project, String instance) throws Exception {
        if (instance != null) {
            this.db = new SpannerKVDatabase();
            final SpannerOptions.Builder builder = SpannerOptions.newBuilder();
            if (project != null)
                builder.setProjectId(project);
            this.db.setSpannerOptions(builder.build());
            this.db.setInstanceId(instance);
        }
    }

    @Test
    protected void testDeleteToInfinity() throws Exception {
        this.db.start();
        try {

            final byte[] key1 = new byte[] { (byte)0x11 };
            final byte[] val1 = new byte[] { (byte)0xaa };
            final byte[] key2 = new byte[] { (byte)0x22 };
            final byte[] val2 = new byte[] { (byte)0xbb };

            // Populate DB
            KVTransaction tx = this.db.createTransaction();
            try {
                tx.removeRange(new byte[0], null);
                tx.put(key1, val1);
                tx.put(key2, val2);
                tx.commit();
            } finally {
                tx.rollback();
            }

            // Display db
            this.show("initial content");

            // Delete to infinity
            tx = this.db.createTransaction();
            try {
                tx.removeRange(ByteUtil.getNextKey(key1), null);
                tx.commit();
            } finally {
                tx.rollback();
            }

            // Verify second key is gone
            tx = this.db.createTransaction();
            try {
                this.show("after remove");
                Assert.assertNull(tx.get(key2));
                tx.commit();
            } finally {
                tx.rollback();
            }

        } finally {
            this.db.stop();
        }
    }

    private void show(String label) throws Exception {
        this.log.info("Spanner content (" + label + "):");
        KVTransaction tx = this.db.createTransaction();
        try {
            this.show(tx, label);
            tx.commit();
        } finally {
            tx.rollback();
        }
    }

    private void show(KVTransaction tx, String label) throws Exception {
        final Exception e = this.showKV(tx, label);
        if (e != null)
            throw e;
    }
}

Add Google Spanner unit test.


package com.jetbrains.python.actions;

import com.intellij.ide.actions.CreateFileFromTemplateDialog;
import com.intellij.ide.actions.CreateFromTemplateAction;
import com.intellij.openapi.project.DumbAware;
import com.intellij.openapi.project.Project;
import com.intellij.psi.PsiDirectory;
import com.intellij.psi.PsiFile;
import com.jetbrains.python.PythonFileType;

/**
 * @author yole
 */
public class CreatePythonFileAction extends CreateFromTemplateAction<PsiFile> implements DumbAware {
  public CreatePythonFileAction() {
    super("Python File", "Creates a Python file from the specified template", PythonFileType.INSTANCE.getIcon());
  }

  @Override
  protected PsiFile createFile(String name, String templateName, PsiDirectory dir) {
    return createFileFromTemplate(name, templateName, dir);
  }

  @Override
  protected void checkBeforeCreate(String name, String templateName, PsiDirectory dir) {
    dir.checkCreateFile(name);
  }

  @Override
  protected void buildDialog(Project project, PsiDirectory directory, CreateFileFromTemplateDialog.Builder builder) {
    builder
      .setTitle("New Python file")
      .addKind("Python file", PythonFileType.INSTANCE.getIcon(), "Python Script")
      .addKind("Python unit test", PythonFileType.INSTANCE.getIcon(), "Python Unit Test");
  }

  @Override
  protected String getActionName(PsiDirectory directory, String newName, String templateName) {
    return "Create Python script " + newName;
  }
}

package com.jetbrains.python.actions;

import com.intellij.ide.actions.CreateFileFromTemplateAction;
import com.intellij.ide.actions.CreateFileFromTemplateDialog;
import com.intellij.openapi.project.DumbAware;
import com.intellij.openapi.project.Project;
import com.intellij.psi.PsiDirectory;
import com.jetbrains.python.PythonFileType;

/**
 * @author yole
 */
public class CreatePythonFileAction extends CreateFileFromTemplateAction implements DumbAware {
  public CreatePythonFileAction() {
    super("Python File", "Creates a Python file from the specified template", PythonFileType.INSTANCE.getIcon());
  }

  @Override
  protected void buildDialog(Project project, PsiDirectory directory, CreateFileFromTemplateDialog.Builder builder) {
    builder
      .setTitle("New Python file")
      .addKind("Python file", PythonFileType.INSTANCE.getIcon(), "Python Script")
      .addKind("Python unit test", PythonFileType.INSTANCE.getIcon(), "Python Unit Test");
  }

  @Override
  protected String getActionName(PsiDirectory directory, String newName, String templateName) {
    return "Create Python script " + newName;
  }
}

Create JavaEE Web Page action


package org.slc.sli.modeling.rest;

import static org.junit.Assert.*;

import java.util.ArrayList;

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

/**
 * JUnit test for Grammars class.
 *
 * @author wscott
 *
 */
public class GrammarsTest {

    private Grammars grammars;

    private static final ArrayList<Include> INCLUDES = new ArrayList<Include>(0);
    private static final ArrayList<Documentation> DOC = new ArrayList<Documentation>(0);

    @Before
    public void setup() throws Exception {
        grammars = new Grammars(DOC, INCLUDES);
    }

    @Test
    public void testNullIncludes() {
        new Grammars(DOC, null);
    }

    @Test
    public void testGetIncludes() {
        assertEquals(INCLUDES, grammars.getIncludes());
    }

    @Test
    public void testToString() {
        assertTrue(!"".equals(grammars.toString()));
    }

}

Add JUnit test for Grammars class in rest modeling module.


package edu.grinnell.tranchri.cohnhan.deweytyl.hardtmad;

/**
 * JSONParser Class
 *
 * @author Hannah Cohn
 * @author Ty Dewey
 * @author Madeleine Hardt
 * @author Christine Tran
 */

public class JSONParser
{
  // +--------+----------------------------------------------
  // | Fields |
  // +--------+

  String jString;
  JSONValue jValue;

  // +--------------+----------------------------------------
  // | Constructors |
  // +--------------+

  public JSONParser(String input)
  {
    jString = input;
  } // JSONParser (String)

  public JSONParser(JSONValue obj)
  {
    jValue = obj;
  } // JSONParser (JSONValue)

  // +---------------+---------------------------------------
  // | Class Methods |
  // +---------------+

  public Object JSONToJavaObject()
    throws Exception
  {
    this.jValue = JSONUtils.parseValue(jString);
    char type = jValue.type();
    switch (type)
      {
        case 'n':
          return JSONUtils.getNumber(jValue);
        case 's':
          return JSONUtils.getString(jValue);
        case 'c':
          {
            String str = JSONUtils.getString(jValue);
            if (str.equals("true"))
              return true;
            else if (str.equals("false"))
              return false;
            else
              return null;
          } // case 'c'
        case 'a':
          return JSONUtils.getArray(jValue);
        case 'o':
          return JSONUtils.getObject(jValue);
      } // switch

    throw new Exception("Unsupported String" + jString);

  } // JSONToJavaObject()

  public String JavaObjectToStringOfJSON()
    throws Exception
  {

    return jString;
  } // JavaObjectToStringOfJSON()

}

Add framework for parser object and String to Object method


package de.xn__ho_hia.quality.null_analysis;

import java.math.BigInteger;

import org.eclipse.jdt.annotation.NonNull;

/**
 * Utility class to work with @NonNull match operations.
 */
public final class NullsafeMath {

    /**
     * @param value
     *            The value to wrap
     * @return A @NonNull {@link BigInteger}
     */
    public static @NonNull BigInteger asBigInteger(final long value) {
        return Nullsafe.nonNull(BigInteger.valueOf(value));
    }

    /**
     * @param value
     *            The value to wrap
     * @return A @NonNull {@link Long}
     */
    public static @NonNull Long asLong(final long value) {
        return Nullsafe.nonNull(Long.valueOf(value));
    }

    /**
     * @param first
     *            The first value to add
     * @param second
     *            The second value to add
     * @return The sum of both values as a @NonNull {@link BigInteger}
     */
    public static @NonNull BigInteger addNullsafe(final BigInteger first, final BigInteger second) {
        return Nullsafe.nonNull(first.add(second));
    }

    /**
     * @param first
     *            The first value to subtract
     * @param second
     *            The second value to subtract
     * @return The difference of both values as a @NonNull {@link BigInteger}
     */
    public static @NonNull BigInteger subtractNullsafe(final BigInteger first, final BigInteger second) {
        return Nullsafe.nonNull(first.subtract(second));
    }

    /**
     * @param first
     *            The first value to divide
     * @param second
     *            The second value to divide
     * @return The division of both values as a @NonNull {@link BigInteger}
     */
    public static @NonNull BigInteger divideNullsafe(final BigInteger first, final BigInteger second) {
        return Nullsafe.nonNull(first.divide(second));
    }

    /**
     * @param first
     *            The first value to multiply
     * @param second
     *            The second value to multiply
     * @return The multiplication of both values as a @NonNull {@link BigInteger}
     */
    public static @NonNull BigInteger multiplyNullsafe(final BigInteger first, final BigInteger second) {
        return Nullsafe.nonNull(first.multiply(second));
    }

}

Add null safe math operations


/*******************************************************************************
 * Copyright (C) 2017 Push Technology Ltd.
 *
 * 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.pushtechnology.adapters.rest.metrics;

import com.pushtechnology.adapters.rest.model.latest.EndpointConfig;
import com.pushtechnology.adapters.rest.model.latest.ServiceConfig;
import com.pushtechnology.diffusion.client.features.control.topics.TopicAddFailReason;
import com.pushtechnology.diffusion.datatype.Bytes;

/**
 * Listener for Diffusion topic creation events.
 *
 * @author Push Technology Limited
 */
public interface TopicCreationListener {
    /**
     * Notified when an attempt to create a Diffusion topic is made and there is no initial value.
     *
     * @param serviceConfig the service
     * @param endpointConfig the endpoint
     */
    void onTopicCreationRequest(ServiceConfig serviceConfig, EndpointConfig endpointConfig);

    /**
     * Notified when an attempt to create a Diffusion topic is made and there is an initial value.
     *
     * @param serviceConfig the service
     * @param endpointConfig the endpoint
     * @param value the initial value
     */
    void onTopicCreationRequest(ServiceConfig serviceConfig, EndpointConfig endpointConfig, Bytes value);

    /**
     * Notified when a Diffusion topic is created and there is no initial value.
     *
     * @param serviceConfig the service
     * @param endpointConfig the endpoint
     */
    void onTopicCreated(ServiceConfig serviceConfig, EndpointConfig endpointConfig);

    /**
     * Notified when a Diffusion topic is created and there is an initial value.
     *
     * @param serviceConfig the service
     * @param endpointConfig the endpoint
     * @param value the initial value
     */
    void onTopicCreated(ServiceConfig serviceConfig, EndpointConfig endpointConfig, Bytes value);

    /**
     * Notified when a Diffusion topic cannot be created and there is no initial value.
     *
     * @param serviceConfig the service
     * @param endpointConfig the endpoint
     * @param reason the cause of failure
     */
    void onTopicCreationFailed(
        ServiceConfig serviceConfig,
        EndpointConfig endpointConfig,
        TopicAddFailReason reason);

    /**
     * Notified when a Diffusion topic cannot be created and there is an initial value.
     *
     * @param serviceConfig the service
     * @param endpointConfig the endpoint
     * @param value the initial value
     * @param reason the cause of failure
     */
    void onTopicCreationFailed(
        ServiceConfig serviceConfig,
        EndpointConfig endpointConfig,
        Bytes value,
        TopicAddFailReason reason);
}

Add listener interface for topic creation events.


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

import junit.framework.TestCase;
import net.sf.acegisecurity.UserDetails;

import org.easymock.MockControl;
import org.easymock.classextension.MockClassControl;
import org.sipfoundry.sipxconfig.common.CoreContext;
import org.sipfoundry.sipxconfig.common.Permission;
import org.sipfoundry.sipxconfig.common.User;

public class AuthenticationDaoImplTest extends TestCase {
    private static final String USER_NAME = "Hjelje";
    private static User s_user = null;

    private MockControl m_coreControl;
    private CoreContext m_coreContext;
    private AuthenticationDaoImpl m_authenticationDaoImpl;

    protected void setUp() throws Exception {
        m_coreControl = MockClassControl.createStrictControl(CoreContext.class);
        m_coreContext = (CoreContext) m_coreControl.getMock();
        m_authenticationDaoImpl = new AuthenticationDaoImpl();
        m_authenticationDaoImpl.setCoreContext(m_coreContext);
        s_user = new User() {
            public boolean hasPermission(Permission permission) {
                return true;
            }
        };
        s_user.setUserName(USER_NAME);
    }

    public void testLoadUserByUsername() {
        // prep the mock core context
        m_coreContext.loadUserByUserNameOrAlias(USER_NAME);
        m_coreControl.setReturnValue(s_user);
        m_coreControl.replay();

        // load the user details
        UserDetails details = m_authenticationDaoImpl.loadUserByUsername(USER_NAME);
        assertEquals(USER_NAME, details.getUsername());
        assertEquals(AuthenticationDaoImpl.AUTH_USER_AND_ADMIN_ARRAY, details.getAuthorities());
        m_coreControl.verify();
    }
}

Add unit test for AuthenticationDaoImpl


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

import java.util.HashMap;
import java.util.Scanner;

public class DavisStaircase {
    private static HashMap<Integer, Integer> cache = new HashMap<Integer, Integer>();

    private static int calculateCombinatoryFor(int n) {
        int ways = 0;
        if (n == 1)
            ways = 1;
        if (n == 2)
            ways = 2;
        if (n == 3)
            ways = 4;

        if (n > 3) {
            for (int i = 1; i <= 3; i++) {
                if (cache.containsKey(n - i))
                    ways += cache.get(n - i);
                else {
                    int result = calculateCombinatoryFor(n - i);
                    ways += result;
                    cache.put(n - i, result);
                }
            }
        }

        return ways;
    }

    public static void main(String[] args) {
        try (Scanner in = new Scanner(System.in)) {
            int s = in.nextInt();
            for (int a0 = 0; a0 < s; a0++) {
                int n = in.nextInt();
                System.out.println(calculateCombinatoryFor(n));
            }
        }
    }
}

Add Davis' staircase CTCI challenge


package org.usfirst.frc4915.MecanumDrive.commands;

import edu.wpi.first.wpilibj.command.Command;

public class GenericTestCommand extends Command {

	int count = 0;
	int i;
	String message;

    public GenericTestCommand(int count, String message) {
        // Use requires() here to declare subsystem dependencies
        // eg. requires(chassis);
    	this.count = count;
    	this.message = message;
    }

    // Called just before this Command runs the first time
    protected void initialize() {
    	System.out.printf("Saying \"%s\" %i times.%n", message, count);
    }

    // Called repeatedly when this Command is scheduled to run
    protected void execute() {
    	System.out.printf("%s (%i/%i)", message, i, count);
    	i++;
    }

    // Make this return true when this Command no longer needs to run execute()
    protected boolean isFinished() {
        return i == count;
    }

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

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

Create a simple command to use in testing things


package javaStringCompare;

import java.util.Arrays;
import java.util.Scanner;

public class Solution {

	public static String[] readAndSplitString(Scanner scanner) {
		String line = scanner.next();
		int windowLength = scanner.nextInt();
		String[] lines = new String[line.length() - windowLength + 1];
		for(int i = 0; i < line.length() - windowLength + 1; ++i) {
			lines[i] = line.substring(i, windowLength + i);
		}
		return lines;
	}

	public static void main(String ...args) {
		Scanner scanner = new Scanner(System.in);
		String[] lines = readAndSplitString(scanner);
		Arrays.sort(lines);
		System.out.println(lines[0]);
		System.out.println(lines[lines.length - 1]);
		scanner.close();
	}
}

Add solution for problem Java String Compare


package leetcode.climbing_stairs;

public class Solution {
    public int climbStairs(int n) {
        int a = 1, b = 1;
        while(n > 0){
        	int tmp = a;
        	a = a + b;
        	b = tmp;
        	n--;
        }
        return b;
    }
}

Add java solution for 70. Climbing Stairs


package leetcode.merge_intervals;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;

import common.Interval;

public class Solution {
    public ArrayList<Interval> merge(ArrayList<Interval> intervals) {
    	ArrayList<Interval> ans = new ArrayList<Interval>();
    	for(int i = intervals.size() - 1; i >= 0; i--){
    		Interval iv = intervals.get(i);
    		if(iv.start > iv.end){
    			int tmp = iv.start;
    			iv.start = iv.end;
    			iv.end = tmp;
    		}
    	}
    	int size = intervals.size();
    	if(intervals.size() == 0) return ans;
    	Collections.sort(intervals, new Comparator<Interval>(){
			@Override
			public int compare(Interval iv1, Interval iv2) {
				if(iv1.start < iv2.start) return -1;
				if(iv1.start > iv2.start) return 1;
				return 0;
			}
    	});
    	Interval cur = intervals.get(0);
    	int index = 1;
    	while(true){
    		while(index < size && intervals.get(index).start <= cur.end){
    			cur.end = Math.max(cur.end, intervals.get(index).end);
    			index++;
    		}
    		ans.add(cur);
    		if(index < size)
    			cur = intervals.get(index);
    		else
    			break;
    	}
    	return ans;
    }

    public static void main(String[] args){
    	ArrayList<Interval> input = new ArrayList<Interval>();
    	//[1,3],[2,6],[8,10],[15,18]
    	input.add(new Interval(0, 4));
    	input.add(new Interval(0, 0));
    	for(Interval iv : new Solution().merge(input)){
    		System.err.println(iv.start + "," + iv.end);
    	}
    }
}

Add java solution for 56. Merge Intervals


package experimentalcode.erich.data.images;

import java.awt.Color;
import java.util.List;

import de.lmu.ifi.dbs.elki.utilities.optionhandling.IntParameter;
import de.lmu.ifi.dbs.elki.utilities.optionhandling.OptionID;
import de.lmu.ifi.dbs.elki.utilities.optionhandling.ParameterException;
import de.lmu.ifi.dbs.elki.utilities.optionhandling.constraints.IntervalConstraint;
import de.lmu.ifi.dbs.elki.utilities.optionhandling.constraints.IntervalConstraint.IntervalBoundary;

public class ComputeHSBColorHistogram extends AbstractComputeColorHistogram {
  int quant;

  /**
   * OptionID for {@link #BINSPERPLANE_PARAM}
   */
  public static final OptionID BINSPERPLANE_ID = OptionID.getOrCreateOptionID("hsbhist.bpp", "Bins per plane for HSV/HSB histogram. This will result in bpp ** 3 bins.");

  /**
   * Parameter that specifies the number of bins (per plane) to use.
   *
   * <p>
   * Key: {@code -rgbhist.bpp}
   * </p>
   */
  private final IntParameter BINSPERPLANE_PARAM = new IntParameter(BINSPERPLANE_ID, new IntervalConstraint(2, IntervalBoundary.CLOSE, 256, IntervalBoundary.CLOSE));

  public ComputeHSBColorHistogram() {
    super();
    addOption(BINSPERPLANE_PARAM);
  }

  @Override
  public List<String> setParameters(List<String> args) throws ParameterException {
    List<String> remainingParameters = super.setParameters(args);

    quant = BINSPERPLANE_PARAM.getValue();

    return remainingParameters;
  }

  private final static float[] hsbbuf = new float[3];

  @Override
  protected int getBinForColor(int rgb) {
    int r = (rgb & 0xFF0000) >> 16;
    int g = (rgb & 0x00FF00) >> 8;
    int b = (rgb & 0x0000FF);

    synchronized(hsbbuf) {
      float[] hsbvals = Color.RGBtoHSB(r, g, b, hsbbuf);
      // The values returned by RGBtoHSB are all in [0:1]
      int h = (int) Math.floor(quant * hsbvals[0]);
      int s = (int) Math.floor(quant * hsbvals[1]);
      int v = (int) Math.floor(quant * hsbvals[2]);
      // Guard against the value of 1.0
      if(h >= quant) {
        h = quant - 1;
      }
      if(s >= quant) {
        s = quant - 1;
      }
      if(v >= quant) {
        v = quant - 1;
      }
      return h * quant * quant + s * quant + v;
    }
  }

  @Override
  protected int getNumBins() {
    return quant * quant * quant;
  }
}

Add histogram class for HSB/HSV colors.


package com.haxademic.sketch.test;

import com.haxademic.core.app.AppSettings;
import com.haxademic.core.app.PAppletHax;
import com.haxademic.core.draw.image.ImageCyclerBuffer;
import com.haxademic.core.file.FileUtil;

import processing.core.PImage;

public class ImageSwapperBufferTest
extends PAppletHax {
	public static void main(String args[]) { PAppletHax.main(Thread.currentThread().getStackTrace()[1].getClassName()); }

	protected ImageCyclerBuffer imageCycler;

	protected void overridePropsFile() {
		p.appConfig.setProperty( AppSettings.WIDTH, 720 );
		p.appConfig.setProperty( AppSettings.HEIGHT, 720 );
		p.appConfig.setProperty( AppSettings.FULLSCREEN, false );
		p.appConfig.setProperty( AppSettings.SMOOTHING, AppSettings.SMOOTH_HIGH );
		p.appConfig.setProperty( AppSettings.RETINA, false );
	}

	public void setup() {
		super.setup();

		PImage[] images = new PImage[] {
				p.loadImage(FileUtil.getFile("images/justin-home.jpg")),
				p.loadImage(FileUtil.getFile("images/justin-home.png")),
		};

		imageCycler = new ImageCyclerBuffer(640, 280, images, 300, 0.5f);
	}

	public void drawApp() {
		p.background(0);

		imageCycler.update();
		p.image(imageCycler.image(), 20, 20);
	}

}

Add image cycler (w/glsl transitions) test


package de.evorepair.analysis.solver.eclipse;

import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.PlatformUI;

public class EclipseUtil {
	public static IWorkbenchPage getActivePage() {
		return PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage();
	}

	public static IEditorPart getActiveEditor(){
		return getActivePage().getActiveEditor();
	}
}

Add missing eclipse util class


package org.commonmark.ext.headerids;

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

/**
 * Provider of unique strings to be used as an identifier
 */
public class UniqueIdentifierProvider
{
    private String defaultIdentifier;
    private final Map<String, Integer> identityMap;

    /**
     * Create a provider with the default identifier of "id"
     */
    public UniqueIdentifierProvider() {
        this("id");
    }

    /**
     * @param defaultIdentifier default identifier to use if given a null, or empty {@code providedIdentity}
     *                          in {@link #getUniqueIdentifier(String)}
     */
    public UniqueIdentifierProvider(String defaultIdentifier)
    {
        this.defaultIdentifier = defaultIdentifier;
        this.identityMap = new HashMap<>();
    }

    public String getDefaultIdentifier()
    {
        return defaultIdentifier;
    }

    public void setDefaultIdentifier(String defaultIdentifier)
    {
        this.defaultIdentifier = defaultIdentifier;
    }

    /**
     *

     * Provides unique strings over the lifetime of the instance
     *

     *

     * This method is not thread safe, concurrent calls can end up
     * with non-unique identifiers
     *

     *

     * Note that collision can occur in the case that
     *

     *
String 'X' provided to getUniqueIdentifier

     *
String 'X' provided again to getUniqueIdentifier

     *
String 'X-1' provided to getUniqueIdentifier

     *

     *

     *

     * In that case, the three ids provided will be
     *

     *
X

     *
X-1

     *
X-1

     *

     *

     *

     * Therefore if collisions are unnacceptable you should ensure that
     * numbers are stripped from end of {@code providedIdentity}
     *

     *
     * @param providedIdentity tentative identifier to be used. Will be used to check if this is unique. Will be the
     *                         basis for the returned identifier
     *
     * @return {@code providedIdentity} if this is the first instance that the {@code providedIdentity} has been passed
     * to the method. Otherwise, {@code providedIdentity + "-" + X} will be returned, where X is the number of times
     * that {@code providedIdentity} has previously been passed in. If {@code providedIdentity} is empty, the default
     * identifier given in the constructor (or "id" if none given) will be used.
     */
    public String getUniqueIdentifier(String providedIdentity) {
        if (providedIdentity == null || providedIdentity.trim().length() == 0) {
            providedIdentity = defaultIdentifier;
        }

        if (!identityMap.containsKey(providedIdentity)) {
            identityMap.put(providedIdentity, 1);
            return providedIdentity;
        } else {
            int currentCount = identityMap.get(providedIdentity);
            identityMap.put(providedIdentity, currentCount + 1);
            return providedIdentity + "-" +currentCount;
        }
    }
}

Add UniqueID Provider as public class


/*
 * Copyright 2018 Graylog, 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.graylog2.gelfclient.transport;

import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import org.graylog2.gelfclient.GelfConfiguration;
import org.testng.annotations.Test;

import static org.testng.Assert.assertEquals;

public class AbstractGelfTransportTest {

    @Test
    public void testThreads() throws Exception {
        final int threads = 23;
        final GelfConfiguration configuration = new GelfConfiguration().threads(threads);
        final AbstractGelfTransport transport = new AbstractGelfTransport(configuration) {
            @Override
            protected void createBootstrap(EventLoopGroup workerGroup) {
                final NioEventLoopGroup eventLoopGroup = (NioEventLoopGroup) workerGroup;
                assertEquals(threads, eventLoopGroup.executorCount());
            }
        };
        transport.stop();
    }
}

Add test for number of threads used by AbstractGelfTransport


package com.opentable.jaxrs;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.PropertyResolver;

import com.opentable.spring.SpecializedConfigFactory;

@Configuration
public class JaxRsClientConfiguration {

    @Bean
    SpecializedConfigFactory<JaxRsClientConfig> jaxRsConfigFactory(PropertyResolver pr) {
        return SpecializedConfigFactory.create(pr, JaxRsClientConfig.class, "jaxrs.client.${name}");
    }

    @Bean
    JaxRsClientFactory jaxrsClientFactory(SpecializedConfigFactory<JaxRsClientConfig> config) {
        return new JaxRsClientFactory(config);
    }

    @Bean
    JaxRsFeatureBinding dataUriHandler() {
        return JaxRsFeatureBinding.bindToAllGroups(new DataUriFeature());
    }
}

package com.opentable.jaxrs;

import com.fasterxml.jackson.databind.ObjectMapper;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.PropertyResolver;

import com.opentable.spring.SpecializedConfigFactory;

@Configuration
public class JaxRsClientConfiguration {

    @Bean
    SpecializedConfigFactory<JaxRsClientConfig> jaxRsConfigFactory(PropertyResolver pr) {
        return SpecializedConfigFactory.create(pr, JaxRsClientConfig.class, "jaxrs.client.${name}");
    }

    @Bean
    JaxRsClientFactory jaxrsClientFactory(SpecializedConfigFactory<JaxRsClientConfig> config) {
        return new JaxRsClientFactory(config);
    }

    @Bean
    JaxRsFeatureBinding dataUriHandler() {
        return JaxRsFeatureBinding.bindToAllGroups(new DataUriFeature());
    }

    @Bean
    JaxRsFeatureBinding jsonFeature(ObjectMapper mapper) {
        return JaxRsFeatureBinding.bindToAllGroups(JsonClientFeature.forMapper(mapper));
    }
}

Enable Jackson on jaxrs clients


/**
 *
 */
package org.corpus_tools.atomic.api.events;

import org.eclipse.core.runtime.IConfigurationElement;
import org.eclipse.core.runtime.Platform;
import org.eclipse.ui.IPartListener2;
import org.eclipse.ui.IWorkbenchPartReference;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.contexts.IContextActivation;
import org.eclipse.ui.contexts.IContextService;

/**
 * TODO Description
 *
 * @author Stephan Druskat <mail@sdruskat.net>
 *
 */
public class PartContextListener implements IPartListener2 {

	private final String partId;
	private IContextActivation contextActivation = null;
	private final String pluginId;
	private String contextId = null;

	/**
	 * @param partId
	 *
	 */
	public PartContextListener(String partId, String pluginId) {
		this.partId = partId;
		this.pluginId = pluginId;
		IConfigurationElement[] elements = Platform.getExtensionRegistry().getConfigurationElementsFor("org.eclipse.ui.contexts");

		for (IConfigurationElement element : elements) {
			if (element.getContributor().getName().equals(pluginId)) {
				this.contextId = element.getAttribute("id");
				break;
			}
		}
	}

	/* (non-Javadoc)
	 * @see org.eclipse.ui.IPartListener2#partActivated(org.eclipse.ui.IWorkbenchPartReference)
	 */
	@Override
	public void partActivated(IWorkbenchPartReference partRef) {
		if (contextId != null) {
			if (partRef.getId().equals(partId)) {
				PlatformUI.getWorkbench().getDisplay().syncExec(new Runnable() {
					@Override
					public void run() {
						contextActivation = PlatformUI.getWorkbench().getService(IContextService.class).activateContext(contextId);
					}
				});
			}
		}
	}

	/* (non-Javadoc)
	 * @see org.eclipse.ui.IPartListener2#partDeactivated(org.eclipse.ui.IWorkbenchPartReference)
	 */
	@Override
	public void partDeactivated(IWorkbenchPartReference partRef) {
		if (contextId != null && contextActivation != null) {
			if (partRef.getId().equals(partId)) {
				PlatformUI.getWorkbench().getDisplay().syncExec(new Runnable() {
					@Override
					public void run() {
						PlatformUI.getWorkbench().getService(IContextService.class).deactivateContext(contextActivation);
					}
				});
			}
		}

	}

	// Unimplemented methods
	@Override public void partBroughtToTop(IWorkbenchPartReference partRef) {}
	@Override public void partClosed(IWorkbenchPartReference partRef) {}
	@Override public void partOpened(IWorkbenchPartReference partRef) {}
	@Override public void partHidden(IWorkbenchPartReference partRef) {}
	@Override public void partVisible(IWorkbenchPartReference partRef) {}
	@Override public void partInputChanged(IWorkbenchPartReference partRef) {}

}

Implement a part listener that sets contexts automatically


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

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

/**
 * @author Gabriel Mihai Ruiu (gabriel.ruiu@mail.com)
 */
@EnableConfigServerRedis
@SpringBootApplication
public class SpringConfigServerRedisTestConfiguration {

    public static void main(String[] args) {
        SpringApplication.run(SpringConfigServerRedisTestConfiguration.class, args);
    }
}

Add main configuration class that tests will use to build the application context


package leetcode.swap_nodes_in_pairs;

import java.util.ArrayList;

import common.ListNode;

public class Solution {
	public ListNode swapPairs(ListNode head) {
		if(head == null || head.next == null) return head;
		ListNode ret = head.next;
		ListNode cur = head;
		ListNode prev = null;
		while(cur != null && cur.next != null){
			ListNode nxt = cur.next;
			cur.next = nxt.next;
			nxt.next = cur;
			if(prev != null){
				prev.next = nxt;
			}
			prev = cur;
			cur = cur.next;
		}
		return ret;
	}

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

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

Add java solution for 24. Swap Nodes in Pairs


package to.etc.domui.component.delayed;

import to.etc.domui.component.misc.MsgBox;
import to.etc.domui.dom.html.Div;
import to.etc.domui.dom.html.HTag;
import to.etc.domui.util.Msgs;
import to.etc.parallelrunner.IAsyncRunnable;
import to.etc.util.CancelledException;
import to.etc.util.StringTool;

/**
 * @author Frits Jalvingh
 * Created on 14-12-21.
 */
abstract public class AsyncDiv<T extends IAsyncRunnable> extends Div {
	final private T m_runnable;

	private final String m_what;

	public AsyncDiv(T runnable, String what) {
		m_runnable = runnable;
		m_what = what;
	}

	@Override
	final public void createContent() throws Exception {
		String what = m_what;
		if(null != what) {
			add(new HTag(1, what));
		}
		add(new AsyncContainer(m_runnable, (cancelled, errorException) -> {
			//-- If we've got an exception replace the contents with the exception message.
			if(errorException != null && !(errorException instanceof CancelledException)) {
				//errorException.printStackTrace();
				StringBuilder sb = new StringBuilder(8192);
				StringTool.strStacktrace(sb, errorException);
				String s = sb.toString();
				s = s.replace("\n", "
\n");

				MsgBox.error(this, Msgs.BUNDLE.getString(Msgs.ASYNC_ERROR) + "
" + s);
			} else if(cancelled) {
				MsgBox.info(this, Msgs.BUNDLE.getString(Msgs.ASYNC_CONTAINER_CANCELLED));
			} else {
				removeAllChildren();
				createContent(m_runnable);
			}
		}));
	}

	abstract public void createContent(T task) throws Exception;
}

Add test page, fix 1st issues.


package com.github.maven_nar;

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

public class ProcessLibraryCommand {

    /**
     * The executable to run
     *
     * @parameter default-value=""
     */
    private String executable;

    /**
     * The library type that this command is valid for
     *
     * @parameter default-value=""
     */
    private String libraryType;

    /**
     * Any additional arguments to pass into the executable
     *
     * @parameter default-value=""
     */
    private List<String> arguments;

    public List<String> getCommandList() {
	List<String> command = new ArrayList<String>();
	command.add(executable);
	command.addAll(arguments);
	return command;
    }

    public String getExecutable() {
        return executable;
    }
    public void setExecutable(String executable) {
        this.executable = executable;
    }
    public List<String> getArguments() {
        return arguments;
    }
    public void setArguments(List<String> arguments) {
        this.arguments = arguments;
    }
    public String getType() {
	// TODO Auto-generated method stub
	return libraryType;
    }

}

package com.github.maven_nar;

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

public class ProcessLibraryCommand {

    /**
     * The executable to run
     *
     * @parameter default-value=""
     */
    private String executable;

    /**
     * The library type that this command is valid for
     *
     * @parameter default-value=""
     */
    private String libraryType;

    /**
     * Any additional arguments to pass into the executable
     *
     * @parameter default-value=""
     */
    private List<String> arguments;

    public List<String> getCommandList() {
	List<String> command = new ArrayList<String>();
	command.add(executable);
	if (arguments != null) {
		command.addAll(arguments);
	}
	return command;
    }

    public String getExecutable() {
        return executable;
    }
    public void setExecutable(String executable) {
        this.executable = executable;
    }
    public List<String> getArguments() {
        return arguments;
    }
    public void setArguments(List<String> arguments) {
        this.arguments = arguments;
    }
    public String getType() {
	// TODO Auto-generated method stub
	return libraryType;
    }

}

Fix NPE for command with no arguments


/**
 * Enable to use HibernateIdGenerator on identifiers in the package: <code>@GeneratedValue(generator = HibernateIdGenerator.NAME)</code>
 */
@org.hibernate.annotations.GenericGenerator(name = com.coreoz.plume.db.hibernate.HibernateIdGenerator.NAME, strategy = "com.coreoz.plume.db.hibernate.HibernateIdGenerator")
package ${package}.db.entities;

Package info added for code generation


/**
 * Copyright (C) 2014 - present by OpenGamma Inc. and the OpenGamma group of companies
 *
 * Please see distribution for license.
 */
package com.opengamma.bbg.component;

import com.opengamma.bbg.referencedata.statistics.BloombergReferenceDataStatistics;
import com.opengamma.bbg.referencedata.statistics.NullBloombergReferenceDataStatistics;
import com.opengamma.component.ComponentRepository;

/**
 * Component factory for the Null Bloomberg Reference Data Statistics.
 */
public class NoneBloombergReferenceDataStatisticsComponentFactory extends DefaultBloombergReferenceDataStatisticsComponentFactory {

  @Override
  protected BloombergReferenceDataStatistics initReferenceDataStatistics(ComponentRepository repo) {
    return NullBloombergReferenceDataStatistics.INSTANCE;
  }

}

Add a NULL bloomberg ref data statistics component factory


package guitests;

import guitests.guihandles.TaskCardHandle;
import static org.junit.Assert.assertTrue;
import static seedu.task.logic.commands.UpdateCommand.MESSAGE_UPDATE_TASK_SUCCESS;

import org.junit.Test;

import seedu.task.commons.core.Messages;
import seedu.task.commons.exceptions.IllegalValueException;
import seedu.task.logic.commands.UpdateCommand;
import seedu.task.model.tag.Tag;
import seedu.task.model.task.*;
import seedu.task.testutil.TestTask;
import seedu.task.testutil.TestUtil;

public class UndoCommandTest extends TaskManagerGuiTest {
    @Test
    public void update() throws IllegalValueException {
        TestTask[] currentList = td.getTypicalTasks();
        int targetIndex = 1;

        // undo add command
        assertUndoSuccess(td.hoon.getAddCommand(), currentList);

        // undo delete command
        assertUndoSuccess("delete " + targetIndex, currentList);

        // undo update command
        assertUndoSuccess("update " + targetIndex + td.ida.getArgs(), currentList);
    }

    private void assertUndoSuccess(String command, TestTask... originalList) {
        commandBox.runCommand(command);
        commandBox.runCommand("undo");
        assertTrue(taskListPanel.isListMatching(originalList));
    }
}

Add basic test for undo command


package com.einevault.users;

import static spark.Spark.get;

/**
 * Created by einevea on 16/08/15.
 */
public class UsersApp {

    public static void main(String[] args) {
        get("/hello", (req, res) -> "Hello World");
    }
}

Create a basic user main


/*
 * Bach - Java Shell Builder
 * Copyright (C) 2019 Christian Stein
 *
 * 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 it;

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

import de.sormuras.bach.Resources;
import java.net.URI;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.condition.DisabledIfSystemProperty;

class ResourcesTests {

  @Test
  @DisabledIfSystemProperty(named = "offline", matches = "true")
  void headRequestOfHttpsGoogleComUsingSystemResourcesIsRespondedWithStatus200() throws Exception {
    assertEquals(200, Resources.ofSystem().head(URI.create("https://google.com")).statusCode());
  }
}

Add test case for Resources


/**
 * @license
 * Copyright 2018 The FOAM Authors. All Rights Reserved.
 * http://www.apache.org/licenses/LICENSE-2.0
 */

package foam.nanos.servlet;

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

/**
 * Typically used to alias short paths like "/" or "/merchant" to specific services.
 */
public class RedirectServlet
    extends HttpServlet
{
  @Override
  protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    String path = getServletConfig().getInitParameter("path");
    RequestDispatcher view = req.getRequestDispatcher(path);
    view.forward(req, resp);
  }
}

Add redirect sevlet, a non tomcat specific version of the Tomcat SubdomainRouter


package org.opennms.web.svclayer;

public class ProgressMonitor {

	private int m_phaseCount = 1;
	private int m_phase = 0;
	private String m_phaseLabel = "Loading";
	private Object m_result = null;
	private Exception m_exception = null;

	public int getPhaseCount() {
		return m_phaseCount;
	}

	public void setPhaseCount(int phaseCount) {
		m_phaseCount = phaseCount;
	}

	public String getPhaseLabel() {
		return m_phaseLabel;
	}

	public int getPhase() {
		return m_phase;
	}

	public void beginNextPhase(String phaseLabel) {
		m_phaseLabel = phaseLabel;
		m_phase++;
	}

	public void finished(Object result) {
		m_result = result;
		m_phaseLabel = "Done";
		m_phase = m_phaseCount;
	}

	public boolean isFinished() {
		return m_result != null;
	}

	public Object getResult() {
		return m_result;
	}

	public boolean isError() {
		return m_exception != null;
	}

	public Exception getException() {
		return m_exception;
	}

	public void errorOccurred(Exception e) {
		m_exception = e;
	}

}

Add progress bar to loading of Surveillence page


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

package alluxio.shell.command;

import alluxio.AlluxioURI;
import alluxio.client.FileSystemTestUtils;
import alluxio.client.WriteType;
import alluxio.shell.AbstractAlluxioShellTest;
import alluxio.underfs.UnderFileSystem;
import org.junit.Assert;
import org.junit.Test;

public class CheckConsistencyCommandTest extends AbstractAlluxioShellTest {
  /**
   * Tests the check consistency shell command correctly identifies a consistent subtree.
   */
  @Test
  public void consistent() throws Exception {
    FileSystemTestUtils
        .createByteFile(mFileSystem, "/testRoot/testFileA", WriteType.CACHE_THROUGH, 10);
    FileSystemTestUtils.createByteFile(mFileSystem, "/testRoot/testDir/testFileB",
        WriteType.CACHE_THROUGH, 20);
    mFsShell.run("checkConsistency", "/testRoot");
    String expected = "/testRoot is consistent with the under storage system.\n";
    Assert.assertEquals(expected, mOutput.toString());
  }

  /**
   * Tests the check consistency shell command correctly identifies inconsistent files in a subtree.
   */
  @Test
  public void inconsistent() throws Exception {
    FileSystemTestUtils
        .createByteFile(mFileSystem, "/testRoot/testFileA", WriteType.CACHE_THROUGH, 10);
    FileSystemTestUtils.createByteFile(mFileSystem, "/testRoot/testDir/testFileB",
        WriteType.CACHE_THROUGH, 20);
    String ufsPath = mFileSystem.getStatus(new AlluxioURI("/testRoot/testDir")).getUfsPath();
    UnderFileSystem ufs = UnderFileSystem.get(ufsPath);
    ufs.delete(ufsPath, true);
    mFsShell.run("checkConsistency", "/testRoot");
    StringBuilder expected = new StringBuilder();
    expected.append("The following files are inconsistent:\n");
    expected.append("/testRoot/testDir\n");
    expected.append("/testRoot/testDir/testFileB\n");
    Assert.assertEquals(expected.toString(), mOutput.toString());
  }
}

Add a unit test for the shell command.


package org.app.material.widget;

import android.support.annotation.StringRes;
import android.support.v4.app.Fragment;

public class FragmentSet {

    private Fragment fragment;
    private CharSequence title;
    private @StringRes int resId;

    public FragmentSet(Fragment fragment, CharSequence title) {
        this.fragment = fragment;
        this.title = title;
    }

    public FragmentSet(Fragment fragment, @StringRes int resId) {
        this.fragment = fragment;
        this.resId = resId;
    }

    public Fragment getFragment() {
        return fragment;
    }

    public CharSequence getTitle() {
        return title;
    }

    public int getResId() {
        return resId;
    }
}

Add set to fragment pager adapter


package nl.hsac.fitnesse.junit;

import org.junit.runner.Description;
import org.junit.runner.Result;
import org.junit.runner.notification.Failure;
import org.junit.runner.notification.RunListener;

import java.io.PrintStream;

/**
 * JUnit RunListener so that TeamCity is updated with progress info while tests run.
 */
public class JUnitTeamcityReporter extends RunListener {
    private final PrintStream out;
    private String currentTestClassName = null;

    public JUnitTeamcityReporter() {
        this(System.out);
    }

    public JUnitTeamcityReporter(final PrintStream out) {
        this.out = out;
        this.currentTestClassName = null;
    }

    @Override
    public void testStarted(Description description) {
        final String testClassName = getTestClassName(description);
        final String testName = getTestName(description);

        if (currentTestClassName == null || !currentTestClassName.equals(testClassName)) {
            testRunFinished(null);
            this.out.println(String.format("##teamcity[testSuiteStarted name='%s']", testClassName));
            currentTestClassName = testClassName;
        }

        out.println(String.format("##teamcity[testStarted name='%s' captureStandardOutput='true']", testName));
    }

    @Override
    public void testFinished(Description description) {
        final String testName = getTestName(description);

        out.println(String.format("##teamcity[testFinished name='%s']", testName));
    }

    @Override
    public void testFailure(Failure failure) {
        if (failure.getTrace() != null && !failure.getTrace().isEmpty())
            out.print(failure.getTrace());
        out.println(String.format("##teamcity[testFailed name='%s' message='%s' details='%s']",
                getTestName(failure.getDescription()),
                "failed",
                ""));
        testFinished(failure.getDescription());
    }

    @Override
    public void testIgnored(Description description) {
        out.println(String.format("##teamcity[testIgnored name='%s' message='%s']",
                getTestName(description),
                ""));
    }

    @Override
    public void testRunFinished(Result result) {
        if (currentTestClassName != null) {
            out.println(String.format("##teamcity[testSuiteFinished name='%s']", currentTestClassName));
        }
    }

    protected String getTestClassName(final Description description) {
        return description.getTestClass().getName();
    }

    protected String getTestName(final Description description) {
        return description.getMethodName();
    }
}

Add RunListener to be used in combination with TeamCity so that start and end time of each page is recorded in the build log in a format that TeamCity can interpret. (Can be used as listener instead of JUnitXMLPerPageListener.)


/*
 * 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.logging.log4j.core.config.plugins;

/**
 * Identifies a default string value for a given plugin attribute or value. This value should be used as a fallback
 * where either the given value is invalid, or when there is no given value.
 */
public @interface PluginDefault {
    /**
     * The default value to use.
     */
    String value();
}

Add annotation for default plugin values.


package br.inpe.cap.evolution.processor;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Collection;
import java.util.stream.Stream;

import org.apache.commons.io.FileUtils;
import org.repodriller.persistence.csv.CSVFile;

public class RemoveUnchangedArtifactsStandAlonePostProcessor {

	public static void main(String[] args) {

		System.out.println("Starting...");

		final File pathToLook = new File("C:\\Users\\LuizWagner\\Desktop\\evolutions_joined\\unchanged");
		final String outputPath = pathToLook + File.separator + "output";
		new File(outputPath).mkdirs();
		Collection<File> arquivos = FileUtils.listFiles(pathToLook, null, false);

		arquivos.parallelStream().forEach((csvInput)-> {

			final RemoveUnchangedArtifactsPostProcessor postProcessor = new RemoveUnchangedArtifactsPostProcessor(false);
			final String name = csvInput.getName();
			System.out.println("Processing "+name);
			final CSVFile csvOutput = new CSVFile(outputPath + File.separator + name);

			try {
				final Stream<String> listCsvLines = Files.lines(Paths.get(csvInput.toURI()));
				postProcessor.processCsvLines(csvOutput, listCsvLines);
			} catch (RuntimeException | IOException e) {
				e.printStackTrace();
			}

			System.gc();
			System.out.println("Done "+name);

		});

		System.out.println("Finish!");

	}

}

Change way of processing lines from List<String> to Stream<String> in order to process the 15 billion lines csv file!


package com.nucleus.vecmath;

/**
 * 3 Component vector utilities
 *
 * @author Richard Sahlin
 *
 */
public class Vector3D extends VecMath {

    /**
     * Returns the cross product vector from vector1 and vector2
     * cx = ay * bz − az * by
     * cy = az * bx − ax * bz
     * cz = ax * by − ay * bx
     *
     * @param vector1
     * @param vector2
     * @return New 3 component vector that is the cross product of vector1 and vector2
     */
    public final static float[] cross3(float[] vector1, float[] vector2) {
        float[] cross = new float[3];
        cross[0] = vector1[Y] * vector2[Z] - vector1[Z] * vector2[Y];
        cross[1] = vector1[Z] * vector2[X] - vector1[X] * vector2[Z];
        cross[2] = vector1[X] * vector2[Y] - vector1[Y] * vector2[X];
        return cross;
    }

    /**
     * Sets a 3 component vector at the specified index
     *
     * @param src
     * @param srcIndex
     * @param dest
     * @param destIndex
     */
    public final static void set(float[] src, int srcIndex, float[] dest, int destIndex) {
        dest[destIndex++] = src[srcIndex++];
        dest[destIndex++] = src[srcIndex++];
        dest[destIndex++] = src[srcIndex++];
    }

    public final static float[] subtract(float[] v1, int v1Index, float[] v2, int v2Index) {
        float[] result = new float[3];
        result[0] = v2[v1Index++] - v1[v2Index++];
        result[1] = v2[v1Index++] - v1[v2Index++];
        result[2] = v2[v1Index] - v1[v2Index];
        return result;
    }

    /**
     * Returns the cross product vector from vector1 and vector2
     * cx = ay * bz − az * by
     * cy = az * bx − ax * bz
     * cz = ax * by − ay * bx
     *
     * @param data Array containing vector1 and vector2 and the destination
     * @param v1 index into array where vertex 1 is
     * @param v2 index into array where vertex 2 is
     * @param dest index to result
     */
    public final static void cross3(float[] data, int v1, int v2, int dest) {
        data[dest + X] = data[v1 + Y] * data[v2 + Z] - data[v1 + Z] * data[v2 + Y];
        data[dest + Y] = data[v1 + Z] * data[v2 + X] - data[v1 + X] * data[v2 + Z];
        data[dest + Z] = data[v1 + X] * data[v2 + Y] - data[v1 + Y] * data[v2 + X];
    }

}

Add class for 3 component vector functionality


/*
8.6.2 The Random Class
page 309
*/

package epfc.cours3449;

import java.util.Random;

public class TestRandom {
    public static void main(String[] args) {
        Random r1 = new Random(3);
        for(int i=0; i<10; i++) {
            System.out.print(r1.nextInt(1000) + " ");
        }
        System.out.println("");
        Random r2 = new Random(3);
        for(int i=0; i<10; i++) {
            System.out.print(r2.nextInt(1000) + " ");
        }
        System.out.println("");
    }
}

Test Random Class, comme dans le livre pg 310


/*
 * Copyright 2018 EPAM Systems
 *
 * 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.epam.ta.reportportal.ws.model.launch;

import com.epam.ta.reportportal.ws.model.ErrorRS;
import com.fasterxml.jackson.annotation.JsonProperty;

import java.util.List;

/**
 * @author Ihar Kahadouski
 */
public class DeleteLaunchesRS {

	@JsonProperty("successfullyDeleted")
	private List<Long> deleted;

	@JsonProperty("notFound")
	private List<Long> notFound;

	@JsonProperty("noPermissions")
	private List<Long> noPermissions;

	@JsonProperty("errors")
	private List<ErrorRS> errors;

	public DeleteLaunchesRS() {
	}

	public DeleteLaunchesRS(List<Long> deleted, List<Long> notFound, List<Long> noPermissions, List<ErrorRS> errors) {
		this.deleted = deleted;
		this.notFound = notFound;
		this.noPermissions = noPermissions;
		this.errors = errors;
	}

	public List<Long> getDeleted() {
		return deleted;
	}

	public void setDeleted(List<Long> deleted) {
		this.deleted = deleted;
	}

	public List<Long> getNotFound() {
		return notFound;
	}

	public void setNotFound(List<Long> notFound) {
		this.notFound = notFound;
	}

	public List<Long> getNoPermissions() {
		return noPermissions;
	}

	public void setNoPermissions(List<Long> noPermissions) {
		this.noPermissions = noPermissions;
	}

	public List<ErrorRS> getErrors() {
		return errors;
	}

	public void setErrors(List<ErrorRS> errors) {
		this.errors = errors;
	}

	@Override
	public String toString() {
		final StringBuilder sb = new StringBuilder("DeleteLaunchesRS{");
		sb.append("deleted=").append(deleted);
		sb.append(", notFound=").append(notFound);
		sb.append(", noPermissions=").append(noPermissions);
		sb.append(", errors=").append(errors);
		sb.append('}');
		return sb.toString();
	}
}

Add delete launches response entity


package leetcode.roman_to_integer;

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

public class Solution {
	public int romanToInt(String s) {
		Map<String, Integer> map = new HashMap<String, Integer>();
    	String[] romans = new String[]{
    		"", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX",
    		"X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC",
    		"C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM",
    		"M", "MM", "MMM",
    	};
    	for(int i = 0; i <= 9; i++){
    		map.put(romans[i], i);
    	}
    	for(int i = 10; i <= 90; i += 10){
    		map.put(romans[i / 10 + 9], i);
    	}
    	for(int i = 100; i <= 900; i += 100){
    		map.put(romans[i / 100 + 18], i);
    	}
    	for(int i = 1000; i <= 3000; i += 1000){
    		map.put(romans[i / 1000 + 27], i);
    	}
    	int offset = 0;
    	int ans = 0;
    	while(offset < s.length()){
    		for(int digits = Math.min(4, s.length() - offset); digits >= 1; digits--){
    			Integer val = map.get(s.substring(offset, offset + digits));
    			if(val != null){
    				ans += val;
    				offset += digits;
    				break;
    			}
    		}
    	}
    	return ans;
	}

	public static void main(String[] args){
		for(int i = 1; i <= 3999; i++){
			if(new Solution().romanToInt(new leetcode.integer_to_roman.Solution().intToRoman(i)) != i){
				System.err.println("failed at " + i);
			}else{
				System.err.println(new leetcode.integer_to_roman.Solution().intToRoman(i) + " " + i);
			}
		}
	}
}

Add java solution for 13. Roman to Integer


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

package gerrit;

import com.google.gerrit.server.rules.StoredValues;
import com.googlecode.prolog_cafe.exceptions.PrologException;
import com.googlecode.prolog_cafe.lang.IntegerTerm;
import com.googlecode.prolog_cafe.lang.Operation;
import com.googlecode.prolog_cafe.lang.Predicate;
import com.googlecode.prolog_cafe.lang.Prolog;
import com.googlecode.prolog_cafe.lang.Term;
import org.eclipse.jgit.revwalk.RevCommit;

/**
 * Prolog fact for the number of parents of a given commit
 *
 * <pre>
 *   'commit_parent_count'(-Count)
 * </pre>
 */
public class PRED_commit_parent_count_1 extends Predicate.P1 {
  public PRED_commit_parent_count_1(Term a1, Operation n) {
    arg1 = a1;
    cont = n;
  }

  @Override
  public Operation exec(Prolog engine) throws PrologException {
    engine.setB0();
    Term a1 = arg1.dereference();

    RevCommit commit = StoredValues.COMMIT.get(engine);

    if (!a1.unify(new IntegerTerm(commit.getParentCount()), engine.trail)) {
      return engine.fail();
    }
    return cont;
  }
}

Add prolog predicate to determine number of parents


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

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

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

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

  private IsRotationUsingIsSubstring isRotation;

  @Before public void setUp() {
    isRotation = new IsRotationUsingIsSubstring();
  }

  @Test(expected = IllegalArgumentException.class)
  public void shouldNotAcceptNullInstancesAsFirstParameter() {
    isRotation.check(null, "");
  }

  @Test(expected = IllegalArgumentException.class)
  public void shouldNotAcceptNullInstancesAsSecondParameter() {
    isRotation.check("", null);
  }

  @Test public void shouldReturnFalseIfS2IsNotRotationOfS1() {
    String s1 = "waterbottle";
    String s2 = "pedro";

    boolean result = isRotation.check(s1, s2);

    assertFalse(result);
  }

  @Test public void shouldReturnTrueIfS2IsNotRotationOfS1() {
    String s1 = "waterbottle";
    String s2 = "erbottlewat";

    boolean result = isRotation.check(s1, s2);

    assertTrue(result);
  }
}

Add some tests to problem 56


package org.codehaus.xfire.aegis.type.basic;

import org.codehaus.xfire.aegis.AbstractXFireAegisTest;
import org.codehaus.xfire.client.XFireProxyFactory;
import org.codehaus.xfire.service.Service;
import org.codehaus.xfire.service.invoker.BeanInvoker;

public class InterfaceImplTest
    extends AbstractXFireAegisTest
{
    public void testInterface() throws Exception
    {
        Service service = getServiceFactory().create(IMyService.class);
        service.setInvoker(new BeanInvoker(new MyService()));
        getServiceRegistry().register(service);
        service.setProperty(IMyObject.class.getName() + ".implementation", MyObject.class.getName());

        IMyService client = (IMyService)
            new XFireProxyFactory(getXFire()).create(service, "xfire.local://IMyService");
        MyObject o = new MyObject();
        o.setName("foo");
        client.receive(o);
    }

    public static interface IMyService
    {
        public void receive(IMyObject o);
    }

    public static class MyService implements IMyService
    {
        public void receive(IMyObject o)
        {
            assertTrue(o instanceof MyObject);
        }
    }

    public interface IMyObject
    {
        public String getName();
    }

    public static class MyObject implements IMyObject
    {
        private String name;

        public String getName()
        {
            return name;
        }

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

}

Add unit test for interface impl feature


/*
 * Copyright (c) Facebook, Inc. and its affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */

package com.facebook.imagepipeline.core;

/** Setter and getter for option about using native code. */
public class NativeCodeSetup {

  private static boolean sUseNativeCode = true;

  private NativeCodeSetup() {}

  /**
   * Setter for useNativeCode option
   *
   * @param useNativeCode true, if you want to use native code
   */
  public static void setUseNativeCode(boolean useNativeCode) {
    sUseNativeCode = useNativeCode;
  }

  /**
   * Getter for useNativeCode option
   *
   * @return true, if you going to use Native code
   */
  public static boolean getUseNativeCode() {
    return sUseNativeCode;
  }
}

Add option to use native code in Fresco


/*
 * Copyright © 2014 <code@io7m.com> http://io7m.com
 *
 * Permission to use, copy, modify, and/or distribute this software for any
 * purpose with or without fee is hereby granted, provided that the above
 * copyright notice and this permission notice appear in all copies.
 *
 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
 * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR
 * IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 */

/**
 * Unit tests.
 */

@com.io7m.jnull.NonNullByDefault
package com.io7m.jfunctional.tests;

Add missing package info file


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Main {
    public static void main(String args[]) throws IOException {
        InputStreamReader ir = new InputStreamReader(System.in);
        BufferedReader in = new BufferedReader(ir);

        int a, b, x;

        a = Integer.parseInt(in.readLine());
        b = Integer.parseInt(in.readLine());

        x = a + b;

        System.out.printf("SOMA = %d\n", x);
    }
}

Solve Simple Sum in java


package absyn;

import env.Env;
import parse.Loc;
import types.Type;

public abstract class Var extends AST {

   // Type of the expression, calculated by the semantic analyser
   public Type type;

   public Var(Loc loc) {
      super(loc);
   }

   // Obtain the type of the expression as a string prefixed by the given text.
   protected String annotateType(String text) {
      final String theType = type == null ? "" : "\n<" + type + ">";
      return text + theType;
   }

   // Do semantic analysis of the expression
   public Type semantic(Env env) {
      type = semantic_(env);
      return type;
   }

   // Type check the expression. Should be defined in the concrete subclasses.
   protected abstract Type semantic_(Env env);
}

Add abstract class for variables


/*
 * Copyright 2005-2014 Red Hat, Inc.
 *
 * Red Hat 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 io.fabric8.maven;

import io.fabric8.kubernetes.client.KubernetesClient;
import io.fabric8.openshift.client.OpenShiftClient;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.apache.maven.plugins.annotations.Mojo;
import org.apache.maven.plugins.annotations.Parameter;
import org.apache.maven.plugins.annotations.ResolutionScope;

/**
 * Cleans up namespace resources.
 * The default behavior is to clean app specific resources, replication controllers, pods, services, routes etc.
 * The command also supports deep cleaning. When enabled deep cleaning will delete everything including secrets, service accounts etc.
 */
@Mojo(name = "clean", requiresDependencyResolution = ResolutionScope.RUNTIME)
public class CleanMojo extends ApplyMojo {

    @Parameter(property = "fabric8.deep.clean", defaultValue = "false")
    private Boolean deep;

    @Override
    public void execute() throws MojoExecutionException, MojoFailureException {
        KubernetesClient client = getKubernetes().inNamespace(getNamespace());

        client.services().delete();
        client.replicationControllers().delete();
        client.pods().delete();

        client.endpoints().delete();
        client.events().delete();

        if (deep) {
            client.secrets().delete();
            client.serviceAccounts().delete();
            client.securityContextConstraints().delete();
        }

        if (client.isAdaptable(OpenShiftClient.class)) {
            OpenShiftClient openShiftClient = client.adapt(OpenShiftClient.class);

            openShiftClient.routes().delete();
            openShiftClient.builds().delete();
            openShiftClient.imageStreams().delete();
            openShiftClient.buildConfigs().delete();
            openShiftClient.deploymentConfigs().delete();
            openShiftClient.templates().delete();

            if (deep) {
                openShiftClient.users().delete();
                openShiftClient.groups().delete();
                openShiftClient.policies().delete();
                openShiftClient.policyBindings().delete();
            }
        }
    }
}

Introduce clean mojo for cleaning up namespaces.


import org.junit.Test;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.WebDriverWait;

import java.util.List;

import static org.junit.Assert.assertTrue;

/**
 * Created by mikas on 12.11.2015.
 */
public class LogInTest {
    private String baseUrl = "http://localhost:3000/";

    @Test
    public void checkTitle(){
        FirefoxDriver driver = new FirefoxDriver();
        driver.get(baseUrl);

        assertTrue(driver.getTitle().equals("Projekt Grupowy 2015 - aplikacja demo"));

        driver.quit();
    }

    @Test
    public void checkIfThereAreFields(){
        FirefoxDriver driver = new FirefoxDriver();
        driver.get(baseUrl);

        int numberOfInputs = 2;

        List<WebElement> inputs = driver.findElementsByCssSelector("input");
        WebElement button = driver.findElementByCssSelector("button");

        assertTrue(inputs.size() == numberOfInputs && button != null);
        driver.quit();
    }

    @Test
    public void testLoginAction(){
        FirefoxDriver driver = new FirefoxDriver();
        driver.get(baseUrl);

        List<WebElement> inputs = driver.findElementsByCssSelector("input");

        WebElement roomInput = inputs.get(0);
        roomInput.sendKeys("13");
        WebElement loginInput = inputs.get(1);
        loginInput.sendKeys("test");

        driver.findElementByCssSelector("button").click();

        String url = driver.getCurrentUrl();

        assertTrue(url != baseUrl);
        driver.quit();
    }
}

Add UI tests for Login page.


package apostov;

import static apostov.Suit.CLUBS;
import static apostov.Suit.DIAMONDS;
import static apostov.Suit.HEARTS;
import static apostov.Suit.SPADES;
import static apostov.Value.FIVE;
import static apostov.Value.FOUR;
import static apostov.Value.KING;
import static apostov.Value.QUEEN;
import static apostov.Value.SEVEN;
import static apostov.Value.SIX;
import static com.google.common.collect.ImmutableSet.copyOf;
import static com.google.common.collect.Iterables.concat;
import static org.junit.Assert.*;
import static strength.PokerHandKind.PAIR;

import org.junit.Test;

import com.google.common.collect.ImmutableCollection;
import com.google.common.collect.ImmutableSet;

import strength.PairRanking;
import strength.PokerHandRanking;

public class ShowdownEvaluatorTest {

	@Test
	public void selectBestCombinationWithTwoKings() {
		final Card seven = new Card(SEVEN, SPADES);
		final ImmutableCollection<Card> holeCards = ImmutableSet.of(
				seven,
				new Card(KING, CLUBS));

		final Card queen = new Card(QUEEN, CLUBS);
		final Card six = new Card(SIX, DIAMONDS);
		final ImmutableCollection<Card> board = ImmutableSet.of(
				new Card(FIVE, CLUBS),
				new Card(KING, DIAMONDS),
				new Card(FOUR, HEARTS),
				queen,
				six);

		final ShowdownEvaluator evaluator = new ShowdownEvaluator();
		final PokerHandRanking handStrength = evaluator.selectBestCombination(copyOf(concat(holeCards, board)));
		assertSame(PAIR, handStrength.handKind);
		final PairRanking pairRanking = (PairRanking) handStrength;
		assertSame(KING, pairRanking.pairValue);
		assertEquals(
				ImmutableSet.of(CLUBS, DIAMONDS),
				ImmutableSet.of(pairRanking.firstSuit, pairRanking.secondSuit));
		assertEquals(queen, pairRanking.firstKicker);
		assertEquals(seven, pairRanking.secondKicker);
		assertEquals(six, pairRanking.thirdKicker);
	}
}

Add a JUnit test for the selectBestCombination() method


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

package org.cyanogenmod.hardware;

import org.cyanogenmod.hardware.util.FileUtils;

import java.io.File;

public class VibratorHW {

    private static String LEVEL_PATH = "/sys/class/timed_output/vibrator/intensity";

    public static boolean isSupported() {
        File f = new File(LEVEL_PATH);
        return f.exists();
    }

    public static int getMaxIntensity()  {
        return 10000;
    }

    public static int getMinIntensity()  {
        return 0;
    }

    public static int getWarningThreshold()  {
        return 9000;
    }

    public static int getCurIntensity()  {
        File f = new File(LEVEL_PATH);
        String actualIntensity = FileUtils.readOneLine(LEVEL_PATH).replace("intensity: ", "");

        return f.exists() ? Integer.parseInt(actualIntensity) : 0;
    }

    public static int getDefaultIntensity()  {
        return 7500;
    }

    public static boolean setIntensity(int intensity)  {
        File f = new File(LEVEL_PATH);

        return f.exists() && FileUtils.writeLine(LEVEL_PATH, String.valueOf(intensity));
    }
}

Allow for vibration intensity to be configured