package com.sinyuk.yuk.utils;

import android.support.v4.view.animation.FastOutSlowInInterpolator;
import android.view.ViewPropertyAnimator;

import fr.castorflex.android.smoothprogressbar.SmoothProgressBar;

/**
 * Created by Sinyuk on 16/8/15.
 */
public class BlackMagics {
    /*
     * 进度条上移
     * @param v
     * @param withLayer
     */
    public static ViewPropertyAnimator scrollUp(SmoothProgressBar progressBar) {
        Preconditions.checkNotNull(progressBar,"progressBar is Null");
        final int offset = progressBar.getHeight();
        progressBar.setTranslationY(offset);
        progressBar.setAlpha(0.01f);
        return progressBar.animate()
                .translationY(0)
                .alpha(1)
                .setDuration(400)
                .setInterpolator(new FastOutSlowInInterpolator())
                .withLayer();
    }

    /*
    * 进度条下移
    * @param v
    * @param withLayer
    */
    public static ViewPropertyAnimator scrollDown(SmoothProgressBar progressBar) {
        Preconditions.checkNotNull(progressBar,"progressBar is Null");
        final int offset = progressBar.getHeight();
        return progressBar.animate()
                .translationY(offset)
                .alpha(0.01f)
                .setDuration(400)
                .setInterpolator(new FastOutSlowInInterpolator())
                .withLayer();
    }
}

package com.sinyuk.yuk.utils;

import android.support.v4.view.animation.FastOutSlowInInterpolator;
import android.view.ViewPropertyAnimator;

import fr.castorflex.android.smoothprogressbar.SmoothProgressBar;

/**
 * Created by Sinyuk on 16/8/15.
 */
public class BlackMagics {
    /*
     * 进度条上移
     * @param v
     * @param withLayer
     */
    public static ViewPropertyAnimator fadeOut(SmoothProgressBar progressBar) {
        Preconditions.checkNotNull(progressBar,"progressBar is Null");
        return progressBar.animate()
                .alpha(0)
                .setDuration(400)
                .setInterpolator(new FastOutSlowInInterpolator())
                .withLayer();
    }

    /*
    * 进度条下移
    * @param v
    * @param withLayer
    */
    public static ViewPropertyAnimator fadeIn(SmoothProgressBar progressBar) {
        Preconditions.checkNotNull(progressBar,"progressBar is Null");
        return progressBar.animate()
                .alpha(1f)
                .setDuration(400)
                .setInterpolator(new FastOutSlowInInterpolator())
                .withLayer();
    }
}

Use fade in/out animation instead

Use fade in/out animation instead


package ts.resources;

import ts.LineOffset;
import ts.TSException;
import ts.internal.LineOffsetReader;

public abstract class AbstractTypeScriptFile implements ITypeScriptFile {

	private final String name;
	private boolean dirty;

	public AbstractTypeScriptFile(String name) {
		this.name = name;
		this.setDirty(true);
	}

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

	@Override
	public void setDirty(boolean dirty) {
		this.dirty = dirty;
	}

	@Override
	public boolean isDirty() {
		return dirty;
	}

	@Override
	public LineOffset getLineOffset(int position) throws TSException {
		return new LineOffsetReader(getContents(), position).getLineOffset();
	}
}

package ts.resources;

import ts.LineOffset;
import ts.TSException;
import ts.internal.LineOffsetReader;

public abstract class AbstractTypeScriptFile implements ITypeScriptFile {

	private final String name;
	private boolean dirty;

	public AbstractTypeScriptFile(String name) {
		this.name = name;
		this.setDirty(false);
	}

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

	@Override
	public void setDirty(boolean dirty) {
		this.dirty = dirty;
	}

	@Override
	public boolean isDirty() {
		return dirty;
	}

	@Override
	public LineOffset getLineOffset(int position) throws TSException {
		return new LineOffsetReader(getContents(), position).getLineOffset();
	}
}

Set dirty to false the first time.

Set dirty to false the first time.


package org.jetbrains.kotlin.ui.editors;

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

import org.eclipse.jface.text.TextAttribute;
import org.eclipse.jface.text.rules.IRule;
import org.eclipse.jface.text.rules.IToken;
import org.eclipse.jface.text.rules.RuleBasedScanner;
import org.eclipse.jface.text.rules.SingleLineRule;
import org.eclipse.jface.text.rules.Token;
import org.eclipse.jface.text.rules.WhitespaceRule;
import org.eclipse.jface.text.rules.WordRule;

public class Scanner extends RuleBasedScanner {

        public Scanner(ColorManager manager) {
        IToken keyword = new Token(new TextAttribute(manager.getColor(IColorConstants.KEYWORD)));
        IToken string = new Token(new TextAttribute(manager.getColor(IColorConstants.STRING)));

        List<IRule> rulesList = new ArrayList<IRule>();

        WordRule wr = new WordRule(new WordDetector());
        for (String word : KeywordManager.getAllKeywords()) {
            wr.addWord(word, keyword);
        }
        rulesList.add(wr);
        rulesList.add(new SingleLineRule("\"", "\"", string, '\\'));
        rulesList.add(new WhitespaceRule(new WhitespaceDetector()));

        IRule[] rules = new IRule[rulesList.size()];
        rules = rulesList.toArray(rules);

        setRules(rules);
    }

}

package org.jetbrains.kotlin.ui.editors;

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

