package com.faforever.api.data.domain;

import lombok.Setter;
import org.hibernate.annotations.Generated;
import org.hibernate.annotations.GenerationTime;

import javax.persistence.Column;
import javax.persistence.FetchType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.MappedSuperclass;
import javax.persistence.OneToOne;

@MappedSuperclass
@Setter
public abstract class Rating {
  private int id;
  private int ranking;
  private Double mean;
  private Double deviation;
  private Player player;
  private double rating;
  private int numberOfGames;

  @Id
  @Column(name = "id")
  public int getId() {
    return id;
  }

  @Column(name = "ranking")
  public int getRanking() {
    return ranking;
  }

  @Column(name = "mean")
  public Double getMean() {
    return mean;
  }

  @Column(name = "deviation")
  public Double getDeviation() {
    return deviation;
  }

  @OneToOne(fetch = FetchType.LAZY)
  @JoinColumn(name = "id", updatable = false, insertable = false)
  public Player getPlayer() {
    return player;
  }

  @Column(name = "rating", updatable = false)
  @Generated(GenerationTime.ALWAYS)
  public double getRating() {
    return rating;
  }

  @Column(name = "num_games", updatable = false)
  public int getNumberOfGames() {
    return numberOfGames;
  }
}

package com.faforever.api.data.domain;

import lombok.Setter;
import org.hibernate.annotations.Generated;
import org.hibernate.annotations.GenerationTime;

import javax.persistence.Column;
import javax.persistence.FetchType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.MappedSuperclass;
import javax.persistence.OneToOne;

@MappedSuperclass
@Setter
public abstract class Rating {
  private int id;
  private int ranking;
  private Double mean;
  private Double deviation;
  private Player player;
  private Double rating;
  private int numberOfGames;

  @Id
  @Column(name = "id")
  public int getId() {
    return id;
  }

  @Column(name = "ranking")
  public int getRanking() {
    return ranking;
  }

  @Column(name = "mean")
  public Double getMean() {
    return mean;
  }

  @Column(name = "deviation")
  public Double getDeviation() {
    return deviation;
  }

  @OneToOne(fetch = FetchType.LAZY)
  @JoinColumn(name = "id", updatable = false, insertable = false)
  public Player getPlayer() {
    return player;
  }

  @Column(name = "rating", updatable = false, insertable = false)
  @Generated(GenerationTime.ALWAYS)
  public Double getRating() {
    return rating;
  }

  @Column(name = "num_games", updatable = false)
  public int getNumberOfGames() {
    return numberOfGames;
  }
}

Fix issues with database calculated rating column


package org.sourceforge.uptodater;

import java.util.*;

public class ConfigData {

    private static final String DEFAULT_CONFIGURATION_NAME = "uptodater";

    protected Map<String,String> configuration = new HashMap<String,String>();

    public ConfigData() {
        addOverrideConfiguration(DEFAULT_CONFIGURATION_NAME);
    }

    public void addOverrideConfiguration(String configurationName) {
        try {
            ResourceBundle res = ResourceBundle.getBundle(configurationName);
            Enumeration<String> keys = res.getKeys();
            while (keys.hasMoreElements()) {
                String key = keys.nextElement();
                configuration.put(key, res.getString(key));
            }
        } catch (MissingResourceException e) {
            //gulp
        }
    }

    public String get(final String propertyName, final String defaultValue) {
        String key = propertyName.trim();
        if(configuration.containsKey(key)) {
            return configuration.get(key);
        }
        else {
            return defaultValue;
        }
    }

}

package org.sourceforge.uptodater;

import java.util.*;

public class ConfigData {

    private static final String DEFAULT_CONFIGURATION_NAME = "uptodater";

    protected Map<String,String> configuration = new HashMap<String,String>();

    public ConfigData() {
        addOverrideConfiguration(DEFAULT_CONFIGURATION_NAME);
    }

    public void addOverrideConfiguration(String configurationName) {
        try {
            ResourceBundle res = ResourceBundle.getBundle(configurationName);
            Enumeration<String> keys = res.getKeys();
            while (keys.hasMoreElements()) {
                String key = keys.nextElement();
                configuration.put(key, res.getString(key));
            }
        } catch (MissingResourceException e) {
            //gulp
        }
    }

    public String get(final String propertyName, final String defaultValue) {
        String key = propertyName.trim();
        if(System.getProperties().containsKey(propertyName)) {
            return System.getProperty(propertyName);
        } else if(configuration.containsKey(key)) {
            return configuration.get(key);
        }
        else {
            return defaultValue;
        }
    }

}

Allow overriding properties on the command line.


/*
 * Copyright (C) 2010 BloatIt. This file is part of BloatIt. BloatIt is free software: you
 * can redistribute it and/or modify it under the terms of the GNU Affero General Public
 * License as published by the Free Software Foundation, either version 3 of the License,
 * or (at your option) any later version. BloatIt 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 Affero General Public
 * License for more details. You should have received a copy of the GNU Affero General
 * Public License along with BloatIt. If not, see <http://www.gnu.org/licenses/>.
 */
package com.bloatit.web.exceptions;

import com.bloatit.web.utils.url.IndexPageUrl;
import com.bloatit.web.utils.url.Url;

public class RedirectException extends Exception {

    private static final long serialVersionUID = -8000625161101556546L;
    private final Url url;

    public RedirectException(final Url url) {
        if (url == null) {
            this.url = new IndexPageUrl();
        } else {
            this.url = url;
        }
    }

    public Url getUrl() {
        return url;
    }

}

/*
 * Copyright (C) 2010 BloatIt. This file is part of BloatIt. BloatIt is free software: you
 * can redistribute it and/or modify it under the terms of the GNU Affero General Public
 * License as published by the Free Software Foundation, either version 3 of the License,
 * or (at your option) any later version. BloatIt 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 Affero General Public
 * License for more details. You should have received a copy of the GNU Affero General
 * Public License along with BloatIt. If not, see <http://www.gnu.org/licenses/>.
 */
package com.bloatit.web.exceptions;

import com.bloatit.web.utils.url.IndexPageUrl;
import com.bloatit.web.utils.url.Url;

// No serialization possible because IndexPageUrl is not serialisable.
@SuppressWarnings("serial")
public class RedirectException extends Exception {

    private final Url url;

    public RedirectException(final Url url) {
        if (url == null) {
            this.url = new IndexPageUrl();
        } else {
            this.url = url;
        }
    }

    public Url getUrl() {
        return url;
    }

}

Fix sonar warning: Bad practice - Non-serializable value stored into instance field of a serializable class


package edu.umd.cs.findbugs.ba.ch;

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

import edu.umd.cs.findbugs.graph.AbstractGraph;

public class ClassHierarchyGraph
		extends AbstractGraph<ClassHierarchyGraphEdge, ClassHierarchyGraphVertex> {

	private Map<String, ClassHierarchyGraphVertex> vertexMap;

	public ClassHierarchyGraph() {
		this.vertexMap = new HashMap<String, ClassHierarchyGraphVertex>();
	}

	public ClassHierarchyGraphVertex lookupVertex(String className) {
		return vertexMap.get(className);
	}

	public ClassHierarchyGraphVertex addVertex(
			String className,
			ClassHierarchyGraphVertexType vertexType) {
		ClassHierarchyGraphVertex vertex = lookupVertex(className);
		if (vertex == null) {
			vertex = new ClassHierarchyGraphVertex(className, vertexType);
			vertexMap.put(className, vertex);
		}
		return vertex;
	}

	//@Override
	protected ClassHierarchyGraphEdge allocateEdge(ClassHierarchyGraphVertex source, ClassHierarchyGraphVertex target) {
		return new ClassHierarchyGraphEdge(source, target);
	}

}

package edu.umd.cs.findbugs.ba.ch;

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

import edu.umd.cs.findbugs.graph.AbstractGraph;

public class ClassHierarchyGraph
		extends AbstractGraph<ClassHierarchyGraphEdge, ClassHierarchyGraphVertex> {

	private Map<String, ClassHierarchyGraphVertex> vertexMap;

	public ClassHierarchyGraph() {
		this.vertexMap = new HashMap<String, ClassHierarchyGraphVertex>();
	}

	public ClassHierarchyGraphVertex lookupVertex(String className) {
		return vertexMap.get(className);
	}

	public ClassHierarchyGraphVertex addVertex(
			String className,
			ClassHierarchyGraphVertexType vertexType) {
		ClassHierarchyGraphVertex vertex = lookupVertex(className);
		if (vertex == null) {
			vertex = new ClassHierarchyGraphVertex(className, vertexType);
			vertexMap.put(className, vertex);
			addVertex(vertex);
		}
		return vertex;
	}

	//@Override
	protected ClassHierarchyGraphEdge allocateEdge(ClassHierarchyGraphVertex source, ClassHierarchyGraphVertex target) {
		return new ClassHierarchyGraphEdge(source, target);
	}

}

Make sure vertices really get added to the graph. Duh.


package com.packetzoom.RNPacketzoom;

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

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

public class RNPacketzoom implements ReactPackage {

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

        modules.add(new RNPacketzoomModule(reactContext));

        return modules;
    }

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

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

package com.packetzoom.RNPacketzoom;

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

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

public class RNPacketzoom implements ReactPackage {

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

        modules.add(new RNPacketzoomModule(reactContext));

        return modules;
    }

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

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

Fix @Override method deprecated in RN 0.47


package net.mcft.copy.backpacks.client;

import net.mcft.copy.core.client.ModResourceLocation;
import net.minecraft.util.ResourceLocation;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;

@SideOnly(Side.CLIENT)
public final class BackpackResources {

	public static final ResourceLocation textureBackpack = new ModResourceLocation("textures/models/backpack.png");
	public static final ResourceLocation textureBackpackOverlay = new ModResourceLocation("textures/models/backpack_overlay.png");

	public static final ResourceLocation modelBackpack = new ModResourceLocation("models/backpack.obj");

	private BackpackResources() {  }

}

package net.mcft.copy.backpacks.client;

import net.mcft.copy.backpacks.WearableBackpacks;
import net.mcft.copy.core.client.ModResource;
import net.minecraft.util.ResourceLocation;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;

@SideOnly(Side.CLIENT)
public final class BackpackResources {

