package invtweaks.api.container;

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

/**
 * A marker for containers that have a chest-like persistent storage component. Enables the Inventory Tweaks sorting
 * buttons for this container.
 */
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface ChestContainer {
    // Set to true if the Inventory Tweaks sorting buttons should be shown for this container.
    boolean showButtons() default true;

    // Size of a chest row
    int rowSize() default 9;

    // Uses 'large chest' mode for sorting buttons
    // (Renders buttons vertically down the right side of the GUI)
    boolean isLargeChest() default false;

    // Annotation for method to get size of a chest row if it is not a fixed size for this container class
    // Signature int func()
    @Retention(RetentionPolicy.RUNTIME)
    @Target(ElementType.METHOD)
    @interface RowSizeCallback {
    }

    // Annotation for method to get size of a chest row if it is not a fixed size for this container class
    // Signature int func()
    @Retention(RetentionPolicy.RUNTIME)
    @Target(ElementType.METHOD)
    @interface IsLargeCallback {
    }
}

package invtweaks.api.container;

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

/**
 * A marker for containers that have a chest-like persistent storage component. Enables the Inventory Tweaks sorting
 * buttons for this container.
 */
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface ChestContainer {
    // Set to true if the Inventory Tweaks sorting buttons should be shown for this container.
    boolean showButtons() default true;

    // Size of a chest row
    int rowSize() default 9;

    // Uses 'large chest' mode for sorting buttons
    // (Renders buttons vertically down the right side of the GUI)
    boolean isLargeChest() default false;

    // Annotation for method to get size of a chest row if it is not a fixed size for this container class
    // Signature int func()
    @Retention(RetentionPolicy.RUNTIME)
    @Target(ElementType.METHOD)
    @interface RowSizeCallback {
    }

    // Annotation for method to get size of a chest row if it is not a fixed size for this container class
    // Signature boolean func()
    @Retention(RetentionPolicy.RUNTIME)
    @Target(ElementType.METHOD)
    @interface IsLargeCallback {
    }
}

Fix API documentation for IsLargeCallback.

Fixes #497.


package io.reon.auth;

import java.util.HashMap;

import io.reon.util.Hex;

public abstract class AbstractAuth implements HttpAuth {
	public static final String REALM = "realm";
	public static final String RESPONSE = "response";
	public static final String NONCE = "nonce";
	public static final String PK = "pk";
	public static final String EQ = "=\"";
	public static final String EOS = "\", ";
	public static final String EOT = "\"";

	public static HashMap<String, String> parse(String text) {
		String[] fields = text.substring(text.indexOf(' ')+1).split(",");
		HashMap<String, String> attrs = new HashMap<>();
		for(String field: fields) {
			String[] kv = field.split("=");
			attrs.put(kv[0].trim(), kv[1].replace('"',' ').trim());
		}
		return attrs;
	}

	public static byte[] fromHex(String value) {
		return Hex.decodeHex(value);
	}

	public static String toHex(byte[] value) {
		return Hex.encodeHex(value, false);
	}
}

package io.reon.auth;

import java.util.HashMap;

import io.reon.util.Hex;

public abstract class AbstractAuth implements HttpAuth {
	public static final String REALM = "realm";
	public static final String RESPONSE = "response";
	public static final String NONCE = "nonce";
	public static final String PK = "pk";
	public static final String EQ = "=\"";
	public static final String EOS = "\", ";
	public static final String EOT = "\"";

	public static HashMap<String, String> parse(String text) {
		HashMap<String, String> attrs = new HashMap<>();
		try {
			String[] fields = text.substring(text.indexOf(' ') + 1).split(",");
			for (String field : fields) {
				String[] kv = field.split("=");
				attrs.put(kv[0].trim(), kv[1].replace('"', ' ').trim());
			}
		} catch (RuntimeException ex) {
			// ignore
		}
		return attrs;
	}

	public static byte[] fromHex(String value) {
		return Hex.decodeHex(value);
	}

	public static String toHex(byte[] value) {
		return Hex.encodeHex(value, false);
	}
}

Fix for crash over badly formatted auth requests


package org.innovateuk.ifs.project.internal;

public enum ProjectSetupStage {
    PROJECT_DETAILS("Project details", 1),
    PROJECT_TEAM("Project team", 2),
    DOCUMENTS("Documents", 3),
    MONITORING_OFFICER("MO", 4),
    BANK_DETAILS("Bank details", 5),
    FINANCE_CHECKS("Finance checks", 6),
    SPEND_PROFILE("Spend profile", 7), //Some competitions don't have this stage. They automatically approve the spend profile.
    GRANT_OFFER_LETTER("GOL", 8),
    PROJECT_SETUP_COMPLETE("Project setup complete", 9);

    private int priority;
    private String shortName;

    ProjectSetupStage(String shortName, int priority) {
        this.shortName = shortName;
        this.priority = priority;
    }

    public int getPriority() {
        return priority;
    }

    public String getShortName() {
        return shortName;
    }
}

package org.innovateuk.ifs.project.internal;

public enum ProjectSetupStage {
    PROJECT_DETAILS("Project details", 1),
    PROJECT_TEAM("Project team", 2),
    DOCUMENTS("Documents", 3),
    MONITORING_OFFICER("MO", 4),
    BANK_DETAILS("Bank details", 5),
    FINANCE_CHECKS("Finance checks", 6),
    SPEND_PROFILE("Spend profile", 7), //Some competitions don't have this stage. They automatically approve the spend profile.
    GRANT_OFFER_LETTER("GOL", 8),
    PROJECT_SETUP_COMPLETE("Complete project setup", 9);

    private int priority;
    private String shortName;

    ProjectSetupStage(String shortName, int priority) {
        this.shortName = shortName;
        this.priority = priority;
    }

    public int getPriority() {
        return priority;
    }

    public String getShortName() {
        return shortName;
    }
}

Complete project setup header updated

IFS-9490: Complete project setup header updated


package maze;

import java.util.LinkedList;
import java.util.List;

/**
 * @author Nick Hirakawa
 */
public class Cell {

    private int x;
    private int y;
    private boolean visited;
    private List<Cell> neighbors;

    public Cell(int x, int y){
        this.x = x;
        this.y = y;
        this.setVisited(false);
        this.neighbors = new LinkedList<Cell>();
    }

    public int getX() {
        return x;
    }

    public int getY() {
        return y;
    }

    public void addNeighbor(Cell cell){
        if(!this.neighbors.contains(cell)){
            this.neighbors.add(cell);
        }
    }

    public List<Cell> getNeighbors(){
        return this.neighbors;
    }

    public boolean isVisited() {
        return visited;
    }

    public void setVisited(boolean visited) {
        this.visited = visited;
    }

    @Override
    public int hashCode(){
        int result = 17;
        result = 37 * result + this.x;
        result = 37 * result + this.y;
        return result;
    }

    @Override
    public boolean equals(Object other){
        Cell cell = (Cell)other;
        return cell.x == this.x && cell.y == this.y;
    }

    @Override
    public String toString(){
        return "(" + x + "," + y + ")";
    }
}

package maze;

import java.util.LinkedList;
import java.util.List;
import java.util.Random;

/**
 * @author Nick Hirakawa
 */
public class Cell {

    private int x;
    private int y;
    private boolean visited;
    private List<Cell> neighbors;
    private Random random;

    public Cell(int x, int y){
        this.x = x;
        this.y = y;
        this.setVisited(false);
        this.neighbors = new LinkedList<Cell>();
        random = new Random();
    }

    public int getX() {
        return x;
    }

    public int getY() {
        return y;
    }

    public void addNeighbor(Cell cell){
        if(!this.neighbors.contains(cell)){
            this.neighbors.add(cell);
        }
    }

    public List<Cell> getNeighbors(){
        return this.neighbors;
    }

    public Cell getRandomNeighbor(){
        return this.neighbors.get(random.nextInt(neighbors.size()));
    }

    public boolean isVisited() {
        return visited;
    }

    public void setVisited(boolean visited) {
        this.visited = visited;
    }

    @Override
    public int hashCode(){
        int result = 17;
        result = 37 * result + this.x;
        result = 37 * result + this.y;
        return result;
    }

    @Override
    public boolean equals(Object other){
        Cell cell = (Cell)other;
        return cell.x == this.x && cell.y == this.y;
    }

    @Override
    public String toString(){
        return "(" + x + "," + y + ")";
    }
}

Add method for getting random neighbor

Add method for getting random neighbor


package hudson.plugins.git.extensions.impl;

import nl.jqno.equalsverifier.EqualsVerifier;
import nl.jqno.equalsverifier.Warning;
import org.junit.Test;

public class CloneOptionTest {

    @Test
    public void equalsContract() {
        EqualsVerifier.forClass(CloneOption.class)
                .usingGetClass()
                .suppress(Warning.NONFINAL_FIELDS)
                .verify();
    }
}

package hudson.plugins.git.extensions.impl;

import hudson.plugins.git.extensions.GitClientType;
import nl.jqno.equalsverifier.EqualsVerifier;
import nl.jqno.equalsverifier.Warning;
import static org.hamcrest.MatcherAssert.*;
import static org.hamcrest.Matchers.*;
import org.junit.Test;

public class CloneOptionTest {

    @Test
    public void getRequiredClient() {
        CloneOption cloneOption = new CloneOption(false, "", 1);
        assertThat(cloneOption.getRequiredClient(), is(GitClientType.GITCLI));
    }

    @Test
    public void equalsContract() {
        EqualsVerifier.forClass(CloneOption.class)
                .usingGetClass()
                .suppress(Warning.NONFINAL_FIELDS)
                .verify();
    }
}

Add a test for CloneOption.getRequiredClient

Cheap and harmless to test


package org.deeplearning4j.nn.conf.layers;

import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;
import lombok.ToString;

import org.nd4j.linalg.lossfunctions.LossFunctions.LossFunction;

@Data @NoArgsConstructor
@ToString(callSuper = true)
@EqualsAndHashCode(callSuper = true)
public class RnnOutputLayer extends BaseOutputLayer {

	private RnnOutputLayer(Builder builder){
		super(builder);
	}

	@NoArgsConstructor
    public static class Builder extends BaseOutputLayer.Builder<Builder> {

    	public Builder(LossFunction lossFunction) {
            this.lossFunction = lossFunction;
        }

