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

package org.gradle.integtests.fixtures.executer;

public class PerformanceTestBuildContext extends IntegrationTestBuildContext {

}

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

package org.gradle.integtests.fixtures.executer;

import org.gradle.test.fixtures.file.TestFile;

import java.io.File;
import java.util.UUID;

public class PerformanceTestBuildContext extends IntegrationTestBuildContext {
    @Override
    public TestFile getTmpDir() {
        String uniquePart = UUID.randomUUID().toString();
        return getTmpBaseDir().file(uniquePart);
    }

    private TestFile getTmpBaseDir() {
        return file("integTest.tmpDir", new File(System.getProperty("java.io.tmpdir"), "integTestBuildTmp-" + System.getProperty("user.name")).getAbsolutePath());
    }

    @Override
    public void configure(GradleExecuter gradleExecuter) {
        super.configure(gradleExecuter);
        gradleExecuter.withCleanupTempDirectory(true);
    }
}

Use unique temp dir for each performance test execution


package org.synyx.urlaubsverwaltung.sicknote;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

@Component
@ConfigurationProperties("uv.sick-note")
public class SickNoteProperties {

    /**
     * Send notification about the end of sick pay by default every day at 06:00 am
     */
    private String endOfPayNotificationCron = "0 0 6 * * *";

    public String getEndOfPayNotificationCron() {
        return endOfPayNotificationCron;
    }

    public void setEndOfPayNotificationCron(String endOfPayNotificationCron) {
        this.endOfPayNotificationCron = endOfPayNotificationCron;
    }
}

package org.synyx.urlaubsverwaltung.sicknote;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import org.springframework.validation.annotation.Validated;

import javax.validation.constraints.NotEmpty;

@Component
@ConfigurationProperties("uv.sick-note")
@Validated
public class SickNoteProperties {

    /**
     * Send notification about the end of sick pay by default every day at 06:00 am
     */
    @NotEmpty
    private String endOfPayNotificationCron = "0 0 6 * * *";

    public String getEndOfPayNotificationCron() {
        return endOfPayNotificationCron;
    }

    public void setEndOfPayNotificationCron(String endOfPayNotificationCron) {
        this.endOfPayNotificationCron = endOfPayNotificationCron;
    }
}

Add bean validation for uv.sick-note.endOfPayNotificationCron


public abstract class Expr {
	public abstract Expr apply (Expr target, double value);
	public abstract String compile ();
	public abstract Expr differentiate (Expr dx);
	public abstract Expr simplify ();
	public abstract Expr simplify (UnaryExpr parent);
	public abstract Expr simplify (BinaryExpr parent, Expr sibling);

	public Expr add (Expr other) {
		return new AddExpr(this, other);
	}

	public Expr mul (Expr other) {
		return new MulExpr(this, other);
	}

	public Expr sub (Expr other) {
		return new SubExpr(this, other);
	}
}

public abstract class Expr {
	public abstract Expr apply (Expr target, double value);
	public abstract String compile ();
	public abstract Expr differentiate (Expr dx);
	public abstract Expr simplify ();
	public abstract Expr simplify (UnaryExpr parent);
	public abstract Expr simplify (BinaryExpr parent, Expr sibling);

	public AddExpr add (Expr other) {
		return new AddExpr(this, other);
	}

	public MulExpr mul (Expr other) {
		return new MulExpr(this, other);
	}

	public SubExpr sub (Expr other) {
		return new SubExpr(this, other);
	}
}

Clarify types of common operations.


package com.bottomsheetbehavior;

import android.support.design.widget.CoordinatorLayout;
import android.view.View;

import com.facebook.react.uimanager.ViewGroupManager;
import com.facebook.react.uimanager.annotations.ReactProp;
import com.facebook.react.uimanager.ThemedReactContext;

public class CoordinatorLayoutManager extends ViewGroupManager<CoordinatorLayoutView> {

    private final static String REACT_CLASS = "RCTCoordinatorLayoutAndroid";

    @Override
    public String getName() {
        return REACT_CLASS;
    }

    @Override
    public CoordinatorLayoutView createViewInstance(ThemedReactContext context) {
        return new CoordinatorLayoutView(context);
    }

    @Override
    public void addView(CoordinatorLayoutView parent, View child, int index) {
        super.addView(parent, child, index);

        // Sets FloatingActionButton anchor automatically
        if (child instanceof FloatingActionButtonView) {
            boolean autoAnchor = ((FloatingActionButtonView) child).getAutoAnchor();
            for (int i = 0; i < parent.getChildCount(); i++) {
                View childView = parent.getChildAt(i);
                if (childView instanceof BottomSheetBehaviorView && autoAnchor) {
                    int bottomSheetId = childView.getId();
                    ((CoordinatorLayout.LayoutParams) child.getLayoutParams()).setAnchorId(bottomSheetId);
                }
            }
        }
    }

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

package com.bottomsheetbehavior;

import android.support.design.widget.CoordinatorLayout;
import android.view.View;

import com.facebook.react.uimanager.ViewGroupManager;
import com.facebook.react.uimanager.annotations.ReactProp;
import com.facebook.react.uimanager.ThemedReactContext;

public class CoordinatorLayoutManager extends ViewGroupManager<CoordinatorLayoutView> {

    private final static String REACT_CLASS = "RCTCoordinatorLayoutAndroid";

    @Override
    public String getName() {
        return REACT_CLASS;
    }

    @Override
    public CoordinatorLayoutView createViewInstance(ThemedReactContext context) {
        return new CoordinatorLayoutView(context);
    }

    @Override
    public void addView(CoordinatorLayoutView parent, View child, int index) {
        super.addView(parent, child, index);

        // Sets FloatingActionButton anchor automatically
        if (child instanceof FloatingActionButtonView) {
            if (((FloatingActionButtonView) child).getAutoAnchor()) {
                for (int i = 0; i < parent.getChildCount(); i++) {
                    View childView = parent.getChildAt(i);
                    if (childView instanceof BottomSheetBehaviorView) {
                        int bottomSheetId = childView.getId();
                        ((CoordinatorLayout.LayoutParams) child.getLayoutParams()).setAnchorId(bottomSheetId);
                    }
                }
            }
        }
    }

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

Check autoAnchor before child iteration


package io.fabric8.app.gerrit;

import io.fabric8.kubernetes.generator.annotation.KubernetesModelProcessor;
import io.fabric8.openshift.api.model.template.TemplateBuilder;

@KubernetesModelProcessor
public class GerritModelProcessor {

    public void onList(TemplateBuilder builder) {
        builder.addNewServiceObject()
                .withNewMetadata()
                  .withName("gerrit-http-service")
                  .addToLabels("component", "gerrit")
                  .addToLabels("provider", "fabric8")
                .endMetadata()
                .withNewSpec()
                  .addNewPort()
/*                    .withProtocol("HTTP")*/
                    .withPort(80)
                      .withNewTargetPort(8080)
                    .endPort()
                    .addToSelector("component", "gerrit")
                    .addToSelector("provider", "fabric8")
                .endSpec()
                .endServiceObject()
                // Second service
                .addNewServiceObject()
                .withNewMetadata()
                  .withName("gerrit-ssh-service")
                  .addToLabels("component", "gerrit")
                  .addToLabels("provider", "fabric8")
                .endMetadata()
                .withNewSpec()
                  .addNewPort()
/*                    .withProtocol("SSH")*/
                    .withPort(29418)
                      .withNewTargetPort(29418)
                    .endPort()
                    .addToSelector("component", "gerrit")
                    .addToSelector("provider", "fabric8")
                .endSpec()
                .endServiceObject()
                .build();
    }
}

package io.fabric8.app.gerrit;

import io.fabric8.kubernetes.generator.annotation.KubernetesModelProcessor;
import io.fabric8.openshift.api.model.template.TemplateBuilder;

@KubernetesModelProcessor
public class GerritModelProcessor {

    public void onList(TemplateBuilder builder) {
        builder.addNewServiceObject()
                .withNewMetadata()
                  .withName("gerrit-http-service")
                  .addToLabels("component", "gerrit")
                  .addToLabels("provider", "fabric8")
                .endMetadata()
                .withNewSpec()
                  .addNewPort()
                    .withProtocol("TCP")
                    .withPort(80)
                      .withNewTargetPort(8080)
                    .endPort()
                    .addToSelector("component", "gerrit")
                    .addToSelector("provider", "fabric8")
                .endSpec()
                .endServiceObject()
                // Second service
                .addNewServiceObject()
                .withNewMetadata()
                  .withName("gerrit-ssh-service")
                  .addToLabels("component", "gerrit")
                  .addToLabels("provider", "fabric8")
                .endMetadata()
                .withNewSpec()
                  .addNewPort()
                    .withProtocol("TCP")
                    .withPort(29418)
                      .withNewTargetPort(29418)
                    .endPort()
                    .addToSelector("component", "gerrit")
                    .addToSelector("provider", "fabric8")
                .endSpec()
                .endServiceObject()
                .build();
    }
}

Fix issue with error spec[0].protocol. The protocol to be used is TCP


/*
 * Copyright (C) 2008 TranceCode Software
 *
 * This library 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 library is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
 * details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this library; if not, write to the Free Software Foundation, Inc.,
 * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
 *
 * $Id$
 */
package org.trancecode.io;

/**
 * Utility methods related to file paths handling.
 *
 * @author Herve Quiroz
 */
public final class Paths
{
    private static final String PATH_DELIMITER = "/";

    private Paths()
    {
        // No instantiation
    }

    public static String asAbsolutePath(final String path)
    {
        if (path.startsWith(PATH_DELIMITER))
        {
            return path;
        }

        return PATH_DELIMITER + path;
    }

    public static String asDirectory(final String path)
    {
        if (path.endsWith(PATH_DELIMITER))
        {
            return path;
        }

        return path + PATH_DELIMITER;
    }
}

/*
 * Copyright (C) 2008 TranceCode Software
 *
 * This library 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 library is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
 * details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this library; if not, write to the Free Software Foundation, Inc.,
 * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
 *
 * $Id$
 */
package org.trancecode.io;

/**
 * Utility methods related to file paths handling.
 *
 * @author Herve Quiroz
 */
public final class Paths
{
    private Paths()
    {
        // No instantiation
    }

    public static String delimiter()
    {
        return "/";
    }

