/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package serverapp;

import java.util.StringTokenizer;
import Hardware.windmill;

/**
 *
 * @author André
 */
public class DeviceLib {

    private windmill lib;

    public DeviceLib() {
        //AULA 3 - inicializar as lib
        lib = new windmill();
    }

    protected String callHardware(String content) {

        String reply = null;
        StringTokenizer st = new StringTokenizer(content, utilities.constants.token);
        String operation = st.nextToken();
        if (operation.equals("ChangeState")) {
            // AULA 3 - Chamar a DLL para mudar o estado
            int state = Integer.parseInt(st.nextToken());
            String error=lib.errorString();
            System.err.println(error);            //Deve desaparecer
        }
        //Aula 3 - Esta parte deve ser removida e a chamada à DLL deve ser feita aqui
        System.err.println("ERROR: Impossible to collect data");                //Deve desaparecer
        reply = "-1" + utilities.constants.token +                              //Deve desaparecer
                "-1" + utilities.constants.token +                              //Deve desaparecer
                "-1" + utilities.constants.token;                               //Deve desaparecer
        return reply;
    }
}

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package serverapp;

import java.util.StringTokenizer;
import Hardware.windmill;

/**
 *
 * @author André
 */
public class DeviceLib {

    private windmill lib;

    public DeviceLib() {
        //AULA 3 - inicializar as lib
        lib = new windmill();
    }

    protected String callHardware(String content) {

        String reply = null;
        StringTokenizer st = new StringTokenizer(content, utilities.constants.token);
        String operation = st.nextToken();
        if (operation.equals("ChangeState")) {
            // AULA 3 - Chamar a DLL para mudar o estado
            int state = Integer.parseInt(st.nextToken());
            int rval = lib.turn_on(state);
            if(rval==0){
                System.err.println("System was already in pretended state!");
            }
        }
        //Aula 3 - Esta parte deve ser removida e a chamada à DLL deve ser feita aqui
        //System.err.println("ERROR: Impossible to collect data");
        int isOn=lib.is_on();
        float power = lib.energy_production();
        String err = lib.errorString();
        reply = isOn + utilities.constants.token +                              //Deve desaparecer
                power + utilities.constants.token +                              //Deve desaparecer
                err + utilities.constants.token;                               //Deve desaparecer
        return reply;
    }
}

Update ServerApp :+1: :rocket: ->18

Update ServerApp :+1:  :rocket: ->18


/*
 * 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.jackrabbit.core.observation;

import javax.jcr.observation.EventListener;

/**
 * Defines a marker interface for {@link javax.jcr.observation.EventListener}
 * implementations that wish a synchronous notification of changes to the
 * workspace. That is, a SynchronousEventListener is called before
 * the call to {@link javax.jcr.Item#save()} returns. In contrast, a regular
 * {@link javax.jcr.observation.EventListener} might be called after
 * save() returns.
 */
public interface SynchronousEventListener extends EventListener {
}

/*
 * 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.jackrabbit.core.observation;

import javax.jcr.observation.EventIterator;
import javax.jcr.observation.EventListener;

/**
 * Defines a marker interface for {@link javax.jcr.observation.EventListener}
 * implementations that wish a synchronous notification of changes to the
 * workspace. That is, a SynchronousEventListener is called before
 * the call to {@link javax.jcr.Item#save()} returns. In contrast, a regular
 * {@link javax.jcr.observation.EventListener} might be called after
 * save() returns.
 *

 * Important note: an implementation of {@link SynchronousEventListener}
 * must not modify content with the thread that calls {@link
 * #onEvent(EventIterator)} otherwise inconsistencies may occur.
 */
public interface SynchronousEventListener extends EventListener {
}

JCR-2357: Duplicate entries in the index
- javadoc

git-svn-id: 02b679d096242155780e1604e997947d154ee04a@828343 13f79535-47bb-0310-9956-ffa450edef68


package org.jboss.shamrock.security;

import java.util.List;

import org.jboss.builder.item.MultiBuildItem;
import org.jboss.shamrock.runtime.RuntimeValue;

/**
 * Information about an authentication mechanism to enable. This is used to call the
 * {@linkplain SecurityTemplate#configureUndertowIdentityManager(RuntimeValue, List)} method to register the auth methods
 * enabled.
 *
 * Custom authentication mechanisms would need to have the {@linkplain io.undertow.servlet.ServletExtension} that
 * registers the {@linkplain io.undertow.security.api.AuthenticationMechanismFactory} for the method.
 */
public final class AuthConfigBuildItem extends MultiBuildItem {
    private AuthConfig authConfig;

    public AuthConfigBuildItem(AuthConfig authConfig) {
        this.authConfig = authConfig;
    }

    public AuthConfig getAuthConfig() {
        return authConfig;
    }
}

package org.jboss.shamrock.security;

import java.util.List;

import org.jboss.builder.item.MultiBuildItem;
import org.jboss.shamrock.runtime.RuntimeValue;

/**
 * Information about an authentication mechanism to enable. This is used to call the
 * {@linkplain SecurityTemplate#configureUndertowIdentityManager(RuntimeValue, List)} method to register the auth methods
 * enabled.
 *
 * Custom authentication mechanisms would need to have the {@linkplain io.undertow.servlet.ServletExtension} that
 * registers the {@linkplain io.undertow.security.api.AuthenticationMechanismFactory} for the method.
 */
public final class AuthConfigBuildItem extends MultiBuildItem {
    private final AuthConfig authConfig;

    public AuthConfigBuildItem(AuthConfig authConfig) {
        this.authConfig = authConfig;
    }

    public AuthConfig getAuthConfig() {
        return authConfig;
    }
}

Make the authConfig field final.

Make the authConfig field final.


package server.threads;

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

import util.match.Match;
import util.statemachine.Move;

public final class RandomPlayRequestThread extends PlayRequestThread
{
	private Move move;

	public RandomPlayRequestThread(Match match, List<Move> legalMoves)
	{
		super(null, match, null, null, null, null, 0, null, true);
		move = legalMoves.get(new Random().nextInt(legalMoves.size()));
	}

	@Override
	public Move getMove()
	{
		return move;
	}

	@Override
	public void run()
	{
		;
	}
}

package server.threads;

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

import util.match.Match;
import util.statemachine.Move;

public final class RandomPlayRequestThread extends PlayRequestThread
{
	private Move move;

	public RandomPlayRequestThread(Match match, List<Move> legalMoves)
	{
		super(null, match, null, legalMoves, null, null, 0, null, true);
		move = legalMoves.get(new Random().nextInt(legalMoves.size()));
	}

	@Override
	public Move getMove()
	{
		return move;
	}

	@Override
	public void run()
	{
		;
	}
}

Fix another bug with the random play request thread initialization.

git-svn-id: 4739e81c2fe647bfb539b919360e2c658e6121ea@501 716a755e-b13f-cedc-210d-596dafc6fb9b


package uk.ac.ebi.atlas.search.analyticsindex.baseline;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import org.springframework.web.client.RestTemplate;

import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertThat;

@RunWith(MockitoJUnitRunner.class)
public class BaselineAnalyticsSearchDaoTest {

    private static final String SOLR_BASE_URL = "http://TEST";
    private static final String JSON_FACET = "{}";

    @Mock
    private RestTemplate restTemplate;

    private final BaselineAnalyticsSearchDao subject = new BaselineAnalyticsSearchDao(restTemplate, SOLR_BASE_URL, JSON_FACET);

    @Test
    public void buildQueryParameters() {
        assertThat(subject.buildQueryParameters("identifierSearch:ENSG00000126549", 0.5, 0), is("query?q=identifierSearch:ENSG00000126549&rows=0&omitHeader=true&fq=expressionLevel:%5B0.5%20TO%20*%5D"));
    }

}

package uk.ac.ebi.atlas.search.analyticsindex.baseline;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import org.springframework.web.client.RestTemplate;

import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertThat;

@RunWith(MockitoJUnitRunner.class)
public class BaselineAnalyticsSearchDaoTest {

    private static final String SOLR_BASE_URL = "http://TEST";
    private static final String JSON_FACET = "{}";

    @Mock
    private RestTemplate restTemplate;

    private final BaselineAnalyticsSearchDao subject = new BaselineAnalyticsSearchDao(restTemplate, SOLR_BASE_URL, JSON_FACET);

    @Test
    public void buildQueryParameters() {
        assertThat(subject.buildQueryParameters("identifierSearch:ENSG00000126549", 0.5, 0), is("query?q=identifierSearch:ENSG00000126549&rows=0&omitHeader=true&fq=(experimentType:rnaseq_mrna_baseline%20AND%20expressionLevel:%5B0.5%20TO%20*%5D)%20OR%20(experimentType:proteomics_baseline%20AND%20expressionLevel:%5B0%20TO%20*%5D)"));
    }

}

Fix unit test after adding separate baseline/proteomics filtering


package org.jaxen.javabean;

import junit.framework.TestCase;

public class DocumentNavigatorTest
    extends TestCase
{

    public void testNothing()
        throws Exception
    {
        JavaBeanXPath xpath = new JavaBeanXPath( "brother[position()<4]/name" );

        Person bob = new Person( "bob", 30 );

        bob.addBrother( new Person( "billy", 34 ) );
        bob.addBrother( new Person( "seth", 29 ) );
        bob.addBrother( new Person( "dave", 32 ) );
        bob.addBrother( new Person( "jim", 29 ) );
        bob.addBrother( new Person( "larry", 42 ) );
        bob.addBrother( new Person( "ted", 22 ) );

        System.err.println( xpath.evaluate( bob ) );
    }

}

package org.jaxen.javabean;

import junit.framework.TestCase;
import org.jaxen.saxpath.helpers.XPathReaderFactory;

public class DocumentNavigatorTest
    extends TestCase
{

    protected void setUp() throws Exception
    {
        System.setProperty( XPathReaderFactory.DRIVER_PROPERTY,
                            "" );
    }

    public void testNothing()
        throws Exception
    {
        JavaBeanXPath xpath = new JavaBeanXPath( "brother[position()<4]/name" );

        Person bob = new Person( "bob", 30 );

        bob.addBrother( new Person( "billy", 34 ) );
        bob.addBrother( new Person( "seth", 29 ) );
        bob.addBrother( new Person( "dave", 32 ) );
        bob.addBrother( new Person( "jim", 29 ) );
        bob.addBrother( new Person( "larry", 42 ) );
        bob.addBrother( new Person( "ted", 22 ) );

        System.err.println( xpath.evaluate( bob ) );
    }

}

Set property in case it has been set wrong previously