	public static final ResourceLocation textureBackpack =
			new ModResource(WearableBackpacks.MOD_ID, "textures/models/backpack.png");
	public static final ResourceLocation textureBackpackOverlay =
			new ModResource(WearableBackpacks.MOD_ID, "textures/models/backpack_overlay.png");

	public static final ResourceLocation modelBackpack =
			new ModResource(WearableBackpacks.MOD_ID, "models/backpack.obj");

	private BackpackResources() {  }

}

Update to copycore's new ModResource


package guitests.guihandles;

import guitests.GuiRobot;
import javafx.stage.Stage;

/**
 * A handle to the Command Box in the GUI.
 */
public class CommandBoxHandle extends GuiHandle{

    private static final String COMMAND_INPUT_FIELD_ID = "#commandTextField";

    public CommandBoxHandle(GuiRobot guiRobot, Stage primaryStage, String stageTitle) {
        super(guiRobot, primaryStage, stageTitle);
    }

    public void enterCommand(String command) {
        setTextField(COMMAND_INPUT_FIELD_ID, command);
    }

    public String getCommandInput() {
        return getTextFieldText(COMMAND_INPUT_FIELD_ID);
    }

    /**
     * Enters the given command in the Command Box and presses enter.
     */
    public void runCommand(String command) {
        enterCommand(command);
        pressEnter();
        guiRobot.sleep(200);
        if (command.equals("clear")) // any commands that has an alert dialog that pops out
            pressEnter();
        guiRobot.sleep(500); //Give time for the command to take effect
    }

    public HelpWindowHandle runHelpCommand() {
        enterCommand("help");
        pressEnter();
        return new HelpWindowHandle(guiRobot, primaryStage);
    }
}

package guitests.guihandles;

import guitests.GuiRobot;
import javafx.stage.Stage;

/**
 * A handle to the Command Box in the GUI.
 */
public class CommandBoxHandle extends GuiHandle{

    private static final String COMMAND_INPUT_FIELD_ID = "#commandTextField";

    public CommandBoxHandle(GuiRobot guiRobot, Stage primaryStage, String stageTitle) {
        super(guiRobot, primaryStage, stageTitle);
    }

    public void enterCommand(String command) {
        setTextField(COMMAND_INPUT_FIELD_ID, command);
    }

    public String getCommandInput() {
        return getTextFieldText(COMMAND_INPUT_FIELD_ID);
    }

    /**
     * Enters the given command in the Command Box and presses enter.
     */
    public void runCommand(String command) {
        enterCommand(command);
        pressEnter();
        guiRobot.sleep(10);
        if (command.equals("clear")) // any commands that has an alert dialog that pops out
            pressEnter();
        guiRobot.sleep(700); //Give time for the command to take effect
    }

    public HelpWindowHandle runHelpCommand() {
        enterCommand("help");
        pressEnter();
        return new HelpWindowHandle(guiRobot, primaryStage);
    }
}

Create new alert class and display an alert when user attempts to clear tasks


package com.oreilly.rdf.tenuki.jaxrs;

import javax.ws.rs.GET;
import javax.ws.rs.Path;

import com.sun.jersey.api.view.Viewable;

@Path("/")
public class UIResource {

	@GET
	public Viewable landingPage() {
		return new Viewable("/templates/test.vm");
	}
}

package com.oreilly.rdf.tenuki.jaxrs;

import javax.ws.rs.GET;
import javax.ws.rs.Path;

import org.apache.velocity.VelocityContext;
import org.apache.velocity.context.Context;

import com.sun.jersey.api.view.Viewable;

@Path("/")
public class UIResource {

	@GET
	public Viewable landingPage() {
		Context c = new VelocityContext();
		return new Viewable("/templates/test.vm", c);
	}
}

Create a context even if we aren't using it just at the moment


package aeronicamc.mods.mxtune.gui;

import com.mojang.blaze3d.systems.RenderSystem;
import net.minecraft.client.renderer.ItemRenderer;
import net.minecraft.item.ItemStack;

public class ModGuiHelper
{
    public static void RenderGuiItemScaled(ItemRenderer itemRenderer, ItemStack pStack, int posX, int posY, int scale, boolean onCenter)
    {
        int xRel = (onCenter ? posX - 16*scale/2 : posX)/scale;
        int yRel = (onCenter ? posY - 16*scale/2 : posY)/scale;
        RenderSystem.scalef(scale, scale, 1F);
        itemRenderer.renderAndDecorateItem(pStack, xRel, yRel);
    }
}

package aeronicamc.mods.mxtune.gui;

import com.mojang.blaze3d.systems.RenderSystem;
import net.minecraft.client.renderer.ItemRenderer;
import net.minecraft.item.ItemStack;

public class ModGuiHelper
{
    public static void RenderGuiItemScaled(ItemRenderer itemRenderer, ItemStack pStack, int posX, int posY, int scale, boolean onCenter)
    {
        RenderSystem.pushMatrix();
        int xRel = (onCenter ? posX - 16*scale/2 : posX)/scale;
        int yRel = (onCenter ? posY - 16*scale/2 : posY)/scale;
        RenderSystem.scalef(scale, scale, 1F);
        itemRenderer.renderAndDecorateItem(pStack, xRel, yRel);
        RenderSystem.popMatrix();
    }
}

Save and restore the matrix so scaling only affects this item render.


package net.hillsdon.svnwiki.web.dispatching;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Communicates a redirect.
 *
 * Exception as that ought to be the effect on control-flow.
 *
 * @author mth
 */
public class RedirectView implements View {

  private static final long serialVersionUID = 1L;
  private final String _url;

  public RedirectView(final String url) {
    _url = url;
  }

  public String getURL() {
    return _url;
  }

  public void render(final HttpServletRequest request, final HttpServletResponse response) throws IOException {
    response.sendRedirect(_url);
  }

}

package net.hillsdon.svnwiki.web.dispatching;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Communicates a redirect.
 *
 * Exception as that ought to be the effect on control-flow.
 *
 * @author mth
 */
public class RedirectView implements View {

  private final String _url;

  public RedirectView(final String url) {
    _url = url;
  }

  public String getURL() {
    return _url;
  }

  public void render(final HttpServletRequest request, final HttpServletResponse response) throws IOException {
    response.sendRedirect(_url);
  }

}

Remove svuid, this class was an exception but isn't anymore.


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

import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

/**
 *
 */
@Configuration
@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers("/health")
            .antMatchers("/metrics")
            .antMatchers("/info");
        getHttp().csrf().disable();
    }
}

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

import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

/**
 *
 */
@Configuration
@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers("/health")
            .antMatchers("/metrics")
            .antMatchers("/info");
    }
}

Remove CSRF disabling in sample code


package org.bouncycastle.bcpg;

import java.io.*;
import java.math.BigInteger;

/**
 * a multiple precision integer
 */
public class MPInteger
    extends BCPGObject
{
    BigInteger    value = null;

    public MPInteger(
        BCPGInputStream    in)
        throws IOException
    {
        int       length = (in.read() << 8) | in.read();
        byte[]    bytes = new byte[(length + 7) / 8];

        in.readFully(bytes);

        value = new BigInteger(1, bytes);
    }

    public MPInteger(
        BigInteger    value)
    {
        this.value = value;
    }

    public BigInteger getValue()
    {
        return value;
    }

    public void encode(
        BCPGOutputStream    out)
        throws IOException
    {
        int length = value.bitLength();

        out.write(length >> 8);
        out.write(length);

        byte[]    bytes = value.toByteArray();

        if (bytes[0] == 0)
        {
            out.write(bytes, 1, bytes.length - 1);
        }
        else
        {
            out.write(bytes, 0, bytes.length);
        }
    }
}

package org.bouncycastle.bcpg;

import java.io.*;
import java.math.BigInteger;

/**
 * a multiple precision integer
 */
public class MPInteger
    extends BCPGObject
{
    BigInteger    value = null;

    public MPInteger(
        BCPGInputStream    in)
        throws IOException
    {
        int       length = (in.read() << 8) | in.read();
        byte[]    bytes = new byte[(length + 7) / 8];

        in.readFully(bytes);

        value = new BigInteger(1, bytes);
    }

    public MPInteger(
        BigInteger    value)
    {
        if (value == null || value.signum() < 0)
        {
            throw new IllegalArgumentException("value must not be null, or negative");
        }

        this.value = value;
    }

    public BigInteger getValue()
    {
        return value;
    }

    public void encode(
        BCPGOutputStream    out)
        throws IOException
    {
        int length = value.bitLength();

        out.write(length >> 8);
        out.write(length);

        byte[]    bytes = value.toByteArray();

        if (bytes[0] == 0)
        {
            out.write(bytes, 1, bytes.length - 1);
        }
        else
        {
            out.write(bytes, 0, bytes.length);
        }
    }
}

Add a check that the BigInteger value is not null or negative


package com.choonster.testmod3.util;

import com.choonster.testmod3.TestMod3;
import com.google.common.collect.ImmutableSet;
import net.minecraft.inventory.EntityEquipmentSlot;

import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class Constants {
	public static final String RESOURCE_PREFIX = TestMod3.MODID + ":";

	/**
	 * The armour equipment slots.
	 */
	public static final Set<EntityEquipmentSlot> ARMOUR_SLOTS = ImmutableSet.copyOf(
			Stream.of(EntityEquipmentSlot.values())
					.filter(equipmentSlot -> equipmentSlot.getSlotType() == EntityEquipmentSlot.Type.ARMOR)
					.collect(Collectors.toList())
	);
}

package com.choonster.testmod3.util;

import com.choonster.testmod3.TestMod3;
import com.google.common.collect.ImmutableSet;
import net.minecraft.entity.ai.attributes.AttributeModifier;
import net.minecraft.inventory.EntityEquipmentSlot;

