package org.camunda.bpm.demo.orderconfirmation.config;

import org.camunda.bpm.demo.orderconfirmation.bean.RuleEntryDAO;
import org.camunda.bpm.demo.orderconfirmation.model.DiscountRuleEntry;

import javax.annotation.PostConstruct;
import javax.ejb.Singleton;
import javax.ejb.Startup;
import javax.inject.Inject;
import java.util.List;
import java.util.logging.Logger;

/*
 * Helper class to create an initial set of discount rules
 */
@Singleton
@Startup
public class DiscountRuleEntryConfig {

  private final static Logger log = Logger.getLogger(DiscountRuleEntryConfig.class.getCanonicalName());

  @Inject
  private RuleEntryDAO rulesDAO;

  /*
   * If no discount rules are present in the database, we create some initial ones
   */
  @PostConstruct
  public void initializeDiscountRules() {
    List<DiscountRuleEntry> rules = rulesDAO.findAllDiscountRuleEntries();
    if ((rules == null) || (rules.size() == 0)) {
      log.info("Creating initial sample discount rules: ...");
      rulesDAO.save(new DiscountRuleEntry("Small orders", 100, 500, 5));
      rulesDAO.save(new DiscountRuleEntry("Mediun orders", 501, 1001, 7));
      rulesDAO.save(new DiscountRuleEntry("Big orders", 1001, 5000, 10));
    }
  }
}

package org.camunda.bpm.demo.orderconfirmation.config;

import org.camunda.bpm.demo.orderconfirmation.bean.RuleEntryDAO;
import org.camunda.bpm.demo.orderconfirmation.model.DiscountRuleEntry;

import javax.annotation.PostConstruct;
import javax.ejb.Singleton;
import javax.ejb.Startup;
import javax.inject.Inject;
import java.util.List;
import java.util.logging.Logger;

/*
 * Helper class to create an initial set of discount rules
 */
@Singleton
@Startup
public class DiscountRuleEntryConfig {

  private final static Logger log = Logger.getLogger(DiscountRuleEntryConfig.class.getCanonicalName());

  @Inject
  private RuleEntryDAO rulesDAO;

  /*
   * If no discount rules are present in the database, we create some initial ones
   */
  @PostConstruct
  public void initializeDiscountRules() {
    List<DiscountRuleEntry> rules = rulesDAO.findAllDiscountRuleEntries();
    if ((rules == null) || (rules.size() == 0)) {
      log.info("Creating initial sample discount rules: ...");
      rulesDAO.save(new DiscountRuleEntry("Small orders", 100, 500, 5));
      rulesDAO.save(new DiscountRuleEntry("Mediun orders", 501, 1000, 7));
      rulesDAO.save(new DiscountRuleEntry("Big orders", 1001, 5000, 10));
    }
  }
}

Fix "amount from" for "Big orders"

Fix "amount from" for "Big orders"


package com.ptsmods.morecommands.commands.server.elevated;

import com.mojang.brigadier.CommandDispatcher;
import com.mojang.brigadier.arguments.StringArgumentType;
import com.ptsmods.morecommands.MoreCommands;
import com.ptsmods.morecommands.miscellaneous.Command;
import net.minecraft.item.ItemStack;
import net.minecraft.server.command.ServerCommandSource;
import net.minecraft.util.Formatting;

public class RenameCommand extends Command {
    @Override
    public void register(CommandDispatcher<ServerCommandSource> dispatcher) {
        dispatcher.register(literalReqOp("rename")
                .then(argument("name", StringArgumentType.greedyString())
                        .executes(ctx -> {
                            ItemStack stack = ctx.getSource().getPlayerOrThrow().getMainHandStack();
                            if (stack.isEmpty()) sendError(ctx, "You are not holding an item.");
                            else {
                                String name = MoreCommands.translateFormattings(ctx.getArgument("name", String.class));
                                stack.setCustomName(literalText(name).build());
                                sendMsg(ctx, "The item has been renamed to " + name + Formatting.RESET + ".");
                                return 1;
                            }
                            return 0;
                        })));
    }

    @Override
    public String getDocsPath() {
        return "/elevated/rename";
    }
}

package com.ptsmods.morecommands.commands.server.elevated;

import com.mojang.brigadier.CommandDispatcher;
import com.mojang.brigadier.arguments.StringArgumentType;
import com.ptsmods.morecommands.MoreCommands;
import com.ptsmods.morecommands.miscellaneous.Command;
import com.ptsmods.morecommands.miscellaneous.MoreGameRules;
import net.minecraft.item.ItemStack;
import net.minecraft.server.command.ServerCommandSource;
import net.minecraft.util.Formatting;

public class RenameCommand extends Command {
    @Override
    public void register(CommandDispatcher<ServerCommandSource> dispatcher) {
        dispatcher.register(literalReqOp("rename")
                .then(argument("name", StringArgumentType.greedyString())
                        .executes(ctx -> {
                            ItemStack stack = ctx.getSource().getPlayerOrThrow().getMainHandStack();
                            if (stack.isEmpty()) sendError(ctx, "You are not holding an item.");
                            else {
                                String nameRaw = ctx.getArgument("name", String.class);
                                String name = MoreGameRules.get().checkBooleanWithPerm(ctx.getSource().getWorld().getGameRules(),
                                        MoreGameRules.get().doItemColoursRule(), ctx.getSource().getEntity()) ?
                                        MoreCommands.translateFormattings(nameRaw) : nameRaw;
                                stack.setCustomName(literalText(name).build());
                                sendMsg(ctx, "The item has been renamed to " + name + Formatting.RESET + ".");
                                return 1;
                            }
                            return 0;
                        })));
    }

    @Override
    public String getDocsPath() {
        return "/elevated/rename";
    }
}

Check gamerule before translating formattings


package pl.mn.ccsg.dialog;

import com.intellij.openapi.project.Project;

import javax.swing.*;
import java.awt.event.ActionEvent;
import java.beans.PropertyChangeListener;

/**
 * @author minidmnv
 */
public class GenerateStructurePanel extends JPanel {

    private JButton directoryChooserButton;
    private JTextField directoryTextArea;
    private JFileChooser pathChooser;
    private final Project project;
    private JLabel pathLabel;

    public GenerateStructurePanel(Project project) {
        this.project = project;
    }

    public void init() {
        initComponents();

        add(pathLabel);
        add(directoryTextArea);
        add(directoryChooserButton);
    }

    private void initComponents() {
        pathLabel = new JLabel("Path:");
        directoryTextArea = new JTextField(project.getBasePath(), 20);
        directoryChooserButton = new JButton("...");
        directoryChooserButton.setAction(directoryChooserAction);
    }

    private Action directoryChooserAction = new Action() {

        @Override
        public Object getValue(String key) {
            return null;
        }

        @Override
        public void putValue(String key, Object value) {

        }

        @Override
        public void setEnabled(boolean b) {

        }

        @Override
        public boolean isEnabled() {
            return false;
        }

        @Override
        public void addPropertyChangeListener(PropertyChangeListener listener) {

        }

        @Override
        public void removePropertyChangeListener(PropertyChangeListener listener) {

        }

        @Override
        public void actionPerformed(ActionEvent e) {

        }
    };

}

package pl.mn.ccsg.dialog;

import com.intellij.openapi.project.Project;

import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.beans.PropertyChangeListener;

/**
 * @author minidmnv
 */
public class GenerateStructurePanel extends JPanel {

    private JButton directoryChooserButton;
    private JTextField directoryTextArea;
    private JFileChooser pathChooser;
    private final Project project;
    private JLabel pathLabel;

    public GenerateStructurePanel(Project project) {
        this.project = project;
    }

    public void init() {
        initComponents();

        add(pathLabel);
        add(directoryTextArea);
        add(directoryChooserButton);
    }

    private void initComponents() {
        pathLabel = new JLabel("Path:");
        directoryTextArea = new JTextField(project.getBasePath(), 20);
        directoryChooserButton = new JButton("...");
        directoryChooserButton.addActionListener(directoryChooserAction);
    }

    private ActionListener directoryChooserAction = e -> openPathChooser();

    private void openPathChooser() {

    }

}

Change PathButton action to action listener


package com.izforge.izpack.installer.base;

import com.izforge.izpack.api.data.AutomatedInstallData;
import com.izforge.izpack.installer.manager.PanelManager;

/**
 * Installer frame controller
 *
 * @author Anthonin Bonnefoy
 */
public class InstallerController
{

    private InstallerFrame installerFrame;
    private PanelManager panelManager;
    private AutomatedInstallData automatedInstallData;

    public InstallerController(PanelManager panelManager, InstallDataConfiguratorWithRules installDataRulesEngineManager, InstallerFrame installerFrame, AutomatedInstallData automatedInstallData)
    {

        this.panelManager = panelManager;
        this.installerFrame = installerFrame;
        this.automatedInstallData = automatedInstallData;
        installDataRulesEngineManager.configureInstallData();

    }

    public InstallerController buildInstallation() throws Exception
    {
        panelManager.loadPanelsInContainer();
        panelManager.instantiatePanels();
        installerFrame.buildGUI();
        installerFrame.sizeFrame();
        return this;
    }

    public void launchInstallation()
    {
        activateFirstPanel();
    }

    private void activateFirstPanel()
    {
        int firstPanel = installerFrame.hasNavigateNext(-1, false);
        if (firstPanel > -1)
        {
            installerFrame.setVisible(true);
            automatedInstallData.setCurPanelNumber(firstPanel);
            installerFrame.switchPanel(firstPanel);
        }
    }

}

package com.izforge.izpack.installer.base;

import com.izforge.izpack.api.data.AutomatedInstallData;
import com.izforge.izpack.installer.manager.PanelManager;

import javax.swing.*;

/**
 * Installer frame controller
 *
 * @author Anthonin Bonnefoy
 */
public class InstallerController
{

    private InstallerFrame installerFrame;
    private PanelManager panelManager;
    private AutomatedInstallData automatedInstallData;

    public InstallerController(PanelManager panelManager, InstallDataConfiguratorWithRules installDataRulesEngineManager, InstallerFrame installerFrame, AutomatedInstallData automatedInstallData)
    {

        this.panelManager = panelManager;
        this.installerFrame = installerFrame;
        this.automatedInstallData = automatedInstallData;
        installDataRulesEngineManager.configureInstallData();

    }

    public InstallerController buildInstallation() throws Exception
    {
        panelManager.loadPanelsInContainer();
        panelManager.instantiatePanels();
        SwingUtilities.invokeLater(new Runnable()
        {
            public void run()
            {
                installerFrame.buildGUI();
                installerFrame.sizeFrame();
            }
        });
        return this;
    }