git-svn-id: 7abf240ce0ec4644a9bf59262a41ad5796234f37@372 43379f7c-b030-0410-81db-e0b70742847c


package me.duncte123.skybot.commands;

import me.duncte123.skybot.Command;
import me.duncte123.skybot.utils.HelpEmbeds;
import net.dv8tion.jda.core.events.message.MessageReceivedEvent;

public class HelpCommand extends Command {

    public final static String help = "shows a list of all the commands.";

    @Override
    public boolean called(String[] args, MessageReceivedEvent event) {
        // TODO Auto-generated method stub
        return true;
    }

    @Override
    public void action(String[] args, MessageReceivedEvent event) {

        event.getAuthor().openPrivateChannel().queue( (pc) -> {
            event.getTextChannel().sendMessage(event.getMember().getAsMention() +" check your DM's").queue();
            pc.sendMessage(HelpEmbeds.mainCommands).queue();
            pc.sendMessage(HelpEmbeds.musicCommands).queue();
            pc.sendMessage(HelpEmbeds.funCommands).queue();
            pc.sendMessage(HelpEmbeds.modCommands).queue();
        },
                err -> event.getChannel().sendMessage("ERROR: " + err.getMessage()).queue() );
    }

    @Override
    public String help() {
        // TODO Auto-generated method stub
        return help;
    }
}

package me.duncte123.skybot.commands;

import me.duncte123.skybot.Command;
import me.duncte123.skybot.utils.HelpEmbeds;
import net.dv8tion.jda.core.entities.TextChannel;
import net.dv8tion.jda.core.events.message.MessageReceivedEvent;

public class HelpCommand extends Command {

    public final static String help = "shows a list of all the commands.";

    @Override
    public boolean called(String[] args, MessageReceivedEvent event) {
        // TODO Auto-generated method stub
        return true;
    }

    @Override
    public void action(String[] args, MessageReceivedEvent event) {

        event.getAuthor().openPrivateChannel().queue( (pc) -> {
            pc.sendMessage(HelpEmbeds.mainCommands).queue( msg -> {
                        pc.sendMessage(HelpEmbeds.musicCommands).queue();
                        pc.sendMessage(HelpEmbeds.funCommands).queue();
                        pc.sendMessage(HelpEmbeds.modCommands).queue();
                        event.getTextChannel().sendMessage(event.getMember().getAsMention() +" check your DM's").queue();
                    },
                    //When sending fails, send to the channel
                    err -> {
                        TextChannel currentChann = event.getTextChannel();
                        currentChann.sendMessage(HelpEmbeds.mainCommands).queue();
                        currentChann.sendMessage(HelpEmbeds.musicCommands).queue();
                        currentChann.sendMessage(HelpEmbeds.funCommands).queue();
                        currentChann.sendMessage(HelpEmbeds.modCommands).queue();
                        currentChann.sendMessage("Message could not be delivered to dm's and has been send in this channel.").queue();
                    }
            );
        },
                err -> event.getChannel().sendMessage("ERROR: " + err.getMessage()).queue()
        );
    }

    @Override
    public String help() {
        // TODO Auto-generated method stub
        return help;
    }
}

Create failover for if the helpmessage fails to send


package info.bitrich.xchangestream.bitfinex.dto;

import com.fasterxml.jackson.annotation.JsonFormat;
import org.knowm.xchange.bitfinex.v1.dto.marketdata.BitfinexTrade;

import java.math.BigDecimal;

/**
 * Created by Lukas Zaoralek on 7.11.17.
 */
@JsonFormat(shape = JsonFormat.Shape.ARRAY)
public class BitfinexWebSocketTrade {
    public long tradeId;
    public long timestamp;
    public BigDecimal amount;
    public BigDecimal price;

    public BitfinexWebSocketTrade() {
    }

    public BitfinexWebSocketTrade(long tradeId, long timestamp, BigDecimal amount, BigDecimal price) {
        this.tradeId = tradeId;
        this.timestamp = timestamp;
        this.amount = amount;
        this.price = price;
    }

    public long getTradeId() {
        return tradeId;
    }

    public long getTimestamp() {
        return timestamp;
    }

    public BigDecimal getAmount() {
        return amount;
    }

    public BigDecimal getPrice() {
        return price;
    }

    public BitfinexTrade toBitfinexTrade() {
        String type;
        if (amount.compareTo(BigDecimal.ZERO) < 0) {
            type = "sell";
        } else {
            type = "buy";
        }

        return new BitfinexTrade(price, amount, timestamp / 1000, "bitfinex", tradeId, type);
    }
}

package info.bitrich.xchangestream.bitfinex.dto;

import com.fasterxml.jackson.annotation.JsonFormat;
import org.knowm.xchange.bitfinex.v1.dto.marketdata.BitfinexTrade;

import java.math.BigDecimal;

/**
 * Created by Lukas Zaoralek on 7.11.17.
 */
@JsonFormat(shape = JsonFormat.Shape.ARRAY)
public class BitfinexWebSocketTrade {
    public long tradeId;
    public long timestamp;
    public BigDecimal amount;
    public BigDecimal price;

    public BitfinexWebSocketTrade() {
    }

    public BitfinexWebSocketTrade(long tradeId, long timestamp, BigDecimal amount, BigDecimal price) {
        this.tradeId = tradeId;
        this.timestamp = timestamp;
        this.amount = amount;
        this.price = price;
    }

    public long getTradeId() {
        return tradeId;
    }

    public long getTimestamp() {
        return timestamp;
    }

    public BigDecimal getAmount() {
        return amount;
    }

    public BigDecimal getPrice() {
        return price;
    }

    public BitfinexTrade toBitfinexTrade() {
        String type;
        if (amount.compareTo(BigDecimal.ZERO) < 0) {
            type = "sell";
        } else {
            type = "buy";
        }
        return new BitfinexTrade(price, amount.abs(), timestamp / 1000, "bitfinex", tradeId, type);
    }
}

Fix trade signs on Bitfinex * Trades from all other exchanges are presented with positive amounts (with the trade type indicating direction). On Bitfinex, sells were arriving negative and buys positive.


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

package org.springframework.boot.actuate.autoconfigure;

import org.springframework.boot.actuate.endpoint.jmx.EndpointMBeanExporter;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jmx.export.MBeanExporter;

@Configuration
@ConditionalOnBean({ MBeanExporter.class })
@AutoConfigureAfter({ EndpointAutoConfiguration.class })
class EndpointMBeanExportAutoConfiguration {

	@Bean
	public EndpointMBeanExporter endpointMBeanExporter() {
		return new EndpointMBeanExporter();
	}

}

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

package org.springframework.boot.actuate.autoconfigure;

import org.springframework.boot.actuate.endpoint.Endpoint;
import org.springframework.boot.actuate.endpoint.jmx.EndpointMBeanExporter;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnExpression;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jmx.export.MBeanExporter;

/**
 * {@link EnableAutoConfiguration Auto-configuration} to enable JMX export for
 * {@link Endpoint}s.
 *
 * @author Christian Dupuis
 */
@Configuration
@ConditionalOnBean({ MBeanExporter.class })
@AutoConfigureAfter({ EndpointAutoConfiguration.class })
@ConditionalOnExpression("${endpoints.jmx.enabled:true}")
class EndpointMBeanExportAutoConfiguration {

	@Bean
	public EndpointMBeanExporter endpointMBeanExporter() {
		// TODO add configuration for domain name
		return new EndpointMBeanExporter();
	}

}

Allow Endpoint JMX export to be switched off


package com.peterphi.std.guice.common.serviceprops.net;

import com.google.inject.AbstractModule;

public class NetworkConfigReloadModule extends AbstractModule
{
	@Override
	protected void configure()
	{
		bind(NetworkConfigReloadDaemon.class).asEagerSingleton();
	}
}

package com.peterphi.std.guice.common.serviceprops.net;

import com.google.inject.AbstractModule;
import com.google.inject.Provides;
import com.google.inject.Singleton;
import com.peterphi.std.guice.config.rest.iface.ConfigRestService;
import com.peterphi.std.guice.restclient.JAXRSProxyClientFactory;

public class NetworkConfigReloadModule extends AbstractModule
{
	@Override
	protected void configure()
	{
		bind(NetworkConfigReloadDaemon.class).asEagerSingleton();
	}

	@Provides
	@Singleton
	public ConfigRestService getConfigService(JAXRSProxyClientFactory factory)
	{
		return factory.getClient(ConfigRestService.class);
	}
}

Add explicit jax-rs client provider for ConfigRestService so that scan.packages doesn't have to include ConfigRestService


package org.openscore.lang.tools.build.tester.parse;

import java.io.Serializable;
import java.util.Map;

/**
 * Created by stoneo on 3/15/2015.
 **/
public class SlangTestCase {

    private final String description;

    private final String testSuits;

    private final String systemPropertiesFile;

    private final Map<String, Serializable> inputs;

    private final Boolean throwsException;

    private final String result;

    public SlangTestCase(String description, String testSuits, String systemPropertiesFile,
                         Map<String, Serializable> inputs, Boolean throwsException, String result){
        this.description = description;
        this.testSuits = testSuits;
        this.systemPropertiesFile = systemPropertiesFile;
        this.inputs = inputs;
        this.throwsException = throwsException;
        this.result = result;
    }

    public String getDescription() {
        return description;
    }

    public String getTestSuits() {
        return testSuits;
    }

    public String getSystemPropertiesFile() {
        return systemPropertiesFile;
    }

    public Map<String, Serializable> getInputs() {
        return inputs;
    }

    public Boolean getThrowsException() {
        return throwsException;
    }

    public String getResult() {
        return result;
    }
}

package org.openscore.lang.tools.build.tester.parse;

import org.apache.commons.collections4.CollectionUtils;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Created by stoneo on 3/15/2015.
 **/
public class SlangTestCase {

    private final String description;

    private final List<String> testSuits;

    private final String systemPropertiesFile;

    private final Map<String, Serializable> inputs;

    private final Boolean throwsException;

    private final String result;

    public static final String BASE_TEST_SUITE = "base";

    public SlangTestCase(String description, List<String> testSuits, String systemPropertiesFile,
                         Map<String, Serializable> inputs, Boolean throwsException, String result){
        this.description = description;
        this.systemPropertiesFile = systemPropertiesFile;
        if(CollectionUtils.isEmpty(testSuits)){
            this.testSuits = new ArrayList<>();
            this.testSuits.add(BASE_TEST_SUITE);
        } else {
            this.testSuits = testSuits;
        }
        this.inputs = inputs;
        this.throwsException = throwsException;
        this.result = result;
    }

