/*
 * Copyright (C) 2009 JavaRosa
 *
 * 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.javarosa.xpath.parser.ast;

import org.javarosa.xpath.expr.XPathExpression;
import org.javarosa.xpath.expr.XPathFilterExpr;
import org.javarosa.xpath.parser.XPathSyntaxException;

import java.util.Enumeration;
import java.util.Vector;

public class ASTNodeFilterExpr extends ASTNode {
    public ASTNodeAbstractExpr expr;
    public Vector predicates;

    public ASTNodeFilterExpr() {
        predicates = new Vector();
    }

    public Vector getChildren() {
        Vector v = new Vector();
        v.addElement(expr);
        for (Enumeration e = predicates.elements(); e.hasMoreElements(); )
            v.addElement(e.nextElement());
        return v;
    }

    public XPathExpression build() throws XPathSyntaxException {
        XPathExpression[] preds = new XPathExpression[predicates.size()];
        for (int i = 0; i < preds.length; i++)
            preds[i] = ((ASTNode)predicates.elementAt(i)).build();

        return new XPathFilterExpr(expr.build(), preds);
    }
}

package org.javarosa.xpath.parser.ast;

import org.javarosa.xpath.expr.XPathExpression;
import org.javarosa.xpath.expr.XPathFilterExpr;
import org.javarosa.xpath.parser.XPathSyntaxException;

import java.util.Enumeration;
import java.util.Vector;

public class ASTNodeFilterExpr extends ASTNode {
    public ASTNodeAbstractExpr expr;
    public Vector predicates;

    public ASTNodeFilterExpr() {
        predicates = new Vector();
    }

    @Override
    public Vector getChildren() {
        Vector v = new Vector();
        v.addElement(expr);
        for (Enumeration e = predicates.elements(); e.hasMoreElements(); )
            v.addElement(e.nextElement());
        return v;
    }

    @Override
    public XPathExpression build() throws XPathSyntaxException {
        XPathExpression[] preds = new XPathExpression[predicates.size()];
        for (int i = 0; i < preds.length; i++)
            preds[i] = ((ASTNode)predicates.elementAt(i)).build();

        return new XPathFilterExpr(expr.build(), preds);
    }
}

Add override and remove licensing comment


package com.veyndan.redditclient;

import android.app.Application;

import com.squareup.leakcanary.LeakCanary;
import com.twitter.sdk.android.Twitter;
import com.twitter.sdk.android.core.TwitterAuthConfig;

import io.fabric.sdk.android.Fabric;
import timber.log.Timber;

public class RedditClientApp extends Application {

    @Override
    public void onCreate() {
        super.onCreate();
        if (BuildConfig.DEBUG) {
            Timber.plant(new Timber.DebugTree());
        }
        final TwitterAuthConfig authConfig = new TwitterAuthConfig(Config.TWITTER_KEY, Config.TWITTER_SECRET);
        Fabric.with(this, new Twitter(authConfig));
        LeakCanary.install(this);
    }
}

package com.veyndan.redditclient;

import android.app.Application;

import com.squareup.leakcanary.LeakCanary;
import com.twitter.sdk.android.Twitter;
import com.twitter.sdk.android.core.TwitterAuthConfig;

import io.fabric.sdk.android.Fabric;
import timber.log.Timber;

public class RedditClientApp extends Application {

    @Override
    public void onCreate() {
        super.onCreate();
        if (BuildConfig.DEBUG) {
            Timber.plant(new Timber.DebugTree() {
                @Override
                protected void log(final int priority, final String tag, final String message,
                                   final Throwable t) {
                    super.log(priority, "veyndan_" + tag, message, t);
                }
            });
        }
        final TwitterAuthConfig authConfig = new TwitterAuthConfig(Config.TWITTER_KEY, Config.TWITTER_SECRET);
        Fabric.with(this, new Twitter(authConfig));
        LeakCanary.install(this);
    }
}

Prepend 'veyndan_' tag to each Timber log for easy logcat usage


package edu.teco.dnd.module.messages.loadStartBlock;

import java.util.UUID;

import edu.teco.dnd.module.ModuleApplicationManager;
import edu.teco.dnd.network.ConnectionManager;
import edu.teco.dnd.network.MessageHandler;
import edu.teco.dnd.network.messages.Response;

public class BlockMessageHandler implements MessageHandler<BlockMessage> {
	final ModuleApplicationManager appManager;

	public BlockMessageHandler(ModuleApplicationManager appManager) {
		this.appManager = appManager;
	}

	@Override
	public Response handleMessage(ConnectionManager connMan, UUID remoteUUID, BlockMessage message) {
		if (appManager.scheduleBlock(message.getApplicationID(), message.block, message.scheduleToId)) {
			return new BlockAck();
		} else {
			return new BlockNak();
		}

	}

}

package edu.teco.dnd.module.messages.loadStartBlock;

import java.util.UUID;

import edu.teco.dnd.module.ModuleApplicationManager;
import edu.teco.dnd.network.ConnectionManager;
import edu.teco.dnd.network.MessageHandler;
import edu.teco.dnd.network.messages.Response;

public class BlockMessageHandler implements MessageHandler<BlockMessage> {
	final ModuleApplicationManager appManager;

	public BlockMessageHandler(ModuleApplicationManager appManager) {
		this.appManager = appManager;
	}

	@Override
	public Response handleMessage(ConnectionManager connMan, UUID remoteUUID, BlockMessage message) {
		try {
			appManager.scheduleBlock(message.getApplicationID(), message.block, message.scheduleToId);
		} catch (Exception e) {
			return new BlockNak();
		}
		return new BlockAck();
	}
}

Rewrite handler to work with exceptions instead of returned booleans.


package com.elmakers.mine.bukkit.economy;

import org.bukkit.configuration.ConfigurationSection;

import com.elmakers.mine.bukkit.api.magic.CasterProperties;
import com.elmakers.mine.bukkit.api.magic.Mage;
import com.elmakers.mine.bukkit.api.magic.MageController;

public class SpellPointCurrency extends BaseMagicCurrency {
    private final boolean isValid;

    public SpellPointCurrency(MageController controller, ConfigurationSection configuration) {
        super(controller, "sp", configuration);
        isValid = controller.isSPEnabled();
    }

    @Override
    public double getBalance(Mage mage, CasterProperties caster) {
        return mage.getSkillPoints();
    }

    @Override
    public boolean has(Mage mage, CasterProperties caster, double amount) {
        return mage.getSkillPoints() >= amount;
    }

    @Override
    public void deduct(Mage mage, CasterProperties caster, double amount) {
        mage.addSkillPoints(-getRoundedAmount(amount));
    }

    @Override
    public boolean give(Mage mage, CasterProperties caster, double amount) {
        if (mage.isAtMaxSkillPoints()) {
            return false;
        }
        mage.addSkillPoints(getRoundedAmount(amount));
        return true;
    }

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

    @Override
    public double getDefaultValue() {
        return defaultValue;
    }
}

package com.elmakers.mine.bukkit.economy;

import org.bukkit.configuration.ConfigurationSection;

import com.elmakers.mine.bukkit.api.magic.CasterProperties;
import com.elmakers.mine.bukkit.api.magic.Mage;
import com.elmakers.mine.bukkit.api.magic.MageController;

public class SpellPointCurrency extends CustomCurrency {
    private final boolean isValid;

    public SpellPointCurrency(MageController controller, ConfigurationSection configuration) {
        super(controller, "sp", configuration);
        isValid = controller.isSPEnabled();
    }

    @Override
    public double getBalance(Mage mage, CasterProperties caster) {
        return mage.getSkillPoints();
    }

    @Override
    public boolean has(Mage mage, CasterProperties caster, double amount) {
        return mage.getSkillPoints() >= amount;
    }

    @Override
    public void deduct(Mage mage, CasterProperties caster, double amount) {
        mage.addSkillPoints(-getRoundedAmount(amount));
    }

    @Override
    public boolean give(Mage mage, CasterProperties caster, double amount) {
        if (mage.isAtMaxSkillPoints()) {
            return false;
        }
        mage.addSkillPoints(getRoundedAmount(amount));
        return true;
    }

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

    @Override
    public double getDefaultValue() {
        return defaultValue;
    }
}

Fix recursion issues with spell points


package org.javersion.object;

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

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

import org.junit.Test;

public class JavaTimeTest {

    @Versionable
    public static class DT {
        final Instant instant = Instant.now();
        final LocalDate localDate = LocalDate.now();
        final LocalDateTime localDateTime = LocalDateTime.now();
    }

    private ObjectSerializer<DT> serializer = new ObjectSerializer<>(DT.class);

    @Test
    public void write_read() {
        final DT dt = new DT();
        DT dtCopy = serializer.fromPropertyMap(serializer.toPropertyMap(dt));
        assertThat(dtCopy.instant).isEqualTo(dt.instant);
        assertThat(dtCopy.localDate).isEqualTo(dt.localDate);
        assertThat(dtCopy.localDateTime).isEqualTo(dt.localDateTime);
    }

}

package org.javersion.object;

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

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

import org.junit.Test;

public class JavaTimeTest {

    @Versionable
    public static class DT {
        private final Instant instant = Instant.now();
        private final LocalDate localDate = LocalDate.now();
        private final LocalDateTime localDateTime = LocalDateTime.now();
    }

    private ObjectSerializer<DT> serializer = new ObjectSerializer<>(DT.class);

    @Test
    public void write_read() {
        final DT dt = new DT();
        DT dtCopy = serializer.fromPropertyMap(serializer.toPropertyMap(dt));
        assertThat(dtCopy.instant).isEqualTo(dt.instant);
        assertThat(dtCopy.localDate).isEqualTo(dt.localDate);
        assertThat(dtCopy.localDateTime).isEqualTo(dt.localDateTime);
    }
}

Verify binding of private final fields


package io.smsc.listeners;

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

import static org.mockito.Mockito.*;

@RunWith(MockitoJUnitRunner.class)
public class EncryptionListenerUnitTest {

    private Object testObject;

    @Before
    public void setUp() {
        testObject = new Object();
    }

    @Mock
    private EncryptionListener listener;

    @Test(expected = IllegalAccessException.class)
    public void testEncryptCall() throws Exception {
        doThrow(IllegalAccessException.class).when(listener).encrypt(testObject);
        listener.encrypt(testObject);
    }

    @Test(expected = IllegalAccessException.class)
    public void testDecryptCall() throws Exception {
        doThrow(IllegalAccessException.class).when(listener).decrypt(testObject);
        listener.decrypt(testObject);
    }
}

package io.smsc.listeners;

import io.smsc.util.EncrypterUtil;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import org.springframework.test.util.ReflectionTestUtils;

import java.awt.event.ActionEvent;

import static org.mockito.Mockito.*;

@RunWith(MockitoJUnitRunner.class)
public class EncryptionListenerUnitTest {

    private Object testObject;

    private EncryptionListener listener;

    private ActionEvent mockEvent;

    @Mock
    private EncryptionListener mockListener;

    @Before
    public void setUp() {
        listener = new EncryptionListener();
        testObject = new Object();
        mockEvent = mock(ActionEvent.class);

        ReflectionTestUtils.setField(EncrypterUtil.class, "secretKey", "smsc.io");
    }

    @Test(expected = IllegalAccessException.class)
    public void testEncryptCallWithException() throws Exception {
        doThrow(IllegalAccessException.class).when(mockListener).encrypt(testObject);

        mockListener.encrypt(testObject);
    }

    @Test(expected = IllegalAccessException.class)
    public void testDecryptCallWithException() throws Exception {
        doThrow(IllegalAccessException.class).when(mockListener).decrypt(testObject);

        mockListener.decrypt(testObject);
    }

    @Test
    public void testEncryptCallWithoutException() throws Exception {
        mockListener.encrypt(testObject);

        verify(mockListener).encrypt(testObject);
    }

    @Test
    public void testDecryptCallWithoutException() throws Exception {
        mockListener.decrypt(testObject);

        verify(mockListener).decrypt(testObject);
    }

    @Test
    public void testEncryptCall() throws Exception {
        listener.encrypt(mockEvent);
    }

    @Test
    public void testDecryptCall() throws Exception {
        listener.decrypt(mockEvent);
    }
}

Add more unit tests for EncryptionListener


package com.kickstarter.ui.views;

import android.content.Context;
import android.util.AttributeSet;
import android.webkit.WebChromeClient;
import android.webkit.WebView;

import com.kickstarter.KsrApplication;
import com.kickstarter.libs.WebViewJavascriptInterface;
import com.kickstarter.services.KickstarterWebViewClient;

import javax.inject.Inject;

public class KickstarterWebView extends WebView {
  @Inject KickstarterWebViewClient client;

  public KickstarterWebView(final Context context) {
    this(context, null);
  }

  public KickstarterWebView(final Context context, final AttributeSet attrs) {
    this(context, attrs, android.R.attr.webViewStyle);
  }

  public KickstarterWebView(final Context context, final AttributeSet attrs, final int defStyle) {
    super(context, attrs, defStyle);

    ((KsrApplication) context.getApplicationContext()).component().inject(this);
    setWebViewClient(client);
    setWebChromeClient(new WebChromeClient());
    getSettings().setJavaScriptEnabled(true);
    getSettings().setAllowFileAccess(false);

    if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) {
      setWebContentsDebuggingEnabled(true);
    }

    addJavascriptInterface(new WebViewJavascriptInterface(this.client), "WebViewJavascriptInterface");
  }
}

package com.kickstarter.ui.views;

import android.content.Context;
import android.util.AttributeSet;
import android.webkit.WebChromeClient;
import android.webkit.WebView;

import com.kickstarter.KsrApplication;
import com.kickstarter.libs.WebViewJavascriptInterface;
import com.kickstarter.services.KickstarterWebViewClient;

import javax.inject.Inject;

public class KickstarterWebView extends WebView {
  @Inject KickstarterWebViewClient client;

  public KickstarterWebView(final Context context) {
    this(context, null);
  }

  public KickstarterWebView(final Context context, final AttributeSet attrs) {
    this(context, attrs, android.R.attr.webViewStyle);
  }

  public KickstarterWebView(final Context context, final AttributeSet attrs, final int defStyle) {
    super(context, attrs, defStyle);

    ((KsrApplication) context.getApplicationContext()).component().inject(this);
    setWebViewClient(client);
    setWebChromeClient(new WebChromeClient());
    getSettings().setJavaScriptEnabled(true);
    getSettings().setAllowFileAccess(false);

    if (android.os.Build.VERSION.SDK_INT >= 19) {
      setWebContentsDebuggingEnabled(true);
    }

    addJavascriptInterface(new WebViewJavascriptInterface(this.client), "WebViewJavascriptInterface");
  }
}

Remove another reference to kitkat


package com.suse.salt.netapi.datatypes.target;

/**
 * Matcher based on salt grains
 */