        @Override
        @SuppressWarnings("unchecked")
        public RnnOutputLayer build() {
            return new RnnOutputLayer(this);
        }
    }
}

package org.deeplearning4j.nn.conf.layers;

import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;
import lombok.ToString;

import org.nd4j.linalg.lossfunctions.LossFunctions.LossFunction;

@Data @NoArgsConstructor
@ToString(callSuper = true)
@EqualsAndHashCode(callSuper = true)
public class RnnOutputLayer extends BaseOutputLayer {

	private RnnOutputLayer(Builder builder){
		super(builder);
	}

	@NoArgsConstructor
    public static class Builder extends BaseOutputLayer.Builder<Builder> {
        protected LossFunction lossFunction = LossFunction.MCXENT;

    	public Builder(LossFunction lossFunction) {
            this.lossFunction = lossFunction;
        }

        @Override
        @SuppressWarnings("unchecked")
        public RnnOutputLayer build() {
            return new RnnOutputLayer(this);
        }
    }
}

Add default loss for RNNOutput

Add default loss for RNNOutput

Former-commit-id: bb723e819949ca911702dff1bcae3f1507df92d5


package me.shoutto.sdk.internal.http;

import me.shoutto.sdk.StmBaseEntity;

/**
 * Implementation of URL provider for Shout to Me API service endpoints
 */

public class DefaultUrlProvider implements StmUrlProvider {

    private String baseApiUrl;

    public DefaultUrlProvider(String baseApiUrl) {
        this.baseApiUrl = baseApiUrl;
    }

    @Override
    public String getUrl(StmBaseEntity entity, HttpMethod httpMethod) {
        String url = String.format("%s%s", baseApiUrl, entity.getBaseEndpoint());
        if (httpMethod.equals(HttpMethod.DELETE) || httpMethod.equals(HttpMethod.PUT)
                || httpMethod.equals(HttpMethod.GET)) {
            url = url.concat(String.format("/%s", entity.getId()));
        }
        return url;
    }
}

package me.shoutto.sdk.internal.http;

import me.shoutto.sdk.StmBaseEntity;

/**
 * Implementation of URL provider for Shout to Me API service endpoints
 */

public class DefaultUrlProvider implements StmUrlProvider {

    private String baseApiUrl;

    public DefaultUrlProvider(String baseApiUrl) {
        this.baseApiUrl = baseApiUrl;
    }

    @Override
    public String getUrl(StmBaseEntity entity, HttpMethod httpMethod) {
        String url = String.format("%s%s", baseApiUrl, entity.getBaseEndpoint());
        if (httpMethod.equals(HttpMethod.DELETE) || httpMethod.equals(HttpMethod.PUT)
                || httpMethod.equals(HttpMethod.GET)) {
            if (entity.getId() != null) {
                url = url.concat(String.format("/%s", entity.getId()));
            }
        }
        return url;
    }
}

Add some protection to default url provider


package jpower.core.test;

import org.junit.runner.RunWith;
import org.junit.runners.Suite;

@RunWith(Suite.class)
@Suite.SuiteClasses(
        {AlphabetTest.class, ConditionTest.class, ConfigurationTest.class, FactoryTest.class, InternalTest.class,
                IOUtilsTest.class, LoadTest.class, MultiMapTest.class, PowerLoaderTest.class, RandomTest.class,
                ThreadUtilsTest.class, ByteUtilsTest.class, WorkerTest.class, GenericSnifferTest.class, OperatingSystemTest.class, CallUtilsTest.class})
public class CoreTestSuite
{
}

package jpower.core.test;

import org.junit.runner.RunWith;
import org.junit.runners.Suite;

@RunWith(Suite.class)
@Suite.SuiteClasses({
        AlphabetTest.class,
        ConditionTest.class,
        ConfigurationTest.class,
        FactoryTest.class,
        InternalTest.class,
        IOUtilsTest.class,
        LoadTest.class,
        MultiMapTest.class,
        PowerLoaderTest.class,
        RandomTest.class,
        ThreadUtilsTest.class,
        ByteUtilsTest.class,
        WorkerTest.class,
        GenericSnifferTest.class,
        OperatingSystemTest.class,
        CallUtilsTest.class,
        ServiceTest.class
})
public class CoreTestSuite
{
}

Add ServiceTest to the Core Test Suite.

Add ServiceTest to the Core Test Suite.


/*******************************************************************************
 * Copyright (c) 2014 Codenvy, S.A.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *   Codenvy, S.A. - initial API and implementation
 *******************************************************************************/
package com.codenvy.ide.editor.codemirror.client;

import javax.inject.Inject;

import com.codenvy.ide.jseditor.client.filetype.FileTypeIdentifier;
import com.codenvy.ide.jseditor.client.texteditor.EditorWidgetFactory;
import com.codenvy.ide.jseditor.client.texteditor.EmbeddedTextEditorPartView;
import com.codenvy.ide.jseditor.client.texteditor.EmbeddedTextEditorPartViewImpl;
import com.codenvy.ide.jseditor.client.texteditor.EmbeddedTextEditorViewFactory;

public class CodeMirrorTextEditorViewFactory implements EmbeddedTextEditorViewFactory {

    @Inject
    private EditorWidgetFactory<CodeMirrorEditorWidget> widgetFactory;
    @Inject
    private FileTypeIdentifier                          fileTypeIdentifier;

    @Override
    public EmbeddedTextEditorPartView createTextEditorPartView() {
        return new EmbeddedTextEditorPartViewImpl<CodeMirrorEditorWidget>(this.widgetFactory, this.fileTypeIdentifier);
    }
}

/*******************************************************************************
 * Copyright (c) 2014 Codenvy, S.A.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *   Codenvy, S.A. - initial API and implementation
 *******************************************************************************/
package com.codenvy.ide.editor.codemirror.client;

import javax.inject.Inject;

import com.codenvy.ide.jseditor.client.JsEditorConstants;
import com.codenvy.ide.jseditor.client.filetype.FileTypeIdentifier;
import com.codenvy.ide.jseditor.client.texteditor.EditorWidgetFactory;
import com.codenvy.ide.jseditor.client.texteditor.EmbeddedTextEditorPartView;
import com.codenvy.ide.jseditor.client.texteditor.EmbeddedTextEditorPartViewImpl;
import com.codenvy.ide.jseditor.client.texteditor.EmbeddedTextEditorViewFactory;

public class CodeMirrorTextEditorViewFactory implements EmbeddedTextEditorViewFactory {

    @Inject
    private EditorWidgetFactory<CodeMirrorEditorWidget> widgetFactory;
    @Inject
    private FileTypeIdentifier                          fileTypeIdentifier;
    @Inject
    private JsEditorConstants                           constants;

    @Override
    public EmbeddedTextEditorPartView createTextEditorPartView() {
        return new EmbeddedTextEditorPartViewImpl<CodeMirrorEditorWidget>(this.widgetFactory, this.fileTypeIdentifier, constants);
    }
}

Add a constants parameter to the view factory


package forager.server;

import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;

public class ListManager {

    private FileOutputStream taskListOut;
    private PrintWriter taskListWriter;

    public ListManager() throws IOException {
        String taskList = "tasklist";
        taskListOut = new FileOutputStream(taskList, true);
        taskListWriter = new PrintWriter(new BufferedOutputStream(taskListOut));
    }

    public void addTask(String command) {
        taskListWriter.println(command);
    }

    public void sync() throws IOException {
        taskListWriter.flush();
        taskListOut.getFD().sync();
    }
}

package forager.server;

import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;

public class ListManager {

    public static final String DEFAULT_LIST_NAME = "tasklist";

    private FileOutputStream taskListOut;
    private PrintWriter taskListWriter;

    private FileOutputStream completedListOut;
    private PrintWriter completedListWriter;

    public ListManager() throws IOException {
        this(DEFAULT_LIST_NAME);
    }

    public ListManager(String taskListName) throws IOException {
        taskListOut = new FileOutputStream(taskListName, true);
        taskListWriter = new PrintWriter(
                new BufferedOutputStream(taskListOut));

        String completedName = taskListName + ".done";
        completedListOut = new FileOutputStream(completedName, true);
        completedListWriter = new PrintWriter(
                new BufferedOutputStream(completedListOut));
    }

    public void addTask(String command) {
        taskListWriter.println(command);
    }

    public void addCompletedTask(String command) {
        completedListWriter.println(command);
    }

    public void sync() throws IOException {
        taskListWriter.flush();
        taskListOut.getFD().sync();
    }
}

Add completed task file implementation

Add completed task file implementation


package org.ihtsdo.buildgeneration;

import org.ihtsdo.buildcloud.entity.Package;
import org.ihtsdo.buildcloud.entity.helper.TestEntityFactory;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.springframework.util.StreamUtils;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.nio.charset.Charset;

public class BuildGeneratorTest {

	private BuildGenerator buildGenerator;
	private String expectedPom;
	private Package releasePackage;

	@Before
	public void setup() throws IOException {
		buildGenerator = new BuildGenerator();
		expectedPom = StreamUtils.copyToString(this.getClass().getResourceAsStream("expected-generated-pom.txt"), Charset.defaultCharset());
		releasePackage = new TestEntityFactory().createPackage("International", "International", "Spanish Edition", "Biannual", "RF2");
	}

	@Test
	public void test() throws IOException {
		ByteArrayOutputStream out = new ByteArrayOutputStream();
		buildGenerator.generate(new OutputStreamWriter(out), releasePackage.getBuild());
		String actualPom = out.toString();

		Assert.assertEquals(expectedPom, actualPom);
	}

}

package org.ihtsdo.buildgeneration;

import org.ihtsdo.buildcloud.entity.Package;
import org.ihtsdo.buildcloud.entity.helper.TestEntityFactory;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.springframework.util.StreamUtils;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.nio.charset.Charset;

public class BuildGeneratorTest {

	private BuildGenerator buildGenerator;
	private String expectedPom;
	private Package releasePackage;

	@Before
	public void setup() throws IOException {
		buildGenerator = new BuildGenerator();
		expectedPom = StreamUtils.copyToString(this.getClass().getResourceAsStream("expected-generated-pom.txt"), Charset.defaultCharset()).replace("\r", "");
		releasePackage = new TestEntityFactory().createPackage("International", "International", "Spanish Edition", "Biannual", "RF2");
	}

