package org.openhds.webservice;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.IOUtils;

public class CacheResponseWriter {

    public static void writeResponse(File fileToWrite, HttpServletResponse response) throws IOException {
        if (!fileToWrite.exists()) {
            response.setStatus(HttpServletResponse.SC_NOT_FOUND);
        }

        response.setStatus(HttpServletResponse.SC_OK);

        InputStream is = null;
        try {
            is = new BufferedInputStream(new FileInputStream(fileToWrite));
            IOUtils.copy(is, response.getOutputStream());
        } finally {
            if (is != null) {
                IOUtils.closeQuietly(is);
            }
        }
    }
}

package org.openhds.webservice;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.IOUtils;

public class CacheResponseWriter {

    public static void writeResponse(File fileToWrite, HttpServletResponse response) throws IOException {
        if (!fileToWrite.exists()) {
            response.setStatus(HttpServletResponse.SC_NOT_FOUND);
        }
        else{
        	response.setStatus(HttpServletResponse.SC_OK);

	        InputStream is = null;
	        try {
	            is = new BufferedInputStream(new FileInputStream(fileToWrite));
	            IOUtils.copy(is, response.getOutputStream());
	        } finally {
	            if (is != null) {
	                IOUtils.closeQuietly(is);
	            }
	        }
        }
    }
}

Write Http-ErrorCode 404 if cached xml file for task does not exist


package info.u_team.u_team_core.api.sync;

import java.util.function.*;

import net.minecraft.network.PacketBuffer;

public abstract class BufferReferenceHolder {

	private PacketBuffer lastKnownValue;

	public abstract PacketBuffer get();

	public abstract void set(PacketBuffer buffer);

	public boolean isDirty() {
		final PacketBuffer buffer = get();
		final boolean dirty = !buffer.equals(lastKnownValue);
		lastKnownValue = buffer;
		return dirty;
	}

	public static final BufferReferenceHolder create(Supplier<PacketBuffer> get, Consumer<PacketBuffer> set) {
		return new BufferReferenceHolder() {

			@Override
			public PacketBuffer get() {
				return get.get();
			}

			@Override
			public void set(PacketBuffer buffer) {
				set.accept(buffer);
			}
		};
	}

}

package info.u_team.u_team_core.api.sync;

import java.util.function.*;

import io.netty.buffer.Unpooled;
import net.minecraft.network.PacketBuffer;

public abstract class BufferReferenceHolder {

	private PacketBuffer lastKnownValue;

	public abstract PacketBuffer get();

	public abstract void set(PacketBuffer buffer);

	public boolean isDirty() {
		final PacketBuffer buffer = get();
		final boolean dirty = !buffer.equals(lastKnownValue);
		lastKnownValue = buffer;
		return dirty;
	}

	public static final BufferReferenceHolder createHolder(Supplier<PacketBuffer> get, Consumer<PacketBuffer> set) {
		return new BufferReferenceHolder() {

			@Override
			public PacketBuffer get() {
				return get.get();
			}

			@Override
			public void set(PacketBuffer buffer) {
				set.accept(buffer);
			}
		};
	}

	public static final BufferReferenceHolder createIntHolder(IntSupplier get, IntConsumer set) {
		return new BufferReferenceHolder() {

			@Override
			public PacketBuffer get() {
				return new PacketBuffer(Unpooled.copyInt(get.getAsInt()));
			}

			@Override
			public void set(PacketBuffer buffer) {
				set.accept(buffer.readInt());
			}
		};
	}

	public static final BufferReferenceHolder createShortHolder(Supplier<Short> get, Consumer<Short> set) {
		return new BufferReferenceHolder() {

			@Override
			public PacketBuffer get() {
				return new PacketBuffer(Unpooled.copyShort(get.get()));
			}

			@Override
			public void set(PacketBuffer buffer) {
				set.accept(buffer.readShort());
			}
		};
	}

	public static final BufferReferenceHolder createLongHolder(LongSupplier get, LongConsumer set) {
		return new BufferReferenceHolder() {

			@Override
			public PacketBuffer get() {
				return new PacketBuffer(Unpooled.copyLong(get.getAsLong()));
			}

			@Override
			public void set(PacketBuffer buffer) {
				set.accept(buffer.readLong());
			}
		};
	}

}

Add some well used holders (int, long, short)


package edu.teco.dnd.network.messages;

import java.util.UUID;

/**
 * A Message that is sent as a Response for another Message.
 *
 * @author Philipp Adolf
 */
public abstract class Response extends Message {
	/**
	 * The UUID of the Message this is a response to.
	 */
	private final UUID sourceUUID;

	/**
	 * Initializes a new Response.
	 *
	 * @param sourceUUID the UUID of the Message this is a response to
	 * @param uuid the UUID for this Message
	 */
	public Response(final UUID sourceUUID, final UUID uuid) {
		super(uuid);
		this.sourceUUID = sourceUUID;
	}

	/**
	 * Initializes a new Response.
	 *
	 * @param sourceUUID the UUID of the Message this is a response to
	 */
	public Response(final UUID sourceUUID) {
		super();
		this.sourceUUID = sourceUUID;
	}

	/**
	 * Returns the UUID of the Message this is a response to.
	 *
	 * @return the UUID of the Message this is a response to
	 */
	public UUID getSourceUUID() {
		return this.sourceUUID;
	}
}

package edu.teco.dnd.network.messages;

import java.util.UUID;

import com.google.gson.annotations.SerializedName;

/**
 * A Message that is sent as a Response for another Message.
 *
 * @author Philipp Adolf
 */
public abstract class Response extends Message {
	/**
	 * The UUID of the Message this is a response to.
	 */
	@SerializedName("sourceuuid")
	private final UUID sourceUUID;

	/**
	 * Initializes a new Response.
	 *
	 * @param sourceUUID the UUID of the Message this is a response to
	 * @param uuid the UUID for this Message
	 */
	public Response(final UUID sourceUUID, final UUID uuid) {
		super(uuid);
		this.sourceUUID = sourceUUID;
	}

	/**
	 * Initializes a new Response.
	 *
	 * @param sourceUUID the UUID of the Message this is a response to
	 */
	public Response(final UUID sourceUUID) {
		super();
		this.sourceUUID = sourceUUID;
	}

	/**
	 * Returns the UUID of the Message this is a response to.
	 *
	 * @return the UUID of the Message this is a response to
	 */
	public UUID getSourceUUID() {
		return this.sourceUUID;
	}
}

Fix name of source UUID attribute

Fix name of source UUID attribute


/*****************************************************************************
 * Copyright (c) 2015 CEA LIST.
 *
 * 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:
 *  CEA LIST - Initial API and implementation
 *****************************************************************************/
package org.eclipse.papyrus.training.library.tests.newchild;

import org.eclipse.papyrus.training.library.tests.AbstractEMFResourceTest;
import org.junit.Test;

/**
 * Test the new child model :
 * - validate the model
 */
public class NewChildTest extends AbstractEMFResourceTest {

	public static final String PATH = org.eclipse.papyrus.training.library.newchild.Activator.PLUGIN_ID + "/resources/extLibrary.creationmenumodel"; // $NON-NLS-0$

	/**
	 * {@inheritDoc}
	 */
	@Override
	public String getFileUri() {
		return PATH;
	}

	@Test
	public void validateResource() {
		doValidateResource();
	}

}

/*****************************************************************************
 * Copyright (c) 2015 CEA LIST.
 *
 * 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:
 *  CEA LIST - Initial API and implementation
 *****************************************************************************/
package org.eclipse.papyrus.training.library.tests.newchild;

import org.eclipse.papyrus.training.library.tests.AbstractEMFResourceTest;
import org.junit.Test;

/**
 * Test the new child model :
 * - validate the model
 */
public class NewChildTest extends AbstractEMFResourceTest {

	public static final String PATH = org.eclipse.papyrus.training.library.newchild.Activator.PLUGIN_ID + "/resources/libraryNodes.creationmenumodel"; // $NON-NLS-0$

	/**
	 * {@inheritDoc}
	 */
	@Override
	public String getFileUri() {
		return PATH;
	}

	@Test
	public void validateResource() {
		doValidateResource();
	}

}

Correct path to new child model in test

Correct path to new child model in test

Signed-off-by: Benoit maggi <d25c97647eeeb5959868ec40f55094f6475a10df@cea.fr>


package ru.nsu.ccfit.bogush;

public class Config {
	public int engineStorageSize;
	public int carBodyStorageSize;
	public int accessoryStorageSize;
	public int carStorageSize;
	public int accessorySuppliers;
	public int workers;
	public int carDealers;

	public boolean logSale;
}

package ru.nsu.ccfit.bogush;

public class Config {
	private int engineStorageSize;
	private int carBodyStorageSize;
	private int accessoryStorageSize;
	private int carStorageSize;
	private int accessorySuppliers;
	private int workers;
	private int carDealers;

	private boolean loggingSales;

	public int getEngineStorageSize() {
		return engineStorageSize;
	}

	public void setEngineStorageSize(int engineStorageSize) {
		this.engineStorageSize = engineStorageSize;
	}

	public int getCarBodyStorageSize() {
		return carBodyStorageSize;
	}

	public void setCarBodyStorageSize(int carBodyStorageSize) {
		this.carBodyStorageSize = carBodyStorageSize;
	}

	public int getAccessoryStorageSize() {
		return accessoryStorageSize;
	}

	public void setAccessoryStorageSize(int accessoryStorageSize) {
		this.accessoryStorageSize = accessoryStorageSize;
	}

	public int getCarStorageSize() {
		return carStorageSize;
	}

	public void setCarStorageSize(int carStorageSize) {
		this.carStorageSize = carStorageSize;
	}

	public int getAccessorySuppliers() {
		return accessorySuppliers;
	}

	public void setAccessorySuppliers(int accessorySuppliers) {
		this.accessorySuppliers = accessorySuppliers;
	}

	public int getWorkers() {
		return workers;
	}

	public void setWorkers(int workers) {
		this.workers = workers;
	}

	public int getCarDealers() {
		return carDealers;
	}

	public void setCarDealers(int carDealers) {
		this.carDealers = carDealers;
	}

	public boolean isLoggingSales() {
		return loggingSales;
	}

	public void setLoggingSales(boolean loggingSales) {
		this.loggingSales = loggingSales;
	}

	@Override
	public String toString() {
		return "Config{" +
				"\n\tengineStorageSize=" + engineStorageSize +
				"\n\tcarBodyStorageSize=" + carBodyStorageSize +
				"\n\taccessoryStorageSize=" + accessoryStorageSize +
				"\n\tcarStorageSize=" + carStorageSize +
				"\n\taccessorySuppliers=" + accessorySuppliers +
				"\n\tworkers=" + workers +
				"\n\tcarDealers=" + carDealers +
				"\n\tloggingSales=" + loggingSales +
				"\n}";
	}
}