import org.eclipse.jface.text.TextAttribute;
import org.eclipse.jface.text.rules.IRule;
import org.eclipse.jface.text.rules.IToken;
import org.eclipse.jface.text.rules.RuleBasedScanner;
import org.eclipse.jface.text.rules.SingleLineRule;
import org.eclipse.jface.text.rules.Token;
import org.eclipse.jface.text.rules.WhitespaceRule;
import org.eclipse.jface.text.rules.WordRule;

public class Scanner extends RuleBasedScanner {

    public Scanner(ColorManager manager) {
        IToken keyword = new Token(new TextAttribute(manager.getColor(IColorConstants.KEYWORD)));
        IToken string = new Token(new TextAttribute(manager.getColor(IColorConstants.STRING)));

        List<IRule> rulesList = new ArrayList<IRule>();

        IToken defaultToken = new Token(new TextAttribute(manager.getColor(IColorConstants.DEFAULT)));
        WordRule wr = new WordRule(new WordDetector(), defaultToken);
        for (String word : KeywordManager.getAllKeywords()) {
            wr.addWord(word, keyword);
        }
        rulesList.add(wr);
        rulesList.add(new SingleLineRule("\"", "\"", string, '\\'));
        rulesList.add(new WhitespaceRule(new WhitespaceDetector()));

        IRule[] rules = new IRule[rulesList.size()];
        rules = rulesList.toArray(rules);

        setRules(rules);
    }

}

Fix bug with code highlightning when keyword in suffix


package com.dkarv.testcases.anonymous;

public class Main {
  Number n;

  public Main(int offset) {
    // test
    if (offset != 0) {
      n = new Number() {
        public void add(int j) {
          this.n = j + offset;
        }
      };
    } else {
      n = new Number();
    }
  }

  public static void main(String[] args) {
    Main main = new Main(2);
    main.n.add(1);
  }
}

package com.dkarv.testcases.anonymous;

public class Main {
  Number n;

  public Main(final int offset) {
    // test
    if (offset != 0) {
      n = new Number() {
        public void add(int j) {
          this.n = j + offset;
        }
      };
    } else {
      n = new Number();
    }
  }

  public static void main(String[] args) {
    Main main = new Main(2);
    main.n.add(1);
  }
}

Make integration test compatible to Java 7


package org.azavea.otm.data;

import org.json.JSONException;

public class SpeciesContainer extends ModelContainer<Species> {

	@Override
	public Species[] getAll() {
		Species[] species = new Species[data.length()];
		for (int i = 0; i < data.length(); i++) {
			species[i] = new Species();
			try {
				species[i].setData(data.getJSONObject(i));
			} catch (JSONException e) {
				e.printStackTrace();
			}
		}
		return species;
	}

}

package org.azavea.otm.data;

import java.util.LinkedHashMap;

import org.json.JSONException;

public class SpeciesContainer extends ModelContainer<Species> {

	@Override
	public LinkedHashMap<Integer,Species> getAll() {
		LinkedHashMap<Integer,Species> speciesList =
				new LinkedHashMap<Integer,Species>(data.length());
		for (int i = 0; i < data.length(); i++) {
			try {
				Species species = new Species();
				species.setData(data.getJSONObject(i));
				speciesList.put(species.getId(), species);

			} catch (JSONException e) {
				e.printStackTrace();
			}
		}
		return speciesList;
	}

}

Implement getAll to return Hash

Implement getAll to return Hash

Species come back ordered by common name.  Preserving this sorting lets
us change the default sort order by just changing the API, which we have
more control over than for installed applications.


package com.herocc.bukkit.core.commands;

import org.bukkit.ChatColor;
import org.bukkit.Material;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;

import com.herocc.bukkit.core.Core;

public class CommandFakeblock implements CommandExecutor {
	private final Core plugin = Core.getPlugin();

	@SuppressWarnings("deprecation")
	@Override
	public boolean onCommand(CommandSender sender, Command cmd, String label, String[] arg) {
		if (cmd.getName().equalsIgnoreCase("fakeblock")) {
	        if (sender.hasPermission("core.head.get")) {
	        	Player player = (Player) sender;
	        	player.sendBlockChange(player.getLocation(), Material.WOOL, (byte) 0);
	        	sender.sendMessage("The block has changed!");
	        } else {
	        	sender.sendMessage(ChatColor.RED + "Sorry, You do not have permission to use this command!");
	        }
		}
		return false;
	}

}

package com.herocc.bukkit.core.commands;

import org.bukkit.ChatColor;
import org.bukkit.Material;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;

import com.herocc.bukkit.core.Core;

public class CommandFakeblock implements CommandExecutor {
	private final Core plugin = Core.getPlugin();

	@SuppressWarnings("deprecation")
	@Override
	public boolean onCommand(CommandSender sender, Command cmd, String label, String[] arg) {
		if (cmd.getName().equalsIgnoreCase("fakeblock")) {
	        if (sender.hasPermission("core.head.get")) {
	        	Player player = (Player) sender;
	        	player.sendBlockChange(player.getLocation(), Material.WOOL, (byte) 0);
	        	sender.sendMessage(ChatColor.GREEN + "The block has changed!");
	        } else {
	        	sender.sendMessage(ChatColor.RED + "Sorry, You do not have permission to use this command!");
	        }
		}
		return false;
	}

}

Add a color green to the message.

Add a color green to the message.


package nerd.tuxmobil.fahrplan.congress.navigation;

import android.support.annotation.NonNull;
import android.support.annotation.Nullable;

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

public class RoomForC3NavConverter {