	@Test
	public void test() throws IOException {
		ByteArrayOutputStream out = new ByteArrayOutputStream();
		buildGenerator.generate(new OutputStreamWriter(out), releasePackage.getBuild());
		String actualPom = out.toString();

		Assert.assertEquals(expectedPom, actualPom);
	}

}

Fix issue with PC WhiteSpace (/r/n) causing test failure.


/*
# Licensed Materials - Property of IBM
# Copyright IBM Corp. 2018
 */

package com.ibm.streamsx.rest.test;

import java.io.IOException;

import com.ibm.streamsx.rest.Instance;

/**
 * Test use of ApplicationBundle including Job submission
 * to a service.
 *
 */
public class AppBundleSasTest extends AppBundleTest {

	@Override
	protected Instance getInstance() throws IOException {
		return StreamingAnalyticsConnectionTest.getTestService().getInstance();
	}
}

/*
# Licensed Materials - Property of IBM
# Copyright IBM Corp. 2018
 */

package com.ibm.streamsx.rest.test;

import static org.junit.Assume.assumeNotNull;

import java.io.IOException;

import org.junit.Before;

import com.ibm.streamsx.rest.Instance;

/**
 * Test use of ApplicationBundle including Job submission
 * to a service.
 *
 */
public class AppBundleSasTest extends AppBundleTest {

    @Before
    public void checkForService() {
        // if we don't have serviceName or vcapServices, skip the test
        assumeNotNull(System.getenv("STREAMING_ANALYTICS_SERVICE_NAME"), System.getenv("VCAP_SERVICES"));
    }

	@Override
	protected Instance getInstance() throws IOException {
		return StreamingAnalyticsConnectionTest.getTestService().getInstance();
	}
}

Check for Sas setup before compiling

Check for Sas setup before compiling


/**
 *
 */
package org.openforis.collect.model.proxy;

import org.granite.messaging.amf.io.util.externalizer.annotation.ExternalizedProperty;
import org.openforis.collect.Proxy;
import org.openforis.idm.model.state.NodeState;

/**
 * @author M. Togna
 *
 */
public class NodeStateProxy implements Proxy {

	private transient NodeState nodeState;

	public NodeStateProxy(NodeState nodeState) {
		this.nodeState = nodeState;
	}

	@ExternalizedProperty
	public int getNodeId() {
		return nodeState.getNode().getId();
	}

	@ExternalizedProperty
	public boolean isRelevant() {
		return nodeState.isRelevant();
	}

	@ExternalizedProperty
	public boolean isRequired() {
		return nodeState.isRequired();
	}

	@ExternalizedProperty
	public ValidationResultsProxy getValidationResults() {
		return new ValidationResultsProxy(nodeState.getValidationResults());
	}

}

/**
 *
 */
package org.openforis.collect.model.proxy;

import org.granite.messaging.amf.io.util.externalizer.annotation.ExternalizedProperty;
import org.openforis.collect.Proxy;
import org.openforis.idm.model.state.NodeState;

/**
 * @author M. Togna
 *
 */
public class NodeStateProxy implements Proxy {

	private transient NodeState nodeState;

	public NodeStateProxy(NodeState nodeState) {
		this.nodeState = nodeState;
	}

	@ExternalizedProperty
	public Integer getNodeId() {
		return nodeState.getNode().getId();
	}

	@ExternalizedProperty
	public boolean isRelevant() {
		return nodeState.isRelevant();
	}

	@ExternalizedProperty
	public boolean isRequired() {
		return nodeState.isRequired();
	}

	@ExternalizedProperty
	public ValidationResultsProxy getValidationResults() {
		return new ValidationResultsProxy(nodeState.getValidationResults());
	}

}

Return Integer instead of primitive int (why there is null in node id?!)


package net.mostlyoriginal.api.component.graphics;

import com.artemis.Component;

/**
 * Color for animations, labels.
 *
 * Optional, convention is to assume white if not set.
 *
 * @author Daan van Yperen
 */
public class Color extends Component {

    public float r;
    public float g;
    public float b;
    public float a;

    public Color() {
    }

    public Color(Color color) {
        this.r = color.r;
        this.g = color.g;
        this.b = color.b;
        this.a = color.a;
    }

    public Color(float r, float g, float b, float a) {
        this.r = r;
        this.g = g;
        this.b = b;
        this.a = a;
    }

    public void set(float r, float g, float b, float a) {
        this.r = r;
        this.g = g;
        this.b = b;
        this.a = a;
    }

    public void set(Color color)
    {
        this.r = color.r;
        this.g = color.g;
        this.b = color.b;
        this.a = color.a;
    }
}

package net.mostlyoriginal.api.component.graphics;

import com.artemis.Component;

/**
 * Color for animations, labels.
 *
 * Optional, convention is to assume white if not set.
 *
 * @author Daan van Yperen
 */
public class Color extends Component {

    public float r;
    public float g;
    public float b;
    public float a;

    public Color() {
    }

    public Color(Color color) {
        this.r = color.r;
        this.g = color.g;
        this.b = color.b;
        this.a = color.a;
    }

	/** Color component by hex, RRGGBBAA. */
	public Color(String hex) {
		this((float)Integer.valueOf(hex.substring(0, 2), 16) / 255.0F,
			 (float)Integer.valueOf(hex.substring(2, 4), 16) / 255.0F,
			 (float)Integer.valueOf(hex.substring(4, 6), 16) / 255.0F,
			 (float)(hex.length() != 8 ? 255 : Integer.valueOf(hex.substring(6, 8), 16)) / 255.0F);
	}

    public Color(float r, float g, float b, float a) {
        this.r = r;
        this.g = g;
        this.b = b;
        this.a = a;
    }

    public void set(float r, float g, float b, float a) {
        this.r = r;
        this.g = g;
        this.b = b;
        this.a = a;
    }

    public void set(Color color)
    {
        this.r = color.r;
        this.g = color.g;
        this.b = color.b;
        this.a = color.a;
    }
}

Add hex constructor to color.

Add hex constructor to color.


package info.agrueneberg.fhir.configurations;

import info.agrueneberg.fhir.services.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private UserService userService;

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userService).passwordEncoder(new BCryptPasswordEncoder());
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .authorizeRequests()
                .anyRequest().authenticated()
                .and()
            .httpBasic();
    }

}

package info.agrueneberg.fhir.configurations;

import info.agrueneberg.fhir.services.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private UserService userService;

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userService).passwordEncoder(new BCryptPasswordEncoder());
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .authorizeRequests()
                .antMatchers(HttpMethod.OPTIONS, "/**").permitAll()
                .anyRequest().authenticated()
                .and()
            .httpBasic();
    }

}

Disable security for OPTIONS requests.

Disable security for OPTIONS requests.


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

import com.mafia.server.bus.notify.NotifyGame;
import com.mafia.server.bus.notify.NotifyViewState;
import com.mafia.server.model.state.Game;
import com.mafia.server.model.state.Player;
import com.mafia.server.model.state.Repository;
import javax.websocket.Session;

/**
 *
 * @author Just1689
 */
public class PlayerEvents {

    public static void playerQuits(Session session) {
        Player player = Repository.getPlayerBySession(session);
        if (player != null) {
            player.getGame().removePlayer(player);
        }
        //Todo: notify?
    }

    public static Player makePlayer(String name, String passCode, String sessionId) {
        return new Player(name, passCode, sessionId);
    }

    public static void joinGame(Player player, Game game) {
        player.setGame(game);
        game.addPlayer(player);
        NotifyViewState.nofity(game);
    }

}

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

import com.mafia.server.bus.notify.NotifyViewState;
import com.mafia.server.model.state.Game;
import com.mafia.server.model.state.Player;
import com.mafia.server.model.state.Repository;
import javax.websocket.Session;

/**
 *
 * @author Just1689
 */
public class PlayerEvents {

    public static void playerQuits(Session session) {
        Player player = Repository.getPlayerBySession(session);
        if (player != null) {
            if (player.getGame() == null) {
                return;
            }
            player.getGame().removePlayer(player);
            GameEvents.checkGame(player.getGame());

        }
    }

    public static Player makePlayer(String name, String passCode, String sessionId) {
        return new Player(name, passCode, sessionId);
    }

    public static void joinGame(Player player, Game game) {
        player.setGame(game);
        game.addPlayer(player);
        NotifyViewState.nofity(game);
    }

}

Check game when player quits

Check game when player quits


package sg.ncl.service.realization.web;

import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import sg.ncl.service.realization.data.jpa.RealizationEntity;
import sg.ncl.service.realization.logic.RealizationService;

import javax.inject.Inject;

/**
 * @author Christopher Zhong
 */
@RestController
@RequestMapping(path = "/realizations", produces = MediaType.APPLICATION_JSON_VALUE)
public class RealizationsController {

    private final RealizationService realizationService;

    @Inject
    protected RealizationsController(final RealizationService realizationService) {
        this.realizationService = realizationService;
    }

    @RequestMapping(method = RequestMethod.GET)
    public void get() {}

    @RequestMapping(path = "/start/{experimentId}", method = RequestMethod.PUT)
    public void startExperiment(@PathVariable Long experimentId) {
        RealizationEntity realizationEntity = realizationService.getByExperimentId(experimentId);
        realizationService.startExperimentInDeter(realizationEntity.getTeamId(), realizationEntity.getExperimentName());
    }
}

package sg.ncl.service.realization.web;

import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import sg.ncl.service.realization.data.jpa.RealizationEntity;
import sg.ncl.service.realization.logic.RealizationService;

import javax.inject.Inject;

/**
 * @author Christopher Zhong
 */
@RestController
@RequestMapping(path = "/realizations", produces = MediaType.APPLICATION_JSON_VALUE)
public class RealizationsController {

    private final RealizationService realizationService;

    @Inject
    protected RealizationsController(final RealizationService realizationService) {
        this.realizationService = realizationService;
    }

    @RequestMapping(method = RequestMethod.GET)
    public void get() {}

    @RequestMapping(path = "/start", method = RequestMethod.PUT)
    public void startExperiment(final RealizationEntity realizationEntity) {
        RealizationEntity realizationEntityDb = realizationService.getByExperimentId(realizationEntity.getExperimentId());

        if (realizationEntity == null) {
            realizationService.save(realizationEntity);
        }

        realizationService.startExperimentInDeter(realizationEntityDb.getTeamId(), realizationEntityDb.getExperimentName());
    }
}

Add start method to controller

Add start method to controller


