package uk.ac.ebi.quickgo.index.annotation;

/**
 * A class for creating stubbed annotations, representing rows of data read from
 * annotation source files.
 *
 * Created 22/04/16
 * @author Edd
 */
public class AnnotationMocker {
    public static Annotation createValidAnnotation() {
        Annotation annotation = new Annotation();

        annotation.db = "IntAct";
        annotation.dbObjectId = "EBI-10043081";
        annotation.dbReferences = "PMID:12871976";
        annotation.qualifier = "enables";
        annotation.goId = "GO:0000977";
        annotation.interactingTaxonId = "taxon:12345";
        annotation.evidenceCode = "ECO:0000353";
        annotation.with = "GO:0036376,GO:1990573";
        annotation.assignedBy = "IntAct";
        annotation.annotationExtension = "occurs_in(CL:1000428)";
        annotation.annotationProperties = "go_evidence=IEA|taxon_id=35758|db_subset=TrEMBL|db_object_symbol=moeA5|db_object_type=protein|db_object_type=protein|target_set=BHF-UCL,Exosome,KRUK|taxon_lineage=1,2,3,4";
        return annotation;
    }
}

package uk.ac.ebi.quickgo.index.annotation;

/**
 * A class for creating stubbed annotations, representing rows of data read from
 * annotation source files.
 *
 * Created 22/04/16
 * @author Edd
 */
public class AnnotationMocker {
    public static Annotation createValidAnnotation() {
        Annotation annotation = new Annotation();

        annotation.db = "IntAct";
        annotation.dbObjectId = "EBI-10043081";
        annotation.dbReferences = "PMID:12871976";
        annotation.qualifier = "enables";
        annotation.goId = "GO:0000977";
        annotation.interactingTaxonId = "taxon:12345";
        annotation.evidenceCode = "ECO:0000353";
        annotation.with = "GO:0036376,GO:1990573";
        annotation.assignedBy = "IntAct";
        annotation.annotationExtension = "occurs_in(CL:1000428)";
        annotation.annotationProperties =
                "go_evidence=IEA|taxon_id=35758|db_subset=TrEMBL|db_object_symbol=moeA5|db_object_type=protein" +
                        "|target_set=BHF-UCL,Exosome,KRUK|taxon_lineage=1,2,3,4";
        return annotation;
    }
}

Remove duplicated db_object_type=protein from the test value for annotation properties.


package org.intermine.webservice.server;

/*
 * Copyright (C) 2002-2011 FlyMine
 *
 * This code may be freely distributed and modified under the
 * terms of the GNU Lesser General Public Licence.  This should
 * be distributed with the code.  See the LICENSE file for more
 * information or http://www.gnu.org/copyleft/lesser.html.
 *
 */

import org.intermine.webservice.server.output.Output;

/**
 * Http status code dictionary.
 * @author Jakub Kulaviak
 **/
public class StatusDictionary
{
    /**
     * @param statusCode status code
     * @return short description of specified status code
     */
    public static String getDescription(int statusCode) {
        switch (statusCode) {
            case Output.SC_BAD_REQUEST:
                return "There is a problem on the client side (in the browser). Bad request. ";
            case Output.SC_FORBIDDEN:
                return "Forbidden. ";
            case Output.SC_INTERNAL_SERVER_ERROR:
                return "Internal server error. ";
            case Output.SC_NO_CONTENT:
                return "Resource representation is empty. ";
            case Output.SC_NOT_FOUND:
                return "Resource not found. ";
            case Output.SC_OK:
                return "OK";
            default:
                return "";
        }
    }
}

package org.intermine.webservice.server;

/*
 * Copyright (C) 2002-2011 FlyMine
 *
 * This code may be freely distributed and modified under the
 * terms of the GNU Lesser General Public Licence.  This should
 * be distributed with the code.  See the LICENSE file for more
 * information or http://www.gnu.org/copyleft/lesser.html.
 *
 */

import org.intermine.webservice.server.output.Output;

/**
 * HTTP status code dictionary.
 * @author Jakub Kulaviak
 **/
public class StatusDictionary
{
    /**
     * @param statusCode status code
     * @return short description of specified status code
     */
    public static String getDescription(int statusCode) {
        String ret;
    	switch (statusCode) {
            case Output.SC_BAD_REQUEST:
                ret = "Bad request. There was a problem with your request parameters:"; break;
            case Output.SC_FORBIDDEN:
                ret = "Forbidden. You do not have access to some part of this query - please log in."; break;
            case Output.SC_INTERNAL_SERVER_ERROR:
                ret = "Internal server error."; break;
            case Output.SC_NO_CONTENT:
                ret = "Resource representation is empty."; break;
            case Output.SC_NOT_FOUND:
                ret = "Resource not found."; break;
            case Output.SC_OK:
                ret = "OK"; break;
            default:
                ret = "Unknown Status";
        }
    	return statusCode + " " + ret;
    }
}

Include the status code in the string, and nicer messages


package me.izstas.rfs.server.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import me.izstas.rfs.server.config.web.PathWithinPattern;
import me.izstas.rfs.server.model.Metadata;
import me.izstas.rfs.server.service.MetadataService;

@RestController
@RequestMapping("/metadata/**")
public class MetadataController {
    @Autowired
    private MetadataService metadataService;

    @RequestMapping(method = RequestMethod.GET)
    public Metadata getMetadata(@PathWithinPattern String path) {
        return metadataService.getMetadataFromUserPath(path);
    }
}

package me.izstas.rfs.server.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import me.izstas.rfs.server.config.web.PathWithinPattern;
import me.izstas.rfs.server.model.Metadata;
import me.izstas.rfs.server.service.MetadataService;

@RestController
@RequestMapping("/metadata/**")
public class MetadataController {
    @Autowired
    private MetadataService metadataService;

    @RequestMapping(method = RequestMethod.GET)
    public Metadata getMetadata(@PathWithinPattern String path) {
        return metadataService.getMetadataFromUserPath(path);
    }

    @RequestMapping(method = RequestMethod.POST)
    public void applyMetadata(@PathWithinPattern String path, @RequestBody Metadata metadata) {
        metadataService.applyMetadataToUserPath(path, metadata);
    }
}

Add POST support for /metadata/**


package org.springframework.social.discord.connect;

import org.springframework.social.connect.ApiAdapter;
import org.springframework.social.connect.ConnectionValues;
import org.springframework.social.connect.UserProfile;
import org.springframework.social.connect.UserProfileBuilder;
import org.springframework.social.discord.api.Discord;
import org.springframework.social.discord.api.DiscordUser;
import org.springframework.web.client.HttpClientErrorException;

public class DiscordAdapter implements ApiAdapter<Discord> {
    @Override
    public boolean test(Discord api) {
        try {
            api.applicationOperations().getApplicationInfo();
            return true;
        } catch (HttpClientErrorException e) {
            return false;
        }
    }

    @Override
    public void setConnectionValues(Discord api, ConnectionValues values) {
        DiscordUser profile = api.userOperations().getUser();
        values.setProviderUserId(String.valueOf(profile.getId()));
        values.setDisplayName(api.userOperations().getNickname());
        values.setProfileUrl("https://discordapp.com/channels/@me");
        values.setImageUrl(api.userOperations().getAvatarUrl());
    }

    @Override
    public UserProfile fetchUserProfile(Discord api) {
        DiscordUser profile = api.userOperations().getUser();
        return new UserProfileBuilder()
            .setId(profile.getId())
            .setFirstName(profile.getUsername())
            .setLastName("#" + profile.getDiscriminator())
            .setUsername(api.userOperations().getNickname())
            .setEmail(profile.getEmail())
            .build();
    }

    @Override
    public void updateStatus(Discord api, String message) {
        // not supported
    }
}

package org.springframework.social.discord.connect;

import org.springframework.social.connect.ApiAdapter;
import org.springframework.social.connect.ConnectionValues;
import org.springframework.social.connect.UserProfile;
import org.springframework.social.connect.UserProfileBuilder;
import org.springframework.social.discord.api.Discord;
import org.springframework.social.discord.api.DiscordUser;
import org.springframework.web.client.HttpClientErrorException;

public class DiscordAdapter implements ApiAdapter<Discord> {
    @Override
    public boolean test(Discord api) {
        try {
            api.applicationOperations().getApplicationInfo();
            return true;
        } catch (HttpClientErrorException e) {
            return false;
        }
    }

    @Override
    public void setConnectionValues(Discord api, ConnectionValues values) {
        DiscordUser profile = api.userOperations().getUser();
        values.setProviderUserId(String.valueOf(profile.getId()));
        values.setDisplayName(profile.getUsername());
        values.setProfileUrl("https://discordapp.com/channels/@me");
        values.setImageUrl(api.userOperations().getAvatarUrl());
    }

    @Override
    public UserProfile fetchUserProfile(Discord api) {
        DiscordUser profile = api.userOperations().getUser();
        return new UserProfileBuilder()
            .setId(profile.getId())
            .setName(profile.getUsername() + " " + profile.getDiscriminator())
            .setUsername(api.userOperations().getNickname())
            .setEmail(profile.getEmail())
            .build();
    }

    @Override
    public void updateStatus(Discord api, String message) {
        // not supported
    }
}

Drop the discriminator under displayName


package in.twizmwaz.cardinal.module.modules.arrows;

import in.twizmwaz.cardinal.util.MiscUtil;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.Color;
import org.bukkit.entity.Arrow;

public class ArrowRunnable implements Runnable {

    private final Arrow arrow;
    private final float x;
    private final float y;
    private final float z;

    private Integer taskId = null;

    protected ArrowRunnable(Arrow arrow, ChatColor chatColor) {
        this.arrow = arrow;
        Color rgb = MiscUtil.convertChatColorToColor(chatColor);
        x = (float) rgb.getRed() / 255;
        y = (float) rgb.getGreen() / 255;
        z = (float) rgb.getBlue() / 255;
    }

    public void setTask(int id) {
        this.taskId = id;
    }

    @Override
    public void run() {
        if (arrow.isOnGround() || arrow.isDead()) {
            ArrowModule.arrowOnGround(arrow);
            Bukkit.getScheduler().cancelTask(taskId);
        } else {
            ArrowModule.sendArrowParticle(arrow, x, y, z);
        }
    }

}

package in.twizmwaz.cardinal.module.modules.arrows;

import in.twizmwaz.cardinal.util.MiscUtil;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.Color;
import org.bukkit.entity.Arrow;

public class ArrowRunnable implements Runnable {

    private static final float ZERO = 0.00001f;

    private final Arrow arrow;
    private final float x;
    private final float y;
    private final float z;

    private Integer taskId = null;

    protected ArrowRunnable(Arrow arrow, ChatColor chatColor) {
        this.arrow = arrow;
        Color rgb = MiscUtil.convertChatColorToColor(chatColor);
        x = rgbToFloat(rgb.getRed());
        y = rgbToFloat(rgb.getGreen());
        z = rgbToFloat(rgb.getBlue());
    }

    private static float rgbToFloat(int i) {
        if (i == 0) {
            return ZERO;
        }
        return (float) i / 255;
    }

    public void setTask(int id) {
        this.taskId = id;
    }

    @Override
    public void run() {
        if (arrow.isOnGround() || arrow.isDead()) {
            ArrowModule.arrowOnGround(arrow);
            Bukkit.getScheduler().cancelTask(taskId);
        } else {
            ArrowModule.sendArrowParticle(arrow, x, y, z);
        }
    }

}

Fix arrow particle color bugs


package info.u_team.u_team_test.screen;

import com.mojang.blaze3d.matrix.MatrixStack;

import info.u_team.u_team_core.gui.UContainerScreen;
import info.u_team.u_team_test.TestMod;
import info.u_team.u_team_test.container.BasicFluidInventoryContainer;
import net.minecraft.entity.player.PlayerInventory;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.text.ITextComponent;

public class BasicFluidInventoryScreen extends UContainerScreen<BasicFluidInventoryContainer> {

	public BasicFluidInventoryScreen(BasicFluidInventoryContainer container, PlayerInventory playerInventory, ITextComponent title) {
		super(container, playerInventory, title, new ResourceLocation(TestMod.MODID, "textures/gui/fluid_inventory.png"));
	}

	@Override
	public void func_230430_a_(MatrixStack matrixStack, int mouseX, int mouseY, float partialTicks) {
		func_230446_a_(matrixStack);
		super.func_230430_a_(matrixStack, mouseX, mouseY, partialTicks);
		// buttons.forEach(button -> button.renderToolTip(mouseX, mouseY)); TODO nessessary??
		func_230459_a_(matrixStack, mouseX, mouseY);
	}
}

package info.u_team.u_team_test.screen;

import com.mojang.blaze3d.matrix.MatrixStack;

import info.u_team.u_team_core.gui.UContainerScreen;
import info.u_team.u_team_test.TestMod;
import info.u_team.u_team_test.container.BasicFluidInventoryContainer;
import net.minecraft.entity.player.PlayerInventory;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.text.ITextComponent;

public class BasicFluidInventoryScreen extends UContainerScreen<BasicFluidInventoryContainer> {

	public BasicFluidInventoryScreen(BasicFluidInventoryContainer container, PlayerInventory playerInventory, ITextComponent title) {
		super(container, playerInventory, title, new ResourceLocation(TestMod.MODID, "textures/gui/fluid_inventory.png"));
	}

	@Override
	public void func_230430_a_(MatrixStack matrixStack, int mouseX, int mouseY, float partialTicks) {
		func_230446_a_(matrixStack);
		super.func_230430_a_(matrixStack, mouseX, mouseY, partialTicks);
		field_230710_m_.forEach(widget -> widget.func_230443_a_(matrixStack, mouseX, mouseY));
		func_230459_a_(matrixStack, mouseX, mouseY);
	}
}

Add call for widget tool tips


import org.junit.Test;

import static org.junit.Assert.*;

public class LibraryTest {

    @Test
    public void testSomeLibraryMethod() {
        Library classUnderTest = new Library();
        assertTrue("someLibraryMethod should return 'true'", classUnderTest.someLibraryMethod());
    }
}

import org.junit.Test;

import static org.hamcrest.CoreMatchers.*;
import static org.junit.Assert.*;

public class LibraryTest {

    @Test
    public void testSomeLibraryMethod() {
        assertThat(new Library().someLibraryMethod(), is(true));
    }
}

Use assertThat instead of assertTrue


/**
 * Created by youweilu on 4/9/17.
 */