import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class Constants {
	public static final String RESOURCE_PREFIX = TestMod3.MODID + ":";

	/**
	 * The armour equipment slots.
	 */
	public static final Set<EntityEquipmentSlot> ARMOUR_SLOTS = ImmutableSet.copyOf(
			Stream.of(EntityEquipmentSlot.values())
					.filter(equipmentSlot -> equipmentSlot.getSlotType() == EntityEquipmentSlot.Type.ARMOR)
					.collect(Collectors.toList())
	);

	/**
	 * {@link AttributeModifier} operation 0.
	 *

	 * Add the modifier's amount to the attribute's amount.
	 */
	public static final int ATTRIBUTE_MODIFIER_OPERATION_ADD = 0;

	/**
	 * {@link AttributeModifier} operation 1.
	 *

	 * Add the result of operation 0 multiplied by the modifier's amount to the attribute's amount.
	 */
	public static final int ATTRIBUTE_MODIFIER_OPERATION_MULTIPLY_OLD_AMOUNT = 1;

	/**
	 * {@link AttributeModifier} operation 2.
	 *

	 * Multiply the attribute's amount by 1.0 + the modifier's amount.
	 */
	public static final int ATTRIBUTE_MODIFIER_OPERATION_MULTIPLY_NEW_AMOUNT = 2;
}

Add constants for AttributeModifier operations


package ru.stqa.pft.addressbook.tests;

import org.openqa.selenium.remote.BrowserType;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import ru.stqa.pft.addressbook.appmanager.ApplicationManager;

/**
 * Created by User on 27.10.2016.
 */
public class TestBase {

  protected final ApplicationManager app = new ApplicationManager(BrowserType.CHROME);

  @BeforeMethod
  public void setUp() throws Exception {
    app.init();
  }

  @AfterMethod
  public void tearDown() {
    app.stop();
  }

}

package ru.stqa.pft.addressbook.tests;

import org.openqa.selenium.remote.BrowserType;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import ru.stqa.pft.addressbook.appmanager.ApplicationManager;

/**
 * Created by User on 27.10.2016.
 */
public class TestBase {

  protected final ApplicationManager app = new ApplicationManager(BrowserType.IE);

  @BeforeMethod
  public void setUp() throws Exception {
    app.init();
  }

  @AfterMethod
  public void tearDown() {
    app.stop();
  }

}

Change tests launch for IE


package com.todoist.markup;

import java.util.regex.Pattern;

class Patterns {
    public static final Pattern HEADER = Pattern.compile("^\\*\\s*");
    public static final Pattern BOLD = Pattern.compile("!!\\s*((?!!!).+?)\\s*!!");
    public static final Pattern ITALIC = Pattern.compile("__\\s*((?!__).+?)\\s*__");
    public static final Pattern LINK = Pattern.compile("((?:ftp|https?)://[^\\s><\\[\\],]+)(?:\\s+\\(([^)]+)\\))?");
    public static final Pattern GMAIL = Pattern.compile("\\[\\[gmail=\\s*(.*?)\\s*,\\s*(.*?)\\s*\\]\\]");
    public static final Pattern OUTLOOK = Pattern.compile("\\[\\[outlook=\\s*(.*?)\\s*,\\s*(.*?)\\s*\\]\\]");
    public static final Pattern THUNDERBIRD =
            Pattern.compile("\\[\\[thunderbird\\n?\\s*([^\\n]+)\\s+([^\\n]+)\\s+\\]\\]");
}

package com.todoist.markup;

import java.util.regex.Pattern;

class Patterns {
    public static final Pattern HEADER = Pattern.compile("^\\*\\s*");
    public static final Pattern BOLD = Pattern.compile("!!\\s*((?!!!).+?)\\s*!!");
    public static final Pattern ITALIC = Pattern.compile("__\\s*((?!__).+?)\\s*__");
    public static final Pattern LINK = Pattern.compile("((?:\\w+)://[^\\s><\\[\\],]+)(?:\\s+\\(([^)]+)\\))?");
    public static final Pattern GMAIL = Pattern.compile("\\[\\[gmail=\\s*(.*?)\\s*,\\s*(.*?)\\s*\\]\\]");
    public static final Pattern OUTLOOK = Pattern.compile("\\[\\[outlook=\\s*(.*?)\\s*,\\s*(.*?)\\s*\\]\\]");
    public static final Pattern THUNDERBIRD =
            Pattern.compile("\\[\\[thunderbird\\n?\\s*([^\\n]+)\\s+([^\\n]+)\\s+\\]\\]");
}

Support evernote:// and other URIs


package com.qubole.streamx.s3.wal;

import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.apache.kafka.connect.errors.ConnectException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.beans.PropertyVetoException;
import java.util.HashMap;

public class ConnectionPool {
  private static final Logger log = LoggerFactory.getLogger(ConnectionPool.class);

  private static HashMap<String, ComboPooledDataSource> dataSources = new HashMap<>();
  public static ComboPooledDataSource getDatasource(String connectionUrl, String user, String password) {
    if(dataSources.containsKey(connectionUrl)) {
      return dataSources.get(connectionUrl);
    }
    else {
      try {
        ComboPooledDataSource cpds = new ComboPooledDataSource();
        cpds.setDriverClass("com.mysql.jdbc.Driver"); //loads the jdbc driver
        cpds.setJdbcUrl(connectionUrl);
        cpds.setUser(user);
        cpds.setPassword(password);
        cpds.setMaxConnectionAge(18000);//5 hours
        return cpds;
      } catch (PropertyVetoException e) {
        log.error("Error while creating c3p0 ComboPooledDataSource" + e);
        throw new ConnectException(e);
      }
    }
  }

}

package com.qubole.streamx.s3.wal;

import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.apache.kafka.connect.errors.ConnectException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.beans.PropertyVetoException;
import java.util.HashMap;

public class ConnectionPool {
  private static final Logger log = LoggerFactory.getLogger(ConnectionPool.class);

  private static HashMap<String, ComboPooledDataSource> dataSources = new HashMap<>();
  public static ComboPooledDataSource getDatasource(String connectionUrl, String user, String password) {
    if(dataSources.containsKey(connectionUrl)) {
      return dataSources.get(connectionUrl);
    }
    else {
      try {
        ComboPooledDataSource cpds = new ComboPooledDataSource();
        cpds.setDriverClass("com.mysql.jdbc.Driver"); //loads the jdbc driver
        cpds.setJdbcUrl(connectionUrl);
        cpds.setUser(user);
        cpds.setPassword(password);
        cpds.setMaxConnectionAge(18000);//5 hours
        dataSources.put(connectionUrl, cpds);
        return cpds;
      } catch (PropertyVetoException e) {
        log.error("Error while creating c3p0 ComboPooledDataSource" + e);
        throw new ConnectException(e);
      }
    }
  }

}

Fix bug : Reuse connection pool


package com.uwetrottmann.shopr.algorithm.test;

import static org.junit.Assert.*;

import org.junit.Test;

public class SimilarityTest {

    @Test
    public void testSimilarity() {
        fail("Not yet implemented");
    }

}

package com.uwetrottmann.shopr.algorithm.test;

import static org.fest.assertions.api.Assertions.assertThat;
import static org.fest.assertions.api.Assertions.failBecauseExceptionWasNotThrown;

import com.uwetrottmann.shopr.algorithm.Similarity;
import com.uwetrottmann.shopr.algorithm.model.Attributes;
import com.uwetrottmann.shopr.algorithm.model.ClothingType;
import com.uwetrottmann.shopr.algorithm.model.Color;

import org.junit.Test;

public class SimilarityTest {

    @Test
    public void testSimilarity() {
        Attributes a1 = new Attributes();
        a1.color = new Color(Color.Value.RED);
        a1.type = new ClothingType(ClothingType.Value.DRESS);

        Attributes a2 = new Attributes();
        a2.color = new Color(Color.Value.BLACK);
        a2.type = null;

        // different color
        assertThat(Similarity.similarity(a1, a2)).isEqualTo(0.0);

        // same color
        a1.color = new Color(Color.Value.BLACK);
        assertThat(Similarity.similarity(a1, a2)).isEqualTo(1.0);

        // throw on no comparable attributes
        a1.color = null;
        try {
            Similarity.similarity(a1, a2);

            failBecauseExceptionWasNotThrown(IllegalArgumentException.class);
        } catch (Exception e) {
            assertThat(e).isInstanceOf(IllegalArgumentException.class);
        }
    }

}

Write test with expected values.


package net.ssehub.kernel_haven.feature_effects;

import net.ssehub.kernel_haven.SetUpException;
import net.ssehub.kernel_haven.analysis.AnalysisComponent;
import net.ssehub.kernel_haven.analysis.PipelineAnalysis;
import net.ssehub.kernel_haven.config.Configuration;

/**
 * An analysis that finds feature effect formulas for variables.
 *
 * @author Adam
 */
public class FeatureEffectAnalysis extends PipelineAnalysis {

    /**
     * Creates a new {@link FeatureEffectAnalysis}.
     *
     * @param config The global configuration.
     */
    public FeatureEffectAnalysis(Configuration config) {
        super(config);
    }

    @Override
    protected AnalysisComponent<?> createPipeline() throws SetUpException {
        return new FeatureEffectFinder(config,
                new PcFinder(config,
                        getCmComponent(),
                        getBmComponent()
                )
        );
    }

}

Convert all text files to Linux linefeeds


package net.maxbraun.mirror;

import android.location.Location;
import android.util.Log;

import org.json.JSONException;
import org.json.JSONObject;

/**
 * A helper class to look up location by IP.
 */
public abstract class GeoLocation {
  private static final String TAG = GeoLocation.class.getSimpleName();

  /**
   * The URL of the geo location API endpoint.
   */
  private static final String GEO_IP_URL = "http://freegeoip.net/json/";

  /**
   * Makes a request to the geo location API and returns the current location or {@code null} on
   * error.
   */
  public static Location getLocation() {
    String response = Network.get(GEO_IP_URL);
    if (response == null) {
      Log.e(TAG, "Empty response.");
      return null;
    }

    // Parse the latitude and longitude from the response JSON.
    try {
      JSONObject responseJson = new JSONObject(response);
      double latitude = responseJson.getDouble("latitude");
      double longitude = responseJson.getDouble("longitude");
      Location location = new Location("");
      location.setLatitude(latitude);
      location.setLongitude(longitude);
      return location;
    } catch (JSONException e) {
      Log.e(TAG, "Failed to parse geo location JSON.");
      return null;
    }
  }
}

package net.maxbraun.mirror;

import android.location.Location;
import android.util.Log;