    public static String asAbsolutePath(final String path)
    {
        if (path.startsWith(delimiter()))
        {
            return path;
        }

        return delimiter() + path;
    }

    public static String asDirectory(final String path)
    {
        if (path.endsWith(delimiter()))
        {
            return path;
        }

        return path + delimiter();
    }
}

Make DELIMITER a method rather than a constant


import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;

public class RArray extends RObject {
    public final ArrayList<RObject> impl;

    public RArray() {
        impl = new ArrayList<RObject>();
    }

    public RArray(RObject... args) {
        impl = new ArrayList<RObject>(Arrays.asList(args));
    }

    public RArray(List<RObject> impl) {
        this.impl = new ArrayList<RObject>(impl);
    }

    public RObject $less$less(RObject what) {
        add(what);

        return this;
    }

    public RObject $lbrack$rbrack(RObject where) {
        int index = (int)((RFixnum)where.to_i()).fix;

        if (index < size()) {
            return get(index);
        }

        return RNil;
    }

    public RObject $lbrack$rbrack$equal(RObject where, RObject what) {
        int index = (int)((RFixnum)where.to_i()).fix;

        // TODO index >= size
        impl.set(index, what);

        return this;
    }

    public RObject size() {
        return new RFixnum(impl.size());
    }

    public RObject clear() {
        impl.clear();
        return this;
    }
}

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;

public class RArray extends RObject {
    public final ArrayList<RObject> impl;

    public RArray() {
        impl = new ArrayList<RObject>();
    }

    public RArray(RObject... args) {
        impl = new ArrayList<RObject>(Arrays.asList(args));
    }

    public RArray(List<RObject> impl) {
        this.impl = new ArrayList<RObject>(impl);
    }

    public RObject $less$less(RObject what) {
        impl.add(what);

        return this;
    }

    public RObject $lbrack$rbrack(RObject where) {
        int index = (int)((RFixnum)where.to_i()).fix;

        if (index < 0) {
            index = impl.size() + index;
        }

        if (index < impl.size()) {
            return impl.get(index);
        } else {
            return RNil;
        }
    }

    public RObject $lbrack$rbrack$equal(RObject where, RObject what) {
        int index = (int)((RFixnum)where.to_i()).fix;

        if (index < 0) {
            index = impl.size() + index;
        }

        if (index >= impl.size()) {
            impl.ensureCapacity(index + 1);
        }

        impl.set(index, what);

        return this;
    }

    public RObject size() {
        return new RFixnum(impl.size());
    }

    public RObject clear() {
        impl.clear();
        return this;
    }
}

Fix existing Array methods and support negative and >= size sets.


/**
 * Copyright (C) 2013 Alexander Szczuczko
 *
 * This file may be modified and distributed under the terms
 * of the MIT license. See the LICENSE file for details.
 */
package ca.szc.keratin.bot.misc;

import org.pmw.tinylog.Configurator;
import org.pmw.tinylog.LoggingLevel;

public class Logging
{

    /**
     * Set tinylog's logging level and output format.
     */
    public static void activateDefaultLoggingConfig()
    {
        String formatPattern = "{date:yyyy-MM-dd HH:mm:ss.SSS} [{thread}] {class}.{method}()  {level}: {message}";
        Configurator.defaultConfig().level( LoggingLevel.TRACE ).formatPattern( formatPattern ).activate();
    }

}

/**
 * Copyright (C) 2013 Alexander Szczuczko
 *
 * This file may be modified and distributed under the terms
 * of the MIT license. See the LICENSE file for details.
 */
package ca.szc.keratin.bot.misc;

import org.pmw.tinylog.Configurator;
import org.pmw.tinylog.LoggingLevel;

/**
 * Set tinylog's logging level and output format.
 */
public class Logging
{
    /**
     * Configure at the given logging level
     */
    public static void activateLoggingConfig( LoggingLevel logLevel )
    {
        String formatPattern = "{date:yyyy-MM-dd HH:mm:ss.SSS} [{thread}] {class}.{method}()  {level}: {message}";
        Configurator.defaultConfig().level( logLevel ).formatPattern( formatPattern ).activate();
    }

    /**
     * Configure at TRACE logging level
     */
    public static void activateDebugLoggingConfig()
    {
        activateLoggingConfig( LoggingLevel.TRACE );
    }
}

Allow more than just TRACE logging levels


package org.gem.log;

import org.apache.log4j.BasicConfigurator;
import org.apache.log4j.Logger;
import org.apache.log4j.PatternLayout;

import org.junit.Test;

import static org.junit.Assert.assertThat;

import static org.junit.matchers.JUnitMatchers.*;

import static org.hamcrest.CoreMatchers.*;

public class AMQPAppenderTest {
    private DummyChannel dummyChannel;
    private DummyAppender dummyAppender;
    private Logger logger = Logger.getLogger(AMQPAppenderTest.class);

    void tearDown() {
        dummyChannel = null;
        dummyAppender = null;

        // this closes the RabbitMQ connections
        BasicConfigurator.resetConfiguration();
    }

    private void setUpDummyAppender() {
        dummyAppender = new DummyAppender();
        dummyAppender.setLayout(new PatternLayout());

        BasicConfigurator.configure(dummyAppender);
    }

    @Test
    public void basicLogging() {
        setUpDummyAppender();

        logger.info("Test");

        dummyChannel = (DummyChannel) dummyAppender.getChannel();

        assertThat(dummyChannel.entries.size(), is(equalTo(1)));

        DummyChannel.Entry entry = dummyChannel.entries.get(0);

        assertThat(entry.exchange, is(equalTo("")));
        assertThat(entry.routingKey, is(equalTo("")));
        assertThat(entry.properties.getType(), is(equalTo("INFO")));
        assertThat(entry.body, is(equalTo("Test\n")));
    }
}

package org.gem.log;

import org.apache.log4j.BasicConfigurator;
import org.apache.log4j.Logger;
import org.apache.log4j.PatternLayout;

import org.junit.Test;

import static org.junit.Assert.assertThat;

import static org.junit.matchers.JUnitMatchers.*;

import static org.hamcrest.CoreMatchers.*;

public class AMQPAppenderTest {
    private DummyChannel dummyChannel;
    private DummyAppender dummyAppender;
    private Logger logger = Logger.getLogger(AMQPAppenderTest.class);

    void tearDown() {
        dummyChannel = null;
        dummyAppender = null;

        // this closes the RabbitMQ connections
        BasicConfigurator.resetConfiguration();
    }

    private void setUpDummyAppender() {
        dummyAppender = new DummyAppender();
        dummyAppender.setLayout(new PatternLayout());

        BasicConfigurator.configure(dummyAppender);
    }

    @Test
    public void basicLogging() {
        setUpDummyAppender();

        logger.info("Test1");
        logger.warn("Test2");

        dummyChannel = (DummyChannel) dummyAppender.getChannel();

        assertThat(dummyChannel.entries.size(), is(equalTo(2)));

        DummyChannel.Entry entry1 = dummyChannel.entries.get(0);

        assertThat(entry1.exchange, is(equalTo("")));
        assertThat(entry1.routingKey, is(equalTo("")));
        assertThat(entry1.properties.getType(), is(equalTo("INFO")));
        assertThat(entry1.body, is(equalTo("Test1\n")));

        DummyChannel.Entry entry2 = dummyChannel.entries.get(1);

        assertThat(entry2.exchange, is(equalTo("")));
        assertThat(entry2.routingKey, is(equalTo("")));
        assertThat(entry2.properties.getType(), is(equalTo("WARN")));
        assertThat(entry2.body, is(equalTo("Test2\n")));
    }
}

Test that .info() and .warn() set the correct event type.


package interpres.language.values;

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

import interpres.ast.AST;

public class Symbol extends Value {
  private java.lang.String intern;
  private AST symbolAST;

  public Symbol(java.lang.String intern) {
    this(intern, null);
  }

  public Symbol(java.lang.String intern, AST symbolAST) {
    this.intern = intern;
    this.symbolAST = symbolAST;
  }

  public java.lang.String getIntern() {
    return this.intern;
  }

  public List<java.lang.String> bytecodeSequence() {
    return Arrays.asList(this.intern);
  }

  public AST getUnquotedAST() {
    return this.symbolAST;
  }

  public java.lang.String toString() {
    return this.intern.toString();
  }
}

package interpres.language.values;

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

import interpres.ast.AST;

public class Symbol extends Value {
  private java.lang.String intern;
  private AST symbolAST;

  public Symbol(java.lang.String intern) {
    this(intern, new interpres.ast.Symbol(intern));
  }

  public Symbol(java.lang.String intern, AST symbolAST) {
    this.intern = intern;
    this.symbolAST = symbolAST;
  }

  public java.lang.String getIntern() {
    return this.intern;
  }

  public List<java.lang.String> bytecodeSequence() {
    return Arrays.asList(this.intern);
  }

  public AST getUnquotedAST() {
    return this.symbolAST;
  }

  public java.lang.String toString() {
    return this.intern.toString();
  }
}

Allow unquoting for symbols that were created by a core function


package myessentials.chat.api;

import myessentials.localization.api.LocalManager;
import net.minecraft.command.ICommandSender;
import net.minecraft.util.IChatComponent;
import net.minecraft.entity.player.EntityPlayerMP;

import java.util.List;

public class ChatManager {

    /**
     * Global method for sending localized messages
     */
    public static void send(ICommandSender sender, String localizationKey, Object... args) {
        send(sender, LocalManager.get(localizationKey, args));
    }

    /**
     * Global method for sending messages
     * If the message sent is a ChatComponentList then only its siblings are sent, omitting the root component
     */
    @SuppressWarnings("unchecked")
    public static void send(ICommandSender sender, IChatComponent message) {
        if (sender == null) {
            return;
        }

        if (message == null) {
            return;
        }

        if (message instanceof ChatComponentList) {
            for (IChatComponent sibling : (List<IChatComponent>)message.getSiblings()) {
                if (sibling == null) {
                    continue;
                }

                sender.addChatMessage(sibling);
            }
        } else {
            sender.addChatMessage(message);
        }
    }