    public void launchInstallation()
    {
        activateFirstPanel();
    }

    private void activateFirstPanel()
    {
        int firstPanel = installerFrame.hasNavigateNext(-1, false);
        if (firstPanel > -1)
        {
            installerFrame.setVisible(true);
            automatedInstallData.setCurPanelNumber(firstPanel);
            installerFrame.switchPanel(firstPanel);
        }
    }

}

Use invokeLater for ui build

Use invokeLater for ui build


package io.katharsis.rs.parameterProvider.provider;

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

import javax.ws.rs.QueryParam;
import javax.ws.rs.container.ContainerRequestContext;

import com.fasterxml.jackson.databind.ObjectMapper;

public class QueryParamProvider implements RequestContextParameterProvider {
  @Override
  public Object provideValue(Parameter parameter, ContainerRequestContext requestContext, ObjectMapper objectMapper) {
    Object returnValue;
    List<String> value = requestContext.getUriInfo().getQueryParameters().get(parameter.getAnnotation(QueryParam.class).value());
    if (value == null || value.isEmpty()) {
      return null;
    } else {
      if (String.class.isAssignableFrom(parameter.getType())) {
        // Given a query string: ?x=y&x=z, JAX-RS will return a value of y.
        returnValue = value.get(0);
      } else {
        try {
          returnValue = objectMapper.readValue(value.get(0), parameter.getType());
        } catch (IOException e) {
          throw new RuntimeException(e);
        }
      }
    }
    return returnValue;
  }

  @Override
  public boolean provides(Parameter parameter) {
    return parameter.isAnnotationPresent(QueryParam.class);
  }
}

package io.katharsis.rs.parameterProvider.provider;

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

import javax.ws.rs.QueryParam;
import javax.ws.rs.container.ContainerRequestContext;

import com.fasterxml.jackson.databind.ObjectMapper;

public class QueryParamProvider implements RequestContextParameterProvider {
  @Override
  public Object provideValue(Parameter parameter, ContainerRequestContext requestContext, ObjectMapper objectMapper) {
    Object returnValue;
    List<String> value = requestContext.getUriInfo().getQueryParameters().get(parameter.getAnnotation(QueryParam.class).value());
    if (value == null || value.isEmpty()) {
      return null;
    } else {
      if (String.class.isAssignableFrom(parameter.getType())) {
        // Given a query string: ?x=y&x=z, JAX-RS will return a value of y.
        returnValue = value.get(0);
      } else if (Iterable.class.isAssignableFrom(parameter.getType())) {
        returnValue = value;
      } else {
        try {
          returnValue = objectMapper.readValue(value.get(0), parameter.getType());
        } catch (IOException e) {
          throw new RuntimeException(e);
        }
      }
    }
    return returnValue;
  }

  @Override
  public boolean provides(Parameter parameter) {
    return parameter.isAnnotationPresent(QueryParam.class);
  }
}

Fix support for multiple values for a single parameter.


/*
 * Copyright (c) 2015 com.haulmont.ts.gui.entities
 */
package com.haulmont.timesheets.gui.extuser;

import com.haulmont.cuba.gui.app.security.user.edit.UserEditor;
import com.haulmont.timesheets.entity.ExtUser;
import com.haulmont.timesheets.global.WorkConfigBean;

import javax.inject.Inject;

/**
 * @author gorelov
 */
public class ExtUserEdit extends UserEditor {

    @Inject
    protected WorkConfigBean workConfigBean;

    @Override
    protected void postInit() {
        ExtUser user = (ExtUser) getItem();
        if (user.getWorkHoursForWeek() == null) {
            user.setWorkHoursForWeek(workConfigBean.getWorkHourForWeek());
        }
    }
}

/*
 * Copyright (c) 2015 com.haulmont.ts.gui.entities
 */
package com.haulmont.timesheets.gui.extuser;

import com.haulmont.cuba.gui.app.security.user.edit.UserEditor;
import com.haulmont.cuba.security.entity.User;
import com.haulmont.timesheets.entity.ExtUser;
import com.haulmont.timesheets.global.WorkTimeConfigBean;

import javax.inject.Inject;

/**
 * @author gorelov
 */
public class ExtUserEdit extends UserEditor {

    @Inject
    protected WorkTimeConfigBean workTimeConfigBean;

    @Override
    protected void initNewItem(User item) {
        super.initNewItem(item);
        ExtUser user = (ExtUser) item;
        if (user.getWorkHoursForWeek() == null) {
            user.setWorkHoursForWeek(workTimeConfigBean.getWorkHourForWeek());
        }
    }
}

Move user defaults to initNewItem

Move user defaults to initNewItem


package de.retest.recheck.ui.descriptors.idproviders;

import static de.retest.recheck.ui.Path.fromString;
import static de.retest.recheck.ui.descriptors.IdentifyingAttributes.create;
import static org.assertj.core.api.Assertions.assertThat;

import org.junit.jupiter.api.Test;

class ElementCountingRetestIdProviderTest {

	@Test
	void test() {
		final ElementCountingRetestIdProvider cut = new ElementCountingRetestIdProvider();
		assertThat( cut.getRetestId( create( fromString( "/html[1]/div[1]" ), "div" ) ) ).isEqualTo( "div-1" );
		assertThat( cut.getRetestId( create( fromString( "/html[1]/div[1]/div[1]" ), "div" ) ) ).isEqualTo( "div-2" );
		assertThat( cut.getRetestId( create( fromString( "/html[1]/div[4]" ), "div" ) ) ).isEqualTo( "div-3" );
		assertThat( cut.getRetestId( create( fromString( "/html[1]/a[1]" ), "a" ) ) ).isEqualTo( "a-1" );
	}

}

package de.retest.recheck.ui.descriptors.idproviders;

import static de.retest.recheck.ui.Path.fromString;
import static de.retest.recheck.ui.descriptors.IdentifyingAttributes.create;
import static org.assertj.core.api.Assertions.assertThat;

import org.junit.jupiter.api.Test;

class ElementCountingRetestIdProviderTest {

	@Test
	void test() {
		final ElementCountingRetestIdProvider cut = new ElementCountingRetestIdProvider();
		assertThat( cut.getRetestId( create( fromString( "/html[1]/div[1]" ), "div" ) ) ).isEqualTo( "div" );
		assertThat( cut.getRetestId( create( fromString( "/html[1]/div[1]/div[1]" ), "div" ) ) ).isEqualTo( "div-1" );
		assertThat( cut.getRetestId( create( fromString( "/html[1]/div[4]" ), "div" ) ) ).isEqualTo( "div-2" );
		assertThat( cut.getRetestId( create( fromString( "/html[1]/a[1]" ), "a" ) ) ).isEqualTo( "a" );
	}

}

Fix test to reflect actual behaviour

Fix test to reflect actual behaviour

it would be more consistent if the first starts with `1`, but since it is the default implementation, it would be hard to change


package com.github.atorr0.predictor.statistics;

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

/**
 * Simple stats. for hits & misses.
 *
 * @author https://github.com/atorr0
 */
public class Statistics {

	protected final List<Long> missesList = new ArrayList<>();

	protected long hits = 0, misses = 0;

	public long incrementHits() {
		return ++hits;
	}

	public long incrementMisses() {
		return ++misses;
	}

	public void next() {

		missesList.add(misses);
		hits = 0;
		misses = 0;
	}

	@Override
	public String toString() {

		long total = 0;
		for (Long misses : missesList)
			total += misses;

		final float hitRatio = Float.parseFloat("" + total) / missesList.size();

		return "Statistics [" //
				+ "hitRatio=" + hitRatio //
				+ ", missesList=" + missesList //
				+ ", hits=" + hits + ", misses=" + misses //
				+ "]";
	}
}

package com.github.atorr0.predictor.statistics;

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

/**
 * Simple stats. for hits & misses.
 *
 * @author https://github.com/atorr0
 */
public class Statistics {

	protected final List<Long> missesList = new ArrayList<>();

	protected long misses = 0;

	public float getHitRatio() {

		long total = 0;
		for (final Long misses : missesList)
			total += misses;

		return 1f - Float.parseFloat("" + total) / missesList.size();
	}

	public long incrementMisses() {
		return ++misses;
	}

	public void next() {

		missesList.add(misses);
		misses = 0;
	}

	@Override
	public String toString() {

		return "Statistics [" //
				+ "hitRatio=" + getHitRatio() //
				+ ", missesList=" + missesList //
				+ ", misses=" + misses //
				+ "]";
	}
}

UPDATE remove hit counts + FIX hit ratio was wrongly calculated


package com.facebook.presto.cli;

public final class Help
{
    private Help() {}

    public static String getHelpText()
    {
        return "" +
                "Supported commands:\n" +
                "QUIT\n" +
                "DESCRIBE <table>\n" +
                "SHOW COLUMNS FROM <table>\n" +
                "SHOW FUNCTIONS\n" +
                "SHOW PARTITIONS FROM <table>\n" +
                "SHOW TABLES\n" +
                "";
    }
}

package com.facebook.presto.cli;

public final class Help
{
    private Help() {}

    public static String getHelpText()
    {
        return "" +
                "Supported commands:\n" +
                "QUIT\n" +
                "DESCRIBE <table>\n" +
                "SHOW COLUMNS FROM <table>\n" +
                "SHOW FUNCTIONS\n" +
                "SHOW PARTITIONS FROM <table>\n" +
                "SHOW TABLES [LIKE <pattern>]\n" +
                "";
    }
}

Add full syntax for SHOW TABLES to help

Add full syntax for SHOW TABLES to help


package com.yammer.dropwizard.apidocs;

import java.util.List;

public class AllowableValues {
	private List<String> values;

	@SuppressWarnings("unused")
	private AllowableValues(){};

	public AllowableValues(List<String> values){
		this.values = values;
	}

	public String getValueType() {
		return "List";
	}

	public List<String> getValues(){
		return values;
	}

}

package com.yammer.dropwizard.apidocs;

import java.util.List;

public class AllowableValues {
	private List<String> values;

	@SuppressWarnings("unused")
	private AllowableValues() {

    }

	public AllowableValues(List<String> values){
		this.values = values;
	}

	public String getValueType() {
		return "List";
	}

	public List<String> getValues(){
		return values;
	}

}

Remove unnecessary semicolon and clean up some code styling.


package org.yggard.brokkgui.wrapper.event;