Make all fields private Add getters and setters Add toString()


package org.panifex.platform.module.dashboard.impl;

import java.util.ArrayList;
import java.util.Collection;

import org.apache.aries.blueprint.annotation.Bean;
import org.apache.aries.blueprint.annotation.Service;
import org.panifex.platform.module.api.sidebar.Sidebar;
import org.panifex.platform.module.api.sidebar.DefaultSidebarCommand;
import org.panifex.platform.module.api.sidebar.SidebarItem;

@Bean(id = DashboardSidebar.ID)
@Service(interfaces = Sidebar.class)
public class DashboardSidebar implements Sidebar {

    public final static String ID = "org.panifex.platform.module.dashboard.impl.DashboardSidebar";

    private Collection<SidebarItem> sidebarItems = new ArrayList<>();

    /**
     * Initializes Dashboard sidebar items;
     */
    public DashboardSidebar() {
        // create dashboard sidebar item
        DefaultSidebarCommand dashboardItem = new DefaultSidebarCommand(
            "Dashboard",
            DashboardContent.ID,
            0);

        // add item to list
        sidebarItems.add(dashboardItem);
    }

    @Override
    public Collection<SidebarItem> getSidebarItems() {
        return sidebarItems;
    }

}

package org.panifex.platform.module.dashboard.impl;

import java.util.ArrayList;
import java.util.Collection;

import org.apache.aries.blueprint.annotation.Bean;
import org.apache.aries.blueprint.annotation.Service;
import org.panifex.platform.module.api.sidebar.Sidebar;
import org.panifex.platform.module.api.sidebar.DefaultSidebarCommand;
import org.panifex.platform.module.api.sidebar.SidebarItem;

@Bean(id = DashboardSidebar.ID)
@Service(interfaces = Sidebar.class)
public class DashboardSidebar implements Sidebar {

    public final static String ID = "org.panifex.platform.module.dashboard.impl.DashboardSidebar";

    private Collection<SidebarItem> sidebarItems = new ArrayList<>();

    /**
     * Initializes Dashboard sidebar items;
     */
    public DashboardSidebar() {
        // create dashboard sidebar item
        DefaultSidebarCommand dashboardItem = new DefaultSidebarCommand(
            "Dashboard",
            DashboardContent.ID,
            0);

        dashboardItem.setIconSclass("glyphicon glyphicon-home");

        // add item to list
        sidebarItems.add(dashboardItem);
    }

    @Override
    public Collection<SidebarItem> getSidebarItems() {
        return sidebarItems;
    }

}

Add css style to Dashboard sidebar item

Add css style to Dashboard sidebar item


/****************************************************************************
 * Copyright (C) 2019 ecsec GmbH.
 * All rights reserved.
 * Contact: ecsec GmbH (info@ecsec.de)
 *
 * This file is part of the Open eCard App.
 *
 * GNU General Public License Usage
 * This file may be used under the terms of the GNU General Public
 * License version 3.0 as published by the Free Software Foundation
 * and appearing in the file LICENSE.GPL included in the packaging of
 * this file. Please review the following information to ensure the
 * GNU General Public License version 3.0 requirements will be met:
 * http://www.gnu.org/copyleft/gpl.html.
 *
 * Other Usage
 * Alternatively, this file may be used in accordance with the terms
 * and conditions contained in a signed written agreement between
 * you and ecsec GmbH.
 *
 ***************************************************************************/

package org.openecard.mobile.activation;

import java.net.URL;
import java.util.Set;
import org.openecard.robovm.annotations.FrameworkInterface;

/**
 *
 * @author Neil Crossley
 */
@FrameworkInterface
public interface EacControllerFactory {

    ActivationController create(URL url, Set<String> supportedCard, ControllerCallback activation, EacInteraction interaction);

    void destroy(ActivationController controller);
}

/****************************************************************************
 * Copyright (C) 2019 ecsec GmbH.
 * All rights reserved.
 * Contact: ecsec GmbH (info@ecsec.de)
 *
 * This file is part of the Open eCard App.
 *
 * GNU General Public License Usage
 * This file may be used under the terms of the GNU General Public
 * License version 3.0 as published by the Free Software Foundation
 * and appearing in the file LICENSE.GPL included in the packaging of
 * this file. Please review the following information to ensure the
 * GNU General Public License version 3.0 requirements will be met:
 * http://www.gnu.org/copyleft/gpl.html.
 *
 * Other Usage
 * Alternatively, this file may be used in accordance with the terms
 * and conditions contained in a signed written agreement between
 * you and ecsec GmbH.
 *
 ***************************************************************************/

package org.openecard.mobile.activation;

import java.util.Set;
import org.openecard.robovm.annotations.FrameworkInterface;

/**
 *
 * @author Neil Crossley
 */
@FrameworkInterface
public interface EacControllerFactory {

    ActivationController create(String url, Set<String> supportedCard, ControllerCallback activation, EacInteraction interaction);

    void destroy(ActivationController controller);
}

Make URL a string because of iOS build problems.


package uk.ac.ebi.quickgo.ontology;

import uk.ac.ebi.quickgo.ontology.coterms.CoTermConfig;
import uk.ac.ebi.quickgo.ontology.service.ServiceConfig;
import uk.ac.ebi.quickgo.rest.controller.SwaggerConfig;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.data.solr.SolrRepositoriesAutoConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Import;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;

/**
 * Runnable class to start an embedded server to host the defined RESTful components.
 *
 * Created 16/11/15
 * @author Edd
 */
@SpringBootApplication(exclude = {SolrRepositoriesAutoConfiguration.class})
@ComponentScan({
        "uk.ac.ebi.quickgo.ontology.controller",
        "uk.ac.ebi.quickgo.rest"})
@Import({ServiceConfig.class, SwaggerConfig.class, CoTermConfig.class})
public class OntologyREST {
    /**
     * Ensures that placeholders are replaced with property values
     */
    @Bean
    static PropertySourcesPlaceholderConfigurer propertyPlaceHolderConfigurer() {
        return new PropertySourcesPlaceholderConfigurer();
    }

    public static void main(String[] args) {
        SpringApplication.run(OntologyREST.class, args);
    }
}

package uk.ac.ebi.quickgo.ontology;

import uk.ac.ebi.quickgo.ontology.coterms.CoTermConfig;
import uk.ac.ebi.quickgo.ontology.service.ServiceConfig;
import uk.ac.ebi.quickgo.rest.controller.SwaggerConfig;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.data.solr.SolrRepositoriesAutoConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Import;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;

/**
 * Runnable class to start an embedded server to host the defined RESTful components.
 *
 * Created 16/11/15
 * @author Edd
 */
@SpringBootApplication(exclude = {SolrRepositoriesAutoConfiguration.class})
@ComponentScan({
        "uk.ac.ebi.quickgo.ontology.controller",
        "uk.ac.ebi.quickgo.rest"})
@Import({ServiceConfig.class, SwaggerConfig.class, CoTermConfig.class, OntologyRestConfig.class})
public class OntologyREST {
    /**
     * Ensures that placeholders are replaced with property values
     */
    @Bean
    static PropertySourcesPlaceholderConfigurer propertyPlaceHolderConfigurer() {
        return new PropertySourcesPlaceholderConfigurer();
    }

    public static void main(String[] args) {
        SpringApplication.run(OntologyREST.class, args);
    }
}

Add configuration for pagaing related properties.


package org.metaborg.meta.lang.dynsem.interpreter.utils;

import java.util.LinkedList;

import com.github.krukow.clj_lang.IPersistentStack;
import com.github.krukow.clj_lang.PersistentList;
import com.oracle.truffle.api.CompilerDirectives.TruffleBoundary;

public class ListUtils {

	@TruffleBoundary
	public static <T> IPersistentStack<T> reverse(IPersistentStack<T> list) {
		if (list.count() == 0) {
			return list;
		}
		final PersistentList<T> plist = (PersistentList<T>) list;

		final LinkedList<T> temp = new LinkedList<>();
		for (T t : plist) {
			temp.add(t);
		}
		return PersistentList.create(temp);
	}

}

package org.metaborg.meta.lang.dynsem.interpreter.utils;

import java.util.ArrayList;
import java.util.Collections;

import com.github.krukow.clj_lang.IPersistentStack;
import com.github.krukow.clj_lang.PersistentList;
import com.oracle.truffle.api.CompilerDirectives.TruffleBoundary;

public class ListUtils {

	@TruffleBoundary
	public static <T> IPersistentStack<T> reverse(IPersistentStack<T> list) {
		if (list.count() == 0) {
			return list;
		}

		final ArrayList<T> mlist = new ArrayList<T>((PersistentList<T>) list);

		Collections.reverse(mlist);

		return PersistentList.create(mlist);
	}

}

Fix incorrect implementation of list reversal


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

import io.trino.spi.ErrorCode;

import static io.trino.spi.StandardErrorCode.CLUSTER_OUT_OF_MEMORY;
import static io.trino.spi.StandardErrorCode.EXCEEDED_LOCAL_MEMORY_LIMIT;

public final class ErrorCodes
{
    private ErrorCodes() {}

    public static boolean isOutOfMemoryError(ErrorCode errorCode)
    {
        return EXCEEDED_LOCAL_MEMORY_LIMIT.toErrorCode().equals(errorCode) // too many tasks from single query on a node
                || CLUSTER_OUT_OF_MEMORY.toErrorCode().equals(errorCode); // too many tasks in general on a node
    }
}

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

import io.trino.spi.ErrorCode;

import static io.trino.spi.StandardErrorCode.CLUSTER_OUT_OF_MEMORY;
import static io.trino.spi.StandardErrorCode.EXCEEDED_GLOBAL_MEMORY_LIMIT;
import static io.trino.spi.StandardErrorCode.EXCEEDED_LOCAL_MEMORY_LIMIT;

public final class ErrorCodes
{
    private ErrorCodes() {}

    public static boolean isOutOfMemoryError(ErrorCode errorCode)
    {
        return EXCEEDED_LOCAL_MEMORY_LIMIT.toErrorCode().equals(errorCode)
                || EXCEEDED_GLOBAL_MEMORY_LIMIT.toErrorCode().equals(errorCode)
                || CLUSTER_OUT_OF_MEMORY.toErrorCode().equals(errorCode);
    }
}

Extend list of error codes treated as out-of-memory


package zero.downtime.soa.api;