    public static void addChatMessageFixed(ICommandSender sender, IChatComponent message) {
        if (!(sender instanceof EntityPlayerMP)||((EntityPlayerMP)sender).playerNetServerHandler != null)
            sender.addChatMessage(message);
        } else {
            //TODO Find a way to re-send the message.
        }
    }
}

package myessentials.chat.api;

import myessentials.localization.api.LocalManager;
import net.minecraft.command.ICommandSender;
import net.minecraft.util.IChatComponent;
import net.minecraft.entity.player.EntityPlayerMP;

import java.util.List;

public class ChatManager {

    /**
     * Global method for sending localized messages
     */
    public static void send(ICommandSender sender, String localizationKey, Object... args) {
        send(sender, LocalManager.get(localizationKey, args));
    }

    /**
     * Global method for sending messages
     * If the message sent is a ChatComponentList then only its siblings are sent, omitting the root component
     */
    @SuppressWarnings("unchecked")
    public static void send(ICommandSender sender, IChatComponent message) {
        if (sender == null) {
            return;
        }

        if (message == null) {
            return;
        }

        if (message instanceof ChatComponentList) {
            for (IChatComponent sibling : (List<IChatComponent>)message.getSiblings()) {
                if (sibling == null) {
                    continue;
                }

                sender.addChatMessage(sibling);
            }
        } else {
            sender.addChatMessage(message);
        }
    }

    public static void addChatMessageFixed(ICommandSender sender, IChatComponent message) {
        if (!(sender instanceof EntityPlayerMP)||((EntityPlayerMP)sender).playerNetServerHandler != null)
            sender.addChatMessage(message);
        }
         //TODO Find a way to re-send the message.
    }
}

Update to make Travis-CI happier.


package com.jedrzejewski.slisp.lexer;

import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;

@RunWith(JUnit4.class)
public class LexerTest {

    @Test
    public void testNextToken() {
        Lexer lexer = new Lexer("(fn (zero? 0) (+ 2 3))");
        List<Token> tokens = new LinkedList<Token>();
        Token token;
        while ((token = lexer.getNextToken()) != null) {
            tokens.add(token);
        }
        List<Token> expected = Arrays.asList(
                new OpenBracket(),
                new Symbol("fn"),
                new OpenBracket(),
                new Symbol("zero?"),
                new Number(0),
                new CloseBracket(),
                new OpenBracket(),
                new Symbol("+"),
                new Number(2),
                new Number(3),
                new CloseBracket(),
                new CloseBracket());
        org.junit.Assert.assertEquals(tokens, expected);
    }
}

package com.jedrzejewski.slisp.lexer;

import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;

@RunWith(JUnit4.class)
public class LexerTest {

    @Test
    public void testNextToken() {
        Lexer lexer = new Lexer("(fn (zero? 0) (+ 2 3))");
        List<Token> tokens = new LinkedList<Token>();
        Token token;
        while ((token = lexer.getNextToken()) != null) {
            tokens.add(token);
        }
        List<Token> expected = Arrays.asList(
                new OpenBracket(),
                new Symbol("fn"),
                new OpenBracket(),
                new Symbol("zero?"),
                new Number(0),
                new CloseBracket(),
                new OpenBracket(),
                new Symbol("+"),
                new Number(2),
                new Number(3),
                new CloseBracket(),
                new CloseBracket());
        org.junit.Assert.assertEquals(expected, tokens);
    }
}

Change order of assert arguments


package com.gr8pefish.portablecrafting.items.craftingItems;

import com.gr8pefish.portablecrafting.items.ItemBase;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;

import java.util.List;

public class ItemSubCrafting extends ItemBase {

    public String[] names = {"crafting_core", "blueprints"};

    public ItemSubCrafting() {
        super("subcrafting.");
        setHasSubtypes(true);
    }

    @Override
    @SideOnly(Side.CLIENT)
    public void getSubItems(Item id, CreativeTabs creativeTab, List<ItemStack> list) {
        for (int i = 0; i < names.length; i++)
            list.add(new ItemStack(id, 1, i));
    }

    @Override
    public String getUnlocalizedName(ItemStack stack) {
        return super.getUnlocalizedName(stack) + names[stack.getItemDamage()];
    }
}

package com.gr8pefish.portablecrafting.items.craftingItems;

import com.gr8pefish.portablecrafting.items.ItemBase;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;

import java.util.List;

public class ItemSubCrafting extends ItemBase {

    public String[] names = {"crafting_core"};

    public ItemSubCrafting() {
        super("subcrafting.");
        setHasSubtypes(true);
    }

    @Override
    @SideOnly(Side.CLIENT)
    public void getSubItems(Item id, CreativeTabs creativeTab, List<ItemStack> list) {
        for (int i = 0; i < names.length; i++)
            list.add(new ItemStack(id, 1, i));
    }

    @Override
    public String getUnlocalizedName(ItemStack stack) {
        return super.getUnlocalizedName(stack) + names[stack.getItemDamage()];
    }
}

Fix registry for no-longer-present subItem


package fr.insee.rmes.api;

public class Configuration {

	// TODO Externalize props
	public final static String SPARQL_END_POINT = "http://id.insee.fr/sparql";

}

package fr.insee.rmes.api;

public class Configuration {

	// TODO Externalize props
	public final static String SPARQL_END_POINT = "http://qfrmessnczlht01.ad.insee.intra/sparql";
	//public final static String SPARQL_END_POINT = "http://id.insee.fr/sparql";
}

Fix minor issue with endpoint configuration


package uk.ac.edukapp.util;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;

public class ServletUtils {

	public static String getCookieValue(Cookie[] cookies, String cookieName,
			String defaultValue) {
		for (int i = 0; i < cookies.length; i++) {
			Cookie cookie = cookies[i];
			if (cookieName.equals(cookie.getName()))
				return (cookie.getValue());
		}
		return (defaultValue);
	}

	public static String getServletRootURL ( HttpServletRequest request ) {
		String serverName = request.getServerName();
		int serverPort = request.getServerPort();
		String protocol;

		if (request.isSecure()){
			protocol = "https";
		}
		else {
			protocol = "http";
		}

		String root = protocol+"://"+serverName+":"+serverPort+"/edukapp";

		return root;
	}

	public static boolean isNumeric(String str) {
		return str.matches("-?\\d+(.\\d+)?");
	}
}

package uk.ac.edukapp.util;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.validator.routines.UrlValidator;

public class ServletUtils {

	public static String getCookieValue(Cookie[] cookies, String cookieName,
			String defaultValue) {
		for (int i = 0; i < cookies.length; i++) {
			Cookie cookie = cookies[i];
			if (cookieName.equals(cookie.getName()))
				return (cookie.getValue());
		}
		return (defaultValue);
	}

	public static String getServletRootURL ( HttpServletRequest request ) {
		String serverName = request.getServerName();
		int serverPort = request.getServerPort();
		String protocol;

		if (request.isSecure()){
			protocol = "https";
		}
		else {
			protocol = "http";
		}

		String root = protocol+"://"+serverName+":"+serverPort+"/edukapp";

		return root;
	}

	public static boolean isNumeric(String str) {
		return str.matches("-?\\d+(.\\d+)?");
	}

	public static boolean checkURL ( String url ) {
		String schemes[] = {"http", "https"};
		UrlValidator urlValidator = new UrlValidator(schemes);
		return urlValidator.isValid(url);
	}
}

Support for web url widget creator


package langton;

import java.awt.Point;
import java.util.HashMap;

public class LangtonsAnt
{
  private final Point[] directions =
  {
    new Point(1, 0),
    new Point(0, 1),
    new Point(-1, 0),
    new Point(0, -1)
  };

  private Point ant;                      // The ant's position
  private int direction = 0;              // The ant's direction
  private HashMap<Point, Boolean> field;  // The field which the ant moves on

  public LangtonsAnt()
  {
    // Create a new Map to hold coordinates for ant
    field = new HashMap<Point, Boolean>();
  }

  public void step()
  {
    // If the ant is on a black square
    if (field.get(ant))
    {
      direction = (direction - 1) % 4;
      field.put(ant, false);
    }
    else  // If the ant is on a white spot
    {
      direction = (direction + 1) % 4;
      field.put(ant, true);
    }

    ant.translate(directions[direction].x,
                  directions[direction].y);
  }

  public static void main(String[] args)
  {
  }
}

package langton;

import java.awt.Point;
import java.util.HashMap;

public class LangtonsAnt
{
  private final Point[] directions =
  {
    new Point(1, 0),
    new Point(0, 1),
    new Point(-1, 0),
    new Point(0, -1)
  };

  private Point ant;                      // The ant's position
  private int direction = 0;              // The ant's direction
  private HashMap<Point, Boolean> plane;  // The plane which the ant moves on

  public LangtonsAnt()
  {
    // Create a new Map to hold coordinates for ant
    plane = new HashMap<Point, Boolean>();
  }

  public Point getAnt()
  {
    return ant;
  }

  public HashMap<Point, Boolean> getPlane()
  {
    return plane;
  }

  public void step()
  {
    // If the ant is on a black square
    if (plane.get(ant))
    {
      direction = (direction - 1) % 4;
      plane.put(ant, false);
    }
    else  // If the ant is on a white spot
    {
      direction = (direction + 1) % 4;
      plane.put(ant, true);
    }

    ant.translate(directions[direction].x,
                  directions[direction].y);
  }
}

Add getPlane-method. Returns the plane which the ant moves on


package edu.northwestern.bioinformatics.studycalendar.dao.reporting;

import edu.northwestern.bioinformatics.studycalendar.dao.StudyCalendarDao;
import gov.nih.nci.cabig.ctms.domain.DomainObject;
import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.springframework.orm.hibernate3.HibernateCallback;

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

/**
 * @author John Dzak
 */
public abstract class ReportDao<F extends ReportFilters, R extends DomainObject> extends StudyCalendarDao<R> {
    @SuppressWarnings("unchecked")
    public List<R> search(final F filters) {
        return getHibernateTemplate().executeFind(new HibernateCallback() {
            @SuppressWarnings("unchecked")
            public Object doInHibernate(Session session) throws HibernateException {
                if (filters.isEmpty()) {
                    logger.debug("No filters selected, skipping search: " + filters);
                    return Collections.emptyList();
                } else {
                    Criteria criteria = session.createCriteria(domainClass());
                    filters.apply(session);
                    return (List<R>) criteria.list();

                }
            }
        });
    }
}