import org.yggard.brokkgui.wrapper.container.BrokkGuiContainer;
import org.yggard.hermod.EventType;
import org.yggard.hermod.HermodEvent;

import net.minecraft.inventory.Slot;

/**
 * @author Ourten 31 oct. 2016
 */
public class SlotEvent extends HermodEvent
{
    public static final EventType<SlotEvent>       ANY   = new EventType<>("SLOT_EVENT");
    public static final EventType<SlotEvent.Click> CLICK = new EventType<>(SlotEvent.ANY, "SLOT_CLICK_EVENT");

    private final Slot                             slot;

    public SlotEvent(final BrokkGuiContainer<?> source, final Slot slot)
    {
        super(source);

        this.slot = slot;
    }

    public Slot getSlot()
    {
        return this.slot;
    }

    public static final class Click extends SlotEvent
    {
        private final int key;

        public Click(final BrokkGuiContainer<?> source, final Slot slot, final int key)
        {
            super(source, slot);

            this.key = key;
        }

        public int getKey()
        {
            return this.key;
        }
    }
}

package org.yggard.brokkgui.wrapper.event;

import org.yggard.brokkgui.wrapper.container.BrokkGuiContainer;
import org.yggard.hermod.EventType;
import org.yggard.hermod.HermodEvent;

import net.minecraft.inventory.Slot;

/**
 * @author Ourten 31 oct. 2016
 */
public class SlotEvent extends HermodEvent
{
    public static final EventType<SlotEvent>       ANY    = new EventType<>("SLOT_EVENT");
    public static final EventType<SlotEvent.Click> CLICK  = new EventType<>(SlotEvent.ANY, "SLOT_CLICK_EVENT");
    public static final EventType<Change>          CHANGE = new EventType<>(SlotEvent.ANY, "SLOT_CHANGE_EVENT");

    private final Slot                             slot;

    public SlotEvent(final BrokkGuiContainer<?> source, final Slot slot)
    {
        super(source);

        this.slot = slot;
    }

    public Slot getSlot()
    {
        return this.slot;
    }

    public static final class Click extends SlotEvent
    {
        private final int key;

        public Click(final BrokkGuiContainer<?> source, final Slot slot, final int key)
        {
            super(source, slot);

            this.key = key;
        }

        public int getKey()
        {
            return this.key;
        }
    }

    public static final class Change extends SlotEvent
    {
        public Change(final BrokkGuiContainer<?> source, final Slot slot)
        {
            super(source, slot);
        }
    }
}

Add a slot change event

Add a slot change event


package info.schleichardt.training.java8.lecture2;

import java.security.MessageDigest;

public class P2_FunctionalInterfacesFirstClassMembers {

    @FunctionalInterface
    public interface HashFunction {
        byte[] hash(final String input) throws Exception;

        //return type, works also in classes
        static HashFunction ofAlgorithm(final String algorithm) {
            return input -> MessageDigest.getInstance(algorithm).digest(input.getBytes());
        }
    }

    //member in a class
    public static final HashFunction hashFunctionClassMember = input -> MessageDigest.getInstance("SHA2").digest(input.getBytes());
    //field
    private final HashFunction hashFunctionAsField = input -> MessageDigest.getInstance("SHA2").digest(input.getBytes());

    //input parameter
    public static byte[] hashInput(final String input, final HashFunction function) throws Exception {
        return function.hash(input);
    }

    public static void demoForReturnType() throws Exception {
        final byte[] hash1 = HashFunction.ofAlgorithm("SHA1").hash("hello");
        final byte[] hash2 = hashInput("hello", HashFunction.ofAlgorithm("SHA1"));
    }

    //example method that is not at all related to the interface HashFunction
    //but still has the same signature of taking a String as input and returning a byte array
    public static byte[] md5(final String input) throws Exception {
        return MessageDigest.getInstance("MD5").digest(input.getBytes());
    }

    //method reference
    public static void demoForMethodReference() throws Exception {
        final HashFunction function = P2_FunctionalInterfacesFirstClassMembers::md5;//double colon for method reference
    }
}

package info.schleichardt.training.java8.lecture2;

import java.security.MessageDigest;

public class P2_FunctionalInterfacesFirstClassMembers {

    @FunctionalInterface
    public interface HashFunction {
        byte[] hash(final String input) throws Exception;

        //return type, works also in classes
        static HashFunction ofAlgorithm(final String algorithm) {
            return input -> MessageDigest.getInstance(algorithm).digest(input.getBytes());
        }
    }

    //member in a class
    public static final HashFunction hashFunctionClassMember = input -> MessageDigest.getInstance("SHA2").digest(input.getBytes());
    //field
    private final HashFunction hashFunctionAsField = input -> MessageDigest.getInstance("SHA2").digest(input.getBytes());

    //input parameter
    public static byte[] hashInput(final String input, final HashFunction function) throws Exception {
        return function.hash(input);
    }

    public static void demoForReturnType() throws Exception {
        final byte[] hash1 = HashFunction.ofAlgorithm("SHA1").hash("hello");
        final byte[] hash2 = hashInput("hello", HashFunction.ofAlgorithm("SHA1"));
    }

    //example method that is not at all related to the interface HashFunction
    //but still has the same signature of taking a String as input and returning a byte array
    //name is not important
    //little brother of duck typing
    public static byte[] md5(final String input) throws Exception {
        return MessageDigest.getInstance("MD5").digest(input.getBytes());
    }

    //method reference
    public static void demoForMethodReference() throws Exception {
        final HashFunction function = P2_FunctionalInterfacesFirstClassMembers::md5;//double colon for method reference
    }
}

Add note that Java 8 provides some kind of duck typing


package de.skuzzle.jeve.builder;

import java.util.function.Supplier;

import de.skuzzle.jeve.ListenerStore;
import de.skuzzle.jeve.providers.SynchronousEventProvider;
import de.skuzzle.jeve.stores.DefaultListenerStore;

/**
 * Default implementation of jeve's fluent builder API.
 *
 * @author Simon Taddiken
 */
public class ConfiguratorImpl implements EventProviderConfigurator {

    @Override
    public SynchronousEventProvider<DefaultListenerStore> createInstantly() {
        return new SynchronousEventProvider<DefaultListenerStore>(
                new DefaultListenerStore());
    }

    @Override
    public ProviderChooser<DefaultListenerStore> defaultStore() {
        final Supplier<DefaultListenerStore> supplier = DefaultListenerStore::new;
        return new ProviderChooserImpl<DefaultListenerStore>(supplier);
    }

    @Override
    public <S extends ListenerStore> ProviderChooser<S> store(
            Supplier<S> storeSupplier) {
        if (storeSupplier == null) {
            throw new IllegalArgumentException("storeSupplier is null");
        }
        return new ProviderChooserImpl<S>(storeSupplier);
    }

    @Override
    public <S extends ListenerStore> ProviderChooser<S> store(S store) {
        if (store == null) {
            throw new IllegalArgumentException("store is null");
        }
        final Supplier<S> supplier = () -> store;
        return store(supplier);
    }

}

package de.skuzzle.jeve.builder;

import java.util.function.Supplier;

import de.skuzzle.jeve.ListenerStore;
import de.skuzzle.jeve.providers.SynchronousEventProvider;
import de.skuzzle.jeve.stores.DefaultListenerStore;

/**
 * Default implementation of jeve's fluent builder API.
 *
 * @author Simon Taddiken
 * @since 2.0.0
 */
public class ConfiguratorImpl implements EventProviderConfigurator {

    @Override
    public SynchronousEventProvider<DefaultListenerStore> createInstantly() {
        return new SynchronousEventProvider<DefaultListenerStore>(
                new DefaultListenerStore());
    }

    @Override
    public ProviderChooser<DefaultListenerStore> defaultStore() {
        final Supplier<DefaultListenerStore> supplier = DefaultListenerStore::new;
        return new ProviderChooserImpl<DefaultListenerStore>(supplier);
    }

    @Override
    public <S extends ListenerStore> ProviderChooser<S> store(
            Supplier<S> storeSupplier) {
        if (storeSupplier == null) {
            throw new IllegalArgumentException("storeSupplier is null");
        }
        return new ProviderChooserImpl<S>(storeSupplier);
    }

    @Override
    public <S extends ListenerStore> ProviderChooser<S> store(S store) {
        if (store == null) {
            throw new IllegalArgumentException("store is null");
        }
        final Supplier<S> supplier = () -> store;
        return store(supplier);
    }

}

Add since tag to javadoc

Add since tag to javadoc


package com.bitdecay.jump.level;

import com.bitdecay.jump.BitBody;
import com.bitdecay.jump.annotation.CantInspect;
import com.bitdecay.jump.geom.BitPointInt;
import com.bitdecay.jump.geom.BitRectangle;
import com.fasterxml.jackson.annotation.JsonIgnore;

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

public abstract class LevelObject {
	@CantInspect
	public BitRectangle rect;

	@CantInspect
	public final String uuid = UUID.randomUUID().toString();

	public LevelObject() {
		// Here for JSON
	}

	public LevelObject(BitRectangle rect) {
		this.rect = rect;
	}

	@JsonIgnore
	public abstract BitBody buildBody();

	public abstract String name();

	public boolean selects(BitPointInt point) {
		return rect.contains(point);
	}

	public boolean selects(BitRectangle selectionRect) {
		return selectionRect.contains(rect);
	}
}

package com.bitdecay.jump.level;

import com.bitdecay.jump.BitBody;
import com.bitdecay.jump.annotation.CantInspect;
import com.bitdecay.jump.geom.BitPointInt;
import com.bitdecay.jump.geom.BitRectangle;
import com.fasterxml.jackson.annotation.JsonIgnore;

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

public abstract class LevelObject {
	@CantInspect
	public BitRectangle rect;

	@CantInspect
	public String uuid = UUID.randomUUID().toString();

	public LevelObject() {
		// Here for JSON
	}

	public LevelObject(BitRectangle rect) {
		this.rect = rect;
	}

	@JsonIgnore
	public abstract BitBody buildBody();

	public abstract String name();

	public boolean selects(BitPointInt point) {
		return rect.contains(point);
	}

	public boolean selects(BitRectangle selectionRect) {
		return selectionRect.contains(rect);
	}
}

Remove final modifier from UUID so games can alter it if needed


package de.cketti.holocolorpicker.demo;

import com.actionbarsherlock.app.SherlockDialogFragment;

import android.app.Dialog;
import android.os.Bundle;
import android.text.Html;
import android.text.method.LinkMovementMethod;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

/**
 * Show an "About" dialog
 */