import org.apache.camel.builder.RouteBuilder;
import org.eclipse.jetty.server.Server;

/**
 * @author magonzal
 * @version 1.0.0
 */
public class HelloServiceApi extends RouteBuilder {

	@Override
	public void configure() throws Exception {

		//@formatter:off
		restConfiguration().component("jetty")
			.host("localhost")
			.port(getRandomServerPort())
			.contextPath("hello-service-api/rest");

		rest("/{user}").description("Say hello to User")
			.get().route().to("direct-vm:hello");
		//@formatter:on
	}

	private int getRandomServerPort() throws Exception {
		Server server = new Server(0);
		server.start();
		return server.getConnectors()[0].getLocalPort();
	}
}

package zero.downtime.soa.api;

import org.apache.camel.builder.RouteBuilder;
import org.eclipse.jetty.server.Server;

/**
 * @author magonzal
 * @version 1.0.0
 */
public class HelloServiceApi extends RouteBuilder {

	@Override
	public void configure() throws Exception {

		//@formatter:off
		restConfiguration().component("jetty")
			.host("localhost")
			.port(getRandomServerPort())
			.contextPath("hello-service-api/rest");

		rest("/{user}").description("Say hello to User")
			.get().route().to("direct-vm:hello");
		//@formatter:on
	}

	private int getRandomServerPort() throws Exception {
		Server server = new Server(0);
		server.start();
		int port = server.getConnectors()[0].getLocalPort();
		server.stop();
		return port;
	}
}

Fix broken random port stuff

Fix broken random port stuff


package fr.openwide.core.wicket.more.markup.html.template.js.jquery.plugins.bootstrap.confirm.component;

import org.apache.wicket.model.IModel;

import fr.openwide.core.wicket.more.markup.html.action.IAjaxAction;

public class AjaxConfirmLinkBuilder<O> extends AbstractConfirmLinkBuilder<AjaxConfirmLink<O>, O> {
	private static final long serialVersionUID = 5629930352899730245L;

	@Override
	public AjaxConfirmLink<O> create(String wicketId, IModel<O> model) {
		if (onAjaxClick == null) {
			throw new IllegalStateException(String.format("%s must be used with a %s", getClass().getName(), IAjaxAction.class.getName()));
		}
		AjaxConfirmLink<O> ajaxConfirmLink = new FunctionalAjaxConfirmLink<O>(
				wicketId, model, form, titleModelFactory, contentModelFactory,
				yesLabelModel, noLabelModel, yesIconModel, noIconModel, yesButtonModel, noButtonModel,
				cssClassNamesModel, keepMarkup, onAjaxClick
		);
		ajaxConfirmLink.add(onAjaxClick.getActionAvailableCondition(model).thenShow());
		return ajaxConfirmLink;
	}

}

package fr.openwide.core.wicket.more.markup.html.template.js.jquery.plugins.bootstrap.confirm.component;

import org.apache.wicket.model.IModel;

import fr.openwide.core.wicket.more.markup.html.action.IAjaxAction;

public class AjaxConfirmLinkBuilder<O> extends AbstractConfirmLinkBuilder<AjaxConfirmLink<O>, O> {
	private static final long serialVersionUID = 5629930352899730245L;

	@Override
	public AjaxConfirmLink<O> create(String wicketId, IModel<O> model) {
		if (onAjaxClick == null) {
			throw new IllegalStateException(String.format("%s must be used with a %s", getClass().getName(), IAjaxAction.class.getName()));
		}
		AjaxConfirmLink<O> ajaxConfirmLink = new FunctionalAjaxConfirmLink<O>(
				wicketId, model, form, titleModelFactory, contentModelFactory,
				yesLabelModel, noLabelModel, yesIconModel, noIconModel, yesButtonModel, noButtonModel,
				cssClassNamesModel, keepMarkup, onAjaxClick
		);
		ajaxConfirmLink.add(onAjaxClick.getActionAvailableCondition(model).thenShowInternal());
		return ajaxConfirmLink;
	}

}

Use thenShowInternal on action condition to avoid visibility colision

(cherry picked from commit 2bf2404b3c89ce318481ef9dcc26088a9b472a93)


package io.akessler.elixircounter;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Intent overlayService = new Intent(this, OverlayService.class);
        startService(overlayService);
        finish();
    }
}

package io.akessler.elixircounter;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {

    /* Used to handle permission request */
    private static final int PERMISSIONS_REQUEST_RECORD_AUDIO = 1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // Check if user has given permission to record audio
        int permissionCheck = ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.RECORD_AUDIO);
        if (permissionCheck != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.RECORD_AUDIO}, PERMISSIONS_REQUEST_RECORD_AUDIO);
            return;
        }

        startOverlayService();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode,
                                           String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        if (requestCode == PERMISSIONS_REQUEST_RECORD_AUDIO) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                startOverlayService();
            } else {
                finish();
            }
        }
    }

    private void startOverlayService() {
        Intent overlayService = new Intent(this, OverlayService.class);
        startService(overlayService);
        finish();
    }
}

Add permissions check to allow recording audio with mic


package xyz.whereuat.whereuat;

import android.content.ContentValues;
import android.content.Context;
import android.location.Location;

import xyz.whereuat.whereuat.db.command.InsertCommand;
import xyz.whereuat.whereuat.db.entry.KeyLocationEntry;

/**
 * Created by kangp3 on 4/10/16.
 */
public class KeyLocationUtils {
    private static final String TAG = "KeyLocObj";

    public static boolean nameIsValid(String name) {
        return name != null && name.length() > 0;
    }

    public static boolean locIsValid(Location loc) {
        return loc != null;
    }

    public static InsertCommand buildInsertCommand(Context context, String name, double latitude,
                                                   double longitude) {
        ContentValues values = new ContentValues();
        values.put(KeyLocationEntry.COLUMN_NAME, name);
        values.put(KeyLocationEntry.COLUMN_LATITUDE, latitude);
        values.put(KeyLocationEntry.COLUMN_LONGITUDE, longitude);

        return new InsertCommand(context, KeyLocationEntry.TABLE_NAME, null, values);
    }
}

package xyz.whereuat.whereuat;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.location.Location;

import xyz.whereuat.whereuat.db.command.InsertCommand;
import xyz.whereuat.whereuat.db.entry.KeyLocationEntry;

/**
 * Created by kangp3 on 4/10/16.
 */
public class KeyLocationUtils {
    private static final String TAG = "KeyLocObj";

    public static boolean nameIsValid(String name) {
        return name != null && name.length() > 0;
    }

    public static boolean locIsValid(Location loc) {
        return loc != null;
    }

    public static String getNearestLoc(Cursor c, Location origin) throws IllegalArgumentException {
        String nearest = null;
        double nearest_dist = Double.MAX_VALUE;

        c.moveToFirst();
        while(c.moveToNext()) {
            double longitude = c.getDouble(c.getColumnIndexOrThrow(
                    KeyLocationEntry.COLUMN_LONGITUDE));
            double latitude = c.getDouble(c.getColumnIndexOrThrow(
                    KeyLocationEntry.COLUMN_LATITUDE));

            Location loc = new Location("");
            loc.setLongitude(longitude);
            loc.setLatitude(latitude);

            double dist = loc.distanceTo(origin);
            if (dist < nearest_dist) {
                nearest = c.getString(c.getColumnIndexOrThrow(KeyLocationEntry.COLUMN_NAME));
                nearest_dist = dist;
            }
        }

        return nearest;
    }

    public static InsertCommand buildInsertCommand(Context context, String name, double latitude,
                                                   double longitude) {
        ContentValues values = new ContentValues();
        values.put(KeyLocationEntry.COLUMN_NAME, name);
        values.put(KeyLocationEntry.COLUMN_LATITUDE, latitude);
        values.put(KeyLocationEntry.COLUMN_LONGITUDE, longitude);

        return new InsertCommand(context, KeyLocationEntry.TABLE_NAME, null, values);
    }
}

Add nearest loc utility function

Add nearest loc utility function


package com.darwinsys.clientware;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * A RESTful (JAX-RS) client NOT using the JAX-RS Client API
 * In fact, not using anything except Core Java APIs.
 */
public class UrlRestClient {

	public static void main(String[] args) throws Exception {

		// IRL this would come from the user, or ??
		final int recipeId = 4;

		// String concat, but ints cannot contain injection data
		URL url = new URL(Constants.ACB_BASE_URL + "/" + recipeId);
		final HttpURLConnection connection = (HttpURLConnection) url.openConnection();
		connection.addRequestProperty("Accept", "application/json");
		InputStream is = connection.getInputStream();
		// Read "is" to get the response from a GET
		BufferedReader bi = new BufferedReader(new InputStreamReader(is));
		String line = null;
		while ((line = bi.readLine()) != null) {
			System.out.println(line);
		}
	}
}

package com.darwinsys.clientware;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * A RESTful (JAX-RS) client NOT using the JAX-RS Client API
 * In fact, not using anything except Core Java APIs.
 */
public class UrlRestClient {

	public static void main(String[] args) throws Exception {

		// IRL this would come from the user, or ??
		final int recipeId = 4;

		// String concat, but ints cannot contain injection data
		URL url = new URL(Constants.ACB_BASE_URL
				.replace("https", "http") // remove when 577 rewritten
				+ "/" + recipeId);
		final HttpURLConnection connection = (HttpURLConnection) url.openConnection();
		connection.addRequestProperty("Accept", "application/json");
		InputStream is = connection.getInputStream();
		// Read "is" to get the response from a GET
		BufferedReader bi = new BufferedReader(new InputStreamReader(is));
		String line = null;
		while ((line = bi.readLine()) != null) {
			System.out.println(line);
		}
	}
}

Make the simple demo fall back to http

Make the simple demo fall back to http


package io.github.imsmobile.fahrplan.model;

import com.google.common.base.Objects;

public class FavoriteModelItem {
    private final String from;
    private final String to;

    FavoriteModelItem(String from, String to) {
        this.from = from;
        this.to = to;
    }

    public String getFrom() {
        return from;
    }

    public String getTo() {
        return to;
    }

    @Override
    public String toString() {
        return from + " \u279C " + to;
    }

    @Override
    public boolean equals(Object obj) {
        return obj instanceof FavoriteModelItem && Objects.equal(((FavoriteModelItem) obj).getFrom().toLowerCase(), from.toLowerCase()) && Objects.equal(((FavoriteModelItem) obj).getTo().toLowerCase(), to.toLowerCase());
    }

    @Override
    public int hashCode() {
        return Objects.hashCode(to.toLowerCase(), from.toLowerCase());
    }
}

package io.github.imsmobile.fahrplan.model;