package edu.northwestern.bioinformatics.studycalendar.dao.reporting;

import edu.northwestern.bioinformatics.studycalendar.dao.StudyCalendarDao;
import gov.nih.nci.cabig.ctms.domain.DomainObject;
import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.criterion.Order;
import org.springframework.orm.hibernate3.HibernateCallback;

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

/**
 * @author John Dzak
 */
public abstract class ReportDao<F extends ReportFilters, R extends DomainObject> extends StudyCalendarDao<R> {
    @SuppressWarnings("unchecked")
    public List<R> search(final F filters) {
        return getHibernateTemplate().executeFind(new HibernateCallback() {
            @SuppressWarnings("unchecked")
            public Object doInHibernate(Session session) throws HibernateException {
                if (filters.isEmpty()) {
                    logger.debug("No filters selected, skipping search: " + filters);
                    return Collections.emptyList();
                } else {
                    Criteria criteria = session.createCriteria(domainClass()).addOrder(Order.asc("id"));
                    filters.apply(session);
                    return (List<R>) criteria.list();

                }
            }
        });
    }
}

Sort for testing. Fix for test failures introduced in r3557.


//////////////////////////////////////////////////////////////////////////////
//
//               Copyright 2010, Starting Block Technologies
//                        www.startingblocktech.com
//
//////////////////////////////////////////////////////////////////////////////

package com.startingblocktech.tcases;

import java.util.Collection;
import java.util.regex.Pattern;

/**
 * Defines utility methods for constructing test definitions.
 *
 * @version $Revision$, $Date$
 */
public abstract class DefUtils
  {
  /**
   * Returns true if the given string is a valid identifier.
   */
  public static boolean isIdentifier( String id)
    {
    return id != null && identifierRegex_.matcher( id).matches();
    }

  /**
   * Throws an exception if the given string is not a valid identifier.
   */
  public static void assertIdentifier( String id) throws IllegalArgumentException
    {
    if( !isIdentifier( id))
      {
      throw new IllegalArgumentException( "\"" + String.valueOf( id) + "\" is not a valid identifier");
      }
    }

  /**
   * Throws an exception if any member of the given set of properties is not a valid identifier.
   */
  public static void assertPropertyIdentifiers( Collection<String> properties) throws IllegalArgumentException
    {
    if( properties != null)
      {
      try
        {
        for( String property : properties)
          {
          assertIdentifier( property);
          }
        }
      catch( Exception e)
        {
        throw new IllegalArgumentException( "Invalid property set", e);
        }
      }
    }

  private static final Pattern identifierRegex_ = Pattern.compile( "[\\w\\-]+");
  }

//////////////////////////////////////////////////////////////////////////////
//
//               Copyright 2010, Starting Block Technologies
//                        www.startingblocktech.com
//
//////////////////////////////////////////////////////////////////////////////

package com.startingblocktech.tcases;

import java.util.Collection;
import java.util.regex.Pattern;

/**
 * Defines utility methods for constructing test definitions.
 *
 * @version $Revision$, $Date$
 */
public abstract class DefUtils
  {
  /**
   * Returns true if the given string is a valid identifier.
   */
  public static boolean isIdentifier( String id)
    {
    return id != null && identifierRegex_.matcher( id).matches();
    }

  /**
   * Throws an exception if the given string is not a valid identifier.
   */
  public static void assertIdentifier( String id) throws IllegalArgumentException
    {
    if( !isIdentifier( id))
      {
      throw
        new IllegalArgumentException
        ( (id==null? "null" : ("\"" + String.valueOf( id) + "\""))
          + " is not a valid identifier");
      }
    }

  /**
   * Throws an exception if any member of the given set of properties is not a valid identifier.
   */
  public static void assertPropertyIdentifiers( Collection<String> properties) throws IllegalArgumentException
    {
    if( properties != null)
      {
      try
        {
        for( String property : properties)
          {
          assertIdentifier( property);
          }
        }
      catch( Exception e)
        {
        throw new IllegalArgumentException( "Invalid property set", e);
        }
      }
    }

  private static final Pattern identifierRegex_ = Pattern.compile( "[\\w\\-]+");
  }

Clean up exception message for null identifier


package openmods.asm;

import net.minecraft.launchwrapper.IClassTransformer;

import org.objectweb.asm.ClassReader;
import org.objectweb.asm.ClassVisitor;
import org.objectweb.asm.ClassWriter;

public class OpenModsClassTransformer implements IClassTransformer {

	public static interface TransformProvider {
		public ClassVisitor createVisitor(ClassVisitor cv);
	}

	private final static TransformProvider INCLUDING_CV = new TransformProvider() {

		@Override
		public ClassVisitor createVisitor(ClassVisitor cv) {
			return new IncludingClassVisitor(cv);
		}
	};

	public static byte[] applyVisitor(byte[] bytes, int flags, TransformProvider context) {
		ClassReader cr = new ClassReader(bytes);
		ClassWriter cw = new ClassWriter(cr, flags);
		ClassVisitor mod = context.createVisitor(cw);

		try {
			cr.accept(mod, 0);
			return cw.toByteArray();
		} catch (StopTransforming e) {
			return bytes;
		}
	}

	@Override
	public byte[] transform(final String name, String transformedName, byte[] bytes) {
		if (name.startsWith("openmods.asm")) return bytes;
		// / no need for COMPUTE_FRAMES, we can handle simple stuff
		return applyVisitor(bytes, 0, INCLUDING_CV);
	}
}

package openmods.asm;

import net.minecraft.launchwrapper.IClassTransformer;

import org.objectweb.asm.ClassReader;
import org.objectweb.asm.ClassVisitor;
import org.objectweb.asm.ClassWriter;

import com.google.common.base.Preconditions;

public class OpenModsClassTransformer implements IClassTransformer {

	public static interface TransformProvider {
		public ClassVisitor createVisitor(ClassVisitor cv);
	}

	private final static TransformProvider INCLUDING_CV = new TransformProvider() {

		@Override
		public ClassVisitor createVisitor(ClassVisitor cv) {
			return new IncludingClassVisitor(cv);
		}
	};

	public static byte[] applyVisitor(byte[] bytes, int flags, TransformProvider context) {
		Preconditions.checkNotNull(bytes);
		ClassReader cr = new ClassReader(bytes);
		ClassWriter cw = new ClassWriter(cr, flags);
		ClassVisitor mod = context.createVisitor(cw);

		try {
			cr.accept(mod, 0);
			return cw.toByteArray();
		} catch (StopTransforming e) {
			return bytes;
		}
	}

	@Override
	public byte[] transform(final String name, String transformedName, byte[] bytes) {
		if (bytes == null || name.startsWith("openmods.asm") || name.startsWith("net.minecraft.")) return bytes;
		// / no need for COMPUTE_FRAMES, we can handle simple stuff
		return applyVisitor(bytes, 0, INCLUDING_CV);
	}
}