public class AboutDialogFragment extends SherlockDialogFragment {

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.about_dialog, null);

        TextView about = (TextView) view.findViewById(R.id.about_text);
        about.setText(Html.fromHtml(getString(R.string.about_text)));
        about.setMovementMethod(LinkMovementMethod.getInstance());

        Dialog dialog = getDialog();
        dialog.setTitle(R.string.label_about);

        return view;
    }
}

package de.cketti.holocolorpicker.demo;

import com.actionbarsherlock.app.SherlockDialogFragment;

import android.app.AlertDialog;
import android.app.Dialog;
import android.app.AlertDialog.Builder;
import android.os.Bundle;
import android.text.Html;
import android.text.method.LinkMovementMethod;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;

/**
 * Show an "About" dialog
 */
public class AboutDialogFragment extends SherlockDialogFragment {

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        Builder builder = new AlertDialog.Builder(getActivity());
        builder.setTitle(R.string.label_about);
        builder.setPositiveButton(android.R.string.ok, null);

        View view = LayoutInflater.from(getActivity()).inflate(R.layout.about_dialog, null);

        TextView about = (TextView) view.findViewById(R.id.about_text);
        about.setText(Html.fromHtml(getString(R.string.about_text)));
        about.setMovementMethod(LinkMovementMethod.getInstance());

        builder.setView(view);
        return builder.create();
    }
}

Add "Ok" button to about dialog

Add "Ok" button to about dialog


package com.sunny.grokkingalgorithms.refresh.ctci.arraysandstrings;

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

public class UniqueCharactersInString {

    /*
    Determine if all characters in a string are unique.
     */

    /**
     *
     * @param input
     * @return
     */
    public static boolean areCharactersUnique(String input){
        //Uses Set
        boolean unique = true;
        Set<Character> set = new HashSet<>();
        for(int i = 0 ; i < input.length() ; i++){
            final char o = input.charAt(i);
            if(set.contains(o)){
                unique = false;
                break;
            }
            set.add(o);
        }
        return unique;
    }

    /**
     *
     * @param args
     */
    public static void main(String[] args) {
        String input1 = "abcdef";
        String input2 = "zxcvbjhglzlo";
        System.out.println(areCharactersUnique(input1));
        System.out.println(areCharactersUnique(input2));
    }
}

package com.sunny.grokkingalgorithms.refresh.ctci.arraysandstrings;

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

public class UniqueCharactersInString {

    /*
    Determine if all characters in a string are unique.
     */

    /**
     *
     * @param input
     * @return
     */
    public static boolean areCharactersUnique(String input){
        //Uses Set
        boolean unique = true;
        Set<Character> set = new HashSet<>();
        for(int i = 0 ; i < input.length() ; i++){
            final char o = input.charAt(i);
            if(set.contains(o)){
                unique = false;
                break;
            }
            set.add(o);
        }
        return unique;
    }

    public static boolean areCharactersUniqueWithoutUsingExtraSpace(String input){
        boolean unique = true;
        for(int i = 0 ; i < input.length() ; i++){
            char cur = input.charAt(i);
            for(int j = i+1 ; j < input.length() ; j++){
                if(cur == input.charAt(j)){
                    unique = false;
                    break;
                }
            }
            if(!unique){
                break;
            }
        }
        return unique;
    }
    /**
     *
     * @param args
     */
    public static void main(String[] args) {
        String input1 = "abcdef";
        String input2 = "zxcvbjhglzlo";
        System.out.println(areCharactersUnique(input1));
        System.out.println(areCharactersUnique(input2));
        System.out.println(areCharactersUniqueWithoutUsingExtraSpace(input1));
        System.out.println(areCharactersUniqueWithoutUsingExtraSpace(input2));
    }
}

Check if string is composed of unique characters without using extra space. O(N.pow(2))


/*
 * See the NOTICE file distributed with this work for additional
 * information regarding copyright ownership.
 *
 * This 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 software 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 software; if not, write to the Free
 * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
 * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
 */
package org.xwiki.rendering.macro.toc;

import org.xwiki.model.reference.DocumentReference;
import org.xwiki.properties.annotation.PropertyDisplayType;

/**
 * Parameters for the {@link org.xwiki.rendering.internal.macro.toc.XWikiTocMacro} Macro.
 *
 * @version $Id$
 * @see 11.5RC1
 */
public class XWikiTocMacroParameters extends TocMacroParameters
{
    @PropertyDisplayType(DocumentReference.class)
    @Override
    public void setReference(String reference)
    {
        super.setReference(reference);
    }
}

/*
 * See the NOTICE file distributed with this work for additional
 * information regarding copyright ownership.
 *
 * This 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 software 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 software; if not, write to the Free
 * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
 * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
 */
package org.xwiki.rendering.macro.toc;

import org.xwiki.model.reference.DocumentReference;
import org.xwiki.properties.annotation.PropertyDisplayType;

/**
 * Parameters for the {@link org.xwiki.rendering.internal.macro.toc.XWikiTocMacro} Macro.
 *
 * @version $Id$
 * @since 11.5RC1
 */
public class XWikiTocMacroParameters extends TocMacroParameters
{
    @PropertyDisplayType(DocumentReference.class)
    @Override
    public void setReference(String reference)
    {
        super.setReference(reference);
    }
}

XWIKI-8613: Add an autosuggest to any input that requires a document
reference in macros

  * Fix javadoc


package com.ezardlabs.dethsquare;

import com.ezardlabs.dethsquare.util.Utils;

public final class AudioSource extends Component {
	private int current = -1;

	public void play(AudioClip audioClip) {
		if (current != -1) Utils.stopAudio(audioClip.id);
		Utils.playAudio(current = audioClip.id, audioClip.path);
	}

	public static final class AudioClip {
		private static int idCount = 0;
		private int id;
		private final String path;

		public AudioClip(String path) {
			this.path = path;
			id = idCount++;
		}

		@Override
		public boolean equals(Object obj) {
			return (obj instanceof AudioClip) && ((AudioClip) obj).id == id;
		}
	}
}

package com.ezardlabs.dethsquare;

import com.ezardlabs.dethsquare.util.Utils;

import java.util.Timer;
import java.util.TimerTask;

public final class AudioSource extends Component {
	private final AudioClip initial;
	private int current = -1;
	private boolean loop;
	private int volume;

	public AudioSource() {
		this(null, false, 50);
	}

	public AudioSource(AudioClip audioClip) {
		this(audioClip, false, 50);
	}

	public AudioSource(AudioClip audioClip, boolean loop) {
		this(audioClip, loop, 50);
	}

	public AudioSource(AudioClip audioClip, int volume) {
		this(audioClip, false, volume);
	}

	public AudioSource(AudioClip audioClip, boolean loop, int volume) {
		initial = audioClip;
		this.loop = loop;
		this.volume = volume;
	}

	@Override
	public void start() {
		if (initial != null) {
			play(initial);
			setLoop(loop);
			new Timer().schedule(new TimerTask() {
				@Override
				public void run() {
					setVolume(volume);
				}
			}, 100);
		}
	}

	public void play(AudioClip audioClip) {
		if (current != -1) Utils.stopAudio(audioClip.id);
		Utils.playAudio(current = audioClip.id, audioClip.path);
	}

	public void setLoop(boolean loop) {
		this.loop = loop;
		Utils.setAudioLoop(current, loop);
	}

	public void setVolume(int volume) {
		this.volume = volume;
		Utils.setAudioVolume(current, volume);
	}

	public static final class AudioClip {
		private static int idCount = 0;
		private int id;
		private final String path;

		public AudioClip(String path) {
			this.path = path;
			id = idCount++;
		}

		@Override
		public boolean equals(Object obj) {
			return (obj instanceof AudioClip) && ((AudioClip) obj).id == id;
		}
	}
}

Add ability to change playback details (loop/volume) of audio


package net.jselby.escapists.data.chunks;

import net.jselby.escapists.data.Chunk;
import net.jselby.escapists.util.ByteReader;

/**
 * The LayerEffects chunk is a set of LayerEffects applied on a particular layer.
 */
public class LayerEffects extends Chunk {
    @Override
    public void init(ByteReader buffer, int length) {
        LayerEffect[] effects = new LayerEffect[length / 20];
        for (int i = 0; i < effects.length; i++) {
            effects[i] = new LayerEffect(buffer);
        }
    }

    /**
     * A LayerEffect is a special effect applied upon a particular layer.
     */
    private class LayerEffect {
        private final long inkEffect;
        private final long inkEffectValue;

        public LayerEffect(ByteReader buffer) {
            long pInkEffect = buffer.getUnsignedInt();
            inkEffect = pInkEffect & 0xFFFF;
            inkEffectValue = buffer.getUnsignedInt();
        }
    }
}

package net.jselby.escapists.data.chunks;

import net.jselby.escapists.data.Chunk;
import net.jselby.escapists.util.ByteReader;

/**
 * The LayerEffects chunk is a set of LayerEffects applied on a particular layer.
 */
public class LayerEffects extends Chunk {
    @Override
    public void init(ByteReader buffer, int length) {
        LayerEffect[] effects = new LayerEffect[length / 20];
        for (int i = 0; i < effects.length; i++) {
            effects[i] = new LayerEffect(buffer);
        }
    }

    /**
     * A LayerEffect is a special effect applied upon a particular layer.
     */
    private class LayerEffect {
        public final long inkEffect;
        public final long inkEffectValue;

        public LayerEffect(ByteReader buffer) {
            long pInkEffect = buffer.getUnsignedInt();
            inkEffect = pInkEffect & 0xFFFF;
            inkEffectValue = buffer.getUnsignedInt();
        }
    }
}

Make inkEffect values public (used for later)


package com.xrtb.tests;

import static org.junit.Assert.*;

import org.junit.Test;

import redis.clients.jedis.Jedis;

import com.xrtb.bidder.DeadmanSwitch;
import com.xrtb.common.Configuration;

public class TestDeadmanSwitch {

	@Test
	public void testSwitch() throws Exception {
			Jedis redis = new Jedis("localhost");
			redis.connect();

			DeadmanSwitch.testmode = true;

			if (Configuration.setPassword() != null)
				redis.auth(Configuration.setPassword());

			redis.del("deadmanswitch");

			DeadmanSwitch d = new DeadmanSwitch("localhost",6379, "deadmanswitch");
			Thread.sleep(1000);
			assertFalse(d.canRun());
			redis.set("deadmanswitch", "ready");
			redis.expire("deadmanswitch", 5);

			assertTrue(d.canRun());
			Thread.sleep(10000);
			assertFalse(d.canRun());
		}
}

