/*
 * Copyright (C) 2017 the original author or authors.
 *
 * This file is part of jBB Application Project.
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  You may obtain a copy of the License at
 *        http://www.apache.org/licenses/LICENSE-2.0
 */

package org.jbb.frontend.web.faq.logic;

import java.util.Set;
import javax.validation.ConstraintViolation;
import org.springframework.stereotype.Component;
import org.springframework.validation.BindingResult;

@Component
public class FaqErrorsBindingMapper {

    public void map(Set<ConstraintViolation<?>> constraintViolations, BindingResult bindingResult) {
        for (ConstraintViolation violation : constraintViolations) {
            String propertyPath = violation.getPropertyPath().toString();
            propertyPath = propertyPath.replace("questions", "entries");
            bindingResult.rejectValue(propertyPath, violation.getMessage());
        }
    }

}

/*
 * Copyright (C) 2017 the original author or authors.
 *
 * This file is part of jBB Application Project.
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  You may obtain a copy of the License at
 *        http://www.apache.org/licenses/LICENSE-2.0
 */

package org.jbb.frontend.web.faq.logic;

import java.util.Set;
import javax.validation.ConstraintViolation;
import org.springframework.stereotype.Component;
import org.springframework.validation.BindingResult;

@Component
public class FaqErrorsBindingMapper {

    public void map(Set<ConstraintViolation<?>> constraintViolations, BindingResult bindingResult) {
        for (ConstraintViolation violation : constraintViolations) {
            String propertyPath = violation.getPropertyPath().toString();
            propertyPath = propertyPath.replace("questions", "entries");
            bindingResult.rejectValue(propertyPath, "x", violation.getMessage());
        }
    }

}

Fix error message for empty field in FAQ ACP form


/*******************************************************************************
 * Copyright (c) 2004 Actuate Corporation. 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: Actuate Corporation - initial API and implementation
 ******************************************************************************/

package org.eclipse.birt.report.tests.engine;

import junit.framework.Test;
import junit.framework.TestSuite;

import org.eclipse.birt.report.tests.engine.api.AllApiTests;
import org.eclipse.birt.report.tests.engine.regression.AllRegressionTests;
import org.eclipse.birt.report.tests.engine.smoke.AllSmokeTests;

public class AllTests
{
	public static Test suite( )
	{
		TestSuite test = new TestSuite( );
		test.addTest( AllRegressionTests.suite( ) );
//		test.addTest( AllCompatibilityTests.suite( ) );
		test.addTest( AllSmokeTests.suite( ) );
		test.addTest( AllApiTests.suite( ) );
		return test;
	}

}

/*******************************************************************************
 * Copyright (c) 2004 Actuate Corporation. 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: Actuate Corporation - initial API and implementation
 ******************************************************************************/

package org.eclipse.birt.report.tests.engine;

import junit.framework.Test;
import junit.framework.TestSuite;

import org.eclipse.birt.report.tests.engine.api.AllApiTests;

public class AllTests
{
	public static Test suite( )
	{
		TestSuite test = new TestSuite( );
//		test.addTest( AllRegressionTests.suite( ) );
//		test.addTest( AllCompatibilityTests.suite( ) );
//		test.addTest( AllSmokeTests.suite( ) );
		test.addTest( AllApiTests.suite( ) );
		return test;
	}

}

Remove regression, smoke and compatibility package. They have been moved to new test framework except for compatibility which is useless.


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

import jsinterop.annotations.JsMethod;

class ArrayStamper {

  public static <T> T[] stampJavaTypeInfo(Object array, T[] referenceType) {
    T[] asArray = JsUtils.uncheckedCast(array);
    $copyType(asArray, referenceType);
    return asArray;
  }

  @JsMethod(namespace = "vmbootstrap.Arrays")
  public static native <T> void $copyType(T[] array, T[] referenceType);
}

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

import jsinterop.annotations.JsMethod;

/** A utility to provide array stamping. Provided as a separate class to simplify super-source. */
public class ArrayStamper {

  public static <T> T[] stampJavaTypeInfo(Object array, T[] referenceType) {
    T[] asArray = JsUtils.uncheckedCast(array);
    $copyType(asArray, referenceType);
    return asArray;
  }

  @JsMethod(namespace = "vmbootstrap.Arrays")
  public static native <T> void $copyType(T[] array, T[] referenceType);
}

Add helper method on JsArray for easing conversion from/to java array.


package org.wildfly.swarm.ribbon.webapp.runtime;

import org.jboss.shrinkwrap.api.Archive;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.asset.ClassLoaderAsset;
import org.wildfly.swarm.container.runtime.AbstractServerConfiguration;
import org.wildfly.swarm.netflix.ribbon.RibbonArchive;
import org.wildfly.swarm.ribbon.webapp.RibbonWebAppFraction;
import org.wildfly.swarm.undertow.WARArchive;

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

/**
 * @author Lance Ball
 */
public class RibbonWebAppConfiguration extends AbstractServerConfiguration<RibbonWebAppFraction> {

    public RibbonWebAppConfiguration() {
        super(RibbonWebAppFraction.class);
    }

    @Override
    public RibbonWebAppFraction defaultFraction() {
        return new RibbonWebAppFraction();
    }

    @Override
    public List<Archive> getImplicitDeployments(RibbonWebAppFraction fraction) throws Exception {
        List<Archive> list = new ArrayList<>();
        WARArchive war = ShrinkWrap.create( WARArchive.class );
        war.addClass( RibbonToTheCurbSSEServlet.class );
        war.addModule("org.wildfly.swarm.netflix.ribbon");
        war.addAsWebResource(new ClassLoaderAsset("ribbon.js", this.getClass().getClassLoader()), "ribbon.js");
        war.setContextRoot("/ribbon");
        war.as(RibbonArchive.class);
        list.add(war);
        return list;
    }

}

package org.wildfly.swarm.ribbon.webapp.runtime;

import org.jboss.shrinkwrap.api.Archive;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.asset.ClassLoaderAsset;
import org.wildfly.swarm.container.runtime.AbstractServerConfiguration;
import org.wildfly.swarm.netflix.ribbon.RibbonArchive;
import org.wildfly.swarm.ribbon.webapp.RibbonWebAppFraction;
import org.wildfly.swarm.undertow.WARArchive;

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

/**
 * @author Lance Ball
 */
public class RibbonWebAppConfiguration extends AbstractServerConfiguration<RibbonWebAppFraction> {

    private static final String DEFAULT_CONTEXT = "/ribbon";

    public RibbonWebAppConfiguration() {
        super(RibbonWebAppFraction.class);
    }

    @Override
    public RibbonWebAppFraction defaultFraction() {
        return new RibbonWebAppFraction();
    }

    @Override
    public List<Archive> getImplicitDeployments(RibbonWebAppFraction fraction) throws Exception {
        String context = System.getProperty( "wildfly.swarm.ribbon.context.path" );
        if (context == null) context = DEFAULT_CONTEXT;

        List<Archive> list = new ArrayList<>();
        WARArchive war = ShrinkWrap.create( WARArchive.class );
        war.addClass( RibbonToTheCurbSSEServlet.class );
        war.addModule("org.wildfly.swarm.netflix.ribbon");
        war.addAsWebResource(new ClassLoaderAsset("ribbon.js", this.getClass().getClassLoader()), "ribbon.js");
        war.setContextRoot(context);
        war.as(RibbonArchive.class);
        list.add(war);
        return list;
    }

}

Make ribbon-webapp's context path configurable.


package edu.usc.glidein.service.db;

import edu.usc.glidein.stubs.types.Site;
import edu.usc.glidein.stubs.types.SiteStatus;

public interface SiteDAO
{
	public int create(Site site) throws DatabaseException;
	public void store(Site site) throws DatabaseException;
	public Site load(int siteId) throws DatabaseException;
	public void delete(int siteId) throws DatabaseException;
	public SiteStatus getStatus(int siteId) throws DatabaseException;
	public void updateStatus(int siteId, SiteStatus status) throws DatabaseException;
}

package edu.usc.glidein.service.db;

import edu.usc.glidein.stubs.types.Site;
import edu.usc.glidein.stubs.types.SiteStatus;

public interface SiteDAO
{
	public int create(Site site) throws DatabaseException;
	public void store(Site site) throws DatabaseException;
	public Site load(int siteId) throws DatabaseException;
	public void delete(int siteId) throws DatabaseException;
	public void updateStatus(int siteId, SiteStatus status, String statusMessage) throws DatabaseException;
	public Site[] list(boolean full) throws DatabaseException;
}

Remove getStatus Modify updateStatus Add list


package com.campmongoose.serversaturday.common.submission;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;

public abstract class AbstractSubmitter<B extends AbstractBuild, I, L> {

    protected final Map<String, B> builds = new HashMap<>();
    @Nonnull
    protected final String name;
    @Nonnull
    protected final UUID uuid;

    protected AbstractSubmitter(@Nonnull String name, @Nonnull UUID uuid) {
        this.name = name;
        this.uuid = uuid;
    }

    @Nullable
    public B getBuild(@Nonnull String name) {
        return builds.get(name);
    }

    @Nonnull
    public List<B> getBuilds() {
        return new ArrayList<>(builds.values());
    }

    @Nonnull
    public abstract I getMenuRepresentation();

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

    @Nonnull
    public UUID getUUID() {
        return uuid;
    }

    @Nonnull
    public abstract B newBuild(@Nonnull String name, @Nonnull L location);

    public boolean removeBuild(@Nonnull String name) {
        return builds.remove(name) != null;
    }

    public abstract void save(@Nonnull File file);
}

package com.campmongoose.serversaturday.common.submission;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;

public abstract class AbstractSubmitter<B extends AbstractBuild, I, L> {

    protected final Map<String, B> builds = new HashMap<>();
    @Nonnull
    protected final String name;
    @Nonnull
    protected final UUID uuid;

    protected AbstractSubmitter(@Nonnull String name, @Nonnull UUID uuid) {
        this.name = name;
        this.uuid = uuid;
    }

    @Nullable
    public B getBuild(@Nonnull String name) {
        return builds.get(name);
    }

    @Nonnull
    public List<B> getBuilds() {
        return new ArrayList<>(builds.values());
    }

    @Nonnull
    public abstract I getMenuRepresentation();

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

    @Nonnull
    public UUID getUUID() {
        return uuid;
    }

    @Nonnull
    public abstract B newBuild(@Nonnull String name, @Nonnull L location);

    public boolean removeBuild(@Nonnull String name) {
        return builds.remove(name) != null;
    }

    public void renameBuild(String newName, B build) {
        builds.remove(build.getName());
        build.setName(newName);
        builds.put(newName, build);
    }

    public abstract void save(@Nonnull File file);
}

Fix an issue with updating builds.


package io.elssa.nn;

public class ElssaMessage {

    private byte[] payload;

    /**
     * Constructs an ElssaMessage from an array of bytes.
     *
     * @param payload message payload in the form of a byte array.
     */
    public ElssaMessage(byte[] payload) {
        this.payload = payload;
    }

    /**
     * Retrieves the payload for this ElssaMessage.
     *
     * @return the ElssaMessage payload
     */
    public byte[] payload() {
        return payload;
    }
}

package io.elssa.nn;