import com.google.common.base.Objects;

public class FavoriteModelItem {
    private final String from;
    private final String to;

    FavoriteModelItem(String from, String to) {
        this.from = from;
        this.to = to;
    }

    public String getFrom() {
        return from;
    }

    public String getTo() {
        return to;
    }

    @Override
    public String toString() {
        return from + " \u279C " + to;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        FavoriteModelItem that = (FavoriteModelItem) o;

        if (from != null ? !from.equals(that.from) : that.from != null) return false;
        return to != null ? to.equals(that.to) : that.to == null;

    }

    @Override
    public int hashCode() {
        int result = from != null ? from.hashCode() : 0;
        result = 31 * result + (to != null ? to.hashCode() : 0);
        return result;
    }
}

Use auto generated hashcode and equals

Use auto generated hashcode and equals


package sk.tomsik68.mclauncher.impl.versions.mcdownload;

import net.minidev.json.JSONArray;
import net.minidev.json.JSONObject;

import java.util.*;

final class ArgumentList implements Iterable<Argument> {
    private static final ArgumentList EMPTY = new ArgumentList(Collections.<Argument>emptyList());
    private final List<Argument> args;

    private ArgumentList(List<Argument> arguments) {
        this.args = Collections.unmodifiableList(arguments);

    }

    static ArgumentList fromString(String s) {
        List<String> tokens = Arrays.asList(s.split(" "));
        List<Argument> args = new ArrayList<>(tokens.size());
        for (String tok : tokens) {
            args.add(Argument.fromString(tok));
        }
        return new ArgumentList(args);
    }

    static ArgumentList fromArray(JSONArray array) {
        List<Argument> arguments = new ArrayList<>();
        for (Object a : array) {
            arguments.add(Argument.fromJson((JSONObject) a));
        }
        return new ArgumentList(arguments);
    }

    public static ArgumentList empty() {
        return EMPTY;
    }

    boolean isEmpty() {
        return args.isEmpty();
    }

    @Override
    public Iterator<Argument> iterator() {
        return args.iterator();
    }
}

package sk.tomsik68.mclauncher.impl.versions.mcdownload;

import net.minidev.json.JSONArray;
import net.minidev.json.JSONObject;

import java.util.*;

final class ArgumentList implements Iterable<Argument> {
    private static final ArgumentList EMPTY = new ArgumentList(Collections.<Argument>emptyList());
    private final List<Argument> args;

    private ArgumentList(List<Argument> arguments) {
        this.args = Collections.unmodifiableList(arguments);

    }

    static ArgumentList fromString(String s) {
        List<String> tokens = Arrays.asList(s.split(" "));
        List<Argument> args = new ArrayList<>(tokens.size());
        for (String tok : tokens) {
            args.add(Argument.fromString(tok));
        }
        return new ArgumentList(args);
    }

    static ArgumentList fromArray(JSONArray array) {
        List<Argument> arguments = new ArrayList<>();
        for (Object a : array) {
            if (a instanceof String)
                arguments.add(Argument.fromString((String) a));
            else if(a instanceof JSONObject)
                arguments.add(Argument.fromJson((JSONObject) a));
        }
        return new ArgumentList(arguments);
    }

    public static ArgumentList empty() {
        return EMPTY;
    }

    boolean isEmpty() {
        return args.isEmpty();
    }

    @Override
    public Iterator<Argument> iterator() {
        return args.iterator();
    }
}

Fix handling of string-only arguments

Fix handling of string-only arguments


package org.metaborg.core.tracing;

import javax.annotation.Nullable;

import org.metaborg.core.source.ISourceLocation;
import org.metaborg.core.source.ISourceRegion;

/**
 * Represents a resolution produced by reference resolution.
 */
public class Resolution {
    /**
     * Area in the source file to highlight as a hyperlink.
     */
    public final ISourceRegion highlight;

    /**
     * Resolution targets. Multiple targets indicate resolution to multiple valid locations.
     */
    public final Iterable<Resolution.Target> targets;

    public Resolution(ISourceRegion highlight, Iterable<Resolution.Target> targets) {
        this.highlight = highlight;
        this.targets = targets;
    }

    public static class Target {
        public final @Nullable String hyperlinkName;
        public final ISourceLocation location;

        public Target(ISourceLocation location) {
            this(null, location);
        }

        public Target(String hyperlinkName, ISourceLocation location) {
            this.hyperlinkName = hyperlinkName;
            this.location = location;
        }
    }
}

package org.metaborg.core.tracing;

import javax.annotation.Nullable;

import org.metaborg.core.source.ISourceLocation;
import org.metaborg.core.source.ISourceRegion;

/**
 * Represents a resolution produced by reference resolution.
 */
public class Resolution {
    /**
     * Area in the source file to highlight as a hyperlink.
     */
    public final ISourceRegion highlight;

    /**
     * Resolution targets. Multiple targets indicate resolution to multiple valid locations.
     */
    public final Iterable<Resolution.Target> targets;

    public Resolution(ISourceRegion highlight, Iterable<Resolution.Target> targets) {
        this.highlight = highlight;
        this.targets = targets;
    }

    public static class Target {
        public final @Nullable String hyperlinkName;
        public final ISourceLocation location;

        public Target(ISourceLocation location) {
            this(null, location);
        }

        public Target(String hyperlinkName, ISourceLocation location) {
            this.hyperlinkName = hyperlinkName == null ? defaultHyperlinkName(location) : hyperlinkName;
            this.location = location;
        }

        private static String defaultHyperlinkName(ISourceLocation location) {
            String fileName = location.resource().getName().getBaseName();
            ISourceRegion region = location.region();
            int row = region.startRow();
            int col = region.startColumn();
            return fileName + ":" + row + ":" + col;
        }
    }
}

Add default resolution label based on origin information


// Copyright eeGeo Ltd (2012-2015), All Rights Reserved

package com.eegeo.searchmenu;

import com.eegeo.searchmenu.SearchMenuResultsListAnimationConstants;

import android.annotation.SuppressLint;
import android.os.Handler;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ListView;

public class SearchResultsScrollButtonTouchDownListener implements View.OnTouchListener
{
	private ListView m_searchList = null;
    private final Handler mHandler = new Handler();

	public SearchResultsScrollButtonTouchDownListener(ListView view) {
		m_searchList = view;
	}

    final Runnable mAction = new Runnable() {
		@SuppressLint("NewApi")
		@Override public void run() {
            mHandler.postDelayed(this, 0);
            m_searchList.scrollListBy(SearchMenuResultsListAnimationConstants.SearchMenuResultsListScrollButtonSpeed);
        }
    };

	@Override
	public boolean onTouch(View v, MotionEvent event) {
		switch(event.getAction()) {
			case MotionEvent.ACTION_DOWN:
	            mHandler.postDelayed(mAction, 0);
	            break;
	        case MotionEvent.ACTION_UP:
	            mHandler.removeCallbacks(mAction);
	            break;
		}
		return false;
	}
}

// Copyright eeGeo Ltd (2012-2015), All Rights Reserved

package com.eegeo.searchmenu;

import com.eegeo.searchmenu.SearchMenuResultsListAnimationConstants;

import android.annotation.SuppressLint;
import android.os.Handler;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ListView;

public class SearchResultsScrollButtonTouchDownListener implements View.OnTouchListener
{
	private ListView m_searchList = null;
    private final Handler mHandler = new Handler();

	public SearchResultsScrollButtonTouchDownListener(ListView view) {
		m_searchList = view;
	}

    final Runnable mAction = new Runnable() {
		@SuppressLint("NewApi")
		@Override public void run() {
            mHandler.postDelayed(this, 0);
            if(android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT)
            {
            	m_searchList.scrollListBy(SearchMenuResultsListAnimationConstants.SearchMenuResultsListScrollButtonSpeed);
            }
        }
    };

	@Override
	public boolean onTouch(View v, MotionEvent event) {
		switch(event.getAction()) {
			case MotionEvent.ACTION_DOWN:
	            mHandler.postDelayed(mAction, 0);
	            break;
	        case MotionEvent.ACTION_UP:
	            mHandler.removeCallbacks(mAction);
	            break;
		}
		return false;
	}
}

Fix for MPLY-7330. ScrollListBy doesnt work with version < 4.4 so disable scrolling on devices before that. Buddy: Tim


/**
 * Copyright 2010 The PlayN 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 playn.html;

import com.google.gwt.canvas.dom.client.Context2d;

import playn.core.AbstractLayer;

abstract class HtmlLayerCanvas extends AbstractLayer {

  abstract void paint(Context2d ctx, float parentAlpha);

  protected HtmlLayerCanvas() {
    super(new HtmlInternalTransform());
  }

  void transform(Context2d ctx) {
    ctx.translate(originX, originY);
    ctx.transform(transform.m00(), transform.m01(), transform.m10(),
        transform.m11(), transform.tx() - originX, transform.ty() - originY);
    ctx.translate(-originX, -originY);
  }
}

/**
 * Copyright 2010 The PlayN 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 playn.html;

import com.google.gwt.canvas.dom.client.Context2d;

import playn.core.AbstractLayer;
import playn.core.StockInternalTransform;

abstract class HtmlLayerCanvas extends AbstractLayer {

  abstract void paint(Context2d ctx, float parentAlpha);

  protected HtmlLayerCanvas() {
    super(HtmlPlatform.hasTypedArraySupport ?
          new HtmlInternalTransform() : new StockInternalTransform());
  }

  void transform(Context2d ctx) {
    ctx.translate(originX, originY);
    ctx.transform(transform.m00(), transform.m01(), transform.m10(),
        transform.m11(), transform.tx() - originX, transform.ty() - originY);
    ctx.translate(-originX, -originY);
  }
}

Use approrpiate transform implementation in canvas backend.


package com.scottbezek.difflib;

import org.junit.Test;

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

import static org.junit.Assert.assertEquals;

public class UnicodeUtilTest {

    @Test
    public void testSplitNaturalCharactersSimple() throws Exception {
        List<String> expected = Arrays.asList("a", "b", "c");
        assertEquals(expected, UnicodeUtil.splitNaturalCharacters("abc", Locale.US));
    }

    @Test
    public void testSplitNaturalCharactersAccent() throws Exception {
        List<String> expected = Arrays.asList("a", "a\u0301", "c");
        assertEquals(expected, UnicodeUtil.splitNaturalCharacters("aa\u0301c", Locale.US));
    }
}

package com.scottbezek.difflib;

import org.junit.Test;

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

import static org.junit.Assert.assertEquals;

public class UnicodeUtilTest {

    @Test
    public void testSplitNaturalCharactersEmpty() throws Exception {
        List<String> expected = Collections.emptyList();
        assertEquals(expected, UnicodeUtil.splitNaturalCharacters("", Locale.US));
    }

    @Test
    public void testSplitNaturalCharactersSingle() throws Exception {
        List<String> expected = Arrays.asList("a");
        assertEquals(expected, UnicodeUtil.splitNaturalCharacters("a", Locale.US));
    }

    @Test
    public void testSplitNaturalCharactersSimple() throws Exception {
        List<String> expected = Arrays.asList("a", "b", "c");
        assertEquals(expected, UnicodeUtil.splitNaturalCharacters("abc", Locale.US));
    }

    @Test
    public void testSplitNaturalCharactersAccent() throws Exception {
        List<String> expected = Arrays.asList("a", "a\u0301", "c");
        assertEquals(expected, UnicodeUtil.splitNaturalCharacters("aa\u0301c", Locale.US));
    }
}

Add a couple more splitNaturalCharacters tests


package dijkstras;

import dijkstras.Dijkstras;		// My implementation of Dijkstras algorithm in package dijkstras

/*
	This class test Dijkstras shortest path algorithm
*/