public class Grains extends DictionaryTarget implements Target<String> {

    /**
     * Creates a grains matcher
     *
     * @param target the targeting expression
     */
    public Grains(String target) {
        super(target);
    }

    /**
     * Creates a grains matcher
     *
     * @param target the targeting expression
     * @param delimiter the character to delimit nesting in the grain name
     */
    public Grains(String target, char delimiter) {
        super(target, delimiter);
    }

    /**
     * Creates a grains matcher
     *
     * @param grain the grain name
     * @param value the value to match
     */
    public Grains(String grain, String value) {
        super(grain, value);
    }

    /**
     * Creates a grains matcher
     *
     * @param grain the grain name
     * @param value the value to match
     * @param delimiter the character to delimit nesting in the grain name
     */
    public Grains(String grain, String value, char delimiter) {
        super(grain, value, delimiter);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public TargetType getType() { return TargetType.GRAIN; }

    @Deprecated
    public String getGrain() { return getKey(); }
}

package com.suse.salt.netapi.datatypes.target;

/**
 * Matcher based on salt grains
 */
public class Grains extends DictionaryTarget implements Target<String> {

    /**
     * Creates a grains matcher
     *
     * @param target the targeting expression
     */
    public Grains(String target) {
        super(target);
    }

    /**
     * Creates a grains matcher
     *
     * @param target the targeting expression
     * @param delimiter the character to delimit nesting in the grain name
     */
    public Grains(String target, char delimiter) {
        super(target, delimiter);
    }

    /**
     * Creates a grains matcher
     *
     * @param grain the grain name
     * @param value the value to match
     */
    public Grains(String grain, String value) {
        super(grain, value);
    }

    /**
     * Creates a grains matcher
     *
     * @param grain the grain name
     * @param value the value to match
     * @param delimiter the character to delimit nesting in the grain name
     */
    public Grains(String grain, String value, char delimiter) {
        super(grain, value, delimiter);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public TargetType getType() { return TargetType.GRAIN; }

    /**
     * Return the grain identifier key
     *
     * @deprecated
     * Use {@link #getKey()} instead.
     */
    @Deprecated
    public String getGrain() { return getKey(); }
}

Add JavaDoc for deprecated methods


package io.github.phantamanta44.shlgl.event;

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

/**
 * Handles the dispatching of events to individual {@link EventStream}s.
 * @author Evan Geng
 */
public class EventBus { // TODO Document

    private final Map<Class<? extends Event>, EventStream<?>> eventStreams;

    public EventBus() {
        eventStreams = new HashMap<>();
        // TODO Register default event types
    }

    public void registerEvent(Class<? extends Event> eventType) {
        eventStreams.put(eventType, new EventStream<>());
    }

    public void post(Event event) {
        eventStreams.entrySet().stream()
                .filter(e -> e.getKey().isAssignableFrom(event.getClass()))
                .forEach(e -> e.getValue().post(event)); // FIXME Cast this somehow
    }

}

package io.github.phantamanta44.shlgl.event;

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

/**
 * Handles the dispatching of events to individual {@link EventStream}s.
 * @author Evan Geng
 */
public class EventBus {

    /**
     * The mapping of event types to {@link EventStream}s.
     */
    private final Map<Class<? extends Event>, EventStream> eventStreams;

    /**
     * Creates and initializes the event bus.
     */
    public EventBus() {
        eventStreams = new HashMap<>();
        // TODO Register default event types
    }

    /**
     * Registers an event type.
     * @param eventType The new event type.
     */
    public void registerEvent(Class<? extends Event> eventType) {
        eventStreams.put(eventType, new EventStream<>());
    }

    /**
     * Dispatches an event to all eligible listeners.
     * @param event The event to post.
     */
    @SuppressWarnings("unchecked")
    public void post(Event event) {
        eventStreams.entrySet().stream()
                .filter(e -> e.getKey().isAssignableFrom(event.getClass()))
                .forEach(e -> e.getValue().post(event));
    }

}

Fix casting issue and document event bus


package org.cryptonit.cloud.timestamping;

import javax.ws.rs.Path;

/**
 * @author Mathias Brossard
 */
@Path("/timestamp")
public class Application {

}

package org.cryptonit.cloud.timestamping;

import javax.ws.rs.Path;
import org.cryptonit.cloud.interfaces.TimestampingAuthorityFactory;

/**
 * @author Mathias Brossard
 */
@Path("/timestamp")
public class Application {
    private static TimestampingAuthorityFactory tsaFactory = null;

    public static void setTimestampingAuthorityFactory(TimestampingAuthorityFactory factory) {
        tsaFactory = factory;
    }
}

Add static method to set TimestampingAuthorityFactory


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

/**
 *
 * @author shane
 */
public class ChatManager {

}

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

import com.lamepancake.chitchat.mediator.Event;

/**
 *
 * @author shane
 */
public class ChatManager {

    public void handleEvent(Event e)
    {

    }
}

Add PromoteUser flag to Event


package biz.paluch.atsoundtrack;

import org.jetbrains.annotations.NotNull;

import com.intellij.codeInsight.completion.CompletionContributor;
import com.intellij.codeInsight.completion.CompletionParameters;
import com.intellij.codeInsight.completion.CompletionResultSet;
import com.intellij.codeInsight.lookup.LookupElement;

/**
 * @author Mark Paluch
 * @since 13.05.15 11:49
 */
public class AtSoundtrackContributor extends CompletionContributor {

    @Override
    public void fillCompletionVariants(CompletionParameters parameters, CompletionResultSet result) {

        if (AtSoundtrack.getName() != null) {
            result.addElement(new LookupElement() {
                @NotNull
                @Override
                public String getLookupString() {
                    return "@soundtrack " + AtSoundtrack.getName();
                }
            });
        }
        super.fillCompletionVariants(parameters, result);
    }
}

package biz.paluch.atsoundtrack;

import static com.intellij.openapi.util.text.StringUtil.*;

import com.intellij.codeInsight.completion.CompletionContributor;
import com.intellij.codeInsight.completion.CompletionParameters;
import com.intellij.codeInsight.completion.CompletionResultSet;
import com.intellij.codeInsight.lookup.LookupElementBuilder;
import com.intellij.psi.PsiComment;
import com.intellij.psi.PsiDocCommentBase;
import com.intellij.psi.xml.XmlComment;
import com.intellij.psi.xml.XmlToken;

/**
 * @author Mark Paluch
 * @since 13.05.15 11:49
 */
public class AtSoundtrackContributor extends CompletionContributor {