/*
 * 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.beam.runners.core.metrics;

import java.io.Serializable;
import org.apache.beam.sdk.metrics.MetricQueryResults;

/**
 * Abstract base class for all metric sinks it can use different serializers.
 */

public abstract class MetricsSink<OutputT> implements Serializable{

  private MetricsSerializer<OutputT> metricsSerializer = provideSerializer();

  void writeMetrics(MetricQueryResults metricQueryResults) throws Exception {
    if (metricsSerializer != null) {
      OutputT serializedMetrics = metricsSerializer.serializeMetrics(metricQueryResults);
      writeSerializedMetrics(serializedMetrics);
    }
  }
  protected abstract MetricsSerializer<OutputT> provideSerializer();
  protected abstract void writeSerializedMetrics(OutputT metrics) throws Exception;
}

/*
 * 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.beam.runners.core.metrics;

import java.io.Serializable;
import org.apache.beam.sdk.metrics.MetricQueryResults;

/** Abstract base class for all metric sinks it can use different serializers. */
public abstract class MetricsSink<OutputT> implements Serializable {

  private MetricsSerializer<OutputT> metricsSerializer = provideSerializer();

  void writeMetrics(MetricQueryResults metricQueryResults) throws Exception {
    OutputT serializedMetrics = metricsSerializer.serializeMetrics(metricQueryResults);
    writeSerializedMetrics(serializedMetrics);
  }

  protected abstract MetricsSerializer<OutputT> provideSerializer();

  protected abstract void writeSerializedMetrics(OutputT metrics) throws Exception;
}

Remove unneeded null check, format

Remove unneeded null check, format


package org.wikipedia.offline;

import android.app.DownloadManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;

public class DownloadManagerReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        if (DownloadManager.ACTION_NOTIFICATION_CLICKED.equals(action)) {
            if (intent.getExtras() == null || !intent.hasExtra(DownloadManager.EXTRA_NOTIFICATION_CLICK_DOWNLOAD_IDS)) {
                return;
            }
            long[] ids = intent.getLongArrayExtra(DownloadManager.EXTRA_NOTIFICATION_CLICK_DOWNLOAD_IDS);

            DownloadManager downloadManager = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
            for (long id : ids) {
                if (Compilation.MIME_TYPE.equals(downloadManager.getMimeTypeForDownloadedFile(id))) {
                    context.startActivity(LocalCompilationsActivity.newIntent(context));
                    break;
                }
            }
        }
    }
}

package org.wikipedia.offline;

import android.app.DownloadManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;

public class DownloadManagerReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        if (DownloadManager.ACTION_NOTIFICATION_CLICKED.equals(action)) {
            if (intent.getExtras() == null || !intent.hasExtra(DownloadManager.EXTRA_NOTIFICATION_CLICK_DOWNLOAD_IDS)) {
                return;
            }
            long[] ids = intent.getLongArrayExtra(DownloadManager.EXTRA_NOTIFICATION_CLICK_DOWNLOAD_IDS);

            DownloadManager downloadManager = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
            for (long id : ids) {
                if (Compilation.MIME_TYPE.equals(downloadManager.getMimeTypeForDownloadedFile(id))) {
                    context.startActivity(LocalCompilationsActivity.
                            newIntent(context).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK));
                    break;
                }
            }
        }
    }
}

Fix possible crash when clicking DownloadManager notification.

The LocalCompilationsActivity must be launched with the NEW_TASK flag,
since we're calling startActivity() from outside an Activity context.

Bug: T172860
Change-Id: I54a3c8a7a9ea282d94298de4e998e35d0adbabb0


package hello.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class Security extends WebSecurityConfigurerAdapter {

	public static final String ADMIN_ROLE = "ADMINISTRATOR";

	@Override
	protected void configure(HttpSecurity http) throws Exception {
		// Use form login for the Web, and HTTP basic for the API.
		http.authorizeRequests().anyRequest().permitAll().and().formLogin().loginPage("/sign-in").permitAll().and()
				.logout().logoutUrl("/sign-out").logoutSuccessUrl("/").permitAll().and().httpBasic();
	}

	@Autowired
	public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
		auth.inMemoryAuthentication().withUser("Rob").password("Haines").roles(ADMIN_ROLE).and().withUser("Caroline")
		.password("Jay").roles(ADMIN_ROLE).and().withUser("Markel").password("Vigo").roles(ADMIN_ROLE);
	}
}

package hello.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class Security extends WebSecurityConfigurerAdapter {

	public static final String ADMIN_ROLE = "ADMINISTRATOR";

	@Override
	protected void configure(HttpSecurity http) throws Exception {

		// Allow all requests and we use method security in the controllers.
		http.authorizeRequests().anyRequest().permitAll();

		// Use form login/logout for the Web.
		http.formLogin().loginPage("/sign-in").permitAll();
		http.logout().logoutUrl("/sign-out").logoutSuccessUrl("/").permitAll();

		// Use HTTP basic for the API.
		http.httpBasic();
	}

	@Autowired
	public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
		auth.inMemoryAuthentication().withUser("Rob").password("Haines").roles(ADMIN_ROLE).and().withUser("Caroline")
		.password("Jay").roles(ADMIN_ROLE).and().withUser("Markel").password("Vigo").roles(ADMIN_ROLE);
	}
}

Split up the HTTP security config for readability.


package com.rehivetech.beeeon.gcm;

import android.app.IntentService;
import android.content.Intent;

import com.google.android.gms.gcm.GoogleCloudMessaging;
import com.google.android.gms.iid.InstanceID;
import com.rehivetech.beeeon.R;
import com.rehivetech.beeeon.controller.Controller;
import com.rehivetech.beeeon.model.GcmModel;

import java.io.IOException;

import timber.log.Timber;

/**
 * Created by martin on 21.01.16.
 */
public class GcmRegistrationIntentService extends IntentService {

	public GcmRegistrationIntentService() {
		super("GcmRegistrationIntentService");
	}

	@Override
	protected void onHandleIntent(Intent intent) {
		try {
			String token = InstanceID.getInstance(this).getToken(getString(R.string.api_keys_google_console_project_id), GoogleCloudMessaging.INSTANCE_ID_SCOPE, null);

			Controller controller = Controller.getInstance(this);
			GcmModel gcmModel = controller.getGcmModel();
			gcmModel.saveGcm(token);
		} catch (IOException e) {
			Timber.e("Error while getting GCM token");
			e.printStackTrace();
		}
	}
}

package com.rehivetech.beeeon.gcm;

import android.app.IntentService;
import android.content.Intent;

import com.google.android.gms.gcm.GoogleCloudMessaging;
import com.google.android.gms.iid.InstanceID;
import com.rehivetech.beeeon.R;
import com.rehivetech.beeeon.controller.Controller;
import com.rehivetech.beeeon.model.GcmModel;

import java.io.IOException;

import timber.log.Timber;

/**
 * Created by martin on 21.01.16.
 */
public class GcmRegistrationIntentService extends IntentService {

	public GcmRegistrationIntentService() {
		super("GcmRegistrationIntentService");
	}

	@Override
	protected void onHandleIntent(Intent intent) {
		try {
			String token = InstanceID.getInstance(this).getToken(getString(R.string.api_keys_google_console_project_id), GoogleCloudMessaging.INSTANCE_ID_SCOPE, null);

			Controller controller = Controller.getInstance(this);
			GcmModel gcmModel = controller.getGcmModel();
			gcmModel.saveGcm(token);
		} catch (IOException | NullPointerException e) {
			Timber.e("Error while getting GCM token");
			e.printStackTrace();
		}
	}
}

FIx null pointer in gcm registration service


package com.greghaskins.spectrum;

import com.greghaskins.spectrum.Spectrum.Block;

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

class AfterEachBlock implements Block {

  private final List<Block> blocks;

  public AfterEachBlock() {
    this.blocks = new ArrayList<>();
  }

  @Override
  public void run() throws Throwable {
    runAllBlocksInReverseOrder(this.blocks.size() - 1);
  }

  private void runAllBlocksInReverseOrder(final int index) throws Throwable {
    if (index < 0) {
      return;
    }
    try {
      this.blocks.get(index).run();
    } finally {
      runAllBlocksInReverseOrder(index - 1);
    }
  }

  public void addBlock(final Block block) {
    this.blocks.add(block);
  }

}

package com.greghaskins.spectrum;

import com.greghaskins.spectrum.Spectrum.Block;

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

class AfterEachBlock implements Block {

  private final List<Block> blocks;

  public AfterEachBlock() {
    this.blocks = new ArrayList<>();
  }

  @Override
  public void run() throws Throwable {
    runRemainingBlocksInReverseOrder(this.blocks.size() - 1);
  }

  private void runRemainingBlocksInReverseOrder(final int currentIndex) throws Throwable {
    if (currentIndex < 0) {
      return;
    }
    try {
      this.blocks.get(currentIndex).run();
    } finally {
      runRemainingBlocksInReverseOrder(currentIndex - 1);
    }
  }

  public void addBlock(final Block block) {
    this.blocks.add(block);
  }

}

Clarify AfterEach execution flow (naming)


package com.openxc.measurements;

import com.openxc.units.Degree;
import com.openxc.util.Range;

/**
 * The SteeringWheelAngle is the angle of the steering wheel.
 *
 * The wheel is considered centered with the angle is 0. The wheel is turned to
 * the left when the angle is negative, and to the right when it is positive.
 */
public class SteeringWheelAngle extends Measurement<Degree>
        implements VehicleMeasurement {
    private final static Range<Degree> RANGE =
        new Range<Degree>(new Degree(-400), new Degree(400));
    public final static String ID = "steering_wheel_angle";

    public SteeringWheelAngle() { }

    public SteeringWheelAngle(Double value) {
        super(new Degree(value), RANGE);
    }

    public SteeringWheelAngle(Degree value) {
        super(value, RANGE);
    }
}

package com.openxc.measurements;

import com.openxc.units.Degree;
import com.openxc.util.Range;

/**
 * The SteeringWheelAngle is the angle of the steering wheel.
 *
 * The wheel is considered centered with the angle is 0. The wheel is turned to
 * the left when the angle is negative, and to the right when it is positive.
 */