public class ElssaMessage {

    private byte[] payload;
    private MessageContext context;

    /**
     * Constructs an ElssaMessage from an array of bytes.
     *
     * @param payload message payload in the form of a byte array.
     */
    public ElssaMessage(byte[] payload) {
        this.payload = payload;
    }

    public ElssaMessage(byte[] payload, MessageContext context) {
        this(payload);
        this.context = context;
    }

    /**
     * Retrieves the payload for this ElssaMessage.
     *
     * @return the ElssaMessage payload
     */
    public byte[] payload() {
        return payload;
    }

    public MessageContext context() {
        return context;
    }
}

Add context to message encapsulation


package io.reflectoring.coderadar.graph.query.repository;

import io.reflectoring.coderadar.analyzer.domain.Commit;
import io.reflectoring.coderadar.graph.analyzer.domain.CommitEntity;
import java.util.List;
import org.springframework.data.neo4j.annotation.Query;
import org.springframework.data.neo4j.repository.Neo4jRepository;
import org.springframework.stereotype.Repository;

@Repository
public interface GetCommitsInProjectRepository extends Neo4jRepository<CommitEntity, Long> {

  @Query(
      "MATCH (p:ProjectEntity)-[:CONTAINS]->(f:FileEntity)-[:CHANGED_IN]->(c:CommitEntity) WHERE ID(p) = {0} RETURN c "
          + "UNION MATCH (p:ProjectEntity)-[:CONTAINS]->(m:ModuleEntity)-[:CONTAINS]->(f:FileEntity)-[:CHANGED_IN]->(c:CommitEntity) WHERE ID(p) = {0} RETURN c")
  List<CommitEntity> findByProjectId(Long projectId);

  @Query(
    value =
        "MATCH (p:Project)-[:HAS]->(c:Commit) WHERE ID(p) = {0} RETURN c ORDER BY c.sequenceNumber DESC LIMIT 1"
  )
  Commit findTop1ByProjectIdOrderBySequenceNumberDesc(Long id);
}

package io.reflectoring.coderadar.graph.query.repository;

import io.reflectoring.coderadar.analyzer.domain.Commit;
import io.reflectoring.coderadar.graph.analyzer.domain.CommitEntity;
import java.util.List;
import org.springframework.data.neo4j.annotation.Query;
import org.springframework.data.neo4j.repository.Neo4jRepository;
import org.springframework.stereotype.Repository;

@Repository
public interface GetCommitsInProjectRepository extends Neo4jRepository<CommitEntity, Long> {

  @Query("MATCH (p1:ProjectEntity)-[:CONTAINS*]-(f1:FileEntity)-[:CHANGED_IN]->(c1:CommitEntity) " +
          "OPTIONAL MATCH (c2:CommitEntity)-[:IS_CHILD_OF]->(c1:CommitEntity) " +
          "WHERE ID(p1) = {0} " +
          "UNWIND [c1, c2] AS c " +
          "RETURN DISTINCT c " +
          "ORDER BY c.timestamp DESC")
  List<CommitEntity> findByProjectId(Long projectId);

  @Query(
    value =
        "MATCH (p:Project)-[:HAS]->(c:Commit) WHERE ID(p) = {0} RETURN c ORDER BY c.sequenceNumber DESC LIMIT 1"
  )
  Commit findTop1ByProjectIdOrderBySequenceNumberDesc(Long id);
}

Update the query for finding all commits belonging to a project


package org.wikipedia.search;

import android.content.Context;
import android.content.Intent;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import org.wikipedia.Constants.InvokeSource;
import org.wikipedia.WikipediaApp;
import org.wikipedia.activity.SingleFragmentActivity;
import org.wikipedia.analytics.IntentFunnel;

import static org.wikipedia.Constants.INTENT_EXTRA_INVOKE_SOURCE;
import static org.wikipedia.Constants.InvokeSource.WIDGET;

public class SearchActivity extends SingleFragmentActivity<SearchFragment> {
    static final String QUERY_EXTRA = "query";

    public static Intent newIntent(@NonNull Context context, InvokeSource source, @Nullable String query) {

        if (source == WIDGET) {
            new IntentFunnel(WikipediaApp.getInstance()).logSearchWidgetTap();
        }

        // We use the ordinal() for passing the INVOKE_SOURCE into the intent because this intent
        // could be used as part of an App Shortcut, and unfortunately app shortcuts do not allow
        // Serializable objects in their intents.
        return new Intent(context, SearchActivity.class)
                .putExtra(INTENT_EXTRA_INVOKE_SOURCE, source.ordinal())
                .putExtra(QUERY_EXTRA, query);
    }

    @Override
    public SearchFragment createFragment() {
        return SearchFragment.newInstance(InvokeSource.values()[getIntent().getIntExtra(INTENT_EXTRA_INVOKE_SOURCE, InvokeSource.TOOLBAR.ordinal())],
                getIntent().getStringExtra(QUERY_EXTRA));
    }
}

package org.wikipedia.search;

import android.content.Context;
import android.content.Intent;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import org.wikipedia.Constants.InvokeSource;
import org.wikipedia.WikipediaApp;
import org.wikipedia.activity.SingleFragmentActivity;
import org.wikipedia.analytics.IntentFunnel;

import static org.wikipedia.Constants.INTENT_EXTRA_INVOKE_SOURCE;
import static org.wikipedia.Constants.InvokeSource.WIDGET;

public class SearchActivity extends SingleFragmentActivity<SearchFragment> {
    static final String QUERY_EXTRA = "query";

    public static Intent newIntent(@NonNull Context context, InvokeSource source, @Nullable String query) {

        if (source == WIDGET) {
            new IntentFunnel(WikipediaApp.getInstance()).logSearchWidgetTap();
        }

        return new Intent(context, SearchActivity.class)
                .putExtra(INTENT_EXTRA_INVOKE_SOURCE, source)
                .putExtra(QUERY_EXTRA, query);
    }

    @Override
    public SearchFragment createFragment() {
        return SearchFragment.newInstance((InvokeSource) getIntent().getSerializableExtra(INTENT_EXTRA_INVOKE_SOURCE),
                getIntent().getStringExtra(QUERY_EXTRA));
    }
}

Undo ordinal conversion, since this is now a static shortcut.


package cz.metacentrum.perun.wui.registrar.widgets.items.validators;

import cz.metacentrum.perun.wui.registrar.widgets.items.Radiobox;
import org.gwtbootstrap3.client.ui.constants.ValidationState;

/**
 * @author Ondrej Velisek <ondrejvelisek@gmail.com>
 */
public class RadioboxValidator extends PerunFormItemValidatorImpl<Radiobox> {

	@Override
	public boolean validateLocal(Radiobox radiobox) {

		if (radiobox.isRequired() && isNullOrEmpty(radiobox.getValue())) {
			setResult(Result.EMPTY);
			radiobox.setStatus(getTransl().cantBeEmpty(), ValidationState.ERROR);
			return false;
		}

		radiobox.setStatus(ValidationState.SUCCESS);
		return true;
	}

}

package cz.metacentrum.perun.wui.registrar.widgets.items.validators;

import com.google.gwt.regexp.shared.MatchResult;
import com.google.gwt.regexp.shared.RegExp;
import cz.metacentrum.perun.wui.registrar.widgets.items.Radiobox;
import org.gwtbootstrap3.client.ui.constants.ValidationState;

/**
 * @author Ondrej Velisek <ondrejvelisek@gmail.com>
 */
public class RadioboxValidator extends PerunFormItemValidatorImpl<Radiobox> {

	@Override
	public boolean validateLocal(Radiobox radiobox) {

		if (radiobox.isRequired() && isNullOrEmpty(radiobox.getValue())) {
			setResult(Result.EMPTY);
			radiobox.setStatus(getTransl().cantBeEmpty(), ValidationState.ERROR);
			return false;
		}

		String regex = radiobox.getItemData().getFormItem().getRegex();

		if (regex != null && !regex.equals("")) {

			RegExp regExp = RegExp.compile(regex);
			MatchResult matcher = regExp.exec(radiobox.getValue());
			boolean matchFound = (matcher != null); // equivalent to regExp.test(inputStr);
			if(!matchFound){

				setResult(Result.INVALID_FORMAT);
				radiobox.setStatus(getErrorMsgOrDefault(radiobox), ValidationState.ERROR);
				return false;
			}
		}

		radiobox.setStatus(ValidationState.SUCCESS);
		return true;
	}

}

Allow regex check on radio buttons on registration forms


package com.byteowls.vaadin.chartjs;

import com.vaadin.shared.ui.JavaScriptComponentState;
import elemental.json.JsonValue;

public class ChartJsState extends JavaScriptComponentState {

    public float width;
    public float height;
    public boolean loggingEnabled;
    public JsonValue configurationJson;

}

package com.byteowls.vaadin.chartjs;

import com.vaadin.shared.ui.JavaScriptComponentState;
import elemental.json.JsonValue;

public class ChartJsState extends JavaScriptComponentState {

    private static final long serialVersionUID = 542472889885500321L;

    public boolean loggingEnabled;
    public JsonValue configurationJson;

}

Remove redunant height and width members. using the inheritated ones


/*
 * Copyright 2013-2017 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.cloud.gateway.filter.factory;

import org.springframework.tuple.Tuple;
import org.springframework.web.server.WebFilter;

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

/**
 * @author Spencer Gibb
 */
public class SetResponseHeaderWebFilterFactory implements WebFilterFactory {

	@Override
	public List<String> argNames() {
		return Arrays.asList(NAME_KEY, VALUE_KEY);
	}

	@Override
	public WebFilter apply(Tuple args) {
		final String header = args.getString(NAME_KEY);
		final String value = args.getString(VALUE_KEY);

		return (exchange, chain) -> {
			exchange.getResponse().getHeaders().set(header, value);

			return chain.filter(exchange);
		};
	}
}

/*
 * Copyright 2013-2017 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.cloud.gateway.filter.factory;

import org.springframework.tuple.Tuple;
import org.springframework.web.server.WebFilter;
import reactor.core.publisher.Mono;

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

/**
 * @author Spencer Gibb
 */
public class SetResponseHeaderWebFilterFactory implements WebFilterFactory {

	@Override
	public List<String> argNames() {
		return Arrays.asList(NAME_KEY, VALUE_KEY);
	}

	@Override
	public WebFilter apply(Tuple args) {
		final String header = args.getString(NAME_KEY);
		final String value = args.getString(VALUE_KEY);

		return (exchange, chain) -> chain.filter(exchange).then(Mono.fromRunnable(() -> {
			exchange.getResponse().getHeaders().set(header, value);
		}));
	}
}

Remove header AFTER response is received.


package org.camunda.bpm.example.multiple_versions_parallel.nonarquillian;

import org.camunda.bpm.engine.impl.util.LogUtil;
import org.camunda.bpm.engine.test.ProcessEngineTestCase;
import org.camunda.bpm.engine.test.Deployment;

/**
 * Test case starting an in-memory database-backed Process Engine.
 */
public class InMemoryH2Test extends ProcessEngineTestCase {

  private static final String PROCESS_DEFINITION_KEY = "multiple-versions-parallel";