    @Override
    public void fillCompletionVariants(CompletionParameters parameters, CompletionResultSet result) {

        String prefix = parameters.getOriginalPosition().getText();

        if (!prefix.contains("soundtrack")) {

            if (!isEmpty(AtSoundtrack.getName())) {

                boolean qualified = false;
                if (parameters.getOriginalPosition() instanceof PsiComment
                        || parameters.getOriginalPosition().getContext() instanceof PsiDocCommentBase
                        || parameters.getOriginalPosition().getClass().getName().contains("PsiDocToken")) {

                    qualified = true;
                }
                if (parameters.getOriginalPosition() instanceof XmlToken) {
                    XmlToken xmlToken = (XmlToken) parameters.getOriginalPosition();

                    if (xmlToken instanceof XmlComment || xmlToken.getContext() instanceof XmlComment) {
                        qualified = true;
                    }
                }

                if (qualified) {
                    if (!prefix.contains("@")) {
                        result.addElement(LookupElementBuilder.create("@soundtrack " + AtSoundtrack.getName()));
                    } else {
                        result.addElement(LookupElementBuilder.create("soundtrack " + AtSoundtrack.getName()));
                    }
                }
            }
        }

        super.fillCompletionVariants(parameters, result);
    }
}

Use code completion in multiple places and compatibility with PyCharm, RubyMine, PhpStorm


//
// Copyright (C) 2006 United States Government as represented by the
// Administrator of the National Aeronautics and Space Administration
// (NASA).  All Rights Reserved.
//
// This software is distributed under the NASA Open Source Agreement
// (NOSA), version 1.3.  The NOSA has been approved by the Open Source
// Initiative.  See the file NOSA-1.3-JPF at the top of the distribution
// directory tree for the complete NOSA document.
//
// THE SUBJECT SOFTWARE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY OF ANY
// KIND, EITHER EXPRESSED, IMPLIED, OR STATUTORY, INCLUDING, BUT NOT
// LIMITED TO, ANY WARRANTY THAT THE SUBJECT SOFTWARE WILL CONFORM TO
// SPECIFICATIONS, ANY IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR
// A PARTICULAR PURPOSE, OR FREEDOM FROM INFRINGEMENT, ANY WARRANTY THAT
// THE SUBJECT SOFTWARE WILL BE ERROR FREE, OR ANY WARRANTY THAT
// DOCUMENTATION, IF PROVIDED, WILL CONFORM TO THE SUBJECT SOFTWARE.
//
package gov.nasa.jpf.search.heuristic;

import gov.nasa.jpf.Config;
import gov.nasa.jpf.jvm.JVM;

/**
 * breadth first search
 */
public class BFSHeuristic extends SimplePriorityHeuristic {

  public BFSHeuristic (Config config, JVM vm) {
    super(config,vm);
  }

  protected int computeHeuristicValue () {
    int priority = vm.getPathLength();

    return priority;
  }

}

//
// Copyright (C) 2006 United States Government as represented by the
// Administrator of the National Aeronautics and Space Administration
// (NASA).  All Rights Reserved.
//
// This software is distributed under the NASA Open Source Agreement
// (NOSA), version 1.3.  The NOSA has been approved by the Open Source
// Initiative.  See the file NOSA-1.3-JPF at the top of the distribution
// directory tree for the complete NOSA document.
//
// THE SUBJECT SOFTWARE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY OF ANY
// KIND, EITHER EXPRESSED, IMPLIED, OR STATUTORY, INCLUDING, BUT NOT
// LIMITED TO, ANY WARRANTY THAT THE SUBJECT SOFTWARE WILL CONFORM TO
// SPECIFICATIONS, ANY IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR
// A PARTICULAR PURPOSE, OR FREEDOM FROM INFRINGEMENT, ANY WARRANTY THAT
// THE SUBJECT SOFTWARE WILL BE ERROR FREE, OR ANY WARRANTY THAT
// DOCUMENTATION, IF PROVIDED, WILL CONFORM TO THE SUBJECT SOFTWARE.
//
package gov.nasa.jpf.search.heuristic;

import gov.nasa.jpf.Config;
import gov.nasa.jpf.jvm.JVM;

/**
 * breadth first search
 */
public class BFSHeuristic extends SimplePriorityHeuristic {

  public BFSHeuristic (Config config, JVM vm) {
  	super(config,vm);
  	System.out.println("BFS Search");
  }

  protected int computeHeuristicValue () {
    int priority = vm.getPathLength();

    return priority;
  }

}

Print BFS Search when you do a BFS Search


/**
 * Copyright © 2011-2012 EMBL - European Bioinformatics Institute
 *
 * 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 uk.ac.ebi.phenotype.util;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLSession;

public class CustomizedHostNameVerifier implements HostnameVerifier {

	@Override
	public boolean verify(String hostname, SSLSession session) {
		return true;
	}

}

/**
 * Copyright © 2011-2013 EMBL - European Bioinformatics Institute
 *
 * 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 uk.ac.ebi.phenotype.util;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLSession;

/**
 * Provides an SSL certification implementation that claims all certificates
 * are valid -- without actually checking them (!).
 *
 * This is required because, for instance,
 * dev.mousephenotype.org has an invalid SSL cert
 *
 */
public class CustomizedHostNameVerifier implements HostnameVerifier {
	@Override
	public boolean verify(String hostname, SSLSession session) {
		return true;
	}
}

Change copyright in Apache 2 license to 2013


package net.mcft.copy.betterstorage.item.cardboard;

import net.mcft.copy.betterstorage.content.Items;
import net.mcft.copy.betterstorage.item.ItemBetterStorage;
import net.minecraft.item.EnumArmorMaterial;
import net.minecraft.item.EnumToolMaterial;
import net.minecraftforge.common.EnumHelper;

public class ItemCardboardSheet extends ItemBetterStorage {

	public static final EnumToolMaterial toolMaterial =
			EnumHelper.addToolMaterial("cardboard", 0, 48, 2.5F, 0.0F, 18);
	public static final EnumArmorMaterial armorMaterial =
			EnumHelper.addArmorMaterial("cardboard", 3, new int[]{ 1, 2, 2, 1 }, 20);

	static {
		toolMaterial.customCraftingMaterial = Items.cardboardSheet;
		armorMaterial.customCraftingMaterial = Items.cardboardSheet;
	}

	public ItemCardboardSheet(int id) {
		super(id);
		setMaxStackSize(8);
	}

}

package net.mcft.copy.betterstorage.item.cardboard;

import net.mcft.copy.betterstorage.content.Items;
import net.mcft.copy.betterstorage.item.ItemBetterStorage;
import net.minecraft.item.EnumArmorMaterial;
import net.minecraft.item.EnumToolMaterial;
import net.minecraftforge.common.EnumHelper;

public class ItemCardboardSheet extends ItemBetterStorage {

	public static final EnumToolMaterial toolMaterial =
			EnumHelper.addToolMaterial("cardboard", 0, 48, 2.5F, 0.0F, 18);
	public static final EnumArmorMaterial armorMaterial =
			EnumHelper.addArmorMaterial("cardboard", 3, new int[]{ 1, 2, 2, 1 }, 20);

	public ItemCardboardSheet(int id) {
		super(id);
		setMaxStackSize(8);

		toolMaterial.customCraftingMaterial = this;
		armorMaterial.customCraftingMaterial = this;
	}

}

Fix cardboard items being unrepairable


// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
@ExportPackage
@PublicApi
package com.yahoo.restapi;

import com.yahoo.api.annotations.PublicApi;
import com.yahoo.osgi.annotation.ExportPackage;

// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
@ExportPackage
package com.yahoo.restapi;

import com.yahoo.osgi.annotation.ExportPackage;

Remove erroneous @PublicApi on com.yahoo.restapi


//
// $Id$
//
// Nexus GWTIO - I/O and network services for Nexus built on GWT and WebSockets
// http://github.com/samskivert/nexus/blob/master/LICENSE

package com.samskivert.nexus.io;

/**
 * A serializer that handles our test classes.
 */
public class TestSerializer extends AbstractSerializer
{
    public TestSerializer ()
    {
        mapStreamer(new Streamer_Widget(), Widget.class);
        mapStreamer(new Streamer_Widget.Wangle(), Widget.Wangle.class);
    }
}

//
// $Id$
//
// Nexus GWTIO - I/O and network services for Nexus built on GWT and WebSockets
// http://github.com/samskivert/nexus/blob/master/LICENSE

package com.samskivert.nexus.io;

/**
 * A serializer that handles our test classes.
 */
public class TestSerializer extends AbstractSerializer
{
    public TestSerializer ()
    {
        mapStreamer(new Streamer_Widget());
        mapStreamer(new Streamer_Widget.Wangle());
    }
}

Use new class-token free streamer registration.


package com.kickstarter.services.apiresponses;

import android.os.Parcelable;

import com.kickstarter.libs.qualifiers.AutoGson;
import com.kickstarter.models.Project;

import java.util.List;

import auto.parcel.AutoParcel;

@AutoGson
@AutoParcel
public abstract class DiscoverEnvelope implements Parcelable {
  public abstract List<Project> projects();
  public abstract UrlsEnvelope urls();

  @AutoGson
  @AutoParcel
  public abstract static class UrlsEnvelope implements Parcelable {
    public abstract ApiEnvelope api();

    @AutoGson
    @AutoParcel
    public abstract static class ApiEnvelope implements Parcelable {
      public abstract String moreProjects();
    }
  }
}

package com.kickstarter.services.apiresponses;

import android.os.Parcelable;

import com.kickstarter.libs.qualifiers.AutoGson;
import com.kickstarter.models.Project;

import java.util.List;

import auto.parcel.AutoParcel;

@AutoGson
@AutoParcel
public abstract class DiscoverEnvelope implements Parcelable {
  public abstract List<Project> projects();
  public abstract UrlsEnvelope urls();

  @AutoGson
  @AutoParcel
  public abstract static class UrlsEnvelope implements Parcelable {
    public abstract ApiEnvelope api();

    @AutoGson
    @AutoParcel
    public abstract static class ApiEnvelope implements Parcelable {
      public abstract String moreProjects();

      @AutoParcel.Builder
      public abstract static class Builder {
        public abstract Builder moreProjects(String __);
        public abstract ApiEnvelope build();
      }

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

    @AutoParcel.Builder
    public abstract static class Builder {
      public abstract Builder api(ApiEnvelope __);
      public abstract UrlsEnvelope build();
    }

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

  @AutoParcel.Builder
  public abstract static class Builder {
    public abstract Builder projects(List<Project> __);
    public abstract Builder urls(UrlsEnvelope __);
    public abstract DiscoverEnvelope build();
  }

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