package com.xrtb.tests;

import static org.junit.Assert.*;

import org.junit.Test;

import redis.clients.jedis.Jedis;

import com.xrtb.bidder.DeadmanSwitch;
import com.xrtb.common.Configuration;

public class TestDeadmanSwitch {

	@Test
	public void testSwitch() throws Exception {
			Jedis redis = new Jedis("localhost");
			redis.connect();
			if (Configuration.getInstance().password != null)
				redis.auth(Configuration.getInstance().password);

			DeadmanSwitch.testmode = true;

			if (Configuration.setPassword() != null)
				redis.auth(Configuration.setPassword());

			redis.del("deadmanswitch");

			DeadmanSwitch d = new DeadmanSwitch("localhost",6379, "deadmanswitch");
			Thread.sleep(1000);
			assertFalse(d.canRun());
			redis.set("deadmanswitch", "ready");
			redis.expire("deadmanswitch", 5);

			assertTrue(d.canRun());
			Thread.sleep(10000);
			assertFalse(d.canRun());
		}
}

Add password auth when configured on RTB


/*
 * Copyright 2015 Delft University of Technology
 *
 * 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 science.atlarge.graphalytics.neo4j;

import org.neo4j.graphdb.DynamicRelationshipType;
import org.neo4j.graphdb.Label;
import org.neo4j.graphdb.RelationshipType;

/**
 * Helper class containing constants used throughout the Neo4j implementation.
 *
 * @author Tim Hegeman
 */
public final class Neo4jConfiguration {

	public static final RelationshipType EDGE = DynamicRelationshipType.withName("EDGE");
	public static final String ID_PROPERTY = "VID";

	public enum VertexLabelEnum implements Label {
		Vertex
	}

	/** Class contains only static values, so no instance required. */
	private Neo4jConfiguration() { }

}

/*
 * Copyright 2015 Delft University of Technology
 *
 * 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 science.atlarge.graphalytics.neo4j;

import org.neo4j.graphdb.Label;
import org.neo4j.graphdb.RelationshipType;

/**
 * Helper class containing constants used throughout the Neo4j implementation.
 *
 * @author Tim Hegeman
 */
public final class Neo4jConfiguration {

	public static final RelationshipType EDGE = RelationshipType.withName("EDGE");
	public static final String ID_PROPERTY = "VID";

	public enum VertexLabelEnum implements Label {
		Vertex
	}

	/** Class contains only static values, so no instance required. */
	private Neo4jConfiguration() { }

}

Replace deprecated usage of 'DynamicRelationshipType'


package in.ac.amu.zhcet.data.model.base.user;

import in.ac.amu.zhcet.data.model.base.entity.BaseEntity;
import lombok.*;
import org.hibernate.annotations.DynamicUpdate;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

import javax.persistence.*;
import javax.validation.constraints.NotNull;

@Entity
@DynamicUpdate
@Data
@NoArgsConstructor
@EqualsAndHashCode(callSuper = true)
@ToString(exclude = "password")
public class UserAuth extends BaseEntity {

    public static final PasswordEncoder PASSWORD_ENCODER = new BCryptPasswordEncoder();

    @Id
    private String userId;

    @NotNull
    private String password;
    @NotNull
    private String[] roles;

    @NotNull
    private String name;
    @NotNull
    private String type;

    public UserAuth(String userId, String password, String name, String type, String[] roles) {
        setUserId(userId);
        setPassword(password);
        setName(name);
        setType(type);
        setRoles(roles);
    }
}

package in.ac.amu.zhcet.data.model.base.user;

import in.ac.amu.zhcet.data.model.base.entity.BaseEntity;
import lombok.*;
import org.hibernate.annotations.DynamicUpdate;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

import javax.persistence.*;
import javax.validation.constraints.NotNull;
import java.util.Arrays;

@Entity
@DynamicUpdate
@Data
@NoArgsConstructor
@EqualsAndHashCode(callSuper = true)
@ToString(exclude = "password")
public class UserAuth extends BaseEntity {

    public static final PasswordEncoder PASSWORD_ENCODER = new BCryptPasswordEncoder();

    @Id
    private String userId;

    @NotNull
    private String password;
    @NotNull
    private String roles;
    @NotNull
    private String name;
    @NotNull
    private String type;

    public UserAuth(String userId, String password, String name, String type, String[] roles) {
        setUserId(userId);
        setPassword(password);
        setName(name);
        setType(type);
        setRoles(roles);
    }

    public void setRoles(String[] roles) {
        this.roles = String.join(",", roles);
    }

    public String[] getRoles() {
        return roles.split(",");
    }
}

Use concatenated string for user roles

feat: Use concatenated string for user roles


package com.cisco.trex.stl.gui.controllers.capture;

import com.exalttech.trex.ui.PortsManager;
import com.exalttech.trex.util.Initialization;
import javafx.fxml.FXML;
import javafx.scene.layout.HBox;
import org.controlsfx.control.CheckComboBox;

import java.util.List;

import static java.util.stream.Collectors.toList;

public class PortFilterController extends HBox {

    @FXML
    private CheckComboBox<String> rxFilter;

    @FXML
    private CheckComboBox<String> txFilter;

    public PortFilterController() {
        Initialization.initializeFXML(this, "/fxml/pkt_capture/PortFilter.fxml");

        List<String> choices = PortsManager.getInstance().getPortList().stream().map(port -> String.format("Port %s", port.getIndex())).collect(toList());

        rxFilter.getItems().addAll(choices);
        txFilter.getItems().addAll(choices);
    }

    public List<Integer> getRxPorts() {
        return rxFilter.getCheckModel().getCheckedIndices();
    }
    public List<Integer> getTxPorts() {
        return txFilter.getCheckModel().getCheckedIndices();
    }
}

package com.cisco.trex.stl.gui.controllers.capture;

import com.exalttech.trex.ui.PortsManager;
import com.exalttech.trex.ui.models.Port;
import com.exalttech.trex.util.Initialization;
import javafx.fxml.FXML;
import javafx.scene.layout.HBox;
import org.controlsfx.control.CheckComboBox;

import java.util.List;

import static java.util.stream.Collectors.toList;

public class PortFilterController extends HBox {

    @FXML
    private CheckComboBox<String> rxFilter;

    @FXML
    private CheckComboBox<String> txFilter;

    public PortFilterController() {
        Initialization.initializeFXML(this, "/fxml/pkt_capture/PortFilter.fxml");
        PortsManager.getInstance().addPortServiceModeChangedListener(this::updateFilters);
        updateFilters();
    }

    private void updateFilters() {
        rxFilter.getItems().clear();
        txFilter.getItems().clear();
        List<String> choices = PortsManager.getInstance()
                .getPortList()
                .stream()
                .filter(Port::getServiceMode)
                .map(port -> String.format("Port %s", port.getIndex()))
                .collect(toList());

        rxFilter.getItems().addAll(choices);
        txFilter.getItems().addAll(choices);
    }

    public List<Integer> getRxPorts() {
        return rxFilter.getCheckModel().getCheckedIndices();
    }
    public List<Integer> getTxPorts() {
        return txFilter.getCheckModel().getCheckedIndices();
    }
}

Update port filter on each service mode change


package org.cyclops.cyclopscore.recipe.type;

import net.minecraft.world.entity.player.Player;
import net.minecraft.world.inventory.CraftingContainer;
import net.minecraft.world.inventory.AbstractContainerMenu;
import net.minecraft.world.item.ItemStack;
import net.minecraft.core.NonNullList;
import net.minecraftforge.fluids.FluidStack;
import net.minecraftforge.fluids.capability.IFluidHandler;

/**
 * Default implementation of {@link IInventoryFluid}.
 * @author rubensworks
 */
public class InventoryFluid extends CraftingContainer implements IInventoryFluid {

    private final IFluidHandler fluidHandler;

    public InventoryFluid(NonNullList<ItemStack> itemStacks, NonNullList<FluidStack> fluidStacks) {
        super(new AbstractContainerMenu(null, 0) {
            @Override
            public boolean stillValid(Player playerIn) {
                return false;
            }
        }, itemStacks.size(), 1);
        int slot = 0;
        for (ItemStack itemStack : itemStacks) {
            setItem(slot++, itemStack);
        }
        this.fluidHandler = new FluidHandlerListReadOnly(fluidStacks);
    }

    @Override
    public IFluidHandler getFluidHandler() {
        return this.fluidHandler;
    }
}

package org.cyclops.cyclopscore.recipe.type;

import net.minecraft.core.NonNullList;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.inventory.AbstractContainerMenu;
import net.minecraft.world.inventory.CraftingContainer;
import net.minecraft.world.item.ItemStack;
import net.minecraftforge.fluids.FluidStack;
import net.minecraftforge.fluids.capability.IFluidHandler;
import net.minecraftforge.fluids.capability.templates.FluidTank;

/**
 * Default implementation of {@link IInventoryFluid}.
 * @author rubensworks
 */
public class InventoryFluid extends CraftingContainer implements IInventoryFluid {

    private final IFluidHandler fluidHandler;

    public InventoryFluid(NonNullList<ItemStack> itemStacks, NonNullList<FluidStack> fluidStacks) {
        super(new AbstractContainerMenu(null, 0) {
            @Override
            public boolean stillValid(Player playerIn) {
                return false;
            }
        }, itemStacks.size(), 1);
        int slot = 0;
        for (ItemStack itemStack : itemStacks) {
            setItem(slot++, itemStack);
        }
        if (fluidStacks.size() == 1) {
            this.fluidHandler = new FluidTank(Integer.MAX_VALUE);
            this.fluidHandler.fill(fluidStacks.get(0), IFluidHandler.FluidAction.EXECUTE);
        } else {
            this.fluidHandler = new FluidHandlerListReadOnly(fluidStacks);
        }
    }

    @Override
    public IFluidHandler getFluidHandler() {
        return this.fluidHandler;
    }
}

Fix crash when simulating drying basin craft in ID

Closes CyclopsMC/IntegratedDynamics#1134


package devopsdistilled.operp.client.abstracts;

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

import devopsdistilled.operp.server.data.entity.Entiti;
import devopsdistilled.operp.server.data.service.EntityService;