    private final static Map<String, String> ROOM_TO_C3NAV_MAPPING = new HashMap<String, String>() {{
        put("HALL 1", "h1");
        put("HALL 2", "h2");
        put("HALL 3", "h3");
        put("HALL 6", "h6");
        put("HALL 13", "h13");
        put("HALL 14", "h14");

        put("HALL B", "hb");
        put("HALL G", "hg");
        put("HALL F", "hf");
    }};

    @Nullable
    public static String convert(@NonNull final String venue, @Nullable final String room) {
        if (room != null && venue.toUpperCase().equals("CCH")) {
            return ROOM_TO_C3NAV_MAPPING.get(room.toUpperCase());
        }
        return null;
    }

}

package nerd.tuxmobil.fahrplan.congress.navigation;

import android.support.annotation.NonNull;
import android.support.annotation.Nullable;

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

public class RoomForC3NavConverter {

    private static final Map<String, String> ROOM_TO_C3NAV_MAPPING = new HashMap<String, String>() {{
        put("HALL 1", "h1");
        put("HALL 2", "h2");
        put("HALL 3", "h3");
        put("HALL 6", "h6");
        put("HALL 13", "h13");
        put("HALL 14", "h14");

        put("HALL B", "hb");
        put("HALL G", "hg");
        put("HALL F", "hf");
    }};

    @Nullable
    public static String convert(@NonNull final String venue, @Nullable final String room) {
        if (room != null && venue.toUpperCase().equals("CCH")) {
            return ROOM_TO_C3NAV_MAPPING.get(room.toUpperCase());
        }
        return null;
    }

}

Order qualifier corresponding to Java conventions.


package com.novoda.simplechromecustomtabs;

import com.novoda.notils.exception.DeveloperError;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.RuntimeEnvironment;

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

@RunWith(RobolectricTestRunner.class)
public class SimpleChromeCustomTabsTest {

    @Test(expected = DeveloperError.class)
    public void givenSimpleChromeCustomTabsIsNotInitialised_whenGettingInstance_thenDeveloperErrorIsThrown() {
        SimpleChromeCustomTabs.getInstance();
    }

    @Test
    public void givenSimpleChromeCustomTabsIsInitialised_whenGettingInstance_thenInstanceIsReturned() {
        SimpleChromeCustomTabs.initialize(RuntimeEnvironment.application);

        assertThat(SimpleChromeCustomTabs.getInstance()).isInstanceOf(SimpleChromeCustomTabs.class);
    }

}

package com.novoda.simplechromecustomtabs;

import com.novoda.notils.exception.DeveloperError;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.RuntimeEnvironment;

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

@RunWith(RobolectricTestRunner.class)
public class SimpleChromeCustomTabsTest {

    @Test
    public void givenSimpleChromeCustomTabsIsNotInitialised_whenGettingInstance_thenDeveloperErrorIsThrown() {
        try {
            SimpleChromeCustomTabs.getInstance();
            fail("A Developer error exception was expected, but there was nothing");
        } catch (DeveloperError e) {
            // passes
        }
    }

    @Test
    public void givenSimpleChromeCustomTabsIsInitialised_whenGettingInstance_thenInstanceIsReturned() {
        SimpleChromeCustomTabs.initialize(RuntimeEnvironment.application);

        assertThat(SimpleChromeCustomTabs.getInstance()).isInstanceOf(SimpleChromeCustomTabs.class);
    }

}

Fix a test that was broken on some versions of java 8. Will change in the future


package com.couchbase.lite;

import android.support.annotation.NonNull;

import com.couchbase.lite.internal.replicator.CBLWebSocket;
import com.couchbase.litecore.C4Socket;

public final class Replicator extends AbstractReplicator {
    /**
     * Initializes a replicator with the given configuration.
     *
     * @param config
     */
    public Replicator(@NonNull ReplicatorConfiguration config) {
        super(config);
    }

    @Override
    void initC4Socket(int hash) {
        C4Socket.socketFactory.put(hash, CBLWebSocket.class);
    }

    @Override
    int framing() {
        return C4Socket.kC4NoFraming;
    }

    @Override
    String schema() {
        return null;
    }
}

package com.couchbase.lite;

import android.support.annotation.NonNull;

import com.couchbase.lite.internal.replicator.CBLWebSocket;
import com.couchbase.litecore.C4Socket;

public final class Replicator extends AbstractReplicator {
    /**
     * Initializes a replicator with the given configuration.
     *
     * @param config
     */
    public Replicator(@NonNull ReplicatorConfiguration config) {
        super(config);
    }

    @Override
    void initSocketFactory(Object socketFactoryContext) {
        C4Socket.socketFactory.put(socketFactoryContext, CBLWebSocket.class);
    }

    @Override
    int framing() {
        return C4Socket.kC4NoFraming;
    }

    @Override
    String schema() {
        return null;
    }
}

Fix Replication compilation error (CE)

Fix Replication compilation error (CE)

We have changed an abstact method initC4Socket(int) to initSocketFactory(Object). The implmenation change has been made to the EE version. The CE version of the Replicator class needs to follow.


package com.amazonaws.services.dynamodbv2.datamodeling;

import static org.junit.Assert.assertEquals;

import org.junit.Test;
import com.amazonaws.services.dynamodbv2.model.DeleteTableRequest;

public class DynamoDBMapperTest {