  public abstract Builder toBuilder();
}

Add builders for nested classes


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

package foam.core;

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

public class MultitonInfo<T>
  implements Axiom, ContextFactory<T>
{
  Map<Object, T> instanceMap = new HashMap<Object, T>();

  String name;
  PropertyInfo p;

  public MultitonInfo(String name, PropertyInfo p) {
    this.name = name;
    this.p = p;
  }

  public String getName() {
    return name;
  }

  public T getInstance(Map<String, Object> args, X x) {
    Object key = args.get(p.getName());
    if ( ! instanceMap.containsKey(key) ) {
      try {
        Class<T> type = (Class<T>)p.getClassInfo().getObjClass();
        T obj = type.newInstance();
        ((ContextAware)obj).setX(x);
        for (Map.Entry<String, Object> entry : args.entrySet()) {
          ((FObject)obj).setProperty(entry.getKey(), entry.getValue());
        }
        instanceMap.put(key, obj);
      } catch (java.lang.Exception e) {
        e.printStackTrace();
        return null;
      }
    }
    return instanceMap.get(key);
  }
}

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

package foam.core;

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

public class MultitonInfo<T>
  implements Axiom, ContextFactory<T>
{
  Map<Object, T> instanceMap = new HashMap<Object, T>();

  String name;
  PropertyInfo p;

  public MultitonInfo(String name, PropertyInfo p) {
    this.name = name;
    this.p = p;
  }

  public String getName() {
    return name;
  }

  public synchronized T getInstance(Map<String, Object> args, X x) {
    Object key = args.get(p.getName());
    if ( ! instanceMap.containsKey(key) ) {
      try {
        Class<T> type = (Class<T>)p.getClassInfo().getObjClass();
        T obj = type.newInstance();
        ((ContextAware)obj).setX(x);
        for ( Map.Entry<String, Object> entry : args.entrySet() ) {
          ((FObject)obj).setProperty(entry.getKey(), entry.getValue());
        }
        instanceMap.put(key, obj);
      } catch (java.lang.Exception e) {
        e.printStackTrace();
        return null;
      }
    }
    return instanceMap.get(key);
  }
}

Make multiton creation thread safe and fix some code style.


//
// $Id$

package com.threerings.gardens.logic;

import com.samskivert.servlet.user.User;
import com.samskivert.servlet.util.ParameterUtil;
import com.samskivert.velocity.InvocationContext;

import com.threerings.gardens.Log;
import com.threerings.gardens.GardensApp;

/**
 * Displays a list of all registered games.
 */
public class browse extends OptionalUserLogic
{
    // documentation inherited
    public void invoke (InvocationContext ctx, GardensApp app, User user)
        throws Exception
    {
        String category = ParameterUtil.getParameter(
            ctx.getRequest(), "category", false);

        if (category.equals("")) {
            // load up the metadata for all of our games
            ctx.put("games", app.getToyBoxRepository().loadGames());

        } else {
            // load up the metadata for the games in this category
            ctx.put("category", category);
            ctx.put("games", app.getToyBoxRepository().loadGames(category));
        }
    }
}

//
// $Id$

package com.threerings.gardens.logic;

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

import com.samskivert.servlet.user.User;
import com.samskivert.servlet.util.ParameterUtil;
import com.samskivert.velocity.InvocationContext;

import com.threerings.toybox.server.persist.Game;

import com.threerings.gardens.Log;
import com.threerings.gardens.GardensApp;

/**
 * Displays a list of all registered games.
 */
public class browse extends OptionalUserLogic
{
    // documentation inherited
    public void invoke (InvocationContext ctx, GardensApp app, User user)
        throws Exception
    {
        String category = ParameterUtil.getParameter(
            ctx.getRequest(), "category", false);

        ArrayList<Game> games;
        if (category.equals("")) {
            // load up the metadata for all of our games
            games = app.getToyBoxRepository().loadGames();

        } else {
            // load up the metadata for the games in this category
            ctx.put("category", category);
            games = app.getToyBoxRepository().loadGames(category);
        }

        // sort our games by name
        Collections.sort(games, new Comparator<Game>() {
            public int compare (Game g1, Game g2) {
                return g1.name.compareTo(g2.name);
            }
        });
        ctx.put("games", games);
    }
}

Sort the games alphabetically in the listing.


package com.github.cosmo0920.fluentd.flume.plugins;

import java.nio.charset.StandardCharsets;

import org.apache.flume.Sink.Status;
import org.apache.flume.Channel;
import org.apache.flume.Event;
import org.apache.flume.Transaction;
import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Matchers;
import org.mockito.Mockito.*;

import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class TestFluentdSink {
}

package com.github.cosmo0920.fluentd.flume.plugins;

import java.nio.charset.StandardCharsets;

import org.apache.flume.Sink.Status;
import org.apache.flume.Channel;
import org.apache.flume.Event;
import org.apache.flume.Transaction;
import org.apache.flume.EventDeliveryException;

import org.komamitsu.fluency.Fluency;

import static org.junit.Assert.*;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Matchers;
import static org.mockito.Mockito.*;

import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;

public class TestFluentdSink {
	private static final Logger logger = LoggerFactory.getLogger(FluentdSink.class);

	@Test
	public void testShouldCommitSuccessfulTransaction() throws EventDeliveryException {
		Channel mockChannel = mock(Channel.class);
		Transaction mockTransaction = mock(Transaction.class);
		Event mockEvent = mock(Event.class);

		when(mockChannel.getTransaction()).thenReturn(mockTransaction);
		when(mockChannel.take()).thenReturn(mockEvent);
		when(mockEvent.getBody()).thenReturn("test body".getBytes(StandardCharsets.UTF_8));

		FluentdSink sink = new FluentdSink();
		sink.setChannel(mockChannel);

		// TODO: Extract Fluency sender and mock it
		assertTrue(true);
		// Status status = sink.process();
		// assertEquals(status, Status.READY);
	}

}

Write test case skeleton with mockito and junit


package info.puzz.a10000sentences.models;

import com.activeandroid.Model;
import com.activeandroid.annotation.Column;
import com.activeandroid.annotation.Table;

import lombok.Data;
import lombok.ToString;
import lombok.experimental.Accessors;

@Data
@Accessors(chain = true)
@ToString
@Table(name = "sentence")
public class Sentence extends Model {

    @Column(name = "sentence_id", index = true, unique = true, onUniqueConflict = Column.ConflictAction.REPLACE)
    public String sentenceId;

    @Column(name = "collection_id", index = true)
    public String collectionId;

    @Column(name = "known")
    public String knownSentence;

    @Column(name = "target")
    public String targetSentence;

    @Column(name = "status")
    public int status = SentenceStatus.TODO.getStatus();

    @Column(name = "complexity", index = true)
    float complexity;

    public String[] getKnownSentences() {
        return String.valueOf(knownSentence).split("\\|");
    }

    public String getFirstKnownSentence() {
        return getKnownSentences()[0];
    }

    public SentenceStatus getSentenceStatus() {
        return SentenceStatus.fromStatus(status);
    }
}

package info.puzz.a10000sentences.models;

import com.activeandroid.Model;
import com.activeandroid.annotation.Column;
import com.activeandroid.annotation.Table;

import lombok.Data;
import lombok.ToString;
import lombok.experimental.Accessors;

@Data
@Accessors(chain = true)
@ToString
@Table(name = "sentence")
public class Sentence extends Model {

    @Column(name = "sentence_id", index = true, unique = true, onUniqueConflict = Column.ConflictAction.REPLACE)
    public String sentenceId;

    @Column(name = "collection_id", index = true)
    public String collectionId;

    @Column(name = "known")
    public String knownSentence;

    @Column(name = "target")
    public String targetSentence;

    @Column(name = "status")
    public int status = SentenceStatus.TODO.getStatus();

    @Column(name = "complexity", index = true)
    float complexity;

    public String[] getKnownSentences() {
        String[] res = String.valueOf(knownSentence).split("\\|");
        if (res.length == 1) {
            return res;
        }
        for (int i = 0; i < res.length; i++) {
            res[i] += String.format(" [%d/%d]", i+1, res.length);
        }
        return res;
    }

    public String getFirstKnownSentence() {
        return getKnownSentences()[0];
    }

    public SentenceStatus getSentenceStatus() {
        return SentenceStatus.fromStatus(status);
    }
}

Add sentence alternative counter in list


package codechicken.lib.recipe;

import com.google.gson.JsonObject;
import net.minecraft.item.crafting.Ingredient;
import net.minecraft.util.JsonUtils;
import net.minecraftforge.common.crafting.CraftingHelper;
import net.minecraftforge.common.crafting.IIngredientFactory;
import net.minecraftforge.common.crafting.JsonContext;

import javax.annotation.Nonnull;

/**
 * Simple conditional ingredient.
 *
 * Created by covers1624 on 18/10/2017.
 */
public class ConditionalIngredientFactory implements IIngredientFactory {

    @Nonnull
    @Override
    public Ingredient parse(JsonContext context, JsonObject json) {
        if (!CraftingHelper.processConditions(JsonUtils.getJsonArray(json, "conditions"), context)) {
            if (json.has("fail")) {
                CraftingHelper.getIngredient(JsonUtils.getJsonObject(json, "failed_condition"), context);
            }
            return Ingredient.EMPTY;
        }
        return CraftingHelper.getIngredient(JsonUtils.getJsonObject(json, "pass"), context);
    }
}

package codechicken.lib.recipe;

import com.google.gson.JsonObject;
import net.minecraft.item.crafting.Ingredient;
import net.minecraft.util.JsonUtils;
import net.minecraftforge.common.crafting.CraftingHelper;
import net.minecraftforge.common.crafting.IIngredientFactory;
import net.minecraftforge.common.crafting.JsonContext;

import javax.annotation.Nonnull;

/**
 * Simple conditional ingredient.
 *
 * Created by covers1624 on 18/10/2017.
 */
public class ConditionalIngredientFactory implements IIngredientFactory {

    @Nonnull
    @Override
    public Ingredient parse(JsonContext context, JsonObject json) {
        if (!CraftingHelper.processConditions(JsonUtils.getJsonArray(json, "conditions"), context)) {
            if (json.has("fail")) {
                CraftingHelper.getIngredient(JsonUtils.getJsonObject(json, "fail"), context);
            }
            return Ingredient.EMPTY;
        }
        return CraftingHelper.getIngredient(JsonUtils.getJsonObject(json, "pass"), context);
    }
}

Fix CondtionalIngredientFactory parsing of fail ingredient.


package com.mapzen.android.sample;

import com.mapzen.android.MapFragment;
import com.mapzen.android.MapManager;
import com.mapzen.tangram.MapController;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;

/**
 * Basic SDK demo, tracks user's current location on map.
 */
public class BasicMapzenActivity extends AppCompatActivity {

    MapFragment mapFragment;
    MapController mapController;
    MapManager mapManager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_sample_mapzen);

        mapFragment = (MapFragment) getSupportFragmentManager().findFragmentById(R.id.fragment);
        mapController = mapFragment.getMap();
        mapManager = mapFragment.getMapManager();
        configureMap();
    }

    private void configureMap() {
        mapController.setMapZoom(17);
        mapManager.setMyLocationEnabled(true);
    }
}

package com.mapzen.android.sample;

import com.mapzen.android.MapFragment;
import com.mapzen.android.MapManager;
import com.mapzen.tangram.MapController;
import com.mapzen.tangram.MapView;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;

/**
 * Basic SDK demo, tracks user's current location on map.
 */
public class BasicMapzenActivity extends AppCompatActivity {

    MapFragment mapFragment;
    MapController mapController;
    MapManager mapManager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_sample_mapzen);

        mapFragment = (MapFragment) getSupportFragmentManager().findFragmentById(R.id.fragment);
        mapFragment.getMapAsync(new MapView.OnMapReadyCallback() {
            @Override public void onMapReady(MapController mapController) {
                BasicMapzenActivity.this.mapController = mapController;
                configureMap();
            }
        });
    }

    private void configureMap() {
        mapManager = mapFragment.getMapManager();
        mapManager.setMyLocationEnabled(true);
    }
}

Use getMapAsync, original file was renamed