class TestDijkstras
{

	// Test A

	public static void testA(){

		int N = 6;		// No. of vertices
		int M = 10;		// No. of edges
		int edges[][] = {	{1,2,10}, 		// Edges
							{2,3,1},
							{3,4,4},
							{4,3,6},
							{5,4,2},
							{1,5,5},
							{2,5,2},
							{5,2,3},
							{5,3,9},
							{4,1,7}
						};

		int s = 1;		// source vertex

		Dijkstras dk = new Dijkstras(N, M, edges, s);

		dk.findShortestPaths();

		System.out.println("Shortest Distances: ");
		dk.showDist();

		System.out.println("Shortest Paths: ");
		for(int i=1;i<=N;i++){

			System.out.print(i+ ": ");
			dk.printPath(i);
			System.out.println();
		}

	}

	public static void main(String args[]){

			// Call testA()

			testA();
	}
}

package dijkstras;

import dijkstras.Dijkstras;		// My implementation of Dijkstras algorithm in package dijkstras

/*
	This class test Dijkstras shortest path algorithm
*/

class TestDijkstras
{

	// Test A

	public static void testA(){

		int N = 7;		// No. of vertices
		int M = 12;		// No. of edges
		int edges[][] = {	{1,2,10}, 		// Edges
							{2,3,1},
							{3,4,4},
							{4,3,6},
							{5,4,2},
							{1,5,5},
							{2,5,2},
							{5,2,3},
							{5,3,9},
							{4,1,7},
							{6,7,5},
							{7,6,6}
						};

		int s = 1;		// source vertex

		Dijkstras dk = new Dijkstras(N, M, edges, s);

		dk.findShortestPaths();

		System.out.println("Shortest Distances: ");
		dk.showDist();

		System.out.println("Shortest Paths: ");
		for(int i=1;i<=N;i++){

			System.out.print(i+ ": ");
			dk.printPath(i);
			System.out.println();
		}

	}

	public static void main(String args[]){

			// Call testA()

			testA();
	}
}

Update test case for Dijkstras

Update test case for Dijkstras


package de.uni_potsdam.hpi.bpt.bp2014.jconfiguration;

import de.uni_potsdam.hpi.bpt.bp2014.jcore.eventhandling.EventDispatcher;

import java.util.List;

/**
 * This class executes configurations.
 */
public class Execution {

	/**
	 * This method marks the scenario as deleted if there are no running instances.
	 *
	 * @param scenarioId DatabaseID of the scenario that is supposed to get marked as deleted
	 * @return true if the scenario was deleted (else false)
	 * @throws Exception Running instances of the scenario exist.
	 */
	public boolean deleteScenario(int scenarioId) throws Exception {
		DbConfigurationConnection conn = new DbConfigurationConnection();
		List<Integer> runningInstances = conn.getRunningScenarioInstances(scenarioId);
		if (runningInstances.size() > 0) {
			return false;
		} else {
			conn.deleteScenario(scenarioId);
			EventDispatcher.unregisterStartQuery(scenarioId);
			return true;
		}
	}
}

package de.uni_potsdam.hpi.bpt.bp2014.jconfiguration;

import de.uni_potsdam.hpi.bpt.bp2014.jcore.eventhandling.EventDispatcher;

import java.util.List;

/**
 * This class executes configurations.
 */
public class Execution {

	/**
	 * This method marks the scenario as deleted if there are no running instances.
	 *
	 * @param scenarioId DatabaseID of the scenario that is supposed to get marked as deleted
	 * @return true if the scenario was deleted (else false)
	 * @throws Exception Running instances of the scenario exist.
	 */
	public boolean deleteScenario(int scenarioId) throws Exception {
		DbConfigurationConnection conn = new DbConfigurationConnection();
		conn.deleteScenario(scenarioId);
		EventDispatcher.unregisterStartQuery(scenarioId);
		return true;
	}
}

Enable scenario deletion via DELETE call at all times (still no button in the frontend unless there are no running instances)


package com.fewlaps.mentiondetector;

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

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

public class RemovePunctuationMarksTest {

    RemovePunctuationMarks removePunctuationMarks;

    @Before
    public void setup() {
        removePunctuationMarks = new RemovePunctuationMarks();
    }

    @Test
    public void shouldRemoveExclamationMarks() throws InterruptedException {
        String textWithPunctuationMarks = "hello!!!!";

        String textWithoutPunctuationMarks = removePunctuationMarks.removePunctuationMarks(textWithPunctuationMarks);

        assertThat(textWithoutPunctuationMarks).doesNotContain("!");
    }

    @Test
    public void shouldRemoveQuestionMarks() throws InterruptedException {
        String textWithPunctuationMarks = "hello????";

        String textWithoutPunctuationMarks = removePunctuationMarks.removePunctuationMarks(textWithPunctuationMarks);

        assertThat(textWithoutPunctuationMarks).doesNotContain("?");
    }

    @Test
    public void shouldRemoveReversedExclamationMarks() throws InterruptedException {
        String textWithPunctuationMarks = "hello";

        String textWithoutPunctuationMarks = removePunctuationMarks.removePunctuationMarks(textWithPunctuationMarks);

        assertThat(textWithoutPunctuationMarks).doesNotContain("");
    }

    @Test
    public void shouldRemoveReversedQuestionMarks() throws InterruptedException {
        String textWithPunctuationMarks = "hello";

        String textWithoutPunctuationMarks = removePunctuationMarks.removePunctuationMarks(textWithPunctuationMarks);

        assertThat(textWithoutPunctuationMarks).doesNotContain("");
    }
}

package com.fewlaps.mentiondetector;

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

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

public class RemovePunctuationMarksTest {

    RemovePunctuationMarks removePunctuationMarks;

    @Before
    public void setup() {
        removePunctuationMarks = new RemovePunctuationMarks();
    }

    @Test
    public void shouldRemoveExclamationMarks() throws InterruptedException {
        String textWithPunctuationMarks = "hello!!!!";

        String textWithoutPunctuationMarks = removePunctuationMarks.removePunctuationMarks(textWithPunctuationMarks);

        assertThat(textWithoutPunctuationMarks).doesNotContain("!");
    }

    @Test
    public void shouldRemoveQuestionMarks() throws InterruptedException {
        String textWithPunctuationMarks = "hello????";

        String textWithoutPunctuationMarks = removePunctuationMarks.removePunctuationMarks(textWithPunctuationMarks);

        assertThat(textWithoutPunctuationMarks).doesNotContain("?");
    }

    @Test
    public void shouldRemoveReversedExclamationMarks() throws InterruptedException {
        String textWithPunctuationMarks = "hello����";

        String textWithoutPunctuationMarks = removePunctuationMarks.removePunctuationMarks(textWithPunctuationMarks);

        assertThat(textWithoutPunctuationMarks).doesNotContain("�");
    }

    @Test
    public void shouldRemoveReversedQuestionMarks() throws InterruptedException {
        String textWithPunctuationMarks = "hello���";

        String textWithoutPunctuationMarks = removePunctuationMarks.removePunctuationMarks(textWithPunctuationMarks);

        assertThat(textWithoutPunctuationMarks).doesNotContain("�");
    }
}

Convert the file to UTF-8

Convert the file to UTF-8


package org.agmip.acmo.translators;

public interface AcmoTranslator {
    public boolean execute(String sourceFolder, String destFolder);
}

package org.agmip.acmo.translators;

import java.io.File;

public interface AcmoTranslator {
    public File execute(String sourceFolder, String destFolder);
}

Change excute method return type from boolean to File


package im.delight.android.ddp;

/*
 * Copyright (c) delight.im <info@delight.im>
 *
 * 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.
 */

public interface SubscribeListener extends Listener {

	public void onSuccess();
	public void onError(String error, String reason, String details);

}

package im.delight.android.ddp;

/*
 * Copyright (c) delight.im <info@delight.im>
 *
 * 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.
 */

public interface SubscribeListener extends Listener {

	void onSuccess();

	void onError(String error, String reason, String details);

}

Remove unnecessary visibility modifiers in interface


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

package org.apache.jmeter.protocol.jms.sampler;

import javax.jms.JMSException;
import javax.jms.Message;

/**
 * Executor for (pseudo) synchronous communication.

 * Created on: October 28, 2004
 *
 * @version $Revision$
 */
public interface QueueExecutor {
    /**
     * Sends and receives a message.
     *
     * @param request the message to send
     * @param deliveryMode the delivery mode to use
     * @param priority the priority for this message
     * @param expiration messages lifetime in ms
     * @return the received message or null
     * @throws JMSException
     *             in case of an exception from the messaging system
     */
    Message sendAndReceive(Message request,
            int deliveryMode,
            int priority,
            long expiration) throws JMSException;

}

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

package org.apache.jmeter.protocol.jms.sampler;

import javax.jms.JMSException;
import javax.jms.Message;

/**
 * Executor for (pseudo) synchronous communication.

 * Created on: October 28, 2004
 *
 */
public interface QueueExecutor {
    /**
     * Sends and receives a message.
     *
     * @param request the message to send
     * @param deliveryMode the delivery mode to use
     * @param priority the priority for this message
     * @param expiration messages lifetime in ms
     * @return the received message or null
     * @throws JMSException
     *             in case of an exception from the messaging system
     */
    Message sendAndReceive(Message request,
            int deliveryMode,
            int priority,
            long expiration) throws JMSException;

}

Remove @version that uses svn revision as it makes useless differences when comparing svn with github