public class HeightofaTree{
    private static int treeHeight(Node n){
        if(n==null)return 0;
        return 1+Math.max(treeHeight(n.getLeft()),treeHeight(n.getRight()));
    }
}

/**
 * PROBLEM
 * The height of a tree (binary or not) is defined to be the maximum distance from the root node to any leaf node. The
 * tree in Figure 5-2, for example, has a height of 4 because the path from A to F, G, or H involves four nodes. Write
 * a function to calculate the height of an rbitrary binary tree.
 */
public class HeightofaTree{
    private static int treeHeight(Node n){
        if(n==null)return 0;
        return 1+Math.max(treeHeight(n.getLeft()),treeHeight(n.getRight()));
    }
}

Add problem description of height of tree.


package com.github.aureliano.edocs.app.gui.menu;

import javax.swing.JMenu;

public class HelpMenu extends JMenu {

	private static final long serialVersionUID = -3275074190970882751L;

	private AboutMenuItem aboutMenuItem;

	public HelpMenu() {
		super.setText("Help");
		this.addMenuItems();
	}

	private void addMenuItems() {
		this.aboutMenuItem = new AboutMenuItem();

		super.add(this.aboutMenuItem);
	}
}

package com.github.aureliano.edocs.app.gui.menu;

import javax.swing.JMenu;

public class HelpMenu extends JMenu {

	private static final long serialVersionUID = -3275074190970882751L;

	private LicenseMenuItem licenseMenuItem;
	private AboutMenuItem aboutMenuItem;

	public HelpMenu() {
		super.setText("Help");
		this.addMenuItems();
	}

	private void addMenuItems() {
		this.licenseMenuItem = new LicenseMenuItem();
		this.aboutMenuItem = new AboutMenuItem();

		super.add(this.licenseMenuItem);
		super.add(this.aboutMenuItem);
	}
}

Add License item to Help menu.


// Copyright © 2013 Esko Luontola <www.orfjackal.net>
// This software is released under the Apache License 2.0.
// The license text is at http://www.apache.org/licenses/LICENSE-2.0

package net.orfjackal.retrolambda.test;

import org.junit.Test;

import java.util.concurrent.Callable;

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;

public class LambdaTest {

    @Test
    public void lambda_returning_value() throws Exception {
        Callable<String> lambda = () -> "some value";

        assertThat(lambda.call(), is("some value"));
    }

    @Test
    public void lambda_returning_nothing() {
        Runnable lambda = () -> {
        };

        lambda.run();
    }

    private int instanceVar = 0;

    @Test
    public void lambda_using_instance_variables() {
        Runnable lambda = () -> {
            instanceVar = 42;
        };
        lambda.run();

        assertThat(instanceVar, is(42));
    }
}

// Copyright © 2013 Esko Luontola <www.orfjackal.net>
// This software is released under the Apache License 2.0.
// The license text is at http://www.apache.org/licenses/LICENSE-2.0

package net.orfjackal.retrolambda.test;

import org.junit.Test;

import java.util.concurrent.Callable;

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;

public class LambdaTest {

    @Test
    public void lambda_returning_value() throws Exception {
        Callable<String> lambda = () -> "some value";

        assertThat(lambda.call(), is("some value"));
    }

    @Test
    public void lambda_returning_nothing() {
        Runnable lambda = () -> {
        };

        lambda.run();
    }

    private int instanceVar = 0;

    @Test
    public void lambda_using_instance_variables() {
        Runnable lambda = () -> {
            instanceVar = 42;
        };
        lambda.run();

        assertThat(instanceVar, is(42));
    }

    @Test
    public void lambda_using_local_variables() {
        int[] localVar = new int[1];
        Runnable lambda = () -> {
            localVar[0] = 42;
        };
        lambda.run();

        assertThat(localVar[0], is(42));
    }
}

Test for using local variables


package com.bwfcwalshy.flarebot.permissions;

import java.util.function.Predicate;

public class PermissionNode implements Predicate<PermissionNode> {

    private final String node;

    public PermissionNode(String node) {
        this.node = node;
    }

    public String getNode() {
        return node;
    }

    @Override
    public boolean test(PermissionNode node) {
        String textNode = getNode().replace(".", "\\.").replace("*", ".*");
        return node.getNode().matches(textNode);
    }
}

package com.bwfcwalshy.flarebot.permissions;

import java.util.Arrays;
import java.util.function.Predicate;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

public class PermissionNode implements Predicate<PermissionNode> {

    private final String node;

    public PermissionNode(String node) {
        this.node = node;
    }

    public String getNode() {
        return node;
    }

    @Override
    public boolean test(PermissionNode node) {
        String textNode = Arrays.stream(getNode().split("(?:^\\*(\\.))|(?:(?<=\\.)\\*(?=\\.))"))
                .map(Pattern::quote)
                .collect(Collectors.joining(".+"));
        return node.getNode().matches(textNode);
    }
}

Make permission nodes better again


package org.bouncycastle.crypto.tls;

import java.io.IOException;
import java.util.Hashtable;

public interface TlsServer {

    void init(TlsServerContext context);

    ProtocolVersion selectVersion(ProtocolVersion clientVersion) throws IOException;

    int selectCipherSuite(int[] offeredCipherSuites) throws IOException;

    short selectCompressionMethod(short[] offeredCompressionMethods) throws IOException;

    void notifySecureRenegotiation(boolean secureNegotiation) throws IOException;

    // Hashtables are (Integer -> byte[])
    Hashtable processClientExtensions(Hashtable serverExtensions) throws IOException;

    TlsCredentials getCredentials();

    TlsKeyExchange getKeyExchange() throws IOException;

    CertificateRequest getCertificateRequest();

    TlsCompression getCompression() throws IOException;

    TlsCipher getCipher() throws IOException;
}

package org.bouncycastle.crypto.tls;

import java.io.IOException;
import java.util.Hashtable;

public interface TlsServer {

    void init(TlsServerContext context);

    ProtocolVersion selectVersion(ProtocolVersion clientVersion) throws IOException;

    int selectCipherSuite(int[] offeredCipherSuites) throws IOException;

    short selectCompressionMethod(short[] offeredCompressionMethods) throws IOException;

    void notifySecureRenegotiation(boolean secureNegotiation) throws IOException;

    // Hashtables are (Integer -> byte[])
    Hashtable processClientExtensions(Hashtable serverExtensions) throws IOException;

    TlsCredentials getCredentials() throws IOException;

    TlsKeyExchange getKeyExchange() throws IOException;

    CertificateRequest getCertificateRequest();

    TlsCompression getCompression() throws IOException;

    TlsCipher getCipher() throws IOException;
}

Add throws IOException to getCredentials


package org.tinylog.impl.format;

import org.junit.jupiter.api.Test;
import org.tinylog.impl.LogEntry;
import org.tinylog.impl.test.LogEntryBuilder;
import org.tinylog.impl.test.PlaceholderRenderer;

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

class ClassPlaceholderTest {

	/**
	 * Verifies that the source class name of a log entry will be output, if set.
	 */
	@Test
	void renderWithClassName() {
		PlaceholderRenderer renderer = new PlaceholderRenderer(new ClassPlaceholder());
		LogEntry logEntry = new LogEntryBuilder().className("foo.MyClass").create();
		assertThat(renderer.render(logEntry)).isEqualTo("foo.MyClass");
	}

	/**
	 * Verifies that "<unknown>" will be output, if the class name is not set.
	 */
	@Test
	void renderWithoutClassName() {
		PlaceholderRenderer renderer = new PlaceholderRenderer(new ClassPlaceholder());
		LogEntry logEntry = new LogEntryBuilder().create();
		assertThat(renderer.render(logEntry)).isEqualTo("<unknown>");
	}

}