  // enable more detailed logging
  static {
    LogUtil.readJavaUtilLoggingConfigFromClasspath();
  }

  /**
   * Just tests if the process definition is deployable.
   */
  @Deployment(resources = "process.bpmn")
  public void testParsingAndDeployment() {
    // nothing is done here, as we just want to check for exceptions during deployment
  }

}

package org.camunda.bpm.example.multiple_versions_parallel.nonarquillian;

import java.io.IOException;
import java.util.Properties;
import java.util.ResourceBundle;

import org.camunda.bpm.engine.impl.util.LogUtil;
import org.camunda.bpm.engine.test.ProcessEngineTestCase;
import org.camunda.bpm.engine.test.Deployment;

/**
 * Test case starting an in-memory database-backed Process Engine.
 */
public class InMemoryH2Test extends ProcessEngineTestCase {

  private static final String PROCESS_DEFINITION_KEY = "multiple-versions-parallel-v";

  // enable more detailed logging
  static {
    LogUtil.readJavaUtilLoggingConfigFromClasspath();
  }

  /**
   * Just tests if the process definition is deployable.
   * @throws IOException
   */
  @Deployment(resources = "process.bpmn")
  public void testParsingAndDeployment() throws IOException {
    Properties version = new Properties();
    version.load(this.getClass().getResourceAsStream("/version.properties"));
    runtimeService.startProcessInstanceByKey(PROCESS_DEFINITION_KEY + version.getProperty("maven.version.major") + "." + version.getProperty("maven.version.minor"));
  }

}

Access version in test case


package nl.homeserver.klimaat;

import java.math.BigDecimal;
import java.time.LocalDateTime;

import lombok.Data;
import nl.homeserver.Trend;

@Data
public class RealtimeKlimaat {
    private LocalDateTime datumtijd;
    private BigDecimal temperatuur;
    private BigDecimal luchtvochtigheid;
    private Trend temperatuurTrend;
    private Trend luchtvochtigheidTrend;
}

package nl.homeserver.klimaat;

import java.math.BigDecimal;
import java.time.LocalDateTime;

import lombok.Getter;
import lombok.Setter;
import nl.homeserver.Trend;

public class RealtimeKlimaat {
    @Getter @Setter
    private LocalDateTime datumtijd;
    @Getter @Setter
    private BigDecimal temperatuur;
    @Getter @Setter
    private BigDecimal luchtvochtigheid;
    @Getter @Setter
    private Trend temperatuurTrend;
    @Getter @Setter
    private Trend luchtvochtigheidTrend;
}

Replace @Data by @Getter and @Setter


package net.aeten.core.spi;

/**
 *
 * @author Thomas Pérennou
 */
public @interface Configuration {
	String name();
	Class<?> provider();
	String parser() default "";
}

package net.aeten.core.spi;

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

/**
 *
 * @author Thomas Pérennou
 */
@Documented
@Retention(RetentionPolicy.SOURCE)
@Target({ElementType.PACKAGE, ElementType.TYPE})
public @interface Configuration {
	String name();
	Class<?> provider();
	String parser() default "";
}

Add Documented, Retention and Target annotations


package com.ibm.watson.common;

import com.ibm.cloud.sdk.core.http.HttpHeaders;
import com.ibm.cloud.sdk.core.test.WatsonServiceUnitTest;
import org.junit.Test;

import java.util.Map;

import static org.junit.Assert.assertTrue;

public class SdkCommonTest extends WatsonServiceUnitTest {
  @Test
  public void testGetDefaultHeaders() {
    String serviceName = "test_name";
    String serviceVersion = "v1";
    String operationId = "test_method";
    Map<String, String> defaultHeaders = SdkCommon.getDefaultHeaders(serviceName, serviceVersion, operationId);

    assertTrue(defaultHeaders.containsKey(HttpHeaders.X_IBMCLOUD_SDK_ANALYTICS));
    String analyticsHeaderValue = defaultHeaders.get(HttpHeaders.X_IBMCLOUD_SDK_ANALYTICS);
    assertTrue(analyticsHeaderValue.contains(serviceName));
    assertTrue(analyticsHeaderValue.contains(serviceVersion));
    assertTrue(analyticsHeaderValue.contains(operationId));
    assertTrue(defaultHeaders.containsKey(HttpHeaders.USER_AGENT));
    assertTrue(defaultHeaders.get(HttpHeaders.USER_AGENT).startsWith("watson-apis-java-sdk/"));
  }
}

package com.ibm.watson.common;

import com.ibm.cloud.sdk.core.http.HttpHeaders;
import org.junit.Test;

import java.util.Map;

import static org.junit.Assert.assertTrue;

public class SdkCommonTest {
  @Test
  public void testGetDefaultHeaders() {
    String serviceName = "test_name";
    String serviceVersion = "v1";
    String operationId = "test_method";
    Map<String, String> defaultHeaders = SdkCommon.getDefaultHeaders(serviceName, serviceVersion, operationId);

    assertTrue(defaultHeaders.containsKey(WatsonHttpHeaders.X_IBMCLOUD_SDK_ANALYTICS));
    String analyticsHeaderValue = defaultHeaders.get(WatsonHttpHeaders.X_IBMCLOUD_SDK_ANALYTICS);
    assertTrue(analyticsHeaderValue.contains(serviceName));
    assertTrue(analyticsHeaderValue.contains(serviceVersion));
    assertTrue(analyticsHeaderValue.contains(operationId));
    assertTrue(defaultHeaders.containsKey(HttpHeaders.USER_AGENT));
    assertTrue(defaultHeaders.get(HttpHeaders.USER_AGENT).startsWith("watson-apis-java-sdk/"));
  }
}

Remove unnecessary extension and change header class reference


// Get JAFFE database from http://www.kasrl.org/jaffe_info.html
// Extract pics in folder named "jaffe"
// package image_test;

import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;

public class svq {