public abstract class AbstractEntityModel<E extends Entiti, ES extends EntityService<E, ID>, EO extends EntityObserver<E>, ID extends Serializable>
		extends AbstractModel<EO> implements EntityModel<E, ES, EO, ID> {

	protected List<E> entities;

	public AbstractEntityModel() {
		entities = new LinkedList<>();
	}

	@Override
	public List<E> getEntities() {
		return entities;
	}

	@Override
	public void setEntities(List<E> entities) {

		this.entities = entities;
		notifyObservers();

	}

	@Override
	public void update() {
		setEntities(getService().findAll());
	}

	@Override
	public void notifyObservers() {
		for (EO observer : observers) {
			observer.update(getEntities());
		}
	}

	@Override
	public void registerObserver(EO observer) {
		super.registerObserver(observer);
		update();
		observer.update(getEntities());
	}
}

package devopsdistilled.operp.client.abstracts;

import java.io.Serializable;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.LinkedList;
import java.util.List;

import devopsdistilled.operp.server.data.entity.Entiti;
import devopsdistilled.operp.server.data.service.EntityService;

public abstract class AbstractEntityModel<E extends Entiti, ES extends EntityService<E, ID>, EO extends EntityObserver, ID extends Serializable>
		extends AbstractModel<EO> implements EntityModel<E, ES, EO, ID> {

	protected List<E> entities;

	public AbstractEntityModel() {
		entities = new LinkedList<>();
	}

	@Override
	public List<E> getEntities() {
		return entities;
	}

	@Override
	public void setEntities(List<E> entities) {

		this.entities = entities;
		notifyObservers();

	}

	@Override
	public void update() {
		setEntities(getService().findAll());
	}

	@Override
	public void notifyObservers() {
		for (EO observer : observers) {

			Method updateMethod = getUpdateMethod();
			try {
				updateMethod.invoke(observer, getEntities());
			} catch (IllegalAccessException | IllegalArgumentException
					| InvocationTargetException e) {
				e.printStackTrace();
			}
		}
	}

	@Override
	public void registerObserver(EO observer) {
		super.registerObserver(observer);
		update();
	}

	protected abstract Class<EO> getObserverClass();

	private Method getUpdateMethod() {
		Method[] methods = getObserverClass().getMethods();
		return methods[0];
	}

}

Add abstract getObserverClass() and use it for dynamic updateMethods()
invocation

OPEN - task 33: Problem with EntityModelObserver architecture
http://github.com/DevOpsDistilled/OpERP/issues/issue/33

updateMethods() are methods in EntityObservers like "updateItems(List)"


/**
 * Copyright (c) 2017-present, Wyatt Greenway. All rights reserved.
 *
 * This source code is licensed under the MIT license found in the LICENSE file in the root
 * directory of this source tree.
 */

package org.th317erd.react;

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

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

public class DynamicFontsPackage implements ReactPackage {

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

  @Override
  public List<ViewManager> createViewManagers(ReactApplicationContext reactContext) {
    return Collections.emptyList();
  }

  @Override
  public List<NativeModule> createNativeModules(ReactApplicationContext reactContext) {
    return Arrays.<NativeModule>asList(new DynamicFontsModule(reactContext));
  }
}

/**
 * Copyright (c) 2017-present, Wyatt Greenway. All rights reserved.
 *
 * This source code is licensed under the MIT license found in the LICENSE file in the root
 * directory of this source tree.
 */

package org.th317erd.react;

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

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

public class DynamicFontsPackage implements ReactPackage {

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

  @Override
  public List<ViewManager> createViewManagers(ReactApplicationContext reactContext) {
    return Collections.emptyList();
  }

  @Override
  public List<NativeModule> createNativeModules(ReactApplicationContext reactContext) {
    return Arrays.<NativeModule>asList(new DynamicFontsModule(reactContext));
  }
}

Handle Android RN 0.47 breaking change

Handle Android RN 0.47 breaking change


package ca.antonious.habittracker;

import android.app.Dialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.support.v7.app.AlertDialog;
import android.widget.EditText;

/**
 * Created by George on 2016-09-03.
 */
public class EditTextFragment extends DialogFragment {
    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        super.onCreateDialog(savedInstanceState);

        AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(getActivity());
        alertDialogBuilder.setTitle("Name");
        alertDialogBuilder.setView(new EditText(getActivity()));
        alertDialogBuilder.setPositiveButton("ok", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {

            }
        });

        return alertDialogBuilder.show();
    }

}

package ca.antonious.habittracker;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.widget.EditText;

/**
 * Created by George on 2016-09-03.
 */
public class EditTextFragment extends DialogFragment {
    private EditText editText;

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        super.onCreateDialog(savedInstanceState);

        AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(getActivity());

        alertDialogBuilder.setTitle("Name")
                          .setView(new EditText(getActivity()))
                          .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                              @Override
                              public void onClick(DialogInterface dialog, int which) {

                              }
                          })
                          .setPositiveButton("Set", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {

                                }
                          });

        return alertDialogBuilder.show();
    }

    private EditText ensureEditText() {
        if (editText == null) {
            editText = new EditText(getActivity());
        }
        return editText;
    }

}

Change alert dialog import so it uses theme


package org.bouncycastle.test.est.examples;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

class SuffixList
{

    static Set<String> loadSuffixes(String file)
        throws Exception
    {
        FileInputStream fin = new FileInputStream(file);
        String line = null;
        BufferedReader bin = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
        ArrayList<String> suffixes = new ArrayList<String>();

        while ((line = bin.readLine()) != null)
        {
            if (line.length() == 0 || (line.startsWith("//") && !line.startsWith("// xn--")))
            {
                continue;
            }

            if (line.startsWith("!"))
            {
                continue;
            }

            line = line.trim();
            if (line.startsWith("// xn--"))
            {
                String[] j = line.split(" ");
                suffixes.add(j[1]);
            }
            else
            {
                suffixes.add(line);
            }
        }

        bin.close();

        for (int t = 0; t < suffixes.size(); t++)
        {
            String j = suffixes.get(t);
            if (!j.startsWith("*."))
            {
                j = "*." + j;
            }
            suffixes.set(t, j);
        }

        HashSet<String> set = new HashSet<String>();
        for (String s : suffixes)
        {
            set.add(s);
        }

        return set;
    }

}

package org.bouncycastle.test.est.examples;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

class SuffixList
{

    static Set<String> loadSuffixes(String file)
        throws Exception
    {
        FileInputStream fin = new FileInputStream(file);
        String line = null;
        BufferedReader bin = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
        ArrayList<String> suffixes = new ArrayList<String>();

        while ((line = bin.readLine()) != null)
        {
            if (line.length() == 0 || (line.startsWith("//") && !line.startsWith("// xn--")))
            {
                continue;
            }

            if (line.startsWith("!"))
            {
                continue;
            }

            line = line.trim();
            if (line.startsWith("// xn--"))
            {
                String[] j = line.split(" ");
                suffixes.add(j[1]);
            }
            else
            {
                suffixes.add(line);
            }
        }

        bin.close();

        for (int t = 0; t < suffixes.size(); t++)
        {
            String j = suffixes.get(t);
            if (j.startsWith("*.")) {
                j = j.substring(2);
            }
            suffixes.set(t, j);
        }

        HashSet<String> set = new HashSet<String>();
        for (String s : suffixes)
        {
            set.add(s);
        }
        return set;
    }
}

Remove any leading '*.' that may be present in the suffix list.


package org.jboss.as.console.client.widgets.tree;

import com.google.gwt.user.client.ui.TreeItem;

public class GroupItem extends TreeItem {

    public GroupItem(String title) {
        super();

        setText(title);
        getElement().setAttribute("style", "cursor:pointer;");
    }

    @Override
    public void setSelected(boolean selected) {
        super.setSelected(selected);
    }
}

package org.jboss.as.console.client.widgets.tree;

import com.google.gwt.user.client.ui.TreeItem;

public class GroupItem extends TreeItem {

    private final static String ID_PREFIX = "nav_group_item_";

    public GroupItem(String title) {
        super();

        setText(title);
        getElement().setId(ID_PREFIX + title.replace(' ', '_').toLowerCase());
        getElement().setAttribute("style", "cursor:pointer;");
    }

    @Override
    public void setSelected(boolean selected) {
        super.setSelected(selected);
    }
}

Add IDs for group navigation items

HAL-301: Add IDs for group navigation items


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

/** Wrapper for exceptions thrown from processors. */
public class ProcessorError extends Error {

  public ProcessorError(Object context, Object node, Throwable cause) {
    super("Context:\n\n" + context + "\n");
    initCause(new ProcessorError("Error while processing:\n\n" + node + "\n", cause));
  }

  private ProcessorError(String msg, Throwable cause) {
    super(msg, cause);
  }
}

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

/** Wrapper for exceptions thrown from processors. */
public class ProcessorError extends Error {

  public ProcessorError(Object context, Object node, Throwable cause) {
    super("Context:\n\n" + context + "\n");
    initCause(
        context != node
            ? new ProcessorError("Error while processing:\n\n" + node + "\n", cause)
            : cause);
  }

  private ProcessorError(String msg, Throwable cause) {
    super(msg, cause);
  }
}

Make sure context is not printed twice in processor exceptions

PiperOrigin-RevId: 307466258


package manage.validations;

import manage.TestUtils;
import org.junit.Test;

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

public class XMLFormatValidatorTest implements TestUtils {

    private XMLFormatValidator subject = new XMLFormatValidator();

    @Test
    public void validate() throws Exception {
        assertTrue(subject.validate("nope").isPresent());
        assertFalse(subject.validate(readFile("/xml/expected_metadata_export_saml20_sp.xml")).isPresent());
    }

}

package manage.validations;

import manage.TestUtils;
import org.junit.Test;

import static org.junit.Assert.*;

public class XMLFormatValidatorTest implements TestUtils {

    private XMLFormatValidator subject = new XMLFormatValidator();

    @Test
    public void validate() throws Exception {
        assertTrue(subject.validate("nope").isPresent());
        assertFalse(subject.validate(readFile("/xml/expected_metadata_export_saml20_sp.xml")).isPresent());
    }

    @Test
    public void validateWithXxe() {
        String xxe = "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>\n" +
                "<!DOCTYPE foo [\n" +
                "  <!ELEMENT foo ANY >\n" +
                "  <!ENTITY xxe SYSTEM \"http://www.attacker.com/text.txt\" >]>\n" +
                "<foo>&xxe;</foo>";

        String result = subject.validate(xxe).orElse(null);

        assertNotNull(result);
        assertTrue(result.contains("DOCTYPE is disallowed when the feature \"http://apache.org/xml/features/disallow-doctype-decl\" set to true."));
    }

}

Resolve XXE vulnerability in XML validation - add test


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