Fix crash on missing classes (it will crash later, but nobody will blame us


/*
 * JBoss, Home of Professional Open Source.
 * Copyright 2014 Red Hat, Inc., and individual contributors
 * as indicated by the @author tags.
 *
 * 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.jboss.modules;

import java.lang.management.ManagementFactory;
import java.lang.management.ThreadMXBean;
import java.security.AccessController;

/**
 * @author David M. Lloyd
 */
final class Metrics {
    static final boolean ENABLED;
    static final ThreadMXBean THREAD_MX_BEAN = ManagementFactory.getThreadMXBean();

    private Metrics() {
    }

    static long getCurrentCPUTime() {
        return ENABLED ? false ? THREAD_MX_BEAN.getCurrentThreadCpuTime() : System.nanoTime() : 0L;
    }

    static {
        ENABLED = Boolean.parseBoolean(AccessController.doPrivileged(new PropertyReadAction("jboss.modules.metrics", "false")));
    }
}

/*
 * JBoss, Home of Professional Open Source.
 * Copyright 2014 Red Hat, Inc., and individual contributors
 * as indicated by the @author tags.
 *
 * 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.jboss.modules;

import java.security.AccessController;

/**
 * @author David M. Lloyd
 */
final class Metrics {
    static final boolean ENABLED;

    private Metrics() {
    }

    static long getCurrentCPUTime() {
        return ENABLED ? System.nanoTime() : 0L;
    }

    static {
        ENABLED = Boolean.parseBoolean(AccessController.doPrivileged(new PropertyReadAction("jboss.modules.metrics", "false")));
    }
}

Fix early initialization of log manager on JDK 9+


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

package com.deltadna.android.sdk.notifications.example;

import android.content.Context;
import androidx.core.app.NotificationCompat;

import com.deltadna.android.sdk.notifications.NotificationFactory;
import com.deltadna.android.sdk.notifications.PushMessage;

/**
 * Example of a {@link NotificationFactory} which changes the look of the
 * notification after a push message is received.
 */
public class StyledNotificationFactory extends NotificationFactory {

    public StyledNotificationFactory(Context context) {
        super(context);
    }

    @Override
    public NotificationCompat.Builder configure(
            NotificationCompat.Builder builder,
            PushMessage message){

        return super.configure(builder, message);

    }
}

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

package com.deltadna.android.sdk.notifications.example;

import android.content.Context;
import androidx.core.app.NotificationCompat;

import com.deltadna.android.sdk.notifications.NotificationFactory;
import com.deltadna.android.sdk.notifications.PushMessage;

/**
 * Example of a {@link NotificationFactory} which changes the look of the
 * notification after a push message is received.
 */
public class StyledNotificationFactory extends NotificationFactory {

    public StyledNotificationFactory(Context context) {
        super(context);
    }

    @Override
    public NotificationCompat.Builder configure(
            Context context,
            PushMessage message){

        return super.configure(context, message);

    }
}

Update the example notifications app


package com.codenvy.ide.ext.datasource.client.sqllauncher;

import com.google.gwt.i18n.client.Constants;

public interface SqlRequestLauncherConstants extends Constants {

    @DefaultStringValue("Open SQL editor")
    String menuEntryOpenSqlEditor();

    @DefaultStringValue("SQL editor")
    String sqlEditorWindowTitle();

    @DefaultStringValue("Select datasource")
    String selectDatasourceLabel();

    @DefaultStringValue("Result limit")
    String resultLimitLabel();

    @DefaultStringValue("Execute")
    String executeButtonLabel();
}

package com.codenvy.ide.ext.datasource.client.sqllauncher;

import com.google.gwt.i18n.client.Messages;

public interface SqlRequestLauncherConstants extends Messages {

    @DefaultMessage("Open SQL editor")
    String menuEntryOpenSqlEditor();

    @DefaultMessage("SQL editor")
    String sqlEditorWindowTitle();

    @DefaultMessage("Select datasource")
    String selectDatasourceLabel();

    @DefaultMessage("Result limit")
    String resultLimitLabel();

    @DefaultMessage("Execute")
    String executeButtonLabel();

    @DefaultMessage("{0} rows.")
    String updateCountMessage(int count);
}

Change constants class to messages


package net.darkmorford.btweagles.eventhandler;

import net.darkmorford.btweagles.item.ModItems;
import net.minecraft.init.Blocks;
import net.minecraft.item.ItemStack;
import net.minecraftforge.event.world.BlockEvent;
import net.minecraftforge.fml.common.Mod;
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent;

@Mod.EventBusSubscriber
public class EventHandlerBlockDrops
{
	@SubscribeEvent
	public static void modifyHarvestDrops(BlockEvent.HarvestDropsEvent event)
	{
		if (event.getState().getBlock() == Blocks.GRAVEL)
		{
			event.getDrops().add(new ItemStack(ModItems.shiny_stone));
		}
	}
}

package net.darkmorford.btweagles.eventhandler;

import net.darkmorford.btweagles.item.ModItems;
import net.minecraft.init.Blocks;
import net.minecraft.item.ItemStack;
import net.minecraftforge.event.world.BlockEvent;
import net.minecraftforge.fml.common.Mod;
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent;

import java.util.Random;

@Mod.EventBusSubscriber
public class EventHandlerBlockDrops
{
	@SubscribeEvent
	public static void modifyHarvestDrops(BlockEvent.HarvestDropsEvent event)
	{
		if (event.getState().getBlock() == Blocks.GRAVEL)
		{
			Random rand = event.getWorld().rand;

			if (rand.nextInt(100) < 2)
			{
				event.getDrops().add(new ItemStack(ModItems.shiny_stone));
			}
		}
	}
}

Reduce drop rate of shiny_stone.


package com.twilio.notify.quickstart.notifyapi;

import com.twilio.notify.quickstart.notifyapi.model.Binding;

import retrofit2.Call;
import retrofit2.Retrofit;
import retrofit2.converter.jackson.JacksonConverterFactory;
import retrofit2.http.Body;
import retrofit2.http.POST;

public class TwilioSDKStarterAPI {
    private static String BASE_SERVER_URL = "https://f5ab0b54.ngrok.io";

    /**
     * A resource defined to register Notify bindings using the sdk-starter projects available in
     * C#, Java, Node, PHP, Python, or Ruby.
     *
     * https://github.com/TwilioDevEd?q=sdk-starter
     */
    interface SDKStarterService {
        @POST("/register")
        Call<Void> register(@Body Binding binding);
    }

    private static SDKStarterService sdkStarterService = new Retrofit.Builder()
            .baseUrl(BASE_SERVER_URL)
            .addConverterFactory(JacksonConverterFactory.create())
            .build()
            .create(SDKStarterService.class);

    public static Call<Void> registerBinding(final Binding binding) {
        return sdkStarterService.register(binding);
    }

}

package com.twilio.notify.quickstart.notifyapi;

import com.twilio.notify.quickstart.notifyapi.model.Binding;

import retrofit2.Call;
import retrofit2.Retrofit;
import retrofit2.converter.jackson.JacksonConverterFactory;
import retrofit2.http.Body;
import retrofit2.http.POST;

public class TwilioSDKStarterAPI {
    private static String BASE_SERVER_URL = "YOUR_SDK_STARTER_SERVER_URL";

    /**
     * A resource defined to register Notify bindings using the sdk-starter projects available in
     * C#, Java, Node, PHP, Python, or Ruby.
     *
     * https://github.com/TwilioDevEd?q=sdk-starter
     */
    interface SDKStarterService {
        @POST("/register")
        Call<Void> register(@Body Binding binding);
    }

    private static SDKStarterService sdkStarterService = new Retrofit.Builder()
            .baseUrl(BASE_SERVER_URL)
            .addConverterFactory(JacksonConverterFactory.create())
            .build()
            .create(SDKStarterService.class);

    public static Call<Void> registerBinding(final Binding binding) {
        return sdkStarterService.register(binding);
    }

}

Replace ngrok url with stub


package ru.job4j.even.numbers.iterator;

import java.util.Iterator;
import java.util.NoSuchElementException;

public class EvenNumbersIterator implements Iterator {
    private int[] numbers;
    private int index = 0;
    private int size;

    public EvenNumbersIterator(final int[] numbers) {
        this.numbers = numbers;
        this.size = numbers.length;
    }

    @Override
    public boolean hasNext() {
        int pointer = index;
        while (pointer < size) {
            if (isEvenNumber(numbers[pointer])) {
                return true;
            } else {
                pointer++;
            }
        }
        return false;
    }

    @Override
    public Object next() {
//        if (size == 0 || !hasNext() || index > size) {
        if (!hasNext()) {
            throw new NoSuchElementException();
        }
        int tmp = numbers[index];
        while (index < size) {
            if (isEvenNumber(tmp)) {
                index++;
                break;
            } else {
                tmp = numbers[++index];
            }
        }
        return tmp;
    }

    private boolean isEvenNumber(int num) {
        return num % 2 == 0;
    }
}

package ru.job4j.even.numbers.iterator;

import java.util.Iterator;
import java.util.NoSuchElementException;

public class EvenNumbersIterator implements Iterator {
    private int[] numbers;
    private int index = 0;
    private int size;

    public EvenNumbersIterator(final int[] numbers) {
        this.numbers = numbers;
        this.size = numbers.length;
    }

    @Override
    public boolean hasNext() {
        int pointer = index;
        while (pointer < size) {
            if (isEvenNumber(numbers[pointer])) {
                return true;
            } else {
                pointer++;
            }
        }
        return false;
    }

    @Override
    public Object next() {
        if (!hasNext()) {
            throw new NoSuchElementException();
        }
        int tmp = numbers[index];
        while (index < size) {
            if (isEvenNumber(tmp)) {
                index++;
                break;
            } else {
                tmp = numbers[++index];
            }
        }
        return tmp;
    }

    private boolean isEvenNumber(int num) {
        return num % 2 == 0;
    }
}

Add a change to method.


/*
 * Copyright Red Hat Inc. and/or its affiliates and other contributors
 * as indicated by the authors tag. All rights reserved.
 *
 * This copyrighted material is made available to anyone wishing to use,
 * modify, copy, or redistribute it subject to the terms and conditions
 * of the GNU General Public License version 2.
 *
 * This particular file is subject to the "Classpath" exception as provided in the
 * LICENSE file that accompanied this code.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT A
 * 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 distribution; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
 * MA  02110-1301, USA.
 */
package com.redhat.ceylon.common.tool;

import java.text.MessageFormat;
import java.util.ResourceBundle;

class ToolMessages {

    private static final ResourceBundle RESOURCE_BUNDLE = ResourceBundle.getBundle("com.redhat.ceylon.common.tool.tools");

    public static String msg(String msgKey, Object... msgArgs) {
        String msg = RESOURCE_BUNDLE.getString(msgKey);
        if (msgArgs != null) {
            msg = MessageFormat.format(msg, msgArgs);
        }
        return msg;
    }

}

/*
 * Copyright Red Hat Inc. and/or its affiliates and other contributors
 * as indicated by the authors tag. All rights reserved.
 *
 * This copyrighted material is made available to anyone wishing to use,
 * modify, copy, or redistribute it subject to the terms and conditions
 * of the GNU General Public License version 2.
 *
 * This particular file is subject to the "Classpath" exception as provided in the
 * LICENSE file that accompanied this code.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT A
 * 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 distribution; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
 * MA  02110-1301, USA.
 */
package com.redhat.ceylon.common.tool;

import java.util.ResourceBundle;

import com.redhat.ceylon.common.Messages;

class ToolMessages extends Messages {

    private static final ResourceBundle RESOURCE_BUNDLE = ResourceBundle.getBundle("com.redhat.ceylon.common.tool.tools");

    public static String msg(String msgKey, Object... msgArgs) {
        return msg(RESOURCE_BUNDLE, msgKey, msgArgs);
    }

}

Extend the common Messages class


package gigaherz.graph.api;

import net.minecraftforge.fml.common.Mod;
import net.minecraftforge.fml.common.Mod.EventHandler;
import net.minecraftforge.fml.common.SidedProxy;
import net.minecraftforge.fml.common.event.FMLInitializationEvent;
import net.minecraftforge.fml.common.event.FMLInterModComms;
import net.minecraftforge.fml.common.event.FMLPreInitializationEvent;
import net.minecraftforge.fml.common.registry.GameRegistry;

@Mod(modid = GraphApiTest.MODID, version = GraphApiTest.VERSION)
public class GraphApiTest
{
    public static final String MODID = "GraphLib";
    public static final String VERSION = "1.0";

    @SidedProxy(clientSide = "gigaherz.graph.api.ClientProxy", serverSide = "gigaherz.graph.api.Proxy")
    public static Proxy proxy;

    public static BlockRegistered networkTest;

    @EventHandler
    public void preInit(FMLPreInitializationEvent event)
    {
        networkTest = new BlockNetworkTest("blockNetworkTest");
        GameRegistry.register(networkTest);
        GameRegistry.register(networkTest.createItemBlock());
        GameRegistry.registerTileEntity(TileNetworkTest.class, "tileNetworkTest");

        proxy.preInit();
    }

    @EventHandler
    public void init(FMLInitializationEvent event)
    {
        proxy.init();

        FMLInterModComms.sendMessage("Waila", "register", "gigaherz.graph.api.WailaProviders.callbackRegister");
    }
}

package gigaherz.graph.api;

import net.minecraftforge.fml.common.Mod;
import net.minecraftforge.fml.common.Mod.EventHandler;
import net.minecraftforge.fml.common.SidedProxy;
import net.minecraftforge.fml.common.event.FMLInitializationEvent;
import net.minecraftforge.fml.common.event.FMLInterModComms;
import net.minecraftforge.fml.common.event.FMLPreInitializationEvent;
import net.minecraftforge.fml.common.registry.GameRegistry;

@Mod(modid = GraphApiTest.MODID, version = GraphApiTest.VERSION)
public class GraphApiTest
{
    public static final String MODID = "GraphLib";
    public static final String VERSION = Constants.API_VERSION;

    @SidedProxy(clientSide = "gigaherz.graph.api.ClientProxy", serverSide = "gigaherz.graph.api.Proxy")
    public static Proxy proxy;

    public static BlockRegistered networkTest;

    @EventHandler
    public void preInit(FMLPreInitializationEvent event)
    {
        networkTest = new BlockNetworkTest("blockNetworkTest");
        GameRegistry.register(networkTest);
        GameRegistry.register(networkTest.createItemBlock());
        GameRegistry.registerTileEntity(TileNetworkTest.class, "tileNetworkTest");

        proxy.preInit();
    }

    @EventHandler
    public void init(FMLInitializationEvent event)
    {
        proxy.init();

        FMLInterModComms.sendMessage("Waila", "register", "gigaherz.graph.api.WailaProviders.callbackRegister");
    }
}

Make the test mod take the version from the API.


package jkind.api.results;

import java.util.Map;

/**
 * A renaming backed by a map from strings to strings
 */
public class MapRenaming extends Renaming {
	private Map<String, String> map;

	public MapRenaming(Map<String, String> map) {
		this.map = map;
	}

	@Override
	public String rename(String original) {
		return map.get(original);
	}
}

package jkind.api.results;

import java.util.Map;

/**
 * A renaming backed by a map from strings to strings
 */
public class MapRenaming extends Renaming {
	private final Map<String, String> map;
	private final Mode mode;

	public static enum Mode {
		NULL, IDENTITY
	}

	public MapRenaming(Map<String, String> map, Mode mode) {
		this.map = map;
		this.mode = mode;
	}

	@Override
	public String rename(String original) {
		String renamed = map.get(original);
		if (renamed == null && mode == Mode.IDENTITY) {
			return original;
		} else {
			return renamed;
		}
	}
}

Add two options for map renamings


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

/**
 * Test environment classes for tests of the {@link io.spine.server.storage.jdbc.aggregate} package.
 */

@ParametersAreNonnullByDefault
package io.spine.server.storage.jdbc.aggregate.given;

import javax.annotation.ParametersAreNonnullByDefault;

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

/**
 * Test environment classes for tests of the {@link io.spine.server.storage.jdbc.aggregate} package.
 */

@CheckReturnValue
@ParametersAreNonnullByDefault
package io.spine.server.storage.jdbc.aggregate.given;

import com.google.errorprone.annotations.CheckReturnValue;

import javax.annotation.ParametersAreNonnullByDefault;

Add `@CheckReturnValue` to package info


package gov.samhsa.c2s.c2suiapi.infrastructure.dto;

import gov.samhsa.c2s.common.validator.constraint.PresentOrFuture;
import lombok.Data;
import org.hibernate.validator.constraints.ScriptAssert;

import javax.validation.Valid;
import javax.validation.constraints.Future;
import javax.validation.constraints.NotNull;
import java.time.LocalDate;

@Data
@ScriptAssert(
        lang = "javascript",
        alias = "_",
        script = "_.startDate != null && _.endDate != null && _.startDate.isBefore(_.endDate)",
        message = "consent end date must be after consent start date")
public class ConsentDto {
    private Long id;
    @NotNull
    @Future
    private LocalDate endDate;
    @Valid
    @NotNull
    private IdentifiersDto fromProviders;
    @Valid
    @NotNull
    private IdentifiersDto sharePurposes;
    @Valid
    @NotNull
    private IdentifiersDto shareSensitivityCategories;
    @NotNull
    @PresentOrFuture
    private LocalDate startDate;
    @Valid
    @NotNull
    private IdentifiersDto toProviders;
}

package gov.samhsa.c2s.c2suiapi.infrastructure.dto;

import gov.samhsa.c2s.common.validator.constraint.PresentOrFuture;
import lombok.Data;
import org.hibernate.validator.constraints.ScriptAssert;

import javax.validation.Valid;
import javax.validation.constraints.Future;
import javax.validation.constraints.NotNull;
import java.time.LocalDate;

@Data
@ScriptAssert(
        lang = "javascript",
        alias = "_",
        script = "_.startDate != null && _.endDate != null && _.startDate.isBefore(_.endDate)",
        message = "consent end date must be after consent start date")
public class ConsentDto {
    private Long id;
    @NotNull
    @Future
    private LocalDate endDate;
    @Valid
    @NotNull
    private IdentifiersDto fromProviders;
    @Valid
    @NotNull
    private IdentifiersDto purposes;
    @Valid
    @NotNull
    private IdentifiersDto sensitivityCategories;
    @NotNull
    @PresentOrFuture
    private LocalDate startDate;
    @Valid
    @NotNull
    private IdentifiersDto toProviders;

    @NotNull
    private boolean shareSensitivityCategoriesEnabled;
}

Update Consent Dto to have shareSensitivityCategoriesEnabled attribute


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

import org.eclipse.egit.github.core.client.GitHubClient;

/**
 * Default client used to communicate with GitHub API
 */
public class DefaultClient extends GitHubClient {

    private static final String USER_AGENT = "GitHubAndroid/1.9";

    /**
     * Create client
     */
    public DefaultClient() {
        super();

        setSerializeNulls(false);
        setUserAgent(USER_AGENT);
    }
}

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

import org.eclipse.egit.github.core.client.GitHubClient;

/**
 * Default client used to communicate with GitHub API
 */
public class DefaultClient extends GitHubClient {

    private static final String USER_AGENT = "ForkHub/1.0";

    /**
     * Create client
     */
    public DefaultClient() {
        super();

        setSerializeNulls(false);
        setUserAgent(USER_AGENT);
    }
}

Update user agent for all requests


package replicant.messages;

import elemental2.core.JsObject;
import javax.annotation.Nonnull;
import jsinterop.annotations.JsOverlay;
import jsinterop.annotations.JsPackage;
import jsinterop.annotations.JsType;
import jsinterop.base.Any;
import jsinterop.base.Js;

/**
 * A simple abstraction for key-value etag pairs.
 */
@JsType( isNative = true, name = "Object", namespace = JsPackage.GLOBAL )
public interface EtagsData
{
  /**
   * Return true if etag for channel is present.
   *
   * @param key the channel key.
   * @return true if the etag is present.
   */
  @JsOverlay
  default boolean containsChannel( @Nonnull final String key )
  {
    return Js.asPropertyMap( this ).has( key );
  }

  /**
   * Return the channels.
   *
   * @return eturn the channels.
   */
  @JsOverlay
  default String[] channels()
  {
    return JsObject.keys( this );
  }

  @Nonnull
  @JsOverlay
  default String getEtag( @Nonnull final String key )
  {
    final Any any = Js.asPropertyMap( this ).getAsAny( key );
    assert null != any;
    return any.asString();
  }
}

package replicant.messages;

import elemental2.core.JsArray;
import elemental2.core.JsObject;
import javax.annotation.Nonnull;
import jsinterop.annotations.JsOverlay;
import jsinterop.annotations.JsPackage;
import jsinterop.annotations.JsType;
import jsinterop.base.Any;
import jsinterop.base.Js;

/**
 * A simple abstraction for key-value etag pairs.
 */
@JsType( isNative = true, name = "Object", namespace = JsPackage.GLOBAL )
public interface EtagsData
{
  /**
   * Return true if etag for channel is present.
   *
   * @param key the channel key.
   * @return true if the etag is present.
   */
  @JsOverlay
  default boolean containsChannel( @Nonnull final String key )
  {
    return Js.asPropertyMap( this ).has( key );
  }

  /**
   * Return the channels.
   *
   * @return eturn the channels.
   */
  @JsOverlay
  default String[] channels()
  {
    final JsArray<String> keys = JsObject.keys( this );
    return keys.asArray( new String[ keys.length ] );
  }

  @Nonnull
  @JsOverlay
  default String getEtag( @Nonnull final String key )
  {
    final Any any = Js.asPropertyMap( this ).getAsAny( key );
    assert null != any;
    return any.asString();
  }
}

Upgrade to the latest Elemental2 API


package nl.thehyve.ocdu.validators.fileValidators;

import nl.thehyve.ocdu.models.OCEntities.ClinicalData;
import nl.thehyve.ocdu.models.OcDefinitions.MetaData;
import nl.thehyve.ocdu.validators.ClinicalDataChecksRunner;
import nl.thehyve.ocdu.validators.clinicalDataChecks.ClinicalDataCrossCheck;
import nl.thehyve.ocdu.validators.clinicalDataChecks.CrfCouldNotBeVerifiedCrossCheck;
import nl.thehyve.ocdu.validators.clinicalDataChecks.CrfExistsCrossCheck;
import nl.thehyve.ocdu.validators.clinicalDataChecks.SiteSubjectMatchCrossCheck;
import nl.thehyve.ocdu.validators.clinicalDataChecks.SitesExistCrossCheck;
import nl.thehyve.ocdu.validators.clinicalDataChecks.StudyStatusAvailable;
import org.openclinica.ws.beans.StudySubjectWithEventsType;

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

/**
 * Created by piotrzakrzewski on 22/06/16.
 */
public class DataPreMappingValidator extends ClinicalDataChecksRunner {

    public DataPreMappingValidator(MetaData metadata, List<ClinicalData> clinicalData, List<StudySubjectWithEventsType> subjectWithEventsTypes) {
        super(metadata, clinicalData, subjectWithEventsTypes);
        Collection<ClinicalDataCrossCheck> checks = new ArrayList<>();
        checks.add(new SitesExistCrossCheck());
        checks.add(new SiteSubjectMatchCrossCheck());
        checks.add(new CrfExistsCrossCheck());
        checks.add(new StudyStatusAvailable());
        checks.add(new CrfCouldNotBeVerifiedCrossCheck());
        this.setChecks(checks);
    }
}

package nl.thehyve.ocdu.validators.fileValidators;

import nl.thehyve.ocdu.models.OCEntities.ClinicalData;
import nl.thehyve.ocdu.models.OcDefinitions.MetaData;
import nl.thehyve.ocdu.validators.ClinicalDataChecksRunner;
import nl.thehyve.ocdu.validators.clinicalDataChecks.*;
import org.openclinica.ws.beans.StudySubjectWithEventsType;

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

/**
 * Created by piotrzakrzewski on 22/06/16.
 */
public class DataPreMappingValidator extends ClinicalDataChecksRunner {

    public DataPreMappingValidator(MetaData metadata, List<ClinicalData> clinicalData, List<StudySubjectWithEventsType> subjectWithEventsTypes) {
        super(metadata, clinicalData, subjectWithEventsTypes);
        Collection<ClinicalDataCrossCheck> checks = new ArrayList<>();
        checks.add(new SitesExistCrossCheck());
        checks.add(new SiteSubjectMatchCrossCheck());
        checks.add(new CrfExistsCrossCheck());
        checks.add(new StudyStatusAvailable());
        checks.add(new CrfCouldNotBeVerifiedCrossCheck());
        checks.add(new EventExistsCrossCheck());
        this.setChecks(checks);
    }
}

Add event existence to the mapping pre checks


package cgeo.geocaching.sorting;

import cgeo.geocaching.Geocache;
import cgeo.geocaching.utils.TextUtils;

import org.apache.commons.lang3.StringUtils;

import java.text.Collator;

/**
 * sorts caches by name
 *
 */
class NameComparator extends AbstractCacheComparator {

    private final Collator collator;

    public NameComparator() {
        collator = TextUtils.getCollator();
    }

    @Override
    protected boolean canCompare(final Geocache cache) {
        return StringUtils.isNotBlank(cache.getName());
    }

    @Override
    protected int compareCaches(final Geocache cache1, final Geocache cache2) {
        return collator.compare(cache1.getNameForSorting(), cache2.getNameForSorting());
    }
}

package cgeo.geocaching.sorting;

import cgeo.geocaching.Geocache;
import cgeo.geocaching.utils.TextUtils;

import org.apache.commons.lang3.StringUtils;

import java.text.Collator;

/**
 * sorts caches by name
 *
 */
class NameComparator extends AbstractCacheComparator {

    private final Collator collator = TextUtils.getCollator();

    @Override
    protected boolean canCompare(final Geocache cache) {
        return StringUtils.isNotBlank(cache.getName());
    }

    @Override
    protected int compareCaches(final Geocache cache1, final Geocache cache2) {
        return collator.compare(cache1.getNameForSorting(), cache2.getNameForSorting());
    }
}

Initialize final field in field declaration


/*
 * Copyright 2015 Hewlett-Packard Development Company, L.P.
 * Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License.
 */

package com.hp.autonomy.searchcomponents.core.search;

import com.hp.autonomy.types.requests.Documents;

import java.io.Serializable;
import java.util.List;
import java.util.Set;

public interface DocumentsService<S extends Serializable, D extends SearchResult, E extends Exception> {
    String HIGHLIGHT_START_TAG = "<Find-IOD-QueryText-Placeholder>";
    String HIGHLIGHT_END_TAG = "</Find-IOD-QueryText-Placeholder>";

    Documents<D> queryTextIndex(final SearchRequest<S> searchRequest) throws E;

    Documents<D> queryTextIndexForPromotions(final SearchRequest<S> searchRequest) throws E;

    List<D> findSimilar(Set<S> indexes, String reference) throws E;

}

/*
 * Copyright 2015 Hewlett-Packard Development Company, L.P.
 * Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License.
 */

package com.hp.autonomy.searchcomponents.core.search;

import com.hp.autonomy.types.requests.Documents;

import java.io.Serializable;
import java.util.List;
import java.util.Set;

public interface DocumentsService<S extends Serializable, D extends SearchResult, E extends Exception> {
    String HIGHLIGHT_START_TAG = "<HavenSearch-QueryText-Placeholder>";
    String HIGHLIGHT_END_TAG = "</HavenSearch-QueryText-Placeholder>";

    Documents<D> queryTextIndex(final SearchRequest<S> searchRequest) throws E;

    Documents<D> queryTextIndexForPromotions(final SearchRequest<S> searchRequest) throws E;

    List<D> findSimilar(Set<S> indexes, String reference) throws E;

}

Change custom tag name [rev. matthew.gordon]


package a4_p01_JS_MJ_test;

public class a4Test {

}

package a4_p01_JS_MJ_test;

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

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

import org.jgrapht.Graph;
import org.jgrapht.WeightedGraph;
import org.jgrapht.graph.DefaultEdge;
import org.jgrapht.graph.DefaultWeightedEdge;
import org.jgrapht.graph.Pseudograph;
import org.junit.BeforeClass;
import org.junit.Test;

import a1_p01_JS_MJ.GraphParser;
import a1_p01_JS_MJ.GraphvizAdapter;
import a1_p01_JS_MJ.SearchResult;
import a2_p01_JS_MJ.AttributedNode;
import a2_p01_JS_MJ.GraphGenerator;
import a3_p01_JS_MJ.Kruskal;
import a4_p01_JS_MJ.Fleury;
import a4_p01_JS_MJ.Hierholzer;

public class a4Test {

	static Graph graphk5;
	static WeightedGraph<AttributedNode<String>, DefaultWeightedEdge> genGraph;

	@BeforeClass
	public static void init() {
		try {
			graphk5 = GraphParser.parseGraphFile("GraphK5.gka");
		} catch(Exception ex) {
			ex.printStackTrace();
		}
		genGraph = GraphGenerator.generateAttributedWeightedGraph(150, 30);
	}

	@Test
	public void fleury_test(){
		Fleury<String> fleury = new Fleury<String>();
		SearchResult result = fleury.search((Pseudograph<String, DefaultEdge>) graphk5);
		printTestResult("Test 1: Fleury - Graph K5", result);
		System.out.println("Test Green.");
		System.out.println("");
	}

	@Test
	public void hierholzer_test(){
		Hierholzer<String> hierholzer = new Hierholzer<String>();
		SearchResult result = hierholzer.algorithm((Pseudograph<String, DefaultEdge>) graphk5);
		printTestResult("Test 1: Fleury - Graph K5", result);
		System.out.println("Test Green.");
		System.out.println("");
	}

	public void printTestResult(String testname, SearchResult result){
		System.out.println(testname);
		System.out.print("Path: ");
		for(DefaultEdge s : (ArrayList<DefaultEdge>) result.getPath()){
			System.out.print(s+", ");
		}
		System.out.println("");
		System.out.println("Path Length " + result.getPathLength()+1);
		System.out.println("Accssess Counter: " + result.getAccsessCounter());
	}
}

Test with K5 graph for fleury and hierholzer added.


class forNameTest {
       public static void main(String argv[]) {
	      try {
		     Class.forName("loadThis");
		     Class c = Class.forName("loadThis", false,
		        new ClassLoader() {
			  public Class loadClass(String n, boolean resolve)
				      throws ClassNotFoundException {
				Class cl = findSystemClass(n);
				if (resolve) {
				      resolveClass(cl);
				}
				return cl;
			  }
		        });
		     System.out.println("constructor not called");
		     c.newInstance();
	      }
	      catch( Exception e ) {
		      System.out.println(e.getMessage());
		      e.printStackTrace();
	      }
       }
}

class loadThis {
      static {
	      try {
		      new loadThis();
	      }
	      catch( Exception e ) {
		      System.out.println(e.getMessage());
		      e.printStackTrace();
	      }
      }

      public loadThis() {
	      System.out.println("constructor called");
      }
}

/* Expected Output:
constructor called
constructor not called
constructor called
*/

class forNameTest {
       public static void main(String argv[]) {
	      try {
		     Class.forName("loadThis");
		     Class c = Class.forName("loadThis", false,
		        new ClassLoader() {
			  public Class loadClass(String n)
				throws ClassNotFoundException {
				return findSystemClass(n);
			  }
		        });
		     System.out.println("constructor not called");
		     c.newInstance();
	      }
	      catch( Exception e ) {
		      System.out.println(e.getMessage());
		      e.printStackTrace();
	      }
       }
}

class loadThis {
      static {
	      try {
		      new loadThis();
	      }
	      catch( Exception e ) {
		      System.out.println(e.getMessage());
		      e.printStackTrace();
	      }
      }

      public loadThis() {
	      System.out.println("constructor called");
      }
}

/* Expected Output:
constructor called
constructor not called
constructor called
*/

Revert to previous version.. it should still work.


package com.google.sps.servlets;

import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseAuthException;
import com.google.firebase.auth.SessionCookieOptions;
import com.google.sps.firebase.FirebaseAppManager;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/init")
public class SessionInit extends HttpServlet {
  // Return empty string if no comment, otherwise return text
  private String getParameter(HttpServletRequest request, String name, String defaultValue) {
    String value = request.getParameter(name);
    if (value == null) {
      return defaultValue;
    } else {
      return value;
    }
  }
}

package com.google.sps.servlets;

import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseAuthException;
import com.google.firebase.auth.SessionCookieOptions;
import com.google.sps.firebase.FirebaseAppManager;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/init")
public class SessionInit extends HttpServlet {
  // Return empty string if no comment, otherwise return text
  private String getParameter(HttpServletRequest request, String name, String defaultValue) {
    String value = request.getParameter(name);
    if (value == null) {
      return defaultValue;
    } else {
      return value;
    }
  }

  @Override
  public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
    String idToken = getParameter(request, "idToken", "");
    // Set session expiration to 5 days.
    long expiresIn = TimeUnit.DAYS.toMillis(5);
    SessionCookieOptions options = SessionCookieOptions.builder().setExpiresIn(expiresIn).build();
    try {
      // Create the session cookie. This will also verify the ID token in the process.
      // The session cookie will have the same claims as the ID token.
      String sessionCookie =
          FirebaseAuth.getInstance(FirebaseAppManager.getApp())
              .createSessionCookie(idToken, options);
      // Set cookie policy parameters as required.
      Cookie cookie = new Cookie("session", sessionCookie /* ... other parameters */);
      cookie.setMaxAge((int) TimeUnit.MILLISECONDS.toSeconds(expiresIn));
      response.addCookie(cookie);
    } catch (FirebaseAuthException e) {
      response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    }
  }
}