public class SteeringWheelAngle extends Measurement<Degree>
        implements VehicleMeasurement {
    private final static Range<Degree> RANGE =
        new Range<Degree>(new Degree(-508), new Degree(508));
    public final static String ID = "steering_wheel_angle";

    public SteeringWheelAngle() { }

    public SteeringWheelAngle(Double value) {
        super(new Degree(value), RANGE);
    }

    public SteeringWheelAngle(Degree value) {
        super(value, RANGE);
    }
}

Define a wider range for the steering wheel angle.


/*
 * © 2013 by Intellectual Reserve, Inc. All rights reserved.
 */

package org.sonar.plugins.xquery.api;

public interface XQueryConstants {
    static String XQUERY_LANGUAGE_KEY = "xqy";
    static String FILE_EXTENSIONS_KEY = "sonar.marklogic.fileExtensions";
    static String SOURCE_DIRECTORY_KEY = "sonar.marklogic.sourceDirectory";
    static String XQTEST_REPORTS_DIRECTORY_KEY = "sonar.xqtest.reportsPath";

    static String XQUERY_LANGUAGE_NAME = "XQuery";
    static String[] DEFAULT_FILE_EXTENSIONS = { "xqy", "xquery", "xq" };
    static String DEFAULT_FILE_EXTENSIONS_STRING = "xqy, xquery, xq";
    static String DEFAULT_SOURCE_DIRECTORY = "src/main/xquery";
    static String DEFAULT_XQTEST_DIRECTORY = "target/xqtest-reports";
}

/*
 * © 2013 by Intellectual Reserve, Inc. All rights reserved.
 */

package org.sonar.plugins.xquery.api;

public interface XQueryConstants {
    static String XQUERY_LANGUAGE_KEY = "xquery";
    static String FILE_EXTENSIONS_KEY = "sonar.marklogic.fileExtensions";
    static String SOURCE_DIRECTORY_KEY = "sonar.marklogic.sourceDirectory";
    static String XQTEST_REPORTS_DIRECTORY_KEY = "sonar.xqtest.reportsPath";

    static String XQUERY_LANGUAGE_NAME = "XQuery";
    static String[] DEFAULT_FILE_EXTENSIONS = { "xqy", "xquery", "xq" , "xqi", "xql", "xqm", "xqws"};
    static String DEFAULT_FILE_EXTENSIONS_STRING = "xqy, xquery, xq, xqi, xql, xqm, xqws";
    static String DEFAULT_SOURCE_DIRECTORY = "src/main/xquery";
    static String DEFAULT_XQTEST_DIRECTORY = "target/xqtest-reports";
}

Change language key to something more appropriate


package <%=packageName%>.web.rest;

import <%=packageName%>.security.AuthoritiesConstants;
import <%=packageName%>.service.AuditEventService;
import <%=packageName%>.web.propertyeditors.LocaleDateTimeEditor;
import org.joda.time.LocalDateTime;
import org.springframework.boot.actuate.audit.AuditEvent;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;

import javax.annotation.security.RolesAllowed;
import javax.inject.Inject;
import java.util.List;

/**
 * REST controller for getting the audit events.
 */
@RestController
@RequestMapping("/app")
public class AuditResource {

    @Inject
    private AuditEventService auditEventService;

    @InitBinder
    public void initBinder(WebDataBinder binder) {
        binder.registerCustomEditor(LocalDateTime.class, new LocaleDateTimeEditor("yyyy-MM-dd", false));
    }

    @RequestMapping(value = "/rest/audits/all",
            method = RequestMethod.GET,
            produces = "application/json")
    @RolesAllowed(AuthoritiesConstants.ADMIN)
    public List<AuditEvent> findAll() {
        return auditEventService.findAll();
    }

    @RequestMapping(value = "/rest/audits/byDates",
            method = RequestMethod.GET,
            produces = "application/json")
    @RolesAllowed(AuthoritiesConstants.ADMIN)
    public List<AuditEvent> findByDates(@RequestParam(value = "fromDate") LocalDateTime fromDate,
                                    @RequestParam(value = "toDate") LocalDateTime toDate) {
        return auditEventService.findByDates(fromDate, toDate);
    }
}

package <%=packageName%>.web.rest;

import <%=packageName%>.security.AuthoritiesConstants;
import <%=packageName%>.service.AuditEventService;
import <%=packageName%>.web.propertyeditors.LocaleDateTimeEditor;
import org.joda.time.LocalDateTime;
import org.springframework.boot.actuate.audit.AuditEvent;
import org.springframework.http.MediaType;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;

import javax.annotation.security.RolesAllowed;
import javax.inject.Inject;
import java.util.List;

/**
 * REST controller for getting the audit events.
 */
@RestController
@RequestMapping("/app")
public class AuditResource {

    @Inject
    private AuditEventService auditEventService;

    @InitBinder
    public void initBinder(WebDataBinder binder) {
        binder.registerCustomEditor(LocalDateTime.class, new LocaleDateTimeEditor("yyyy-MM-dd", false));
    }

    @RequestMapping(value = "/rest/audits/all",
            method = RequestMethod.GET,
            produces = MediaType.APPLICATION_JSON_VALUE)
    @RolesAllowed(AuthoritiesConstants.ADMIN)
    public List<AuditEvent> findAll() {
        return auditEventService.findAll();
    }

    @RequestMapping(value = "/rest/audits/byDates",
            method = RequestMethod.GET,
            produces = MediaType.APPLICATION_JSON_VALUE)
    @RolesAllowed(AuthoritiesConstants.ADMIN)
    public List<AuditEvent> findByDates(@RequestParam(value = "fromDate") LocalDateTime fromDate,
                                    @RequestParam(value = "toDate") LocalDateTime toDate) {
        return auditEventService.findByDates(fromDate, toDate);
    }
}

Use MediaType instead of user-written string


package org.metaborg.meta.lang.template.strategies;

import org.spoofax.interpreter.core.Tools;
import org.spoofax.interpreter.terms.IStrategoTerm;
import org.spoofax.interpreter.terms.ITermFactory;
import org.strategoxt.lang.Context;
import org.strategoxt.lang.Strategy;

public class unquote_0_0 extends Strategy {
    public static String unquote(String s) {
        return (s != null && ((s.startsWith("\"") && s.endsWith("\"")) || (s.startsWith("'") && s.endsWith("'")))) ? s =
            s.substring(1, s.length() - 1) : s;
    }

    public static unquote_0_0 instance = new unquote_0_0();

    @Override public IStrategoTerm invoke(Context context, IStrategoTerm current) {
        final String str = Tools.asJavaString(current);
        final ITermFactory factory = context.getFactory();
        IStrategoTerm after = factory.makeString(unquote(str));
        after = factory.annotateTerm(after, current.getAnnotations());
        after = factory.copyAttachments(current, after);
        return after;
    }
}

package org.metaborg.meta.lang.template.strategies;

import org.spoofax.interpreter.core.Tools;
import org.spoofax.interpreter.terms.IStrategoTerm;
import org.spoofax.interpreter.terms.ITermFactory;
import org.strategoxt.lang.Context;
import org.strategoxt.lang.Strategy;

public class unquote_0_0 extends Strategy {
    public static String unquote(String s) {
        return s != null && s.length() >= 2
            && (s.startsWith("\"") && s.endsWith("\"") || s.startsWith("'") && s.endsWith("'"))
                ? s.substring(1, s.length() - 1) : s;
    }

    public static unquote_0_0 instance = new unquote_0_0();

    @Override public IStrategoTerm invoke(Context context, IStrategoTerm current) {
        final String str = Tools.asJavaString(current);
        final ITermFactory factory = context.getFactory();
        IStrategoTerm after = factory.makeString(unquote(str));
        after = factory.annotateTerm(after, current.getAnnotations());
        after = factory.copyAttachments(current, after);
        return after;
    }
}

Fix `unquote` strategy for strings containing just a single quote


package com.coreoz.plume.jersey.jackson;

import javax.inject.Provider;
import javax.inject.Singleton;

import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;

// check https://github.com/FasterXML/jackson-databind/issues/779 to see when we can have the SafeObjectMapper
@Singleton
public class ObjectMapperProvider implements Provider<ObjectMapper> {

	private final ObjectMapper objectMapper = new ObjectMapper()
		.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS)
		.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);

	@Override
	public ObjectMapper get() {
		return objectMapper;
	}

}

package com.coreoz.plume.jersey.jackson;

import javax.inject.Provider;
import javax.inject.Singleton;

import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;

// check https://github.com/FasterXML/jackson-databind/issues/779 to see when we can have the SafeObjectMapper
@Singleton
public class ObjectMapperProvider implements Provider<ObjectMapper> {

	private final ObjectMapper objectMapper = new ObjectMapper()
		.registerModule(new JavaTimeModule())
		.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS)
		.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS)
		.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);

	@Override
	public ObjectMapper get() {
		return objectMapper;
	}

}

Add Java 8 Time serialization feature for Jackson


/**
 * Copyright 2017 Pivotal Software, Inc.
 *

 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *

 * http://www.apache.org/licenses/LICENSE-2.0
 *

 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package io.micrometer.core.instrument.simple;

import com.google.common.util.concurrent.AtomicDouble;
import io.micrometer.core.instrument.AbstractMeter;
import io.micrometer.core.instrument.Counter;

public class CumulativeCounter extends AbstractMeter implements Counter {
    private final AtomicDouble value;

    /** Create a new instance. */
    public CumulativeCounter(Id id) {
        super(id);
        this.value = new AtomicDouble();
    }

    @Override
    public void increment(double amount) {
        value.getAndAdd(amount);
    }

    @Override
    public double count() {
        return value.get();
    }
}

/**
 * Copyright 2017 Pivotal Software, Inc.
 *

 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *

 * http://www.apache.org/licenses/LICENSE-2.0
 *

 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package io.micrometer.core.instrument.simple;

import io.micrometer.core.instrument.AbstractMeter;
import io.micrometer.core.instrument.Counter;

import java.util.concurrent.atomic.DoubleAdder;

public class CumulativeCounter extends AbstractMeter implements Counter {
    private final DoubleAdder value;

    /** Create a new instance. */
    public CumulativeCounter(Id id) {
        super(id);
        this.value = new DoubleAdder();
    }

    @Override
    public void increment(double amount) {
        value.add(amount);
    }

    @Override
    public double count() {
        return value.sum();
    }
}

Remove unintended import of Guava classes


package battlecode.world.signal;

import java.util.Arrays;

import battlecode.engine.signal.Signal;
import battlecode.world.NeutralsMap;