package org.tinylog.impl.format;

import org.junit.jupiter.api.Test;
import org.tinylog.impl.LogEntry;
import org.tinylog.impl.test.LogEntryBuilder;
import org.tinylog.impl.test.PlaceholderRenderer;

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

class ClassPlaceholderTest {

	/**
	 * Verifies that the source class name of a log entry will be output, if set.
	 */
	@Test
	void renderWithClassName() {
		PlaceholderRenderer renderer = new PlaceholderRenderer(new ClassPlaceholder());
		LogEntry logEntry = new LogEntryBuilder().className("foo.MyClass").create();
		assertThat(renderer.render(logEntry)).isEqualTo("foo.MyClass");
	}

	/**
	 * Verifies that {@code <unknown>} will be output, if the class name is not set.
	 */
	@Test
	void renderWithoutClassName() {
		PlaceholderRenderer renderer = new PlaceholderRenderer(new ClassPlaceholder());
		LogEntry logEntry = new LogEntryBuilder().create();
		assertThat(renderer.render(logEntry)).isEqualTo("<unknown>");
	}

}

Update Javadoc in class placeholder test


package com.simperium.test;

import com.simperium.client.Bucket;
import com.simperium.client.ChannelProvider;

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

public class MockChannelProvider implements ChannelProvider {

    public List<String> logs = new ArrayList<String>();

    @Override
    public MockChannel buildChannel(Bucket bucket) {
        return new MockChannel(bucket);
    }

    @Override
    public void log(int level, CharSequence message) {
        // noop
        logs.add(message.toString());
    }

    @Override
    public int getLogLevel() {
        return ChannelProvider.LOG_DISABLED;
    }

    public String getLastLog() {
        if (logs.size() > 0) {
            return logs.get(logs.size()-1);
        }
        return null;
    }

}

package com.simperium.test;

import com.simperium.client.Bucket;
import com.simperium.client.ChannelProvider;

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

public class MockChannelProvider implements ChannelProvider {

    public List<String> logs = new ArrayList<String>();

    @Override
    public MockChannel buildChannel(Bucket bucket) {
        return new MockChannel(bucket);
    }

    @Override
    public void log(int level, CharSequence message) {
        // noop
        logs.add(message.toString());
    }

    @Override
    public int getLogLevel() {
        return ChannelProvider.LOG_DISABLED;
    }

    @Override
    public void addHeartbeatListener(HeartbeatListener listener) {
    }

    public String getLastLog() {
        if (logs.size() > 0) {
            return logs.get(logs.size()-1);
        }
        return null;
    }

}

Add heartbeat listener to mock channel provider class


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

import java.io.FileInputStream;
import java.util.Properties;

import org.apache.logging.log4j.util.PropertiesUtil;
import org.junit.Test;

import static org.junit.Assert.*;

/**
 *
 */
public class PropertiesUtilTest {

    @Test
    public void testSubset() throws Exception {
        Properties props = new Properties();
        props.load(new FileInputStream("target/test-classes/log4j2-properties.properties"));
        Properties subset = PropertiesUtil.extractSubset(props, "appender.Stdout.filter.marker");
        assertNotNull("No subset returned", subset);
        assertTrue("Incorrect number of items. Expected 4, actual " + subset.size(), subset.size() == 4);
        assertTrue("Missing property", subset.containsKey("type"));
    }
}

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

import java.util.Properties;

import org.apache.logging.log4j.util.PropertiesUtil;
import org.junit.Test;

import static org.junit.Assert.*;

/**
 *
 */
public class PropertiesUtilTest {

    @Test
    public void testSubset() throws Exception {
        Properties props = new Properties();
        props.load(ClassLoader.getSystemResourceAsStream("log4j2-properties.properties"));
        Properties subset = PropertiesUtil.extractSubset(props, "appender.Stdout.filter.marker");
        assertNotNull("No subset returned", subset);
        assertTrue("Incorrect number of items. Expected 4, actual " + subset.size(), subset.size() == 4);
        assertTrue("Missing property", subset.containsKey("type"));
    }
}

Use class loader resource in test.


package leetcode;

import java.util.Arrays;

/**
 * https://leetcode.com/problems/product-of-array-except-self/
 */
public class Problem238 {
   public int[] productExceptSelf(int[] nums) {
       int totalWithoutZero = 1;
       int total = 1;
       int nZero = 0;
       for (int num : nums) {
           if (num != 0) {
               totalWithoutZero *= num;
           } else {
               nZero++;
           }
           total *= num;
       }
       int[] output = new int[nums.length];
       for (int i = 0; i < nums.length; i++) {
           if (nZero > 1) {
               output[i] = 0;
           } else if (nZero == 1) {
               if (nums[i] == 0) {
                   output[i] = totalWithoutZero;
               } else {
                   output[i] = 0;
               }
           } else {
               output[i] = total / nums[i];
           }
       }
       return output;
   }

   public static void main(String[] args) {
       Problem238 prob = new Problem238();
       System.out.println(Arrays.toString(prob.productExceptSelf(new int[]{1, 2, 3, 4}))); // [24, 12, 8, 6]
       System.out.println(Arrays.toString(prob.productExceptSelf(new int[]{0, 0}))); // [0, 0]
       System.out.println(Arrays.toString(prob.productExceptSelf(new int[]{0, 2, 3}))); // [6, 0, 0]
   }
}

package leetcode;

/**
 * https://leetcode.com/problems/product-of-array-except-self/
 */
public class Problem238 {
   public int[] productExceptSelf(int[] nums) {
       int[] output = new int[nums.length];
       int x = 1;
       // forward
       for (int i = 0; i < nums.length; i++) {
           x *= nums[i];
           output[i] = x;
       }
       x = 1;
       int backward = 1;
       for (int i = nums.length-1; i >= 0; i--) {
           if (i != 0) {
               x = output[i-1] * backward;
               backward *= nums[i];
           } else {
               x = backward;
           }
           output[i] = x;
       }
       return output;
   }
}

Solve problem 238 without using division


package it.unibz.inf.ontop.model.type.impl;

import com.google.common.collect.ImmutableMap;
import com.google.inject.assistedinject.Assisted;
import com.google.inject.assistedinject.AssistedInject;
import it.unibz.inf.ontop.model.type.DBTermType;
import it.unibz.inf.ontop.model.type.TermType;
import it.unibz.inf.ontop.model.type.TypeFactory;

import java.util.Map;

public class H2SQLDBTypeFactory extends DefaultSQLDBTypeFactory {

    private static final String BOOL_STR = "BOOL";

    @AssistedInject
    private H2SQLDBTypeFactory(@Assisted TermType rootTermType, @Assisted TypeFactory typeFactory) {
        super(createH2SQLTypeMap(rootTermType, typeFactory), createH2SQLCodeMap());
    }

    private static Map<String, DBTermType> createH2SQLTypeMap(TermType rootTermType, TypeFactory typeFactory) {
        Map<String, DBTermType> map = createDefaultSQLTypeMap(rootTermType, typeFactory);
        // TODO: add the other alias BIT?
        map.put(BOOL_STR, new BooleanDBTermType(BOOL_STR, rootTermType.getAncestry(), typeFactory.getXsdBooleanDatatype()));
        return map;
    }

    private static ImmutableMap<DefaultTypeCode, String> createH2SQLCodeMap() {
        Map<DefaultTypeCode, String> map = createDefaultSQLCodeMap();
        map.put(DefaultTypeCode.BOOLEAN, BOOL_STR);
        return ImmutableMap.copyOf(map);
    }
}

package it.unibz.inf.ontop.model.type.impl;

import com.google.common.collect.ImmutableMap;
import com.google.inject.assistedinject.Assisted;
import com.google.inject.assistedinject.AssistedInject;
import it.unibz.inf.ontop.model.type.DBTermType;
import it.unibz.inf.ontop.model.type.TermType;
import it.unibz.inf.ontop.model.type.TypeFactory;

import java.util.Map;

public class H2SQLDBTypeFactory extends DefaultSQLDBTypeFactory {

    @AssistedInject
    private H2SQLDBTypeFactory(@Assisted TermType rootTermType, @Assisted TypeFactory typeFactory) {
        super(createH2SQLTypeMap(rootTermType, typeFactory), createH2SQLCodeMap());
    }

    private static Map<String, DBTermType> createH2SQLTypeMap(TermType rootTermType, TypeFactory typeFactory) {
        Map<String, DBTermType> map = createDefaultSQLTypeMap(rootTermType, typeFactory);
        return map;
    }

    private static ImmutableMap<DefaultTypeCode, String> createH2SQLCodeMap() {
        Map<DefaultTypeCode, String> map = createDefaultSQLCodeMap();
        return ImmutableMap.copyOf(map);
    }
}

Use BOOLEAN as default H2 boolean type.


import java.util.*;

class PathDElement {
  char type;
  ArrayList<Float> values;
  PathDElement() {
    values = new ArrayList<Float>();
  }
}

class PathDParser {

  // Split a string describing the segments of a path into
  void partition( String path, ArrayList<PathDElement> pathElements ) {
    String delimiters = "(?=m|l|c|v|h|q|z|M|L|C|V|H|Q|Z)";
    String[] tokens = path.split(delimiters);

    pathElements.clear();

    for( String t: tokens ) {
      PathDElement elem = new PathDElement();
      elem.type = t.charAt(0);
      // Split
      String[] values = t.substring(1).replaceAll("^[,\\s]+", "").split("[,\\s]+");
      ArrayList<String> stringValues = new ArrayList<String>(Arrays.asList(values));
      System.out.println(elem.type);
      for( String s: stringValues ) {
        System.out.println(s);
        elem.values.add(Float.parseFloat(s));
      }
      System.out.println("size = " + elem.values.size());
    }

  }

} // class PathDParser

import java.util.*;

class PathDElement {
  char type;
  ArrayList<Float> values;
  PathDElement() {
    values = new ArrayList<Float>();
  }
}

class PathDParser {

  // Split a string describing the segments of a path into
  void partition( String path, ArrayList<PathDElement> pathElements ) {
    String delimiters = "(?=m|l|c|v|h|q|z|M|L|C|V|H|Q|Z)";
    String[] tokens = path.split(delimiters);

    pathElements.clear();

    for( String t: tokens ) {
      PathDElement elem = new PathDElement();
      elem.type = t.charAt(0);

      boolean isRelative = Character.isLowerCase(elem.type);

      // Split
      String[] values = t.substring(1).replaceAll("^[,\\s]+", "").split("[,\\s]+");
      ArrayList<String> stringValues = new ArrayList<String>(Arrays.asList(values));
      System.out.println(elem.type);
      for( String s: stringValues ) {
        System.out.println(s);
        elem.values.add(Float.parseFloat(s));
      }
      System.out.println("size = " + elem.values.size());

    }

  }

} // class PathDParser

Determine whether coordinates are relative


package org.cyclops.commoncapabilities.capability.wrench;