Create session cookie that expires in 5 days.


package see.integration;

import org.junit.experimental.theories.DataPoints;
import org.junit.experimental.theories.Theories;
import org.junit.experimental.theories.Theory;
import org.junit.runner.RunWith;
import see.See;
import see.tree.Node;

import static org.junit.Assert.assertEquals;

@RunWith(Theories.class)
public class TreeEquivalenceTest {
    See see = new See();

    @DataPoints
    public static final String[] data = {"a", "1+2", "sum(2,3)", "9+42+100500.0", "a = 5", "isDefined(crn)"};

    @Theory
    public void testEquivalence(String example) throws Exception {
        Node<Object> run1 = see.parseExpression(example);
        Node<Object> run2 = see.parseExpression(example);

        assertEquals(run1, run2);
    }
}

package see.integration;

import org.junit.experimental.theories.DataPoints;
import org.junit.experimental.theories.Theories;
import org.junit.experimental.theories.Theory;
import org.junit.runner.RunWith;
import see.See;
import see.tree.Node;

import static org.junit.Assert.assertEquals;

@RunWith(Theories.class)
public class TreeEquivalenceTest {
    See see = new See();

    @DataPoints
    public static final String[] data = {"a", "1+2", "sum(2,3)", "9+42+100500.0", "a = 5", "isDefined(crn)"};