    public static void main(String[] args) {
        // read image
        BufferedImage input = null;
        try {
            input = ImageIO.read(new File("jaffe/KA.AN1.39.tiff.bmp"));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        // to byte array
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        try {
            ImageIO.write( input, "bmp", baos );
            baos.flush();
        } catch (IOException e) {

        }
        byte[] bytearray = baos.toByteArray();

        // to BufferedImage
        ByteArrayInputStream bais = new ByteArrayInputStream(bytearray);
        BufferedImage output = null;
        try {
            output = ImageIO.read(bais);
            bais.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        System.out.println("Done!");
    }
}

// Get JAFFE database from http://www.kasrl.org/jaffe_info.html
// Extract pics in folder named "jaffe"
// package image_test;

import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;

public class svq {

    public static void main(String[] args) {
        // read image
        BufferedImage input = null;
        try {
            input = ImageIO.read(new File("jaffe/KA.AN1.39.tiff.bmp"));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        // to byte array
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        try {
            ImageIO.write( input, "bmp", baos );
            baos.flush();
        } catch (IOException e) {

        }
        byte[] bytearray = baos.toByteArray();

        // to BufferedImage
        ByteArrayInputStream bais = new ByteArrayInputStream(bytearray);
        BufferedImage output = null;
        try {
            output = ImageIO.read(bais);
            bais.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        // save result
        try {
            ImageIO.write(output, "BMP", new File("test.bmp"));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        System.out.println("Done!");
    }
}

Save buffered image as bmp


package com.almende.util;

import com.almende.dialog.aws.AWSClient;

public class AWSThread extends Thread {

    @Override
    public void run() {
        ParallelInit.awsClient = new AWSClient();
        ParallelInit.awsClientActive = true;
    }
}

package com.almende.util;

import com.almende.dialog.Settings;
import com.almende.dialog.aws.AWSClient;

public class AWSThread extends Thread {

    @Override
    public void run() {
        ParallelInit.awsClient = new AWSClient();
        ParallelInit.awsClient.init( Settings.BUCKET_NAME, Settings.AWS_ACCESS_KEY, Settings.AWS_ACCESS_KEY_SECRET );
        ParallelInit.awsClientActive = true;
    }
}

Put init back in aws client


package com.letscode.lcg;

import java.util.Random;

import com.badlogic.gdx.backends.lwjgl.LwjglApplication;
import com.badlogic.gdx.backends.lwjgl.LwjglApplicationConfiguration;

public class Main {
	public static void main(String[] args) {
		LwjglApplicationConfiguration cfg = new LwjglApplicationConfiguration();
		String hostname = args.length > 0 ? args[0] : "localhost";
		int port = args.length > 1 ? Integer.parseInt(args[1]) : 80;
		String nickname = args.length > 2 ? args[2] : "Player " + (new Random().nextInt(12415124));

		cfg.title = "Lambda Cipher Genesis - " + nickname;
		cfg.useGL20 = false;

		{
			cfg.width = 1024;
			cfg.height = 600;
		}
		new LwjglApplication(new LcgApp(hostname, port, nickname), cfg);
	}
}

package com.letscode.lcg;

import java.util.Random;

import com.badlogic.gdx.backends.lwjgl.LwjglApplication;
import com.badlogic.gdx.backends.lwjgl.LwjglApplicationConfiguration;

public class Main {
	public static void main(String[] args) {
		LwjglApplicationConfiguration cfg = new LwjglApplicationConfiguration();
		String hostname = args.length > 0 ? args[0] : "localhost";
		int port = args.length > 1 ? Integer.parseInt(args[1]) : 80;
		String nickname = args.length > 2 ? args[2] : null;//"Player " + (new Random().nextInt(12415124));

		final String gameTitle = "Lambda Cipher Genesis";

		cfg.title = nickname != null ? gameTitle + " - " + nickname : gameTitle;
		cfg.useGL20 = false;
		cfg.width = 1024;
		cfg.height = 600;

		new LwjglApplication(new LcgApp(hostname, port, nickname), cfg);
	}
}

Fix desktop version for crash in situation when no parameters are given.


package com.github.zhanhb.judge.common;

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

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

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

}

package com.github.zhanhb.judge.common;

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

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

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

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

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

    }

}

Add default option builder limits


package com.edinarobotics.zeke.commands;

import edu.wpi.first.wpilibj.command.Command;
import com.edinarobotics.utils.gamepad.Gamepad;
import com.edinarobotics.zeke.subsystems.DrivetrainStrafe;
import com.edinarobotics.zeke.Components;
import com.edinarobotics.utils.gamepad.GamepadAxisState;

public class GamepadDriveStrafeCommand extends Command {
    private Gamepad gamepad;
    private GamepadAxisState gamepadAxisState;
    private DrivetrainStrafe drivetrainStrafe;

    public GamepadDriveStrafeCommand(Gamepad gamepad) {
        super("GamepadDriveStrafe");
        this.gamepad = gamepad;
        this.drivetrainStrafe = Components.getInstance().drivetrainStrafe;
        requires(drivetrainStrafe);
    }

    protected void initialize() {
    }

    protected void execute() {
        double magnitude = gamepad.getGamepadAxisState().getLeftMagnitude();
        double direction = gamepad.getGamepadAxisState().getLeftDirection();
        drivetrainStrafe.setMecanumPolarStrafe(magnitude, direction);
    }

    protected boolean isFinished() {
        return false;
    }

    protected void end() {
    }

    protected void interrupted() {
        end();
    }

}

package com.edinarobotics.zeke.commands;

import edu.wpi.first.wpilibj.command.Command;
import com.edinarobotics.utils.gamepad.Gamepad;
import com.edinarobotics.zeke.subsystems.DrivetrainStrafe;
import com.edinarobotics.zeke.Components;
import com.edinarobotics.utils.gamepad.GamepadAxisState;

public class GamepadDriveStrafeCommand extends Command {
    private Gamepad gamepad;
    private GamepadAxisState gamepadAxisState;
    private DrivetrainStrafe drivetrainStrafe;

    public GamepadDriveStrafeCommand(Gamepad gamepad) {
        super("GamepadDriveStrafe");
        this.gamepad = gamepad;
        this.drivetrainStrafe = Components.getInstance().drivetrainStrafe;
        requires(drivetrainStrafe);
    }

    protected void initialize() {
    }

    protected void execute() {
        double magnitude = gamepad.getGamepadAxisState().getLeftMagnitude();
        double direction = wpilibAngleCorrection(gamepad.getGamepadAxisState().getLeftDirection());
        drivetrainStrafe.setMecanumPolarStrafe(magnitude, direction);
    }

    protected boolean isFinished() {
        return false;
    }

    protected void end() {
    }

    protected void interrupted() {
        end();
    }

    public static double wpilibAngleCorrection(double normalAngle){
        //Converts normal angle format to the weird WPILib measurement
        double convertedAngle = (normalAngle - 90.0) * -1.0;
        if(convertedAngle > 180.0){
            return convertedAngle - 360.0;
        }
        else if(convertedAngle < -180.0){
            return convertedAngle + 360.0;
        }
        return convertedAngle;
    }

}

Add angle correction to normal robot code.


package hudson.model;

import hudson.model.Slave.ComputerImpl;
import hudson.triggers.SafeTimerTask;

/**
 * Periodically checks the slaves and try to reconnect dead slaves.
 *
 * @author Kohsuke Kawaguchi
 */
public class SlaveReconnectionWork extends SafeTimerTask {
    protected void doRun() {
        for(Slave s : Hudson.getInstance().getSlaves()) {
            ComputerImpl c = s.getComputer();
            if(c==null) // shouldn't happen, but let's be defensive
                continue;
            if(c.isOffline() && c.isStartSupported())
                c.tryReconnect();
        }
    }
}

package hudson.model;

import hudson.model.Slave.ComputerImpl;
import static hudson.model.SlaveAvailabilityStrategy.*;
import hudson.triggers.SafeTimerTask;

import java.util.Map;
import java.util.WeakHashMap;

/**
 * Periodically checks the slaves and try to reconnect dead slaves.
 *
 * @author Kohsuke Kawaguchi
 */
public class SlaveReconnectionWork extends SafeTimerTask {
    protected void doRun() {
        // use a weak hashmap
        Map<Slave, Long> nextCheck = new WeakHashMap<Slave, Long>();
        for (Slave s : Hudson.getInstance().getSlaves()) {
            if (!nextCheck.containsKey(s) || System.currentTimeMillis() > nextCheck.get(s)) {
                final Queue queue = Hudson.getInstance().getQueue();
                boolean hasJob = false;
                for (Executor exec: s.getComputer().getExecutors()) {
                    if (!exec.isIdle()) {
                        hasJob = true;
                        break;
                    }
                }
                // TODO get only the items from the queue that can apply to this slave
                State state = new State(queue.getItems().length > 0, hasJob);
                // at the moment I don't trust strategies to wait more than 60 minutes
                // strategies need to wait at least one minute
                final long waitInMins = Math.min(1, Math.max(60, s.getAvailabilityStrategy().check(s, state)));
                nextCheck.put(s, System.currentTimeMillis() + 60 * 1000 * waitInMins);
            }
        }
    }
}

Make the slave availability strategy actually do stuff!


package org.realityforge.ssf;

import java.util.UUID;
import javax.annotation.Nonnull;
import javax.inject.Inject;
import org.keycloak.adapters.OidcKeycloakAccount;
import org.realityforge.keycloak.sks.SimpleAuthService;

public class SimpleSecureSessionManager
  extends InMemorySessionManager<SimpleSessionInfo>
{
  @Inject
  private SimpleAuthService _authService;

  @Nonnull
  @Override
  protected SimpleSessionInfo newSessionInfo()
  {
    final OidcKeycloakAccount account = _authService.getAccount();
    final String userID = account.getKeycloakSecurityContext().getToken().getId();
    final String sessionID = UUID.randomUUID().toString();
    return new SimpleSessionInfo( userID, sessionID );
  }
}

package org.realityforge.ssf;

import java.util.UUID;
import javax.annotation.Nonnull;
import javax.inject.Inject;
import org.keycloak.adapters.OidcKeycloakAccount;
import org.realityforge.keycloak.sks.SimpleAuthService;

public class SimpleSecureSessionManager
  extends InMemorySessionManager<SimpleSessionInfo>
{
  @Inject
  private SimpleAuthService _authService;

  @Nonnull
  @Override
  protected SimpleSessionInfo newSessionInfo()
  {
    final OidcKeycloakAccount account = _authService.findAccount();
    final String userID = null == account ? null : account.getKeycloakSecurityContext().getToken().getId();
    final String sessionID = UUID.randomUUID().toString();
    return new SimpleSessionInfo( userID, sessionID );
  }
}

Allow null users in session manager. If it get's to this point then assume it is ok


package handlers;

import org.atmosphere.config.service.AtmosphereHandlerService;
import org.atmosphere.cpr.AtmosphereHandler;
import org.atmosphere.cpr.AtmosphereRequest;
import org.atmosphere.cpr.AtmosphereResource;
import org.atmosphere.cpr.AtmosphereResourceEvent;

import java.io.IOException;

/**
 * Created by rostifar on 6/14/16.
 */
@AtmosphereHandlerService
public class ScrabbleGameHandler implements AtmosphereHandler {

    //action when connection is made to the backend

    @Override
    public void onRequest(AtmosphereResource atmosphereResource) throws IOException {

        AtmosphereRequest request = atmosphereResource.getRequest();

        System.out.println("hi");
    }

    //called when Broadcaster broadcasts an event
    @Override
    public void onStateChange(AtmosphereResourceEvent atmosphereResourceEvent) throws IOException {

    }

    @Override
    public void destroy() {

    }
}

package handlers;

import org.atmosphere.config.service.AtmosphereHandlerService;
import org.atmosphere.cpr.*;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import java.io.IOException;

/**
 * Created by rostifar on 6/14/16.
 */
@AtmosphereHandlerService
public class ScrabbleGameHandler implements AtmosphereHandler {

    //action when connection is made to the backend

    @Override
    public void onRequest(AtmosphereResource atmosphereResource) throws IOException {

        AtmosphereRequest request = atmosphereResource.getRequest();
        AtmosphereResponse response = atmosphereResource.getResponse();

        System.out.println("Called:" + this.getClass().getName());
//        request.get
        RequestDispatcher reqDispatcher = request.getRequestDispatcher("/Index.html");
        try {
            reqDispatcher.forward(request, response);
        } catch (ServletException e) {
            e.printStackTrace();
        }
    }

    //called when Broadcaster broadcasts an event
    @Override
    public void onStateChange(AtmosphereResourceEvent atmosphereResourceEvent) throws IOException {

    }

    @Override
    public void destroy() {

    }
}

Join existing game using a game code is now working. Next...fix socket issues.


package peergos.shared.user.fs;

/** A Fragment is a part of an EncryptedChunk which is stored directly in IPFS in a raw format block
 *
 */
public class Fragment {
    public static final int MAX_LENGTH = 512*1024; // max size allowed by bitswap protocol is 1 MiB

    public final byte[] data;

    public Fragment(byte[] data) {
        if (MAX_LENGTH < data.length)
            throw new IllegalStateException("fragment size "+ data.length +" greater than max "+ MAX_LENGTH);
        this.data = data;
    }
}

package peergos.shared.user.fs;

/** A Fragment is a part of an EncryptedChunk which is stored directly in IPFS in a raw format block
 *
 */
public class Fragment {
    // max message size allowed by bitswap protocol is 2 MiB, and the block must fit within that
    public static final int MAX_LENGTH = 1024*1024;

    public final byte[] data;

    public Fragment(byte[] data) {
        if (MAX_LENGTH < data.length)
            throw new IllegalStateException("fragment size "+ data.length +" greater than max "+ MAX_LENGTH);
        this.data = data;
    }
}

Increase block size to 1 MiB


package org.commcare.android.tasks;

import org.commcare.android.tasks.ResourceEngineTask.ResourceEngineOutcomes;
import org.commcare.resources.model.UnresolvedResourceException;

public interface ResourceEngineListener {
    public void reportSuccess(boolean b);
    public void failMissingResource(UnresolvedResourceException ure, ResourceEngineOutcomes statusmissing);
    public void failBadReqs(int code, String vReq, String vAvail, boolean majorIsProblem);
    public void failUnknown(ResourceEngineOutcomes statusfailunknown);
    public void updateResourceProgress(int done, int pending, int phase);
    public void failWithNotification(ResourceEngineOutcomes statusfailstate);
}

package org.commcare.android.tasks;

import org.commcare.android.tasks.ResourceEngineTask.ResourceEngineOutcomes;
import org.commcare.resources.model.UnresolvedResourceException;

public interface ResourceEngineListener {
    void reportSuccess(boolean b);
    void failMissingResource(UnresolvedResourceException ure, ResourceEngineOutcomes statusmissing);
    void failBadReqs(int code, String vReq, String vAvail, boolean majorIsProblem);
    void failUnknown(ResourceEngineOutcomes statusfailunknown);
    void updateResourceProgress(int done, int pending, int phase);
    void failWithNotification(ResourceEngineOutcomes statusfailstate);
}

Remove redundant 'public' keyword from interface methods


package jasenmoloy.wirelesscontrol.mvp;

import android.app.Application;

import jasenmoloy.wirelesscontrol.io.OnGeofenceDataLoadFinishedListener;

/**
 * Created by jasenmoloy on 2/25/16.
 */
public interface MainPresenter extends Application.ActivityLifecycleCallbacks {
    int MAX_ALLOWABLE_GEOFENCES = 50;

    void onAllPermissionsGranted();
    boolean allowNewGeofence();
}

package jasenmoloy.wirelesscontrol.mvp;

import android.app.Application;

import jasenmoloy.wirelesscontrol.io.OnGeofenceDataLoadFinishedListener;

/**
 * Created by jasenmoloy on 2/25/16.
 */
public interface MainPresenter extends Application.ActivityLifecycleCallbacks {
    int MAX_ALLOWABLE_GEOFENCES = 25;

    void onAllPermissionsGranted();
    boolean allowNewGeofence();
}

Change max allowable geofences to 25 as the limit per device user is 100. This could cause issues for other applications if we go to high.


package net.dimensions;

public class Dimensions
{
    public static void init()
    {
        System.out.println("Initializing Dimensions...");
    }
}

package net.dimensions;

import java.util.Random;

public class Dimensions {

    private static Random rand;

    public static void init() {
        System.out.println("Initializing Dimensions...");
        rand = new Random();
    }

    public static Random getRandom(){
        return rand;
    }
}

Add Random instance into main class


package me.proxer.library.enums;

import com.squareup.moshi.Json;

/**
 * Enum holding the available synonym types.
 *
 * @author Ruben Gees
 */
public enum SynonymType {
    @Json(name = "name")ORIGINAL,
    @Json(name = "nameeng")ENGLISH,
    @Json(name = "nameger")GERMAN,
    @Json(name = "namejap")JAPANESE,
    @Json(name = "namekor")KOREAN,
    @Json(name = "syn")ORIGINAL_ALTERNATIVE,
}

package me.proxer.library.enums;

import com.squareup.moshi.Json;

/**
 * Enum holding the available synonym types.
 *
 * @author Ruben Gees
 */
public enum SynonymType {
    @Json(name = "name")ORIGINAL,
    @Json(name = "nameeng")ENGLISH,
    @Json(name = "nameger")GERMAN,
    @Json(name = "namejap")JAPANESE,
    @Json(name = "namekor")KOREAN,
    @Json(name = "namezhn")CHINESE,
    @Json(name = "syn")ORIGINAL_ALTERNATIVE,
}

Add support for chinese synonyms


package fi.csc.chipster.rest;

import java.io.IOException;

import javax.annotation.Priority;
import javax.ws.rs.Priorities;
import javax.ws.rs.container.ContainerRequestContext;
import javax.ws.rs.container.ContainerResponseContext;
import javax.ws.rs.container.ContainerResponseFilter;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.ext.Provider;

@Provider
@Priority(Priorities.HEADER_DECORATOR)
public class CORSResponseFilter implements ContainerResponseFilter {

	@Override
	public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext) throws IOException {

		MultivaluedMap<String, Object> headers = responseContext.getHeaders();

		//headers.add("Access-Control-Allow-Origin", "*");
		headers.add("Access-Control-Allow-Origin", requestContext.getHeaderString("origin"));
		headers.add("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT");
		headers.add("Access-Control-Allow-Headers", "authorization, content-type"); // request
		headers.add("Access-Control-Expose-Headers", "location"); // response
		headers.add("Access-Control-Allow-Credentials", "true");
		headers.add("Access-Control-Max-Age", "1728000"); // in seconds, 20 days
		//headers.add("Access-Control-Max-Age", "1"); // makes debugging easier
	}
}

package fi.csc.chipster.rest;

import java.io.IOException;

import javax.annotation.Priority;
import javax.ws.rs.Priorities;
import javax.ws.rs.container.ContainerRequestContext;
import javax.ws.rs.container.ContainerResponseContext;
import javax.ws.rs.container.ContainerResponseFilter;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.ext.Provider;

@Provider
@Priority(Priorities.HEADER_DECORATOR)
public class CORSResponseFilter implements ContainerResponseFilter {