    public String getDescription() {
        return description;
    }

    public List<String> getTestSuits() {
        return testSuits;
    }

    public String getSystemPropertiesFile() {
        return systemPropertiesFile;
    }

    public Map<String, Serializable> getInputs() {
        return inputs;
    }

    public Boolean getThrowsException() {
        return throwsException;
    }

    public String getResult() {
        return result;
    }
}

Change testSuites to be a list with default value

Signed-off-by: Orit Stone <530a3c863b274210fbf305df5a70e325b4dbcb5a@hp.com>


package fixtures.azurespecials;

import com.microsoft.rest.ServiceResponse;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;

public class HeaderOperationsTests {
    private static AutoRestAzureSpecialParametersTestClient client;

    @BeforeClass
    public static void setup() {
        client = new AutoRestAzureSpecialParametersTestClientImpl("http://localhost.:3000");
    }

    @Test
    public void customNamedRequestId() throws Exception {
        ServiceResponse<Void> response = client.getHeaderOperations().customNamedRequestId("9C4D50EE-2D56-4CD3-8152-34347DC9F2B0");
        Assert.assertEquals(200, response.getResponse().code());
    }
}

package fixtures.azurespecials;

import com.microsoft.rest.ServiceResponseWithHeaders;
import fixtures.azurespecials.models.HeaderCustomNamedRequestIdHeaders;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;

public class HeaderOperationsTests {
    private static AutoRestAzureSpecialParametersTestClient client;

    @BeforeClass
    public static void setup() {
        client = new AutoRestAzureSpecialParametersTestClientImpl("http://localhost.:3000");
    }

    @Test
    public void customNamedRequestId() throws Exception {
        ServiceResponseWithHeaders<Void, HeaderCustomNamedRequestIdHeaders> response = client.getHeaderOperations().customNamedRequestId("9C4D50EE-2D56-4CD3-8152-34347DC9F2B0");
        Assert.assertEquals(200, response.getResponse().code());
        Assert.assertEquals("123", response.getHeaders().getFooRequestId());
    }
}

Add test on response typed headers

Add test on response typed headers


package org.nuxeo.drive.service.impl;

import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;

import org.apache.commons.lang.StringUtils;
import org.nuxeo.ecm.core.api.IdRef;

/**
 * Helper to handle synchronization root definitions.
 *
 * @author Antoine Taillefer
 */
public class RootDefinitionsHelper {

    private RootDefinitionsHelper() {
        // Utility class
    }

    /**
     * Parses the given synchronization root definitions string.
     */
    public static Map<String, Set<IdRef>> parseRootDefinitions(
            String rootDefinitions) {
        Map<String, Set<IdRef>> lastActiveRootRefs = new LinkedHashMap<String, Set<IdRef>>();
        if (rootDefinitions != null) {
            String[] rootDefinitionComponents = StringUtils.split(
                    rootDefinitions, ",");
            for (String rootDefinition : rootDefinitionComponents) {
                String[] rootComponents = StringUtils.split(rootDefinition, ":");
                String repoName = rootComponents[0].trim();
                Set<IdRef> refs = lastActiveRootRefs.get(repoName);
                if (refs == null) {
                    refs = new HashSet<IdRef>();
                    lastActiveRootRefs.put(repoName, refs);
                }
                refs.add(new IdRef(rootComponents[1].trim()));
            }
        }
        return lastActiveRootRefs;
    }

}

package org.nuxeo.drive.service.impl;

import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;

import org.apache.commons.lang.StringUtils;
import org.nuxeo.ecm.core.api.IdRef;

/**
 * Helper to handle synchronization root definitions.
 *
 * @author Antoine Taillefer
 */
public final class RootDefinitionsHelper {

    private RootDefinitionsHelper() {
        // Utility class
    }

    /**
     * Parses the given synchronization root definitions string.
     */
    public static Map<String, Set<IdRef>> parseRootDefinitions(
            String rootDefinitions) {
        Map<String, Set<IdRef>> lastActiveRootRefs = new LinkedHashMap<String, Set<IdRef>>();
        if (rootDefinitions != null) {
            String[] rootDefinitionComponents = StringUtils.split(
                    rootDefinitions, ",");
            for (String rootDefinition : rootDefinitionComponents) {
                String[] rootComponents = StringUtils.split(rootDefinition, ":");
                String repoName = rootComponents[0].trim();
                Set<IdRef> refs = lastActiveRootRefs.get(repoName);
                if (refs == null) {
                    refs = new HashSet<IdRef>();
                    lastActiveRootRefs.put(repoName, refs);
                }
                refs.add(new IdRef(rootComponents[1].trim()));
            }
        }
        return lastActiveRootRefs;
    }

}

Fix Sonar Major violations: Final Class

NXP-11577: Fix Sonar Major violations: Final Class


package org.spoofax.jsglr2.recovery;

import org.metaborg.parsetable.productions.IProduction;
import org.spoofax.jsglr2.messages.Message;
import org.spoofax.jsglr2.messages.SourceRegion;
import org.spoofax.jsglr2.parser.Position;

public class RecoveryMessages {

    public static Message get(IProduction production, Position start, Position end) {
        SourceRegion region = new SourceRegion(start, end);

        String message;

        if("WATER".equals(production.constructor()))
            message = "Not expected";
        else if("INSERTION".equals(production.constructor())) {
            String insertion;

            if (production.isLiteral())
                insertion = production.lhs().descriptor().replaceAll("^\"|\"$", "");
            else
                insertion = "Token";

            message = insertion + " expected";
        } else
            message = "Invalid syntax";

        return Message.error(message, region);
    }

}

package org.spoofax.jsglr2.recovery;

import org.metaborg.parsetable.productions.IProduction;
import org.metaborg.parsetable.symbols.ILiteralSymbol;
import org.spoofax.jsglr2.messages.Message;
import org.spoofax.jsglr2.messages.SourceRegion;
import org.spoofax.jsglr2.parser.Position;

public class RecoveryMessages {

    public static Message get(IProduction production, Position start, Position end) {
        SourceRegion region = new SourceRegion(start, end);

        String message;

        if("WATER".equals(production.constructor()))
            message = "Not expected";
        else if("INSERTION".equals(production.constructor())) {
            String insertion;

            if (production.isLiteral())
                insertion = ((ILiteralSymbol) production.lhs()).literal();
            else
                insertion = "Token";

            message = insertion + " expected";
        } else
            message = "Invalid syntax";

        return Message.error(message, region);
    }

}

Simplify retrieval of literal for insertion recovery messages


package org.spongepowered.server.mixin.core.item.crafting;

import net.minecraft.item.crafting.CraftingManager;
import net.minecraft.item.crafting.IRecipe;
import net.minecraft.util.ResourceLocation;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;

@Mixin(CraftingManager.class)
public abstract class CraftingManagerMixin_Vanilla {

    @Inject(method = "register(Lnet/minecraft/util/ResourceLocation;Lnet/minecraft/item/crafting/IRecipe;)V", at = @At(value = "NEW"), cancellable = true)
    private static void register(final ResourceLocation name, final IRecipe recipe, final CallbackInfo ci) {
        final int id = CraftingManager.REGISTRY.getIDForObject(CraftingManager.REGISTRY.getObject(name));
        CraftingManager.REGISTRY.register(id, name, recipe);
        ci.cancel();
    }

}

package org.spongepowered.server.mixin.core.item.crafting;

import net.minecraft.item.crafting.CraftingManager;
import net.minecraft.item.crafting.IRecipe;
import net.minecraft.util.ResourceLocation;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;

@Mixin(CraftingManager.class)
public abstract class CraftingManagerMixin_Vanilla {

    @Inject(method = "register(Lnet/minecraft/util/ResourceLocation;Lnet/minecraft/item/crafting/IRecipe;)V", at = @At(value = "NEW"), cancellable = true)
    private static void vanilla$register(final ResourceLocation name, final IRecipe recipe, final CallbackInfo ci) {
        final int id = CraftingManager.REGISTRY.getIDForObject(CraftingManager.REGISTRY.getObject(name));
        CraftingManager.REGISTRY.register(id, name, recipe);
        ci.cancel();
    }

}

Update injection name to match new naming scheme


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

import io.github.johardi.r2rmlparser.util.StringUtils;

public class InvalidPropertyAttributeException extends JR2RmlParserRuntimeException
{
   private static final long serialVersionUID = 1681949L;

   private String mPropertyLabel;
   private String mExceptionDetail;

   public InvalidPropertyAttributeException(String propertyLabel)
   {
      mPropertyLabel = propertyLabel;
   }

   public void setExceptionDetail(String detail)
   {
      mExceptionDetail = detail;
   }

   @Override
   public String getMessage()
   {
      StringBuilder sb = new StringBuilder();
      sb.append("Invalid property attribute for");
      sb.append("\"").append(mPropertyLabel).append("\"");
      if (!StringUtils.isEmpty(mExceptionDetail)) {
         sb.append(" ");
         sb.append(mExceptionDetail);
      }
      return sb.toString();
   }
}

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

import io.github.johardi.r2rmlparser.util.StringUtils;

public class InvalidPropertyAttributeException extends JR2RmlParserRuntimeException
{
   private static final long serialVersionUID = 1681949L;

   private String mPropertyLabel;
   private String mExceptionDetail;

   public InvalidPropertyAttributeException(String propertyLabel)
   {
      mPropertyLabel = propertyLabel;
   }

   public void setExceptionDetail(String detail)
   {
      mExceptionDetail = detail;
   }

   @Override
   public String getMessage()
   {
      StringBuilder sb = new StringBuilder();
      sb.append("Invalid property attribute for ");
      sb.append("\"").append(mPropertyLabel).append("\"");
      if (!StringUtils.isEmpty(mExceptionDetail)) {
         sb.append(" ");
         sb.append(mExceptionDetail);
      }
      return sb.toString();
   }
}

Add space in the error message.

Add space in the error message.


package com.github.verhagen.textadventure.core.domain;

import static org.testng.Assert.assertEquals;

import org.testng.annotations.Test;

import com.github.verhagen.textadventure.core.impl.domain.Item;
import com.github.verhagen.textadventure.core.impl.domain.Room;
import com.github.verhagen.textadventure.core.impl.domain.TextVisitor;

public class TextVisitorTest {

	@Test
	public void visitEmptyHall() {
		String description = "There is a front door on the south and a door on the east.";
		IRoom hall = new Room("hall", description);

		TextVisitor visitor = new TextVisitor();
		hall.accept(visitor);

		assertEquals(visitor.asText(), description);
	}