    @Test
    public void testGenerateDeleteTableRequest(){
        String prefix = "DEV-";
        final String tableName = "OBJECTORMEXAMPLE";

        DynamoDBMapperConfig.TableNameOverride tableNameOverride =
                DynamoDBMapperConfig.TableNameOverride.withTableNamePrefix(prefix);
        DynamoDBMapperConfig config = new DynamoDBMapperConfig(tableNameOverride);
        DynamoDBMapper dynamoDBMapper = new DynamoDBMapper(null, config);

        // Create the simplest table as possible for our test purposes only
        @DynamoDBTable(tableName = tableName)
        class ObjectORMExample{}

        // test
        DeleteTableRequest deleteTableRequest = dynamoDBMapper.generateDeleteTableRequest(ObjectORMExample.class);
        assertEquals(deleteTableRequest.getTableName(), prefix.concat(tableName));
    }

}

package com.amazonaws.services.dynamodbv2.datamodeling;

import static org.junit.Assert.assertEquals;

import org.junit.Test;
import com.amazonaws.services.dynamodbv2.model.DeleteTableRequest;

public class DynamoDBMapperTest {

    @Test
    public void testGenerateDeleteTableRequest1(){
        final String tableName = "OBJECTORMEXAMPLE";

        DynamoDBMapper dynamoDBMapper = new DynamoDBMapper(null);

        // Create the simplest table as possible for our test purposes only
        @DynamoDBTable(tableName = tableName)
        class ObjectORMExample{}

        // test
        DeleteTableRequest deleteTableRequest = dynamoDBMapper.generateDeleteTableRequest(ObjectORMExample.class);
        assertEquals(deleteTableRequest.getTableName(), tableName);
    }

    @Test
    public void testGenerateDeleteTableRequest2(){
        String prefix = "DEV-";
        final String tableName = "OBJECTORMEXAMPLE";

        DynamoDBMapperConfig.TableNameOverride tableNameOverride =
                DynamoDBMapperConfig.TableNameOverride.withTableNamePrefix(prefix);
        DynamoDBMapperConfig config = new DynamoDBMapperConfig(tableNameOverride);
        DynamoDBMapper dynamoDBMapper = new DynamoDBMapper(null, config);

        // Create the simplest table as possible for our test purposes only
        @DynamoDBTable(tableName = tableName)
        class ObjectORMExample{}

        // test
        DeleteTableRequest deleteTableRequest = dynamoDBMapper.generateDeleteTableRequest(ObjectORMExample.class);
        assertEquals(deleteTableRequest.getTableName(), prefix.concat(tableName));
    }

}

Add test not overriding table name

Add test not overriding table name


package com.github.aesteve.vertx.nubes.utils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;

/**
 * Singleton pattern implementation using enums.
 *
 * See "Effective Java" by Joshua Bloch
 *
 * @author aesteve
 */
public enum DateUtils {

    INSTANCE;

    private SimpleDateFormat iso8601Parser;

    private DateUtils() {
        // FIXME : use Java 8 API instead (with moments)
        iso8601Parser = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
        iso8601Parser.setTimeZone(TimeZone.getTimeZone("UTC"));
    }

    public Date parseIso8601(String date) throws ParseException {
        return iso8601Parser.parse(date);
    }

    public String formatIso8601(Date date) {
        return iso8601Parser.format(date);
    }

}

package com.github.aesteve.vertx.nubes.utils;

import java.text.ParseException;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.TimeZone;

import javax.xml.datatype.DatatypeConfigurationException;
import javax.xml.datatype.DatatypeFactory;
import javax.xml.datatype.XMLGregorianCalendar;

/**
 * Singleton pattern implementation using enums.
 *
 * See "Effective Java" by Joshua Bloch
 *
 * @author aesteve
 */
public enum DateUtils {

    INSTANCE;

    private DatatypeFactory factory;

    private DateUtils() {
        try {
            factory = DatatypeFactory.newInstance();
        } catch (DatatypeConfigurationException dtce) {
            throw new RuntimeException(dtce);
        }
    }

    public Date parseIso8601(String date) throws ParseException {
        XMLGregorianCalendar cal = factory.newXMLGregorianCalendar(date);
        return cal.toGregorianCalendar().getTime();
    }

    public String formatIso8601(Date date, TimeZone zone) {
        GregorianCalendar cal = new GregorianCalendar();
        cal.setTime(date);
        if (zone != null) {
            cal.setTimeZone(zone);
        }
        XMLGregorianCalendar calXml = factory.newXMLGregorianCalendar(cal);
        if (zone == null) {
            // display as UTC
            calXml = calXml.normalize();
        }
        return calXml.toXMLFormat();
    }

    public String formatIso8601(Date date) {
        return formatIso8601(date, null);
    }

}

Use XMLCalendar to handle iso 8601 dates


package edu.hm.hafner.analysis;

import java.util.Optional;
import java.util.regex.Pattern;
import java.util.stream.Stream;

import org.apache.commons.lang3.StringUtils;

import static edu.hm.hafner.analysis.PackageDetectors.*;

/**
 * Detects the namespace of a C# workspace file.
 *
 * @author Ullrich Hafner
 */
class CSharpNamespaceDetector extends AbstractPackageDetector {
    private static final Pattern NAMESPACE_PATTERN = Pattern.compile("^namespace .*$");

    CSharpNamespaceDetector() {
        this(new FileSystem());
    }

    CSharpNamespaceDetector(final FileSystem fileSystem) {
        super(fileSystem);
    }

    @Override
    public boolean accepts(final String fileName) {
        return fileName.endsWith(".cs");
    }