git-svn-id: 5ccfe34f605a6c2f9041ff2965ab60012c62539a@1788653 13f79535-47bb-0310-9956-ffa450edef68


package jpower.core.config;

import jpower.core.load.Loadable;
import jpower.core.load.Reloadable;
import jpower.core.utils.ExceptionUtils;

import java.io.File;
import java.io.IOException;
import java.nio.file.Path;

/**
 * Configuration File Wrapper
 */
public class ConfigFile implements Loadable, Reloadable
{
   private final Path path;
   private final Configuration configuration = new Configuration();

   /**
    * Creates a ConfigFile from the path
    *
    * @param path path
    */
   public ConfigFile(Path path)
   {
      this.path = path;
   }

   /**
    * Creates a ConfigFile from the file
    * @param file file
    */
   public ConfigFile(File file)
   {
      this.path = file.toPath();
   }

   /**
    * Loads the Configuration File
    */
   @Override
   public void load()
   {
      try
      {
         configuration.load(path.toFile());
      }
      catch (IOException e)
      {
         ExceptionUtils.throwUnchecked(e);
      }
   }

   /**
    * Reloads the Configuration File
    */
   @Override
   public void reload()
   {
      configuration.reset();
      load();
   }

   /**
    * Gets the Configuration from the File
    * @return configuration
    */
   public Configuration getConfiguration()
   {
      return configuration;
   }
}

package jpower.core.config;

import jpower.core.load.Loadable;
import jpower.core.load.Reloadable;
import jpower.core.utils.ExceptionUtils;

import java.io.File;
import java.io.IOException;
import java.nio.file.Path;

/**
 * Configuration File Wrapper
 */
public class ConfigFile implements Loadable, Reloadable
{
   private final File file;
   private final Configuration configuration = new Configuration();

   /**
    * Creates a @link{ConfigFile} from the Path
    *
    * @param path the path to load the configuration from
    */
   public ConfigFile(Path path)
   {
      this(path.toFile());
   }

   /**
    * Creates a {@link ConfigFile} from the file
    * @param file the file to load the configuration from
    */
   public ConfigFile(File file)
   {
      this.file = file;
   }

   /**
    * Loads the configuration file
    */
   @Override
   public void load()
   {
      try
      {
         configuration.load(file);
      }
      catch (IOException e)
      {
         ExceptionUtils.throwUnchecked(e);
      }
   }

   /**
    * Reloads the configuration file
    */
   @Override
   public void reload()
   {
      configuration.reset();
      load();
   }

   /**
    * Gets the {@link Configuration} from the File
    * @return configuration
    */
   public Configuration getConfiguration()
   {
      return configuration;
   }
}

Fix Silly Code and cleanup JavaDoc

Configuration: Fix Silly Code and cleanup JavaDoc


package ru.job4j.Exception;

/**
 * The class MenuOutException.
 *
 * @author Alexander Mezgin
 * @version 1.0
 * @since 14.01.2017
 */
public class MenuOutException extends RuntimeException {
    /**
     * Constructor fo class MenuOutException.
     *
     * @param message message
     */
    public MenuOutException(String message) {
        super(message);
    }
}

package ru.job4j.exception;

/**
 * The class MenuOutException.
 *
 * @author Alexander Mezgin
 * @version 1.0
 * @since 14.01.2017
 */
public class MenuOutException extends RuntimeException {
    /**
     * Constructor fo class MenuOutException.
     *
     * @param message message
     */
    public MenuOutException(String message) {
        super(message);
    }
}