	@Override
	public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext) throws IOException {

		MultivaluedMap<String, Object> headers = responseContext.getHeaders();

		//headers.add("Access-Control-Allow-Origin", "*");
		headers.add("Access-Control-Allow-Origin", requestContext.getHeaderString("origin"));
		headers.add("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT");
		headers.add("Access-Control-Allow-Headers", "authorization, content-type"); // request
		headers.add("Access-Control-Expose-Headers", "location, Accept-Ranges"); // response
		headers.add("Access-Control-Allow-Credentials", "true");
		headers.add("Access-Control-Max-Age", "1728000"); // in seconds, 20 days
		//headers.add("Access-Control-Max-Age", "1"); // makes debugging easier
	}
}

Allow browser to get accept-ranges header


package me.duncte123.skybot.utils;

import net.dv8tion.jda.core.events.message.MessageReceivedEvent;

import java.util.Arrays;

public class CommandParser {

    public CommandContainer parse(String rw, MessageReceivedEvent e){
        final String[] split = rw.substring(rw.indexOf(Config.prefix) + 1, rw.length()).split(" ");
        final String invoke = split[0];
        final String[] args = Arrays.copyOfRange(split, 1, split.length);

        return new CommandContainer(invoke, args, e);
    }

     public class CommandContainer {
         public final String invoke;
         public final String[] args;
         public final MessageReceivedEvent event;

         public CommandContainer(String invoke, String[] args, MessageReceivedEvent e){
             this.invoke = invoke;
             this.args = args;
             this.event = e;
         }
     }

}

package me.duncte123.skybot.utils;

import net.dv8tion.jda.core.events.message.MessageReceivedEvent;

import java.util.Arrays;

public class CommandParser {

    public CommandContainer parse(String rw, MessageReceivedEvent e){
        final String[] split = rw.substring(rw.indexOf(Config.prefix) + 1, rw.length()).split(" ");
        final String invoke = split[0].toLowerCase();
        final String[] args = Arrays.copyOfRange(split, 1, split.length);

        return new CommandContainer(invoke, args, e);
    }

     public class CommandContainer {
         public final String invoke;
         public final String[] args;
         public final MessageReceivedEvent event;

         public CommandContainer(String invoke, String[] args, MessageReceivedEvent e){
             this.invoke = invoke;
             this.args = args;
             this.event = e;
         }
     }

}

Make the called command to lowercase


import javax.swing.JFrame;
/*Author: Peter Chow
 *
 *
 * SudokuCapture will capture images from a webcam,
 * using still image capture from the video, another thread will approximate the bounds of the board
 * and try to scan in the values of the board for the program to use.
 * After a successful scan, the program will solve the board and display the answer using an overlay over the camera view
 *
 * */

public class SudokuCapture {

	public static void main (String args[]){
		init();
		CaptureWebcam webcam = new CaptureWebcam();
		webcam.display();
	}

	private static void init() {
		System.out.println("start");
		String answer = System.getProperty("sun.arch.data.model");
		if(answer.matches("64")){
			System.loadLibrary("./build/x64/opencv_java300");
		}else if(answer.matches("32")){
			System.loadLibrary("./build/x86/opencv_java300");
		}else{
			System.err.println("Your platform is not comptable");
			System.exit(0);
		}
	}

}

/*Author: Peter Chow
 *
 *
 * SudokuCapture will capture images from a webcam,
 * using still image capture from the video, another thread will approximate the bounds of the board
 * and try to scan in the values of the board for the program to use.
 * After a successful scan, the program will solve the board and display the answer using an overlay over the camera view
 *
 * */

public class SudokuCapture {

	public static void main (String args[]){
		init();
		CaptureWebcam webcam = new CaptureWebcam();
		webcam.display();
	}

	//Load up OpenCV lib by checking if the machine is 64-bit or 32-bit
	private static void init() {
		System.out.println("starting webcam capture");
		String answer = System.getProperty("sun.arch.data.model");
		if(answer.matches("64"))
		{
			System.loadLibrary("./build/x64/opencv_java300");
		}
		else if(answer.matches("32"))
		{
			System.loadLibrary("./build/x86/opencv_java300");
		}
		else
		{
			System.err.println("Your platform is not comptable");
			System.exit(0);
		}
	}

}

Refactor code and added new comments


package org.gem.log;

import org.apache.log4j.BasicConfigurator;
import org.apache.log4j.Logger;
import org.apache.log4j.PatternLayout;

import org.junit.Test;

import static org.junit.Assert.assertThat;

import static org.junit.matchers.JUnitMatchers.*;

import static org.hamcrest.CoreMatchers.*;

public class AMQPAppenderTest {
    private DummyChannel dummyChannel;
    private DummyAppender dummyAppender;
    private Logger logger = Logger.getLogger(AMQPAppenderTest.class);

    void tearDown() {
        dummyChannel = null;
        dummyAppender = null;

        // this closes the RabbitMQ connections
        BasicConfigurator.resetConfiguration();
    }

    private void setUpDummyAppender() {
        dummyAppender = new DummyAppender();
        dummyAppender.setLayout(new PatternLayout());

        BasicConfigurator.configure(dummyAppender);
    }

    @Test
    public void basicLogging() {
        setUpDummyAppender();

        logger.info("Test");

        dummyChannel = (DummyChannel) dummyAppender.getChannel();

        assertThat(dummyChannel.entries.size(), is(equalTo(1)));

        DummyChannel.Entry entry = dummyChannel.entries.get(0);

        assertThat(entry.exchange, is(equalTo("")));
        assertThat(entry.routingKey, is(equalTo("")));
        assertThat(entry.properties.getType(), is(equalTo("INFO")));
        assertThat(entry.body, is(equalTo("Test\n")));
    }
}

package org.gem.log;

import org.apache.log4j.BasicConfigurator;
import org.apache.log4j.Logger;
import org.apache.log4j.PatternLayout;

import org.junit.Test;

import static org.junit.Assert.assertThat;

import static org.junit.matchers.JUnitMatchers.*;

import static org.hamcrest.CoreMatchers.*;

public class AMQPAppenderTest {
    private DummyChannel dummyChannel;
    private DummyAppender dummyAppender;
    private Logger logger = Logger.getLogger(AMQPAppenderTest.class);

    void tearDown() {
        dummyChannel = null;
        dummyAppender = null;

        // this closes the RabbitMQ connections
        BasicConfigurator.resetConfiguration();
    }

    private void setUpDummyAppender() {
        dummyAppender = new DummyAppender();
        dummyAppender.setLayout(new PatternLayout());

        BasicConfigurator.configure(dummyAppender);
    }

    @Test
    public void basicLogging() {
        setUpDummyAppender();

        logger.info("Test1");
        logger.warn("Test2");

        dummyChannel = (DummyChannel) dummyAppender.getChannel();

        assertThat(dummyChannel.entries.size(), is(equalTo(2)));

        DummyChannel.Entry entry1 = dummyChannel.entries.get(0);

        assertThat(entry1.exchange, is(equalTo("")));
        assertThat(entry1.routingKey, is(equalTo("")));
        assertThat(entry1.properties.getType(), is(equalTo("INFO")));
        assertThat(entry1.body, is(equalTo("Test1\n")));

        DummyChannel.Entry entry2 = dummyChannel.entries.get(1);

        assertThat(entry2.exchange, is(equalTo("")));
        assertThat(entry2.routingKey, is(equalTo("")));
        assertThat(entry2.properties.getType(), is(equalTo("WARN")));
        assertThat(entry2.body, is(equalTo("Test2\n")));
    }
}

Test that .info() and .warn() set the correct event type.


package mezz.jei.plugins.vanilla.furnace;

import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.awt.Color;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;

import net.minecraft.client.Minecraft;
import net.minecraft.item.ItemStack;

import mezz.jei.plugins.vanilla.VanillaRecipeWrapper;
import mezz.jei.util.Translator;

public class FuelRecipe extends VanillaRecipeWrapper {
	@Nonnull
	private final List<ItemStack> input;
	@Nullable
	private final String burnTimeString;

	public FuelRecipe(@Nonnull Collection<ItemStack> input, int burnTime) {
		this.input = new ArrayList<>(input);
		this.burnTimeString = Translator.translateToLocalFormatted("gui.jei.furnaceBurnTime", burnTime);
	}

	@Nonnull
	@Override
	public List<ItemStack> getInputs() {
		return input;
	}

	@Nonnull
	@Override
	public List<ItemStack> getOutputs() {
		return Collections.emptyList();
	}