    @Override
    public String detectPackageName(final Stream<String> lines) {
        Optional<String> namespace = lines.filter(NAMESPACE_PATTERN.asPredicate()).findFirst();
        if (namespace.isPresent()) {
            String line = namespace.get();
            if (line.contains("{")) {
                return StringUtils.substringBetween(line, " ", "{").trim();
            }
            else {
                return StringUtils.substringAfter(line, " ").trim();
            }
        }
        return UNDEFINED_PACKAGE;
    }
}

package edu.hm.hafner.analysis;

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

import static edu.hm.hafner.analysis.PackageDetectors.*;

/**
 * Detects the namespace of a C# workspace file.
 *
 * @author Ullrich Hafner
 */
class CSharpNamespaceDetector extends AbstractPackageDetector {
    private static final Pattern NAMESPACE_PATTERN = Pattern.compile("^\\s*namespace\\s+([^{]*)\\s*\\{?\\s*$");

    CSharpNamespaceDetector() {
        this(new FileSystem());
    }

    CSharpNamespaceDetector(final FileSystem fileSystem) {
        super(fileSystem);
    }

    @Override
    public boolean accepts(final String fileName) {
        return fileName.endsWith(".cs");
    }

    @Override
    public String detectPackageName(final Stream<String> lines) {
        return lines.map(NAMESPACE_PATTERN::matcher)
                .filter(Matcher::matches)
                .findFirst()
                .map(matcher -> matcher.group(1))
                .orElse(UNDEFINED_PACKAGE).trim();
    }
}

Use regexp with matcher to identify a namespace.


package com.google.sps.servlets;

import com.google.sps.workspace.Workspace;
import com.google.sps.workspace.WorkspaceFactory;
import java.io.IOException;
import java.util.concurrent.ExecutionException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/workspace/downloadWorkspace")
public class DownloadWorkspace extends HttpServlet {
  WorkspaceFactory workspaceFactory;

  @Override
  public void init() throws ServletException {
    // TODO Auto-generated method stub
    super.init();
    workspaceFactory = WorkspaceFactory.getInstance();
  }

  @Override
  protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    Workspace w = workspaceFactory.fromWorkspaceID(req.getParameter("workspaceID"));

    resp.setContentType("application/x-gzip");

    try {
      w.getArchive().archive(resp.getOutputStream());
    } catch (InterruptedException | ExecutionException e) {
      resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    }
  }
}

package com.google.sps.servlets;

import com.google.appengine.api.blobstore.BlobKey;
import com.google.appengine.api.blobstore.BlobstoreService;
import com.google.appengine.api.blobstore.BlobstoreServiceFactory;
import com.google.sps.workspace.WorkspaceFactory;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/workspace/downloadWorkspace")
public class DownloadWorkspace extends HttpServlet {
  WorkspaceFactory workspaceFactory;

  @Override
  public void init() throws ServletException {
    // TODO Auto-generated method stub
    super.init();
    workspaceFactory = WorkspaceFactory.getInstance();
  }

  @Override
  protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    String downloadID = req.getParameter("downloadID");

    resp.setContentType("application/x-gzip");

    BlobstoreService blobstoreService = BlobstoreServiceFactory.getBlobstoreService();
    BlobKey blobKey =
        blobstoreService.createGsBlobKey(
            "/gs/fulfillment-deco-step-2020.appspot.com/" + downloadID);
    blobstoreService.serve(blobKey, resp);
  }
}

Update download servlet to pull from cloud storage.


package mil.nga.giat.mage.sdk.http.resource;

import android.content.Context;

import com.squareup.okhttp.ResponseBody;

import mil.nga.giat.mage.sdk.http.HttpClientManager;
import retrofit.Call;
import retrofit.Callback;
import retrofit.Retrofit;
import retrofit.http.GET;

/***
 * RESTful communication for the API
 *
 * @author newmanw
 */

public class ApiResource {

    public interface ApiService {

        @GET("/api")
        Call<ResponseBody> getApi();
    }

    private static final String LOG_NAME = ApiResource.class.getName();

    private Context context;

    public ApiResource(Context context) {
        this.context = context;
    }

    public void getApi(String url, Callback<ResponseBody> callback) {
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(url)
                .client(HttpClientManager.getInstance(context).httpClient())
                .build();

        ApiService service = retrofit.create(ApiService.class);
        service.getApi().enqueue(callback);
    }
}

package mil.nga.giat.mage.sdk.http.resource;

import android.content.Context;

import com.squareup.okhttp.ResponseBody;

import mil.nga.giat.mage.sdk.http.HttpClientManager;
import retrofit.Call;
import retrofit.Callback;
import retrofit.Retrofit;
import retrofit.http.GET;

/***
 * RESTful communication for the API
 *
 * @author newmanw
 */

public class ApiResource {

    public interface ApiService {

        @GET("/api")
        Call<ResponseBody> getApi();
    }

    private static final String LOG_NAME = ApiResource.class.getName();

    private Context context;

    public ApiResource(Context context) {
        this.context = context;
    }

    public void getApi(String url, Callback<ResponseBody> callback) {
        try {
            Retrofit retrofit = new Retrofit.Builder()
                    .baseUrl(url)
                    .client(HttpClientManager.getInstance(context).httpClient())
                    .build();

            ApiService service = retrofit.create(ApiService.class);
            service.getApi().enqueue(callback);
        } catch (IllegalArgumentException e) {
            callback.onFailure(e);
        }
    }
}

Fix crash on invalid URL

Fix crash on invalid URL


package info.u_team.u_team_test.potion;

import info.u_team.u_team_core.potion.UPotion;
import info.u_team.u_team_test.init.TestEffects;
import net.minecraft.potion.EffectInstance;