	@Test
	public void visitHallWithABook() {
		String description = "There is a front door on the south and a door on the east.";
		String title = "TRS-80 Assembly-Language Programming";
		IRoom hall = new Room("hall", description);
		IItem book = new Item("book", title);
		hall.add(book);

		TextVisitor visitor = new TextVisitor();
		hall.accept(visitor);

		assertEquals(visitor.asText(), description + "Items: " + book.getName());
	}

}

package com.github.verhagen.textadventure.core.domain;

import static org.testng.Assert.assertEquals;

import org.testng.annotations.Test;

import com.github.verhagen.textadventure.core.impl.domain.Item;
import com.github.verhagen.textadventure.core.impl.domain.Room;
import com.github.verhagen.textadventure.core.impl.domain.TextVisitor;

public class TextVisitorTest {

	@Test
	public void visitEmptyHall() {
		String description = "There is a front door on the south and a door on the east.";
		IRoom hall = new Room("hall", description);

		TextVisitor visitor = new TextVisitor();
		hall.accept(visitor);

		assertEquals(visitor.asText(), "You are in a hall. " + description);
	}

	@Test
	public void visitHallWithABook() {
		String description = "There is a front door on the south and a door on the east.";
		String title = "TRS-80 Assembly-Language Programming";
		IRoom hall = new Room("hall", description);
		IItem book = new Item("book", title);
		hall.add(book);

		TextVisitor visitor = new TextVisitor();
		hall.accept(visitor);

		assertEquals(visitor.asText(), "You are in a hall. " + description + " Items: " + book.getName());
	}

}

Update test cases asserts, to update TextVisitor creating better description


package co.codesharp.jwampsharp.defaultBinding;

import co.codesharp.jwampsharp.api.client.WampChannel;
import co.codesharp.jwampsharp.api.client.WampChannelFactoryImpl;
import co.codesharp.jwampsharp.core.binding.WampTextBinding;
import co.codesharp.jwampsharp.defaultBinding.jsr.WebsocketWampTextConnection;

import java.net.URI;

/**
 * Created by Elad on 7/11/2014.
 */
public class DefaultWampChannelFactory extends WampChannelFactoryImpl {
    public <TMessage> WampChannel createChannel
            (URI address,
             String realm,
             WampTextBinding<TMessage> binding) {
        WebsocketWampTextConnection<TMessage> connection =
                new WebsocketWampTextConnection<TMessage>(address, binding);

        return this.createChannel(realm, connection, binding);
    }

    public WampChannel createJsonChannel(URI address,
                                          String realm) {
        JsonNodeBinding binding = new JsonNodeBinding();

        return this.createChannel(address, realm, binding);
    }
}

package co.codesharp.jwampsharp.defaultBinding;

import co.codesharp.jwampsharp.api.client.WampChannel;
import co.codesharp.jwampsharp.api.client.WampChannelFactoryImpl;
import co.codesharp.jwampsharp.core.binding.WampTextBinding;
import co.codesharp.jwampsharp.defaultBinding.jsr.WebsocketWampTextConnection;

import java.net.URI;

/**
 * Created by Elad on 7/11/2014.
 */
public class DefaultWampChannelFactory extends WampChannelFactoryImpl {

    private JsonNodeBinding jsonNodeBinding = new JsonNodeBinding();

    public <TMessage> WampChannel createChannel
            (URI address,
             String realm,
             WampTextBinding<TMessage> binding) {
        WebsocketWampTextConnection<TMessage> connection =
                new WebsocketWampTextConnection<TMessage>(address, binding);

        return this.createChannel(realm, connection, binding);
    }

    public WampChannel createJsonChannel(URI address,
                                          String realm) {
        return this.createChannel(address, realm, jsonNodeBinding);
    }
}

Use the same reference for all method calls


package org.shipkit.internal.gradle.util;

import org.gradle.api.GradleException;
import org.shipkit.gradle.git.GitPushTask;

public class CannotPushToGithubException extends RuntimeException {
    public static final String GH_WRITE_TOKEN_NOT_SET_MSG = "Cannot push to remote repository. GH_WRITE_TOKEN not set or you don't have write access to remote. Please recheck your configuration.";
    public static final String GH_WRITE_TOKEN_INVALID_MSG = "Cannot push to remote repository. GH_WRITE_TOKEN is set but possibly invalid. Please recheck your configuration.";

    private CannotPushToGithubException(String message, Throwable cause) {
        super(message, cause);
    }

    public static CannotPushToGithubException create(Exception e, GitPushTask task) {
        String message;
        if (task.getSecretValue() == null) {
            message = GH_WRITE_TOKEN_NOT_SET_MSG;
        } else {
            message = GH_WRITE_TOKEN_INVALID_MSG;
        }
        return new CannotPushToGithubException(message, e);
    }

    public static boolean matchException(GradleException e) {
        return e.getMessage().contains("Authentication failed") || e.getMessage().contains("unable to access");
    }
}

package org.shipkit.internal.gradle.util;

import org.gradle.api.GradleException;
import org.shipkit.gradle.git.GitPushTask;

public class CannotPushToGithubException extends RuntimeException {
    public static final String GH_WRITE_TOKEN_NOT_SET_MSG = "Cannot push to remote repository. GH_WRITE_TOKEN env variable not set or you don't have write access to remote. Please recheck your configuration.";
    public static final String GH_WRITE_TOKEN_INVALID_MSG = "Cannot push to remote repository. GH_WRITE_TOKEN env variable is set but possibly invalid. Please recheck your configuration.";

    private CannotPushToGithubException(String message, Throwable cause) {
        super(message, cause);
    }

    public static CannotPushToGithubException create(Exception e, GitPushTask task) {
        String message;
        if (task.getSecretValue() == null) {
            message = GH_WRITE_TOKEN_NOT_SET_MSG;
        } else {
            message = GH_WRITE_TOKEN_INVALID_MSG;
        }
        return new CannotPushToGithubException(message, e);
    }

    public static boolean matchException(GradleException e) {
        return e.getMessage().contains("Authentication failed") || e.getMessage().contains("unable to access");
    }
}

Make error message more specific.

Make error message more specific.


package org.knowm.xchange.bitfinex.v1.dto.trade;

import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonRawValue;

public class BitfinexCancelOrderRequest {

  @JsonProperty("request")
  protected String request;

  @JsonProperty("nonce")
  protected String nonce;

  @JsonProperty("order_id")
  @JsonRawValue
  private int orderId;

  /**
   * Constructor
   *
   * @param nonce
   * @param orderId
   */
  public BitfinexCancelOrderRequest(String nonce, int orderId) {

    this.request = "/v1/order/cancel";
    this.orderId = orderId;
    this.nonce = nonce;
  }

  public String getOrderId() {

    return String.valueOf(orderId);
  }

}

package org.knowm.xchange.bitfinex.v1.dto.trade;

import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonRawValue;

public class BitfinexCancelOrderRequest {

  @JsonProperty("request")
  protected String request;

  @JsonProperty("nonce")
  protected String nonce;

  @JsonProperty("order_id")
  @JsonRawValue
  private long orderId;

  /**
   * Constructor
   *
   * @param nonce
   * @param orderId
   */
  public BitfinexCancelOrderRequest(String nonce, long orderId) {

    this.request = "/v1/order/cancel";
    this.orderId = orderId;
    this.nonce = nonce;
  }

  public String getOrderId() {

    return String.valueOf(orderId);
  }

}

Order id is now long type

Order id is now long type


package com.orientechnologies.orient.core.db.tool.importer;

import com.orientechnologies.orient.core.db.record.OIdentifiable;

/** Created by tglman on 28/07/17. */
public abstract class OAbstractCollectionConverter<T> implements OValuesConverter<T> {
  private final OConverterData converterData;

  protected OAbstractCollectionConverter(OConverterData converterData) {
    this.converterData = converterData;
  }

  public interface ResultCallback {
    void add(Object item);
  }

  protected boolean convertSingleValue(final Object item, ResultCallback result, boolean updated) {
    if (item == null) return false;

    if (item instanceof OIdentifiable) {
      final OValuesConverter<OIdentifiable> converter =
          (OValuesConverter<OIdentifiable>)
              OImportConvertersFactory.INSTANCE.getConverter(item, converterData);

      final OIdentifiable newValue = converter.convert((OIdentifiable) item);

      // this code intentionally uses == instead of equals, in such case we may distinguish rids
      // which already contained in
      // document and RID which is used to indicate broken record
      if (newValue != OImportConvertersFactory.BROKEN_LINK) result.add(newValue);

      if (!newValue.equals(item)) updated = true;
    } else {
      final OValuesConverter valuesConverter =
          OImportConvertersFactory.INSTANCE.getConverter(item.getClass(), converterData);
      if (valuesConverter == null) result.add(item);
      else {
        final Object newValue = valuesConverter.convert(item);
        if (newValue != item) updated = true;

        result.add(newValue);
      }
    }

    return updated;
  }
}

package com.orientechnologies.orient.core.db.tool.importer;

import com.orientechnologies.orient.core.db.record.OIdentifiable;

/** Created by tglman on 28/07/17. */
public abstract class OAbstractCollectionConverter<T> implements OValuesConverter<T> {
  private final OConverterData converterData;

  protected OAbstractCollectionConverter(OConverterData converterData) {
    this.converterData = converterData;
  }

  public interface ResultCallback {
    void add(Object item);
  }

  protected boolean convertSingleValue(final Object item, ResultCallback result, boolean updated) {
    if (item == null) return false;

    if (item instanceof OIdentifiable) {
      final OValuesConverter<OIdentifiable> converter =
          (OValuesConverter<OIdentifiable>)
              OImportConvertersFactory.INSTANCE.getConverter(item, converterData);

      final OIdentifiable newValue = converter.convert((OIdentifiable) item);

      // this code intentionally uses == instead of equals, in such case we may distinguish rids
      // which already contained in
      // document and RID which is used to indicate broken record
      if (newValue != OImportConvertersFactory.BROKEN_LINK) result.add(newValue);

      if (!newValue.equals(item)) updated = true;
    } else {
      final OValuesConverter valuesConverter =
          OImportConvertersFactory.INSTANCE.getConverter(item, converterData);
      if (valuesConverter == null) result.add(item);
      else {
        final Object newValue = valuesConverter.convert(item);
        if (newValue != item) updated = true;

        result.add(newValue);
      }
    }

    return updated;
  }
}

Fix import with links in embedded collections of maps


// Copyright 2017 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      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.crypto.tink;

import java.security.GeneralSecurityException;