	@Override
	public void drawInfo(@Nonnull Minecraft minecraft, int recipeWidth, int recipeHeight) {
		minecraft.fontRendererObj.drawString(burnTimeString, 24, 12, Color.gray.getRGB());
	}
}

package mezz.jei.plugins.vanilla.furnace;

import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.awt.Color;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;

import net.minecraft.client.Minecraft;
import net.minecraft.item.ItemStack;

import mezz.jei.plugins.vanilla.VanillaRecipeWrapper;
import mezz.jei.util.Translator;

public class FuelRecipe extends VanillaRecipeWrapper {
	@Nonnull
	private final List<List<ItemStack>> inputs;
	@Nonnull
	private final String burnTimeString;

	public FuelRecipe(@Nonnull Collection<ItemStack> input, int burnTime) {
		this.inputs = Collections.singletonList(new ArrayList<>(input));
		this.burnTimeString = Translator.translateToLocalFormatted("gui.jei.furnaceBurnTime", burnTime);
	}

	@Nonnull
	@Override
	public List<List<ItemStack>> getInputs() {
		return inputs;
	}

	@Nonnull
	@Override
	public List<ItemStack> getOutputs() {
		return Collections.emptyList();
	}

	@Override
	public void drawInfo(@Nonnull Minecraft minecraft, int recipeWidth, int recipeHeight) {
		minecraft.fontRendererObj.drawString(burnTimeString, 24, 12, Color.gray.getRGB());
	}
}

Fix fuel recipe transfer helper


/*-------------------------------------------------------------------------
*
* Copyright (c) 2004-2005, PostgreSQL Global Development Group
*
* IDENTIFICATION
*   $PostgreSQL: pgjdbc/org/postgresql/util/PSQLDriverVersion.java,v 1.21 2006/12/01 12:06:21 jurka Exp $
*
*-------------------------------------------------------------------------
*/
package org.postgresql.util;

import org.postgresql.Driver;

/**
 * This class holds the current build number and a utility program to print
 * it and the file it came from.  The primary purpose of this is to keep
 * from filling the cvs history of Driver.java.in with commits simply
 * changing the build number.  The utility program can also be helpful for
 * people to determine what version they really have and resolve problems
 * with old and unknown versions located somewhere in the classpath.
 */
public class PSQLDriverVersion {

    public final static int buildNumber = 601;

    public static void main(String args[]) {
        java.net.URL url = Driver.class.getResource("/org/postgresql/Driver.class");
        System.out.println(Driver.getVersion());
        System.out.println("Found in: " + url);
    }

}

/*-------------------------------------------------------------------------
*
* Copyright (c) 2004-2005, PostgreSQL Global Development Group
*
* IDENTIFICATION
*   $PostgreSQL: pgjdbc/org/postgresql/util/PSQLDriverVersion.java,v 1.22 2007/07/31 06:05:43 jurka Exp $
*
*-------------------------------------------------------------------------
*/
package org.postgresql.util;

import org.postgresql.Driver;

/**
 * This class holds the current build number and a utility program to print
 * it and the file it came from.  The primary purpose of this is to keep
 * from filling the cvs history of Driver.java.in with commits simply
 * changing the build number.  The utility program can also be helpful for
 * people to determine what version they really have and resolve problems
 * with old and unknown versions located somewhere in the classpath.
 */
public class PSQLDriverVersion {

    public final static int buildNumber = 602;

    public static void main(String args[]) {
        java.net.URL url = Driver.class.getResource("/org/postgresql/Driver.class");
        System.out.println(Driver.getVersion());
        System.out.println("Found in: " + url);
    }

}

Prepare for release of 8.3dev-602.


/*
 * 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 tw.edu.npu.mis;

/**
 * The model class of the calculator application.
 */
public class Calculator {

    /**
     * The available operators of the calculator.
     */
    public enum Operator {
        CLEAR,       // C
        CLEAR_ENTRY, // CE
        BACKSPACE,   // ⌫
        EQUAL,       // =
        PLUS,        // +
        MINUS,       // -
        TIMES,       // ×
        OVER,        // ⁄
        PLUS_MINUS,  // ±
        RECIPROCAL,  // 1/x
        PERCENT,     // %
        SQRT,        // √
        MEM_CLEAR,   // MC
        MEM_SET,     // MS
        MEM_PLUS,    // M+
        MEM_MINUS,   // M-
        MEM_RECALL   // MR
    }

    public void appendDigit(int digit) {
        // TODO code application logic here
    }

    public void appendDot() {
        // TODO code application logic here
    }

    public void performOperation(Operator operator) {
        // TODO code application logic here
    }

    public String getDisplay() {
        // TODO code application logic here
        return null;
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // TODO code application logic here
    }

}

/*
 * 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 tw.edu.npu.mis;

/**
 * The model class of the calculator application.
 */
public class Calculator {

    /**
     * The available operators of the calculator.
     */
    public enum Operator {
        EQUAL,       // =
        PLUS,        // +
        MINUS,       // -
        TIMES,       // ×
        OVER,        // ⁄
        PLUS_MINUS,  // ±
        RECIPROCAL,  // 1/x
        PERCENT,     // %
        SQRT,        // √
        BACKSPACE,   // ⌫
        CLEAR,       // C
        CLEAR_ENTRY, // CE
        MEM_SET,     // MS
        MEM_PLUS,    // M+
        MEM_MINUS,   // M-
        MEM_RECALL,  // MR
        MEM_CLEAR    // MC
    }

    public void appendDigit(int digit) {
        // TODO code application logic here
    }

    public void appendDot() {
        // TODO code application logic here
    }

    public void performOperation(Operator operator) {
        // TODO code application logic here
    }

    public String getDisplay() {
        // TODO code application logic here
        return null;
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // TODO code application logic here
    }

}

Revert "Revert "Revert "Reorder operator"""


package devopsdistilled.operp.client;

import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

import devopsdistilled.operp.client.context.AppContext;
import devopsdistilled.operp.client.main.MainWindow;

public class ClientApp {
	public static void main(String[] args) {
		ApplicationContext context = new AnnotationConfigApplicationContext(
				AppContext.class);

		MainWindow window = context.getBean(MainWindow.class);
		window.init();

		System.out.println(context);
	}
}

package devopsdistilled.operp.client;

import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

import devopsdistilled.operp.client.context.AppContext;
import devopsdistilled.operp.client.main.MainWindow;

public class ClientApp {

	private static ApplicationContext context;

	public static ApplicationContext getApplicationContext() {
		return context;
	}

	public static void main(String[] args) {
		context = new AnnotationConfigApplicationContext(AppContext.class);

		MainWindow window = context.getBean(MainWindow.class);
		window.init();

		System.out.println(context);
	}
}

Create static instance of ApplicationContext for global reference


package org.graphstream.gama.extension;

import msi.gama.common.interfaces.IKeyword;

public class IKeywordGSAdditional implements IKeyword {
	// New commands

	public static final String ADD = "gs_add";
	public static final String ADD_ATTRIBUTE = "gs_add_attribute";
	public static final String ADD_SENDER = "gs_add_sender";
	public static final String CLEAR = "gs_clear";
	public static final String CLEAR_SENDERS = "gs_clear_senders";
	public static final String REMOVE = "gs_remove";
	public static final String REMOVE_ATTRIBUTE = "gs_remove_attribute";
	public static final String STEP = "gs_step";

	// Facets associated to a command

	public static final String SENDERID = "gs_sender_id";
}

package org.graphstream.gama.extension;

import msi.gama.common.interfaces.IKeyword;

public class IKeywordGSAdditional implements IKeyword {
	// New commands

	public static final String ADD = "gs_add";
	public static final String ADD_ATTRIBUTE = "gs_add_attribute";
	public static final String ADD_SENDER = "gs_add_sender";
	public static final String CLEAR = "gs_clear";
	public static final String CLEAR_SENDERS = "gs_clear_senders";
	public static final String REMOVE = "gs_remove";
	public static final String REMOVE_ATTRIBUTE = "gs_remove_attribute";
	public static final String STEP = "gs_step";

	// Facets associated to a command

	public static final String SENDERID = "gs_sender_id";
	public static final String STEP_NUMBER = "gs_step_number";

}

Add new facet for 'step' command


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

package org.chromium.sdk;

import java.io.IOException;

import org.chromium.sdk.util.MethodIsBlockingException;

/**
 * Abstraction of a remote JavaScript virtual machine which is embedded into
 * some application and accessed via TCP/IP connection to a port opened by
 * DebuggerAgent. Clients can use it to conduct debugging process.
 */
public interface StandaloneVm extends JavascriptVm {
  /**
   * Connects to the target VM.
   *
   * @param listener to report the debug events to
   * @throws IOException if there was a transport layer error
   * @throws UnsupportedVersionException if the SDK protocol version is not
   *         compatible with that supported by the browser
     * @throws MethodIsBlockingException because initialization implies couple of remote calls
     *     (to request version etc)
   */
  void attach(DebugEventListener listener)
      throws IOException, UnsupportedVersionException, MethodIsBlockingException;

  /**
   * @return name of embedding application as it wished to name itself; might be null
   */
  String getEmbedderName();

  /**
   * @return version of V8 implementation, format is unspecified; must not be null if
   *         {@link StandaloneVm} has been attached
   */
  // TODO: align this with {@link JavascriptVm#getVersion()} method.
  String getVmVersion();

  /**
   * @return message explaining why VM is detached; may be null
   */
  String getDisconnectReason();
}

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

package org.chromium.sdk;

import java.io.IOException;

import org.chromium.sdk.util.MethodIsBlockingException;

/**
 * Abstraction of a remote JavaScript virtual machine which is embedded into
 * some application and accessed via TCP/IP connection to a port opened by
 * DebuggerAgent. Clients can use it to conduct debugging process.
 */
public interface StandaloneVm extends JavascriptVm {
  /**
   * Connects to the target VM.
   *
   * @param listener to report the debug events to
   * @throws IOException if there was a transport layer error
   * @throws UnsupportedVersionException if the SDK protocol version is not
   *         compatible with that supported by the browser
     * @throws MethodIsBlockingException because initialization implies couple of remote calls
     *     (to request version etc)
   */
  void attach(DebugEventListener listener)
      throws IOException, UnsupportedVersionException, MethodIsBlockingException;

  /**
   * @return name of embedding application as it wished to name itself; might be null
   */
  String getEmbedderName();

  /**
   * This version should correspond to {@link JavascriptVm#getVersion()}. However it gets available
   * earlier, at the transport handshake stage.
   * @return version of V8 implementation, format is unspecified; must not be null if
   *         {@link StandaloneVm} has been attached
   */
  String getVmVersion();

  /**
   * @return message explaining why VM is detached; may be null
   */
  String getDisconnectReason();
}

Drop TODO for getVmVersion method


package com.nostra13.universalimageloader.cache;

import java.lang.ref.Reference;
import java.lang.ref.SoftReference;

import android.graphics.Bitmap;

/**
 * Image cache limited by size. Contains Bitmaps.<br />
 * Not thread-safe.
 *
 * @author Sergey Tarasevich (nostra13[at]gmail[dot]com)
 */
public class ImageCache extends LimitedCache<String, Bitmap> {

	private int sizeLimit;