public class RadiationPotion extends UPotion {

	public RadiationPotion(String name, int duration, int amplifier) {
		super(name, "radiation", new EffectInstance(TestEffects.RADIATION, duration, amplifier));
	}
}

package info.u_team.u_team_test.potion;

import info.u_team.u_team_core.potion.UPotion;
import info.u_team.u_team_test.init.TestEffects;
import net.minecraft.potion.EffectInstance;

public class RadiationPotion extends UPotion {

	public RadiationPotion(String name, int duration, int amplifier) {
		super(name, "radiation", new EffectInstance(TestEffects.RADIATION.get(), duration, amplifier));
	}
}

Fix compile errors in potion

Fix compile errors in potion


package org.synyx.urlaubsverwaltung;

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

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

@DirtiesContext
public abstract class TestContainersBase {

    static final MariaDBContainer<?> mariaDB = new MariaDBContainer<>(NAME + ":10.5");

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

package org.synyx.urlaubsverwaltung;

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

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

public abstract class TestContainersBase {

    static final MariaDBContainer<?> mariaDB = new MariaDBContainer<>(NAME + ":10.5");

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

Remove dirties context of testcontainerbase


package de.itemis.mosig.ringbuffer;

public class CircularBuffer {

	private final int size;
	private int count = 0;

	public CircularBuffer(int size) {
		this.size = size;
	}

	public void add() {
		count++;
	}

	public int size() {
		return size;
	}

	public int count() {
		return count;
	}
}

package de.itemis.mosig.ringbuffer;

public class CircularBuffer {

	private final int size;
	private int count = 0;

	public CircularBuffer(int size) {
		this.size = size;
	}

	public void add(int element) {
		count++;
	}

	public int size() {
		return size;
	}

	public int count() {
		return count;
	}
}

Add operation now takes an argument.

GREEN: Add operation now takes an argument.


package in.twizmwaz.cardinal.module.modules.appliedRegion.type;

import in.twizmwaz.cardinal.module.modules.appliedRegion.AppliedRegion;
import in.twizmwaz.cardinal.module.modules.filter.FilterModule;
import in.twizmwaz.cardinal.module.modules.filter.FilterState;
import in.twizmwaz.cardinal.module.modules.regions.RegionModule;
import in.twizmwaz.cardinal.module.modules.regions.type.BlockRegion;
import org.bukkit.event.EventHandler;
import org.bukkit.event.player.PlayerMoveEvent;
import org.bukkit.util.Vector;

public class VelocityRegion extends AppliedRegion {

    public final Vector velocity;

    public VelocityRegion(RegionModule region, FilterModule filter, String message, Vector velocity) {
        super(region, filter, message);
        this.velocity = velocity;
    }

    @EventHandler
    public void onPlayerMove(PlayerMoveEvent event) {
        if (region.contains(new BlockRegion(null, event.getTo().toVector())) && filter.evaluate(event.getPlayer()).equals(FilterState.ALLOW)) {
            event.getPlayer().setVelocity(velocity);
        }
    }
}

package in.twizmwaz.cardinal.module.modules.appliedRegion.type;

import in.twizmwaz.cardinal.module.modules.appliedRegion.AppliedRegion;
import in.twizmwaz.cardinal.module.modules.filter.FilterModule;
import in.twizmwaz.cardinal.module.modules.filter.FilterState;
import in.twizmwaz.cardinal.module.modules.regions.RegionModule;
import in.twizmwaz.cardinal.module.modules.regions.type.BlockRegion;
import org.bukkit.event.EventHandler;
import org.bukkit.event.player.PlayerMoveEvent;
import org.bukkit.util.Vector;

public class VelocityRegion extends AppliedRegion {

    public final Vector velocity;

    public VelocityRegion(RegionModule region, FilterModule filter, String message, Vector velocity) {
        super(region, filter, message);
        this.velocity = velocity;
    }

    @EventHandler
    public void onPlayerMove(PlayerMoveEvent event) {
        if (filter == null) {
            if (region.contains(new BlockRegion(null, event.getTo().toVector())))
                event.getPlayer().setVelocity(velocity);
        } else if (region.contains(new BlockRegion(null, event.getTo().toVector())) && filter.evaluate(event.getPlayer()).equals(FilterState.ALLOW)) {
            event.getPlayer().setVelocity(velocity);
        }
    }
}

Fix an NPE with Velocity regions

Fix an NPE with Velocity regions


package org.inferred.freebuilder.processor.util.feature;

import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;

import javax.annotation.processing.ProcessingEnvironment;

/**
 * A set of {@link Feature} instances, determined dynamically by calling
 * {@link FeatureType#forEnvironment}.
 */
public class EnvironmentFeatureSet implements FeatureSet {

  private class FeatureFromEnvironmentLoader
      extends CacheLoader<FeatureType<?>, Feature<?>> {
    private final ProcessingEnvironment env;

    /**
featureType -> featureType.forEnvironment(env)
 */
    private FeatureFromEnvironmentLoader(ProcessingEnvironment env) {
      this.env = env;
    }

    @Override
    public Feature<?> load(FeatureType<?> featureType) {
      return featureType.forEnvironment(env, EnvironmentFeatureSet.this);
    }
  }

  private final LoadingCache<FeatureType<?>, Feature<?>> featuresByType;

  /** Constructs a feature set using the given processing environment. */
  public EnvironmentFeatureSet(ProcessingEnvironment env) {
    featuresByType = CacheBuilder.newBuilder()
        .concurrencyLevel(1)
        .build(new FeatureFromEnvironmentLoader(env));
  }