/**
 * Interface for public key signing.
 *
 *
Digital Signatures provide functionality of signing data and verification of the signatures.
 *
 *
Security guarantees

 *
 *
The functionality of Digital Signatures is represented a pair of primitives (interfaces)
 * {@link PublicKeySign} for signing of data, and {@link PublicKeyVerify} for verification of
 * signatures. Implementations of these interfaces are secure against adaptive chosen-message
 * attacks. Signing data ensures the authenticity and the integrity of that data, but not its
 * secrecy.
 *
 * @since 1.0.0
 */
public interface PublicKeySign {
  /**
   * Computes the signature for {@code data}.
   *
   * @return the signature of {$code data}
   */
  byte[] sign(final byte[] data) throws GeneralSecurityException;
}

// Copyright 2017 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      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.crypto.tink;

import java.security.GeneralSecurityException;

/**
 * Interface for public key signing.
 *
 *
Digital Signatures provide functionality of signing data and verification of the signatures.
 *
 *
Security guarantees

 *
 *
The functionality of Digital Signatures is represented a pair of primitives (interfaces)
 * {@link PublicKeySign} for signing of data, and {@link PublicKeyVerify} for verification of
 * signatures. Implementations of these interfaces are secure against adaptive chosen-message
 * attacks. Signing data ensures the authenticity and the integrity of that data, but not its
 * secrecy.
 *
 * @since 1.0.0
 */
public interface PublicKeySign {
  /**
   * Computes the signature for {@code data}.
   *
   * @return the signature of {@code data}
   */
  byte[] sign(final byte[] data) throws GeneralSecurityException;
}

Fix typo in Javadoc tag for sign() return description.

PiperOrigin-RevId: 287240118


package pt.up.fe.comp.utils;

import java.util.Stack;

public class SymbolTable<T> {

    public SymbolTable(boolean lazy) {
        _lazy = lazy;
        beginScope();
    }

    public void beginScope() {
        _scopes.add(new Scope<T>(_lazy));
    }

    public void endScope() {
        // do not delete "global" scope
        if (_scopes.size() > 1)
            _scopes.pop();
    }

    public void setLazy(boolean value) {
        _lazy = value;
        for (Scope<T> scp : _scopes) {
            scp.setLazy(value);
        }
    }

    public void addSymbol(String name, Class type, Producer<T> init) {
        _scopes.peek().addSymbol(name, type, init);
    }

    public boolean contains(String name) {
        return get(name) != null;
    }

    public T get(String name) {
        T value;
        for (Scope<T> scp : _scopes) {
            value = scp.getSymbol(name);
            if (value != null) return value;
        }
        return null;
    }

    public Class getType(String name) {
        Class type;
        for (Scope<T> scp : _scopes) {
            type = scp.getSymbolType(name);
            if (type != null) return type;
        }
        return null;
    }

    private Stack<Scope<T>> _scopes = new Stack<>();
    private boolean _lazy;
}

package pt.up.fe.comp.utils;

import java.util.Stack;

public class SymbolTable<T> {

    public SymbolTable(boolean lazy) {
        _lazy = lazy;
        beginScope();
    }

    public void beginScope() {
        _scopes.add(new Scope<T>(_lazy));
    }

    public void endScope() {
        // do not delete "global" scope
        if (_scopes.size() > 1)
            _scopes.pop();
    }

    public void setLazy(boolean value) {
        _lazy = value;
        for (Scope<T> scp : _scopes) {
            scp.setLazy(value);
        }
    }

    public void addSymbol(String name, Class type, Producer<T> init) {
        if (!contains(name))
            _scopes.peek().addSymbol(name, type, init);
        else throw new Error(name + " is already declared.");
    }

    public boolean contains(String name) {
        return get(name) != null;
    }

    public T get(String name) {
        T value;
        for (Scope<T> scp : _scopes) {
            value = scp.getSymbol(name);
            if (value != null) return value;
        }
        return null;
    }

    public Class getType(String name) {
        Class type;
        for (Scope<T> scp : _scopes) {
            type = scp.getSymbolType(name);
            if (type != null) return type;
        }
        return null;
    }

    private Stack<Scope<T>> _scopes = new Stack<>();
    private boolean _lazy;
}

Add check for redeclared symbols.

Add check for redeclared symbols.


package com.woopra;

import java.util.Properties;
/**
 * @author Woopra on 1/26/2013
 *
 */
public class WoopraEvent {
	private String eventName = null;
	private Properties properties = null;

	public WoopraEvent(String eventName) {
		super(eventName, new Properties();
	}

	public WoopraEvent(String eventName, Properties properties) {
		this.properties = properties;
		this.properties.setProperty("name", eventName);
	}

	public Properties getProperties() {
		return properties;
	}

	public void setProperties(Properties properties) {
		this.properties = properties;
	}

	public void addEventProperties(Properties newProperties) {
		properties.putAll(newProperties);
	}

	public void addEventProperty(String key, String value) {
		properties.setProperty(key, value);
	}
}

package com.woopra;

import java.util.Properties;
/**
 * @author Woopra on 1/26/2013
 *
 */
public class WoopraEvent {
	private String eventName = null;
	private Properties properties = null;

	public WoopraEvent(String eventName) {
		super(eventName, new Properties();
	}

	public WoopraEvent(String eventName, Properties properties) {
		this.properties = properties;
		if (this.properties == null) {
			this.properties = new Properties();
		}
		this.properties.setProperty("name", eventName);
	}

	public Properties getProperties() {
		return properties;
	}

	public void setProperties(Properties properties) {
		this.properties = properties;
	}

	public void addEventProperties(Properties newProperties) {
		properties.putAll(newProperties);
	}

	public void addEventProperty(String key, String value) {
		properties.setProperty(key, value);
	}
}

Fix event name not being added in constructor.


/*
 *   Copyright (C) 2016 to the original 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 io.fabric8.spring.cloud.discovery;

import org.springframework.boot.context.properties.ConfigurationProperties;

@ConfigurationProperties("spring.cloud.kubernetes.discovery")
public class KubernetesDiscoveryProperties {

    private boolean enabled = true;
    private String serviceName = "unknown";

    public boolean isEnabled() {
        return enabled;
    }

    public void setEnabled(boolean enabled) {
        this.enabled = enabled;
    }

    public String getServiceName() {
        return serviceName;
    }
}

/*
 *   Copyright (C) 2016 to the original 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 io.fabric8.spring.cloud.discovery;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;

@ConfigurationProperties("spring.cloud.kubernetes.discovery")
public class KubernetesDiscoveryProperties {

    private boolean enabled = true;

    @Value("${spring.application.name:unknown}")
    private String serviceName = "unknown";

    public boolean isEnabled() {
        return enabled;
    }

    public void setEnabled(boolean enabled) {
        this.enabled = enabled;
    }

    public String getServiceName() {
        return serviceName;
    }
}

Use the application name as the default local service id in KubernetesDiscovery.


import datastructures.PriorityQueue;
import java.util.*;

public class PriorityQueueTest {
    public static void main(String[] args) throws Exception {
        for (int i = 0; i < 5; i ++) {
            testRandomSort(10000 + ((int) (Math.random() * 10000)));
        }
    }

    private static void testRandomSort(int count) throws Exception {
        System.out.printf("\tRandomSort (n = %d)\n", count);
        PriorityQueue<Integer> q = new PriorityQueue<>();
        for (int i = 0; i < count; i ++) {
            q.add((int) (Math.random() * Integer.MAX_VALUE));
        }

        if (q.isEmpty()) {
            throw new Exception("Queue is empty");
        }

        if (q.size() != count) {
            throw new Exception("Queue size is incorrect");
        }

        int prev = q.poll();

        while (!q.isEmpty()) {
            int curr = q.poll();

            if (curr < prev) {
                throw new Exception("Incorrect poll order");
            }
            prev = curr;
        }
    }
}

import datastructures.PriorityQueue;
import java.util.*;

public class PriorityQueueTest {
    public static void main(String[] args) throws Exception {
        for (int i = 0; i < 5; i ++) {
            testRandomSort(10000 + ((int) (Math.random() * 10000)));
            testRandomSortAndInsert(10000 + ((int) (Math.random() * 10000)));
        }
    }

    private static void testRandomSort(int count) throws Exception {
        System.out.printf("\tRandomSort (n = %d)\n", count);
        PriorityQueue<Integer> q = new PriorityQueue<>();
        for (int i = 0; i < count; i ++) {
            q.add((int) (Math.random() * Integer.MAX_VALUE));
        }

        if (q.isEmpty()) {
            throw new Exception("Queue is empty");
        }

        if (q.size() != count) {
            throw new Exception("Queue size is incorrect");
        }

        int prev = q.poll();

        while (!q.isEmpty()) {
            int curr = q.poll();

            if (curr < prev) throw new Exception("Incorrect poll order");
            prev = curr;
        }
    }

    private static void testRandomSortAndInsert(int count) throws Exception {
        System.out.printf("\tRandomSortAndInsert (n = %d)\n", count);
        PriorityQueue<Integer> q = new PriorityQueue<>();
        for (int i = 0; i < count; i ++) {
            q.add((int) (Math.random() * Integer.MAX_VALUE));
        }

        if (q.isEmpty()) {
            throw new Exception("Queue is empty");
        }

        if (q.size() != count) {
            throw new Exception("Queue size is incorrect");
        }

        while (!q.isEmpty()) {
            int curr = q.poll();
            if (q.isEmpty()) break;
            int next = q.poll();

            if (curr > next) throw new Exception("Incorrect poll order");

            if (Math.random() < 0.5) {
                q.add((int) (Math.random() * Integer.MAX_VALUE));
            }
        }
    }
}

Add sort and insert heap test

Add sort and insert heap test


package bean;

import java.net.URI;

import javax.enterprise.context.ApplicationScoped;
import javax.ws.rs.FormParam;
import javax.ws.rs.POST;

import org.eclipse.microprofile.rest.client.RestClientBuilder;

import bean.MarkdownBean.SyntaxHighlighter;
import lombok.SneakyThrows;

@ApplicationScoped
public class HiliteMeHighlighter implements SyntaxHighlighter {

	interface HiliteMeService {
		@POST
		String highlight(
			@FormParam("code") String code,
			@FormParam("lexer") String lexer,
			@FormParam("linenos") boolean lineNos,
			@FormParam("style") String style
		);
	}

	@Override
	@SneakyThrows
	public String highlight(String text, String language) {
		// TODO use embedded Python interpreter?
		URI apiUri = new URI("http://hilite.me/api"); //$NON-NLS-1$
		HiliteMeService hiliteMe = RestClientBuilder.newBuilder()
			.baseUri(apiUri)
			.build(HiliteMeService.class);
		return hiliteMe.highlight(text, language, true, "colorful"); //$NON-NLS-1$
	}

}

package bean;

import java.net.URI;

import javax.enterprise.context.ApplicationScoped;
import javax.ws.rs.FormParam;
import javax.ws.rs.POST;

import org.eclipse.microprofile.rest.client.RestClientBuilder;

import bean.MarkdownBean.SyntaxHighlighter;
import lombok.SneakyThrows;

@ApplicationScoped
public class HiliteMeHighlighter implements SyntaxHighlighter {

	public interface HiliteMeService {
		@POST
		String highlight(
			@FormParam("code") String code,
			@FormParam("lexer") String lexer,
			@FormParam("linenos") boolean lineNos,
			@FormParam("style") String style
		);
	}

	@Override
	@SneakyThrows
	public String highlight(String text, String language) {
		// TODO use embedded Python interpreter?
		URI apiUri = new URI("http://hilite.me/api"); //$NON-NLS-1$
		HiliteMeService hiliteMe = RestClientBuilder.newBuilder()
			.baseUri(apiUri)
			.build(HiliteMeService.class);
		return hiliteMe.highlight(text, language, true, "colorful"); //$NON-NLS-1$
	}

}

Make HiliteMeService public for CDI

Make HiliteMeService public for CDI


package data.trainnetwork;

import java.io.Serializable;
import java.math.BigInteger;
import java.security.SecureRandom;

/**
 * A class representing a Seat within section
 * @author Balazs Pete
 *
 */
public class Seat implements Serializable {