	public ImageCache(int sizeLimit) {
		this.sizeLimit = sizeLimit;
	}

	@Override
	protected int getSize(Bitmap value) {
		return value.getRowBytes() * value.getHeight();
	}

	@Override
	protected int getSizeLimit() {
		return sizeLimit;
	}

	@Override
	protected Reference<Bitmap> createReference(Bitmap value) {
		return new SoftReference<Bitmap>(value);
	}
}

package com.nostra13.universalimageloader.cache;

import java.lang.ref.Reference;
import java.lang.ref.WeakReference;

import android.graphics.Bitmap;

/**
 * Image cache limited by size. Contains Bitmaps.<br />
 * Not thread-safe.
 *
 * @author Sergey Tarasevich (nostra13[at]gmail[dot]com)
 */
public class ImageCache extends LimitedCache<String, Bitmap> {

	private int sizeLimit;

	public ImageCache(int sizeLimit) {
		this.sizeLimit = sizeLimit;
	}

	@Override
	protected int getSize(Bitmap value) {
		return value.getRowBytes() * value.getHeight();
	}

	@Override
	protected int getSizeLimit() {
		return sizeLimit;
	}

	@Override
	protected Reference<Bitmap> createReference(Bitmap value) {
		return new WeakReference<Bitmap>(value);
	}
}

Return mistakenly replaced weak reference


package com.tom_e_white.chickenalerts;

import android.app.Notification;
import android.app.NotificationManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.media.MediaPlayer;

public class ChickenAlertReceiver extends BroadcastReceiver {
	@Override
	public void onReceive(Context context, Intent intent) {
		Notification notification = new Notification.Builder(context)
				.setContentTitle("Chicken Alert")
				.setContentText("Have you put the chickens to bed?")
				.setTicker("Have you put the chickens to bed?")
				.setSmallIcon(R.drawable.ic_launcher).build();
		notification.flags |= Notification.FLAG_AUTO_CANCEL;
		NotificationManager notificationManager = (NotificationManager) context
				.getSystemService(Context.NOTIFICATION_SERVICE);
		notificationManager.notify(0, notification);

		MediaPlayer mediaPlayer = MediaPlayer.create(context, R.raw.cluck);
		mediaPlayer.start(); // no need to call prepare(); create() does that for you
	}

}

package com.tom_e_white.chickenalerts;

import android.app.Notification;
import android.app.NotificationManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;

public class ChickenAlertReceiver extends BroadcastReceiver {
	@Override
	public void onReceive(Context context, Intent intent) {
		Notification notification = new Notification.Builder(context)
				.setContentTitle("Chicken Alert")
				.setContentText("Have you put the chickens to bed?")
				.setTicker("Have you put the chickens to bed?")
				.setSmallIcon(R.drawable.ic_launcher).build();
		notification.flags |= Notification.FLAG_AUTO_CANCEL;
		NotificationManager notificationManager = (NotificationManager) context
				.getSystemService(Context.NOTIFICATION_SERVICE);
		notificationManager.notify(0, notification);

		MediaPlayer mediaPlayer = MediaPlayer.create(context, R.raw.cluck);
		mediaPlayer.start();
		mediaPlayer.setOnCompletionListener(new OnCompletionListener() {
	        @Override
	        public void onCompletion(MediaPlayer mp) {
	            mp.release();
	        }
	    });
	}

}

Stop media player after sound.


package com.github.xetorthio.jedisque;

import java.net.URI;
import java.net.URISyntaxException;

import org.junit.Test;

import redis.clients.jedis.exceptions.JedisConnectionException;

public class ConnectionTest {
	@Test
	public void iterateOverHosts() throws URISyntaxException {
		try (Jedisque q = new Jedisque(new URI("disque://localhost:55665"),
				new URI("disque://localhost:7711"))) {
			q.info();
		}
	}

	@Test(expected = JedisConnectionException.class)
	public void throwExceptionWhenNodesAreUnavailbale()
			throws URISyntaxException {
		try (Jedisque q = new Jedisque(new URI("disque://localhost:55665"),
				new URI("disque://localhost:55666"))) {
			q.info();
		}
	}
}

package com.github.xetorthio.jedisque;

import java.net.URI;
import java.net.URISyntaxException;

import org.junit.Test;

import redis.clients.jedis.exceptions.JedisConnectionException;

public class ConnectionTest {

	@Test
	public void iterateOverHosts() throws URISyntaxException {
		Jedisque q = new Jedisque(new URI("disque://localhost:55665"), new URI("disque://localhost:7711"));
		q.info();
		q.close();

	}

	@Test(expected = JedisConnectionException.class)
	public void throwExceptionWhenNodesAreUnavailbale() throws URISyntaxException {
		Jedisque q = new Jedisque(new URI("disque://localhost:55665"), new URI("disque://localhost:55666"));
		q.info();
		q.close();
	}
}

Change test strategy in favor of simple testing Update project source to 1.6


package xyz.pushpad;

import javax.crypto.spec.SecretKeySpec;
import javax.crypto.Mac;
import java.security.SignatureException;
import java.security.NoSuchAlgorithmException;
import java.security.InvalidKeyException;
import javax.xml.bind.DatatypeConverter;

public class Pushpad {
  public String authToken;
  public String projectId;

  public Pushpad(String authToken, String projectId) {
    this.authToken = authToken;
    this.projectId = projectId;
  }

  public String signatureFor(String data) {
    SecretKeySpec signingKey = new SecretKeySpec(this.authToken.getBytes(), "HmacSHA1");
    String encoded = null;
    try {
      Mac mac = Mac.getInstance("HmacSHA1");
      mac.init(signingKey);
      byte[] rawHmac = mac.doFinal(data.getBytes());
      encoded = DatatypeConverter.printHexBinary(rawHmac);
    } catch (NoSuchAlgorithmException | InvalidKeyException e) {
      e.printStackTrace();
    }

    return encoded;
  }

  public String path() {
    return "https://pushpad.xyz/projects/" + this.projectId + "/subscription/edit";
  }

  public String pathFor(String uid) {
    String uidSignature = this.signatureFor(uid);
    return this.path() + "?uid=" + uid + "&uid_signature=" + uidSignature;
  }

  public Notification buildNotification(String title, String body, String targetUrl) {
    return new Notification(this, title, body, targetUrl);
  }
}

package xyz.pushpad;

import javax.crypto.spec.SecretKeySpec;
import javax.crypto.Mac;
import java.security.SignatureException;
import java.security.NoSuchAlgorithmException;
import java.security.InvalidKeyException;
import javax.xml.bind.DatatypeConverter;

public class Pushpad {
  public String authToken;
  public String projectId;

  public Pushpad(String authToken, String projectId) {
    this.authToken = authToken;
    this.projectId = projectId;
  }

  public String signatureFor(String data) {
    SecretKeySpec signingKey = new SecretKeySpec(this.authToken.getBytes(), "HmacSHA1");
    String encoded = null;
    try {
      Mac mac = Mac.getInstance("HmacSHA1");
      mac.init(signingKey);
      byte[] rawHmac = mac.doFinal(data.getBytes());
      encoded = DatatypeConverter.printHexBinary(rawHmac).toLowerCase();
    } catch (NoSuchAlgorithmException | InvalidKeyException e) {
      e.printStackTrace();
    }

    return encoded;
  }

  public String path() {
    return "https://pushpad.xyz/projects/" + this.projectId + "/subscription/edit";
  }

  public String pathFor(String uid) {
    String uidSignature = this.signatureFor(uid);
    return this.path() + "?uid=" + uid + "&uid_signature=" + uidSignature;
  }

  public Notification buildNotification(String title, String body, String targetUrl) {
    return new Notification(this, title, body, targetUrl);
  }
}

Convert HMAC-SHA1 signatures to lower case


package org.blaazinsoftware.centaur.service;

import com.google.appengine.api.search.Cursor;
import com.google.appengine.api.search.OperationResult;
import com.google.appengine.api.search.checkers.Preconditions;

import java.io.Serializable;
import java.util.Collection;
import java.util.Collections;

/**
 * @author Randy May
 *         Date: 15-04-09
 */
public class SearchResults <T> implements Serializable {

    private final OperationResult operationResult;
    private final Collection<T> results;
    private final long numberFound;
    private final int numberReturned;
    private final Cursor cursor;

    protected SearchResults(OperationResult operationResult, Collection<T> results, long numberFound, int numberReturned, Cursor cursor) {
        this.operationResult = (OperationResult) Preconditions.checkNotNull(operationResult, "operation result cannot be null");
        this.results = Collections.unmodifiableCollection((Collection) Preconditions.checkNotNull(results, "search results cannot be null"));
        this.numberFound = numberFound;
        this.numberReturned = numberReturned;
        this.cursor = cursor;
    }

    public OperationResult getOperationResult() {
        return operationResult;
    }

    public Collection<T> getResults() {
        return results;
    }

    public long getNumberFound() {
        return numberFound;
    }

    public int getNumberReturned() {
        return numberReturned;
    }

    public Cursor getCursor() {
        return cursor;
    }
}

package org.blaazinsoftware.centaur.service;

import com.google.appengine.api.search.Cursor;
import com.google.appengine.api.search.OperationResult;

import java.io.Serializable;
import java.util.Collection;

/**
 * @author Randy May
 *         Date: 15-04-09
 */
public class SearchResults <T> implements Serializable {

    private final OperationResult operationResult;
    private final Collection<T> results;
    private final long numberFound;
    private final int numberReturned;
    private final Cursor cursor;

    protected SearchResults(OperationResult operationResult, Collection<T> results, long numberFound, int numberReturned, Cursor cursor) {
        if (null == operationResult) {
            throw new NullPointerException("Operation Result cannot be null");
        }
        this.operationResult = operationResult;
        if (null == results) {
            throw new NullPointerException("Search Results cannot be null");
        }
        this.results = results;
        this.numberFound = numberFound;
        this.numberReturned = numberReturned;
        this.cursor = cursor;
    }

    public OperationResult getOperationResult() {
        return operationResult;
    }

    public Collection<T> getResults() {
        return results;
    }

    public long getNumberFound() {
        return numberFound;
    }

    public int getNumberReturned() {
        return numberReturned;
    }

    public Cursor getCursor() {
        return cursor;
    }
}

Remove usage of unsupported Class.


package edu.stuy.commands;

import edu.stuy.Robot;
import edu.wpi.first.wpilibj.command.Command;

/**
 *
 */
public class LiftControlCommand extends Command {

    public LiftControlCommand() {
        // Use requires() here to declare subsystem dependencies
        // eg. requires(chassis);
        requires(Robot.lift);
    }

    // Called just before this Command runs the first time
    protected void initialize() {
    }

    // Called repeatedly when this Command is scheduled to run
    protected void execute() {
        double input = squareInput(Robot.oi.operatorPad.getRightY());
        Robot.lift.manualControl(-input);
    }

    // Square the value of the input while preserving its sign
    private double squareInput(double input) {
        boolean negative = input < 0;
        input = input * input;
        if (negative) {
            input = -input;
        }
        return input;
    }

    // Make this return true when this Command no longer needs to run execute()
    protected boolean isFinished() {
        // This is the Lift's default command.
        return false;
    }