import net.minecraft.world.IWorldNameable;
import net.minecraftforge.common.capabilities.Capability;
import net.minecraftforge.common.capabilities.CapabilityInject;
import org.cyclops.commoncapabilities.CommonCapabilities;
import org.cyclops.commoncapabilities.api.capability.wrench.DefaultWrench;
import org.cyclops.commoncapabilities.api.capability.wrench.IWrench;
import org.cyclops.cyclopscore.config.extendedconfig.CapabilityConfig;
import org.cyclops.cyclopscore.modcompat.capabilities.DefaultCapabilityStorage;

/**
 * Config for the wrench capability.
 * @author rubensworks
 *
 */
public class WrenchConfig extends CapabilityConfig<IWrench> {

    /**
     * The unique instance.
     */
    public static WrenchConfig _instance;

    @CapabilityInject(IWorldNameable.class)
    public static Capability<IWrench> CAPABILITY = null;

    /**
     * Make a new instance.
     */
    public WrenchConfig() {
        super(
                CommonCapabilities._instance,
                true,
                "wrench",
                "Indicates if something is a wrench",
                IWrench.class,
                new DefaultCapabilityStorage<IWrench>(),
                DefaultWrench.class
        );
    }
}

package org.cyclops.commoncapabilities.capability.wrench;

import net.minecraftforge.common.capabilities.Capability;
import net.minecraftforge.common.capabilities.CapabilityInject;
import org.cyclops.commoncapabilities.CommonCapabilities;
import org.cyclops.commoncapabilities.api.capability.wrench.DefaultWrench;
import org.cyclops.commoncapabilities.api.capability.wrench.IWrench;
import org.cyclops.cyclopscore.config.extendedconfig.CapabilityConfig;
import org.cyclops.cyclopscore.modcompat.capabilities.DefaultCapabilityStorage;

/**
 * Config for the wrench capability.
 * @author rubensworks
 *
 */
public class WrenchConfig extends CapabilityConfig<IWrench> {

    /**
     * The unique instance.
     */
    public static WrenchConfig _instance;

    @CapabilityInject(IWrench.class)
    public static Capability<IWrench> CAPABILITY = null;

    /**
     * Make a new instance.
     */
    public WrenchConfig() {
        super(
                CommonCapabilities._instance,
                true,
                "wrench",
                "Indicates if something is a wrench",
                IWrench.class,
                new DefaultCapabilityStorage<IWrench>(),
                DefaultWrench.class
        );
    }
}

Fix wrench capability failing to register


package com.sleekbyte.tailor.listeners;

import com.sleekbyte.tailor.antlr.SwiftBaseListener;
import com.sleekbyte.tailor.antlr.SwiftParser;
import com.sleekbyte.tailor.common.Location;
import com.sleekbyte.tailor.common.Messages;
import com.sleekbyte.tailor.output.Printer;
import com.sleekbyte.tailor.utils.ListenerUtil;
import org.antlr.v4.runtime.tree.ParseTree;
import org.antlr.v4.runtime.tree.TerminalNodeImpl;

public class ForceTypeCastListener extends SwiftBaseListener {

    private Printer printer;

    public ForceTypeCastListener(Printer printer) {
        this.printer = printer;
    }

    @Override
    public void enterTypeCastingOperator(SwiftParser.TypeCastingOperatorContext ctx) {
        verifyForceTypeCasting(ctx);
    }

    private void verifyForceTypeCasting(SwiftParser.TypeCastingOperatorContext ctx) {
        ParseTree secondChild = ctx.getChild(1);
        if (secondChild.getText().equals("!")) {
            // TODO: use util method that returns location of parse tree once {} check gets merged into master
            Location exclamationLocation = ListenerUtil.getTokenLocation(((TerminalNodeImpl) secondChild).getSymbol());
            printer.warn(Messages.FORCE_CAST, exclamationLocation);
        }
    }
}

package com.sleekbyte.tailor.listeners;

import com.sleekbyte.tailor.antlr.SwiftBaseListener;
import com.sleekbyte.tailor.antlr.SwiftParser;
import com.sleekbyte.tailor.common.Location;
import com.sleekbyte.tailor.common.Messages;
import com.sleekbyte.tailor.output.Printer;
import com.sleekbyte.tailor.utils.ListenerUtil;
import org.antlr.v4.runtime.tree.ParseTree;

public class ForceTypeCastListener extends SwiftBaseListener {

    private Printer printer;

    public ForceTypeCastListener(Printer printer) {
        this.printer = printer;
    }

    @Override
    public void enterTypeCastingOperator(SwiftParser.TypeCastingOperatorContext ctx) {
        verifyForceTypeCasting(ctx);
    }

    private void verifyForceTypeCasting(SwiftParser.TypeCastingOperatorContext ctx) {
        ParseTree secondChild = ctx.getChild(1);
        if (secondChild.getText().equals("!")) {
            Location exclamationLocation = ListenerUtil.getParseTreeStartLocation(secondChild);
            printer.warn(Messages.FORCE_CAST, exclamationLocation);
        }
    }
}

Address TODO in force type cast method


package uk.ac.abdn.foodsafety.provenance;

import java.util.Observable;

import uk.ac.abdn.foodsafety.common.Logging;
import eu.larkc.csparql.common.RDFTable;
import eu.larkc.csparql.core.ResultFormatter;

class FoodSafetyFormatter extends ResultFormatter {
    private final String queryName;

    FoodSafetyFormatter(final String queryName) {
        this.queryName = queryName;
    }

    /**
     * Called when C-Sparql emits a window.
     */
    @Override
    public void update(final Observable ignored, final Object rdfTableUntyped) {
        final RDFTable rdfTable = (RDFTable) rdfTableUntyped;
        Logging.info(String.format("Query %s emitted %d triples", this.queryName, rdfTable.size()));
    }

    public void addSparql(final String name, final String content) {
        // TODO Auto-generated method stub

    }

    public void setOwl(final String content) {
        // TODO Auto-generated method stub

    }
}

package uk.ac.abdn.foodsafety.provenance;

import java.util.ArrayList;
import java.util.EnumMap;
import java.util.List;
import java.util.Observable;

import uk.ac.abdn.foodsafety.common.Logging;
import eu.larkc.csparql.common.RDFTable;
import eu.larkc.csparql.core.ResultFormatter;

class FoodSafetyFormatter extends ResultFormatter {
    /** Name picked up from directory - used for logging */
    private final String queryName;

    private EnumMap<Stage, List<String>> sparqlUpdateQueries =
            new EnumMap<Stage, List<String>>(Stage.class);

    FoodSafetyFormatter(final String queryName) {
        this.queryName = queryName;
        //Initialize SPARQL update query collections
        for (Stage s : Stage.values()) {
            this.sparqlUpdateQueries.put(s, new ArrayList<String>());
        }
    }

    /**
     * Called when C-Sparql emits a window.
     */
    @Override
    public void update(final Observable ignored, final Object rdfTableUntyped) {
        final RDFTable rdfTable = (RDFTable) rdfTableUntyped;
        Logging.info(String.format("Query %s emitted %d triples", this.queryName, rdfTable.size()));
    }

    public void addSparql(final String name, final String content) {
        this.sparqlUpdateQueries.get(Stage.valueOf(name.toUpperCase())).add(content);
    }

    public void setOwl(final String content) {
        // TODO Auto-generated method stub

    }

    private enum Stage {
      COLDSTART,
      WARM;
    };
}

Store the SPARQL update queries


package com.github.aureliano.edocs.app.gui;

import java.awt.BorderLayout;
import java.awt.Dimension;

import javax.swing.JFrame;
import javax.swing.JPanel;

import com.github.aureliano.edocs.app.gui.menu.MenuBar;

public class AppFrame extends JFrame {

	private static final long serialVersionUID = 7618501026967569839L;

	private TabbedPane tabbedPane;

	public AppFrame() {
		this.buildGui();
	}

	private void buildGui() {
		super.setTitle("e-Docs");
		super.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

		JPanel panel = new JPanel(new BorderLayout());
		panel.setOpaque(true);
		panel.add(new VerticalToolBar(), BorderLayout.WEST);

		this.tabbedPane = new TabbedPane();
		panel.add(this.tabbedPane, BorderLayout.CENTER);

		super.setContentPane(panel);
		super.setJMenuBar(new MenuBar());
	}

	public void showFrame() {
		super.pack();
		super.setVisible(true);
		super.setSize(new Dimension(500, 500));
	}
}

package com.github.aureliano.edocs.app.gui;

import java.awt.BorderLayout;
import java.awt.Dimension;

import javax.swing.JFrame;
import javax.swing.JPanel;

import com.github.aureliano.edocs.app.gui.menu.MenuBar;

public class AppFrame extends JFrame {

	private static final long serialVersionUID = 7618501026967569839L;

	private TabbedPane tabbedPane;

	public AppFrame() {
		this.buildGui();
	}

	private void buildGui() {
		super.setTitle("e-Docs");
		super.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

		JPanel panel = new JPanel(new BorderLayout());
		panel.setOpaque(true);
		panel.add(new VerticalToolBar(), BorderLayout.WEST);

		this.tabbedPane = new TabbedPane();
		panel.add(this.tabbedPane, BorderLayout.CENTER);

		super.setContentPane(panel);
		super.setJMenuBar(new MenuBar());
	}

	public void showFrame() {
		super.pack();
		super.setSize(new Dimension(500, 500));
		super.setLocationRelativeTo(null);
		super.setVisible(true);
	}
}

Set main frame default location.


package entity;

import java.util.HashSet;
import java.util.Set;

/**
 * Created by Jakob Pfeiffer on 19.10.17.
 */
public abstract class BaseEntity implements Comparable<BaseEntity> {
	private long identity;
	private int version;
	private long creationTimestamp;
	Set<Message> messagesCaused;

	public BaseEntity() {
		this.version = 1;
		this.messagesCaused = new HashSet<>();
		this.creationTimestamp = System.currentTimeMillis();
	}

	public long getIdentity() {
		return identity;
	}

	public int getVersion() {
		return version;
	}

	public void setVersion(int version) {
		this.version = version;
	}

	public long getCreationTimestamp() {
		return creationTimestamp;
	}

	public Set<Message> getMessagesCaused() {
		return messagesCaused;
	}

	@Override
	public int compareTo(BaseEntity o) {
		return this.identity < ((BaseEntity) o).identity ? -1 : this.identity > ((BaseEntity) o).identity ? +1 : 0;
	}
}

package entity;

import java.util.HashSet;
import java.util.Set;

/**
 * Created by Jakob Pfeiffer on 19.10.17.
 */
public abstract class BaseEntity implements Comparable<BaseEntity> {
	private long identity;
	private int version;
	private long creationTimestamp;
	Set<Message> messagesCaused;

	public BaseEntity() {
		this.version = 1;
		this.messagesCaused = new HashSet<>();
		this.creationTimestamp = System.currentTimeMillis();
	}

	public long getIdentity() {
		return identity;
	}

	public int getVersion() {
		return version;
	}

	public void setVersion(int version) {
		this.version = version;
	}

	public long getCreationTimestamp() {
		return creationTimestamp;
	}