	private String id, sectionId = null;

	/**
	 * Create a new Seat
	 * @param id
	 */
	public Seat() {
		this.id = new BigInteger(130, new SecureRandom()).toString(32);
	}

	/**
	 * Get the ID of the Seat
	 * @return
	 */
	public String getId() {
		return id;
	}

	/**
	 * Add the corresponding {@link Section} (will be stored as an ID reference)
	 * @param section The section the seat belongs to
	 */
	public void addSection(Section section) {
		sectionId = section.getID();
	}

	/**
	 * Get the ID of the corresponding {@link Section}
	 * @return The id of the section
	 */
	public String getSectionId() {
		return sectionId;
	}

	/**
	 * Compare another seat with this one
	 * @param seat The other seat to compare with
	 * @return True if the two seats are identical
	 */
	public boolean equals(Seat seat) {
		return id.equals(seat.getId());
	}
}

package data.trainnetwork;

import java.io.Serializable;
import java.math.BigInteger;
import java.security.SecureRandom;

/**
 * A class representing a Seat within section
 * @author Balazs Pete
 *
 */
public class Seat implements Serializable {

	/**
	 *
	 */
	private static final long serialVersionUID = 3197202742981022435L;

	private String id, sectionId = null;

	/**
	 * Create a new Seat
	 * @param id
	 */
	public Seat() {
		this.id = new BigInteger(130, new SecureRandom()).toString(32);
	}

	/**
	 * Get the ID of the Seat
	 * @return
	 */
	public String getId() {
		return id;
	}

	/**
	 * Add the corresponding {@link Section} (will be stored as an ID reference)
	 * @param section The section the seat belongs to
	 */
	public void addSection(Section section) {
		sectionId = section.getID();
	}

	/**
	 * Get the ID of the corresponding {@link Section}
	 * @return The id of the section
	 */
	public String getSectionId() {
		return sectionId;
	}

	/**
	 * Compare another seat with this one
	 * @param seat The other seat to compare with
	 * @return True if the two seats are identical
	 */
	public boolean equals(Seat seat) {
		return id.equals(seat.getId());
	}
}

Add serial id to seat

Add serial id to seat


package com.rollbar.jvmti;

import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

/**
 * CacheFrame is a frame generated from the native interface to hold a method and a list of local
 * variables for later use.
 */
public final class CacheFrame {
  private Method method;
  private final LocalVariable[] locals;

  /**
   * Constructor with the method and list of local variables.
   */
  public CacheFrame(Method method, LocalVariable[] locals) {
    this.method = method;
    this.locals = locals;
  }

  /**
   * Getter.
   *
   * @return the method that generated this frame.
   */
  public Method getMethod() {
    return method;
  }

  /**
   * Getter.
   *
   * @return the local variables for this frame.
   */
  public Map<String, Object> getLocals() {
    if (locals == null || locals.length == 0) {
      return Collections.emptyMap();
    }

    Map<String, Object> localsMap = new HashMap<>();
    for (LocalVariable localVariable : locals) {
      if (localVariable != null) {
        localsMap.put(localVariable.getName(), localVariable.getValue());
      }
    }

    return localsMap;
  }

  @Override
  public String toString() {
    return "CacheFrame{"
      + ", locals=" + Arrays.toString(locals)
      + '}';
  }
}

package com.rollbar.jvmti;

import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

/**
 * CacheFrame is a frame generated from the native interface to hold a method and a list of local
 * variables for later use.
 */
public final class CacheFrame {
  private Method method;
  private final LocalVariable[] locals;

  /**
   * Constructor with the method and list of local variables.
   */
  public CacheFrame(Method method, LocalVariable[] locals) {
    this.method = method;
    this.locals = Arrays.copyOf(locals, locals.length);
  }

  /**
   * Getter.
   *
   * @return the method that generated this frame.
   */
  public Method getMethod() {
    return method;
  }

  /**
   * Getter.
   *
   * @return the local variables for this frame.
   */
  public Map<String, Object> getLocals() {
    if (locals == null || locals.length == 0) {
      return Collections.emptyMap();
    }

    Map<String, Object> localsMap = new HashMap<>();
    for (LocalVariable localVariable : locals) {
      if (localVariable != null) {
        localsMap.put(localVariable.getName(), localVariable.getValue());
      }
    }

    return localsMap;
  }

  @Override
  public String toString() {
    return "CacheFrame{"
      + ", locals=" + Arrays.toString(locals)
      + '}';
  }
}

Make the findbugs checker happy

Make the findbugs checker happy


package tetris.game;

import java.awt.*;
import javax.swing.*;

public class MainConsole{

    private JFrame frame;
    private Canvas canvas;

    public MainConsole(){
        frame = new JFrame("Tetris");
        frame.setSize((Canvas.WIDTH + 7) * Canvas.SIDE_OF_SQUARE,
            (Canvas.HEIGHT + 1) * Canvas.SIDE_OF_SQUARE);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);
        frame.setResizable(false);

        canvas = new Canvas();
        frame.addKeyListener(canvas.getKeyListener());
        frame.add(canvas,BorderLayout.CENTER);
    }

    public static void main(String [] args){
        SwingUtilities.invokeLater(new Runnable(){
            @Override
            public void run(){
                new MainConsole();
            }
        });
    }
}

package tetris.game;

import java.awt.*;
import javax.swing.*;

public class MainConsole{

    private JFrame frame;
    private Canvas canvas;

    public MainConsole(){
        frame = new JFrame("Tetris");
        frame.setSize((Canvas.WIDTH + 7) * Canvas.SIDE_OF_SQUARE,
            (Canvas.HEIGHT + 1) * Canvas.SIDE_OF_SQUARE);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);
        frame.setResizable(false);
	frame.setLocationRelativeTo(null);

        canvas = new Canvas();
        frame.addKeyListener(canvas.getKeyListener());
        frame.add(canvas,BorderLayout.CENTER);
    }

    public static void main(String [] args){
        SwingUtilities.invokeLater(new Runnable(){
            @Override
            public void run(){
		JOptionPane.showMessageDialog(null, 	"Press [up] key to rotate the blocks\n" +
							"Press [down] key to move the blocks down\n" +
							"Press [left] key to move the blocks to the left\n" +
							"Press [right] key to move the blocks to the right\n" +
							"Press [space] key to move the blocks all the way down\n" +
							"Press [P] key to pause the game\n" +
							"Press [R] key to resume the game\n");
                new MainConsole();
            }
        });
    }
}

Update description with Canvas class

Update description with Canvas class


/*
 * Copyright 2021 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      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 quantize;

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

/** Creates a dictionary with keys of colors, and values of count of the color */
public final class QuantizerMap implements Quantizer {
  Map<Integer, Integer> colorToCount;

  @Override
  public QuantizerResult quantize(int[] pixels, int colorCount) {
    final HashMap<Integer, Integer> pixelByCount = new HashMap<>();
    for (int pixel : pixels) {
      pixelByCount.merge(pixel, 1, (Integer count, Integer newValue) -> count + newValue);
    }
    colorToCount = pixelByCount;
    return new QuantizerResult(pixelByCount);
  }

  public Map<Integer, Integer> getColorToCount() {
    return colorToCount;
  }
}

/*
 * Copyright 2021 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      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 quantize;

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

/** Creates a dictionary with keys of colors, and values of count of the color */
public final class QuantizerMap implements Quantizer {
  Map<Integer, Integer> colorToCount;

  @Override
  public QuantizerResult quantize(int[] pixels, int colorCount) {
    final HashMap<Integer, Integer> pixelByCount = new HashMap<>();
    for (int pixel : pixels) {
      final Integer currentPixelCount = pixelByCount.get(pixel);
      final int newPixelCount = currentPixelCount == null ? 1 : currentPixelCount + 1;
      pixelByCount.put(pixel, newPixelCount);
    }
    colorToCount = pixelByCount;
    return new QuantizerResult(pixelByCount);
  }

  public Map<Integer, Integer> getColorToCount() {
    return colorToCount;
  }
}

Remove `HashMap.merge`, which is absent in Java7.

PiperOrigin-RevId: 445068304


package it.gov.aifa.invoice_processor.service.persistence;
import org.springframework.data.repository.PagingAndSortingRepository;

import it.gov.aifa.invoice_processor.entity.invoice.InvoiceVersion;

public interface InvoiceVersionRepository extends PagingAndSortingRepository<InvoiceVersion, String> {
}

package it.gov.aifa.invoice_processor.service.persistence;
import org.springframework.data.repository.CrudRepository;

import it.gov.aifa.invoice_processor.entity.invoice.InvoiceVersion;

public interface InvoiceVersionRepository extends CrudRepository<InvoiceVersion, String> {
}

Use a CrudRepository instead of a PagingAndSortingRepository


/*
 * Copyright 2015 the original author or authors.
 *
 * 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
 */

package org.junit.gen5.commons.util;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;

import org.junit.Assert;
import org.junit.Test;

public class FindClassesInPackageTest {