/**
 * TODO: update docs
 *
 * @author axc
 */
public class NeutralsDensitySignal extends Signal {
    private final double[][] amounts;
    public NeutralsDensitySignal(NeutralsMap nm) {
        amounts = nm.copyOfCurrentAmounts();
    }

    public double[][] getAmounts() {
        return amounts;
    }
}

package battlecode.world.signal;

import java.util.Arrays;

import battlecode.engine.signal.Signal;
import battlecode.world.NeutralsMap;

/**
 * TODO: update docs
 *
 * @author axc
 */
public class NeutralsDensitySignal extends Signal {
    private final int[][] amounts;
    public NeutralsDensitySignal(NeutralsMap nm) {
        double[][] temp = nm.copyOfCurrentAmounts();
        amounts = new int[temp.length][temp[0].length];
        for (int i = 0; i < temp.length; i++) {
            for (int j = 0; j < temp[i].length; j++) {
                amounts[i][j] = (int) Math.round(temp[i][j]);
            }
        }
    }

    public int[][] getAmounts() {
        return amounts;
    }
}

Save storage in neutrals density signal

Save storage in neutrals density signal


package com.centurylinkcloud.servers.service;

import com.centurylinkcloud.servers.config.ServersModule;
import com.centurylinkcloud.servers.domain.*;
import com.centurylinkcloud.servers.domain.datacenter.DataCenters;
import com.google.inject.Guice;
import com.google.inject.Inject;
import com.google.inject.Injector;
import org.junit.Before;
import org.junit.Test;

import static com.centurylinkcloud.servers.domain.InstanceType.STANDARD;

/**
 * @author ilya.drabenia
 */
public class ServerServiceTest {

    @Inject
    private ServerService serverService;

    @Before
    public void setUp() {
        Guice.createInjector(new ServersModule()).injectMembers(this);
    }

    @Test
    public void testCreate() throws Exception {
        serverService.create("ALTR", new Server()
            .name("ALTRS1")
            .type(STANDARD)
            .group(new Group()
                .datacenter(DataCenters.DE_FRANKFURT)
                .name("Group3")
            )
            .machine(new Machine()
                .cpuCount(1)
                .ram(2)
            )
            .template(new Template()
                .name("CENTOS-6-64-TEMPLATE")
            )
        );
    }

}

package com.centurylinkcloud.servers.service;

import com.centurylinkcloud.servers.config.ServersModule;
import com.centurylinkcloud.servers.domain.*;
import com.centurylinkcloud.servers.domain.datacenter.DataCenters;
import com.google.inject.Guice;
import com.google.inject.Inject;
import com.google.inject.Injector;
import org.junit.Before;
import org.junit.Test;

import static com.centurylinkcloud.servers.domain.InstanceType.STANDARD;

/**
 * @author ilya.drabenia
 */
public class ServerServiceTest {

    @Inject
    private ServerService serverService;

    @Before
    public void setUp() {
        Guice
            .createInjector(new ServersModule())
            .injectMembers(this);
    }

    @Test
    public void testCreate() throws Exception {
        serverService.create("ALTR", new Server()
            .name("ALTRS1")
            .type(STANDARD)
            .group(new Group()
                .datacenter(DataCenters.DE_FRANKFURT)
                .name("Group3")
            )
            .machine(new Machine()
                .cpuCount(1)
                .ram(2)
            )
            .template(new Template()
                .name("CENTOS-6-64-TEMPLATE")
            )
        );
    }

}

Add support of Google Guice dependency injection at integration tests


package com.google.sps.utilities;

public final class DatabaseConstants {
  public static final String INSTANCE_ID = "step-188-instance";
  public static final String DATABASE_ID = "event-organizer-db";
  public static final String PROJECT_ID = "event-organizer-step-2020";
}

package com.google.sps.utilities;

public final class DatabaseConstants {
  public static final String INSTANCE_ID = "step-188-instance";
  public static final String DATABASE_ID = "event-organizer-db-1";
  public static final String PROJECT_ID = "event-organizer-step-2020";
}

Fix database constant after database restore.


package com.jakewharton.rxbinding.internal;

import android.os.Handler;
import android.os.Looper;
import java.util.concurrent.atomic.AtomicIntegerFieldUpdater;
import rx.Subscription;

public abstract class MainThreadSubscription implements Subscription, Runnable {
  private static final Handler mainThread = new Handler(Looper.getMainLooper());

  @SuppressWarnings("unused") // Updated by 'unsubscribedUpdater' object.
  private volatile int unsubscribed;
  private static final AtomicIntegerFieldUpdater<MainThreadSubscription> unsubscribedUpdater =
      AtomicIntegerFieldUpdater.newUpdater(MainThreadSubscription.class, "unsubscribed");

  @Override public final boolean isUnsubscribed() {
    return unsubscribed != 0;
  }

  @Override public final void unsubscribe() {
    if (unsubscribedUpdater.compareAndSet(this, 0, 1)) {
      if (Looper.getMainLooper() == Looper.myLooper()) {
        onUnsubscribe();
      } else {
        mainThread.post(this);
      }
    }
  }

  @Override public final void run() {
    onUnsubscribe();
  }

  protected abstract void onUnsubscribe();
}

package com.jakewharton.rxbinding.internal;

import android.os.Handler;
import android.os.Looper;
import android.support.annotation.Keep;

import java.util.concurrent.atomic.AtomicIntegerFieldUpdater;
import rx.Subscription;

public abstract class MainThreadSubscription implements Subscription, Runnable {
  private static final Handler mainThread = new Handler(Looper.getMainLooper());

  @Keep
  @SuppressWarnings("unused") // Updated by 'unsubscribedUpdater' object.
  private volatile int unsubscribed;
  private static final AtomicIntegerFieldUpdater<MainThreadSubscription> unsubscribedUpdater =
      AtomicIntegerFieldUpdater.newUpdater(MainThreadSubscription.class, "unsubscribed");

  @Override public final boolean isUnsubscribed() {
    return unsubscribed != 0;
  }

  @Override public final void unsubscribe() {
    if (unsubscribedUpdater.compareAndSet(this, 0, 1)) {
      if (Looper.getMainLooper() == Looper.myLooper()) {
        onUnsubscribe();
      } else {
        mainThread.post(this);
      }
    }
  }

  @Override public final void run() {
    onUnsubscribe();
  }

  protected abstract void onUnsubscribe();
}

Add @Keep annotation on unsubscribed field

Since it's accessed via reflection, this needs to be kept un-obfuscated.


/*
 * Copyright 2016 the original author or authors.
 *
 * 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.gradle.caching.internal.tasks;

import org.gradle.api.internal.TaskOutputsInternal;
import org.gradle.caching.internal.tasks.origin.TaskOutputOriginReader;
import org.gradle.caching.internal.tasks.origin.TaskOutputOriginWriter;

import java.io.InputStream;
import java.io.OutputStream;

public interface TaskOutputPacker {
    // Initial format version
    // NOTE: This should be changed whenever we pack a cache entry, such as
    // - changing from gzip to bzip2.
    // - adding/removing properties to the origin metadata
    // - using a different format for the origin metadata
    // - any major changes of the layout of a cache entry
    int CACHE_ENTRY_FORMAT = 1;

    void pack(TaskOutputsInternal taskOutputs, OutputStream output, TaskOutputOriginWriter writeOrigin);

    void unpack(TaskOutputsInternal taskOutputs, InputStream input, TaskOutputOriginReader readOrigin);
}

/*
 * Copyright 2016 the original author or authors.
 *
 * 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.gradle.caching.internal.tasks;

import org.gradle.api.internal.TaskOutputsInternal;
import org.gradle.caching.internal.tasks.origin.TaskOutputOriginReader;
import org.gradle.caching.internal.tasks.origin.TaskOutputOriginWriter;

import java.io.InputStream;
import java.io.OutputStream;

public interface TaskOutputPacker {
    // Initial format version
    // NOTE: This should be changed whenever we change the way we pack a cache entry, such as
    // - changing from gzip to bzip2.
    // - adding/removing properties to the origin metadata
    // - using a different format for the origin metadata
    // - any major changes of the layout of a cache entry
    int CACHE_ENTRY_FORMAT = 1;

    void pack(TaskOutputsInternal taskOutputs, OutputStream output, TaskOutputOriginWriter writeOrigin);

    void unpack(TaskOutputsInternal taskOutputs, InputStream input, TaskOutputOriginReader readOrigin);
}

Add missing words to comment

Add missing words to comment

+review REVIEW-6446


package com.hubspot.dropwizard.guice;

import com.hubspot.dropwizard.guice.objects.ExplicitDAO;
import com.hubspot.dropwizard.guice.objects.ExplicitResource;
import io.dropwizard.testing.junit.ResourceTestRule;
import org.junit.ClassRule;
import org.junit.Test;

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

/**
 * this test is created to address to Null Pointer Exceptions in JerseyTest.teardown() related to ServiceLocator
 * See: https://github.com/dropwizard/dropwizard/issues/828 and http://permalink.gmane.org/gmane.comp.java.dropwizard.devel/376
 */
public class InjectedResourcesTest {

    @ClassRule
    public static final ResourceTestRule resources = ResourceTestRule.builder()
            .addResource(new ExplicitResource(new ExplicitDAO()))
            .build();

    @Test
    public void shouldGetExplicitMessage() {
        // when
        String message = resources.client().target("/explicit/message").request().get(String.class);

        // then
        assertThat(message).isEqualTo("this DAO was bound explicitly");
    }

    @Test
    public void shouldGetJitMessage() {
        // when
        String message = resources.client().target("/explicit/message").request().get(String.class);

        // then
        assertThat(message).isEqualTo("this DAO was bound explicitly");
    }
}

package com.hubspot.dropwizard.guice;

import com.hubspot.dropwizard.guice.objects.ExplicitDAO;
import com.hubspot.dropwizard.guice.objects.ExplicitResource;
import com.squarespace.jersey2.guice.JerseyGuiceUtils;

import io.dropwizard.testing.junit.ResourceTestRule;

import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.ClassRule;
import org.junit.Test;

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

/**
 * this test is created to address to Null Pointer Exceptions in JerseyTest.teardown() related to ServiceLocator
 * See: https://github.com/dropwizard/dropwizard/issues/828 and http://permalink.gmane.org/gmane.comp.java.dropwizard.devel/376
 */