import org.json.JSONException;
import org.json.JSONObject;

/**
 * A helper class to look up location by IP.
 */
public abstract class GeoLocation {
  private static final String TAG = GeoLocation.class.getSimpleName();

  /**
   * The URL of the geo location API endpoint.
   */
  private static final String GEO_IP_URL = "http://ip-api.com/json";

  /**
   * Makes a request to the geo location API and returns the current location or {@code null} on
   * error.
   */
  public static Location getLocation() {
    String response = Network.get(GEO_IP_URL);
    if (response == null) {
      Log.e(TAG, "Empty response.");
      return null;
    }

    // Parse the latitude and longitude from the response JSON.
    try {
      JSONObject responseJson = new JSONObject(response);
      double latitude = responseJson.getDouble("lat");
      double longitude = responseJson.getDouble("lon");
      Location location = new Location("");
      location.setLatitude(latitude);
      location.setLongitude(longitude);
      return location;
    } catch (JSONException e) {
      Log.e(TAG, "Failed to parse geo location JSON.");
      return null;
    }
  }
}

Switch to a geo IP API that isn't down


package org.intermine.util;

import static org.apache.commons.lang.StringUtils.isBlank;

import java.util.Map;
import java.util.Properties;

import javax.mail.MessagingException;

public class Emailer {

	private static final String PREFIX = "mail.regarding.";

	private final Properties properties;

	public Emailer(Properties properties) {
		this.properties = properties;
	}

	public void email(String to, String messageKey) throws MessagingException {
		String subject = properties.getProperty(PREFIX + messageKey + ".subject");
		String body = properties.getProperty(PREFIX + messageKey + ".body");
		MailUtils.email(to, subject, body, properties);
	}

	public void email(String to, String messageKey, Object... vars) throws MessagingException {
		String subject = properties.getProperty(PREFIX + messageKey + ".subject");
		String bodyFmt = properties.getProperty(PREFIX + messageKey + ".body");
		String body = String.format(bodyFmt, vars);
		MailUtils.email(to, subject, body, properties);
	}

	public void welcome(String to) throws MessagingException {
		MailUtils.welcome(to, properties);
	}

	public String subscribeToList(String address) throws MessagingException {
		String mailingList = properties.getProperty("mail.mailing-list");
        if (!isBlank(mailingList)) {
            MailUtils.subscribe(address, properties);
            return mailingList;
        }
        return null;
	}

}

package org.intermine.util;

import static org.apache.commons.lang.StringUtils.isBlank;

import java.util.Map;
import java.util.Properties;

import javax.mail.MessagingException;

import org.apache.commons.lang.StringUtils;

public class Emailer {

    private static final String PREFIX = "mail.regarding.";

    private final Properties properties;

    public Emailer(Properties properties) {
        this.properties = properties;
    }

    public void email(String to, String messageKey) throws MessagingException {
        String subject = properties.getProperty(PREFIX + messageKey + ".subject");
        String body = properties.getProperty(PREFIX + messageKey + ".body");
        MailUtils.email(to, subject, body, properties);
    }

    public void email(String to, String messageKey, Object... vars) throws MessagingException {
        String subject = properties.getProperty(PREFIX + messageKey + ".subject");
        String bodyFmt = properties.getProperty(PREFIX + messageKey + ".body");
        if (StringUtils.isBlank(bodyFmt)) {
            throw new MessagingException("No email template configured for " + messageKey);
        }
        String body = String.format(bodyFmt, vars);
        MailUtils.email(to, subject, body, properties);
    }

    public void welcome(String to) throws MessagingException {
        MailUtils.welcome(to, properties);
    }

    public String subscribeToList(String address) throws MessagingException {
        String mailingList = properties.getProperty("mail.mailing-list");
        if (!isBlank(mailingList)) {
            MailUtils.subscribe(address, properties);
            return mailingList;
        }
        return null;
    }

}

Handle missing templates nicely. Whitespace


/**
 * Copyright (C) 2014 Antonin Stefanutti (antonin.stefanutti@gmail.com)
 *
 * 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.apache.camel.cdi;

import javax.inject.Qualifier;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Qualifier
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE, ElementType.METHOD, ElementType.FIELD, ElementType.PARAMETER})
public @interface ContextName {

    String value();
}

/**
 * Copyright (C) 2014 Antonin Stefanutti (antonin.stefanutti@gmail.com)
 *
 * 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.apache.camel.cdi;

import javax.inject.Qualifier;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Qualifier
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE, ElementType.METHOD, ElementType.FIELD, ElementType.PARAMETER})
public @interface ContextName {

    /**
     * Returns the name of the CamelContext to add the routes to.
     * If no value is specified then the default CamelContext is used.
     */
    String value() default "";
}

Add comment & default value for the camelcontext


package io.openex.config;

import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.util.StdDateFormat;
import com.fasterxml.jackson.datatype.hibernate5.Hibernate5Module;
import io.openex.database.model.User;
import org.springframework.context.annotation.Bean;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;

@Component
@EnableAsync
public class AppConfig {

    private final static String ANONYMOUS_USER = "anonymousUser";

    // Validations
    public final static String MANDATORY_MESSAGE = "This value should not be blank.";

    public static User currentUser() {
        Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        if (ANONYMOUS_USER.equals(principal)) {
            User anonymousUser = new User();
            anonymousUser.setId("anonymous");
            anonymousUser.setEmail("anonymous@openex.io");
            return anonymousUser;
        }
        assert principal instanceof User;
        return (User) principal;
    }

    @Bean
    ObjectMapper openexJsonMapper() {
        ObjectMapper mapper = new ObjectMapper();
        mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        mapper.setDateFormat(new StdDateFormat().withColonInTimeZone(true));
        mapper.registerModule(new Hibernate5Module());
        return mapper;
    }
}

package io.openex.config;

import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.util.StdDateFormat;
import com.fasterxml.jackson.datatype.hibernate5.Hibernate5Module;
import io.openex.database.model.User;
import org.springframework.context.annotation.Bean;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;

@Component
@EnableAsync
public class AppConfig {

    private final static String ANONYMOUS_USER = "anonymousUser";

    // Validations
    public final static String MANDATORY_MESSAGE = "This value should not be blank.";

    public static User currentUser() {
        Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        if (ANONYMOUS_USER.equals(principal)) {
            User anonymousUser = new User();
            anonymousUser.setId("anonymous");
            anonymousUser.setEmail("anonymous@openex.io");
            return anonymousUser;
        }
        assert principal instanceof User;
        return (User) principal;
    }

    public static void updateSessionUser(User user) {
        Authentication authentication = new UsernamePasswordAuthenticationToken(user, user.getPassword(), user.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(authentication);
    }

    @Bean
    ObjectMapper openexJsonMapper() {
        ObjectMapper mapper = new ObjectMapper();
        mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        mapper.setDateFormat(new StdDateFormat().withColonInTimeZone(true));
        mapper.registerModule(new Hibernate5Module());
        return mapper;
    }
}

Update user session profile when self updating


package com.edinarobotics.zed.commands;

import com.edinarobotics.utils.math.Point2;

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

    public static final Point2 PYRAMID_BACK_MIDDLE = new Point2(-0.018, -0.25);
    public static final Point2 PYRAMID_BACK_RIGHT = new Point2(-0.063829, -0.226891);

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

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

    public FixedPointVisionTrackingCommand(Point2 point2) {
        this(point2.getX(), point2.getY());
    }

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

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

package com.edinarobotics.zed.commands;

import com.edinarobotics.utils.math.Point2;

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

    public static final Point2 PYRAMID_BACK_MIDDLE_NEW = new Point2(-0.018, -0.25);
    public static final Point2 PYRAMID_BACK_RIGHT = new Point2(-0.063829, -0.226891);
    public static final Point2 PYRAMID_BACK_MIDDLE = new Point2(0.0273556, -0.29411);
    public static final Point2 PYRAMID_BACK_MIDDLE_NEW2 = new Point2(-0.143, -0.241);

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

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

    public FixedPointVisionTrackingCommand(Point2 point2) {
        this(point2.getX(), point2.getY());
    }

    public FixedPointVisionTrackingCommand(Point2 point2, byte goalType) {
        this(point2.getX(), point2.getY(), goalType);
    }

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

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

Add extra fixed-point value from practice field testing.


package io.github.spharris.ssc;

import com.google.inject.AbstractModule;
import com.google.inject.assistedinject.FactoryModuleBuilder;
import com.sun.jna.Native;

public class SscGuiceModule extends AbstractModule {

  @Override
  protected void configure() {
    bind(Ssc.class).toInstance((Ssc) Native.loadLibrary(Ssc.SSC_LIB_NAME, Ssc.class));
    install(new FactoryModuleBuilder().implement(SscModule.class, SscModule.class)
        .build(SscModuleFactory.class));
  }
}

package io.github.spharris.ssc;

import com.google.inject.AbstractModule;
import com.google.inject.assistedinject.FactoryModuleBuilder;
import com.sun.jna.Native;

public class SscGuiceModule extends AbstractModule {

  @Override
  protected void configure() {
    bind(Ssc.class).toInstance((Ssc) Native.loadLibrary(Ssc.SSC_LIB_NAME, Ssc.class));
    bind(DataContainer.class);

    install(new FactoryModuleBuilder().implement(SscModule.class, SscModule.class)
        .build(SscModuleFactory.class));
  }
}

Add integration tests for data


package vrampal.connectfour.webjsp;

import javax.servlet.http.HttpServletRequest;

import lombok.RequiredArgsConstructor;

@RequiredArgsConstructor
public class ConnectFourRequest {

  /**
   * Type: String
   */
  public static final String MAIN_MESSAGE = "main_message";

  /**
   * Type: String
   */
  public static final String SUB_MESSAGE = "sub_message";

  /**
   * Type: String
   */
  public static final String GAME_ID = "game_id";

  private final HttpServletRequest req;

  public ConnectFourSession getSession() {
    // TODO should we have a cache ?
    return new ConnectFourSession(req.getSession());
  }

  public String getParameter(String name) {
    return req.getParameter(name);
  }

  public String getMainMessage() {
    return req.getParameter(MAIN_MESSAGE);
  }