	@Test
	public void findAllClassesInThisPackage() throws IOException, ClassNotFoundException {
		List<Class<?>> classes = Arrays.asList(ReflectionUtils.findAllClassesInPackage("org.junit.gen5.commons"));
		System.out.println("Number of classes found: " + classes.size());
		for (Class<?> clazz : classes) {
			System.out.println(clazz.getName());
		}
		Assert.assertTrue("Should be at least 20 classes", classes.size() >= 20);
		Assert.assertTrue(classes.contains(NestedClassToBeFound.class));
		Assert.assertTrue(classes.contains(MemberClassToBeFound.class));
	}

	class MemberClassToBeFound {
	}

	static class NestedClassToBeFound {
	}

}

/*
 * Copyright 2015 the original author or authors.
 *
 * 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
 */

package org.junit.gen5.commons.util;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;

import org.junit.Assert;
import org.junit.Test;

public class FindClassesInPackageTest {

	@Test
	public void findAllClassesInThisPackage() throws IOException, ClassNotFoundException {
		List<Class<?>> classes = Arrays.asList(ReflectionUtils.findAllClassesInPackage("org.junit.gen5.commons"));
		Assert.assertTrue("Should be at least 20 classes", classes.size() >= 20);
		Assert.assertTrue(classes.contains(NestedClassToBeFound.class));
		Assert.assertTrue(classes.contains(MemberClassToBeFound.class));
	}

	class MemberClassToBeFound {
	}

	static class NestedClassToBeFound {
	}

}

Remove printing to System.out in test

Remove printing to System.out in test


package junit.runner;

/**
 * This class defines the current version of JUnit
 */
public class Version {
	private Version() {
		// don't instantiate
	}

	public static String id() {
		return "3.7";
	}
}

package junit.runner;

/**
 * This class defines the current version of JUnit
 */
public class Version {
	private Version() {
		// don't instantiate
	}

	public static String id() {
		return "@version@";
	}
}

Put back abstract version number

Put back abstract version number


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

package com.google.sps.data;

public final class Trend {

  private final long id;
  private final String title;
  private final long frequency;
  private final long timestamp;

  public Trend(long id, String title, long frequency, long timestamp) {
    this.id = id;
    this.title = title;
    this.frequency = frequency;
    this.timestamp = timestamp;
  }
}

Implement parser for trends and their frequencies and store those trends in datastore


package org.yeastrc.proxl.proxl_gen_import_xml_kojak.kojak_and_percolator.constants;

import java.math.BigDecimal;

public class KojakPercolatorDefaultFilterValueConstants {

	public static final BigDecimal PERCOLATOR_PEPTIDE_Q_VALUE_DEFAULT = new BigDecimal( "0.01" );

	public static final BigDecimal PERCOLATOR_PSM_Q_VALUE_DEFAULT = new BigDecimal( "0.01" );
}

package org.yeastrc.proxl.proxl_gen_import_xml_kojak.kojak_and_percolator.constants;

import java.math.BigDecimal;

public class KojakPercolatorDefaultFilterValueConstants {

	public static final BigDecimal PERCOLATOR_PEPTIDE_Q_VALUE_DEFAULT = new BigDecimal( "0.05" );

	public static final BigDecimal PERCOLATOR_PSM_Q_VALUE_DEFAULT = new BigDecimal( "0.05" );
}

Change q-value default cutoff to 0.05 for both peptide and PSM

This is for Percolator q-value default cutoff


package de.digitalcollections.iiif.presentation.model.impl.v2;

public class PhysicalDimensionsServiceImpl extends ServiceImpl {
  private double physicalScale;
  private String physicalUnits;

  public PhysicalDimensionsServiceImpl() {}

  public PhysicalDimensionsServiceImpl(double physicalScale, String physicalUnits) {
    this.physicalScale = physicalScale;
    this.physicalUnits = physicalUnits;
  }

  @Override
  public String getContext() {
    return "http://iiiif.io/api/annex/services/physdim/1/context.json";
  }

  @Override
  public String getProfile() {
    return "http://iiiif.io/api/annex/services/physdim";
  }

  public Double getPhysicalScale() {
    return physicalScale;
  }

  public String getPhysicalUnits() {
    return physicalUnits;
  }

  public void setPhysicalScale(double physicalScale) {
    this.physicalScale = physicalScale;
  }

  public void setPhysicalUnits(String physicalUnits) {
    this.physicalUnits = physicalUnits;
  }
}

package de.digitalcollections.iiif.presentation.model.impl.v2;

public class PhysicalDimensionsServiceImpl extends ServiceImpl {
  private double physicalScale;
  private String physicalUnits;

  public PhysicalDimensionsServiceImpl() {}

  public PhysicalDimensionsServiceImpl(double physicalScale, String physicalUnits) {
    this.physicalScale = physicalScale;
    this.physicalUnits = physicalUnits;
  }

  @Override
  public String getContext() {
    return "http://iiif.io/api/annex/services/physdim/1/context.json";
  }

  @Override
  public String getProfile() {
    return "http://iiif.io/api/annex/services/physdim";
  }

  public Double getPhysicalScale() {
    return physicalScale;
  }

  public String getPhysicalUnits() {
    return physicalUnits;
  }

  public void setPhysicalScale(double physicalScale) {
    this.physicalScale = physicalScale;
  }

  public void setPhysicalUnits(String physicalUnits) {
    this.physicalUnits = physicalUnits;
  }
}

Fix typo in physical dimensions profile and @context


package beaform.events;

import static org.junit.Assert.assertEquals;

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

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

import beaform.utilities.SystemTime;
import beaform.utilities.TimeSource;

public class StoreEventTest {

	@Before
	public void setup() {
		SystemTime.setTimeSource(new TimeSource() {
			private final long timeInMillis = 0;

			@Override
			public long getSystemTime() {
				return this.timeInMillis;
			}
		});
	}

	@After
	public void destroy() {
		SystemTime.reset();
	}

	@Test
	public void testEventString() {
		// Create a 'create' event for a new formula
		String name = "TestFormula";
		Event createEvent = new FormulaCreatedEvent(name);

		Date timestamp = SystemTime.getAsDate();
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
		String expectedResult = "[" + df.format(timestamp) + "] FormulaCreated " + name;
		// Check if the event converts to a string correctly
		// [timestamp] action properties
		String assertMessageOnFail = "Event format doesn't match with the expected one";
		assertEquals(assertMessageOnFail, expectedResult, createEvent.toEventString());
	}

}

package beaform.events;

import static org.junit.Assert.assertEquals;

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

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

import beaform.utilities.SystemTime;

public class StoreEventTest {

	@Before
	public void setup() {
		SystemTime.setTimeSource(() -> 0);
	}

	@After
	public void destroy() {
		SystemTime.reset();
	}

	@Test
	public void testEventString() {
		// Create a 'create' event for a new formula
		String name = "TestFormula";
		Event createEvent = new FormulaCreatedEvent(name);

		Date timestamp = SystemTime.getAsDate();
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
		String expectedResult = "[" + df.format(timestamp) + "] FormulaCreated " + name;
		// Check if the event converts to a string correctly
		// [timestamp] action properties
		String assertMessageOnFail = "Event format doesn't match with the expected one";
		assertEquals(assertMessageOnFail, expectedResult, createEvent.toEventString());
	}

}

Use a lambda as it is a lot shorter

Use a lambda as it is a lot shorter


package collections;

import java.util.Iterator;
import java.util.NoSuchElementException;
import java.util.Stack;

import binarytrees.TreeNode;

public class PreorderIterator<T> implements Iterator<T> {
	private T nextItem;
	private final Stack<TreeNode<T>> stack;

	public PreorderIterator(TreeNode<T> rootNode) {
		this.nextItem = null;
		this.stack = new Stack<TreeNode<T>>();
		stack.push(rootNode);
	}

	@Override
	public boolean hasNext() {
		if (nextItem != null) {
			return true;
		}

		if (stack.empty()) {
			return false;
		}

		TreeNode<T> node = stack.peek();
		nextItem = node.getValue();
		if (node.hasLeft()) {
			stack.push(node.getLeft());
		} else {
			while (!stack.empty()) {
				TreeNode<T> current = stack.pop();
				if (current.hasRight()) {
					stack.push(current.getRight());
					break;
				}
			}
		}

		return true;
	}

	@Override
	public T next() {
		if (!hasNext()) {
			throw new NoSuchElementException();
		}

		T toReturn = nextItem;
		nextItem = null;
		return toReturn;
	}

	@Override
	public void remove() {
		throw new UnsupportedOperationException();
	}
}

package collections;

import java.util.Iterator;
import java.util.NoSuchElementException;
import java.util.Stack;

import binarytrees.TreeNode;

/**
 * An iterator that iterates through a binary tree in pre-order.
 */
public class PreorderIterator<T> implements Iterator<T> {
	private T nextItem;
	private final Stack<TreeNode<T>> stack;

	public PreorderIterator(TreeNode<T> rootNode) {
		this.nextItem = null;
		this.stack = new Stack<TreeNode<T>>();
		stack.push(rootNode);
	}

	@Override
	public boolean hasNext() {
		if (nextItem != null) {
			return true;
		}

		if (stack.empty()) {
			return false;
		}

		TreeNode<T> node = stack.peek();
		nextItem = node.getValue();
		if (node.hasLeft()) {
			stack.push(node.getLeft());
		} else {
			while (!stack.empty()) {
				TreeNode<T> current = stack.pop();
				if (current.hasRight()) {
					stack.push(current.getRight());
					break;
				}
			}
		}

		return true;
	}

	@Override
	public T next() {
		if (!hasNext()) {
			throw new NoSuchElementException();
		}

		T toReturn = nextItem;
		nextItem = null;
		return toReturn;
	}

	@Override
	public void remove() {
		throw new UnsupportedOperationException();
	}
}

Add comment for pre-order iteration.

[Java] Add comment for pre-order iteration.


package org.commacq;

import java.io.PrintWriter;
import java.io.Writer;

/**
 * Contains a large buffer. Reuse these objects.
 */
public class CsvLineCallbackWriter extends CsvLineCallbackAbstractSimple {

	private final PrintWriter printWriter;

	public CsvLineCallbackWriter(Writer writer) {
		printWriter = new PrintWriter(writer);
	}

	@Override
	public void processUpdate(String columnNamesCsv, CsvLine csvLine) throws CsvUpdateBlockException {
		printWriter.println(csvLine.getCsvLine());
	}

	@Override
	public void processRemove(String id) throws CsvUpdateBlockException {
		printWriter.println(id);
	}
}

package org.commacq;

import java.io.PrintWriter;
import java.io.Writer;

/**
 * Contains a large buffer. Reuse these objects.
 */
public class CsvLineCallbackWriter implements CsvLineCallback {