Edit chapter_ 003/socket. Replacement name package. Edit Client.java (used try-with-resources.


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

import static com.google.common.truth.delegation.FooSubject.FOO;

import static org.truth0.Truth.ASSERT;
import org.junit.Test;

/**
 * A test that's more or less intended to show how one uses an extended verb.
 *
 */
public class DelegationTest {

  @Test public void customTypeProposition() {
    ASSERT.about(FOO).that(new Foo(5)).matches(new Foo(2 + 3));
  }

  @Test public void customTypePropositionWithFailure() {
    try {
      ASSERT.about(FOO).that(new Foo(5)).matches(new Foo(4));
      ASSERT.fail("Should have thrown.");
    } catch (AssertionError e) {
      ASSERT.that(e.getMessage()).contains("Not true that");
      ASSERT.that(e.getMessage()).contains("matches");
    }
  }
}

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

import static com.google.common.truth.delegation.FooSubject.FOO;
import static org.truth0.Truth.ASSERT;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;

/**
 * A test that's more or less intended to show how one uses an extended verb.
 *
 */
@RunWith(JUnit4.class)
public class DelegationTest {

  @Test public void customTypeProposition() {
    ASSERT.about(FOO).that(new Foo(5)).matches(new Foo(2 + 3));
  }

  @Test public void customTypePropositionWithFailure() {
    try {
      ASSERT.about(FOO).that(new Foo(5)).matches(new Foo(4));
      ASSERT.fail("Should have thrown.");
    } catch (AssertionError e) {
      ASSERT.that(e.getMessage()).contains("Not true that");
      ASSERT.that(e.getMessage()).contains("matches");
    }
  }
}

Add a RunsWith for JUnit4

Add a RunsWith for JUnit4


package com.antew.redditinpictures.library.json;

import com.antew.redditinpictures.library.enums.Vote;
import com.antew.redditinpictures.library.gson.VoteAdapter;
import com.antew.redditinpictures.library.logging.Log;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonSyntaxException;

public class JsonDeserializer {
    public static final String TAG = JsonDeserializer.class.getSimpleName();
    private static Gson gson;

    public static <T> T deserialize(String json, Class<T> clazz) {
        try {
            return getGson().fromJson(json, clazz);
        } catch (JsonSyntaxException e) {
            Log.e(TAG, "deserialize - Error parsing JSON!", e);
        } catch (IllegalStateException e) {
            Log.e(TAG, "deserialize - Error parsing JSON!", e);
        }

        return null;
    }

    public static Gson getGson() {
        if (gson == null) {
            GsonBuilder builder = new GsonBuilder();
            builder.registerTypeAdapter(Vote.class, new VoteAdapter());
            builder.serializeNulls();
            gson = builder.create();
        }

        return gson;
    }
}

package com.antew.redditinpictures.library.json;

import com.antew.redditinpictures.library.enums.Vote;
import com.antew.redditinpictures.library.gson.VoteAdapter;
import com.antew.redditinpictures.library.logging.Log;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonSyntaxException;
import java.io.Reader;

public class JsonDeserializer {
    public static final String TAG = JsonDeserializer.class.getSimpleName();
    private static Gson gson;

    public static <T> T deserialize(Reader json, Class<T> clazz) {
        try {
            return getGson().fromJson(json, clazz);
        } catch (JsonSyntaxException e) {
            Log.e(TAG, "deserialize - Error parsing JSON!", e);
        } catch (IllegalStateException e) {
            Log.e(TAG, "deserialize - Error parsing JSON!", e);
        }

        return null;
    }

    public static <T> T deserialize(String json, Class<T> clazz) {
        try {
            return getGson().fromJson(json, clazz);
        } catch (JsonSyntaxException e) {
            Log.e(TAG, "deserialize - Error parsing JSON!", e);
        } catch (IllegalStateException e) {
            Log.e(TAG, "deserialize - Error parsing JSON!", e);
        }

        return null;
    }

    public static Gson getGson() {
        if (gson == null) {
            GsonBuilder builder = new GsonBuilder();
            builder.registerTypeAdapter(Vote.class, new VoteAdapter());
            builder.serializeNulls();
            gson = builder.create();
        }

        return gson;
    }
}

Add JSON deserializer which takes a reader


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

package com.googlesource.gerrit.plugins.deleteproject;

import com.google.gerrit.extensions.registration.DynamicSet;
import com.google.gerrit.extensions.webui.JavaScriptPlugin;
import com.google.gerrit.extensions.webui.WebUiPlugin;
import com.google.inject.servlet.ServletModule;

public class HttpModule extends ServletModule {
  @Override
  protected void configureServlets() {
    DynamicSet.bind(binder(), WebUiPlugin.class)
        .toInstance(new JavaScriptPlugin("delete-project.html"));
  }
}

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

package com.googlesource.gerrit.plugins.deleteproject;

import com.google.gerrit.extensions.registration.DynamicSet;
import com.google.gerrit.extensions.webui.JavaScriptPlugin;
import com.google.gerrit.extensions.webui.WebUiPlugin;
import com.google.inject.servlet.ServletModule;

public class HttpModule extends ServletModule {
  @Override
  protected void configureServlets() {
    DynamicSet.bind(binder(), WebUiPlugin.class)
        .toInstance(new JavaScriptPlugin("delete-project.js"));
  }
}

Switch over to loading .js file

Switch over to loading .js file

Gerrit no longer supports html plugins so we have
to use the .js version.

Bug: Issue 14335
Change-Id: I284647480d0cac76f3afde0aa566b47121ff9511


package com.akikanellis.kata01.offer;

import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import java.util.stream.Stream;

/**
 * A representation of a collection of {@link com.akikanellis.kata01.offer.OfferStrategies}.
 */
public final class OfferStrategies {
    private final Set<OfferStrategy> strategies;

    private OfferStrategies(Collection<OfferStrategy> strategies) { this.strategies = new HashSet<>(strategies); }

    public static OfferStrategies fromCollection(Collection<OfferStrategy> offerStrategies) {
        return new OfferStrategies(offerStrategies);
    }

    public static OfferStrategies empty() { return new OfferStrategies(Collections.emptyList()); }

    public boolean isEmpty() { return strategies.isEmpty(); }

    public Set<OfferStrategy> asSet() { return new HashSet<>(strategies); }

    public Stream<OfferStrategy> stream() { return strategies.stream(); }
}

package com.akikanellis.kata01.offer;

import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import java.util.stream.Stream;

/**
 * A representation of a collection of {@link com.akikanellis.kata01.offer.OfferStrategies}.
 */
public final class OfferStrategies {
    private final Set<OfferStrategy> strategies;

    private OfferStrategies(Collection<OfferStrategy> strategies) { this.strategies = new HashSet<>(strategies); }

    public static OfferStrategies fromCollection(Collection<OfferStrategy> offerStrategies) {
        return new OfferStrategies(offerStrategies);
    }

    public static OfferStrategies empty() { return fromCollection(Collections.emptyList()); }

    public boolean isEmpty() { return strategies.isEmpty(); }

    public Set<OfferStrategy> asSet() { return new HashSet<>(strategies); }

    public Stream<OfferStrategy> stream() { return strategies.stream(); }
}

Use static factory method instead of constructor


package router.client.api2;

import java.util.List;
import java.util.Objects;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;

public final class OnChangeCallbackChain
{
  @Nonnull
  private final List<RouteEntry<OnChangeCallbackAsync>> _chain;

  public OnChangeCallbackChain( @Nonnull final List<RouteEntry<OnChangeCallbackAsync>> chain )
  {
    _chain = Objects.requireNonNull( chain );
  }

  public void onChange( @Nullable final String previousLocation,
                        @Nonnull final Runnable abortRoute,
                        @Nonnull final Runnable continueRoute )
  {
    onChange( previousLocation, abortRoute, continueRoute, 0 );
  }

  private void onChange( @Nullable final String previousLocation,
                         @Nonnull final Runnable abortRoute,
                         @Nonnull final Runnable continueRoute,
                         final int index )
  {
    if ( index >= _chain.size() )
    {
      continueRoute.run();
    }
    else
    {
      final RouteEntry<OnChangeCallbackAsync> entry = _chain.get( index );
      entry.getCallback().onChange( previousLocation, entry.getLocation(), new OnChangeControl()
      {
        @Override
        public void abort()
        {
          abortRoute.run();
        }

        @Override
        public void proceed()
        {
          onChange( previousLocation, abortRoute, continueRoute, index + 1 );
        }
      } );
    }
  }
}

package router.client.api2;

import java.util.List;
import java.util.Objects;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;

public final class OnChangeCallbackChain
{
  @Nonnull
  private final List<RouteEntry<OnChangeCallbackAsync>> _chain;

  public OnChangeCallbackChain( @Nonnull final List<RouteEntry<OnChangeCallbackAsync>> chain )
  {
    _chain = Objects.requireNonNull( chain );
  }

  public void onChange( @Nullable final String previousLocation,
                        @Nonnull final Runnable abortAction,
                        @Nonnull final Runnable nextAction )
  {
    onChange( previousLocation, abortAction, nextAction, 0 );
  }

  private void onChange( @Nullable final String previousLocation,
                         @Nonnull final Runnable abortAction,
                         @Nonnull final Runnable nextAction,
                         final int index )
  {
    if ( index >= _chain.size() )
    {
      nextAction.run();
    }
    else
    {
      final RouteEntry<OnChangeCallbackAsync> entry = _chain.get( index );
      entry.getCallback().onChange( previousLocation, entry.getLocation(), new OnChangeControl()
      {
        @Override
        public void abort()
        {
          abortAction.run();
        }

        @Override
        public void halt()
        {
          nextAction.run();
        }

        @Override
        public void proceed()
        {
          onChange( previousLocation, abortAction, nextAction, index + 1 );
        }
      } );
    }
  }
}

Implement missing halt callback method and rename actions


package com.github.vlsidlyarevich.unity.controller;

import com.github.vlsidlyarevich.unity.service.WorkerProfileSearchService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

/**
 * Created by vlad on 30.09.16.
 */
@RestController
@RequestMapping("/api/workers/search")
public class WorkerProfileSearchController {

    @Autowired
    private WorkerProfileSearchService service;

    @RequestMapping(method = RequestMethod.POST)
    public ResponseEntity<?> getWorkersByFilters(MultiValueMap<String, String> filters) {
        return new ResponseEntity<>(service.findByFilters(filters), HttpStatus.OK);
    }

}

package com.github.vlsidlyarevich.unity.controller;

import com.github.vlsidlyarevich.unity.service.WorkerProfileSearchService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

/**
 * Created by vlad on 30.09.16.
 */
@RestController
@RequestMapping("/api/workers/search")
public class WorkerProfileSearchController {

    @Autowired
    private WorkerProfileSearchService service;

    @RequestMapping(method = RequestMethod.POST)
    public ResponseEntity<?> getWorkersByFilters(@RequestBody Map<String, String> filters) {
        return new ResponseEntity<>(service.findByFilters(filters), HttpStatus.OK);
    }

}

Switch to map as request body

Switch to map as request body


package placebooks.model.json;

import java.io.IOException;

import org.codehaus.jackson.JsonParser;
import org.codehaus.jackson.JsonProcessingException;
import org.codehaus.jackson.map.DeserializationContext;
import org.codehaus.jackson.map.JsonDeserializer;

import com.vividsolutions.jts.geom.Geometry;
import com.vividsolutions.jts.io.ParseException;
import com.vividsolutions.jts.io.WKTReader;

public class GeometryJSONDeserializer extends JsonDeserializer<Geometry>
{
	@Override
	public Geometry deserialize(final JsonParser parser, final DeserializationContext context) throws IOException,
			JsonProcessingException
	{
		try
		{
			return new WKTReader().read(parser.getText());
		}
		catch (final ParseException e)
		{
			throw new IOException("Parse Error", e);
		}
	}
}

package placebooks.model.json;

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

import org.codehaus.jackson.JsonParser;
import org.codehaus.jackson.JsonProcessingException;
import org.codehaus.jackson.map.DeserializationContext;
import org.codehaus.jackson.map.JsonDeserializer;

import com.vividsolutions.jts.geom.Geometry;
import com.vividsolutions.jts.io.WKTReader;

public class GeometryJSONDeserializer extends JsonDeserializer<Geometry>
{
	private final Logger logger = Logger.getLogger(GeometryJSONDeserializer.class.getName());

	@Override
	public Geometry deserialize(final JsonParser parser, final DeserializationContext context) throws IOException,
			JsonProcessingException
	{
		try
		{
			return new WKTReader().read(parser.getText());
		}
		catch (final Exception e)
		{
			logger.log(Level.SEVERE, e.getMessage(), e);
			return null;
		}
	}
}

Use null geometry if parsing geometry fails


/*******************************************************************************
 * Copyright (c) 2004, 2008 Tasktop Technologies and others.
 * 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:
 *     Tasktop Technologies - initial API and implementation
 *******************************************************************************/

package org.eclipse.mylyn.ide.tests;

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

import org.eclipse.mylyn.internal.ide.ui.TaskTemplateVariableResolver;

/**
 * @author Mik Kersten
 */
public class AllIdeTests {

	public static Test suite() {
		TestSuite suite = new TestSuite("Test for org.eclipse.mylyn.ide.tests");
		suite.addTestSuite(OpenCorrespondingTaskActionTest.class);
		suite.addTestSuite(IdeStartupTest.class);
		suite.addTestSuite(IdePreferencesTest.class);
		suite.addTestSuite(TaskTemplateVariableResolver.class);
		return suite;
	}
}

/*******************************************************************************
 * Copyright (c) 2004, 2008 Tasktop Technologies and others.
 * 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:
 *     Tasktop Technologies - initial API and implementation
 *******************************************************************************/

package org.eclipse.mylyn.ide.tests;

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

/**
 * @author Mik Kersten
 */
public class AllIdeTests {

	public static Test suite() {
		TestSuite suite = new TestSuite("Test for org.eclipse.mylyn.ide.tests");
		suite.addTestSuite(OpenCorrespondingTaskActionTest.class);
		suite.addTestSuite(IdeStartupTest.class);
		suite.addTestSuite(IdePreferencesTest.class);
		suite.addTestSuite(TaskTemplateResolverTest.class);
		return suite;
	}
}

Fix Error: The method addTestSuite(Class<? extends TestCase>) in the type TestSuite is not applicable for the arguments (Class<TaskTemplateVariableResolver>)

TaskTemplateVariableResolver is now TaskTemplateResolverTest


/*
 * 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 net.aethersanctum.lilrest.server;

import org.skife.config.Config;
import org.skife.config.Default;
import org.skife.config.TimeSpan;

/**
 */
public interface JaxRsServerConfig {
    @Config("basic.server.listen-port")
    @Default("8081")
    int port();

    @Config("basic.server.max-threads")
    @Default("500")
    int maxThreads();

    @Config("basic.server.idle-timeout")
    @Default("30000ms")
    TimeSpan idleTimeout();
}

/*
 * 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 net.aethersanctum.lilrest.server;

import org.skife.config.Config;
import org.skife.config.Default;
import org.skife.config.TimeSpan;

/**
 */
public interface JaxRsServerConfig {
    @Config("basic.server.listen-port")
    @Default("8080")
    int port();

    @Config("basic.server.max-threads")
    @Default("500")
    int maxThreads();

    @Config("basic.server.idle-timeout")
    @Default("30000ms")
    TimeSpan idleTimeout();
}

Revert "update default test server port to 8081"

This reverts commit 4e784e0252201b7890a8a6749dda8b8fa68e33d9. Which
broke the tests because their port numbers weren't updated too. And
there was no real need to make this change in the first place.


package com.github.sormuras.bach.core;

import com.github.sormuras.bach.Bach;
import com.github.sormuras.bach.ToolOperator;
import com.github.sormuras.bach.internal.ArgumentsParser;
import com.github.sormuras.bach.internal.PathSupport;
import java.io.PrintWriter;
import java.nio.file.Path;
import java.util.Optional;

public class Checksum implements ToolOperator {
  public record Arguments(Path file, Optional<String> algorithm, Optional<String> expected) {}

  @Override
  public int run(Bach bach, PrintWriter out, PrintWriter err, String... args) {
    var arguments = ArgumentsParser.create(Arguments.class).parse(args);
    var path = arguments.file();
    var algorithm = arguments.algorithm().orElse("SHA-256");
    var computed = PathSupport.computeChecksum(path, algorithm);
    if (arguments.expected().isEmpty()) {
      out.printf("%s %s%n", computed, path);
      return 0;
    }
    var expected = arguments.expected().get();
    if (computed.equalsIgnoreCase(expected)) return 0;
    err.printf(
        """
        Checksum mismatch detected!
               path: %s
          algorithm: %s
           computed: %s
           expected: %s
        """,
        path, algorithm, computed, expected);
    return 2;
  }
}

package com.github.sormuras.bach.core;

import com.github.sormuras.bach.internal.ArgumentsParser;
import com.github.sormuras.bach.internal.PathSupport;
import java.io.PrintWriter;
import java.nio.file.Path;
import java.util.Optional;
import java.util.spi.ToolProvider;

public class Checksum implements ToolProvider {
  public record Arguments(Path file, Optional<String> algorithm, Optional<String> expected) {}

  @Override
  public String name() {
    return "checksum";
  }

  @Override
  public int run(PrintWriter out, PrintWriter err, String... args) {
    var arguments = ArgumentsParser.create(Arguments.class).parse(args);
    var path = arguments.file();
    var algorithm = arguments.algorithm().orElse("SHA-256");
    var computed = PathSupport.computeChecksum(path, algorithm);
    if (arguments.expected().isEmpty()) {
      out.printf("%s %s%n", computed, path);
      return 0;
    }
    var expected = arguments.expected().get();
    if (computed.equalsIgnoreCase(expected)) return 0;
    err.printf(
        """
        Checksum mismatch detected!
               path: %s
          algorithm: %s
           computed: %s
           expected: %s
        """,
        path, algorithm, computed, expected);
    return 2;
  }
}

Reduce dependencies of `checksum` tool

Reduce dependencies of `checksum` tool


package in.twizmwaz.cardinal.module.modules.blitz;

import in.twizmwaz.cardinal.match.Match;
import in.twizmwaz.cardinal.module.ModuleBuilder;
import in.twizmwaz.cardinal.module.ModuleCollection;
import in.twizmwaz.cardinal.util.TimeUtils;
import org.jdom2.Element;

public class BlitzBuilder implements ModuleBuilder {

    public ModuleCollection load(Match match) {
        ModuleCollection result = new ModuleCollection();
        for (Element element : match.getDocument().getRootElement().getChildren("blitz")) {
            boolean broadcastLives = false;
            if (element.getChild("broadcastLives").getText() != null) {
                broadcastLives = Boolean.parseBoolean(element.getChild("broadcastLives").getText());
            }
            int lives = 1;
            if (element.getChild("lives").getText() != null) {
                lives = Integer.parseInt(element.getChild("lives").getText());
            }
            int time = 0;
            if (element.getChild("time").getText() != null) {
                time = TimeUtils.timePeriodsToSeconds(element.getChild("time").getText());
            }
            String title = null;
            if (element.getChild("title").getText() != null) {
                title = element.getChild("title").getText();
            }
            result.add(new Blitz(title, broadcastLives, lives, time));
        }
        return result;
    }

}

package in.twizmwaz.cardinal.module.modules.blitz;

import in.twizmwaz.cardinal.match.Match;
import in.twizmwaz.cardinal.module.ModuleBuilder;
import in.twizmwaz.cardinal.module.ModuleCollection;
import in.twizmwaz.cardinal.util.TimeUtils;
import org.jdom2.Element;

public class BlitzBuilder implements ModuleBuilder {

    public ModuleCollection load(Match match) {
        ModuleCollection<Blitz> result = new ModuleCollection<Blitz>();
        for (Element element : match.getDocument().getRootElement().getChildren("blitz")) {
            boolean broadcastLives = element.getChild("broadcastLives") != null && Boolean.parseBoolean(element.getChild("broadcastLives").getText());
            int lives = element.getChild("lives") == null ? 1 : Integer.parseInt(element.getChild("lives").getText());
            int time = element.getChild("time") == null ? 0 : TimeUtils.timePeriodsToSeconds(element.getChild("time").getText());
            String title = element.getChildText("title");
            result.add(new Blitz(title, broadcastLives, lives, time));
        }
        return result;
    }

}

Fix an NPEs when elements are not present


package nl.r0b3rtk.jmoribus.spring;

public class SpringRunner {

}

package nl.r0b3rtk.jmoribus.spring;

public class SpringRunner {

    public SpringRunner()
    {
        // default constructor
    }
}

Add default constructor to test Travis

Add default constructor to test Travis


package org.lodder.subtools.subsort.lib.control;

import java.io.File;
import java.util.List;

import org.lodder.subtools.sublibrary.Manager;
import org.lodder.subtools.sublibrary.exception.ControlFactoryException;
import org.lodder.subtools.sublibrary.exception.ReleaseControlException;
import org.lodder.subtools.sublibrary.exception.ReleaseParseException;
import org.lodder.subtools.sublibrary.logging.Logger;
import org.lodder.subtools.sublibrary.model.Release;
import org.lodder.subtools.sublibrary.settings.model.MappingTvdbScene;

public class VideoFileFactory {

  public static Release get(final File file, List<MappingTvdbScene> dict, Manager manager) throws ControlFactoryException, ReleaseParseException, ReleaseControlException {
		Logger.instance.trace("VideoFileFactory", "get", "");
    VideoFileControl vfc = VideoFileControlFactory.getController(file, manager);
    Release release = null;
		if (vfc instanceof EpisodeFileControl) {
			release = vfc.process(dict);
		} else if (vfc instanceof MovieFileControl) {
			release = vfc.process(dict);
		}
		return release;
	}

}

package org.lodder.subtools.subsort.lib.control;

import java.io.File;
import java.util.List;

import org.lodder.subtools.sublibrary.Manager;
import org.lodder.subtools.sublibrary.exception.ControlFactoryException;
import org.lodder.subtools.sublibrary.exception.ReleaseControlException;
import org.lodder.subtools.sublibrary.exception.ReleaseParseException;
import org.lodder.subtools.sublibrary.model.Release;
import org.lodder.subtools.sublibrary.settings.model.MappingTvdbScene;

public class VideoFileFactory {

  public static Release get(final File file, List<MappingTvdbScene> dict, Manager manager) throws ControlFactoryException, ReleaseParseException, ReleaseControlException {
    VideoFileControl vfc = VideoFileControlFactory.getController(file, manager);
    Release release = null;
		if (vfc instanceof EpisodeFileControl) {
			release = vfc.process(dict);
		} else if (vfc instanceof MovieFileControl) {
			release = vfc.process(dict);
		}
		return release;
	}

}

Remove logging, no usefull info

Remove logging, no usefull info


package com.kickstarter.libs.utils;

import com.kickstarter.factories.CategoryFactory;
import com.kickstarter.factories.LocationFactory;
import com.kickstarter.libs.RefTag;
import com.kickstarter.services.DiscoveryParams;

import junit.framework.TestCase;

import static com.kickstarter.libs.utils.DiscoveryParamsUtils.refTag;

public class DiscoveryParamsUtilsTest extends TestCase {

  public void testRefTag() {
    assertEquals(
      refTag(DiscoveryParams.builder().category(CategoryFactory.artCategory()).build()),
      RefTag.category()
    );

    assertEquals(
      refTag(DiscoveryParams.builder().category(CategoryFactory.artCategory()).sort(DiscoveryParams.Sort.POPULAR).build()),
      RefTag.category(DiscoveryParams.Sort.POPULAR)
    );

    assertEquals(
      refTag(DiscoveryParams.builder().location(LocationFactory.germany()).build()),
      RefTag.city()
    );

    assertEquals(
      refTag(DiscoveryParams.builder().staffPicks(true).build()),
      RefTag.recommended()
    );

    assertEquals(
      refTag(DiscoveryParams.builder().staffPicks(true).sort(DiscoveryParams.Sort.POPULAR).build()),
      RefTag.recommended(DiscoveryParams.Sort.POPULAR)
    );

    assertEquals(
      refTag(DiscoveryParams.builder().social(1).build()),
      RefTag.social()
    );

    assertEquals(
      refTag(DiscoveryParams.builder().term("art").build()),
      RefTag.search()
    );

    assertEquals(
      refTag(DiscoveryParams.builder().build()),
      RefTag.discovery()
    );
  }
}

package com.kickstarter.libs.utils;

import com.kickstarter.factories.CategoryFactory;
import com.kickstarter.factories.LocationFactory;
import com.kickstarter.libs.RefTag;
import com.kickstarter.services.DiscoveryParams;

import junit.framework.TestCase;

public class DiscoveryParamsUtilsTest extends TestCase {

  public void testRefTag() {
    assertEquals(
      DiscoveryParamsUtils.refTag(DiscoveryParams.builder().category(CategoryFactory.artCategory()).build()),
      RefTag.category()
    );

    assertEquals(
      DiscoveryParamsUtils.refTag(DiscoveryParams.builder()
        .category(CategoryFactory.artCategory())
        .sort(DiscoveryParams.Sort.POPULAR)
        .build()),
      RefTag.category(DiscoveryParams.Sort.POPULAR)
    );

    assertEquals(
      DiscoveryParamsUtils.refTag(DiscoveryParams.builder().location(LocationFactory.germany()).build()),
      RefTag.city()
    );

    assertEquals(
      DiscoveryParamsUtils.refTag(DiscoveryParams.builder().staffPicks(true).build()),
      RefTag.recommended()
    );

    assertEquals(
      DiscoveryParamsUtils.refTag(DiscoveryParams.builder().staffPicks(true).sort(DiscoveryParams.Sort.POPULAR).build()),
      RefTag.recommended(DiscoveryParams.Sort.POPULAR)
    );

    assertEquals(
      DiscoveryParamsUtils.refTag(DiscoveryParams.builder().social(1).build()),
      RefTag.social()
    );

    assertEquals(
      DiscoveryParamsUtils.refTag(DiscoveryParams.builder().term("art").build()),
      RefTag.search()
    );

    assertEquals(
      DiscoveryParamsUtils.refTag(DiscoveryParams.builder().build()),
      RefTag.discovery()
    );
  }
}

Remove static import in this test.

Remove static import in this test.


package me.dilek.izlek.domain;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;

public class SeasonCollection implements Iterable<Season>, Serializable {

    private static final long serialVersionUID = -4364084422273324469L;

    private final List<Season> seasons;

    public SeasonCollection() {
        this.seasons = new ArrayList<>();
    }

    @SuppressWarnings("unchecked")
    public Collection<Season> getSeasons() {
        return (Collection<Season>) ((ArrayList<Season>) seasons).clone();
    }

    public void add(Season season) {
        this.seasons.add(season);
    }

    @Override
    public Iterator<Season> iterator() {
        return seasons.iterator();
    }

    public void addEpisode(int season, int episode, String title,
                           String publishDate) {
        while (seasons.size() < season - 1) {
            seasons.add(new Season(seasons.size() + 1));
        }
        Season s = seasons.get(season - 1);
        s.addEpisode(episode, title, publishDate);
    }
}

package me.dilek.izlek.domain;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;

public class SeasonCollection implements Iterable<Season>, Serializable {

    private static final long serialVersionUID = -4364084422273324469L;

    private final List<Season> seasons;

    public SeasonCollection() {
        this.seasons = new ArrayList<>();
    }

    @SuppressWarnings("unchecked")
    public Collection<Season> getSeasons() {
        return (Collection<Season>) ((ArrayList<Season>) seasons).clone();
    }

    public void add(Season season) {
        this.seasons.add(season);
    }

    @Override
    public Iterator<Season> iterator() {
        return seasons.iterator();
    }

    public void addEpisode(int season, int episode, String title,
                           String publishDate) {
        while (seasons.size() < season) {
            seasons.add(new Season(season));
        }
        Season s = seasons.get(season - 1);
        s.addEpisode(episode, title, publishDate);
    }
}

Fix a trivial indexing issue

Fix a trivial indexing issue