  public void setMainMessage(String mainMessage) {
    req.setAttribute(MAIN_MESSAGE, mainMessage);
  }

  public String getSubMessage() {
    return req.getParameter(SUB_MESSAGE);
  }

  public void setSubMessage(String subMessage) {
    req.setAttribute(SUB_MESSAGE, subMessage);
  }

  public String getGameId() {
    return req.getParameter(GAME_ID);
  }

  public void setGameId(String gameId) {
    req.setAttribute(GAME_ID, gameId);
  }

}

package vrampal.connectfour.webjsp;

import javax.servlet.http.HttpServletRequest;

import lombok.RequiredArgsConstructor;

@RequiredArgsConstructor
public class ConnectFourRequest {

  /**
   * Type: String
   */
  public static final String MAIN_MESSAGE = "main_message";

  /**
   * Type: String
   */
  public static final String SUB_MESSAGE = "sub_message";

  /**
   * Type: String
   */
  public static final String GAME_ID = "game_id";

  private final HttpServletRequest req;

  // ----- Session -----

  public ConnectFourSession getSession() {
    return new ConnectFourSession(req.getSession());
  }

  // ----- Request parameters -----

  public String getParameter(String name) {
    return req.getParameter(name);
  }

  // ----- Request attributes -----

  public String getMainMessage() {
    return (String) req.getAttribute(MAIN_MESSAGE);
  }

  public void setMainMessage(String mainMessage) {
    req.setAttribute(MAIN_MESSAGE, mainMessage);
  }

  public String getSubMessage() {
    return (String) req.getAttribute(SUB_MESSAGE);
  }

  public void setSubMessage(String subMessage) {
    req.setAttribute(SUB_MESSAGE, subMessage);
  }

  public String getGameId() {
    return (String) req.getAttribute(GAME_ID);
  }

  public void setGameId(String gameId) {
    req.setAttribute(GAME_ID, gameId);
  }

}

Fix attributes and not parameters


package com.maxmind.geoip2.model;

/**
 *

 * This class provides a model for the data returned by the GeoIP2 Precision:
 * Insights end point.
 *

 *

 * The only difference between the City and Insights model classes is which
 * fields in each record may be populated.
 *

 *

 * @see GeoIP2 Web
 * Services
 *

 */
final public class InsightsResponse extends AbstractCityResponse {
    public InsightsResponse() {
    }
}

package com.maxmind.geoip2.model;

/**
 *

 * This class provides a model for the data returned by the GeoIP2 Precision:
 * Insights end point.
 *

 *

 * The only difference between the City and Insights model classes is which
 * fields in each record may be populated.
 *

 *

 * @see GeoIP2 Web
 * Services
 *

 */
public class InsightsResponse extends AbstractCityResponse {
    public InsightsResponse() {
    }
}

Remove final from InsightsReponse model


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

package com.google.sps.servlets;

import java.io.IOException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/** Servlet that returns some example content. TODO: modify this file to handle comments data */
@WebServlet("/data")
public class DataServlet extends HttpServlet {

  @Override
  public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
    response.setContentType("text/html;");
    response.getWriter().println("
Hello world!
");
  }
}

Add newline to end of file.


package com.coronaide.test.ui;

import java.io.IOException;
import java.util.stream.Collectors;

import javax.inject.Inject;

import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;

import com.coronaide.core.model.Project;
import com.coronaide.core.service.IProjectService;
import com.coronaide.ui.CoronaUIApplication;

public class CreateProjectTest extends CoronaUITest {

    @Inject
    private IProjectService projectService;

    private final String TEST_PROJECT_NAME = "test_project";

    @Before
    public void setup() throws Exception {
        launch(CoronaUIApplication.class);
    }

    @Test
    public void createProjectTest() {
        clickOn("#menu-file").clickOn("#menu-file-new-project");
        write(TEST_PROJECT_NAME);
        clickOn("OK");
        Assert.assertTrue("Expected newly created project to be found in project list.",
                projectService.getAll().stream().map(Project::getName).collect(Collectors.toList())
                        .contains(TEST_PROJECT_NAME));
    }

    @After
    public void teardown() {
        projectService.getAll().stream()
                .filter(p -> TEST_PROJECT_NAME.equals(p.getName()))
                .forEach(p -> {
                    try {
                        projectService.delete(p);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                });
    }

}

package com.coronaide.test.ui;

import java.io.IOException;
import java.util.Collection;
import java.util.function.Predicate;
import java.util.stream.Collectors;

import javax.inject.Inject;

import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;

import com.coronaide.core.model.Project;
import com.coronaide.core.service.IProjectService;
import com.coronaide.ui.CoronaUIApplication;

public class CreateProjectTest extends CoronaUITest {

    @Inject
    private IProjectService projectService;

    private final String TEST_PROJECT_NAME = "test_project";

    @Before
    public void setup() throws Exception {
        launch(CoronaUIApplication.class);
    }

    @Test
    public void createProjectTest() {
        clickOn("#menu-file").clickOn("#menu-file-new-project");
        write(TEST_PROJECT_NAME);
        clickOn("OK");

        Collection<String> projectNames = projectService.getAll().stream()
                .map(Project::getName)
                .collect(Collectors.toList());

        boolean found = projectNames.stream()
                .filter(Predicate.isEqual(TEST_PROJECT_NAME))
                .findAny()
                .isPresent();

        Assert.assertTrue("Expected newly created project to be found in project list (" + projectNames + ")", found);
    }

    @After
    public void teardown() {
        projectService.getAll().stream()
        .filter(p -> TEST_PROJECT_NAME.equals(p.getName()))
        .forEach(p -> {
            try {
                projectService.delete(p);
            } catch (IOException e) {
                e.printStackTrace();
            }
        });
    }

}

Add more information to failure message


package com.breakersoft.plow.dispatcher;

import java.util.concurrent.atomic.AtomicBoolean;

public class DispatchConfig {

    /*
     * Maximum number of processes to start on a single
     * dispatching pass for a given node.
     */
    public static int MAX_PROCS_PER_JOB = 4;

    /*
     * Maximum number of cores to dispatch from a node per pass.
     * Can actually go over the max, but if you do then dispatching
     * switches to the next job.
     */
    public static int MAX_CORES_PER_JOB = 4;

    /*
     * Set to true once dispatching should start to happen.
     */
    public static AtomicBoolean IS_ENABLED = new AtomicBoolean(true);

}

package com.breakersoft.plow.dispatcher;

import java.util.concurrent.atomic.AtomicBoolean;

public class DispatchConfig {

    /*
     * Maximum number of processes to start on a single
     * dispatching pass for a given node.
     */
    public static int MAX_PROCS_PER_JOB = 16;

    /*
     * Maximum number of cores to dispatch from a node per pass.
     * Can actually go over the max, but if you do then dispatching
     * switches to the next job.
     */
    public static int MAX_CORES_PER_JOB = 16;

    /*
     * Set to true once dispatching should start to happen.
     */
    public static AtomicBoolean IS_ENABLED = new AtomicBoolean(true);

}

Allow the dispatcher to look lots of cores for now.


/*******************************************************************************
 * Copyright (C) 2018 Kwaku Twumasi-Afriyie <kwaku.twumasi@quakearts.com>
 *
 * This program and the accompanying materials are made
 * available under the terms of the Eclipse Public License 2.0
 * which is available at https://www.eclipse.org/legal/epl-2.0/
 *
 * SPDX-License-Identifier: EPL-2.0
 ******************************************************************************/
package com.quakearts.webapp.orm.cdi;

import javax.enterprise.inject.Produces;

import com.quakearts.webapp.orm.DataStoreFactory;
import com.quakearts.webapp.orm.cdi.annotation.DataStoreHandle;

public class DataStoreFactoryProducer {
	@Produces
	public @DataStoreHandle DataStoreFactory getDataStoreHandle() {
		return DataStoreFactory.getInstance();
	}
}

/*******************************************************************************
 * Copyright (C) 2018 Kwaku Twumasi-Afriyie <kwaku.twumasi@quakearts.com>
 *
 * This program and the accompanying materials are made
 * available under the terms of the Eclipse Public License 2.0
 * which is available at https://www.eclipse.org/legal/epl-2.0/
 *
 * SPDX-License-Identifier: EPL-2.0
 ******************************************************************************/
package com.quakearts.webapp.orm.cdi;

import javax.enterprise.inject.Produces;

import com.quakearts.webapp.orm.DataStoreFactory;
import com.quakearts.webapp.orm.cdi.annotation.DataStoreFactoryHandle;

public class DataStoreFactoryProducer {
	@Produces
	public @DataStoreFactoryHandle DataStoreFactory getDataStoreHandle() {
		return DataStoreFactory.getInstance();
	}
}

Use @DataStoreFactoryHandle instead of @DataStoreHandle


package de.ddb.pdc.storage;

import de.ddb.pdc.core.AnsweredQuestion;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.TimeZone;
import org.springframework.data.annotation.Id;

/**
 * Entity representing the PDC record structure in storage.
 */
public class StorageModel {

  @Id
  private String id;

  private final String itemId;
  private final String itemCategory;
  private final String institution;
  private final boolean publicDomain;
  private final List<AnsweredQuestion> trace;
  private final String timestamp;

  /**
   * Constructor for storing new records.
   * The timestamp is automatically assigned to the current date and time.
   */
  public StorageModel(String itemId, String itemCategory, String institution,
          boolean publicDomain, List<AnsweredQuestion> trace) {

    this.itemId = itemId;
    this.itemCategory = itemCategory;
    this.institution = institution;
    this.publicDomain = publicDomain;
    this.trace = trace;
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
    this.timestamp = sdf.format(new Date());
  }

  public String getItemId() {
    return itemId;
  }

  public String getItemCategory() {
    return itemCategory;
  }

  public String getInstitution() {
    return institution;
  }

  public boolean isPublicDomain() {
    return publicDomain;
  }

  public List<AnsweredQuestion> getTrace() {
    return trace;
  }

  public String getTimestampAsString() {
    return timestamp;
  }

}

package de.ddb.pdc.storage;

import de.ddb.pdc.core.AnsweredQuestion;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.TimeZone;
import org.springframework.data.annotation.Id;

/**
 * Entity representing the PDC record structure in storage.
 */
public class StorageModel {