package com.nikolavp.approval.reporters;

import com.nikolavp.approval.Approval;
import org.junit.Assume;
import org.junit.Test;

import java.awt.*;
import java.nio.file.FileSystems;

/**
 *
 * User: nikolavp
 * Date: 26/02/14
 * Time: 14:28
 */

public class ReportersExamplesIT {

    @Test
    public void testGvimApprovalProcess() throws Exception {
        Assume.assumeTrue(Desktop.isDesktopSupported());
        Approval approval = new Approval(Reporters.gvim());

        approval.verify("some test content".getBytes(), FileSystems.getDefault().getPath("target", "verifications", "testGvimApprovalProcess.txt"));
    }

    @Test
    public void testConsoleApprovalProcess() throws Exception {
        Assume.assumeTrue(Desktop.isDesktopSupported());
        Approval approval = new Approval(Reporters.console());
        approval.verify("some test content".getBytes(), FileSystems.getDefault().getPath("target", "verifications", "testConsoleApprovalProcess.txt"));
    }

    @Test
    public void testGeditApprovalProcess() throws Exception {
        Assume.assumeTrue(Desktop.isDesktopSupported());
        Approval approval = new Approval(Reporters.gedit());
        approval.verify("some test content".getBytes(), FileSystems.getDefault().getPath("target", "verifications", "testGeditApprovalProcess.txt"));
    }
}

package com.nikolavp.approval.reporters;

import com.nikolavp.approval.Approval;
import org.junit.Assume;
import org.junit.Ignore;
import org.junit.Test;

import java.awt.*;
import java.nio.file.FileSystems;

/**
 *
 * User: nikolavp
 * Date: 26/02/14
 * Time: 14:28
 */
@Ignore
public class ReportersExamplesIT {

    @Test
    public void testGvimApprovalProcess() throws Exception {
        Assume.assumeTrue(Desktop.isDesktopSupported());
        Approval approval = new Approval(Reporters.gvim());

        approval.verify("some test content\n".getBytes(), FileSystems.getDefault().getPath("target", "verifications", "testGvimApprovalProcess.txt"));
    }

    @Test
    public void testConsoleApprovalProcess() throws Exception {
        Assume.assumeTrue(Desktop.isDesktopSupported());
        Approval approval = new Approval(Reporters.console());
        approval.verify("some test content\n".getBytes(), FileSystems.getDefault().getPath("target", "verifications", "testConsoleApprovalProcess.txt"));
    }

    @Test
    public void testGeditApprovalProcess() throws Exception {
        Assume.assumeTrue(Desktop.isDesktopSupported());
        Approval approval = new Approval(Reporters.gedit());
        approval.verify("some test content\n".getBytes(), FileSystems.getDefault().getPath("target", "verifications", "testGeditApprovalProcess.txt"));
    }
}

Add new lines here because they are added by some editors(vim for example)


package com.projectning.service.exceptions;

import com.projectning.util.ErrorMessage;

@SuppressWarnings("serial")
public class NotFoundException extends SdkException
{
  private NotFoundExceptionType typeNotFound = NotFoundExceptionType.NOT_SPECIFIED;

  // TODO: Could modify message to prepend with typeNotFound.toString()
  public NotFoundException()
  {
    super(ErrorMessage.UNKNOWN_ERROR.getMsg());
  }

  public NotFoundException(NotFoundExceptionType typeNotFound)
  {
    super();
    this.typeNotFound = typeNotFound;
  }

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

  public NotFoundException(NotFoundExceptionType typeNotFound, String message)
  {
    super(message);

    this.typeNotFound = typeNotFound;
  }

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

  public NotFoundException(NotFoundExceptionType typeNotFound, Throwable cause)
  {
    super(cause);
    this.typeNotFound = typeNotFound;
  }

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

  public NotFoundException(NotFoundExceptionType typeNotFound, String message, Throwable cause)
  {
    super(message, cause);
    this.typeNotFound = typeNotFound;
  }

  public NotFoundExceptionType getType()
  {
    return this.typeNotFound;
  }

  @Override
  public String getMessage()
  {
    return this.typeNotFound.toString() + ": " + super.getMessage();
  }
}

package com.projectning.service.exceptions;

import com.projectning.util.ErrorMessage;

@SuppressWarnings("serial")
public class NotFoundException extends SdkException
{
  private NotFoundExceptionType typeNotFound = NotFoundExceptionType.NOT_SPECIFIED;

  // TODO: Could modify message to prepend with typeNotFound.toString()
  public NotFoundException()
  {
    super(ErrorMessage.UNKNOWN_ERROR.getMsg());
  }

  public NotFoundException(NotFoundExceptionType typeNotFound)
  {
    super();
    this.typeNotFound = typeNotFound;
  }

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

  public NotFoundException(NotFoundExceptionType typeNotFound, String message)
  {
    super(message);

    this.typeNotFound = typeNotFound;
  }

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

  public NotFoundException(NotFoundExceptionType typeNotFound, Throwable cause)
  {
    super(cause);
    this.typeNotFound = typeNotFound;
  }

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

  public NotFoundException(NotFoundExceptionType typeNotFound, String message, Throwable cause)
  {
    super(message, cause);
    this.typeNotFound = typeNotFound;
  }

  public NotFoundExceptionType getType()
  {
    return this.typeNotFound;
  }

  /*
  @Override
  public String getMessage()
  {
    return this.typeNotFound.toString() + ": " + super.getMessage();
  }
  */
}

Comment out method that put extra string into error message


package com.edinarobotics.zed.commands;

public class FixedPointVisionTrackingCommand extends VisionTrackingCommand {
    private double fixedXSetpoint;
    private double fixedYSetpoint;

    public FixedPointVisionTrackingCommand(double xSetpoint, double ySetpoint) {
        super();
        this.fixedXSetpoint = xSetpoint;
        this.fixedYSetpoint = ySetpoint;
    }

    public FixedPointVisionTrackingCommand(double xSetpoint, double ySetpoint, byte goalType) {
        super(goalType);
        this.fixedXSetpoint = xSetpoint;
        this.fixedYSetpoint = ySetpoint;
    }

    protected double getXSetpoint(double distance) {
        return fixedXSetpoint;
    }

    protected double getYSetpoint(double distance) {
        return fixedYSetpoint;
    }
}

package com.edinarobotics.zed.commands;

public class FixedPointVisionTrackingCommand extends VisionTrackingCommand {
    private double fixedXSetpoint;
    private double fixedYSetpoint;

    public static final double PYRAMID_BACK_MIDDLE_X = 0.0273556;
    public static final double PYRAMID_BACK_MIDDLE_Y = -0.29411;
    public static final double PYRAMID_BACK_RIGHT_X = -0.063829;
    public static final double PYRAMID_BACK_RIGHT_Y = -0.226891;

    public FixedPointVisionTrackingCommand(double xSetpoint, double ySetpoint) {
        super();
        this.fixedXSetpoint = xSetpoint;
        this.fixedYSetpoint = ySetpoint;
    }

    public FixedPointVisionTrackingCommand(double xSetpoint, double ySetpoint, byte goalType) {
        super(goalType);
        this.fixedXSetpoint = xSetpoint;
        this.fixedYSetpoint = ySetpoint;
    }

    protected double getXSetpoint(double distance) {
        return fixedXSetpoint;
    }

    protected double getYSetpoint(double distance) {
        return fixedYSetpoint;
    }
}

Add fixed vision tracking point constants to the fixed point command.


package org.opennms.netmgt.vulnscand;

import junit.framework.TestCase;

import org.opennms.core.queue.FifoQueue;
import org.opennms.core.queue.FifoQueueImpl;
import org.opennms.netmgt.config.VulnscandConfigFactory;

public class SchedulerTest extends TestCase {

	protected void setUp() throws Exception {

		System.setProperty("opennms.home", "src/test/test-configurations/vulnscand");

		VulnscandConfigFactory.init();

		super.setUp();

	}

	protected void tearDown() throws Exception {
		super.tearDown();
	}

	public void FIXMEtestCreate() throws Exception {
		FifoQueue q = new FifoQueueImpl();
		Scheduler scheduler = new Scheduler(q);
		Vulnscand vulnscand = null;
		vulnscand.initialize();

	}

}

package org.opennms.netmgt.vulnscand;

import junit.framework.TestCase;

import org.opennms.core.queue.FifoQueue;
import org.opennms.core.queue.FifoQueueImpl;
import org.opennms.netmgt.config.VulnscandConfigFactory;

public class SchedulerTest extends TestCase {

	protected void setUp() throws Exception {

		System.setProperty("opennms.home", "src/test/test-configurations/vulnscand");

		VulnscandConfigFactory.init();

		super.setUp();

	}

	protected void tearDown() throws Exception {
		super.tearDown();
	}

    // FIXME
	public void FIXMEtestCreate() throws Exception {
		FifoQueue q = new FifoQueueImpl();
		Scheduler scheduler = new Scheduler(q);
		Vulnscand vulnscand = null;
		vulnscand.initialize();

	}

}

Add a "FIXME" comment for the disabled test so it shows up as a note in Eclipse (this idea was suggested awhile ago by brozow).


package com.pspdfkit.vangogh.api;

import com.pspdfkit.vangogh.rx.AnimationCompletable;
import io.reactivex.Completable;

/**
 * Class containing convenient animation scheduling methods.
 */
public final class AnimationSchedulers {

    /**
     * Animates given animations at the same time.
     * @param animations Animation to execute together.
     * @return Completable finishing once the last animation is completed.
     */
    public static Completable together(AnimationCompletable... animations) {
        return Completable.mergeArray(animations);
    }

    /**
     * Animates given animations one after another
     * @param animations Animation to execute sequentially.
     * @return Completable finishing once the last animation is completed.
     */
    public static Completable sequentially(AnimationCompletable... animations) {
        return Completable.concatArray(animations);
    }

}

package com.pspdfkit.vangogh.api;

import com.pspdfkit.vangogh.rx.AnimationCompletable;
import io.reactivex.Completable;

/**
 * Class containing convenient animation scheduling methods.
 */
public final class AnimationSchedulers {

    /**
     * Animates given animations at the same time.
     * @param animations Animations to execute together.
     * @return Completable finishing once the last animation is completed.
     */
    public static Completable together(Completable... animations) {
        return Completable.mergeArray(animations);
    }

    /**
     * Animates given animations one after another
     * @param animations Animations to execute sequentially.
     * @return Completable finishing once the last animation is completed.
     */
    public static Completable sequentially(Completable... animations) {
        return Completable.concatArray(animations);
    }

}

Enable scheduling Completables, not just AnimationCompletables


package com.smooch.rnsmooch;

import com.facebook.react.ReactPackage;
import com.facebook.react.bridge.JavaScriptModule;
import com.facebook.react.bridge.NativeModule;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.uimanager.ViewManager;

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

public class ReactNativeSmoochPackage implements ReactPackage {
    @Override
    public List<NativeModule> createNativeModules(ReactApplicationContext reactContext) {
        List<NativeModule> modules = new ArrayList<>();

        modules.add(new ReactNativeSmooch(reactContext));
        return modules;
    }