  @Override
  public <T extends Feature<T>> T get(FeatureType<T> featureType) {
    @SuppressWarnings("unchecked")
    T feature = (T) featuresByType.getUnchecked(featureType);
    return feature;
  }
}

package org.inferred.freebuilder.processor.util.feature;

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

import javax.annotation.processing.ProcessingEnvironment;

/**
 * A set of {@link Feature} instances, determined dynamically by calling
 * {@link FeatureType#forEnvironment}.
 */
public class EnvironmentFeatureSet implements FeatureSet {

  private final ProcessingEnvironment env;
  private final Map<FeatureType<?>, Feature<?>> featuresByType = new HashMap<>();

  /** Constructs a feature set using the given processing environment. */
  public EnvironmentFeatureSet(ProcessingEnvironment env) {
    this.env = env;
  }

  @Override
  public <T extends Feature<T>> T get(FeatureType<T> featureType) {
    @SuppressWarnings("unchecked")
    T feature = (T) featuresByType.computeIfAbsent(featureType, $ -> $.forEnvironment(env, this));
    return feature;
  }
}

Use Map.computeIfAbsent rather than a LoadingCache


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

package com.horcrux.svg;

import android.graphics.Canvas;
import android.graphics.Paint;

/**
 * Shadow node for virtual RNSVGPath view
 */
public class RNSVGDefsShadowNode extends RNSVGDefinitionShadowNode {

    @Override
    public void draw(Canvas canvas, Paint paint, float opacity) {
        traverseChildren(new NodeRunnable() {
            public boolean run(RNSVGVirtualNode node) {
                node.saveDefinition();
                return true;
            }
        });
    }
}

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

package com.horcrux.svg;

import android.graphics.Canvas;
import android.graphics.Paint;

/**
 * Shadow node for virtual RNSVGPath view
 */
public class RNSVGDefsShadowNode extends RNSVGDefinitionShadowNode {

    @Override
    public void draw(Canvas canvas, Paint paint, float opacity) {
        traverseChildren(new NodeRunnable() {
            public boolean run(RNSVGVirtualNode node) {
                node.saveDefinition();
                return true;
            }
        });
        traverseChildren(new NodeRunnable() {
            public boolean run(RNSVGVirtualNode node) {
                node.markUpdateSeen();
                node.traverseChildren(this);
                return true;
            }
        });
    }
}

Mark all descendants of Defs as seen after a draw

When adding clipping paths in a def and changing properties of that clipping path (or its descendants), redraw is triggered only once as updates are never marked as seen.
This change makes sure to call `markUpdateSeen` on all descendants of the Defs node on a `draw`.


package jp.gecko655.fujimiya.bot;

import org.quartz.*;
import org.quartz.impl.StdSchedulerFactory;

import static org.quartz.JobBuilder.newJob;
import static org.quartz.SimpleScheduleBuilder.repeatSecondlyForever;
import static org.quartz.TriggerBuilder.newTrigger;

public class SchedulerMain {
    private static Scheduler scheduler;
    public static void main(String[] args) throws SchedulerException {
        System.out.println("Scheduler Started!!!");
        scheduler = StdSchedulerFactory.getDefaultScheduler();

        scheduler.start();
        setSchedule(FujimiyaReply.class, 60*5);
        //setSchedule(FujimiyaRemove.class, 60*5);

    }
    private static void setSchedule(Class<? extends Job> classForExecute, int intervalSeconds) throws SchedulerException {
        JobDetail jobDetail = newJob(classForExecute).build();

        Trigger trigger = newTrigger()
                .startNow()
                .withSchedule(repeatSecondlyForever(intervalSeconds))
                .build();

        scheduler.scheduleJob(jobDetail, trigger);
        System.out.println(classForExecute.getName()+" has been scheduled in interval: "+intervalSeconds+" [s]");

    }

}

package jp.gecko655.fujimiya.bot;

import java.time.ZoneId;
import java.util.TimeZone;

import org.quartz.*;
import org.quartz.impl.StdSchedulerFactory;

import static org.quartz.JobBuilder.newJob;
import static org.quartz.SimpleScheduleBuilder.repeatSecondlyForever;
import static org.quartz.TriggerBuilder.newTrigger;

public class SchedulerMain {
    private static Scheduler scheduler;
    public static void main(String[] args) throws SchedulerException {
        System.out.println("Scheduler Started!!!");
        scheduler = StdSchedulerFactory.getDefaultScheduler();

        scheduler.start();
        setSchedule(FujimiyaReply.class, repeatSecondlyForever(60*5));
        setSchedule(FujimiyaBot.class, repeatSecondlyForever(60*60*4));
        setSchedule(
                FujimiyaLunch.class,
                CronScheduleBuilder
                    .dailyAtHourAndMinute(12, 25)
                    .inTimeZone(TimeZone.getTimeZone("JST")));
        setSchedule(
                FujimiyaRemove.class,
                CronScheduleBuilder
                    .atHourAndMinuteOnGivenDaysOfWeek(9, 0, DateBuilder.MONDAY)
                    .inTimeZone(TimeZone.getTimeZone("JST")));

    }
    private static void setSchedule(Class<? extends Job> classForExecute, ScheduleBuilder<? extends Trigger> schedule) throws SchedulerException {
        JobDetail jobDetail = newJob(classForExecute).build();

        Trigger trigger = newTrigger()
                .startNow()
                .withSchedule(schedule)
                .build();

        scheduler.scheduleJob(jobDetail, trigger);
        System.out.println(classForExecute.getName()+" has been scheduled");

    }

}

Set schedule for 4 crons.

Set schedule for 4 crons.


package uk.ac.ebi.atlas.species;

import org.apache.commons.lang.StringUtils;

import javax.inject.Inject;
import javax.inject.Named;

@Named
public class SpeciesFactory {