  @Id
  private String id;

  private final String itemId;
  private final String itemCategory;
  private final String institution;
  private final Boolean publicDomain;
  private final List<AnsweredQuestion> trace;
  private final String timestamp;

  /**
   * Constructor for storing new records.
   * The timestamp is automatically assigned to the current date and time.
   */
  public StorageModel(String itemId, String itemCategory, String institution,
          Boolean publicDomain, List<AnsweredQuestion> trace) {

    this.itemId = itemId;
    this.itemCategory = itemCategory;
    this.institution = institution;
    this.publicDomain = publicDomain;
    this.trace = trace;
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
    this.timestamp = sdf.format(new Date());
  }

  public String getItemId() {
    return itemId;
  }

  public String getItemCategory() {
    return itemCategory;
  }

  public String getInstitution() {
    return institution;
  }

  public boolean isPublicDomain() {
    return publicDomain;
  }

  public List<AnsweredQuestion> getTrace() {
    return trace;
  }

  public String getTimestampAsString() {
    return timestamp;
  }

}

Add changes forgotten in the last commit :-(


package de.prob2.ui.consoles.b;

import com.google.inject.Inject;
import com.google.inject.Singleton;

import de.prob2.ui.consoles.Console;

@Singleton
public class BConsole extends Console {

	private BInterpreter interpreter;

	@Inject
	private BConsole(BInterpreter interpreter) {
		super();
		this.interpreter = interpreter;
		this.appendText("Prob 2.0 B Console \n >");
	}

	@Override
	protected void handleEnter() {
		super.handleEnterAbstract();
		String currentLine = getCurrentLine();
		if(currentLine.isEmpty()) {
			this.appendText("\nnull");
		} else {
			this.appendText("\n" + interpreter.exec(instructions.get(posInList)));
		}
		this.appendText("\n >");
		this.setEstimatedScrollY(Double.MAX_VALUE);
	}

}

package de.prob2.ui.consoles.b;

import com.google.inject.Inject;
import com.google.inject.Singleton;

import de.prob2.ui.consoles.Console;
import de.prob2.ui.consoles.ConsoleExecResult;
import de.prob2.ui.consoles.ConsoleExecResultType;

@Singleton
public class BConsole extends Console {

	private BInterpreter interpreter;

	@Inject
	private BConsole(BInterpreter interpreter) {
		super();
		this.interpreter = interpreter;
		this.appendText("Prob 2.0 B Console \n >");
	}

	@Override
	protected void handleEnter() {
		super.handleEnterAbstract();
		String currentLine = getCurrentLine();
		if(currentLine.isEmpty()) {
			this.appendText("\nnull");
		} else {
			ConsoleExecResult execResult = interpreter.exec(instructions.get(posInList));
			this.appendText("\n" + execResult);
			if(execResult.getResultType() == ConsoleExecResultType.ERROR) {
				int begin = this.getText().length() - execResult.toString().length();
				int end = this.getText().length();
				this.setStyleClass(begin, end, "error");
			}
		}
		this.appendText("\n >");
		this.setStyleClass(this.getText().length() - 2, this.getText().length(), "current");
		this.setEstimatedScrollY(Double.MAX_VALUE);
	}

}

Add error highlightening in B Console


package com.equalize.xpi.af.modules.tester;

import java.util.Hashtable;

import com.equalize.xpi.tester.util.ParameterHelper;

public class ModuleTesterMain {

	public static void main(String[] args) {
		try {
			// Default files
			String inputFile = "C:\\Users\\ksap086\\Desktop\\Excel2XML_Scenario1.xlsx";
			String paramFile = "C:\\Users\\ksap086\\Desktop\\Excel2XML_Scenario1_param.txt";
			String outFile = "C:\\Users\\ksap086\\Desktop\\output.txt";

			// Module to be tested
			String module = "com.equalize.xpi.af.modules.FormatConversionBean";

			// Get module parameters and initialize tester
			Hashtable<String, String> contextData = ParameterHelper.newInstance(paramFile).getParams();
			ModuleTester tester = ModuleTester.newInstance(module, inputFile, contextData);

			// Add dynamic configuration
			tester.addDynCfg("http://sap.com/xi/XI/System/File", "FileName", "FileA.txt");

			// Execute processing
			tester.getDynCfg("before");
			tester.execute(outFile);
			tester.getDynCfg("after");

		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}

package com.equalize.xpi.af.modules.tester;

import java.util.Hashtable;

import com.equalize.xpi.tester.util.ParameterHelper;

public class ModuleTesterMain {

	public static void main(String[] args) {
		try {
			// Sample arguments:-
			// arg0 - com.equalize.xpi.af.modules.FormatConversionBean
			// arg1 - C:\Users\ksap086\Desktop\input.txt
			// arg2 - C:\Users\ksap086\Desktop\param.txt
			// arg3 - C:\Users\ksap086\Desktop\output.txt
			if(args.length < 4)
				throw new RuntimeException("Please enter arguments in Run Configuration");

			// Module to be tested
			String module = args[0];
			// Files
			String inputFile = args[1];
			String paramFile = args[2];
			String outFile = args[3];

			// Get module parameters and initialize tester
			Hashtable<String, String> contextData = ParameterHelper.newInstance(paramFile).getParams();
			ModuleTester tester = ModuleTester.newInstance(module, inputFile, contextData);

			// Add dynamic configuration
			//tester.addDynCfg("http://sap.com/xi/XI/System/File", "FileName", "FileA.txt");

			// Execute processing
			tester.getDynCfg("before");
			tester.execute(outFile);
			tester.getDynCfg("after");

		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}

Change standalone module tester to use arguments as input


package com.tortel.deploytrack;

import java.util.List;

import com.tortel.deploytrack.data.*;

import android.content.Context;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;

public class DeploymentFragmentAdapter extends FragmentPagerAdapter {
	private List<Deployment> deployments;
	private DatabaseManager db;

	public DeploymentFragmentAdapter(Context context, FragmentManager fm){
		super(fm);
		db = DatabaseManager.getInstance(context);
		deployments = db.getAllDeployments();
	}

	public void reload(){
		Log.d("Reloading data");
		deployments = db.getAllDeployments();
		notifyDataSetChanged();
	}

	@Override
	public Fragment getItem(int position) {
		if(deployments.size() == position){
			return new NoDataFragment();
		}
		return DeploymentFragment.newInstance(deployments.get(position));
	}

	@Override
	public int getCount() {
		return deployments.size() + 1;
	}

	@Override
	public CharSequence getPageTitle(int position){
		if(deployments.size() == position){
			return "Welcome";
		}
		return deployments.get(position).getName();
	}

}

package com.tortel.deploytrack;

import java.util.List;

import com.tortel.deploytrack.data.*;

import android.content.Context;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;

public class DeploymentFragmentAdapter extends FragmentStatePagerAdapter {
	private List<Deployment> deployments;
	private DatabaseManager db;

	public DeploymentFragmentAdapter(Context context, FragmentManager fm){
		super(fm);
		db = DatabaseManager.getInstance(context);
		deployments = db.getAllDeployments();
	}

	public void reload(){
		Log.d("Reloading data");
		deployments = db.getAllDeployments();
		notifyDataSetChanged();
	}

	@Override
	public Fragment getItem(int position) {
		if(deployments.size() == position){
			return new NoDataFragment();
		}
		return DeploymentFragment.newInstance(deployments.get(position));
	}

	@Override
	public int getCount() {
		return deployments.size() + 1;
	}

	@Override
	public CharSequence getPageTitle(int position){
		if(deployments.size() == position){
			return "Welcome";
		}
		return deployments.get(position).getName();
	}

}

Change pager type to avoid NPEs


/*
 * Copyright (C) 2013,2014 The Cat Hive Developers.
 *
 * 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.
 */

/**
 * Internal implementation details of the fx-cdi framework.
 *
Classes of this package are not part of the public
 * API
 * and should not be used by application programmers directly!

 */

package com.cathive.fx.cdi.internal;

/*
 * Copyright (C) 2013,2014 The Cat Hive Developers.
 *
 * 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.
 */

/**
 * Internal implementation details of the fx-cdi framework.
 *
Classes of this package are not part of the public API
 * and should not be used by application programmers directly!

 */

package com.cathive.fx.cdi.internal;

Remove "abbr" element in Javadoc that causes javadoc generator to crash.


package org.freecode.irc.votebot.api;

import org.freecode.irc.Privmsg;
import org.freecode.irc.Transmittable;
import org.freecode.irc.votebot.FreeVoteBot;

import java.sql.Connection;

public abstract class AdminModule extends CommandModule {
    public AdminModule(FreeVoteBot fvb, Connection dbConn) {
        super(fvb, dbConn);
    }

    @Override
    public boolean canRun(Transmittable trns) {
        if (super.canRun(trns)) {
            String host = ((Privmsg) trns).getHost();
            for (String admin_host : FreeVoteBot.ADMIN_HOSTS) {
                if (host.equals(admin_host)) {
                    return true;
                }
            }
        }
        return false;
    }
}

package org.freecode.irc.votebot.api;

import org.freecode.irc.Notice;
import org.freecode.irc.Privmsg;
import org.freecode.irc.Transmittable;
import org.freecode.irc.votebot.FreeVoteBot;
import org.freecode.irc.votebot.NoticeFilter;

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

public abstract class AdminModule extends CommandModule {
    public AdminModule(FreeVoteBot fvb) {
        super(fvb);
    }

    @Override
    public void process(Transmittable trns) {
        final Privmsg privmsg = (Privmsg) trns;
        privmsg.getIrcConnection().addListener(new NoticeFilter() {
            public boolean accept(Notice notice) {
                Pattern pattern = Pattern.compile("\u0002(.+?)\u0002");
                Matcher matcher = pattern.matcher(notice.getMessage());
                if (matcher.find() && matcher.find()) {
                    String access = matcher.group(1);
                    System.out.println(access);
                    if (access.equals("Founder")) {
                        return notice.getNick().equals("ChanServ") && notice.getMessage().contains("Main nick:") && notice.getMessage().contains("\u0002" + privmsg.getNick() + "\u0002");
                    }
                }
                if (notice.getMessage().equals("Permission denied."))
                    notice.getIrcConnection().removeListener(this);
                return false;
            }

            public void run(Notice notice) {
                processMessage(privmsg);
                privmsg.getIrcConnection().removeListener(this);
            }
        });
        privmsg.getIrcConnection().send(new Privmsg("ChanServ", "WHY " + FreeVoteBot.CHANNEL + " " + privmsg.getNick(), privmsg.getIrcConnection()));
    }
}

Check access level instead of nick for Admin modules


package com.michaldabski.utils;

import android.util.SparseArray;
import android.view.View;

public class ViewHolder
{
	final View root;
	final SparseArray<View> views = new SparseArray<View>(3);

	public ViewHolder(View root)
	{
		this.root = root;
	}

	@SuppressWarnings("unchecked")
	public <T extends View> T getViewById(int id)
	{
		T view = (T) views.get(id);
		if (view == null)
		{
			views.put(id, (view = (T) root.findViewById(id)));
			if (view == null)
				throw new NullPointerException("Cannot find requested view id "+String.valueOf(id));
		}
		return view;
	}
}

package com.michaldabski.utils;

import android.util.SparseArray;
import android.view.View;

public class ViewHolder
{
	final View root;
	final SparseArray<View> views = new SparseArray<View>(3);

	public ViewHolder(View root)
	{
		this.root = root;
	}

	@SuppressWarnings("unchecked")
	public <T extends View> T getViewById(int id)
	{
		T view = (T) views.get(id);
		if (view == null)
		{
			views.put(id, (view = (T) root.findViewById(id)));
			if (view == null)
				throw new NullPointerException("Cannot find requested view id "+String.valueOf(id));
		}
		return view;
	}

	public boolean hasView(int id)
	{
		if (views.get(id) != null) return true;
		else
		{
			View view = this.root.findViewById(id);
			if (view == null) return false;
			else
			{
				views.put(id, view);
				return true;
			}
		}
	}
}

Add hasView() method to viewHolder


package org.sagebionetworks.bridge.config;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;

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

public class BridgeConfigTest {

    @Before
    public void before() {
        System.setProperty("bridge.pwd", "when.the.password.is.not.a.password");
        System.setProperty("bridge.salt", "when.the.salt.is.some.random.sea.salt");
    }

    @After
    public void after() {
        System.clearProperty("bridge.pwd");
        System.clearProperty("bridge.salt");
        System.clearProperty("bridge.env");
    }

    @Test
    public void testDefault() {
        BridgeConfig config = new BridgeConfig();
        assertTrue(config.isStub());
        assertNull(config.getProperty("someFakePropertyThatDoesNotExist"));
    }

    @Test
    public void testEncryption() {
        BridgeConfig config = new BridgeConfig();
        assertEquals("example.value", config.getProperty("example.property"));
        assertEquals("example.value.encrypted", config.getProperty("example.property.encrypted"));
    }

    @Test
    public void testEnvironment() {
        System.setProperty("bridge.env", "dev");
        BridgeConfig config = new BridgeConfig();
        assertEquals("example.value.for.dev", config.getProperty("example.property"));
    }
}

package org.sagebionetworks.bridge.config;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;

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

public class BridgeConfigTest {

    @Before
    public void before() {
        System.setProperty("bridge.pwd", "when.the.password.is.not.a.password");
        System.setProperty("bridge.salt", "when.the.salt.is.some.random.sea.salt");
        System.setProperty("bridge.user", "unit.test");
    }

    @After
    public void after() {
        System.clearProperty("bridge.pwd");
        System.clearProperty("bridge.salt");
        System.clearProperty("bridge.user");
        System.clearProperty("bridge.env");
    }

    @Test
    public void testDefault() {
        BridgeConfig config = new BridgeConfig();
        assertTrue(config.isStub());
        assertNull(config.getProperty("someFakePropertyThatDoesNotExist"));
    }

    @Test
    public void testEncryption() {
        BridgeConfig config = new BridgeConfig();
        assertEquals("example.value", config.getProperty("example.property"));
        assertEquals("example.value.encrypted", config.getProperty("example.property.encrypted"));
    }

    @Test
    public void testEnvironment() {
        System.setProperty("bridge.env", "dev");
        BridgeConfig config = new BridgeConfig();
        assertEquals("example.value.for.dev", config.getProperty("example.property"));
    }

    @Test
    public void testUser() {
        BridgeConfig config = new BridgeConfig();
        assertEquals("unit.test", config.getProperty("bridge.user"));
    }
}

Add bridge.user to the config.


/*
 * #%L
 * GwtMaterial
 * %%
 * Copyright (C) 2015 - 2018 GwtMaterialDesign
 * %%
 * 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.
 * #L%
 */
package gwt.material.design.client.js;

import gwt.material.design.client.base.helper.ScrollHelper;
import jsinterop.annotations.JsPackage;
import jsinterop.annotations.JsProperty;
import jsinterop.annotations.JsType;

/**
 * JSInterop util for {@link ScrollHelper}
 *
 * @author kevzlou7979@gmail.com
 */
@JsType(isNative = true, name = "Object", namespace = JsPackage.GLOBAL)
public class ScrollOption {

    @JsProperty
    public double scrollTop;
}

/*
 * #%L
 * GwtMaterial
 * %%
 * Copyright (C) 2015 - 2018 GwtMaterialDesign
 * %%
 * 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.
 * #L%
 */
package gwt.material.design.client.js;

import gwt.material.design.client.base.helper.ScrollHelper;
import jsinterop.annotations.JsPackage;
import jsinterop.annotations.JsProperty;
import jsinterop.annotations.JsType;

/**
 * JSInterop util for {@link ScrollHelper}
 *
 * @author kevzlou7979@gmail.com
 */
@JsType(isNative = true, name = "Object", namespace = JsPackage.GLOBAL)
public class ScrollOption {

    @JsProperty
    public Object scrollTop;
}

Convert scroll top to Object


package beaform.debug;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

public class AsyncDebugUtils {
	private static final ExecutorService EXECUTOR = Executors.newSingleThreadExecutor();

	public static Future<String> clearDb() {
		return EXECUTOR.submit(new ClearDbTask(), "Done");
	}

	public static Future<String> listAllFormulas() {
		return EXECUTOR.submit(new ListFormulasTask(), "Done");
	}

	public static Future<String> fillDb() {
		return EXECUTOR.submit(new FillDbTask(), "Done");
	}
}

package beaform.debug;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

public final class AsyncDebugUtils {

	private static final ExecutorService EXECUTOR = Executors.newSingleThreadExecutor();

	private AsyncDebugUtils() {
		// Utility classes don't need public constructors
	}

	public static Future<String> clearDb() {
		return EXECUTOR.submit(new ClearDbTask(), "Done");
	}

	public static Future<String> listAllFormulas() {
		return EXECUTOR.submit(new ListFormulasTask(), "Done");
	}

	public static Future<String> fillDb() {
		return EXECUTOR.submit(new FillDbTask(), "Done");
	}
}

Mark this class as a utility class


package fi.helsinki.cs.tmc.cli.command;

import fi.helsinki.cs.tmc.cli.Application;

import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.GnuParser;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;

/**
 * Class is a test command class.
 */
public class TestCommand implements Command {
    private Options options;
    private GnuParser parser;

    public TestCommand(Application app) {
        this.parser = new GnuParser();
        this.options = new Options();
        options.addOption("a", false, "testikomento");
    }

    @Override
    public String getDescription() {
        return "This is an easter egg test command.";
    }

    @Override
    public String getName() {
        return "EasterEgg";
    }

    @Override
    public void run(String[] args) {
        try {
            CommandLine line = this.parser.parse(options, args);
            if (line.hasOption("a")) {
                System.out.println("Let's run easter egg with -a");
            } else {
                System.out.println("Let's run easter egg.");
            }
        } catch (ParseException exp) {
            System.err.println("Parsing failed.  Reason: " + exp.getMessage());
        }
    }
}

package fi.helsinki.cs.tmc.cli.command;

import fi.helsinki.cs.tmc.cli.Application;

import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.GnuParser;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;

/**
 * Class is a test command class.
 */
public class TestCommand implements Command {
    private Options options;
    private GnuParser parser;

    public TestCommand(Application app) {
        this.parser = new GnuParser();
        this.options = new Options();
        options.addOption("a", false, "testikomento");
    }

    @Override
    public String getDescription() {
        return "This is an easter egg test command.";
    }

    @Override
    public String getName() {
        return "easter-egg";
    }

    @Override
    public void run(String[] args) {
        try {
            CommandLine line = this.parser.parse(options, args);
            if (line.hasOption("a")) {
                System.out.println("Let's run easter egg with -a");
            } else {
                System.out.println("Let's run easter egg.");
            }
        } catch (ParseException exp) {
            System.err.println("Parsing failed.  Reason: " + exp.getMessage());
        }
    }
}

Rename the easter egg command.


package org.pharmgkb.parsers;

import java.io.IOException;
import java.io.PrintWriter;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Collection;
import java.util.function.Function;
import java.util.stream.Stream;
import javax.annotation.Nonnegative;
import javax.annotation.Nonnull;

/**
 * Counterpart to {@link LineParser}.
 *
 * @author Douglas Myers-Turnbull
 */
public interface LineWriter<T> extends Function<T, String> {

  default void writeToFile(@Nonnull Collection<T> lines, @Nonnull Path file) throws IOException {
    try (PrintWriter pw = new PrintWriter(Files.newBufferedWriter(file))) {
      lines.stream()
          .map(this)
          .forEach(pw::println);
    }
  }

  /**
   * Override this to add post- or pre- validation or processing.
   */
  default @Nonnull Stream<String> writeAll(@Nonnull Stream<T> stream) {
    return stream.map(this);
  }

  /**
   * @return The total number of lines this writer processed since its creation
   */
  @Nonnegative
  long nLinesProcessed();

  @Override
  @Nonnull String apply(@Nonnull T t);
}

package org.pharmgkb.parsers;

import java.io.IOException;
import java.io.PrintWriter;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Collection;
import java.util.function.Function;
import java.util.stream.Stream;
import javax.annotation.Nonnegative;
import javax.annotation.Nonnull;

/**
 * Counterpart to {@link LineParser}.
 *
 * @author Douglas Myers-Turnbull
 */
public interface LineWriter<T> extends Function<T, String> {

  default void writeToFile(@Nonnull Collection<T> lines, @Nonnull Path file) throws IOException {
    try (PrintWriter pw = new PrintWriter(Files.newBufferedWriter(file))) {
      writeAll(lines.stream())
          .forEach(pw::println);
    }
  }

  /**
   * Override this to add post- or pre- validation or processing.
   */
  default @Nonnull Stream<String> writeAll(@Nonnull Stream<T> stream) {
    return stream.map(this);
  }

  /**
   * @return The total number of lines this writer processed since its creation
   */
  @Nonnegative
  long nLinesProcessed();

  @Override
  @Nonnull String apply(@Nonnull T t);
}

Call writeAll() to make sure pre/post operations by subclasses get applied properly.


package com.github.zhanhb.judge.common;

import java.nio.file.Path;
import lombok.Builder;
import lombok.Getter;
import lombok.Value;

@Builder(builderClassName = "Builder")
@Getter
@Value
@SuppressWarnings("FinalClass")
public class Options {

    private Path inputFile;
    private Path errFile;
    private Path outputFile; // 提交程序的输出文件
    private Path standardOutput; // 标程输出的文件
    private long timeLimit;
    private long memoryLimit;
    private long outputLimit;
    private boolean redirectErrorStream;
    private String command;
    private Path workDirectory;

}

package com.github.zhanhb.judge.common;

import java.nio.file.Path;
import lombok.Builder;
import lombok.Getter;
import lombok.Value;

@Builder(builderClassName = "Builder")
@Getter
@Value
@SuppressWarnings("FinalClass")
public class Options {

    private Path inputFile;
    private Path errFile;
    private Path outputFile; // 提交程序的输出文件
    private Path standardOutput; // 标程输出的文件
    private long timeLimit;
    private long memoryLimit;
    private long outputLimit;
    private boolean redirectErrorStream;
    private String command;
    private Path workDirectory;

    @SuppressWarnings("PublicInnerClass")
    public static class Builder {

        Builder() {
            timeLimit = Long.MAX_VALUE;
            memoryLimit = Long.MAX_VALUE;
            outputLimit = Long.MAX_VALUE;
        }

    }

}

Add default option builder limits


package com.googlecode.mp4parser.boxes.apple;

import java.nio.ByteBuffer;

/**
 * Created by sannies on 10/15/13.
 */
public class AppleTrackNumberBox extends AppleDataBox {
    public AppleTrackNumberBox() {
        super("tkrn", 0);
    }

    int a;
    int b;

    public int getA() {
        return a;
    }

    public void setA(int a) {
        this.a = a;
    }

    public int getB() {
        return b;
    }

    public void setB(int b) {
        this.b = b;
    }

    @Override
    protected byte[] writeData() {
        ByteBuffer bb = ByteBuffer.allocate(8);
        bb.putInt(a);
        bb.putInt(b);
        return bb.array();
    }

    @Override
    protected void parseData(ByteBuffer data) {
        a = data.getInt();
        b = data.getInt();
    }

    @Override
    protected int getDataLength() {
        return 8;
    }
}

package com.googlecode.mp4parser.boxes.apple;

import java.nio.ByteBuffer;

/**
 * Created by sannies on 10/15/13.
 */
public class AppleTrackNumberBox extends AppleDataBox {
    public AppleTrackNumberBox() {
        super("trkn", 0);
    }

    int a;
    int b;

    public int getA() {
        return a;
    }

    public void setA(int a) {
        this.a = a;
    }

    public int getB() {
        return b;
    }

    public void setB(int b) {
        this.b = b;
    }

    @Override
    protected byte[] writeData() {
        ByteBuffer bb = ByteBuffer.allocate(8);
        bb.putInt(a);
        bb.putInt(b);
        return bb.array();
    }

    @Override
    protected void parseData(ByteBuffer data) {
        a = data.getInt();
        b = data.getInt();
    }

    @Override
    protected int getDataLength() {
        return 8;
    }
}

Fix typo tkrn -> trkn (patch by m krueger)


package me.hfox.morphix.annotation;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Reference {

    public boolean dbRef() default true;

}

package me.hfox.morphix.annotation;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Reference {

    public boolean dbRef() default false;

}

Change default value of dbRef to false


package ch.poole.openinghoursparser;

import java.io.ByteArrayInputStream;
import java.util.List;
import java.util.Scanner;

/**
 * Individual testing for the OpeningHoursParser, receiving
 * inputs from System.in
 *
 *
 * @author Vuong Ho
 *
 */

public class IndividualTest {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        Boolean isStrict = args[0].equals("true");
        while(true) {
            System.out.print("Please enter your input: ");
            String input = sc.nextLine();
            try {
                OpeningHoursParser parser = new OpeningHoursParser(new ByteArrayInputStream(input.getBytes()));
                List<ch.poole.openinghoursparser.Rule> rules = parser.rules(isStrict);
                System.out.println("Legal input string");
                System.out.println("Detected rules in input string listed below");
                for(ch.poole.openinghoursparser.Rule rule : rules) {
                    System.out.println(rule.toDebugString());
                }
                System.out.println("\n------------------------------\n");
            } catch (OpeningHoursParseException e) {
                System.out.println("Illegal input string");
                e.printStackTrace();
                System.out.println("\n------------------------------\n");
            }
        }
    }
}

package ch.poole.openinghoursparser;

import java.io.ByteArrayInputStream;
import java.util.List;
import java.util.Scanner;

/**
 * Individual testing for the OpeningHoursParser, receiving inputs from System.in
 *
 *
 * @author Vuong Ho
 *
 */
public class IndividualTest {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        Boolean isStrict = args[0].equals("true");
        System.out.println("Parse strings in opening-hours format, empty input will terminate");
        while (true) {
            System.out.print("Please enter your input: ");
            String input = sc.nextLine();
            if ("".equals(input)) {
                break;
            }
            try {
                OpeningHoursParser parser = new OpeningHoursParser(new ByteArrayInputStream(input.getBytes()));
                List<ch.poole.openinghoursparser.Rule> rules = parser.rules(isStrict);
                System.out.println("Legal input string");
                System.out.println("Detected rules in input string listed below");
                System.out.println("\n------------------------------\n");
                for (ch.poole.openinghoursparser.Rule rule : rules) {
                    System.out.println(rule.toDebugString());
                }
                System.out.println("\n------------------------------\n");
            } catch (OpeningHoursParseException e) {
                System.out.println("Illegal input string");
                e.printStackTrace();
                System.out.println("\n------------------------------\n");
            }
        }
    }
}

Allow empty input to terminate testing


package fi.helsinki.cs.tmc.cli.tmcstuff;

import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertNotNull;

import fi.helsinki.cs.tmc.cli.Application;

import fi.helsinki.cs.tmc.core.TmcCore;
import fi.helsinki.cs.tmc.core.domain.Course;

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

import java.util.Locale;

public class TmcUtilTest {

    @Test
    public void findCouseIfItExists() {
        Application app;
        Course course;

        app = new Application();
        course = TmcUtil.findCourse(app.getTmcCore(), "demo");
        assertNotNull(course);
    }

    @Test
    public void returnNullIfCourseWontExist() {
        Application app;
        Course course;

        app = new Application();
        course = TmcUtil.findCourse(app.getTmcCore(), "afuwhf");
        assertNull(course);
    }
}

package fi.helsinki.cs.tmc.cli.tmcstuff;

import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;

import fi.helsinki.cs.tmc.cli.Application;

import fi.helsinki.cs.tmc.core.TmcCore;
import fi.helsinki.cs.tmc.core.domain.Course;

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

import java.util.Locale;

public class TmcUtilTest {

    @Test
    public void findCouseIfItExists() {
        Application app;
        Course course;

        app = new Application();
        course = TmcUtil.findCourse(app.getTmcCore(), "demo");
        assertNotNull(course);
    }

    @Test
    public void returnNullIfCourseWontExist() {
        Application app;
        Course course;

        app = new Application();
        course = TmcUtil.findCourse(app.getTmcCore(), "afuwhf");
        assertNull(course);
    }
}

Fix the import order in the new tests.


/**
 * Traq desktop application.
 *
 * @author Jack Polgar <jack@polgar.id.au>
 * @license Apache-2.0
 */

import javax.swing.*;
import traq.models.Project;

/**
 * Main application.
 */
public class Traq {
    /**
     * Set to create main window.
     */
    public static void main(String args[]) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                JFrame mainWindow = new JFrame("Traq");
                mainWindow.setSize(600,500);
                mainWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

                Project testProject = new Project(0, "Test", "testing", "Just a test");

                JPanel testPanel = new JPanel();
                JLabel projectName = new JLabel(testProject.getName());
                JLabel projectSlug = new JLabel(testProject.getSlug());
                JLabel projectDescription = new JLabel(testProject.getDescription());

                testPanel.add(projectName);
                testPanel.add(projectSlug);
                testPanel.add(projectDescription);

                mainWindow.add(testPanel);

                mainWindow.setVisible(true);
            }
        });
    }
}

/**
 * Traq desktop application.
 *
 * @author Jack Polgar <jack@polgar.id.au>
 * @license Apache-2.0
 */

import javax.swing.*;

import java.util.ArrayList;

import traq.models.Project;
import traq.models.Site;

/**
 * Main application.
 */
public class Traq {
    /**
     * Set to create main window.
     */
    public static void main(String args[]) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                JFrame mainWindow = new JFrame("Traq");
                mainWindow.setSize(600,500);
                mainWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

                Site currentSite = new Site("Traq", "https://bugs.traq.io");

                ArrayList<Project> projects = currentSite.getProjects();
                Project testProject = projects.get(0);

                JPanel testPanel = new JPanel();
                JLabel projectName = new JLabel(testProject.getName());
                JLabel projectSlug = new JLabel(testProject.getSlug());
                JLabel projectDescription = new JLabel(testProject.getDescription());

                testPanel.add(projectName);
                testPanel.add(projectSlug);
                testPanel.add(projectDescription);

                mainWindow.add(testPanel);

                mainWindow.setVisible(true);
            }
        });
    }
}

Use the API to fetch projects.