    @Override
    public List<Class<? extends JavaScriptModule>> createJSModules() {
        return Collections.emptyList();
    }

    @Override
    public List<ViewManager> createViewManagers(ReactApplicationContext reactContext) {
        return new ArrayList<>();
    }
}

package com.smooch.rnsmooch;

import com.facebook.react.ReactPackage;
import com.facebook.react.bridge.JavaScriptModule;
import com.facebook.react.bridge.NativeModule;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.uimanager.ViewManager;

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

public class ReactNativeSmoochPackage implements ReactPackage {
    @Override
    public List<NativeModule> createNativeModules(ReactApplicationContext reactContext) {
        List<NativeModule> modules = new ArrayList<>();

        modules.add(new ReactNativeSmooch(reactContext));
        return modules;
    }

    @Override
    public List<ViewManager> createViewManagers(ReactApplicationContext reactContext) {
        return new ArrayList<>();
    }
}

Remove method that was removed from interface


package io.cucumber.messages;

import org.junit.Test;

import java.time.Duration;
import java.time.Instant;
import java.time.temporal.TemporalUnit;

import static io.cucumber.messages.TimeConversion.durationToJavaDuration;
import static io.cucumber.messages.TimeConversion.javaDurationToDuration;
import static io.cucumber.messages.TimeConversion.javaInstantToTimestamp;
import static io.cucumber.messages.TimeConversion.timestampToJavaInstant;
import static org.junit.Assert.assertEquals;

public class TimeConversionTest {
    @Test
    public void convertsToAndFromTimestamp() {
        Instant javaInstant = Instant.now();
        Messages.Timestamp timestamp = javaInstantToTimestamp(javaInstant);
        Instant javaInstantAgain = timestampToJavaInstant(timestamp);

        assertEquals(javaInstant, javaInstantAgain);
    }

    @Test
    public void convertsToAndFromDuration() {
        Duration javaDuration = Duration.ofMillis(1234);
        Messages.Duration duration = javaDurationToDuration(javaDuration);
        Duration javaDurationAgain = durationToJavaDuration(duration);

        assertEquals(javaDuration, javaDurationAgain);
    }
}

package io.cucumber.messages;

import org.junit.Test;

import java.time.Duration;
import java.time.Instant;
import java.time.temporal.TemporalUnit;

import static io.cucumber.messages.TimeConversion.durationToJavaDuration;
import static io.cucumber.messages.TimeConversion.javaDurationToDuration;
import static io.cucumber.messages.TimeConversion.javaInstantToTimestamp;
import static io.cucumber.messages.TimeConversion.timestampToJavaInstant;
import static org.junit.Assert.assertEquals;

public class TimeConversionTest {
    @Test
    public void convertsToAndFromTimestamp() {
        Instant javaInstant = Instant.now();
        Messages.Timestamp timestamp = javaInstantToTimestamp(javaInstant);
        Instant javaInstantAgain = timestampToJavaInstant(timestamp);

        assertEquals(javaInstant, javaInstantAgain);
    }

    @Test
    public void convertsToAndFromDuration() {
        Duration javaDuration = Duration.ofSeconds(3, 161000);
        Messages.Duration duration = javaDurationToDuration(javaDuration);
        Duration javaDurationAgain = durationToJavaDuration(duration);

        assertEquals(javaDuration, javaDurationAgain);
    }
}

Add better Java test for time conversion


package pl.edu.uj.JImageStream.model;

import pl.edu.uj.JImageStream.api.ImageStream;
import pl.edu.uj.JImageStream.util.Util;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

//todo needs some added functionality, return bufferedImage, etc
public class StreamableImage {

    private BufferedImage bufferedImage;

    //todo extract to IOImageUtilsClass, maybe
    public StreamableImage(File file) throws IOException {
        bufferedImage = Util.convert(ImageIO.read(file), BufferedImage.TYPE_4BYTE_ABGR_PRE);
    }

    public StreamableImage(BufferedImage bufferedImage) {
        this.bufferedImage = bufferedImage;
    }

    //todo same, maybe
    public void save(String format, String file) throws IOException {
        ImageIO.write(bufferedImage, format, new File(file));
    }

    public int getHeight() {
        return bufferedImage.getHeight();
    }

    public int getWidth() {
        return bufferedImage.getWidth();
    }

    public ImageStream stream() {
        return new ImageStream(bufferedImage, false);
    }

    public ImageStream parallelStream() {
        return new ImageStream(bufferedImage, true);
    }

}

package pl.edu.uj.JImageStream.model;

import pl.edu.uj.JImageStream.api.ImageStream;
import pl.edu.uj.JImageStream.util.Util;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

//todo needs some added functionality, return bufferedImage, etc
public class StreamableImage {

    private BufferedImage bufferedImage;

    //todo extract to IOImageUtilsClass, maybe
    public StreamableImage(File file) throws IOException {
        bufferedImage = Util.convert(ImageIO.read(file), BufferedImage.TYPE_INT_ARGB_PRE);
    }

    public StreamableImage(BufferedImage bufferedImage) {
        this.bufferedImage = bufferedImage;
    }

    //todo same, maybe
    public void save(String format, String file) throws IOException {
        ImageIO.write(bufferedImage, format, new File(file));
    }

    public int getHeight() {
        return bufferedImage.getHeight();
    }

    public int getWidth() {
        return bufferedImage.getWidth();
    }

    public ImageStream stream() {
        return new ImageStream(bufferedImage, false);
    }

    public ImageStream parallelStream() {
        return new ImageStream(bufferedImage, true);
    }

}

Fix mistake in ColorModel from ABGR into ARGB


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

import com.github.daytron.revworks.data.UserType;

/**
 *
 * @author Ryan Gilera
 */
class StudentUser extends User {

    private final String studentID;

    public StudentUser(String id, String studentID, String firstname,
            String lastname, UserType userType) {
        super(id, firstname, lastname, userType);
        this.studentID = studentID;
    }

    public String getStudentID() {
        return studentID;
    }

}

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

import com.github.daytron.revworks.data.UserType;

/**
 * The child class of {@link User} for Administrators user role.
 *
 * @author Ryan Gilera
 */
class AdminUser extends User {

    private final String adminEmail;

     /**
     * Creates a new AdminUser object with parameter values namely the user id,
     * admin's email, first name and last name.
     *
     * @param userId The identifying id for a user
     * @param lecturerId The identifying id for a lecturer
     * @param email The email assigned by the College which acts as a username
     * @param firstname The first name of the lecturer
     * @param lastname The last name of the lecturer
     */
    public AdminUser(String id, String adminEmail, String firstname,
            String lastname) {
        super(id, firstname, lastname, UserType.ADMIN);
        this.adminEmail = adminEmail;
    }

    /**
     * Returns admin's email address.
     *
     * @return String object for admin's email information
     */
    public String getadminEmail() {
        return adminEmail;
    }

}

Add admin user child class


/**
 * Copyright 2011, Aiki IT, FotoRenamer
 *

 * 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 de.aikiit.fotorenamer.gui;

import org.junit.Test;

import static org.junit.Assert.assertNotNull;

/**
 * Test directory selector.
 *
 * @author hirsch
 * @version 2011-04-08, 00:22
 */
public class ImageDirectorySelectorTest {
    @Test
    public void performInit() {
        assertNotNull(new ImageDirectorySelector(null));
    }

}

/**
 * Copyright 2011, Aiki IT, FotoRenamer
 *

 * 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 de.aikiit.fotorenamer.gui;

import org.junit.Ignore;
import org.junit.Test;

import static org.junit.Assert.assertNotNull;

/**
 * Test directory selector.
 *
 * @author hirsch
 * @version 2011-04-08, 00:22
 */
@Ignore("Not working on travis since no X11 present")
public class ImageDirectorySelectorTest {
    @Test
    public void performInit() {
        assertNotNull(new ImageDirectorySelector(null));
    }

}

Fix buildfailure by ignoring test on travis.


package com.kii.thingif.command;

/**
 * Represents base cass of Action.
 */
public interface Action{
}

package com.kii.thingif.command;

/**
 * Marks a class as group of actions of command. The class implements Acton defines single actions
 * as fields of the class.
 *
The class must define {@link ActionAnnotation} for each field of the class, SDK uses the
 * defined annotations to serialize the class to json data or deserialize json data to a instance
 * of the class.
 *
 *
Serialize Principles

 *

 *
Name of action after serialized.
 *

 *

 *             If value of actionName of {@link ActionAnnotation} is not an empty string, SDK uses
 *             this value as key of action in serialized json object.
 *

 *

 *             If value of actionName annotation is empty string, SDK will name of attribute of
 *             the class as key of action in serialized json object.
 *

 *

 *

 *
Value of action is serialized with Gson.
 *

 *

 *             If action value is null, SDK does not include the action into serialized json data.
 *

 *

 *             If action value is primitive type(like int, boolean, float, double), SDK serializes
 *             it by its type.
 *

 *

 *             If action value is simple data type(like String, Number or subclass of Number(Integer,
 *             Float, etc.)), SDK serializes it by its type.
 *

 *

 *             If action value is customized object defined by developer, SDK serializes it using Gson.
 *

 *

 *            If action value is Collection type, SDK serializes it using Gson.
 *

 *

 *            If action value is array(like int[]), SDK serialized it using Gson.
 *

 *

 *

 *

 */
public interface Action {
}

Add description of serialize and deserialize(not completed)


package com.jpardogo.android.listbuddies.models;

import android.content.Context;
import android.graphics.Color;

import com.jpardogo.android.listbuddies.R;
import com.jpardogo.android.listbuddies.adapters.CustomizeSpinnersAdapter;

import java.util.Random;

/**
 * Created by jpardogo on 22/02/2014.
 */
public class KeyValuePair {
    private String key;
    private Object value;

    public KeyValuePair(String key, Object value) {
        this.key = key;
        this.value = value;
    }

    public int getColor(Context context) {
        int color = -1;
        if (value instanceof CustomizeSpinnersAdapter.OptionTypes) {
            switch ((CustomizeSpinnersAdapter.OptionTypes) value) {
                case BLACK:
                    color = context.getResources().getColor(R.color.black);
                    break;
                case RANDOM:
                    Random rnd = new Random();
                    color = Color.argb(255, rnd.nextInt(256), rnd.nextInt(256), rnd.nextInt(256));
                    break;
            }
        } else {
            throw new ClassCastException("Wrong type of value, the value must be CustomizeSpinnersAdapter.OptionTypes");
        }
        return color;
    }

    public String getKey() {
        return key;
    }

    public int getScrollOption() {
        return (Integer) value;
    }
}

package com.jpardogo.android.listbuddies.models;

import android.content.Context;

import com.jpardogo.android.listbuddies.R;
import com.jpardogo.android.listbuddies.adapters.CustomizeSpinnersAdapter;

/**
 * Created by jpardogo on 22/02/2014.
 */
public class KeyValuePair {
    private String key;
    private Object value;