    @Theory
    public void testEquivalence(String example) throws Exception {
        Node<Object> run1 = see.parseExpression(example);
        Node<Object> run2 = see.parseExpression(example);

        assertEquals(run1, run2);
        assertEquals(run1.hashCode(), run2.hashCode());
    }
}

Test for tree equivalence now checks hashCode


package com.axellience.vuegwt.client.definitions;

import com.axellience.vuegwt.client.VueComponent;

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

/**
 * A Cache for generated VueComponentDefinitions.
 * Using static initializer block, VueComponentDefinitions register an instance of themselves in
 * this Cache.
 * VueGWT then use this cache to get definitions for VueComponents.
 * @author Adrien Baron
 */
public class VueComponentDefinitionCache
{
    private static Map<Class<? extends VueComponent>, VueComponentDefinition>
        componentDefinitionsCache = new HashMap<>();

    public static void registerComponent(Class<? extends VueComponent> vueComponentClass,
        VueComponentDefinition componentDefinition)
    {
        componentDefinitionsCache.put(vueComponentClass, componentDefinition);
    }

    public static VueComponentDefinition getComponentDefinitionForClass(
        Class<? extends VueComponent> vueComponentClass)
    {
        VueComponentDefinition componentDefinition =
            componentDefinitionsCache.get(vueComponentClass);
        if (componentDefinition != null)
            return componentDefinition;

        throw new RuntimeException(
            "Couldn't find the given Component " + vueComponentClass.getCanonicalName() +
                ". Are you sure annotations are being processed?");
    }
}