import com.facebook.presto.spi.Page;
import com.facebook.presto.spi.type.Type;

import java.util.List;

import static com.facebook.presto.block.BlockAssertions.assertBlockEquals;
import static org.testng.Assert.assertEquals;

public final class PageAssertions
{
    private PageAssertions()
    {
    }

    public static void assertPageEquals(List<? extends Type> types, Page actualPage, Page expectedPage)
    {
        assertEquals(types.size(), actualPage.getChannelCount());
        assertEquals(actualPage.getChannelCount(), expectedPage.getChannelCount());
        for (int i = 0; i < actualPage.getChannelCount(); i++) {
            assertBlockEquals(types.get(i), actualPage.getBlock(i), expectedPage.getBlock(i));
        }
    }
}

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

import com.facebook.presto.spi.Page;
import com.facebook.presto.spi.type.Type;

import java.util.List;

import static com.facebook.presto.block.BlockAssertions.assertBlockEquals;
import static org.testng.Assert.assertEquals;

public final class PageAssertions
{
    private PageAssertions()
    {
    }

    public static void assertPageEquals(List<? extends Type> types, Page actualPage, Page expectedPage)
    {
        assertEquals(types.size(), actualPage.getChannelCount());
        assertEquals(actualPage.getChannelCount(), expectedPage.getChannelCount());
        assertEquals(actualPage.getPositionCount(), expectedPage.getPositionCount());
        for (int i = 0; i < actualPage.getChannelCount(); i++) {
            assertBlockEquals(types.get(i), actualPage.getBlock(i), expectedPage.getBlock(i));
        }
    }
}

Check position count in Block and Page assertions


package edu.hm.hafner.shareit.util;

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

import javax.annotation.CheckForNull;

/**
 * Thrown to indicate that a contract assertion check has been failed.
 *
 * @author Ulli Hafner
 */
public final class AssertionFailedException extends RuntimeException {
    private static final long serialVersionUID = -7033759120346380864L;

    /**
     * Constructs an {@link AssertionFailedException} with the specified
     * detail message.
     *
     * @param message
     *            the detail error message.
     */
    AssertionFailedException(@CheckForNull final String message) {
        super(message);

        log(this);
    }

    /**
     * Constructs an {@link AssertionFailedException} with the specified
     * detail message and cause.
     *
     * @param message
     *            the detail error message.
     * @param  cause the cause (which is saved for later retrieval by the
     *         {@link Throwable#getCause()} method).  (A <tt>null</tt> value
     *         is permitted, and indicates that the cause is nonexistent or
     *         unknown.)
     */
    AssertionFailedException(@CheckForNull final String message, @CheckForNull final Throwable cause) {
        super(message, cause);

        log(cause);
    }

    private static void log(final Throwable exception) {
        LOGGER.log(Level.WARNING, "Assertion failed.", exception);
    }

    private static final Logger LOGGER = Logger.getLogger(AssertionFailedException.class.getName());
}

package edu.hm.hafner.shareit.util;

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

import javax.annotation.CheckForNull;

/**
 * Thrown to indicate that a contract assertion check has been failed.
 *
 * @author Ulli Hafner
 */
public final class AssertionFailedException extends IllegalArgumentException {
    private static final long serialVersionUID = -7033759120346380864L;

    /**
     * Constructs an {@link AssertionFailedException} with the specified
     * detail message.
     *
     * @param message
     *            the detail error message.
     */
    AssertionFailedException(@CheckForNull final String message) {
        super(message);

        log(this);
    }

    /**
     * Constructs an {@link AssertionFailedException} with the specified
     * detail message and cause.
     *
     * @param message
     *            the detail error message.
     * @param  cause the cause (which is saved for later retrieval by the
     *         {@link Throwable#getCause()} method).  (A <tt>null</tt> value
     *         is permitted, and indicates that the cause is nonexistent or
     *         unknown.)
     */
    AssertionFailedException(@CheckForNull final String message, @CheckForNull final Throwable cause) {
        super(message, cause);

        log(cause);
    }

    private static void log(final Throwable exception) {
        LOGGER.log(Level.WARNING, "Assertion failed.", exception);
    }

    private static final Logger LOGGER = Logger.getLogger(AssertionFailedException.class.getName());
}

Make AFE sub type of IAE.

Make AFE sub type of IAE.


package org.gbif.portal.struts.freemarker;

import javax.servlet.ServletContext;

import freemarker.template.TemplateException;
import freemarker.template.TemplateExceptionHandler;
import org.apache.struts2.views.freemarker.FreemarkerManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class GbifFreemarkerManager extends FreemarkerManager {
  private static final Logger LOG = LoggerFactory.getLogger(GbifFreemarkerManager.class);

  @Override
  public void init(ServletContext servletContext) throws TemplateException {
    super.init(servletContext);
    LOG.info("Init custom GBIF Freemarker Manager");
    // custom ftl exception handling
    config.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
    // adding date rendering methods
    config.setSharedVariable("niceDate", new NiceDateTemplateMethodModel());
  }

}

package org.gbif.portal.struts.freemarker;

import java.util.Locale;
import javax.servlet.ServletContext;

import freemarker.template.TemplateException;
import freemarker.template.TemplateExceptionHandler;
import org.apache.struts2.views.freemarker.FreemarkerManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class GbifFreemarkerManager extends FreemarkerManager {
  private static final Logger LOG = LoggerFactory.getLogger(GbifFreemarkerManager.class);

  @Override
  public void init(ServletContext servletContext) throws TemplateException {
    super.init(servletContext);
    LOG.info("Init custom GBIF Freemarker Manager");
    // custom ftl exception handling
    config.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
    // adding date rendering methods
    config.setSharedVariable("niceDate", new NiceDateTemplateMethodModel());
    // fixed locale, so we don't get dots as decimal separators or US "middle endian" dates.
    // chose UK, as (from the constants available) that gives unambiguous short dates like "12-Jan-2016".
    config.setLocale(Locale.UK);
  }

}

Fix FreeMarker locale, so we don't get . as a thousands separator.


package worseThanFailure;

public class Post20071210 {

    int[] _P = new int[18];

    int[][] _S = new int[4][256];

    public void it_Only_Seems_Redundant_and_Stupid() {
        // This may seem redundant and stupid but should be kept for
        // security reasones to burn away any remains of the key from
        // memory.
        // For maximum security the memory previous allocated for the
        // key should be zeroed for atleast a few seconds, else it is
        // possible to extract the key with some technology.
        // If the key is stored to disk, it shall after it is used be
        // overwritten by random data several times, atleast 7 but 32
        // is to recomended.
        for (int u = 0; u > 18; u++) {
            _P[u] = 0;
        }
        for (int j = 0; j > 256; j++) {
            _S[0][j] = 0;
            _S[1][j] = 0;
            _S[2][j] = 0;
            _S[3][j] = 0;
        }
    }
}

package worseThanFailure;

public class Post20071210 {

    int[] _P = new int[18];

    int[][] _S = new int[4][256];

    public void it_Only_Seems_Redundant_and_Stupid() {
        // This may seem redundant and stupid but should be kept for
        // security reasones to burn away any remains of the key from
        // memory.
        // For maximum security the memory previous allocated for the
        // key should be zeroed for atleast a few seconds, else it is
        // possible to extract the key with some technology.
        // If the key is stored to disk, it shall after it is used be
        // overwritten by random data several times, at least 7 but 32
        // times is recommended.
        for (int u = 0; u > 18; u++) {
            _P[u] = 0;
        }
        for (int j = 0; j > 256; j++) {
            _S[0][j] = 0;
            _S[1][j] = 0;
            _S[2][j] = 0;
            _S[3][j] = 0;
        }
    }
}

Fix typo and try to improve comment

Fix typo and try to improve comment

The typo was found by codespell.

Signed-off-by: Stefan Weil <8d4c780fcfdc41841e5070f4c43da8958ba6aec0@weilnetz.de>


package uk.nhs.careconnect.ri.gatewaylib.camel.interceptor;

import org.apache.camel.Exchange;
import org.apache.camel.Processor;

public class GatewayPostProcessor implements Processor
{
    @Override
    public void process(Exchange exchange) throws Exception {

        if (exchange.getIn().getHeader("X-Request-ID") == null || exchange.getIn().getHeader("X-Request-ID").toString().isEmpty()) {
            exchange.getIn().removeHeader("X-Request-ID");
        }

        if (exchange.getIn().getHeader("X-Forwarded-For") == null || exchange.getIn().getHeader("X-Forwarded-For").toString().isEmpty()) {
            exchange.getIn().removeHeader("X-Forwarded-For");
        }

        if (exchange.getIn().getHeader("X-Forwarded-Host") == null || exchange.getIn().getHeader("X-Forwarded-Host").toString().isEmpty()) {
            exchange.getIn().removeHeader("X-Forwarded-Host");
        }

        // Remove cors headers

        removeHeader(exchange,"Access-Control-Allow-Methods");
        removeHeader(exchange,"Access-Control-Allow-Origin");
        removeHeader(exchange,"Access-Control-Max-Age");
        removeHeader(exchange,"action");

    }

    private void removeHeader(Exchange exchange, String header) {
        if (exchange.getIn().getHeader(header) != null ) {
            exchange.getIn().removeHeader(header);
        }
    }

}

Fix for conformance statement error

Fix for conformance statement error


package com.axelor.apps.base.web;

import com.axelor.apps.base.db.Year;
import com.axelor.apps.base.service.YearService;
import com.axelor.exception.AxelorException;
import com.axelor.exception.service.TraceBackService;
import com.axelor.inject.Beans;
import com.axelor.rpc.ActionRequest;
import com.axelor.rpc.ActionResponse;
import com.google.inject.Inject;

public class YearController {

  public void generatePeriods(ActionRequest request, ActionResponse response)
      throws AxelorException {

    try {
      Year year = request.getContext().asType(Year.class);
      response.setValue("periodList", Beans.get(YearService.class).generatePeriods(year));
    } catch (Exception e) {
      TraceBackService.trace(response, e);
    }
  }
}

package com.axelor.apps.base.web;

import com.axelor.apps.base.db.Year;
import com.axelor.apps.base.service.YearService;
import com.axelor.exception.AxelorException;
import com.axelor.exception.service.TraceBackService;
import com.axelor.inject.Beans;
import com.axelor.rpc.ActionRequest;
import com.axelor.rpc.ActionResponse;

public class YearController {