	public Set<Message> getMessagesCaused() {
		return messagesCaused;
	}

	@Override
	public int compareTo(BaseEntity o) {
		if (this.identity == o.identity) {
			return 0;
		}
		return this.identity < o.identity ? -1 : +1;
	}
}

Rewrite ternary operator. Remove unnecessary casting of the object to compare


package us.myles.ViaVersion.api.rewriters;

import us.myles.ViaVersion.api.protocol.ClientboundPacketType;
import us.myles.ViaVersion.api.protocol.Protocol;
import us.myles.ViaVersion.api.remapper.PacketRemapper;
import us.myles.ViaVersion.api.type.Type;

public class SoundRewriter {
    protected final Protocol protocol;
    protected final IdRewriteFunction idRewriter;

    public SoundRewriter(Protocol protocol) {
        this.protocol = protocol;
        this.idRewriter = id -> protocol.getMappingData().getSoundMappings().getNewId(id);
    }

    public SoundRewriter(Protocol protocol, IdRewriteFunction idRewriter) {
        this.protocol = protocol;
        this.idRewriter = idRewriter;
    }

    // The same for entity sound
    public void registerSound(ClientboundPacketType packetType) {
        protocol.registerOutgoing(packetType, new PacketRemapper() {
            @Override
            public void registerMap() {
                map(Type.VAR_INT); // Sound Id
                handler(wrapper -> {
                    int soundId = wrapper.get(Type.VAR_INT, 0);
                    int mappedId = idRewriter.rewrite(soundId);
                    if (mappedId == -1) {
                        wrapper.cancel();
                    } else if (soundId != mappedId) {
                        wrapper.set(Type.VAR_INT, 0, mappedId);
                    }
                });
            }
        });
    }
}

package us.myles.ViaVersion.api.rewriters;

import us.myles.ViaVersion.api.protocol.ClientboundPacketType;
import us.myles.ViaVersion.api.protocol.Protocol;
import us.myles.ViaVersion.api.remapper.PacketHandler;
import us.myles.ViaVersion.api.remapper.PacketRemapper;
import us.myles.ViaVersion.api.type.Type;

public class SoundRewriter {
    protected final Protocol protocol;
    protected final IdRewriteFunction idRewriter;

    public SoundRewriter(Protocol protocol) {
        this.protocol = protocol;
        this.idRewriter = id -> protocol.getMappingData().getSoundMappings().getNewId(id);
    }

    public SoundRewriter(Protocol protocol, IdRewriteFunction idRewriter) {
        this.protocol = protocol;
        this.idRewriter = idRewriter;
    }

    // The same for entity sound
    public void registerSound(ClientboundPacketType packetType) {
        protocol.registerOutgoing(packetType, new PacketRemapper() {
            @Override
            public void registerMap() {
                map(Type.VAR_INT); // Sound Id
                handler(getSoundHandler());
            }
        });
    }

    public PacketHandler getSoundHandler() {
        return wrapper -> {
            int soundId = wrapper.get(Type.VAR_INT, 0);
            int mappedId = idRewriter.rewrite(soundId);
            if (mappedId == -1) {
                wrapper.cancel();
            } else if (soundId != mappedId) {
                wrapper.set(Type.VAR_INT, 0, mappedId);
            }
        };
    }
}

Add method to get handler in sound rewriter


package de.craften.plugins.educraft.luaapi.functions;

import de.craften.plugins.educraft.luaapi.EduCraftApiFunction;
import org.bukkit.Location;
import org.luaj.vm2.LuaValue;
import org.luaj.vm2.Varargs;

/**
 * Lua API function to move one block forward.
 */
public class MoveForwardFunction extends EduCraftApiFunction {
    @Override
    public Varargs execute(Varargs varargs) {
        Location targetLocation = getApi().getStationaryBehavior().getLocation().clone().add(getApi().getDirection());

        if (!targetLocation.getBlock().getType().isSolid()) {
            getApi().getStationaryBehavior().setLocation(targetLocation);
        }

        return LuaValue.NIL;
    }
}

package de.craften.plugins.educraft.luaapi.functions;

import de.craften.plugins.educraft.luaapi.EduCraftApiFunction;
import org.bukkit.Location;
import org.bukkit.block.BlockFace;
import org.luaj.vm2.LuaValue;
import org.luaj.vm2.Varargs;

/**
 * Lua API function to move one block forward.
 */
public class MoveForwardFunction extends EduCraftApiFunction {
    @Override
    public Varargs execute(Varargs varargs) {
        Location targetLocation = getApi().getStationaryBehavior().getLocation().clone().add(getApi().getDirection());

        if (!targetLocation.getBlock().getType().isSolid()
                && !targetLocation.getBlock().getRelative(BlockFace.UP).getType().isSolid()) {
            getApi().getStationaryBehavior().setLocation(targetLocation);
        }

        return LuaValue.NIL;
    }
}

Check if two blocks are non-solid before moving forward.


package org.adaptlab.chpir.android.survey.Receivers;

import org.adaptlab.chpir.android.survey.SurveyActivity;
import org.adaptlab.chpir.android.survey.SurveyFragment;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;

public class SurveyLaunchReceiver extends BroadcastReceiver {
    private static final String TAG = "SurveyLaunchReceiver";

    @Override
    public void onReceive(Context context, Intent intent) {
        Long instrumentId = intent.getLongExtra(SurveyFragment.EXTRA_INSTRUMENT_ID, -1);
        Log.i(TAG, "Received broadcast to launch survey for instrument with remote id " + instrumentId);
        Intent i = new Intent(context, SurveyActivity.class);
        i.putExtra(SurveyFragment.EXTRA_INSTRUMENT_ID, instrumentId);
        i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(i);
    }
}

package org.adaptlab.chpir.android.survey.Receivers;

import org.adaptlab.chpir.android.survey.SurveyActivity;
import org.adaptlab.chpir.android.survey.SurveyFragment;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;

public class SurveyLaunchReceiver extends BroadcastReceiver {
    private static final String TAG = "SurveyLaunchReceiver";

    @Override
    public void onReceive(Context context, Intent intent) {
        Long instrumentId = intent.getLongExtra(SurveyFragment.EXTRA_INSTRUMENT_ID, -1);
        Log.i(TAG, "Received broadcast to launch survey for instrument with remote id " + instrumentId);
        if (instrumentId > -1) {
            Intent i = new Intent(context, SurveyActivity.class);
            i.putExtra(SurveyFragment.EXTRA_INSTRUMENT_ID, instrumentId);
            i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            context.startActivity(i);
        }
    }
}

Fix instrument does not exist for id bug in survey launch receiver


package com.vikashkothary.life.data.local;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

import javax.inject.Inject;
import javax.inject.Singleton;

import com.vikashkothary.life.injection.ApplicationContext;

@Singleton
public class DbOpenHelper extends SQLiteOpenHelper {

    public static final String DATABASE_NAME = "ribots.db";
    public static final int DATABASE_VERSION = 2;