public class InjectedResourcesTest {

    static {
        JerseyGuiceUtils.reset();
    }

    @ClassRule
    public static final ResourceTestRule resources = ResourceTestRule.builder()
            .addResource(new ExplicitResource(new ExplicitDAO()))
            .build();

    @Test
    public void shouldGetExplicitMessage() {
        // when
        String message = resources.client().target("/explicit/message").request().get(String.class);

        // then
        assertThat(message).isEqualTo("this DAO was bound explicitly");
    }

    @Test
    public void shouldGetJitMessage() {
        // when
        String message = resources.client().target("/explicit/message").request().get(String.class);

        // then
        assertThat(message).isEqualTo("this DAO was bound explicitly");
    }
}

Make sure this is set up before the test runs


package model;

import junit.framework.TestCase;

import java.awt.Color;

/**
 *
 * @author bwoconnor
 *
 */

public class TestBoard extends TestCase{
	public void testBoard(){

	}

}

package model;

import junit.framework.TestCase;

import java.awt.Color;

/**
 *
 * @author bwoconnor
 *
 */

public class TestBoard extends TestCase{
	public void testBoard(){
		Board b = new Board();
		b.board[0][0] = new BoardTile(0,0);
		b.board[1][0] = new BoardTile(1,0);
		b.board[2][0] = new BoardTile(2,0);
		b.board[3][0] = new BoardTile(3,0);
		b.board[4][0] = new BoardTile(4,0);
		b.board[5][0] = new BoardTile(5,0);

	}

}

Test created, had to stop because of piece issues.


package wtf.password;

import retrofit.RestAdapter;
import retrofit.http.Field;
import retrofit.http.FormUrlEncoded;
import retrofit.http.POST;

/**
 * @author Erik Beeson
 */
public class ZxcvbnRemote {
	private final ZxcvbnRemoteService service;

	public ZxcvbnRemote() {
		this("https://password.wtf");
	}

	public ZxcvbnRemote(String endpoint) {
		this.service = new RestAdapter.Builder()
							   .setEndpoint(endpoint)
							   .build()
							   .create(ZxcvbnRemoteService.class);
	}

	public PasswordStrength zxcvbn(String password) throws IllegalArgumentException {
		if(password != null && password.length() > 0) {
			return service.zxcvbn(password);
		} else {
			throw new IllegalArgumentException("Invalid password: " + password);
		}
	}

	interface ZxcvbnRemoteService {
		@POST("/zxcvbn")
		@FormUrlEncoded
		PasswordStrength zxcvbn(@Field("password") String password);
	}
}

package wtf.password;

import retrofit.RestAdapter;
import retrofit.http.Field;
import retrofit.http.FormUrlEncoded;
import retrofit.http.POST;

/**
 * @author Erik Beeson
 */
public class ZxcvbnRemote {
	private final ZxcvbnRemoteService service;

	public ZxcvbnRemote(String endpoint) {
		this.service = new RestAdapter.Builder()
							   .setEndpoint(endpoint)
							   .build()
							   .create(ZxcvbnRemoteService.class);
	}

	public PasswordStrength zxcvbn(String password) throws IllegalArgumentException {
		if(password != null && password.length() > 0) {
			return service.zxcvbn(password);
		} else {
			throw new IllegalArgumentException("Invalid password: " + password);
		}
	}

	interface ZxcvbnRemoteService {
		@POST("/zxcvbn")
		@FormUrlEncoded
		PasswordStrength zxcvbn(@Field("password") String password);
	}
}

Remove default constructor to ensure that consumers understand this is a remote service


package uk.ac.ebi.quickgo.client.service.loader.presets.evidence;

import org.springframework.batch.item.ItemProcessor;
import org.springframework.batch.item.validator.ValidationException;

import static uk.ac.ebi.quickgo.client.service.loader.presets.PresetsValidationHelper.checkIsNullOrEmpty;

/**
 * Validates the {@link RawEvidenceNamedPreset} instances being read from flat-files and mapped via
 * {@link StringToRawEvidenceNamedPresetMapper}.
 *
 * Created 05/03/18
 * @author Tony Wardell
 */
public class RawEvidenceNamedPresetValidator implements ItemProcessor<RawEvidenceNamedPreset, RawEvidenceNamedPreset> {
    @Override public RawEvidenceNamedPreset process(RawEvidenceNamedPreset rawNamedPreset) {
        if (rawNamedPreset == null) {
            throw new ValidationException("RawDBPreset cannot be null or empty");
        }

        checkIsNullOrEmpty(rawNamedPreset.name);

        return rawNamedPreset;
    }

}

package uk.ac.ebi.quickgo.client.service.loader.presets.evidence;

import org.springframework.batch.item.ItemProcessor;
import org.springframework.batch.item.validator.ValidationException;

import static uk.ac.ebi.quickgo.client.service.loader.presets.PresetsValidationHelper.checkIsNullOrEmpty;

/**
 * Validates the {@link RawEvidenceNamedPreset} instances being read from flat-files and mapped via
 * {@link StringToRawEvidenceNamedPresetMapper}.
 *
 * Created 05/03/18
 * @author Tony Wardell
 */
public class RawEvidenceNamedPresetValidator implements ItemProcessor<RawEvidenceNamedPreset, RawEvidenceNamedPreset> {
    @Override public RawEvidenceNamedPreset process(RawEvidenceNamedPreset rawEvidenceNamedPreset) {
        if (rawEvidenceNamedPreset == null) {
            throw new ValidationException("RawEvidenceNamedPreset cannot be null or empty");
        }

        checkIsNullOrEmpty(rawEvidenceNamedPreset.name);

        return rawEvidenceNamedPreset;
    }

}

Fix cut 'n' paster error RawDBPreset -> RawEvidenceNamedPreset. Code tidy.


/*
 * Copyright (c) 2016, WSO2 Inc. (http://wso2.com) All Rights Reserved.
 *
 * 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.wso2.msf4j.example;

import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.StreamingOutput;

/**
 * Hello service resource class.
 */
@Path("/hello")
public class HelloService {

    @GET
    @Path("/{name}")
    public String hello(@PathParam("name") String name) {
        System.out.println("Hello");
        return "Hello " + name;
    }
}

/*
 * Copyright (c) 2016, WSO2 Inc. (http://wso2.com) All Rights Reserved.
 *
 * 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.wso2.msf4j.example;

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

/**
 * Hello service resource class.
 */
@Path("/hello")
public class HelloService {

    @GET
    @Path("/{name}")
    public String hello(@PathParam("name") String name) {
        System.out.println("Hello");
        return "Hello " + name;
    }
}

Remove unused imports from helloworld sample


package org.cyclops.integrateddynamics.capability.cable;

import org.cyclops.integrateddynamics.api.block.cable.ICableFakeable;

/**
 * Default implementation of {@link ICableFakeable}.
 * @author rubensworks
 */
public abstract class CableFakeableDefault implements ICableFakeable {

    private boolean real = true;

    @Override
    public boolean isRealCable() {
        return real;
    }

    @Override
    public void setRealCable(boolean real) {
        this.real = real;
        sendUpdate();
    }

    protected abstract void sendUpdate();
}

package org.cyclops.integrateddynamics.capability.cable;

import org.cyclops.integrateddynamics.api.block.cable.ICableFakeable;

/**
 * Default implementation of {@link ICableFakeable}.
 * @author rubensworks
 */
public abstract class CableFakeableDefault implements ICableFakeable {

    private boolean real = true;

    @Override
    public boolean isRealCable() {
        return real;
    }

    @Override
    public void setRealCable(boolean real) {
        boolean oldReal = this.real;
        this.real = real;
        if (oldReal != this.real) {
            sendUpdate();
        }
    }

    protected abstract void sendUpdate();
}

Fix display panels causing unnecessary chunk rerenders


package com.nilhcem.droidcontn.utils;

/**
 * Preconditions inspired by
 * https://github.com/google/guava/blob/master/guava/src/com/google/common/base/Preconditions.java
 */
public final class Preconditions {

    private Preconditions() {
        throw new UnsupportedOperationException();
    }

    /**
     * Ensures the truth of an expression involving one or more parameters to the calling method.
     *
     * @param expression a boolean expression
     * @throws IllegalArgumentException if {@code expression} is false
     */
    public static void checkArgument(boolean expression) {
        if (!expression) {
            throw new IllegalArgumentException();
        }
    }
}

package com.nilhcem.droidcontn.utils;

import android.os.Looper;

import com.nilhcem.droidcontn.BuildConfig;

/**
 * Preconditions inspired by
 * https://github.com/google/guava/blob/master/guava/src/com/google/common/base/Preconditions.java
 */
public final class Preconditions {

    private Preconditions() {
        throw new UnsupportedOperationException();
    }

    /**
     * Ensures the truth of an expression involving one or more parameters to the calling method.
     *
     * @param expression a boolean expression
     * @throws IllegalArgumentException if {@code expression} is false
     */
    public static void checkArgument(boolean expression) {
        if (!expression) {
            throw new IllegalArgumentException();
        }
    }

    public static void checkOnMainThread() {
        if (BuildConfig.DEBUG) {
            if (!isOnMainThread()) {
                throw new IllegalStateException("This method should be called from the main thread");
            }
        }
    }

    public static void checkNotOnMainThread() {
        if (BuildConfig.DEBUG) {
            if (isOnMainThread()) {
                throw new IllegalStateException("This method must not be called on the main thread");
            }
        }
    }

    private static boolean isOnMainThread() {
        return Thread.currentThread() == Looper.getMainLooper().getThread();
    }
}

Add thread preconditions to ensure call is/is not on the main thread


package com.farm.processes;

import com.farm.database.accounts.AccountBalance;
import com.farm.database.accounts.AccountBalanceRepository;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.transaction.Transactional;

/**
 * Farm project. 2017
 * Description:
 */
@Service
@Transactional
public class AccountBalanceProcess
{
  @Resource
  private AccountBalanceRepository accountBalanceRepository;

  public AccountBalance findOrCreateByAccountNumber(){

  }
}

package com.farm.processes;

import com.farm.database.accounts.Account;
import com.farm.database.accounts.AccountBalance;
import com.farm.database.accounts.AccountBalanceRepository;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.transaction.Transactional;

import static java.util.Objects.isNull;

/**
 * Farm project. 2017
 * Description:
 */