	private final PrintWriter printWriter;

	public CsvLineCallbackWriter(Writer writer) {
		printWriter = new PrintWriter(writer);
	}

	@Override
	public void processUpdate(String columnNamesCsv, CsvLine csvLine) throws CsvUpdateBlockException {
		printWriter.println(csvLine.getCsvLine());
	}

	@Override
	public void processRemove(String id) throws CsvUpdateBlockException {
		printWriter.println(id);
	}

	/**
	 * Add csv header
	 */
	@Override
	public void startUpdateBlock(String columnNamesCsv) throws CsvUpdateBlockException {
		printWriter.println(columnNamesCsv);
	}

	@Override
	public final void finishUpdateBlock() throws CsvUpdateBlockException {
		//No behaviour defined.
	}

	@Override
	public final void startBulkUpdate(String columnNamesCsv) throws CsvUpdateBlockException {
		//No behaviour defined.
	}

	@Override
	public final void startBulkUpdateForGroup(String group, String idWithinGroup) throws CsvUpdateBlockException {
		//No behaviour defined.
	}

	@Override
	public void cancel() {
		//No behaviour defined.
	}
}

Correct Http Csv output so that it contains the csv column headings.


package org.keycloak.connections.jpa.updater;

import org.keycloak.models.KeycloakSession;
import org.keycloak.provider.Provider;

import java.sql.Connection;

/**
 * @author Stian Thorgersen
 */
public interface JpaUpdaterProvider extends Provider {

    public String FIRST_VERSION = "1.0.0.Final";

    public String LAST_VERSION = "1.5.0";

    public String getCurrentVersionSql(String defaultSchema);

    public void update(KeycloakSession session, Connection connection, String defaultSchema);

    public void validate(Connection connection, String defaultSchema);

}

package org.keycloak.connections.jpa.updater;

import org.keycloak.models.KeycloakSession;
import org.keycloak.provider.Provider;

import java.sql.Connection;

/**
 * @author Stian Thorgersen
 */
public interface JpaUpdaterProvider extends Provider {

    public String FIRST_VERSION = "1.0.0.Final";

    public String LAST_VERSION = "1.6.0";

    public String getCurrentVersionSql(String defaultSchema);

    public void update(KeycloakSession session, Connection connection, String defaultSchema);

    public void validate(Connection connection, String defaultSchema);

}

Fix db migration not running as latest jpa version wasn't updated


/*
 UVCServiceInformationProfile.java
 Copyright (c) 2015 NTT DOCOMO,INC.
 Released under the MIT license
 http://opensource.org/licenses/mit-license.php
 */
package org.deviceconnect.android.deviceplugin.uvc.profile;

import org.deviceconnect.android.profile.DConnectProfileProvider;
import org.deviceconnect.android.profile.ServiceInformationProfile;

/**
 * UVC ServiceInformation Profile.
 *
 * @author NTT DOCOMO, INC.
 */
public class UVCServiceInformationProfile extends ServiceInformationProfile{

    public UVCServiceInformationProfile(final DConnectProfileProvider provider) {
        super(provider);
    }
}

/*
 UVCServiceInformationProfile.java
 Copyright (c) 2015 NTT DOCOMO,INC.
 Released under the MIT license
 http://opensource.org/licenses/mit-license.php
 */
package org.deviceconnect.android.deviceplugin.uvc.profile;

import android.content.Intent;
import android.os.Bundle;

import org.deviceconnect.android.deviceplugin.uvc.UVCDeviceManager;
import org.deviceconnect.android.deviceplugin.uvc.UVCDeviceService;
import org.deviceconnect.android.profile.DConnectProfileProvider;
import org.deviceconnect.android.profile.ServiceInformationProfile;

/**
 * UVC ServiceInformation Profile.
 *
 * @author NTT DOCOMO, INC.
 */
public class UVCServiceInformationProfile extends ServiceInformationProfile{

    private static final String PARAM_USB = "usb";

    private final UVCDeviceManager mDeviceMgr;

    public UVCServiceInformationProfile(final DConnectProfileProvider provider) {
        super(provider);
        mDeviceMgr = ((UVCDeviceService) provider).getDeviceManager();
    }

    @Override
    protected boolean onGetInformation(final Intent request, final Intent response,
                                       final String serviceId) {
        super.onGetInformation(request, response, serviceId);
        Bundle connect = response.getBundleExtra(PARAM_CONNECT);
        connect.putBoolean(PARAM_USB, mDeviceMgr.getDevice(serviceId) != null);
        return true;
    }
}

Implement Service Information API of UVC Device Plug-in.


package org.synyx.urlaubsverwaltung.user;

import org.springframework.web.servlet.i18n.SessionLocaleResolver;

import javax.servlet.http.HttpServletRequest;
import java.security.Principal;
import java.util.Locale;

class UserSettingsAwareSessionLocaleResolver extends SessionLocaleResolver {

    private final UserSettingsService userSettingsService;

    UserSettingsAwareSessionLocaleResolver(UserSettingsService userSettingsService) {
        this.userSettingsService = userSettingsService;
    }

    @Override
    protected Locale determineDefaultLocale(HttpServletRequest request) {

        final Principal userPrincipal = request.getUserPrincipal();
        if (userPrincipal == null) {
            return request.getLocale();
        }

        final Locale locale = userSettingsService.findLocaleForUsername(userPrincipal.getName())
            .orElseGet(request::getLocale);

        setLocaleContext(request, null, () -> locale);

        return locale;
    }
}

package org.synyx.urlaubsverwaltung.user;

import org.springframework.web.servlet.i18n.SessionLocaleResolver;

import javax.annotation.Nonnull;
import javax.servlet.http.HttpServletRequest;
import java.security.Principal;
import java.util.Locale;

class UserSettingsAwareSessionLocaleResolver extends SessionLocaleResolver {

    private final UserSettingsService userSettingsService;

    UserSettingsAwareSessionLocaleResolver(UserSettingsService userSettingsService) {
        this.userSettingsService = userSettingsService;
    }

    @Nonnull
    @Override
    protected Locale determineDefaultLocale(HttpServletRequest request) {

        final Principal userPrincipal = request.getUserPrincipal();
        if (userPrincipal == null) {
            return request.getLocale();
        }

        final Locale locale = userSettingsService.findLocaleForUsername(userPrincipal.getName())
            .orElseGet(request::getLocale);

        setLocaleContext(request, null, () -> locale);

        return locale;
    }
}

Add @Nonnull annotation to determineDefaultLocale


package com.ivanph.webintent;

import android.content.Intent;
import android.net.Uri;
import com.facebook.react.bridge.NativeModule;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.ReactContext;
import com.facebook.react.bridge.ReactContextBaseJavaModule;
import com.facebook.react.bridge.ReactMethod;
import com.facebook.react.common.MapBuilder;

/**
 * {@link NativeModule} that allows JS to open the default browser
    for an url.
 */
public class RNWebIntentModule extends ReactContextBaseJavaModule {

  ReactApplicationContext reactContext;

  public RNWebIntentModule(ReactApplicationContext reactContext) {
    super(reactContext);
    this.reactContext = reactContext;
  }

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

  @ReactMethod
  public void open(String url) {
    if (Uri.parse(url).getScheme() == null) {
      //if URL is missing scheme default to http
      Uri.Builder builder = new Uri.Builder();
      url = builder.scheme("http").authority(url).build().toString();
    }
    Intent intent = new Intent(Intent.ACTION_VIEW);
    intent.setData(Uri.parse(url));
    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    this.reactContext.startActivity(intent);
  }
}

package com.ivanph.webintent;

import android.content.Intent;
import android.net.Uri;
import com.facebook.react.bridge.NativeModule;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.ReactContext;
import com.facebook.react.bridge.ReactContextBaseJavaModule;
import com.facebook.react.bridge.ReactMethod;
import com.facebook.react.common.MapBuilder;

/**
 * {@link NativeModule} that allows JS to open the default browser
    for an url.
 */
public class RNWebIntentModule extends ReactContextBaseJavaModule {

  ReactApplicationContext reactContext;

  public RNWebIntentModule(ReactApplicationContext reactContext) {
    super(reactContext);
    this.reactContext = reactContext;
  }

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

  @ReactMethod
  public void open(String url) {
    if (Uri.parse(url).getScheme() == null) {
      //if URL is missing scheme default to http
      Uri.Builder builder = new Uri.Builder();
      url = builder.scheme("http").authority(url).build().toString();
    }
    Intent intent = new Intent(Intent.ACTION_VIEW);
    intent.setData(Uri.parse(url));
    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    //Check that an app exists to receive the intent
    if (intent.resolveActivity(this.reactContext.getPackageManager()) != null) {
      this.reactContext.startActivity(intent);
    }
  }
}

Check that an app able to handle the Intent exists

Prevents the app from crashing if an intent is send
with no app able to handle it


package eu.rekawek.coffeegb.timer;

import eu.rekawek.coffeegb.Gameboy;
import eu.rekawek.coffeegb.cpu.SpeedMode;

public class Counter {

    private final int frequency;

    private final SpeedMode speedMode;

    private int clocks;

    private int counter;

    public Counter(int frequency, SpeedMode speedMode) {
        this.frequency = frequency;
        this.speedMode = speedMode;
    }

    public boolean tick() {
        int divider = Gameboy.TICKS_PER_SEC / frequency;
        if (speedMode != null) {
            divider /= speedMode.getSpeedMode();
        }
        if (++clocks >= divider) {
            clocks = 0;
            counter = (counter + 1) & 0xff;
            return true;
        } else {
            return false;
        }
    }

    public int getCounter() {
        return counter;
    }

    public void setCounter(int counter) {
        this.counter = counter;
    }
}

package eu.rekawek.coffeegb.timer;

import eu.rekawek.coffeegb.Gameboy;
import eu.rekawek.coffeegb.cpu.SpeedMode;

public class Counter {

    private final int frequency;

    private final SpeedMode speedMode;

    private int clocks;

    private int counter;

    public Counter(int frequency, SpeedMode speedMode) {
        this.frequency = frequency;
        this.speedMode = speedMode;
    }

    public boolean tick() {
        int divider = Gameboy.TICKS_PER_SEC / frequency;
        if (speedMode != null) {
            divider /= speedMode.getSpeedMode();
        }
        if (++clocks >= divider) {
            clocks = 0;
            counter = (counter + 1) & 0xff;
            return true;
        } else {
            return false;
        }
    }

    public int getCounter() {
        return counter;
    }

    public void setCounter(int counter) {
        this.counter = counter;
        this.clocks = 0;
    }
}

Reset internal DIV clock on resetting the counter.