    @Inject
    public DbOpenHelper(@ApplicationContext Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    @Override
    public void onConfigure(SQLiteDatabase db) {
        super.onConfigure(db);
        //Uncomment line below if you want to enable foreign keys
        //db.execSQL("PRAGMA foreign_keys=ON;");
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.beginTransaction();
        try {
            db.execSQL(Db.RibotProfileTable.CREATE);
            //Add other tables here
            db.setTransactionSuccessful();
        } finally {
            db.endTransaction();
        }
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { }

}

package com.vikashkothary.life.data.local;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

import javax.inject.Inject;
import javax.inject.Singleton;

import com.vikashkothary.life.injection.ApplicationContext;

@Singleton
public class DbOpenHelper extends SQLiteOpenHelper {

    public static final String DATABASE_NAME = "ribots.db";
    public static final int DATABASE_VERSION = 1;

    @Inject
    public DbOpenHelper(@ApplicationContext Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    @Override
    public void onConfigure(SQLiteDatabase db) {
        super.onConfigure(db);
        //Uncomment line below if you want to enable foreign keys
        //db.execSQL("PRAGMA foreign_keys=ON;");
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.beginTransaction();
        try {
            db.execSQL(Db.RibotProfileTable.CREATE);
            //Add other tables here
            db.setTransactionSuccessful();
        } finally {
            db.endTransaction();
        }
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { }

}

Change Ribots database version from 2 to 1


package edu.northwestern.bioinformatics.studycalendar.dao;

import edu.northwestern.bioinformatics.studycalendar.domain.Source;

import java.util.List;

public class SourceDao extends StudyCalendarMutableDomainObjectDao<Source> {
    public Class<Source> domainClass() {
        return Source.class;
    }

    public List<Source> getAll()  {
        return getHibernateTemplate().find("from Source order by name");
    }

    public Source getByName(String name) {
        List<Source> sources = getHibernateTemplate().find("from Source where name = ?", name);
        if (!sources.isEmpty()) {
            return sources.get(0);
        }
        return null;
    }
}

package edu.northwestern.bioinformatics.studycalendar.dao;

import edu.northwestern.bioinformatics.studycalendar.domain.Source;

import java.util.List;

public class SourceDao extends StudyCalendarMutableDomainObjectDao<Source> {
    public Class<Source> domainClass() {
        return Source.class;
    }

    /**
     * Finds all the activity sources available
     *
     * @return      a list of all the available activity sources
     */
    public List<Source> getAll()  {
        return getHibernateTemplate().find("from Source order by name");
    }

    /**
     * Finds all the actiivty sources for the given activity source name
     *
     * @param  name the name of the activity source to search for
     * @return      the source that was found for the given activity source name
     */
    public Source getByName(String name) {
        List<Source> sources = getHibernateTemplate().find("from Source where name = ?", name);
        if (!sources.isEmpty()) {
            return sources.get(0);
        }
        return null;
    }
}

Add javadoc to source dao.


package com.indeed.proctor.builder.maven;

import com.indeed.proctor.builder.LocalProctorBuilder;
import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugins.annotations.Mojo;
import org.apache.maven.plugins.annotations.Parameter;

import java.io.File;
import java.io.FileWriter;
import java.io.Writer;

@Mojo(name = "generate-matrix")
public class BuilderMojo extends AbstractMojo {

    @Parameter(property = "topDirectory", defaultValue = "${basedir}/src/main/proctor-data")
    private File topDirectory;

    @Parameter(property = "outputFile", defaultValue = "${project.build.directory}/proctor-test-matrix.json")
    private File outputFile;

    @Parameter(property = "author", defaultValue = "")
    private String author;

    @Parameter(property = "version", defaultValue = "-1")
    private String version;

    @Override
    public final void execute() throws MojoExecutionException {
        if(!topDirectory.exists()) {
            return;
        }
        try {
            // try to make sure path exists
            outputFile.getParentFile().mkdirs();

            Writer w = new FileWriter(outputFile);
            new LocalProctorBuilder(topDirectory, w, "".equals(author) ? author : null, version).execute();
            w.close();
        } catch (Exception e) {
            throw new MojoExecutionException("Failure during builder execution", e);
        }
    }
}

package com.indeed.proctor.builder.maven;

import com.indeed.proctor.builder.LocalProctorBuilder;
import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugins.annotations.Mojo;
import org.apache.maven.plugins.annotations.Parameter;

import java.io.File;
import java.io.FileWriter;
import java.io.Writer;

@Mojo(name = "generate-matrix")
public class BuilderMojo extends AbstractMojo {

    @Parameter(property = "topDirectory", defaultValue = "${basedir}/src/main/proctor-data")
    private File topDirectory;

    @Parameter(property = "outputFile", defaultValue = "${project.build.directory}/proctor-test-matrix.json")
    private File outputFile;

    @Parameter(property = "author", defaultValue = "")
    private String author;

    @Parameter(property = "version", defaultValue = "-1")
    private String version;

    @Override
    public final void execute() throws MojoExecutionException {
        if(!topDirectory.exists()) {
            return;
        }
        try {
            // try to make sure path exists
            outputFile.getParentFile().mkdirs();

            Writer w = new FileWriter(outputFile);
            new LocalProctorBuilder(topDirectory, w, "".equals(author) ? null : author, version).execute();
            w.close();
        } catch (Exception e) {
            throw new MojoExecutionException("Failure during builder execution", e);
        }
    }
}

Fix empty author assignment inline if


package to.etc.domui.injector;

import org.eclipse.jdt.annotation.Nullable;
import to.etc.domui.dom.html.AbstractPage;
import to.etc.util.PropertyInfo;

/**
 * @author Frits Jalvingh
 * Created on 20-12-18.
 */
public interface ITypedValueAccessChecker<T> {
	boolean isAccessAllowed(PropertyInfo info, AbstractPage page, @Nullable T value) throws Exception;
}

package to.etc.domui.injector;

import org.eclipse.jdt.annotation.NonNull;
import to.etc.domui.dom.html.AbstractPage;
import to.etc.util.PropertyInfo;

/**
 * @author Frits Jalvingh
 * Created on 20-12-18.
 */
public interface ITypedValueAccessChecker<T> {
	boolean isAccessAllowed(PropertyInfo info, AbstractPage page, @NonNull T value) throws Exception;
}

Add injected values check infra, and add checkcs for product and ProductChange.


package com.tozny.sdk.realm.methods.email_challenge;

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.tozny.sdk.ToznyApiRequest;

import javax.annotation.Nullable;

/**
 * Constructs a Request for invoking the "realm.email_challenge" method.
 */
@JsonAutoDetect(getterVisibility = JsonAutoDetect.Visibility.NONE)
public class EmailChallengeRequest implements ToznyApiRequest {
    @JsonProperty(required=true) private String method = "realm.email_challenge";
    @JsonProperty(required=true) private String destination;
    @JsonProperty private String callback;
    @JsonProperty private String hostname;
    @JsonProperty private Boolean send;

    public EmailChallengeRequest(String destination, @Nullable String callback, @Nullable String hostname, @Nullable Boolean send) {
        this.destination = destination;
        this.callback = callback;
        this.hostname = hostname;

        if (send == null) {
            this.send = true;
        } else {
            this.send = send;
        }
    }

    public String getMethod() {
        return method;
    }

    public String getDestination() {
        return destination;
    }

    @Nullable
    public String getCallback() {
        return callback;
    }

    @Nullable
    public String getHostname() {
        return hostname;
    }

    @Nullable
    public Boolean getSend() {
        return send;
    }
}

package com.tozny.sdk.realm.methods.email_challenge;

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.tozny.sdk.ToznyApiRequest;

import javax.annotation.Nullable;

/**
 * Constructs a Request for invoking the "realm.email_challenge" method.
 */
@JsonAutoDetect(getterVisibility = JsonAutoDetect.Visibility.NONE)
public class EmailChallengeRequest implements ToznyApiRequest {
    @JsonProperty(required=true) private String method = "realm.email_challenge";
    @JsonProperty(required=true) private String destination;
    @JsonProperty private String callback;
    @JsonProperty private String hostname;
    @JsonProperty private String send;

    public EmailChallengeRequest(String destination, @Nullable String callback, @Nullable String hostname, @Nullable Boolean send) {
        this.destination = destination;
        this.callback = callback;
        this.hostname = hostname;

        if (send == null) {
            this.send = "yes";
        } else {
            this.send = "no";
        }
    }

    public String getMethod() {
        return method;
    }

    public String getDestination() {
        return destination;
    }

    @Nullable
    public String getCallback() {
        return callback;
    }

    @Nullable
    public String getHostname() {
        return hostname;
    }

    @Nullable
    public Boolean getSend() {
        return send.equals("yes");
    }
}

Update the 'send' parameter to work with the actual API spec


package com.twitter.intellij.pants.service.project.wizard;

import com.intellij.openapi.externalSystem.service.project.wizard.AbstractExternalProjectImportProvider;
import com.intellij.openapi.vfs.VirtualFile;
import com.twitter.intellij.pants.util.PantsConstants;
import com.twitter.intellij.pants.util.PantsUtil;
import org.jetbrains.annotations.Nullable;

public class PantsProjectImportProvider extends AbstractExternalProjectImportProvider {
  public PantsProjectImportProvider(PantsProjectImportBuilder builder) {
    super(builder, PantsConstants.SYSTEM_ID);
  }

  @Override
  protected boolean canImportFromFile(VirtualFile file) {
    return PantsUtil.isBUILDFileName(file.getName());
  }

  @Nullable
  @Override
  public String getFileSample() {
    return "<b>Pants</b> build file (BUILD.*)";
  }
}

package com.twitter.intellij.pants.service.project.wizard;

import com.intellij.ide.util.projectWizard.ModuleWizardStep;
import com.intellij.ide.util.projectWizard.ProjectJdkStep;
import com.intellij.ide.util.projectWizard.WizardContext;
import com.intellij.openapi.externalSystem.service.project.wizard.AbstractExternalProjectImportProvider;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.util.ArrayUtil;
import com.twitter.intellij.pants.util.PantsConstants;
import com.twitter.intellij.pants.util.PantsUtil;
import org.jetbrains.annotations.Nullable;

public class PantsProjectImportProvider extends AbstractExternalProjectImportProvider {
  public PantsProjectImportProvider(PantsProjectImportBuilder builder) {
    super(builder, PantsConstants.SYSTEM_ID);
  }

  @Override
  protected boolean canImportFromFile(VirtualFile file) {
    return PantsUtil.isBUILDFileName(file.getName());
  }

  @Nullable
  @Override
  public String getFileSample() {
    return "<b>Pants</b> build file (BUILD.*)";
  }

  @Override
  public ModuleWizardStep[] createSteps(WizardContext context) {
    return ArrayUtil.append(super.createSteps(context), new ProjectJdkStep(context));
  }
}

Configure JDK while importing a project


package org.opennms.netmgt.model;

import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.Restrictions;
import org.hibernate.type.StringType;

public class OnmsRestrictions {
    private static final StringType STRING_TYPE = new StringType();

    /**
     * Performs an iplike match on the ipAddr column of the current table.
     *
     * @param value iplike match
     * @return SQL restriction for this iplike match
     */
    public static Criterion ipLike(String value) {
        return Restrictions.sqlRestriction("iplike({alias}.ipAddr, ?)", value, STRING_TYPE);
    }
}

/*
 * This file is part of the OpenNMS(R) Application.
 *
 * OpenNMS(R) is Copyright (C) 2006 The OpenNMS Group, Inc.  All rights reserved.
 * OpenNMS(R) is a derivative work, containing both original code, included code and modified
 * code that was published under the GNU General Public License. Copyrights for modified
 * and included code are below.
 *
 * OpenNMS(R) is a registered trademark of The OpenNMS Group, Inc.
 *
 * Copyright (C) 2007 The OpenNMS Group, Inc.  All rights reserved.
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the/m
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
 *
 * For more information contact:
 *      OpenNMS Licensing       <license@opennms.org>
 *      http://www.opennms.org/
 *      http://www.opennms.com/
 */
package org.opennms.netmgt.model;

import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.Restrictions;
import org.hibernate.type.StringType;

/**
 * Provide OpenNMS-specific Hibernate Restrictions.
 *
 * @author DJ Gregor
 */
public class OnmsRestrictions {
    private static final StringType STRING_TYPE = new StringType();

    /**
     * Performs an iplike match on the ipAddr column of the current table.
     *
     * @param value iplike match
     * @return SQL restriction for this iplike match
     */
    public static Criterion ipLike(String value) {
        return Restrictions.sqlRestriction("iplike({alias}.ipAddr, ?)", value, STRING_TYPE);
    }
}

Add copyright and a little bit of javadoc.


package org.jenkins.ci.plugins.jenkinslint.check;

import hudson.slaves.DumbSlave;
import org.junit.Rule;
import org.junit.Test;
import org.jvnet.hudson.test.JenkinsRule;

import static org.junit.Assert.assertTrue;

/**
 * SlaveDescriptionChecker Test Case.
 *
 * @author Victor Martinez
 */
public class SlaveLabelCheckerTestCase {
    private SlaveDescriptionChecker checker = new SlaveDescriptionChecker();

    @Rule public JenkinsRule j = new JenkinsRule();
    @Test public void testDefaultSlave() throws Exception {
        DumbSlave slave = j.createSlave();
        assertTrue(checker.executeCheck(slave));
    }
    @Test public void testEmptySlaveName() throws Exception {
        DumbSlave slave = j.createSlave();
        slave.setNodeName("");
        assertTrue(checker.executeCheck(slave));
    }
    @Test public void testSlaveDescription() throws Exception {
        DumbSlave slave = j.createSlave();
        slave.setNodeName("blablabla");
        assertTrue(checker.executeCheck(slave));
    }
    /**
    @Test public void testControlComment() throws Exception {
        DumbSlave slave = j.createSlave();
        assertFalse(checker.isIgnored(project.getDescription()));
        project.setDescription("#lint:ignore:" + checker.getClass().getSimpleName());
        assertTrue(checker.isIgnored(project.getDescription()));
    }*/
}

package org.jenkins.ci.plugins.jenkinslint.check;

import hudson.model.Node;
import hudson.model.Slave;
import hudson.slaves.DumbSlave;
import hudson.slaves.JNLPLauncher;
import hudson.slaves.NodeProperty;
import hudson.slaves.RetentionStrategy;
import org.junit.Rule;
import org.junit.Test;
import org.jvnet.hudson.test.JenkinsRule;

import java.util.Collections;

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

/**
 * SlaveLabelCheckerTestCase Test Case.
 *
 * @author Victor Martinez
 */
public class SlaveLabelCheckerTestCase {
    private SlaveLabelChecker checker = new SlaveLabelChecker();

    @Rule public JenkinsRule j = new JenkinsRule();
    @Test public void testDefaultSlave() throws Exception {
        Slave slave = createSlave("default", "", "");
        assertTrue(checker.executeCheck(slave));
    }
    @Test public void testSlaveLabel() throws Exception {
        Slave slave = createSlave("default", "", "somelabel");
        assertFalse(checker.executeCheck(slave));
    }

    @Test public void testControlComment() throws Exception {
        Slave slave = createSlave("default", "", "");
        assertFalse(checker.isIgnored(slave.getNodeDescription()));
        slave = createSlave("default", "#lint:ignore:" + checker.getClass().getSimpleName(), "");
        assertTrue(checker.isIgnored(slave.getNodeDescription()));
    }

    private Slave createSlave(String name, String description, String label) throws Exception {
        return new DumbSlave(name, description, "/wherever", "1", Node.Mode.NORMAL, label, new JNLPLauncher(), RetentionStrategy.NOOP, Collections.<NodeProperty<?>>emptyList());
    }
}

Test cases for slavelabel check


package info.u_team.u_team_test.data.provider;

import java.util.function.BiConsumer;

import info.u_team.u_team_core.data.*;
import info.u_team.u_team_test.init.*;
import net.minecraft.util.ResourceLocation;
import net.minecraft.world.storage.loot.LootTable;

public class TestLootTablesProvider extends CommonLootTablesProvider {

	public TestLootTablesProvider(GenerationData data) {
		super(data);
	}

	@Override
	protected void registerLootTables(BiConsumer<ResourceLocation, LootTable> consumer) {
		registerBlock(TestBlocks.BASIC.get(), addFortuneBlockLootTable(TestBlocks.BASIC.get(), TestItems.BASIC.get()), consumer);
		registerBlock(TestBlocks.BASIC_TILEENTITY.get(), addTileEntityBlockLootTable(TestBlocks.BASIC_TILEENTITY.get()), consumer);
		registerBlock(TestBlocks.BASIC_ENERGY_CREATOR.get(), addTileEntityBlockLootTable(TestBlocks.BASIC_ENERGY_CREATOR.get()), consumer);
		registerBlock(TestBlocks.BASIC_FLUID_INVENTORY.get(), addTileEntityBlockLootTable(TestBlocks.BASIC_FLUID_INVENTORY.get()), consumer);
	}

}

package info.u_team.u_team_test.data.provider;

import java.util.function.BiConsumer;

import info.u_team.u_team_core.data.*;
import info.u_team.u_team_test.init.*;
import net.minecraft.util.ResourceLocation;
import net.minecraft.world.storage.loot.LootTable;

public class TestLootTablesProvider extends CommonLootTablesProvider {

	public TestLootTablesProvider(GenerationData data) {
		super(data);
	}

	@Override
	protected void registerLootTables(BiConsumer<ResourceLocation, LootTable> consumer) {
		registerBlock(TestBlocks.BASIC, addFortuneBlockLootTable(TestBlocks.BASIC.get(), TestItems.BASIC.get()), consumer);
		registerBlock(TestBlocks.BASIC_TILEENTITY, addTileEntityBlockLootTable(TestBlocks.BASIC_TILEENTITY.get()), consumer);
		registerBlock(TestBlocks.BASIC_ENERGY_CREATOR, addTileEntityBlockLootTable(TestBlocks.BASIC_ENERGY_CREATOR.get()), consumer);
		registerBlock(TestBlocks.BASIC_FLUID_INVENTORY, addTileEntityBlockLootTable(TestBlocks.BASIC_FLUID_INVENTORY.get()), consumer);
	}

}

Use the method in test loot tables now


/*
 * FindBugs - Find Bugs in Java programs
 * Copyright (C) 2003-2008 University of Maryland
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */

package edu.umd.cs.findbugs.classfile.engine.asm;

import org.objectweb.asm.Opcodes;

/**
 * @author pugh
 */
public class FindBugsASM {

    public static final int ASM_VERSION = Opcodes.ASM7_EXPERIMENTAL;

}

/*
 * FindBugs - Find Bugs in Java programs
 * Copyright (C) 2003-2008 University of Maryland
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */

package edu.umd.cs.findbugs.classfile.engine.asm;

import org.objectweb.asm.Opcodes;

/**
 * @author pugh
 */
public class FindBugsASM {

    private static final boolean USE_EXPERIMENTAL = Boolean.parseBoolean(System.getProperty("spotbugs.experimental"));
    public static final int ASM_VERSION = USE_EXPERIMENTAL ? Opcodes.ASM7_EXPERIMENTAL : Opcodes.ASM6;

}

Use Opcodes.ASM7_EXPERIMENTAL if system property spotbugs.experimental=true


package org.beanmaker.util;

public class Ids {

    public static String getProtectionCodeFromParameterName(final String parameterName) {
        return getProtectionCodeFromParameterName(parameterName, "_");
    }

    public static String getProtectionCodeFromParameterName(final String parameterName, final String separatorRegex) {
        final String[] elements = parameterName.split(separatorRegex);
        if (elements.length < 2)
            throw new IllegalArgumentException("Could not separate id/code from name based on regex: "
                    + separatorRegex);

        return elements[elements.length - 1];
    }

    public static long getIdFromParameterName(final String parameterName) {
        return Long.valueOf(getProtectionCodeFromParameterName(parameterName));
    }

    public static long getIdFromParameterName(final String parameterName, final String separatorRegex) {
        return Long.valueOf(getProtectionCodeFromParameterName(parameterName, separatorRegex));
    }
}

package org.beanmaker.util;

import java.util.Collection;
import java.util.HashSet;
import java.util.Set;

public class Ids {

    public static String getProtectionCodeFromParameterName(final String parameterName) {
        return getProtectionCodeFromParameterName(parameterName, "_");
    }

    public static String getProtectionCodeFromParameterName(final String parameterName, final String separatorRegex) {
        final String[] elements = parameterName.split(separatorRegex);
        if (elements.length < 2)
            throw new IllegalArgumentException("Could not separate id/code from name based on regex: "
                    + separatorRegex);

        return elements[elements.length - 1];
    }

    public static long getIdFromParameterName(final String parameterName) {
        return Long.valueOf(getProtectionCodeFromParameterName(parameterName));
    }

    public static long getIdFromParameterName(final String parameterName, final String separatorRegex) {
        return Long.valueOf(getProtectionCodeFromParameterName(parameterName, separatorRegex));
    }

    public static Set<Long> getIdSet(final Collection<DbBeanInterface> beans) {
        final Set<Long> set = new HashSet<Long>();

        for (DbBeanInterface bean: beans)
            set.add(bean.getId());

        return set;
    }
}

Add function that takes a Collection of beans and returns a Set of ids


package Engine;

import java.util.HashMap;

public class Strategy {

    HashMap<String, Double> hotnessMap;

    // bettingFunction is an array of length 5;
<<<<<<< HEAD
    public Strategy() {
        hotnessMap = new HashMap<String, Double>();
        for (int i = 1; i < 14; i++) {
            if (i == 1)
                hotnessMap.put("A", 1.0);
            else if (i == 11)
                hotnessMap.put("J", 1.0);
            else if (i == 12)
                hotnessMap.put("Q", 1.0);
            else if (i == 13)
                hotnessMap.put("K", 1.0);
            else
                hotnessMap.put(i + "", 1.0);
        }
    }

    double getHottnessForCard(Card card) {
        return hotnessMap.get(card.getRank());
=======
    public Strategy(double[] hotnessMap, int[] bettingFunction) {
      this.hotnessMap = hotnessMap;
      this.bettingFunction = bettingFunction;
    }

    double getHottnessForCard(Card card) {
      return hotnessMap[card.getValues()[0] - 1];
>>>>>>> parent of 706d131... Fix bug in strategy
    }

    double getBetMultiplier(double hotness) {
        return 1;
    }
}

package Engine;

import java.util.HashMap;

public class Strategy {

    HashMap<String, Double> hotnessMap;

    // bettingFunction is an array of length 5;
<<<<<<< HEAD
<<<<<<< HEAD
    public Strategy() {
        hotnessMap = new HashMap<String, Double>();
        for (int i = 1; i < 14; i++) {
            if (i == 1)
                hotnessMap.put("A", 1.0);
            else if (i == 11)
                hotnessMap.put("J", 1.0);
            else if (i == 12)
                hotnessMap.put("Q", 1.0);
            else if (i == 13)
                hotnessMap.put("K", 1.0);
            else
                hotnessMap.put(i + "", 1.0);
        }
    }

    double getHottnessForCard(Card card) {
        return hotnessMap.get(card.getRank());
=======
=======
>>>>>>> parent of 706d131... Fix bug in strategy
    public Strategy(double[] hotnessMap, int[] bettingFunction) {
      this.hotnessMap = hotnessMap;
      this.bettingFunction = bettingFunction;
    }

    double getHottnessForCard(Card card) {
      return hotnessMap[card.getValues()[0] - 1];
<<<<<<< HEAD
>>>>>>> parent of 706d131... Fix bug in strategy
=======
>>>>>>> parent of 706d131... Fix bug in strategy
    }

    double getBetMultiplier(double hotness) {
        return 1;
    }
}

Revert "Fix bug in strategy"


package com.nguyenquyhy.discordbridge.models;

import ninja.leaping.configurate.objectmapping.Setting;
import ninja.leaping.configurate.objectmapping.serialize.ConfigSerializable;

/**
 * Created by Hy on 12/11/2016.
 */
@ConfigSerializable
public class ChannelMinecraftMentionConfig implements IConfigInheritable<ChannelMinecraftMentionConfig> {
    public ChannelMinecraftMentionConfig() {

    }

    /**
     * This is called only when the config file is first created.
     */
    void initializeDefault() {
        userTemplate = "&6@&e%a";
        roleTemplate = "&6@&a%r";
        everyoneTemplate = "&6@&3%a";
    }

    @Setting
    public String userTemplate;
    @Setting
    public String roleTemplate;
    @Setting
    public String everyoneTemplate;

    @Override
    public void inherit(ChannelMinecraftMentionConfig parent) {
        if (userTemplate == null) userTemplate = parent.userTemplate;
        if (roleTemplate == null) roleTemplate = parent.roleTemplate;
        if (everyoneTemplate == null) everyoneTemplate = parent.everyoneTemplate;
    }
}

package com.nguyenquyhy.discordbridge.models;

import ninja.leaping.configurate.objectmapping.Setting;
import ninja.leaping.configurate.objectmapping.serialize.ConfigSerializable;

/**
 * Created by Hy on 12/11/2016.
 */
@ConfigSerializable
public class ChannelMinecraftMentionConfig implements IConfigInheritable<ChannelMinecraftMentionConfig> {
    public ChannelMinecraftMentionConfig() {

    }

    /**
     * This is called only when the config file is first created.
     */
    void initializeDefault() {
        userTemplate = "&6@&e%a&r";
        roleTemplate = "&6@&a%r&r";
        everyoneTemplate = "&6@&3%a&r";
    }

    @Setting
    public String userTemplate;
    @Setting
    public String roleTemplate;
    @Setting
    public String everyoneTemplate;

    @Override
    public void inherit(ChannelMinecraftMentionConfig parent) {
        if (userTemplate == null) userTemplate = parent.userTemplate;
        if (roleTemplate == null) roleTemplate = parent.roleTemplate;
        if (everyoneTemplate == null) everyoneTemplate = parent.everyoneTemplate;
    }
}

Add reset color to default mention templates.


package com.porterhead.filter.spring;

import com.porterhead.filter.BaseCORSFilter;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Created by iainporter on 26/07/2014.
 */
@Component
public class SpringCrossOriginResourceSharingFilter extends BaseCORSFilter implements Filter {

    @Value("${cors.allowed.origins}")
    String allowedOriginsString;

    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
        if(req instanceof HttpServletRequest) {
            if (((HttpServletRequest) req).getHeader("Origin") != null) {
                String origin = ((HttpServletRequest) req).getHeader("Origin");
                if (getAllowedOrigins(allowedOriginsString).contains(origin)) {
                    HttpServletResponse response = (HttpServletResponse) res;
                    response.setHeader("Access-Control-Allow-Origin", origin);
                    response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE, OPTIONS");
                    response.setHeader("Access-Control-Max-Age", "3600");
                    response.setHeader("Access-Control-Allow-Headers", "x-requested-with, Authorization, Content-Type");
                }
            }
        }
        chain.doFilter(req, res);
    }

    public void init(FilterConfig filterConfig) {}

    public void destroy() {}

}

package com.porterhead.filter.spring;

import com.porterhead.filter.BaseCORSFilter;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Created by iainporter on 26/07/2014.
 */
@Component
public class SpringCrossOriginResourceSharingFilter extends BaseCORSFilter implements Filter {

    @Value("${cors.allowed.origins}")
    String allowedOriginsString;

    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
        if(req instanceof HttpServletRequest) {
            if (((HttpServletRequest) req).getHeader("Origin") != null) {
                String origin = ((HttpServletRequest) req).getHeader("Origin");
                if (getAllowedOrigins(allowedOriginsString).contains(origin)) {
                    HttpServletResponse response = (HttpServletResponse) res;
                    response.setHeader("Access-Control-Allow-Origin", origin);
                    response.setHeader("Access-Control-Allow-Methods",  "GET, POST, PUT, DELETE, OPTIONS");
                    response.setHeader("Access-Control-Max-Age", "3600");
                    response.setHeader("Access-Control-Allow-Headers", "x-requested-with, Authorization, Content-Type");
                }
            }
        }
        chain.doFilter(req, res);
    }

    public void init(FilterConfig filterConfig) {}

    public void destroy() {}

}

Fix Spring CORS Filter impl


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

package org.elasticsearch.plugin.ingest.rest;

import org.elasticsearch.common.inject.Inject;
import org.elasticsearch.rest.*;

import static org.elasticsearch.plugin.ingest.IngestPlugin.*;
import static org.elasticsearch.plugin.ingest.IngestPlugin.INGEST_PARAM_CONTEXT_KEY;

public class IngestRestFilter extends RestFilter {

    @Inject
    public IngestRestFilter(RestController controller) {
        controller.registerFilter(this);
    }

    @Override
    public void process(RestRequest request, RestChannel channel, RestFilterChain filterChain) throws Exception {
        request.putInContext(INGEST_PARAM_CONTEXT_KEY, request.param(INGEST_PARAM));
        filterChain.continueProcessing(request, channel);
    }
}

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

package org.elasticsearch.plugin.ingest.rest;

import org.elasticsearch.common.inject.Inject;
import org.elasticsearch.rest.*;

import static org.elasticsearch.plugin.ingest.IngestPlugin.*;
import static org.elasticsearch.plugin.ingest.IngestPlugin.INGEST_PARAM_CONTEXT_KEY;

public class IngestRestFilter extends RestFilter {

    @Inject
    public IngestRestFilter(RestController controller) {
        controller.registerFilter(this);
    }

    @Override
    public void process(RestRequest request, RestChannel channel, RestFilterChain filterChain) throws Exception {
        if (request.hasParam(INGEST_PARAM)) {
            request.putInContext(INGEST_PARAM_CONTEXT_KEY, request.param(INGEST_PARAM));
        }
        filterChain.continueProcessing(request, channel);
    }
}

Add the ingest param to the context only if present


// Copyright (c) 2013 Intel Corporation. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

package org.xwalk.runtime.extension;

import android.app.Activity;
import android.content.Context;

/**
 * This is a public class to provide context for extensions.
 * It'll be shared by all extensions.
 */
public class XWalkExtensionContextWrapper extends XWalkExtensionContext {
    private XWalkExtensionContext mOriginContext;

    public XWalkExtensionContextWrapper(XWalkExtensionContext context) {
        mOriginContext = context;
    }

    public Object registerExtension(XWalkExtension extension) {
        return mOriginContext.registerExtension(extension);
    }

    public void unregisterExtension(XWalkExtension extension) {
        mOriginContext.unregisterExtension(extension);
    }

    public void postMessage(XWalkExtension extension, String message) {
        mOriginContext.postMessage(extension, message);
    }

    public Context getContext() {
        return mOriginContext.getContext();
    }

    public Activity getActivity() {
        return mOriginContext.getActivity();
    }
}

// Copyright (c) 2013 Intel Corporation. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

package org.xwalk.runtime.extension;

import android.app.Activity;
import android.content.Context;

/**
 * This is a public class to provide context for extensions.
 * It'll be shared by all external extensions.
 */
public class XWalkExtensionContextWrapper extends XWalkExtensionContext {
    private XWalkExtensionContext mOriginContext;

    public XWalkExtensionContextWrapper(XWalkExtensionContext context) {
        mOriginContext = context;
    }

    public Object registerExtension(XWalkExtension extension) {
        return mOriginContext.registerExtension(extension);
    }

    public void unregisterExtension(XWalkExtension extension) {
        mOriginContext.unregisterExtension(extension);
    }

    public void postMessage(XWalkExtension extension, String message) {
        mOriginContext.postMessage(extension, message);
    }

    public Context getContext() {
        // This is very tricky because for external extensions, we should
        // use Activity which contains the context for runtime client side.
        // mOriginContext.getContext() returns the context of library package,
        // e.g., the package context of runtime side.
        return mOriginContext.getActivity();
    }

    public Activity getActivity() {
        return mOriginContext.getActivity();
    }
}

Return the correct context for external extensions


package dk.statsbiblioteket.medieplatform.newspaper.ninestars;

import dk.statsbiblioteket.medieplatform.autonomous.Batch;
import dk.statsbiblioteket.medieplatform.autonomous.ResultCollector;
import dk.statsbiblioteket.medieplatform.autonomous.RunnableComponent;

import java.util.Properties;

public class MockComponent implements RunnableComponent {

    public MockComponent(Properties properties) {

    }

    @Override
    public String getComponentName() {
        return "MockComponent";
    }

    @Override
    public String getComponentVersion() {
        return getClass().getPackage().getImplementationVersion();
    }

    @Override
    public String getEventID() {
        return "Mock_Event";
    }

    @Override
    public void doWorkOnBatch(Batch batch,
                              ResultCollector resultCollector)
            throws
            Exception {
        return;
    }
}

package dk.statsbiblioteket.medieplatform.newspaper.ninestars;

import dk.statsbiblioteket.medieplatform.autonomous.Batch;
import dk.statsbiblioteket.medieplatform.autonomous.EventStorer;
import dk.statsbiblioteket.medieplatform.autonomous.EventTrigger;
import dk.statsbiblioteket.medieplatform.autonomous.ResultCollector;
import dk.statsbiblioteket.medieplatform.autonomous.RunnableComponent;

import java.util.Properties;

public class MockComponent implements RunnableComponent {

    public MockComponent(Properties properties) {

    }

    @Override
    public String getComponentName() {
        return "MockComponent";
    }

    @Override
    public String getComponentVersion() {
        return getClass().getPackage().getImplementationVersion();
    }

    @Override
    public String getEventID() {
        return "Mock_Event";
    }

    @Override
    public void doWorkOnBatch(Batch batch,
                              ResultCollector resultCollector)
            throws
            Exception {
        return;
    }

    @Override
    public EventTrigger getEventTrigger() {
        return null;
    }

    @Override
    public EventStorer getEventStorer() {
        return null;
    }
}

Update to match new framework


package com.greetings;

import java.util.concurrent.ConcurrentHashMap;

public class Main {
    public static void main(String[] args) {
        System.out.println(new ConcurrentHashMap());
    }
}

package com.greetings;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class Main {
    public static void main(String[] args) {
        Map<Integer, String> myMap = new ConcurrentHashMap<Integer,         String>();
        myMap.put(1, "one");
        myMap.put(2, "two");
        myMap.put(3, "three");
        System.out.println(myMap);
    }
}

Add further output to main


/*
 * Copyright 2013 MovingBlocks
 *
 * 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.terasology.engine.modes.loadProcesses;

import org.terasology.engine.modes.LoadProcess;

/**
 * @author Immortius
 */
public abstract class StepBasedLoadProcess implements LoadProcess {

    private int stepsComplete;
    private int totalSteps;

    protected void stepDone() {
        stepsComplete++;
    }

    protected void setTotalSteps(int amount) {
        this.totalSteps = Math.min(1, amount);
    }

    @Override
    public final float getProgress() {
        return (float) Math.min(totalSteps, stepsComplete) / totalSteps;
    }
}

/*
 * Copyright 2013 MovingBlocks
 *
 * 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.terasology.engine.modes.loadProcesses;

import org.terasology.engine.modes.LoadProcess;

/**
 * @author Immortius
 */
public abstract class StepBasedLoadProcess implements LoadProcess {

    private int stepsComplete;
    private int totalSteps = 1;

    protected void stepDone() {
        stepsComplete++;
    }

    protected void setTotalSteps(int amount) {
        this.totalSteps = Math.max(1, amount);
    }

    @Override
    public final float getProgress() {
        return (float) Math.min(totalSteps, stepsComplete) / totalSteps;
    }
}

Fix for loading bar flicking to empty for some steps.


package org.spoofax.jsglr2.parseforest;

import org.spoofax.jsglr.client.imploder.IToken;
import org.spoofax.jsglr2.parser.Position;

public abstract class AbstractParseForest {

    private final Position startPosition, endPosition;

    public IToken token, firstToken, lastToken;

    protected AbstractParseForest(Position startPosition, Position endPosition) {
        this.startPosition = startPosition;
        this.endPosition = endPosition;

        this.token = null;
        this.firstToken = null;
        this.lastToken = null;
    }

    public Position getStartPosition() {
        return startPosition;
    }

    public Position getEndPosition() {
        return endPosition;
    }

    public abstract String descriptor();

}

package org.spoofax.jsglr2.parseforest;

import org.spoofax.jsglr2.parser.Position;

public abstract class AbstractParseForest {

    private final Position startPosition, endPosition;

    protected AbstractParseForest(Position startPosition, Position endPosition) {
        this.startPosition = startPosition;
        this.endPosition = endPosition;
    }

    public Position getStartPosition() {
        return startPosition;
    }

    public Position getEndPosition() {
        return endPosition;
    }

    public abstract String descriptor();

}

Remove tokens from parse forest