    public KeyValuePair(String key, Object value) {
        this.key = key;
        this.value = value;
    }

    public int getColor(Context context) {
        int color = -1;
        if (value instanceof CustomizeSpinnersAdapter.OptionTypes) {
            switch ((CustomizeSpinnersAdapter.OptionTypes) value) {
                case BLACK:
                    color = context.getResources().getColor(R.color.black);
                    break;
                case INSET:
                    color = context.getResources().getColor(R.color.inset);
                    break;
            }
        } else {
            throw new ClassCastException("Wrong type of value, the value must be CustomizeSpinnersAdapter.OptionTypes");
        }
        return color;
    }

    public String getKey() {
        return key;
    }

    public int getScrollOption() {
        return (Integer) value;
    }
}

Change random for inset color


package me.yamakaja.runtimetransformer;

import java.io.File;
import java.lang.reflect.Method;
import java.net.URL;
import java.net.URLClassLoader;

/**
 * Created by Yamakaja on 19.05.17.
 */
public class RuntimeTransformer {

    public RuntimeTransformer(Class<?>... transformers) {
        ClassLoader systemClassLoader = ClassLoader.getSystemClassLoader();
        if (systemClassLoader instanceof URLClassLoader) {
            URLClassLoader urlClassLoader = (URLClassLoader) ClassLoader.getSystemClassLoader();

            try {
                Method method = URLClassLoader.class.getDeclaredMethod("addURL", URL.class);
                method.setAccessible(true);

                File file = new File(new File(System.getProperty("java.home")).getParent(), "lib/tools.jar");
                if (!file.exists())
                    throw new RuntimeException("Not running with JDK!");

                method.invoke(urlClassLoader, file.toURI().toURL());
            } catch (Throwable throwable) {
                throwable.printStackTrace();
            }
        }

        TransformerUtils.attachAgent(TransformerUtils.saveAgentJar(), transformers);
    }

}

package me.yamakaja.runtimetransformer;

import java.io.File;
import java.lang.reflect.Method;
import java.net.URL;
import java.net.URLClassLoader;
import java.nio.file.Files;
import java.nio.file.Path;

/**
 * Created by Yamakaja on 19.05.17.
 */
public class RuntimeTransformer {

    private static final String ATTACH_MOD_PATH = "jmods/jdk.attach.jmod";

    public RuntimeTransformer(Class<?>... transformers) {
        ClassLoader systemClassLoader = ClassLoader.getSystemClassLoader();

        File javaHome = new File(System.getProperty("java.home"));
        if (systemClassLoader instanceof URLClassLoader) {
            URLClassLoader urlClassLoader = (URLClassLoader) ClassLoader.getSystemClassLoader();

            try {
                Method method = URLClassLoader.class.getDeclaredMethod("addURL", URL.class);
                method.setAccessible(true);

                File toolsJar = new File(javaHome, "lib/tools.jar");
                if (!toolsJar.exists())
                    throw new RuntimeException("Not running with JDK!");

                method.invoke(urlClassLoader, toolsJar.toURI().toURL());
            } catch (Throwable throwable) {
                throwable.printStackTrace();
            }
        } else {
            Path attachMod = javaHome.toPath().resolve(ATTACH_MOD_PATH);
            if (Files.notExists(attachMod)) {
                throw new RuntimeException("Not running with JDK!");
            }
        }

        TransformerUtils.attachAgent(TransformerUtils.saveAgentJar(), transformers);
    }

}

Verify if the JDK attach mod is installed


package org.synyx.urlaubsverwaltung;

import org.springframework.test.context.DynamicPropertyRegistry;
import org.springframework.test.context.DynamicPropertySource;
import org.testcontainers.containers.MariaDBContainer;

import static org.testcontainers.containers.MariaDBContainer.NAME;

public abstract class TestContainersBase {

    static final MariaDBContainer<?> mariaDB = new MariaDBContainer<>(NAME + ":10.5")
        .withCommand("--character-set-server=utf8mb4", "--collation-server=utf8mb4_unicode_ci");

    @DynamicPropertySource
    static void mariaDBProperties(DynamicPropertyRegistry registry) {
        mariaDB.start();
        registry.add("spring.datasource.url", mariaDB::getJdbcUrl);
        registry.add("spring.datasource.username", mariaDB::getUsername);
        registry.add("spring.datasource.password", mariaDB::getPassword);
    }
}

package org.synyx.urlaubsverwaltung;

import org.springframework.test.context.DynamicPropertyRegistry;
import org.springframework.test.context.DynamicPropertySource;
import org.testcontainers.containers.MariaDBContainer;

import static org.testcontainers.containers.MariaDBContainer.NAME;

public abstract class TestContainersBase {

    static final MariaDBContainer<?> mariaDB = new MariaDBContainer<>(NAME + ":10.5")
        .withCommand("--character-set-server=utf8mb4", "--collation-server=utf8mb4_unicode_ci", "--max-connections=300");

    @DynamicPropertySource
    static void mariaDBProperties(DynamicPropertyRegistry registry) {
        mariaDB.start();
        registry.add("spring.datasource.url", mariaDB::getJdbcUrl);
        registry.add("spring.datasource.username", mariaDB::getUsername);
        registry.add("spring.datasource.password", mariaDB::getPassword);
    }
}

Increase max connections to 300 for mariadb


package com.indeed.proctor.store;

import java.util.Objects;
import java.util.Set;

/**
 * Details of a single revision
 */
public class RevisionDetails {
    private final Revision revision;
    private final Set<String> modifiedTests;

    public RevisionDetails(
            final Revision revision,
            final Set<String> modifiedTests
    ) {
        this.revision = revision;
        this.modifiedTests = modifiedTests;
    }

    public Revision getRevision() {
        return revision;
    }

    public Set<String> getModifiedTests() {
        return modifiedTests;
    }

    @Override
    public boolean equals(final Object o) {
        if (this == o) {
            return true;
        }
        if (o == null || getClass() != o.getClass()) {
            return false;
        }
        final RevisionDetails that = (RevisionDetails) o;
        return Objects.equals(revision, that.revision) &&
                Objects.equals(modifiedTests, that.modifiedTests);
    }

    @Override
    public int hashCode() {
        return Objects.hash(revision, modifiedTests);
    }

    @Override
    public String toString() {
        return com.google.common.base.Objects.toStringHelper(this)
                .add("revision", revision)
                .add("modifiedTests", modifiedTests)
                .toString();
    }
}

package com.indeed.proctor.store;

import javax.annotation.Nonnull;
import java.util.Objects;
import java.util.Set;

/**
 * Details of a single revision
 */
public class RevisionDetails {
    @Nonnull
    private final Revision revision;
    @Nonnull
    private final Set<String> modifiedTests;

    public RevisionDetails(
            @Nonnull final Revision revision,
            @Nonnull final Set<String> modifiedTests
    ) {
        this.revision = revision;
        this.modifiedTests = modifiedTests;
    }

    @Nonnull
    public Revision getRevision() {
        return revision;
    }

    @Nonnull
    public Set<String> getModifiedTests() {
        return modifiedTests;
    }

    @Override
    public boolean equals(final Object o) {
        if (this == o) {
            return true;
        }
        if (o == null || getClass() != o.getClass()) {
            return false;
        }
        final RevisionDetails that = (RevisionDetails) o;
        return Objects.equals(revision, that.revision) &&
                Objects.equals(modifiedTests, that.modifiedTests);
    }

    @Override
    public int hashCode() {
        return Objects.hash(revision, modifiedTests);
    }

    @Override
    public String toString() {
        return com.google.common.base.Objects.toStringHelper(this)
                .add("revision", revision)
                .add("modifiedTests", modifiedTests)
                .toString();
    }
}

Add nonnull for fields in the model


// Copyright Verizon Media. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.restapi;

import com.yahoo.container.jdisc.HttpRequest;
import com.yahoo.container.jdisc.HttpResponse;
import com.yahoo.container.jdisc.LoggingRequestHandler;

/**
 * @author bjorncs
 */
public abstract class RestApiRequestHandler<T extends RestApiRequestHandler<T>> extends LoggingRequestHandler {

    private final RestApi restApi;

    @FunctionalInterface public interface RestApiProvider<T> { RestApi createRestApi(T self); }

    /**
     * RestApi will usually refer to handler methods of subclass, which are not accessible before super constructor has completed.
     * This is hack to leak reference to subclass instance's "this" reference.
     * Caller must ensure that provider instance does not try to access any uninitialized fields.
     */
    @SuppressWarnings("unchecked")
    protected RestApiRequestHandler(LoggingRequestHandler.Context context, RestApiProvider<T> provider) {
        super(context);
        this.restApi = provider.createRestApi((T)this);
    }

    protected RestApiRequestHandler(LoggingRequestHandler.Context context, RestApi restApi) {
        super(context);
        this.restApi = restApi;
    }

    @Override public final HttpResponse handle(HttpRequest request) { return restApi.handleRequest(request); }
}

// Copyright Verizon Media. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.restapi;

import com.yahoo.container.jdisc.HttpRequest;
import com.yahoo.container.jdisc.HttpResponse;
import com.yahoo.container.jdisc.LoggingRequestHandler;

/**
 * @author bjorncs
 */
public abstract class RestApiRequestHandler<T extends RestApiRequestHandler<T>> extends LoggingRequestHandler {

    private final RestApi restApi;

    @FunctionalInterface public interface RestApiProvider<T> { RestApi createRestApi(T self); }

    /**
     * RestApi will usually refer to handler methods of subclass, which are not accessible before super constructor has completed.
     * This is hack to leak reference to subclass instance's "this" reference.
     * Caller must ensure that provider instance does not try to access any uninitialized fields.
     */
    @SuppressWarnings("unchecked")
    protected RestApiRequestHandler(LoggingRequestHandler.Context context, RestApiProvider<T> provider) {
        super(context);
        this.restApi = provider.createRestApi((T)this);
    }

    protected RestApiRequestHandler(LoggingRequestHandler.Context context, RestApi restApi) {
        super(context);
        this.restApi = restApi;
    }

    @Override public final HttpResponse handle(HttpRequest request) { return restApi.handleRequest(request); }

    protected RestApi restApi() { return restApi; }
}

Add getter for restapi instance


package rocks.nt.apm.jmeter.config.influxdb;

/**
 * Constants (Tag, Field, Measurement) names for the requests measurement.
 *
 * @author Alexander Wert
 *
 */
public interface RequestMeasurement {

	/**
	 * Measurement name.
	 */
	String MEASUREMENT_NAME = "requestsRaw";

	/**
	 * Tags.
	 *
	 * @author Alexander Wert
	 *
	 */
	public interface Tags {
		/**
		 * Request name tag.
		 */
		String REQUEST_NAME = "requestName";
	}

	/**
	 * Fields.
	 *
	 * @author Alexander Wert
	 *
	 */
	public interface Fields {
		/**
		 * Response time field.
		 */
		String RESPONSE_TIME = "responseTime";

		/**
		 * Error count field.
		 */
		String ERROR_COUNT = "errorCount";

		/**
		 * Thread name field
		 */
		String THREAD_NAME = "threadName";