    private final SpeciesPropertiesTrader speciesPropertiesTrader;

    @Inject
    public SpeciesFactory(SpeciesPropertiesTrader speciesPropertiesTrader) {
        this.speciesPropertiesTrader = speciesPropertiesTrader;
    }

    public Species create(String name) {
        return StringUtils.isNotEmpty(name) ? new Species(name, speciesPropertiesTrader.get(name)) : new Species("", SpeciesProperties.UNKNOWN);
    }
}

package uk.ac.ebi.atlas.species;

import javax.inject.Inject;
import javax.inject.Named;

@Named
public class SpeciesFactory {

    private final SpeciesPropertiesTrader speciesPropertiesTrader;

    @Inject
    public SpeciesFactory(SpeciesPropertiesTrader speciesPropertiesTrader) {
        this.speciesPropertiesTrader = speciesPropertiesTrader;
    }

    public Species create(String name) {
        return new Species(name, speciesPropertiesTrader.get(name));
    }

    public Species createUnknownSpecies() {
        return new Species("", SpeciesProperties.UNKNOWN);
    }
}

Add explicit method to create an unknown species to express a clearer intent (sometimes a species will be unknown if we can’t map it to a reference species, sometimes we actually want an unknown species, no matter what it is)


/*
 * Mutability Detector
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 *
 * Further licensing information for this project can be found in
 * 		license/LICENSE.txt
 */

package org.mutabilitydetector.locations;

public interface CodeLocation<T extends CodeLocation<T>> extends Comparable<T> {

    String typeName();

    public abstract String prettyPrint();

}

/*
 * Mutability Detector
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 *
 * Further licensing information for this project can be found in
 * 		license/LICENSE.txt
 */

package org.mutabilitydetector.locations;

public interface CodeLocation<T extends CodeLocation<T>> extends Comparable<T> {

    String typeName();

    public abstract String prettyPrint();

    public static class UnknownCodeLocation implements CodeLocation<UnknownCodeLocation> {

        public static final UnknownCodeLocation UNKNOWN = new UnknownCodeLocation();

        private UnknownCodeLocation() { }

        @Override
        public int compareTo(UnknownCodeLocation o) {
            return 0; // There can be only one.
        }

        @Override
        public String typeName() {
            return "unknown code location";
        }

        @Override
        public String prettyPrint() {
            return "[Unknown code location]";
        }

    }

}

Add an unknown code location to be used when there's unhandled errors.

git-svn-id: ed609ce04ec9e3c0bc25e071e87814dd6d976548@418 c7a0535c-eda6-11de-83d8-6d5adf01d787


package org.certificatetransparency.ctlog.comm;

import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;

import java.io.IOException;

/**
 * Simple delegator to HttpClient, so it can be mocked
 */
public class HttpPostInvoker {
  /**
   * Make an HTTP POST method call to the given URL with the provided JSON payload.
   * @param url URL for POST method
   * @param jsonPayload Serialized JSON payload.
   * @return Server's response body.
   */
  public String makePostRequest(String url, String jsonPayload) {
    HttpClient httpClient = new DefaultHttpClient();
    try {
      HttpPost post = new HttpPost(url);
      post.setEntity(new StringEntity(jsonPayload, "utf-8"));
      post.addHeader("Content-Type", "application/json; charset=utf-8");

      return httpClient.execute(post, new BasicResponseHandler());
    } catch (IOException e) {
      throw new LogCommunicationException("Error making POST request to " + url, e);
    } finally {
      httpClient.getConnectionManager().shutdown();
    }
  }
}

package org.certificatetransparency.ctlog.comm;

import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;

import java.io.IOException;

/**
 * Simple delegator to HttpClient, so it can be mocked
 */
public class HttpPostInvoker {
  /**
   * Make an HTTP POST method call to the given URL with the provided JSON payload.
   * @param url URL for POST method
   * @param jsonPayload Serialized JSON payload.
   * @return Server's response body.
   */
  public String makePostRequest(String url, String jsonPayload) {
    try (CloseableHttpClient httpClient = HttpClientBuilder.create().build()) {
      HttpPost post = new HttpPost(url);
      post.setEntity(new StringEntity(jsonPayload, "utf-8"));
      post.addHeader("Content-Type", "application/json; charset=utf-8");

      return httpClient.execute(post, new BasicResponseHandler());
    } catch (IOException e) {
      throw new LogCommunicationException("Error making POST request to " + url, e);
    }
  }
}

Java: Move away from deprecated HTTP client API after libraries update.


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

Actually its not nullable, but since we don't set one on creation, Hibernate trips on double.
Therefore we use Double again.


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.

git-svn-id: e7d6bde23f017c9ff4efd468d79d66def666766b@4044 eae3c2d3-9b19-0410-a86e-396b6ccb6ab3


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

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

Remove CSRF disabling in sample code

Don't want to encourage bad practices after all.


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

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

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

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.

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

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

Former-commit-id: 4dacd2ba9162d107c6e1f61334855174b2cb44c7


/**
 * 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;
    }
}

[api] 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

Add integration tests for data