@Service
@Transactional
public class AccountBalanceProcess
{
  @Resource
  private AccountBalanceRepository accountBalanceRepository;

  public AccountBalance findOrCreateByAccount(Account account){
    AccountBalance accountBalance = accountBalanceRepository.findByAccount(account);
    if (isNull(accountBalance)){

    }
  }
}

Work with account balance process

Work with account balance process


package seedu.taskmanager.logic.parser;

import java.util.regex.Pattern;

import seedu.taskmanager.logic.parser.ArgumentTokenizer.Prefix;

/**
 * Contains Command Line Interface (CLI) syntax definitions common to multiple commands
 */
public class CliSyntax {

    /* Prefix definitions */
    public static final Prefix PREFIX_STARTDATE = new Prefix("s/");
    public static final Prefix PREFIX_ENDDATE = new Prefix("e/");
    public static final Prefix PREFIX_DESCRIPTION = new Prefix("d/");
    public static final Prefix PREFIX_TAG = new Prefix("#");

    /* Alternative prefix definitions for natural variations of user input*/
//    public static final Prefix ALTERNATIVE_PREFIX_STARTDATE = new Prefix("start on ");
//    public static final Prefix ALTERNATIVE_PREFIX_ENDDATE = new Prefix("end on ");
//    public static final Prefix ALTERNATIVE_PREFIX_DESCRIPTION = new Prefix("with description ");

    /* Patterns definitions */
    public static final Pattern KEYWORDS_ARGS_FORMAT =
            Pattern.compile("(?<keywords>\\S+(?:\\s+\\S+)*)"); // one or more keywords separated by whitespace

    // File Path allows numbers, "/.-", space, lowercase and uppercase letters
    public static final Pattern FILEPATH_ARGS_FORMAT = Pattern.compile("([ 0-9a-zA-Z/.-])+");
}

package seedu.taskmanager.logic.parser;

import java.util.regex.Pattern;

import seedu.taskmanager.logic.parser.ArgumentTokenizer.Prefix;

/**
 * Contains Command Line Interface (CLI) syntax definitions common to multiple commands
 */
public class CliSyntax {

    /* Prefix definitions */
    public static final Prefix PREFIX_STARTDATE = new Prefix("s/");
    public static final Prefix PREFIX_ENDDATE = new Prefix("e/");
    public static final Prefix PREFIX_DESCRIPTION = new Prefix("d/");
    public static final Prefix PREFIX_TAG = new Prefix("#");

    /* Alternative prefix definitions for natural variations of user input*/
//    public static final Prefix ALTERNATIVE_PREFIX_STARTDATE = new Prefix("start on ");
//    public static final Prefix ALTERNATIVE_PREFIX_ENDDATE = new Prefix("end on ");
//    public static final Prefix ALTERNATIVE_PREFIX_DESCRIPTION = new Prefix("with description ");

    /* Patterns definitions */
    public static final Pattern KEYWORDS_ARGS_FORMAT =
            Pattern.compile("(?<keywords>\\S+(?:\\s+\\S+)*)"); // one or more keywords separated by whitespace

    // File Path allows numbers, "/.-", space, lowercase and uppercase letters
    public static final Pattern FILEPATH_ARGS_FORMAT = Pattern.compile("([ 0-9a-zA-Z/_.-])+");
}

Fix to allow “_” (underline) in file path name


package info.u_team.u_team_test.block;

import info.u_team.u_team_core.block.UBlock;
import info.u_team.u_team_test.init.TestItemGroups;
import net.minecraft.block.SoundType;
import net.minecraft.block.material.Material;
import net.minecraft.item.*;

public class BasicBlock extends UBlock {

	public BasicBlock(String name) {
		super(name, TestItemGroups.GROUP, Properties.create(Material.ROCK).hardnessAndResistance(2F).sound(SoundType.GROUND).slipperiness(0.8F).lightValue(1), new Item.Properties().rarity(Rarity.UNCOMMON));
	}

}

package info.u_team.u_team_test.block;

import info.u_team.u_team_core.block.UBlock;
import info.u_team.u_team_test.init.TestItemGroups;
import net.minecraft.block.SoundType;
import net.minecraft.block.material.Material;
import net.minecraft.item.*;

public class BasicBlock extends UBlock {

	public BasicBlock() {
		super(TestItemGroups.GROUP, Properties.create(Material.ROCK).hardnessAndResistance(2F).sound(SoundType.GROUND).slipperiness(0.8F).lightValue(1), new Item.Properties().rarity(Rarity.UNCOMMON));
	}

}

Remove String name from basic block

Remove String name from basic block


package info.u_team.u_team_test.integration;

import org.apache.logging.log4j.*;

import info.u_team.u_team_core.api.integration.*;

@Integration("xyz")
public class TestIntegrationNotCall implements IModIntegration {

	public static final Logger LOGGER = LogManager.getLogger("IntegrationNotCall");

	static {
		LOGGER.fatal("Integration not call is cinit!");
	}

	@Override
	public void construct() {
		LOGGER.fatal("Integration not call is constructed! THIS SHOULD NEVER HAPPEN!!");
		throw new RuntimeException("Integration should not be constructed");
	}

}

package info.u_team.u_team_test.integration;

import org.apache.logging.log4j.*;

import info.u_team.u_team_core.api.integration.*;
import info.u_team.u_team_test.TestMod;

@Integration(modid = TestMod.MODID, integration = "xyz")
public class TestIntegrationNotCall implements IModIntegration {

	public static final Logger LOGGER = LogManager.getLogger("IntegrationNotCall");

	static {
		LOGGER.fatal("Integration not call is cinit!");
	}

	@Override
	public void construct() {
		LOGGER.fatal("Integration not call is constructed! THIS SHOULD NEVER HAPPEN!!");
		throw new RuntimeException("Integration should not be constructed");
	}

}

Add the new modid field in the integration not call


package com.rehivetech.beeeon.threading.task;

import android.content.Context;

import com.rehivetech.beeeon.controller.Controller;

import java.util.EnumSet;

/**
 * Created by martin on 29.3.16.
 */
public class ReloadDashboardDataTask extends ReloadGateDataTask{

	public ReloadDashboardDataTask(Context context, boolean forceReload, ReloadWhat what) {
		super(context, forceReload, what);
	}

	public ReloadDashboardDataTask(Context context, boolean forceReload, EnumSet<ReloadWhat> what) {
		super(context, forceReload, what);
	}

	@Override
	public Boolean doInBackground(String... params) {
		if (!super.doInBackground(params[0])) {
			return false;
		}

		if (params.length ==  1) {
			return true;
		}

		return Controller.getInstance(mContext).getWeatherModel().reloadWeather(mContext, params[0], params[1], params[2]);
	}
}

package com.rehivetech.beeeon.threading.task;

import android.content.Context;

import com.rehivetech.beeeon.controller.Controller;
import com.rehivetech.beeeon.exception.AppException;

import java.util.EnumSet;

/**
 * Created by martin on 29.3.16.
 */
public class ReloadDashboardDataTask extends ReloadGateDataTask{

	public ReloadDashboardDataTask(Context context, boolean forceReload, ReloadWhat what) {
		super(context, forceReload, what);
	}

	public ReloadDashboardDataTask(Context context, boolean forceReload, EnumSet<ReloadWhat> what) {
		super(context, forceReload, what);
	}

	@Override
	public Boolean doInBackground(String... params) {
		try {
			if (!super.doInBackground(params[0])) {
				return false;
			}
		} catch (AppException e) {
			return false;
		}

		if (params.length == 1) {
			return true;
		}

		return Controller.getInstance(mContext).getWeatherModel().reloadWeather(mContext, params[0], params[1], params[2]);
	}
}

Fix crash in reload task in dashboard

Fix crash in reload task in dashboard


/*
 * Copyright 2002-2013 the original author or authors.
 *
 * 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.springframework.xd.demo.gemfire;

import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.web.servlet.config.annotation.AsyncSupportConfigurer;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

/**
 * @author David Turanski
 *
 */
@Configuration
@EnableScheduling
public class MvcConfig  extends WebMvcConfigurerAdapter {
	@Override
	public void configureAsyncSupport(AsyncSupportConfigurer configurer) {
		configurer.setDefaultTimeout(30*1000L);
	}
}

/*
 * Copyright 2002-2013 the original author or authors.
 *
 * 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.springframework.xd.demo.gemfire;

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

import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.web.servlet.config.annotation.AsyncSupportConfigurer;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

/**
 * @author David Turanski
 *
 */
@Configuration
@EnableScheduling
public class MvcConfig extends WebMvcConfigurerAdapter {
	@Override
	public void configureAsyncSupport(AsyncSupportConfigurer configurer) {
		configurer.setDefaultTimeout(30*1000L);
	}

	public void addInterceptors(InterceptorRegistry registry) {
		registry.addInterceptor(new HandlerInterceptorAdapter() {
			@Override
			public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
				response.setHeader("Access-Control-Allow-Origin", "http://localhost:9889");
        return true;
			}
		});
	}
}

Add cross-domain origin header to responses.

Implemented in MVC interceptor.


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

import java.io.IOException;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet(urlPatterns={"/*"})
public class FilterServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        resp.setStatus(HttpServletResponse.SC_MOVED_PERMANENTLY);
        resp.setHeader("Location", "/start/");
    }

}

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

import java.io.IOException;
import java.io.PrintWriter;

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(urlPatterns={"/"})
public class FilterServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
        System.out.println("FilterServlet caught request " + req.getRequestURI());
        if ("/".equals(req.getRequestURI())) {
            System.out.println("Forwarding request");
            resp.setStatus(HttpServletResponse.SC_MOVED_PERMANENTLY);
            resp.setHeader("Location", "/start/");
        } else {
            resp.setStatus(HttpServletResponse.SC_NOT_FOUND);
            PrintWriter writer = resp.getWriter();
            StringBuffer urlBuffer = req.getRequestURL();
            String appLocation = urlBuffer.toString();
            String appUrl = appLocation.substring(0, appLocation.indexOf(req.getRequestURI())) + "/start/";
            writer.println("Resource not found, the Liberty app accelerator can be found here.");
        }
    }

}

Update filter to only redirect if accessed at root, otherwise produce 404 with link to actual page.

Signed-off-by: Kate Stanley <59c12a62b1d23be702ac06d493bad7887a15d0c5@uk.ibm.com>