    // Called once after isFinished returns true
    protected void end() {
    }

    // Called when another command which requires one or more of the same
    // subsystems is scheduled to run
    protected void interrupted() {
    }
}

package edu.stuy.commands;

import edu.stuy.Robot;
import edu.wpi.first.wpilibj.command.Command;

/**
 *
 */
public class LiftControlCommand extends Command {

    public LiftControlCommand() {
        // Use requires() here to declare subsystem dependencies
        // eg. requires(chassis);
        requires(Robot.lift);
    }

    // Called just before this Command runs the first time
    protected void initialize() {
    }

    // Called repeatedly when this Command is scheduled to run
    protected void execute() {
        double input = squareInput(Robot.oi.operatorPad.getRightY()) * 0.75;
        Robot.lift.manualControl(-input);
    }

    // Square the value of the input while preserving its sign
    private double squareInput(double input) {
        boolean negative = input < 0;
        input = input * input;
        if (negative) {
            input = -input;
        }
        return input;
    }

    // Make this return true when this Command no longer needs to run execute()
    protected boolean isFinished() {
        // This is the Lift's default command.
        return false;
    }

    // Called once after isFinished returns true
    protected void end() {
    }

    // Called when another command which requires one or more of the same
    // subsystems is scheduled to run
    protected void interrupted() {
    }
}

Make lift manual control 75% speed


package org.jongo;

import org.bson.types.ObjectId;
import org.jongo.model.Friend;
import org.jongo.util.JongoTestCase;
import org.jongo.util.MongoInMemoryRule;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;

import java.util.Iterator;

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

public class FindWithHintTest extends JongoTestCase {

    @Rule
    public static final MongoInMemoryRule mongo = new MongoInMemoryRule();

    private MongoCollection collection;

    @Before
    public void setUp() throws Exception {
        collection = createEmptyCollection("friends");
    }

    @After
    public void tearDown() throws Exception {
        dropCollection("friends");
    }

    @Test
    public void canFindWithHint() throws Exception {
        /* given */
        Friend noName = new Friend(new ObjectId(), null);
        collection.save(noName);

        collection.ensureIndex("{name: 1}", "{sparse: true}");

        /* when */
        // force to use _id index instead of name index which is sparsed
        Iterator<Friend> friends = collection.find().hint("{$natural: 1}").sort("{name: 1}").as(Friend.class).iterator();

        /* then */
        assertThat(friends.hasNext()).isTrue();
    }

}

package org.jongo;

import org.bson.types.ObjectId;
import org.jongo.model.Friend;
import org.jongo.util.JongoTestCase;
import org.jongo.util.MongoInMemoryRule;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;

import java.util.Iterator;

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

public class FindWithHintTest extends JongoTestCase {

    private MongoCollection collection;

    @Before
    public void setUp() throws Exception {
        collection = createEmptyCollection("friends");
    }

    @After
    public void tearDown() throws Exception {
        dropCollection("friends");
    }

    @Test
    public void canFindWithHint() throws Exception {
        /* given */
        Friend noName = new Friend(new ObjectId(), null);
        collection.save(noName);

        collection.ensureIndex("{name: 1}", "{sparse: true}");

        /* when */
        // force to use _id index instead of name index which is sparsed
        Iterator<Friend> friends = collection.find().hint("{$natural: 1}").sort("{name: 1}").as(Friend.class).iterator();

        /* then */
        assertThat(friends.hasNext()).isTrue();
    }

}

Remove in memory mongodb When running tests, it use the same port than real mongodb so it cause some tests issues if a read mongodb is running.


package fr.insee.pogues.transforms;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.nio.charset.StandardCharsets;
import java.util.Map;

@Service
public class StromaeServiceImpl implements StromaeService {

    @Autowired
    Environment env;

    @Autowired
    HttpClient httpClient;

    private String serviceUri;

    @PostConstruct
    public void setUp(){
        serviceUri = env.getProperty("fr.insee.pogues.api.remote.stromae.vis.url");
    }

    @Override
    public String transform(String input, Map<String, Object> params) throws Exception {
        try {
            String uri = String.format("%s/%s", serviceUri,
                    params.get("name"));
            HttpPost post = new HttpPost(uri);
            post.setEntity(new StringEntity(input, StandardCharsets.UTF_8));
            post.setHeader("Content-type", "application/xml");
            HttpResponse response = httpClient.execute(post);
            return EntityUtils.toString(response.getEntity());
        } catch(Exception e) {
            throw e;
        }

    }
}

package fr.insee.pogues.transforms;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.nio.charset.StandardCharsets;
import java.util.Map;

@Service
public class StromaeServiceImpl implements StromaeService {

    @Autowired
    HttpClient httpClient;

    @Value("${fr.insee.pogues.api.remote.stromae.vis.url}")
    private String serviceUri;

    @Override
    public String transform(String input, Map<String, Object> params) throws Exception {
        try {
            String uri = String.format("%s/%s", serviceUri,
                    params.get("name"));
            HttpPost post = new HttpPost(uri);
            post.setEntity(new StringEntity(input, StandardCharsets.UTF_8));
            post.setHeader("Content-type", "application/xml");
            HttpResponse response = httpClient.execute(post);
            return EntityUtils.toString(response.getEntity());
        } catch(Exception e) {
            throw e;
        }

    }
}

Use value declarations instead of env injection


package hu.webarticum.treeprinter.printer;

import hu.webarticum.treeprinter.TreeNode;
import hu.webarticum.treeprinter.printer.listing.ListingTreePrinter;

/**
 * Main interface for tree printers.
 *
 * A tree printer visualize a {@link TreeNode} and its entire subtree structure.
 * Any implementation can have its own way to do this.
 * Some implementations (e. g. {@link ListingTreePrinter}) can print
 * large data in a memory efficient way via
 * print(TreeNode) or print(TreeNode, Appendable).
 */
@FunctionalInterface
public interface TreePrinter {

    public void print(TreeNode rootNode, Appendable out);

    public default void print(TreeNode rootNode) {
        print(rootNode, System.out);
    }

    public default String stringify(TreeNode rootNode) {
        StringBuilder builder = new StringBuilder();
        print(rootNode, builder);
        return builder.toString();
    }

}

Fix invalid html in a doc comment


package info.u_team.u_team_test.item;

import info.u_team.u_team_core.item.UItem;
import info.u_team.u_team_test.init.TestItemGroups;
import net.minecraft.item.*;
import net.minecraft.potion.*;
import net.minecraftforge.api.distmarker.*;

public class BasicFoodItem extends UItem {

	private static final Food FOOD = (new Food.Builder()).hunger(4).saturation(1.2F).effect(() -> new EffectInstance(Effects.GLOWING, 200, 0), 1).setAlwaysEdible().fastToEat().build();

	public BasicFoodItem(String name) {
		super(name, TestItemGroups.GROUP, new Properties().rarity(Rarity.RARE).food(FOOD));
	}

	@OnlyIn(Dist.CLIENT)
	@Override
	public boolean hasEffect(ItemStack stack) {
		return true;
	}
}

package info.u_team.u_team_test.item;

import info.u_team.u_team_core.item.UItem;
import info.u_team.u_team_test.init.TestItemGroups;
import net.minecraft.item.*;
import net.minecraft.potion.*;
import net.minecraftforge.api.distmarker.*;

public class BasicFoodItem extends UItem {

	private static final Food FOOD = (new Food.Builder()).hunger(4).saturation(1.2F).effect(() -> new EffectInstance(Effects.GLOWING, 200, 0), 1).setAlwaysEdible().fastToEat().build();

	public BasicFoodItem() {
		super(TestItemGroups.GROUP, new Properties().rarity(Rarity.RARE).food(FOOD));
	}

	@OnlyIn(Dist.CLIENT)
	@Override
	public boolean hasEffect(ItemStack stack) {
		return true;
	}
}

Remove string name ctor from basic food item


package uk.ac.ebi.atlas.tsne;

import com.google.common.collect.ImmutableMap;

import javax.inject.Inject;
import javax.inject.Named;
import java.util.concurrent.ThreadLocalRandom;
import java.util.stream.Collectors;

@Named
public class GeneExpressionDao {

    private final TSnePlotDao tSnePlotDao;

    @Inject
    public GeneExpressionDao(TSnePlotDao tSnePlotDao) {
        this.tSnePlotDao = tSnePlotDao;
    }

    public ImmutableMap<String, Double> fetchGeneExpression(String experimentAccession, String geneId) {
        return ImmutableMap.copyOf(
                tSnePlotDao.fetchTSnePlotPoints(experimentAccession)
                        .values().stream()
                        .collect(
                                Collectors.toMap(
                                        TSnePoint::name, p -> ThreadLocalRandom.current().nextDouble(0.0, 10000.0))));
    }
}

package uk.ac.ebi.atlas.tsne;

import com.google.common.collect.ImmutableMap;

import javax.inject.Inject;
import javax.inject.Named;
import java.util.concurrent.ThreadLocalRandom;
import java.util.stream.Collectors;

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

@Named
public class GeneExpressionDao {

    private final TSnePlotDao tSnePlotDao;

    @Inject
    public GeneExpressionDao(TSnePlotDao tSnePlotDao) {
        this.tSnePlotDao = tSnePlotDao;
    }

    public ImmutableMap<String, Double> fetchGeneExpression(String experimentAccession, String geneId) {
        return ImmutableMap.copyOf(
                tSnePlotDao.fetchTSnePlotPoints(experimentAccession)
                        .values().stream()
                        .collect(
                                Collectors.toMap(
                                        TSnePoint::name,
                                        p -> isBlank(geneId) ?
                                                0.0 : ThreadLocalRandom.current().nextDouble(0.0, 10000.0))));
    }
}

Return 0 expression level if gene ID is blank


package com.bugsnag.android;

import org.json.JSONObject;

import com.bugsnag.android.DeviceData;

public class DeviceDataTest extends BugsnagTestCase {
    public void testSaneValues() {
        DeviceData deviceData = new DeviceData(getContext());

        assertTrue(deviceData.getScreenDensity() > 0);
        assertNotNull(deviceData.getScreenResolution());
        assertNotNull(deviceData.getTotalMemory());
        assertNotNull(deviceData.isRooted());
        assertNotNull(deviceData.getLocale());
        assertNotNull(deviceData.getAndroidId());
    }
}

package com.bugsnag.android;

import org.json.JSONObject;

import com.bugsnag.android.DeviceData;

public class DeviceDataTest extends BugsnagTestCase {
    public void testSaneValues() {
        DeviceData deviceData = new DeviceData(getContext());

        assertTrue(deviceData.getScreenDensity() > 0);
        assertNotNull(deviceData.getScreenResolution());
        assertNotNull(deviceData.getTotalMemory());
        assertNotNull(deviceData.isRooted());
        assertNotNull(deviceData.getLocale());

        if(android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.FROYO) {
            // Emulators returned null for android id before android 2.2
            assertNotNull(deviceData.getAndroidId());
        }
    }
}

Handle emulator bug in tests


package com.biotronisis.pettplant.debug;

public class MyDebug {
    public static final boolean LOG = true;
}

package com.biotronisis.pettplant.debug;

public class MyDebug {
    public static final boolean LOG = false;
}

Change value of debug flag.