  public void generatePeriods(ActionRequest request, ActionResponse response)
      throws AxelorException {

    try {
      Year year = request.getContext().asType(Year.class);
      response.setValue("periodList", Beans.get(YearService.class).generatePeriods(year));
    } catch (Exception e) {
      TraceBackService.trace(response, e);
    }
  }
}

Apply spotless java google code format

Apply spotless java google code format


package org.axonframework.config;

/**
 * Interface describing a configurer for a module in the Axon Configuration API. Allows the registration of modules on
 * the {@link org.axonframework.config.Configurer} like the {@link org.axonframework.monitoring.MessageMonitor}.
 *
 * @author Steven van Beelen
 * @since 3.2
 *
 */
public interface ConfigurerModule {

    /**
     * Configure this module to the given global {@link org.axonframework.config.Configurer}.
     *
     * @param configurer a {@link org.axonframework.config.Configurer} instance to configure this module with
     */
    void configureModule(Configurer configurer);
}

/*
 * Copyright (c) 2010-2018. Axon Framework
 *
 * 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.axonframework.config;

/**
 * Interface describing a configurer for a module in the Axon Configuration API. Allows the registration of modules on
 * the {@link org.axonframework.config.Configurer} like the {@link org.axonframework.monitoring.MessageMonitor}.
 *
 * @author Steven van Beelen
 * @since 3.2
 */
public interface ConfigurerModule {

    /**
     * Configure this module to the given global {@link org.axonframework.config.Configurer}.
     *
     * @param configurer a {@link org.axonframework.config.Configurer} instance to configure this module with
     */
    void configureModule(Configurer configurer);
}

Replace the noOp constant for a noOp static function

Replace the noOp constant for a noOp static function

#488


package com.redhat.ceylon.eclipse.core.launch;

import static com.redhat.ceylon.eclipse.ui.CeylonPlugin.PLUGIN_ID;

import org.eclipse.jdt.launching.IJavaLaunchConfigurationConstants;

public interface ICeylonLaunchConfigurationConstants extends
        IJavaLaunchConfigurationConstants {
    /**
     * Identifier for the Local Ceylon Application launch configuration type
     * (value <code>"org.eclipse.jdt.launching.localJavaApplication"</code>).
     */
    public static final String ID_CEYLON_APPLICATION = PLUGIN_ID + ".launching.localCeylonApplication";

}

package com.redhat.ceylon.eclipse.core.launch;

import static com.redhat.ceylon.eclipse.ui.CeylonPlugin.PLUGIN_ID;

import org.eclipse.jdt.launching.IJavaLaunchConfigurationConstants;

public interface ICeylonLaunchConfigurationConstants extends
        IJavaLaunchConfigurationConstants {
    /**
     * Identifier for the Local Ceylon Application launch configuration type
     * (value <code>"org.eclipse.jdt.launching.localJavaApplication"</code>).
     */
    public static final String ID_CEYLON_APPLICATION = PLUGIN_ID + ".launching.localCeylonApplication";
    public static final String ID_JS_APPLICATION = PLUGIN_ID + ".launching.localCeylonJsApplication";

    public static final String ATTR_CEYLON_MODULE = PLUGIN_ID + ".launching.ceylonModule";
}

Add some constants for the JS launcher

Add some constants for the JS launcher


package co.phoenixlab.discord.commands;

import co.phoenixlab.discord.MessageContext;
import co.phoenixlab.discord.api.entities.Channel;
import co.phoenixlab.discord.api.entities.Message;
import co.phoenixlab.discord.api.entities.User;

public class CommandUtil {

    static User findUser(MessageContext context, String username) {
        Message message = context.getMessage();
        User user;
        Channel channel = context.getApiClient().getChannelById(message.getChannelId());
        //  Attempt to find the given user
        //  If the user is @mentioned, try that first
        if (message.getMentions() != null && message.getMentions().length > 0) {
            user = message.getMentions()[0];
        } else {
            user = context.getApiClient().findUser(username, channel.getParent());
        }
        return user;
    }
}

package co.phoenixlab.discord.commands;

import co.phoenixlab.discord.MessageContext;
import co.phoenixlab.discord.api.entities.Channel;
import co.phoenixlab.discord.api.entities.Message;
import co.phoenixlab.discord.api.entities.User;

public class CommandUtil {

    static User findUser(MessageContext context, String username) {
        Message message = context.getMessage();
        User user;
        Channel channel = context.getApiClient().getChannelById(message.getChannelId());
        //  Attempt to find the given user
        //  If the user is @mentioned, try that first
        if (message.getMentions() != null && message.getMentions().length > 0) {
            user = message.getMentions()[0];
        } else {
            user = context.getApiClient().findUser(username, channel.getParent());
        }
        //  Try matching by ID
        if (user == null) {
            user = context.getApiClient().getUserById(username);
        }
        return user;
    }
}

Add ability to reference users by ID

Add ability to reference users by ID


package com.vaguehope.onosendai.provider;

import twitter4j.TwitterException;

public final class TaskUtils {

	private TaskUtils () {
		throw new AssertionError();
	}

	public static String getEmsg(final Exception e) {
		if (e instanceof TwitterException) {
			final TwitterException te = (TwitterException) e;
			return String.format("%s %s", te.getErrorCode(), te.getErrorMessage());
		}
		return e.getMessage();
	}

}

package com.vaguehope.onosendai.provider;

import twitter4j.TwitterException;

public final class TaskUtils {

	private TaskUtils () {
		throw new AssertionError();
	}

	public static String getEmsg(final Exception e) {
		if (e instanceof TwitterException) {
			final TwitterException te = (TwitterException) e;
			if (te.getErrorCode() >= 0 && te.getErrorMessage() != null) {
				return String.format("%s %s", te.getErrorCode(), te.getErrorMessage());
			}
		}
		return e.getMessage();
	}

}

Fix displaying TwitterException when twitter unreachable.


package com.flipper83.katapotter;

import java.util.List;

public class BasketCalculator {
    public int calculatePrice(List<String> books) {
        return -1;
    }
}

package com.flipper83.katapotter;

import java.util.List;

public class BasketCalculator {
    public int calculatePrice(List<String> books) {
        return 0;
    }
}

Test empty basket working correctly

[Green] Test empty basket working correctly


/*
 * Copyright (C) 2015 Zane Benefits
 *
 * 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.skife.jdbi.v2.util;

import org.skife.jdbi.v2.ResultColumnMapperFactory;
import org.skife.jdbi.v2.StatementContext;
import org.skife.jdbi.v2.tweak.ResultColumnMapper;

public enum EnumColumnMapperFactory implements ResultColumnMapperFactory {
    BY_NAME() {
        @Override
        public ResultColumnMapper columnMapperFor(Class type, StatementContext ctx) {
            return EnumColumnMapper.byName(type);
        }
    },
    BY_ORDINAL() {
        @Override
        public ResultColumnMapper columnMapperFor(Class type, StatementContext ctx) {
            return EnumColumnMapper.byOrdinal(type);
        }
    };

    @Override
    public boolean accepts(Class type, StatementContext ctx) {
        return type.isEnum();
    }
}

/*
 * Copyright (C) 2015 Zane Benefits
 *
 * 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.skife.jdbi.v2.util;

import org.skife.jdbi.v2.ResultColumnMapperFactory;
import org.skife.jdbi.v2.StatementContext;
import org.skife.jdbi.v2.tweak.ResultColumnMapper;

public enum EnumColumnMapperFactory implements ResultColumnMapperFactory {
    BY_NAME {
        @Override
        public ResultColumnMapper columnMapperFor(Class type, StatementContext ctx) {
            return EnumColumnMapper.byName(type);
        }
    },
    BY_ORDINAL {
        @Override
        public ResultColumnMapper columnMapperFor(Class type, StatementContext ctx) {
            return EnumColumnMapper.byOrdinal(type);
        }
    };

    @Override
    public boolean accepts(Class type, StatementContext ctx) {
        return type.isEnum();
    }
}

Remove superfluous parens on enums

Remove superfluous parens on enums


package no.uio.ifi.trackfind.backend.services;

import org.apache.commons.collections4.CollectionUtils;
import org.eclipse.jgit.api.Git;
import org.eclipse.jgit.api.errors.GitAPIException;
import org.eclipse.jgit.lib.Ref;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class VersioningService {

    private Git git;

    /**
     * Commit everything.
     *
     * @param operation      Operation to commit.
     * @param repositoryName Name of changed repo to use in commit message.
     * @throws GitAPIException In case of Git error.
     */
    public void commitAllChanges(Operation operation, String repositoryName) throws GitAPIException {
        git.add().addFilepattern(".").call();
        git.commit().setAll(true).setMessage(operation.name() + ": " + repositoryName).call();
    }

    /**
     * Tag current revision (HEAD, hopefully).
     *
     * @param repositoryName Name of changed repo to use in tag name.
     * @throws GitAPIException In case of Git error.
     */
    public void tag(String repositoryName) throws GitAPIException {
        List<Ref> tags = git.tagList().call();
        git.tag().setName(CollectionUtils.size(tags) + "." + repositoryName).call();
    }

    public enum Operation {
        CRAWLING, REMAPPING
    }

    @Autowired
    public void setGit(Git git) {
        this.git = git;
    }

}

package no.uio.ifi.trackfind.backend.services;

import org.apache.commons.collections4.CollectionUtils;
import org.eclipse.jgit.api.Git;
import org.eclipse.jgit.api.errors.GitAPIException;
import org.eclipse.jgit.lib.Ref;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * Service for maintaining versioning of indices. Currently backed by Git.
 *
 * @author Dmytro Titov
 */
@Service
public class VersioningService {

    private Git git;

    /**
     * Commit everything.
     *
     * @param operation      Operation to commit.
     * @param repositoryName Name of changed repo to use in commit message.
     * @throws GitAPIException In case of Git error.
     */
    public void commitAllChanges(Operation operation, String repositoryName) throws GitAPIException {
        git.add().addFilepattern(".").call();
        git.commit().setAll(true).setMessage(operation.name() + ": " + repositoryName).call();
    }

    /**
     * Tag current revision (HEAD, hopefully).
     *
     * @param repositoryName Name of changed repo to use in tag name.
     * @throws GitAPIException In case of Git error.
     */
    public void tag(String repositoryName) throws GitAPIException {
        List<Ref> tags = git.tagList().call();
        git.tag().setName(CollectionUtils.size(tags) + "." + repositoryName).call();
    }

    public enum Operation {
        CRAWLING, REMAPPING
    }

    @Autowired
    public void setGit(Git git) {
        this.git = git;
    }

}

Implement versioned crawling and remapping.