package com.axellience.vuegwt.client.definitions;

import com.axellience.vuegwt.client.VueComponent;

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

/**
 * A Cache for generated VueComponentDefinitions.
 * Using static initializer block, VueComponentDefinitions register an instance of themselves in
 * this Cache.
 * VueGWT then use this cache to get definitions for VueComponents.
 * @author Adrien Baron
 */
public class VueComponentDefinitionCache
{
    private static Map<Class<? extends VueComponent>, VueComponentDefinition>
        componentDefinitionsCache = new HashMap<>();

    public static void registerComponent(Class<? extends VueComponent> vueComponentClass,
        VueComponentDefinition componentDefinition)
    {
        componentDefinitionsCache.put(vueComponentClass, componentDefinition);
    }

    public static VueComponentDefinition getComponentDefinitionForClass(
        Class<? extends VueComponent> vueComponentClass)
    {
        VueComponentDefinition componentDefinition =
            componentDefinitionsCache.get(vueComponentClass);
        if (componentDefinition != null)
            return componentDefinition;

        throw new RuntimeException("Couldn't find the given Component "
            + vueComponentClass.getCanonicalName()
            + ". Make sure your annotations are being processed, and that you added the -generateJsInteropExports flag to GWT.");
    }
}

Improve error message when Component is not found in Cache


/*
 * 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.hadoop.hbase.client;

import static org.apache.hadoop.hbase.HConstants.CLIENT_CONNECTION_REGISTRY_IMPL_CONF_KEY;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.util.ReflectionUtils;
import org.apache.yetus.audience.InterfaceAudience;

/**
 * Factory class to get the instance of configured connection registry.
 */
@InterfaceAudience.Private
final class ConnectionRegistryFactory {

  private ConnectionRegistryFactory() {
  }

  /**
   * @return The connection registry implementation to use.
   */
  static ConnectionRegistry getRegistry(Configuration conf) {
    Class<? extends ConnectionRegistry> clazz = conf.getClass(
        CLIENT_CONNECTION_REGISTRY_IMPL_CONF_KEY, ZKConnectionRegistry.class,
        ConnectionRegistry.class);
    return ReflectionUtils.newInstance(clazz, conf);
  }
}

/*
 * 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.hadoop.hbase.client;

import static org.apache.hadoop.hbase.HConstants.CLIENT_CONNECTION_REGISTRY_IMPL_CONF_KEY;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.util.ReflectionUtils;
import org.apache.yetus.audience.InterfaceAudience;

/**
 * Factory class to get the instance of configured connection registry.
 */
@InterfaceAudience.Private
final class ConnectionRegistryFactory {

  private ConnectionRegistryFactory() {
  }

  /**
   * @return The connection registry implementation to use.
   */
  static ConnectionRegistry getRegistry(Configuration conf) {
    Class<? extends ConnectionRegistry> clazz = conf.getClass(
        CLIENT_CONNECTION_REGISTRY_IMPL_CONF_KEY, MasterRegistry.class,
        ConnectionRegistry.class);
    return ReflectionUtils.newInstance(clazz, conf);
  }
}

Revert "Switch the default registry to ZK based"


package com.example.client;

import jsinterop.annotations.JsMethod;
import jsinterop.annotations.JsPackage;
import jsinterop.annotations.JsType;

@JsType(isNative = true)
public class Dragula {

	@JsMethod(namespace = JsPackage.GLOBAL)
	public native static Dragula dragula(Element... elements);

}

package com.example.client;

import jsinterop.annotations.JsMethod;
import jsinterop.annotations.JsOverlay;
import jsinterop.annotations.JsPackage;
import jsinterop.annotations.JsProperty;
import jsinterop.annotations.JsType;

@JsType(isNative = true)
public class Dragula {

	@JsMethod(namespace = JsPackage.GLOBAL)
	public native static Dragula dragula(Element... elements);

	@JsMethod(namespace = JsPackage.GLOBAL)
	public native static Dragula dragula(Element[] elements, DragulaOptions options);

	@JsMethod(namespace = JsPackage.GLOBAL)
	public native static Dragula dragula(DragulaOptions options);

	@JsOverlay
	public static Dragula dragula(Element element, DragulaOptions options) {
		return dragula(new Element[] { element }, options);
	}

	@JsOverlay
	public static Dragula dragula(Element element, Element element2, DragulaOptions options) {
		return dragula(new Element[] { element, element2 }, options);
	}

	@JsOverlay
	public static Dragula dragula(Element element, Element element2, Element element3, DragulaOptions options) {
		return dragula(new Element[] { element, element2, element3 }, options);
	}

	@JsOverlay
	public static Dragula dragula(DragulaOptions options, Element... elements) {
		return dragula(elements, options);
	}

	@JsProperty
	public native JsArray<Element> getContainers();

}

Add more methods to dragula


package interfaces;

import java.util.List;

public interface Semantics {

	public List<Integer> getPossibleActions(Graph graph) throws Exception;

	public Graph executeAction(Graph graph, List<Integer> ids) throws Exception;

	public boolean isFinished(Graph graph) throws Exception;

}

Remove some weird unnecessary whitespace


package codesample.java10;

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

public class NewStuffJavaTen {
    public static void main(String[] args) {

        /* Type-inference (Note: does not work for non-local variables, array initializers,
        lambdas (when you create lambda. Returning result into var is OK) */
        var message = "Hello, world!";
        System.out.println(message);

        // Note: This will be array list of Objects
        var empList = new ArrayList<>();

        /* copyOf for collections */
        var list = List.of(1,2,3);
        var copy = List.copyOf(list);

        /* unmodifiable collections on collectors*/
        var set = copy.stream()
                .map(value -> value * 3)
                .collect(Collectors.toUnmodifiableSet());

        /* orElseThrow without arguments throws NoSuchElementException */
        var oneElementList = List.of(5);
        var onlyElement = oneElementList.stream()
                .filter(value -> value > 3)
                .findFirst()
                .orElseThrow();
    }
}

package codesample.java10;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class NewStuffJavaTen {
    public static void main(String[] args) {

        /* Type-inference (Note: does not work for non-local variables, array initializers,
        lambdas (when you create lambda. Returning result into var is OK) */
        var message = "Hello, world!";

        var кукареку = new Кукареку<Кукарек>();

        System.out.println(message);

        // Note: This will be array list of Objects
        var empList = new ArrayList<>();

        /* copyOf for collections */
        var list = List.of(1,2,3);
        var copy = List.copyOf(list);

        /* unmodifiable collections on collectors*/
        var set = copy.stream()
                .map(value -> value * 3)
                .collect(Collectors.toUnmodifiableSet());

        /* orElseThrow without arguments throws NoSuchElementException */
        var oneElementList = List.of(5);
        var onlyElement = oneElementList.stream()
                .filter(value -> value > 3)
                .findFirst()
                .orElseThrow();

        var var = Var.var();
        var.var().var().var().var();

        var listOfInt = new ArrayList<Integer>(List.of(1,2,3));
        var copyy = Collections.unmodifiableList(listOfInt);
        System.out.println(copyy);
        listOfInt.add(4);
        System.out.println(copyy);
    }

    public interface Animal {}
    public interface Cat extends Animal { void meow(); }
    public interface Dog extends Animal { void woof(); }

    void makeSound(Animal animal) {
        var catDog = (Cat & Dog) animal;
        catDog.meow();
        catDog.woof();
    }

    static class Кукареку<T> {

    }

    static class Кукарек {

    }

    public static class Var {
        public static Var var() {
            return new Var();
        }
    }
}

Add new java 10 code