		/**
		 * Test name field
		 */
		String TEST_NAME = "testName";

		 * Node name field
		 */
		String NODE_NAME = "nodeName";
	}
}

package rocks.nt.apm.jmeter.config.influxdb;

/**
 * Constants (Tag, Field, Measurement) names for the requests measurement.
 *
 * @author Alexander Wert
 *
 */
public interface RequestMeasurement {

	/**
	 * Measurement name.
	 */
	String MEASUREMENT_NAME = "requestsRaw";

	/**
	 * Tags.
	 *
	 * @author Alexander Wert
	 *
	 */
	public interface Tags {
		/**
		 * Request name tag.
		 */
		String REQUEST_NAME = "requestName";
	}

	/**
	 * Fields.
	 *
	 * @author Alexander Wert
	 *
	 */
	public interface Fields {
		/**
		 * Response time field.
		 */
		String RESPONSE_TIME = "responseTime";

		/**
		 * Error count field.
		 */
		String ERROR_COUNT = "errorCount";

		/**
		 * Thread name field
		 */
		String THREAD_NAME = "threadName";

		/**
		 * Test name field
		 */
		String TEST_NAME = "testName";

		/**
		 * Node name field
		 */
		String NODE_NAME = "nodeName";
	}
}

Fix build again after merge error in Github.


package com.openxc.measurements;

import junit.framework.TestCase;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;

public class BrakePedalStatusTest extends TestCase {
    BrakePedalStatus measurement;

    @Override
    public void setUp() {
        measurement = new BrakePedalStatus(new Boolean(false));
    }

    public void testGet() {
        assertThat(measurement.getValue().booleanValue(), equalTo(false));
    }

    public void testHasNoRange() {
        assertFalse(measurement.hasRange());
    }
}

package com.openxc.measurements;

import junit.framework.TestCase;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;

public class BrakePedalStatusTest extends TestCase {
    BrakePedalStatus measurement;

    @Override
    public void setUp() {
        measurement = new BrakePedalStatus(new Boolean(false));
    }

    public void testGet() {
        assertThat(measurement.getValue().booleanValue(), equalTo(false));
    }

    public void testHasNoRange() {
        assertFalse(measurement.hasRange());
    }

    public void testGenericName() {
        assertEquals(measurement.getGenericName(), measurement.ID);
    }
}

Test that genericName method is overridden.


package eu.f3rog.blade.sample.arg;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.EditText;

import java.util.Random;

import blade.Blade;
import blade.F;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import eu.f3rog.blade.sample.R;

@Blade
public class TestArgActivity extends AppCompatActivity {

    @BindView(R.id.edt_num)
    EditText mEditNumber;
    @BindView(R.id.edt_text)
    EditText mEditText;

    @OnClick(R.id.btn_show_fragment)
    public void showFragment() {
        int number = Integer.parseInt(mEditNumber.getText().toString());
        String text = mEditText.getText().toString();
        Data data = new Data(number, text);

        double randomDouble = new Random().nextDouble();

        getSupportFragmentManager().beginTransaction()
                .replace(R.id.frag, F.newDataFragment(randomDouble, data))
                .commit();
    }

    @OnClick(R.id.btn_show_dialog)
    public void b2() {
        F.newSampleDialogFragment("Hello mate :)").show(getSupportFragmentManager(), "some-tag");
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_test_arg);
        ButterKnife.bind(this);
    }

}

package eu.f3rog.blade.sample.arg;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.EditText;
import android.widget.Toast;

import java.util.Random;

import blade.Blade;
import blade.F;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import eu.f3rog.blade.sample.R;

@Blade
public class TestArgActivity extends AppCompatActivity {

    @BindView(R.id.edt_num)
    EditText mEditNumber;
    @BindView(R.id.edt_text)
    EditText mEditText;

    @OnClick(R.id.btn_show_fragment)
    public void showFragment() {
        if (mEditNumber.getText().length() == 0) {
            Toast.makeText(this, "Input a number!", Toast.LENGTH_SHORT).show();
            mEditNumber.requestFocus();
            return;
        }
        int number = Integer.parseInt(mEditNumber.getText().toString());
        String text = mEditText.getText().toString();
        Data data = new Data(number, text);

        double randomDouble = new Random().nextDouble();

        getSupportFragmentManager().beginTransaction()
                .replace(R.id.frag, F.newDataFragment(randomDouble, data))
                .commit();
    }

    @OnClick(R.id.btn_show_dialog)
    public void b2() {
        F.newSampleDialogFragment("Hello mate :)").show(getSupportFragmentManager(), "some-tag");
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_test_arg);
        ButterKnife.bind(this);
    }

}

Fix crash when Arg "Enter Number" field is left empty.


package com.michelboudreau.alternator;

public class AlternatorDBServer
{
    public static void main(final String[] args) throws Exception
    {
        int port = 9090;

        // TODO: Parse args for alternate port.
        AlternatorDB db = new AlternatorDB(port);
        db.start();

        System.out.println(
                String.format("AlternatorDB has started and is listening on port %d.", port));
    }
}

package com.michelboudreau.alternator;

import java.io.File;

public class AlternatorDBServer {

    /**
     * Allow the database to be persisted to disk when the server shuts down.
     */
    private static final boolean sandboxStatusSaveToDisk = false;

    /**
     * Discard the database contents when the server shuts down.
     */
    private static final boolean sandboxStatusDiscardData = true;

    private static final int defaultPort = 9090;

    public static void main(final String[] args) throws Exception {

        File persistenceFile = null;

        int port = defaultPort;

        if (args.length >= 1) {
            String persistencePath = args[0];
            persistenceFile = new File(persistencePath);
        }

        AlternatorDB db = new AlternatorDB(port, persistenceFile, sandboxStatusSaveToDisk);
        db.start();

        if (persistenceFile != null) {
            System.out.println(
                    String.format("+++++ AlternatorDB loaded data from file: %s", persistenceFile.getCanonicalPath()));
        }

        System.out.println(
                String.format("+++++ AlternatorDB has started and is listening on port %d.", port));

        if (persistenceFile != null) {
            System.out.println(
                    String.format("Press the Enter key to exit gracefully and save data to file: %s", persistenceFile.getCanonicalPath()));
        }
        System.out.print("Use Control-C to force exit (without saving data changes): ");
        String input = System.console().readLine();

        System.out.println("----- AlternatorDB is shutting down...");

        db.stop();

        if (persistenceFile != null) {
            System.out.println(
                    String.format("----- Data was saved to file: %s", persistenceFile.getCanonicalPath()));
        }
    }
}

Support a persistence file in executable JAR console operation.


package jp.ac.nii.prl.mape.controller.service;

import java.net.URI;

import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import jp.ac.nii.prl.mape.controller.model.MAPEKComponent;

@Service("knowledgeBaseService")
public class KnowledgeBaseServiceImpl implements KnowledgeBaseService {

	/* (non-Javadoc)
	 * @see jp.ac.nii.prl.mape.controller.service.KnowledgeBaseService#put(java.lang.String, java.lang.String)
	 */
	@Override
	public void put(MAPEKComponent kb, String bx, String view) {
		RestTemplate template = new RestTemplate();
		URI location = template.postForLocation(kb.getBaseUrl() + "/bx", view);
		view = template.getForObject(location, String.class);
	}

	/* (non-Javadoc)
	 * @see jp.ac.nii.prl.mape.controller.service.KnowledgeBaseService#get(java.lang.String)
	 */
	@Override
	public String get(MAPEKComponent kb, String bx) {
		RestTemplate template = new RestTemplate();
		String view = template.getForObject(kb.getBaseUrl() + "/bx", String.class);
		return view;
	}
}

package jp.ac.nii.prl.mape.controller.service;

import java.net.URI;

import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import jp.ac.nii.prl.mape.controller.model.MAPEKComponent;

@Service("knowledgeBaseService")
public class KnowledgeBaseServiceImpl implements KnowledgeBaseService {

	/* (non-Javadoc)
	 * @see jp.ac.nii.prl.mape.controller.service.KnowledgeBaseService#put(java.lang.String, java.lang.String)
	 */
	@Override
	public void put(MAPEKComponent kb, String bx, String view) {
		RestTemplate template = new RestTemplate();
		URI location = template.postForLocation(kb.getUrl() + "/get/" + bx, view);
		view = template.getForObject(location, String.class);
	}

	/* (non-Javadoc)
	 * @see jp.ac.nii.prl.mape.controller.service.KnowledgeBaseService#get(java.lang.String)
	 */
	@Override
	public String get(MAPEKComponent kb, String bx) {
		RestTemplate template = new RestTemplate();
		System.out.println(kb.getUrl() + "/get/" + bx);
		String view = template.getForObject(kb.getUrl() + "/get/" + bx, String.class);
		return view;
	}
}

Fix URLs in KB service calls


package eu.livotov.labs.android.d3s;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static java.util.regex.Pattern.CASE_INSENSITIVE;
import static java.util.regex.Pattern.DOTALL;
import static java.util.regex.Pattern.compile;

/**
 * Utilities to find 3DS values in ACS webpages.
 */
final class D3SRegexUtils {

    /**
     * Pattern to find the value of an attribute named value from an html tag with an attribute named name and a value of PaRes.
     */
    private static final Pattern paresFinder = compile("<input(?=.+?name=\"PaRes\")(?=.+?value=\"(\\S+?)\").+>", DOTALL | CASE_INSENSITIVE);

    /**
     * Finds the PaRes in an html page.
     *
     * @param html String representation of the html page to search within.
     * @return PaRes or null if not found
     */
    @Nullable
    static String findPaRes(@NonNull String html) {
        if (html.trim().isEmpty()) return null;

        String paRes = null;
        Matcher paresMatcher = paresFinder.matcher(html);
        if (paresMatcher.find()) {
            paRes = paresMatcher.group(1);
        }

        return paRes;
    }
}

package eu.livotov.labs.android.d3s;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static java.util.regex.Pattern.CASE_INSENSITIVE;
import static java.util.regex.Pattern.DOTALL;
import static java.util.regex.Pattern.compile;

/**
 * Utilities to find 3DS values in ACS webpages.
 */
final class D3SRegexUtils {

    /**
     * Pattern to find the value of an attribute named value from an html tag with an attribute named name and a value of PaRes.
     */
    private static final Pattern paresFinder = compile("<input(?=.+?name=\"PaRes\")(?=.+?value=\"(\\S+?)\").+>", DOTALL | CASE_INSENSITIVE);

    /**
     * Finds the PaRes in an html page.
     * <p>
     * Note: If more than one PaRes is found in a page only the first will be returned.
     *
     * @param html String representation of the html page to search within.
     * @return PaRes or null if not found
     */
    @Nullable
    static String findPaRes(@NonNull String html) {
        if (html.trim().isEmpty()) return null;

        String paRes = null;
        Matcher paresMatcher = paresFinder.matcher(html);
        if (paresMatcher.find()) {
            paRes = paresMatcher.group(1);
        }

        return paRes;
    }
}

Add additional comment about only matching first value