package com.packtpublishing.tddjava.friendships;

import java.util.*;

public class Friendships {
    private final Map<String, List<String>> friendships = new HashMap<>();

    public void makeFriends(String person1, String person2) {
        addFriend(person1, person2);
        addFriend(person2, person1);
    }

    public List<String> getFriendsList(String person) {
        if (!friendships.containsKey(person)) {
            return Collections.emptyList();
        }
        return friendships.get(person);
    }

    public boolean areFriends(String person1, String person2) {
        return friendships.containsKey(person1)
                && friendships.get(person1).contains(person2);
    }

    private void addFriend(String person, String friend) {
        if (!friendships.containsKey(person)) {
            friendships.put(person, new ArrayList<String>());
        }
        List<String> friends = friendships.get(person);
        if (!friends.contains(friend)) {
            friends.add(friend);
        }
    }
}

package com.packtpublishing.tddjava.friendships;

import java.util.*;

public class Friendships {
    private final Map<String, List<String>> friendships = new HashMap<String, List<String>>();

    public void makeFriends(String person1, String person2) {
        addFriend(person1, person2);
        addFriend(person2, person1);
    }

    public List<String> getFriendsList(String person) {
        if (!friendships.containsKey(person)) {
            return Collections.emptyList();
        }
        return friendships.get(person);
    }

    public boolean areFriends(String person1, String person2) {
        return friendships.containsKey(person1)
                && friendships.get(person1).contains(person2);
    }

    private void addFriend(String person, String friend) {
        if (!friendships.containsKey(person)) {
            friendships.put(person, new ArrayList<String>());
        }
        List<String> friends = friendships.get(person);
        if (!friends.contains(friend)) {
            friends.add(friend);
        }
    }
}

Use generic type instead of diamond operator for Java 6 compatibility


package net.domesdaybook.automata.base;

import net.domesdaybook.automata.State;
import net.domesdaybook.automata.Transition;
import net.domesdaybook.automata.TransitionFactory;
import net.domesdaybook.matcher.bytes.ByteMatcher;

/**
 * @author Matt Palmer
 */
public class ByteMatcherTransitionFactory implements TransitionFactory<ByteMatcher, ByteMatcher>{

  public Transition<ByteMatcher> create(final ByteMatcher source,
                                        final boolean ignoreInversion,
                                        final State<ByteMatcher> toState) {
    return new ByteMatcherTransition(source, toState);
  }

}

package net.domesdaybook.automata.base;

import net.domesdaybook.automata.State;
import net.domesdaybook.automata.Transition;
import net.domesdaybook.automata.TransitionFactory;
import net.domesdaybook.matcher.bytes.ByteMatcher;

/**
 * @author Matt Palmer
 */
public class ByteMatcherTransitionFactory implements TransitionFactory<ByteMatcher, ByteMatcher>{

  public Transition<ByteMatcher> create(final ByteMatcher source,
                                        final boolean ignoreInversion,
                                        final State<ByteMatcher> toState) {
    return new ByteMatcherTransition<ByteMatcher>(source, toState);
  }

}

Fix use of raw type.

Fix use of raw type.


/*
 * Copyright 2019 StreamSets 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.streamsets.datacollector.config;

import com.streamsets.pipeline.api.GenerateResourceBundle;
import com.streamsets.pipeline.api.Label;

/**
 * Enum for representing possible Cluster Type
 */
@GenerateResourceBundle
public enum SparkClusterType implements Label {
  AZURE_HD_INSIGHT("Apache Spark for HDInsight"),
  DATABRICKS("Databricks"),
  EMR("EMR"),
  DATAPROC("Dataproc"),
  YARN("Hadoop YARN"),
  KUBERNETES("Kubernetes Cluster (advanced users only)"),
  LOCAL("None (local)"),
  STANDALONE_SPARK_CLUSTER("Spark Standalone Cluster"),
  SQL_SERVER_BIG_DATA_CLUSTER("SQL Server 2019 Big Data Cluster"),
  ;

  private final String label;

  SparkClusterType(String label) {
    this.label = label;
  }

  @Override
  public String getLabel() {
    return label;
  }
}

/*
 * Copyright 2019 StreamSets 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.streamsets.datacollector.config;

import com.streamsets.pipeline.api.GenerateResourceBundle;
import com.streamsets.pipeline.api.Label;

/**
 * Enum for representing possible Cluster Type
 */
@GenerateResourceBundle
public enum SparkClusterType implements Label {
  AZURE_HD_INSIGHT("Apache Spark for HDInsight"),
  DATABRICKS("Databricks"),
  EMR("EMR"),
  DATAPROC("Dataproc"),
  YARN("Hadoop YARN"),
  KUBERNETES("Kubernetes Cluster"),
  LOCAL("None (local)"),
  STANDALONE_SPARK_CLUSTER("Spark Standalone Cluster"),
  SQL_SERVER_BIG_DATA_CLUSTER("SQL Server 2019 Big Data Cluster"),
  ;

  private final String label;

  SparkClusterType(String label) {
    this.label = label;
  }

  @Override
  public String getLabel() {
    return label;
  }
}

SDC-15068: Update label for kubernetes selection in Spark configuration

Change-Id: I4bf80c324fbad953519f459bd033b997153410af
Reviewed-on: https://review.streamsets.net/c/datacollector/+/33167
Reviewed-by: Madhukar Devaraju <d22477479bbf55ba62bd822f4112c80f292c7805@streamsets.com>
Reviewed-by: Santhosh Kumar <dcc54d3f6dcdfa9d2e6b02f6c7f69cc77b8d8c9a@streamsets.com>


/*
 * 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.commons.io.testtools;

import java.io.*;

/**
 * Base class for testcases doing tests with files.
 */
public abstract class FileBasedTestCase  {

    private static volatile File testDir;

    @SuppressWarnings("ResultOfMethodCallIgnored")
    public static File getTestDirectory() {
        if (testDir == null) {
            testDir = new File("test/io/").getAbsoluteFile();
        }
        testDir.mkdirs();
        return testDir;
    }

}

/*
 * 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.commons.io.testtools;

import java.io.*;
import static org.junit.Assert.fail;

/**
 * Base class for testcases doing tests with files.
 */
public abstract class FileBasedTestCase  {

    private static volatile File testDir;

    @SuppressWarnings("ResultOfMethodCallIgnored")
    public static File getTestDirectory() {
        if (testDir == null) {
            testDir = new File("target/test_io/").getAbsoluteFile();
        }
        testDir.mkdirs();
        if (!testDir.isDirectory()) {
            fail("Could not create directory " + testDir);
        }
        return testDir;
    }

}

Use temporary dir that can be fully deleted


package io.teknek.topship;

import java.util.Map;

public class SimpleTermExtractor implements TermExtractor{

  @Override
  public Map<String, Long> extractScores(Shop shop) {
    // TODO Auto-generated method stub
    return null;
  }

}

package io.teknek.topship;

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

/** This is the bare bones thing that works logically but basically
 * produces nothing useful as it will count a the etc as terms */
public class SimpleTermExtractor implements TermExtractor{

  @Override
  public Map<String, Long> extractScores(Shop shop) {
    Map<String,Long> termScore = new HashMap<String,Long>();
    for (Item item: shop.getItems()){
      StringTokenizer st = new StringTokenizer(item.getTitle(), " .!,?");
      while (st.hasMoreTokens()){
        String token = st.nextToken();
        scoreTerm(token, termScore);
      }
      st = new StringTokenizer(item.getDescription(), " .!,?");
      while (st.hasMoreTokens()){
        String token = st.nextToken();
        scoreTerm(token, termScore);
      }
    }
    return termScore;
  }

  private static void scoreTerm(String term, Map<String,Long> termScore){
    term = term.toLowerCase();
    if (term.endsWith("'s")){
      term = term.replace("'s", "");
    }
    if (term.endsWith("’s")){
      term = term.replace("’s", "");
    }
    if (termScore.containsKey(term)){
      termScore.put(term, termScore.get(term) + 1L);
    } else {
      termScore.put(term, 1L);
    }
  }
}

Use basic tokenizer to extract words

Use basic tokenizer to extract words


package org.workcraft.types;

import java.util.LinkedHashMap;

public class LinkedTwoWayMap<S, T> extends GeneralTwoWayMap<S, T> {
    public LinkedTwoWayMap() {
        super(new LinkedHashMap<S, T>(), new LinkedHashMap<T, S>());
    }

}

package org.workcraft.types;

import java.util.LinkedHashMap;

public class LinkedTwoWayMap<S, T> extends GeneralTwoWayMap<S, T> {
    public LinkedTwoWayMap() {
        super(new LinkedHashMap<>(), new LinkedHashMap<>());
    }
}

Use implicit parameters for specialisation of generic class


package forager.client;

import java.io.IOException;

import galileo.net.ClientMessageRouter;
import galileo.net.GalileoMessage;
import galileo.net.MessageListener;
import galileo.net.NetworkDestination;

public class Forager implements MessageListener {

    private NetworkDestination overlord;
    private ClientMessageRouter messageRouter;
    private boolean once = false;

    public Forager(NetworkDestination overlord) {
        this.overlord = overlord;
    }

    public void start()
    throws IOException {
        messageRouter = new ClientMessageRouter();
        messageRouter.addListener(this);
        messageRouter.connectTo(overlord);

        /* Join the network */
    }

    @Override
    public void onConnect(NetworkDestination endpoint) {

    }

    @Override
    public void onDisconnect(NetworkDestination endpoint) {
        //TODO: auto reconnect
    }

    @Override
    public void onMessage(GalileoMessage message) {

    }

    public static void main(String[] args)
    throws IOException {
        if (args.length < 2) {
            System.out.println("Usage: forager.client.Forager <host> <port>");
            System.exit(1);
        }

        String host = args[0];
        int port = Integer.parseInt(args[1]);
        NetworkDestination overlord = new NetworkDestination(host, port);

        Forager forager = new Forager(overlord);
        forager.start();
    }
}

package forager.client;

import java.io.IOException;

import forager.events.JoinEvent;

import galileo.event.EventWrapper;
import galileo.net.ClientMessageRouter;
import galileo.net.GalileoMessage;
import galileo.net.MessageListener;
import galileo.net.NetworkDestination;

public class Forager implements MessageListener {

    private NetworkDestination overlord;
    private ClientMessageRouter messageRouter;

    public Forager(NetworkDestination overlord) {
        this.overlord = overlord;
    }

    public void start()
    throws IOException {
        messageRouter = new ClientMessageRouter();
        messageRouter.addListener(this);
        messageRouter.connectTo(overlord);

        /* Join the network */
        JoinEvent join = new JoinEvent();
        messageRouter.sendMessage(overlord, EventWrapper.wrap(join));
    }

    @Override
    public void onConnect(NetworkDestination endpoint) {

    }

    @Override
    public void onDisconnect(NetworkDestination endpoint) {
        //TODO: auto reconnect
    }

    @Override
    public void onMessage(GalileoMessage message) {

    }

    public static void main(String[] args)
    throws IOException {
        if (args.length < 2) {
            System.out.println("Usage: forager.client.Forager <host> <port>");
            System.exit(1);
        }

        String host = args[0];
        int port = Integer.parseInt(args[1]);
        NetworkDestination overlord = new NetworkDestination(host, port);

        Forager forager = new Forager(overlord);
        forager.start();
    }
}

Send join message on startup

Send join message on startup


/*
 * Aerospike Client - Java Library
 *
 * Copyright 2013 by Aerospike, Inc. All rights reserved.
 *
 * Availability of this source code to partners and customers includes
 * redistribution rights covered by individual contract. Please check your
 * contract for exact rights and responsibilities.
 */
package com.aerospike.client.async;

import com.aerospike.client.AerospikeException;
import com.aerospike.client.cluster.Node;
import com.aerospike.client.listener.RecordSequenceListener;
import com.aerospike.client.policy.ScanPolicy;

public final class AsyncScanExecutor extends AsyncMultiExecutor {
	private final RecordSequenceListener listener;

	public AsyncScanExecutor(
		AsyncCluster cluster,
		ScanPolicy policy,
		RecordSequenceListener listener,
		String namespace,
		String setName,
		String[] binNames
	) throws AerospikeException {
		this.listener = listener;

		Node[] nodes = cluster.getNodes();
		completedSize = nodes.length;

		for (Node node : nodes) {
			AsyncScan async = new AsyncScan(this, cluster, (AsyncNode)node, policy, listener, namespace, setName, binNames);
			async.execute();
		}
	}

	protected void onSuccess() {
		listener.onSuccess();
	}

	protected void onFailure(AerospikeException ae) {
		listener.onFailure(ae);
	}
}

/*
 * Aerospike Client - Java Library
 *
 * Copyright 2013 by Aerospike, Inc. All rights reserved.
 *
 * Availability of this source code to partners and customers includes
 * redistribution rights covered by individual contract. Please check your
 * contract for exact rights and responsibilities.
 */
package com.aerospike.client.async;

import com.aerospike.client.AerospikeException;
import com.aerospike.client.ResultCode;
import com.aerospike.client.cluster.Node;
import com.aerospike.client.listener.RecordSequenceListener;
import com.aerospike.client.policy.ScanPolicy;

public final class AsyncScanExecutor extends AsyncMultiExecutor {
	private final RecordSequenceListener listener;

	public AsyncScanExecutor(
		AsyncCluster cluster,
		ScanPolicy policy,
		RecordSequenceListener listener,
		String namespace,
		String setName,
		String[] binNames
	) throws AerospikeException {
		this.listener = listener;

		Node[] nodes = cluster.getNodes();
		if (nodes.length == 0) {
			throw new AerospikeException(ResultCode.SERVER_NOT_AVAILABLE, "Scan failed because cluster is empty.");
		}

		completedSize = nodes.length;

		for (Node node : nodes) {
			AsyncScan async = new AsyncScan(this, cluster, (AsyncNode)node, policy, listener, namespace, setName, binNames);
			async.execute();
		}
	}

	protected void onSuccess() {
		listener.onSuccess();
	}

	protected void onFailure(AerospikeException ae) {
		listener.onFailure(ae);
	}
}

Throw exception when running scan/query and the cluster is empty.


package pro.jtaylor.timetracker.core;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import pro.jtaylor.timetracker.core.dao.TimeEntry;

import java.util.List;

@Component
public class Tracker {
    @Autowired
    private List<TimeEntry> entries;

    /**
     * Add Method
     * @param int add for entries
     */

    public void add(TimeEntry entry) {
        entries.add(entry);
    }

    /**
     * Remove Method
     * @param int remove for entries
     */

    public void remove(TimeEntry entry) {
        entries.remove(entry);
    }

    /**
     * Size Method
     * @param int size for entries
     */

    public int size() {
        return entries.size();
    }

    /**
     * Get Method
     * @param TimeEntry get for entries
     */

    public TimeEntry get(int index) {

        // boolean vaild = false;
        // if (vaild == true) {
        // whatever
        //
        return entries.get(index);
    }
}

Update line end and EOF for build fail

Update line end and EOF for build fail


package de.static_interface.sinkcity;

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

public enum CitySettings {

    FIRE(0b0000_0001),
    MOBS(0b0000_0010),
    TNT_BUILD(0b0000_0100),
    TNT_EXPLODE(0b0000_1000),
    EXPLOSION(0b0001_0000);

    private int activatedPattern;

    private CitySettings(int activatedPattern) {
        this.activatedPattern = activatedPattern;
    }

    public static List<CitySettings> getActivatedCitySettings(int citySettings) {
        List<CitySettings> activatedSettings = new ArrayList<CitySettings>();
        for (CitySettings settings : CitySettings.values()) {
            if ((citySettings & settings.activatedPattern) == settings.activatedPattern)
                activatedSettings.add(settings);
        }

        return activatedSettings;
    }

    public static boolean settingActivated(CitySettings setting, int citySettings) {
        return ((setting.activatedPattern & citySettings) == setting.activatedPattern);
    }
}

package de.static_interface.sinkcity;

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

public enum CitySettings {

    FIRE(0b0000_0001),
    MOBS(0b0000_0010),
    TNT_BUILD(0b0000_0100),
    TNT_EXPLODE(0b0000_1000),
    EXPLOSION(0b0001_0000),
    OPEN_CITY(0b0010_0000);

    private int activatedPattern;

    private CitySettings(int activatedPattern) {
        this.activatedPattern = activatedPattern;
    }

    public static List<CitySettings> getActivatedCitySettings(int citySettings) {
        List<CitySettings> activatedSettings = new ArrayList<CitySettings>();
        for (CitySettings settings : CitySettings.values()) {
            if ((citySettings & settings.activatedPattern) == settings.activatedPattern)
                activatedSettings.add(settings);
        }

        return activatedSettings;
    }

    public static boolean settingActivated(CitySettings setting, int citySettings) {
        return ((setting.activatedPattern & citySettings) == setting.activatedPattern);
    }
}

Switch from YML configuration files to XML configuration files.


package name.falgout.jeffrey.throwing;

import java.util.Objects;
import java.util.Optional;
import java.util.function.Function;

@FunctionalInterface
public interface RethrowChain<X extends Throwable, Y extends Throwable>
    extends Function<X, Optional<Y>> {
  public static <Y extends Throwable> RethrowChain<Throwable, Y> castTo(Class<Y> clazz) {
    return e -> Optional.ofNullable(clazz.isInstance(e) ? clazz.cast(e) : null);
  }

  default public RethrowChain<X, Y> connect(RethrowChain<X, Y> link) {
    Objects.requireNonNull(link);
    return x -> {
      Optional<Y> y = apply(x);
      if (y.isPresent()) {
        return y;
      }

      return link.apply(x);
    };
  }

  default public <Z extends Throwable> RethrowChain<X, Z> rethrow(
      Function<? super Y, ? extends Z> mapper) {
    Objects.requireNonNull(mapper);
    return x -> apply(x).map(mapper);
  }

  default public Function<X, Y> finish() {
    return finish(x -> {
      throw new AssertionError(x);
    });
  }

  default public Function<X, Y> finish(Function<? super X, ? extends Y> unhandledException) {
    Objects.requireNonNull(unhandledException);
    return x -> {
      return apply(x).orElseGet(() -> {
        if (x instanceof RuntimeException) {
          throw (RuntimeException) x;
        } else if (x instanceof Error) {
          throw (Error) x;
        }

        return unhandledException.apply(x);
      });
    };
  }
}

package name.falgout.jeffrey.throwing;

import java.util.Objects;
import java.util.Optional;
import java.util.function.Function;

@FunctionalInterface
public interface RethrowChain<X extends Throwable, Y extends Throwable>
    extends Function<X, Optional<Y>> {
  public static <Y extends Throwable> RethrowChain<Throwable, Y> castTo(Class<? extends Y> clazz) {
    return e -> Optional.ofNullable(clazz.isInstance(e) ? clazz.cast(e) : null);
  }

  default public RethrowChain<X, Y> connect(RethrowChain<X, Y> link) {
    Objects.requireNonNull(link);
    return x -> {
      Optional<Y> y = apply(x);
      if (y.isPresent()) {
        return y;
      }

      return link.apply(x);
    };
  }

  default public <Z extends Throwable> RethrowChain<X, Z> rethrow(
      Function<? super Y, ? extends Z> mapper) {
    Objects.requireNonNull(mapper);
    return x -> apply(x).map(mapper);
  }

  default public Function<X, Y> finish() {
    return finish(x -> {
      throw new AssertionError(x);
    });
  }

  default public Function<X, Y> finish(Function<? super X, ? extends Y> unhandledException) {
    Objects.requireNonNull(unhandledException);
    return x -> {
      return apply(x).orElseGet(() -> {
        if (x instanceof RuntimeException) {
          throw (RuntimeException) x;
        } else if (x instanceof Error) {
          throw (Error) x;
        }

        return unhandledException.apply(x);
      });
    };
  }
}

Allow castTo to automatically widen the generic bound.


package to.etc.domui.test.binding;

import org.junit.Assert;
import org.junit.Test;
import to.etc.domui.test.binding.order1.TestBindingOrder1;
import to.etc.domui.webdriver.core.AbstractWebDriverTest;

/**
 * @author Frits Jalvingh
 *         Created on 15-3-17.
 */
public class TestBindingOrder extends AbstractWebDriverTest {
	@Test
	public void testBinding1() throws Exception {
		wd().openScreen(TestBindingOrder1.class);

		//-- Switching country should switch city
		wd().select("country", "Netherlands");
		String city = wd().selectGetSelectedLabel("city");
		Assert.assertEquals("Amsterdam", city);

		wd().select("country", "USA");
		city = wd().selectGetSelectedLabel("city");
		Assert.assertEquals("New York", city);

		//-- Switching city to a city in another country should  change country
		wd().select("city", "Lelystad");
		city = wd().selectGetSelectedLabel("country");
		Assert.assertEquals("Netherlands", city);

		//-- Switching city to another in the same country
		wd().select("city", "Amsterdam");
		city = wd().selectGetSelectedLabel("country");
		Assert.assertEquals("Netherlands", city);

		Thread.sleep(10000);
	}
}

package to.etc.domui.test.binding;

import org.junit.Assert;
import org.junit.Test;
import to.etc.domui.test.binding.order1.TestBindingOrder1;
import to.etc.domui.webdriver.core.AbstractWebDriverTest;

/**
 * @author Frits Jalvingh
 *         Created on 15-3-17.
 */
public class TestBindingOrder extends AbstractWebDriverTest {

	/**
	 * https://etc.to/confluence/display/DOM/Tests%3A+data+binding
	 * @throws Exception
	 */
	@Test
	public void testBinding1() throws Exception {
		wd().openScreen(TestBindingOrder1.class);

		//-- Switching country should switch city
		wd().select("country", "Netherlands");
		String city = wd().selectGetSelectedLabel("city");
		Assert.assertEquals("Amsterdam", city);

		wd().select("country", "USA");
		city = wd().selectGetSelectedLabel("city");
		Assert.assertEquals("New York", city);

		//-- Switching city to a city in another country should  change country
		wd().select("city", "Lelystad");
		city = wd().selectGetSelectedLabel("country");
		Assert.assertEquals("Netherlands", city);

		//-- Switching city to another in the same country
		wd().select("city", "Amsterdam");
		city = wd().selectGetSelectedLabel("country");
		Assert.assertEquals("Netherlands", city);

		Thread.sleep(10000);
	}
}

Add wiki note for test.

[webdriver] Add wiki note for test.


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

package com.google.gerrit.server.git;

import com.google.gerrit.lifecycle.LifecycleModule;
import com.google.gerrit.server.config.RepositoryConfig;
import com.google.inject.Inject;

/**
 * Module to install {@link MultiBaseLocalDiskRepositoryManager} rather than {@link
 * LocalDiskRepositoryManager} if needed.
 */
public class GitRepositoryManagerModule extends LifecycleModule {

  private final RepositoryConfig repoConfig;

  @Inject
  public GitRepositoryManagerModule(RepositoryConfig repoConfig) {
    this.repoConfig = repoConfig;
  }

  @Override
  protected void configure() {
    if (repoConfig.getAllBasePaths().isEmpty()) {
      install(new LocalDiskRepositoryManager.Module());
    } else {
      install(new MultiBaseLocalDiskRepositoryManager.Module());
    }
  }
}

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

package com.google.gerrit.server.git;

import com.google.gerrit.lifecycle.LifecycleModule;
import com.google.gerrit.server.ModuleImpl;
import com.google.gerrit.server.config.RepositoryConfig;
import com.google.inject.Inject;

/**
 * Module to install {@link MultiBaseLocalDiskRepositoryManager} rather than {@link
 * LocalDiskRepositoryManager} if needed.
 */
@ModuleImpl(name = GitRepositoryManagerModule.MANAGER_MODULE)
public class GitRepositoryManagerModule extends LifecycleModule {
  public static final String MANAGER_MODULE = "git-manager";

  private final RepositoryConfig repoConfig;

  @Inject
  public GitRepositoryManagerModule(RepositoryConfig repoConfig) {
    this.repoConfig = repoConfig;
  }

  @Override
  protected void configure() {
    if (repoConfig.getAllBasePaths().isEmpty()) {
      install(new LocalDiskRepositoryManager.Module());
    } else {
      install(new MultiBaseLocalDiskRepositoryManager.Module());
    }
  }
}

Add possibility to override MultiBaseLocalDiskRepositoryManager

Add possibility to override MultiBaseLocalDiskRepositoryManager in lib
module by making GitRepositoryManagerModule as replaceable with module
that is annotated with 'git-manager' name.

Bug: Issue 15407
Change-Id: Ie470a035167225494d2b6f1977a0f7988f164aa4


package org.apache.ibatis.parsing;

import org.apache.ibatis.io.Resources;
import static org.junit.Assert.assertEquals;
import org.junit.Test;

import java.io.Reader;

public class XPathParserTest {

  @Test
  public void shouldTestXPathParserMethods() throws Exception {
    String resource = "resources/nodelet_test.xml";
    Reader reader = Resources.getResourceAsReader(resource);
    XPathParser parser = new XPathParser(reader, false, null, null);
    assertEquals((long)1970, parser.evalLong("/employee/birth_date/year"));
    assertEquals((short)6, parser.evalShort("/employee/birth_date/month"));
    assertEquals(15, parser.evalInteger("/employee/birth_date/day"));
    assertEquals(5.8f, parser.evalFloat("/employee/height"));
    assertEquals(5.8d, parser.evalDouble("/employee/height"));
    assertEquals("${id_var}", parser.evalString("/employee/@id"));
    assertEquals(Boolean.TRUE, parser.evalBoolean("/employee/active"));
    assertEquals("<id>${id_var}</id>", parser.evalNode("/employee/@id").toString().trim());
    assertEquals(7, parser.evalNodes("/employee/*").size());
    XNode node = parser.evalNode("/employee/height");
    assertEquals("employee/height", node.getPath());
    assertEquals("employee[${id_var}]_height", node.getValueBasedIdentifier());
  }

}

package org.apache.ibatis.parsing;

import org.apache.ibatis.io.Resources;
import static org.junit.Assert.assertEquals;
import org.junit.Test;

import java.io.Reader;

public class XPathParserTest {

  @Test
  public void shouldTestXPathParserMethods() throws Exception {
    String resource = "resources/nodelet_test.xml";
    Reader reader = Resources.getResourceAsReader(resource);
    XPathParser parser = new XPathParser(reader, false, null, null);
    assertEquals((Long)1970l, parser.evalLong("/employee/birth_date/year"));
    assertEquals((short) 6, (short) parser.evalShort("/employee/birth_date/month"));
    assertEquals((Integer) 15, parser.evalInteger("/employee/birth_date/day"));
    assertEquals((Float) 5.8f, parser.evalFloat("/employee/height"));
    assertEquals((Double) 5.8d, parser.evalDouble("/employee/height"));
    assertEquals("${id_var}", parser.evalString("/employee/@id"));
    assertEquals(Boolean.TRUE, parser.evalBoolean("/employee/active"));
    assertEquals("<id>${id_var}</id>", parser.evalNode("/employee/@id").toString().trim());
    assertEquals(7, parser.evalNodes("/employee/*").size());
    XNode node = parser.evalNode("/employee/height");
    assertEquals("employee/height", node.getPath());
    assertEquals("employee[${id_var}]_height", node.getValueBasedIdentifier());
  }

}

Fix test so that it works with Junit 4.6

git-svn-id: 38b70485df25d5e096a1845b40b72a0bf0ca9ea6@2409 6a4a4fef-ff2a-56b0-fee9-946765563393


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

import java.util.Iterator;
import java.util.Map;
import java.util.Set;

import org.apache.commons.modeler.util.IntrospectionUtils;

public abstract class BaseGBean {

    protected void setParameters(Object object, Map map){
        if (map != null){
            Set keySet = map.keySet();
            Iterator iterator = keySet.iterator();
            while(iterator.hasNext()){
                String name = (String)iterator.next();
                String value = (String)map.get(name);

                IntrospectionUtils.setProperty(object, name, value);
            }
        }

    }

}

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

import java.util.Iterator;
import java.util.Map;
import java.util.Set;

import org.apache.tomcat.util.IntrospectionUtils;

public abstract class BaseGBean {

    protected void setParameters(Object object, Map map){
        if (map != null){
            Set keySet = map.keySet();
            Iterator iterator = keySet.iterator();
            while(iterator.hasNext()){
                String name = (String)iterator.next();
                String value = (String)map.get(name);

                IntrospectionUtils.setProperty(object, name, value);
            }
        }

    }

}

Use the Tomcat INtrospection utilities instead of commons modeler

git-svn-id: d69ffe4ccc4861bf06065bd0072b85c931fba7ed@357261 13f79535-47bb-0310-9956-ffa450edef68


package org.literacyapp.model.gson;

import java.util.Calendar;
import org.literacyapp.model.gson.analytics.StudentImageCollectionEventGson;

public class StudentImageGson extends BaseEntityGson {

    private DeviceGson device;

    private Calendar timeCollected;

    private String imageFileUrl;

    private StudentImageFeatureGson studentImageFeature;

    private StudentImageCollectionEventGson studentImageCollectionEvent;

    public DeviceGson getDevice() {
        return device;
    }

    public void setDevice(DeviceGson device) {
        this.device = device;
    }

    public Calendar getTimeCollected() {
        return timeCollected;
    }

    public void setTimeCollected(Calendar timeCollected) {
        this.timeCollected = timeCollected;
    }

    public String getImageFileUrl() {
        return imageFileUrl;
    }

    public void setImageFileUrl(String imageFileUrl) {
        this.imageFileUrl = imageFileUrl;
    }

    public StudentImageFeatureGson getStudentImageFeature() {
        return studentImageFeature;
    }

    public void setStudentImageFeature(StudentImageFeatureGson studentImageFeature) {
        this.studentImageFeature = studentImageFeature;
    }

    public StudentImageCollectionEventGson getStudentImageCollectionEvent() {
        return studentImageCollectionEvent;
    }

    public void setStudentImageCollectionEvent(StudentImageCollectionEventGson studentImageCollectionEvent) {
        this.studentImageCollectionEvent = studentImageCollectionEvent;
    }
}

package org.literacyapp.model.gson;

import java.util.Calendar;
import org.literacyapp.model.gson.analytics.StudentImageCollectionEventGson;

public class StudentImageGson extends BaseEntityGson {

    private Calendar timeCollected;

    private String imageFileUrl;

    private StudentImageFeatureGson studentImageFeature;

    private StudentImageCollectionEventGson studentImageCollectionEvent;

    public Calendar getTimeCollected() {
        return timeCollected;
    }

    public void setTimeCollected(Calendar timeCollected) {
        this.timeCollected = timeCollected;
    }

    public String getImageFileUrl() {
        return imageFileUrl;
    }

    public void setImageFileUrl(String imageFileUrl) {
        this.imageFileUrl = imageFileUrl;
    }

    public StudentImageFeatureGson getStudentImageFeature() {
        return studentImageFeature;
    }

    public void setStudentImageFeature(StudentImageFeatureGson studentImageFeature) {
        this.studentImageFeature = studentImageFeature;
    }

    public StudentImageCollectionEventGson getStudentImageCollectionEvent() {
        return studentImageCollectionEvent;
    }

    public void setStudentImageCollectionEvent(StudentImageCollectionEventGson studentImageCollectionEvent) {
        this.studentImageCollectionEvent = studentImageCollectionEvent;
    }
}

Remove device from student image

Remove device from student image


package org.zalando.pazuzu.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

@Configuration
public class CorsConfiguration {

    @Value("${pazuzu.registry.cors.allowedOrigins:}")
    private String allowedOrigins;

    @Bean
    public WebMvcConfigurer corsConfigurer() {
        return new WebMvcConfigurerAdapter() {
            @Override
            public void addCorsMappings(CorsRegistry registry) {
                registry.addMapping("/api/**").allowedOrigins(allowedOrigins);
            }
        };
    }
}

package org.zalando.pazuzu.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

@Configuration
public class CorsConfiguration {

    @Value("${pazuzu.registry.cors.allowedOrigins:}")
    private String allowedOrigins;

    @Bean
    public WebMvcConfigurer corsConfigurer() {
        return new WebMvcConfigurerAdapter() {
            @Override
            public void addCorsMappings(CorsRegistry registry) {
                registry
                        .addMapping("/api/**")
                        .allowedOrigins(allowedOrigins)
                        .allowedMethods("GET", "PUT", "POST", "DELETE");
            }
        };
    }
}

Set the allowed methods to all required ones.

The Spring boot default ones do not allow for `PUT` and `DELETE`.


package org.commcare.suite.model;

/**
 * Piece of required session data that is acquired via an xpath computation
 *
 * @author Phillip Mates (pmates@dimagi.com)
 */
public class ComputedDatum extends SessionDatum {
    public ComputedDatum() {

    }

    /**
     * @param id    Name used to access the computed data in the session instance
     * @param value XPath expression whose evaluation result is used as the data
     */
    public ComputedDatum(String id, String value) {
        super(id, value);
    }
}

package org.commcare.suite.model;

/**
 * Piece of required session data that is acquired via an xpath computation
 *
 * @author Phillip Mates (pmates@dimagi.com)
 */
public class ComputedDatum extends SessionDatum {
    @SuppressWarnings("unused")
    public ComputedDatum() {
        // used in serialization
    }

    /**
     * @param id    Name used to access the computed data in the session instance
     * @param value XPath expression whose evaluation result is used as the data
     */
    public ComputedDatum(String id, String value) {
        super(id, value);
    }
}

Add suppress unused & comment

Add suppress unused & comment


package woko.actions;

import java.util.Enumeration;
import java.util.Locale;
import java.util.MissingResourceException;
import java.util.ResourceBundle;

public class WokoResourceBundle extends ResourceBundle {

  private Locale locale;

  public WokoResourceBundle(Locale locale) {
    this.locale = locale;
  }

  @Override
  public Enumeration<String> getKeys() {
    return null;
  }

  @Override
  protected Object handleGetObject(String fullKey) {
      return getResult(locale, "WokoResources", fullKey);
  }

  // Just returns null if the bundle or the key is not found,
  // instead of throwing an exception.
  private String getResult(Locale loc, String name, String key) {
    String result = null;
    ResourceBundle bundle = ResourceBundle.getBundle(name, loc);
    if (bundle != null) {
      try { result = bundle.getString(key); }
      catch (MissingResourceException exc) { }
    }
    return result;
  }
}

package woko.actions;

import java.util.Enumeration;
import java.util.Locale;
import java.util.MissingResourceException;
import java.util.ResourceBundle;

public class WokoResourceBundle extends ResourceBundle {

    private static final String WOKO_RESOURCES_BUNDLE = "WokoResources";
    private static final String APP_RESOURCES_BUNDLE = "ApplicationResources";

    private Locale locale;

    public WokoResourceBundle(Locale locale) {
        this.locale = locale;
    }

    @Override
    public Enumeration<String> getKeys() {
        return null;
    }

    @Override
    protected Object handleGetObject(String fullKey) {
        // First, try to get resources from app specific bundle
        String result = getResult(locale, APP_RESOURCES_BUNDLE, fullKey);
        if (result == null)
            result = getResult(locale, WOKO_RESOURCES_BUNDLE, fullKey);

        return result;

    }

    // Just returns null if the bundle or the key is not found,
    // instead of throwing an exception.
    private String getResult(Locale loc, String name, String key) {
        String result = null;
        ResourceBundle bundle = ResourceBundle.getBundle(name, loc);
        if (bundle != null) {
            try { result = bundle.getString(key); }
            catch (MissingResourceException exc) { }
        }
        return result;
    }
}

Add specific Resource bundle management

Add specific Resource bundle management


package com.kickstarter.services.gcm;

import android.app.IntentService;
import android.content.Intent;
import android.support.annotation.NonNull;

import com.google.android.gms.gcm.GoogleCloudMessaging;
import com.google.android.gms.iid.InstanceID;
import com.kickstarter.R;

import timber.log.Timber;

public class UnregisterService extends IntentService {
  private static final String WORKER_THREAD_NAME = "UnregisterService";

  public UnregisterService() {
    super(WORKER_THREAD_NAME);
  }

  @Override
  protected void onHandleIntent(@NonNull final Intent intent) {
    Timber.d("onHandleIntent");

    try {
      final InstanceID instanceID = InstanceID.getInstance(this);
      instanceID.deleteToken(getString(R.string.gcm_defaultSenderId), GoogleCloudMessaging.INSTANCE_ID_SCOPE);
      Timber.d("Deleted token");
    } catch (final Exception e) {
      Timber.e("Failed to delete token: " + e.toString());
    }
  }
}

package com.kickstarter.services.gcm;

import android.app.IntentService;
import android.content.Intent;
import android.support.annotation.NonNull;

import com.google.android.gms.gcm.GoogleCloudMessaging;
import com.google.android.gms.iid.InstanceID;
import com.kickstarter.R;

import timber.log.Timber;

public class UnregisterService extends IntentService {
  public UnregisterService() {
    super("UnregisterService");
  }

  @Override
  protected void onHandleIntent(@NonNull final Intent intent) {
    Timber.d("onHandleIntent");

    try {
      final InstanceID instanceID = InstanceID.getInstance(this);
      instanceID.deleteToken(getString(R.string.gcm_defaultSenderId), GoogleCloudMessaging.INSTANCE_ID_SCOPE);
      Timber.d("Deleted token");
    } catch (final Exception e) {
      Timber.e("Failed to delete token: " + e.toString());
    }
  }
}

Remove constant only used once

Remove constant only used once


package com.github.mobile.android.repo;

import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.github.mobile.android.R.id;
import com.github.mobile.android.util.AvatarHelper;
import com.madgag.android.listviews.ViewHolder;

import org.eclipse.egit.github.core.User;

/**
 * View holder to display a user/organization
 */
public class OrgViewHolder implements ViewHolder<User> {

    private final AvatarHelper avatarHelper;

    private final TextView nameText;

    private final ImageView avatarView;

    /**
     * Create org view holder
     *
     * @param view
     * @param avatarHelper
     */
    public OrgViewHolder(final View view, final AvatarHelper avatarHelper) {
        this.avatarHelper = avatarHelper;
        nameText = (TextView) view.findViewById(id.tv_org_name);
        avatarView = (ImageView) view.findViewById(id.iv_gravatar);
    }

    @Override
    public void updateViewFor(User user) {
        nameText.setText(user.getLogin());
        avatarView.setBackgroundDrawable(null);
        avatarHelper.bind(avatarView, user);
    }
}

package com.github.mobile.android.repo;

import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.github.mobile.android.R.id;
import com.github.mobile.android.util.AvatarHelper;
import com.madgag.android.listviews.ViewHolder;

import org.eclipse.egit.github.core.User;

/**
 * View holder to display a user/organization
 */
public class OrgViewHolder implements ViewHolder<User> {

    private final AvatarHelper avatarHelper;

    private final TextView nameText;

    private final ImageView avatarView;

    /**
     * Create org view holder
     *
     * @param view
     * @param avatarHelper
     */
    public OrgViewHolder(final View view, final AvatarHelper avatarHelper) {
        this.avatarHelper = avatarHelper;
        nameText = (TextView) view.findViewById(id.tv_org_name);
        avatarView = (ImageView) view.findViewById(id.iv_gravatar);
    }

    @Override
    public void updateViewFor(final User user) {
        nameText.setText(user.getLogin());
        avatarView.setBackgroundDrawable(null);
        avatarHelper.bind(avatarView, user);
    }
}

Mark user parameter as final

Mark user parameter as final


package org.metaborg.util.arrays;

import java.util.Collection;

public final class Arrays2 {
    public static <T> boolean addAll(Collection<T> addTo, T[] elementsToAdd) {
        boolean modified = false;
        for(T e : elementsToAdd) {
            modified = modified || addTo.add(e);
        }
        return modified;
    }
}

package org.metaborg.util.arrays;

import java.util.Collection;

public final class Arrays2 {
    public static <T> boolean addAll(Collection<T> addTo, T[] elementsToAdd) {
        boolean modified = false;
        for(T e : elementsToAdd) {
            modified = addTo.add(e) || modified;
        }
        return modified;
    }
}

Fix only one element being added.

Fix only one element being added.


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

package android.arch.lifecycle;

import android.media.PlaybackParams;
import android.os.Build;
import android.support.test.filters.SdkSuppress;
import android.support.test.filters.SmallTest;
import android.support.test.runner.AndroidJUnit4;

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

@RunWith(AndroidJUnit4.class)
@SdkSuppress(maxSdkVersion = Build.VERSION_CODES.N_MR1)
@SmallTest
public class MissingClassTest {
    public static class ObserverWithMissingClasses {
        @SuppressWarnings("unused")
        public void newApiMethod(PlaybackParams params) {}

        @OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
        public void onResume() {}
    }

    @Test(expected = IllegalArgumentException.class)
    public void testMissingApi() {
        new ReflectiveGenericLifecycleObserver(new ObserverWithMissingClasses());
    }
}

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

package android.arch.lifecycle;

import android.app.PictureInPictureParams;
import android.os.Build;
import android.support.test.filters.SdkSuppress;
import android.support.test.filters.SmallTest;
import android.support.test.runner.AndroidJUnit4;

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

@RunWith(AndroidJUnit4.class)
@SdkSuppress(maxSdkVersion = Build.VERSION_CODES.N_MR1)
@SmallTest
public class MissingClassTest {
    public static class ObserverWithMissingClasses {
        @SuppressWarnings("unused")
        public void newApiMethod(PictureInPictureParams params) {}

        @OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
        public void onResume() {}
    }

    @Test(expected = IllegalArgumentException.class)
    public void testMissingApi() {
        new ReflectiveGenericLifecycleObserver(new ObserverWithMissingClasses());
    }
}

[automerger] Merge "Use api from 26" into oc-mr1-support-27.0-dev am: f5c970b5df am: 0e91a7eccb

Change-Id: Ie2bf4613e238a264bcbcff78f4e28d0e33bb2b82


package com.github.ferstl.jarscan;

import org.adoptopenjdk.jitwatch.jarscan.IJarScanOperation;
import org.adoptopenjdk.jitwatch.jarscan.freqinlinesize.FreqInlineSizeOperation;
import org.apache.maven.plugins.annotations.LifecyclePhase;
import org.apache.maven.plugins.annotations.Mojo;
import org.apache.maven.plugins.annotations.Parameter;
import org.apache.maven.plugins.annotations.ResolutionScope;

/**
 * List every method with bytecode larger than specified limit.
 */
@Mojo(
    name = "maxMethodSize",
    aggregator = false,
    defaultPhase = LifecyclePhase.VERIFY,
    requiresDependencyCollection = ResolutionScope.TEST,
    requiresDependencyResolution = ResolutionScope.TEST,
    requiresDirectInvocation = false,
    threadSafe = true)
public class MaxMethodSizeMojo extends AbstractJarScanMojo {

  /**
   * Report methods larger than the specified bytes. The default for {@code -XX:MaxInlineSize} is 35. The default for
   * {@code -XX:FreqInlineSize} is 325.
   *
   * @since 1.1.0
   */
  @Parameter(property = "limit", defaultValue = "0")
  private int limit;

  @Override
  protected IJarScanOperation createOperation() {
    return new FreqInlineSizeOperation(this.limit);
  }

}

package com.github.ferstl.jarscan;

import org.adoptopenjdk.jitwatch.jarscan.IJarScanOperation;
import org.adoptopenjdk.jitwatch.jarscan.freqinlinesize.FreqInlineSizeOperation;
import org.apache.maven.plugins.annotations.LifecyclePhase;
import org.apache.maven.plugins.annotations.Mojo;
import org.apache.maven.plugins.annotations.Parameter;
import org.apache.maven.plugins.annotations.ResolutionScope;

/**
 * List every method with bytecode larger than specified limit.
 *
 * @since 1.1
 */
@Mojo(
    name = "maxMethodSize",
    aggregator = false,
    defaultPhase = LifecyclePhase.VERIFY,
    requiresDependencyCollection = ResolutionScope.TEST,
    requiresDependencyResolution = ResolutionScope.TEST,
    requiresDirectInvocation = false,
    threadSafe = true)
public class MaxMethodSizeMojo extends AbstractJarScanMojo {

  /**
   * Report methods larger than the specified bytes. The default for {@code -XX:MaxInlineSize} is 35. The default for
   * {@code -XX:FreqInlineSize} is 325.
   *
   * @since 1.1
   */
  @Parameter(property = "limit", defaultValue = "0")
  private int limit;

  @Override
  protected IJarScanOperation createOperation() {
    return new FreqInlineSizeOperation(this.limit);
  }

}

Add @since to class Javadoc

Add @since to class Javadoc


package com.quizdeck.model.inputs;

import com.quizdeck.model.database.Quiz;
import com.quizdeck.model.database.submission;
import lombok.Getter;
import lombok.Setter;

import javax.validation.constraints.NotNull;
import java.util.List;

/**
 * Created by Cade on 2/17/2016.
 */
@Getter
@Setter
public class CompleteQuizInput {

    @NotNull
    private Quiz quiz;

    @NotNull
    private String quizId;

    @NotNull
    private List<submission> submissions;

    public CompleteQuizInput(String quizId, Quiz quiz, List<submission> submissions) {
        this.quizId = quizId;
        this.quiz = quiz;
        this.submissions = submissions;
    }

}

package com.quizdeck.model.inputs;

import com.quizdeck.model.database.Quiz;
import com.quizdeck.model.database.submission;
import lombok.Getter;
import lombok.Setter;

import javax.validation.constraints.NotNull;
import java.util.List;

/**
 * Created by Cade on 2/17/2016.
 */
@Getter
@Setter
public class CompleteQuizInput {

    @NotNull
    private Quiz quiz;

    @NotNull
    private String quizId;

    @NotNull
    private List<submission> submissions;

    public CompleteQuizInput() {}

    public CompleteQuizInput(String quizId, Quiz quiz, List<submission> submissions) {
        this.quizId = quizId;
        this.quiz = quiz;
        this.submissions = submissions;
    }

}

Add default constructor for Jackson

Add default constructor for Jackson


package org.helioviewer.jhv.timelines.data;

import java.util.HashMap;

public class BandType {

    private String baseURL;
    private String label;
    private String name;
    private String unitLabel;
    private final HashMap<String, Double> warnLevels = new HashMap<>();
    private double min;
    private double max;
    private boolean isLog = false;

    @Override
    public String toString() {
        return label;
    }

    public String getBaseURL() {
        return baseURL;
    }

    public void setBaseURL(String _baseURL) {
        baseURL = _baseURL;
    }

    public String getLabel() {
        return label;
    }

    public void setLabel(String _label) {
        label = _label;
    }

    public String getUnitLabel() {
        return unitLabel;
    }

    public void setUnitLabel(String _unitLabel) {
        unitLabel = _unitLabel;
    }

    public HashMap<String, Double> getWarnLevels() {
        return warnLevels;
    }

    public double getMin() {
        return min;
    }

    public void setMin(double _min) {
        min = _min;
    }

    public double getMax() {
        return max;
    }

    public void setMax(double _max) {
        max = _max;
    }

    public void setName(String _name) {
        name = _name;
    }

    public String getName() {
        return name;
    }

    public void setScale(String scale) {
        isLog = scale.equals("logarithmic");
    }

    public boolean isLogScale() {
        return isLog;
    }

}

package org.helioviewer.jhv.timelines.data;

import java.util.HashMap;

public class BandType {

    private String label;
    private String name;
    private String unitLabel;
    private final HashMap<String, Double> warnLevels = new HashMap<>();
    private double min;
    private double max;
    private boolean isLog = false;
    private DataProvider dataprovider;

    @Override
    public String toString() {
        return label;
    }

    public String getLabel() {
        return label;
    }

    public void setLabel(String _label) {
        label = _label;
    }

    public String getUnitLabel() {
        return unitLabel;
    }

    public void setUnitLabel(String _unitLabel) {
        unitLabel = _unitLabel;
    }

    public HashMap<String, Double> getWarnLevels() {
        return warnLevels;
    }

    public double getMin() {
        return min;
    }

    public void setMin(double _min) {
        min = _min;
    }

    public double getMax() {
        return max;
    }

    public void setMax(double _max) {
        max = _max;
    }

    public void setName(String _name) {
        name = _name;
    }

    public String getName() {
        return name;
    }

    public void setScale(String scale) {
        isLog = scale.equals("logarithmic");
    }

    public boolean isLogScale() {
        return isLog;
    }

    public DataProvider getDataprovider() {
        return dataprovider;
    }

    public void setDataprovider(DataProvider dataprovider) {
        this.dataprovider = dataprovider;
    }

}

Replace baseURL with data provider.

Replace baseURL with data provider.

git-svn-id: 4e353c0944fe8da334633afc35765ef362dec675@8663 b4e469a2-07ce-4b26-9273-4d7d95a670c7


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

package net.uncontended.precipice.timeout;

import java.util.concurrent.TimeUnit;

public class NewTimerService {

    private final long resolution;
    private final long startTime;

    public NewTimerService(long resolution, TimeUnit unit) {
        this.resolution = unit.toMillis(resolution);
        startTime = TimeUnit.NANOSECONDS.toMillis(System.nanoTime());
    }

    public void schedule(Object task, long delay, TimeUnit unit) {

    }
}

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

package net.uncontended.precipice.timeout;

import java.util.concurrent.TimeUnit;

/**
 * Unstable and still in development. At this time, {@link TimeoutService} should be used.
 */
public class NewTimerService {

    private final long resolution;
    private final long startTime;

    public NewTimerService(long resolution, TimeUnit unit) {
        this.resolution = unit.toMillis(resolution);
        startTime = TimeUnit.NANOSECONDS.toMillis(System.nanoTime());
    }

    public void schedule(Object task, long delay, TimeUnit unit) {

    }
}

Add comment about timeout service stability


/* IBM_PROLOG_BEGIN_TAG
 * This is an automatically generated prolog.
 *
 * $Source: src/java/test/blockmap/com/ibm/research/blockmap/CapiTestSupport.java $
 *
 * IBM Data Engine for NoSQL - Power Systems Edition User Library Project
 *
 * Contributors Listed Below - COPYRIGHT 2015,2016,2017
 * [+] International Business Machines Corp.
 *
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
 * implied. See the License for the specific language governing
 * permissions and limitations under the License.
 *
 * IBM_PROLOG_END_TAG
 */
package com.ibm.research.blockmap;

import org.junit.Ignore;

@Ignore
class CapiTestSupport {

	static final String DEVICE_PATH = "amd64".equals(System.getProperty("os.arch")) ? null : "/dev/sdf"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
    //static final String DEVICE_PATH="/dev/hdisk0";

}

/* IBM_PROLOG_BEGIN_TAG
 * This is an automatically generated prolog.
 *
 * $Source: src/java/test/blockmap/com/ibm/research/blockmap/CapiTestSupport.java $
 *
 * IBM Data Engine for NoSQL - Power Systems Edition User Library Project
 *
 * Contributors Listed Below - COPYRIGHT 2015,2016,2017
 * [+] International Business Machines Corp.
 *
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
 * implied. See the License for the specific language governing
 * permissions and limitations under the License.
 *
 * IBM_PROLOG_END_TAG
 */
package com.ibm.research.blockmap;

import org.junit.Ignore;

@Ignore
class CapiTestSupport {

	static final String DEVICE_PATH = "amd64".equals(System.getProperty("os.arch")) ? null : System.getProperty("CAPI_DEVICE_PATH", "/dev/sdf"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
    //static final String DEVICE_PATH="/dev/hdisk0";

}

Use the CAPI_DEVICE_PATH property in blockmap tests


package org.jeecqrs.common.event.sourcing;

/**
 *
 * @param <E>  the base event type
 */
public interface EventSourcingBus<E> {

    void persist(E event);

}

/*
 * Copyright (c) 2013 Red Rainbow IT Solutions GmbH, Germany
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy of
 * this software and associated documentation files (the "Software"), to deal in
 * the Software without restriction, including without limitation the rights to
 * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
 * the Software, and to permit persons to whom the Software is furnished to do so,
 * subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
 * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
 * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
 * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
 * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */

package org.jeecqrs.common.event.sourcing;

import java.util.List;
import org.jeecqrs.common.event.Event;

/**
 * Provides the ability to store a changes made during event sourcing.
 *
 * @param <E>  the base event type
 */
public interface EventSourcingBus<E extends Event> {

    void store(long originalVersion, List<E> changes);

}

Change signature of store method

Change signature of store method


package org.reldb.dbrowser.ui.content.recent;

import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.layout.FormLayout;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.FormData;
import org.eclipse.swt.layout.FormAttachment;
import org.reldb.dbrowser.ui.DbTab;

public class RecentPanel extends Composite {

	private Label lblConvert;

	/**
	 * Create the composite.
	 *
	 * @param parent
	 * @param style
	 */
	public RecentPanel(Composite parent, DbTab dbTab, int style) {
		super(parent, style);
		FormLayout formLayout = new FormLayout();
		formLayout.marginWidth = 5;
		formLayout.marginHeight = 5;
		setLayout(formLayout);

		lblConvert = new Label(this, SWT.NONE);
		FormData fd_lblConvert = new FormData();
		fd_lblConvert.top = new FormAttachment(0);
		fd_lblConvert.left = new FormAttachment(0);
		fd_lblConvert.right = new FormAttachment(100);
		lblConvert.setLayoutData(fd_lblConvert);
		lblConvert.setText("Recently-used database options go here.");
	}
}

package org.reldb.dbrowser.ui.content.recent;

import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.layout.FormLayout;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.FormData;
import org.eclipse.swt.layout.FormAttachment;
import org.reldb.dbrowser.ui.DbTab;

public class RecentPanel extends Composite {

	/**
	 * Create the composite.
	 *
	 * @param parent
	 * @param style
	 */
	public RecentPanel(Composite parent, DbTab dbTab, int style) {
		super(parent, style);
		FormLayout formLayout = new FormLayout();
		formLayout.marginWidth = 5;
		formLayout.marginHeight = 5;
		setLayout(formLayout);

		Label lblConvert = new Label(this, SWT.NONE);
		FormData fd_lblConvert = new FormData();
		fd_lblConvert.top = new FormAttachment(0);
		fd_lblConvert.left = new FormAttachment(0);
		fd_lblConvert.right = new FormAttachment(100);
		lblConvert.setLayoutData(fd_lblConvert);
		lblConvert.setText("Recently-used database options go here.");
	}
}

Work on Recently-Used Database tab.

Work on Recently-Used Database tab.


package com.atsebak.raspberrypi.protocol.ssh;

import lombok.Builder;
import net.schmizz.sshj.SSHClient;
import net.schmizz.sshj.transport.verification.PromiscuousVerifier;

import java.io.IOException;

@Builder
public class SSH {
    private int timeout;
    private int connectionTimeout;

    /**
     * Build an SSHJ SSH Client
     *
     * @return
     */
    public SSHClient toClient() {
        SSHClient sshClient = new SSHClient();
        try {
            sshClient.addHostKeyVerifier(new PromiscuousVerifier());
            sshClient.loadKnownHosts();
            sshClient.setConnectTimeout(connectionTimeout);
            sshClient.setTimeout(timeout);
        } catch (IOException e) {

        }
        return sshClient;
    }
}

package com.atsebak.raspberrypi.protocol.ssh;

import lombok.Builder;
import net.schmizz.sshj.SSHClient;
import net.schmizz.sshj.transport.verification.PromiscuousVerifier;

import java.io.IOException;

@Builder
public class SSH {
    private int timeout;
    private int connectionTimeout;

    /**
     * Build an SSHJ SSH Client
     *
     * @return
     */
    public SSHClient toClient() {
        SSHClient sshClient = new SSHClient();
        try {
            sshClient.addHostKeyVerifier(new PromiscuousVerifier());
            sshClient.setConnectTimeout(connectionTimeout);
            sshClient.setTimeout(timeout);
            sshClient.loadKnownHosts();
        } catch (IOException e) {

        }
        return sshClient;
    }
}

Fix issue with test breaking when loading known hosts


package org.javarosa.xpath.expr;

import org.javarosa.core.model.condition.EvaluationContext;
import org.javarosa.core.model.instance.DataInstance;
import org.javarosa.core.util.externalizable.DeserializationException;
import org.javarosa.core.util.externalizable.PrototypeFactory;
import org.javarosa.xpath.XPathUnsupportedException;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;

public class XPathUnionExpr extends XPathBinaryOpExpr {
    public XPathUnionExpr() {
    } //for deserialization

    public XPathUnionExpr(XPathExpression a, XPathExpression b) {
        super(-1, a, b);
    }

    @Override
    public Object evalRaw(DataInstance model, EvaluationContext evalContext) {
        throw new XPathUnsupportedException("nodeset union operation");
    }

    @Override
    public String toString() {
        return super.toString("union");
    }

    @Override
    public void readExternal(DataInputStream in, PrototypeFactory pf) throws IOException, DeserializationException {
        super.readExternal(in, pf);
    }

    @Override
    public void writeExternal(DataOutputStream out) throws IOException {
        super.writeExternal(out);
    }

    @Override
    public String toPrettyString() {
        return "unsupported union operation";
    }
}

package org.javarosa.xpath.expr;

import org.javarosa.core.model.condition.EvaluationContext;
import org.javarosa.core.model.instance.DataInstance;
import org.javarosa.core.util.externalizable.DeserializationException;
import org.javarosa.core.util.externalizable.PrototypeFactory;
import org.javarosa.xpath.XPathUnsupportedException;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;

public class XPathUnionExpr extends XPathBinaryOpExpr {
    public XPathUnionExpr() {
    } //for deserialization

    public XPathUnionExpr(XPathExpression a, XPathExpression b) {
        super(-1, a, b);
    }

    @Override
    public Object evalRaw(DataInstance model, EvaluationContext evalContext) {
        throw new XPathUnsupportedException("nodeset union operation");
    }

    @Override
    public String toString() {
        return super.toString("union");
    }

    @Override
    public void readExternal(DataInputStream in, PrototypeFactory pf) throws IOException, DeserializationException {
        readExpressions(in, pf);
        op = -1;
    }

    @Override
    public void writeExternal(DataOutputStream out) throws IOException {
        writeExpressions(out);
    }

    @Override
    public String toPrettyString() {
        return "unsupported union operation";
    }
}

Fix externalization oversite that would have required a migration


package com.rarchives.ripme.tst.ripper.rippers;

import com.rarchives.ripme.ripper.rippers.GfycatRipper;
import org.junit.jupiter.api.Test;

import java.io.IOException;
import java.net.URL;

public class GfycatRipperTest extends RippersTest {

    /**
     * Rips correctly formatted URL directly from Gfycat
     * @throws IOException
     */
    @Test
    public void testGfycatGoodURL() throws IOException{
        GfycatRipper ripper = new GfycatRipper(new URL("https://gfycat.com/TemptingExcellentIchthyosaurs"));
        testRipper(ripper);
    }
    /**
     * Rips badly formatted URL directly from Gfycat
     * @throws IOException
     */
    public void testGfycatBadURL() throws IOException {
        GfycatRipper ripper  = new GfycatRipper(new URL("https://gfycat.com/gifs/detail/limitedtestyamericancrow"));
        testRipper(ripper);
    }

    public void testGfycatProfile() throws IOException {
        GfycatRipper ripper  = new GfycatRipper(new URL("https://gfycat.com/@golbanstorage"));
        testRipper(ripper);
    }
}

package com.rarchives.ripme.tst.ripper.rippers;

import com.rarchives.ripme.ripper.rippers.GfycatRipper;
import org.junit.jupiter.api.Test;

import java.io.IOException;
import java.net.URL;

public class GfycatRipperTest extends RippersTest {

    /**
     * Rips correctly formatted URL directly from Gfycat
     * @throws IOException
     */
    @Test
    public void testGfycatGoodURL() throws IOException{
        GfycatRipper ripper = new GfycatRipper(new URL("https://gfycat.com/TemptingExcellentIchthyosaurs"));
        testRipper(ripper);
    }
    /**
     * Rips badly formatted URL directly from Gfycat
     * @throws IOException
     */
    public void testGfycatBadURL() throws IOException {
        GfycatRipper ripper  = new GfycatRipper(new URL("https://gfycat.com/gifs/detail/limitedtestyamericancrow"));
        testRipper(ripper);
    }

    /**
     * Rips a Gfycat profile
     * @throws IOException
     */
    public void testGfycatProfile() throws IOException {
        GfycatRipper ripper  = new GfycatRipper(new URL("https://gfycat.com/@golbanstorage"));
        testRipper(ripper);
    }

    /**
     * Rips a Gfycat amp link
     * @throws IOException
     */
    public void testGfycatAmp() throws IOException {
        GfycatRipper ripper = new GfycatRipper(new URL("https://gfycat.com/amp/TemptingExcellentIchthyosaurs"));
        testRipper(ripper);
    }
}

Add unit test for Gfycat Amp links

Add unit test for Gfycat Amp links


package jp.toastkid.article.search;

import static org.junit.Assert.assertNotNull;

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

import org.junit.Test;

/**
 * Test of {@link SearchResult}.
 * @author Toast kid
 *
 */
public class SearchResultTest {

    /**
     * Test of {@link SearchResult} constructor.
     * @throws IOException
     */
    @Test
    public void testSearchResult() throws IOException {
        final Path path = Files.createTempFile("temp", ".txt");
        final SearchResult searchResult = new SearchResult(path.toString());
        assertNotNull(searchResult.toString());
    }

    /**
     * Test of {@link SearchResult#makeSimple(String)}.
     *
     * @throws IOException
     */
    @Test
    public void testMakeSimple() throws IOException {
        final Path path = Files.createTempFile("temp", ".txt");
        final SearchResult simple = SearchResult.makeSimple(path.toString());
        assertNotNull(simple);
    }

}

package jp.toastkid.article.search;

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

import org.junit.Test;

import static org.junit.Assert.*;

/**
 * Test of {@link SearchResult}.
 * @author Toast kid
 *
 */
public class SearchResultTest {

    /**
     * Test of {@link SearchResult} constructor.
     * @throws IOException
     */
    @Test
    public void testSearchResult() throws IOException {
        final Path path = Files.createTempFile("temp", ".txt");
        final SearchResult searchResult = new SearchResult(path.toString());
        assertNotNull(searchResult.toString());
        assertNotNull(searchResult.filePath());
        assertTrue(searchResult.getOrEmpty("").isEmpty());
        assertTrue(0 < searchResult.lastModified());
        assertTrue(searchResult.mapIsEmpty());
        assertSame(0, searchResult.size());
        assertNull(searchResult.title());
    }

    /**
     * Test of {@link SearchResult#makeSimple(String)}.
     *
     * @throws IOException
     */
    @Test
    public void testMakeSimple() throws IOException {
        final Path path = Files.createTempFile("temp", ".txt");
        final SearchResult simple = SearchResult.makeSimple(path.toString());
        assertNotNull(simple);
    }

}

Modify unit test of search result.

Modify unit test of search result.


package uk.ac.cam.cstibhotel.otcanalyser.gui;

import java.awt.BorderLayout;

import javax.swing.JFrame;

import uk.ac.cam.cstibhotel.otcanalyser.communicationlayer.SearchListener;
import uk.ac.cam.cstibhotel.otcanalyser.communicationlayer.SearchResult;

public class GUI extends JFrame implements SearchListener {

	private static final long serialVersionUID = 1L;

	public StatusBar statusBar;

	public static GUI gui;
	static SearchWindow searchWindow;
	DataViewer dataViewer;

	public static GUI getInstance() {
		if (gui==null) {
			gui = new GUI();
		}
		return gui;
	}

	public GUI() {
		setTitle("OTC Analyser");
		setSize(1000,600);
		setDefaultCloseOperation(EXIT_ON_CLOSE);
		searchWindow = SearchWindow.getInstance();
		add(searchWindow,BorderLayout.WEST);
		searchWindow.setVisible(true);
		statusBar = StatusBar.getInstance();
		add(statusBar,BorderLayout.SOUTH);
		statusBar.setVisible(true);
		dataViewer = DataViewer.dataViewer;
		this.add(dataViewer);
		dataViewer.setVisible(true);
		this.setVisible(true);
	}

	@Override
	public void getSearchResult(SearchResult s) {
		DataViewer.addTrades(s.getResultData());
	}

}

package uk.ac.cam.cstibhotel.otcanalyser.gui;

import java.awt.BorderLayout;

import javax.swing.JFrame;

import uk.ac.cam.cstibhotel.otcanalyser.communicationlayer.SearchListener;
import uk.ac.cam.cstibhotel.otcanalyser.communicationlayer.SearchResult;

public class GUI extends JFrame implements SearchListener {

	private static final long serialVersionUID = 1L;

	public StatusBar statusBar;

	public static GUI gui;
	static SearchWindow searchWindow;
	DataViewer dataViewer;

	public static GUI getInstance() {
		if (gui==null) {
			gui = new GUI();
		}
		return gui;
	}

	public GUI() {
		setTitle("OTC Analyser");
		setSize(1000,600);
		setDefaultCloseOperation(EXIT_ON_CLOSE);
		searchWindow = SearchWindow.getInstance();
		add(searchWindow,BorderLayout.WEST);
		searchWindow.setVisible(true);
		statusBar = StatusBar.getInstance();
		add(statusBar,BorderLayout.SOUTH);
		statusBar.setVisible(true);
		dataViewer = DataViewer.dataViewer;
		this.add(dataViewer);
		dataViewer.setVisible(true);
		this.setVisible(true);
	}

	@Override
	public void getSearchResult(SearchResult s) {
		DataViewer.clearTrades();
		DataViewer.addTrades(s.getResultData());
	}

}

Clear trades from old search from data viewer before adding new ones


package com.breadwallet.tools.util;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;

/**
 * Created by byfieldj on 2/15/18.
 *

 *

 * Reusable class to quick check whether user is connect to Wifi or mobile data
 */

public class BRConnectivityStatus {

    private Context mContext;

    public BRConnectivityStatus(Context context) {
        this.mContext = context;
    }

    // Returns true if connected to wifi, false if connected to mobile data
    public boolean isWifiOrMobileDataConntected() {
        ConnectivityManager cm = (ConnectivityManager)
                mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo netinfo = cm.getActiveNetworkInfo();

        if (netinfo != null && netinfo.isConnectedOrConnecting()) {
            android.net.NetworkInfo wifi =
                    cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
            android.net.NetworkInfo mobile =
                    cm.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);

            if ((mobile != null && mobile.isConnectedOrConnecting()) || (wifi != null &&
                    wifi.isConnectedOrConnecting())) {
                return true;
            } else {
                return false;
            }
        } else {
            return false;
        }
    }

}

package com.breadwallet.tools.util;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;

/**
 * Created by byfieldj on 2/15/18.
 *

 *

 * Reusable class to quick check whether user is connect to Wifi or mobile data
 */

public class BRConnectivityStatus {

    private Context mContext;
    public static final int NO_NETWORK = 0;
    public static final int WIFI_ON = 1;
    public static final int MOBILE_ON = 2;
    public static final int MOBILE_WIFI_ON = 3;

    public BRConnectivityStatus(Context context) {
        this.mContext = context;
    }

    // Returns true if connected to wifi, false if connected to mobile data
    public int isMobileDataOrWifiConnected() {
        ConnectivityManager cm = (ConnectivityManager)
                mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo netinfo = cm.getActiveNetworkInfo();

        if (netinfo != null && netinfo.isConnectedOrConnecting()) {
            android.net.NetworkInfo wifi =
                    cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
            android.net.NetworkInfo mobile =
                    cm.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);

            // Mobile Data is on only
            if ((mobile != null && mobile.isConnectedOrConnecting()) && (wifi == null ||
                    !wifi.isConnectedOrConnecting())) {
                return MOBILE_ON;

                // Wifi is on only
            } else if (wifi != null && wifi.isConnectedOrConnecting() && (mobile == null || !mobile.isConnectedOrConnecting())) {
                return WIFI_ON;

                // Both mobile and wifi is on
            } else if (mobile != null && wifi != null && mobile.isConnectedOrConnecting() && wifi.isConnectedOrConnecting()) {

                return MOBILE_WIFI_ON;
            }
        }

        return NO_NETWORK;
    }

}

Fix mobile and wifi check logic

Fix mobile and wifi check logic


package devopsdistilled.operp.client.abstracts;

import javax.swing.JComponent;
import javax.swing.JDialog;

import net.miginfocom.swing.MigLayout;

public abstract class SubTaskPane {
	protected JDialog dialog;
	protected JComponent owner;

	public SubTaskPane() {
		dialog = new JDialog();
	}

	public abstract JComponent getPane();

	public void setOwner(JComponent owner) {
		this.owner = owner;
	}

	public JDialog getDialog() {
		dialog.getContentPane().setLayout(new MigLayout("debug"));
		dialog.getContentPane().add(getPane());
		dialog.setLocationRelativeTo(owner);
		dialog.setSize(400, 600);
		dialog.setVisible(true);
		return dialog;
	}

}

package devopsdistilled.operp.client.abstracts;

import javax.swing.JComponent;
import javax.swing.JDialog;

import net.miginfocom.swing.MigLayout;

public abstract class SubTaskPane {
	protected JDialog dialog;
	protected JComponent owner;

	public SubTaskPane() {
		dialog = new JDialog();
	}

	public abstract JComponent getPane();

	public void setOwner(JComponent owner) {
		this.owner = owner;
	}

	public JDialog getDialog() {
		dialog.getContentPane().setLayout(new MigLayout("debug, fill"));
		dialog.getContentPane().add(getPane(), "grow");
		dialog.setLocationRelativeTo(owner);
		dialog.setSize(400, 600);
		dialog.setVisible(true);
		return dialog;
	}

}

Set components to grow inside to fill JDialog ContentPane


package edu.northwestern.bioinformatics.studycalendar.dao;

import edu.northwestern.bioinformatics.studycalendar.domain.StudySegment;

/**
 * @author Moses Hohman
 * @author Rhett Sutphin
 */
public class StudySegmentDao extends StudyCalendarMutableDomainObjectDao<StudySegment> {
    @Override
    public Class<StudySegment> domainClass() {
        return StudySegment.class;
    }

    public void delete(StudySegment segment) {
        getHibernateTemplate().delete(segment);
    }
}

package edu.northwestern.bioinformatics.studycalendar.dao;

import edu.northwestern.bioinformatics.studycalendar.domain.StudySegment;

/**
 * @author Moses Hohman
 * @author Rhett Sutphin
 */
public class StudySegmentDao extends StudyCalendarMutableDomainObjectDao<StudySegment> {
    @Override
    public Class<StudySegment> domainClass() {
        return StudySegment.class;
    }

    /**
     * Deletes the given study segment
     *
     * @param  segment the study segment to delete
     */
    public void delete(StudySegment segment) {
        getHibernateTemplate().delete(segment);
    }
}

Add javadoc to study segment dao.

Add javadoc to study segment dao.


package com.filestack.internal.responses;

import com.google.gson.annotations.SerializedName;

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

/** Response object from multipart upload endpoint. */
public class UploadResponse {
  private String url;
  @SerializedName("location_url")
  private String locationUrl;
  @SerializedName("headers")
  private S3Headers s3Headers;

  public String getUrl() {
    return url;
  }

  public String getLocationUrl() {
    return locationUrl;
  }

  /**
   * Return {@link Map} of S3 headers.
   */
  public Map<String, String> getS3Headers() {
    HashMap<String, String> headers = new HashMap<>();
    headers.put("Authorization", s3Headers.auth);
    if (s3Headers.acl != null) {
      headers.put("x-amz-acl", s3Headers.acl);
    }
    headers.put("Content-MD5", s3Headers.md5);
    headers.put("x-amz-content-sha256", s3Headers.sha256);
    headers.put("x-amz-date", s3Headers.date);
    if (s3Headers.encryption != null) {
      headers.put("x-amz-server-side-encryption", s3Headers.encryption);
    }
    return headers;
  }

  private class S3Headers {
    @SerializedName("Authorization")
    private String auth;
    @SerializedName("x-amz-acl")
    private String acl;
    @SerializedName("Content-MD5")
    private String md5;
    @SerializedName("x-amz-content-sha256")
    private String sha256;
    @SerializedName("x-amz-date")
    private String date;
    @SerializedName("x-amz-server-side-encryption")
    private String encryption;
  }
}

package com.filestack.internal.responses;

import com.google.gson.JsonObject;
import com.google.gson.annotations.SerializedName;

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

/** Response object from multipart upload endpoint. */
public class UploadResponse {
  private String url;
  @SerializedName("location_url")
  private String locationUrl;
  @SerializedName("headers")
  private JsonObject s3Headers;

  public String getUrl() {
    return url;
  }

  public String getLocationUrl() {
    return locationUrl;
  }

  /**
   * Return {@link Map} of S3 headers.
   */
  public Map<String, String> getS3Headers() {
    HashMap<String, String> out = new HashMap<>();
    for (String key : s3Headers.keySet()) {
      out.put(key, s3Headers.get(key).getAsString());
    }
    return out;
  }
}

Replace S3Headers class with JsonObject

Fix: Replace S3Headers class with JsonObject

Related to #47 and #52 but #47 is still necessary.


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

package org.chromium.chrome.browser.nfc;

import android.app.Activity;
import android.nfc.NfcAdapter;
import android.util.Log;

/**
 * Initializes Android Beam (sharing URL via NFC) for devices that have NFC. If user taps their
 * device with another Beam capable device, then Chrome gets the current URL, filters for security
 * and returns the result to Android.
 */
public final class BeamController {
    /**
     * If the device has NFC, construct a BeamCallback and pass it to Android.
     *
     * @param activity Activity that is sending out beam messages.
     * @param provider Provider that returns the URL that should be shared.
     */
    public static void registerForBeam(final Activity activity, final BeamProvider provider) {
        final NfcAdapter nfcAdapter = NfcAdapter.getDefaultAdapter(activity);
        if (nfcAdapter == null) return;
        try {
            final BeamCallback beamCallback = new BeamCallback(activity, provider);
            nfcAdapter.setNdefPushMessageCallback(beamCallback, activity);
            nfcAdapter.setOnNdefPushCompleteCallback(beamCallback, activity);
        } catch (IllegalStateException e) {
            Log.w("BeamController", "NFC registration failure. Can't retry, giving up.");
        }
    }
}

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

package org.chromium.chrome.browser.nfc;

import android.app.Activity;
import android.nfc.NfcAdapter;
import android.util.Log;

/**
 * Initializes Android Beam (sharing URL via NFC) for devices that have NFC. If user taps their
 * device with another Beam capable device, then Chrome gets the current URL, filters for security
 * and returns the result to Android.
 */
public final class BeamController {
    /**
     * If the device has NFC, construct a BeamCallback and pass it to Android.
     *
     * @param activity Activity that is sending out beam messages.
     * @param provider Provider that returns the URL that should be shared.
     */
    public static void registerForBeam(final Activity activity, final BeamProvider provider) {
        final NfcAdapter nfcAdapter = NfcAdapter.getDefaultAdapter(activity);
        if (nfcAdapter == null) return;
        try {
            final BeamCallback beamCallback = new BeamCallback(activity, provider);
            nfcAdapter.setNdefPushMessageCallback(beamCallback, activity);
            nfcAdapter.setOnNdefPushCompleteCallback(beamCallback, activity);
        } catch (IllegalStateException | SecurityException e) {
            Log.w("BeamController", "NFC registration failure. Can't retry, giving up.");
        }
    }
}

Handle NFC permission being unavailable.

With a rooted device, some apps can remove permissions. Prevents chrome
from crashing if NFC is revoked.

BUG=481979

Review URL: https://codereview.chromium.org/1104053003

Cr-Commit-Position: 972c6d2dc6dd5efdad1377c0d224e03eb8f276f7@{#327571}


package mn.devfest.persistence;

import android.content.Context;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.support.annotation.NonNull;

import mn.devfest.api.model.Conference;

/**
 * Stores and provides information about the conference. The app is shipped with a local copy of
 * the latest conference information. As we get newer information from the API, this is updated.
 *
 * @author pfuentes
 */
public class ConferenceRepository {

    Context mContext;
    SharedPreferences mSharedPreferences;

    public ConferenceRepository (@NonNull Context context){
        mContext = context;
        mSharedPreferences = PreferenceManager.getDefaultSharedPreferences(mContext);
    }

    public void setConference(Conference conference) {
        //TODO implement
    }

    public Conference getConference() {
        //TODO implement and remove dummy return
        return new Conference();
    }

}

package mn.devfest.persistence;

import android.content.Context;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;

import mn.devfest.api.model.Conference;

/**
 * Stores and provides information about the conference. The app is shipped with a local copy of
 * the latest conference information. As we get newer information from the API, this is updated.
 *
 * @author pfuentes
 */
public class ConferenceRepository {

    Context mContext;
    SharedPreferences mSharedPreferences;

    public ConferenceRepository(@NonNull Context context) {
        mContext = context;
        mSharedPreferences = PreferenceManager.getDefaultSharedPreferences(mContext);
    }

    /**
     * Removes any existing persisted conference data and replaces it with the passed value
     *
     * @param conference most up-to-date conference information available
     */
    public void setConference(@Nullable Conference conference) {
        //TODO implement
    }

    /**
     * Provides the most recently persisted conference data
     *
     * @return persisted conference data
     */
    @NonNull
    public Conference getConference() {
        //TODO implement and remove dummy return
        return new Conference();
    }

}

Document methods in conference repository


package org.restheart.examples;

import java.io.IOException;
import com.google.protobuf.InvalidProtocolBufferException;
import com.mashape.unirest.http.Unirest;
import com.mashape.unirest.http.exceptions.UnirestException;

public class Test {
    public static void main(String[] args) throws Exception  {
        testRequest(args[0] == null ? "World" : args[0]);
    }

    public static void testRequest(String name) throws UnirestException, InvalidProtocolBufferException, IOException  {
        var body = HelloRequest.newBuilder()
            .setName(name)
            .build();

        var resp = Unirest.post("http://localhost:8080/proto")
                .header("Content-Type", "application/protobuf")
                .body(body.toByteArray())
                .asBinary();

        var reply = HelloReply.parseFrom(resp.getBody().readAllBytes());

        System.out.println(reply.getMessage());
    }
}

package org.restheart.examples;

import java.io.IOException;
import com.google.protobuf.InvalidProtocolBufferException;
import com.mashape.unirest.http.Unirest;
import com.mashape.unirest.http.exceptions.UnirestException;

public class Test {
    public static void main(String[] args) throws Exception  {
        testRequest(args.length < 1 ? "World" : args[0]);
    }

    public static void testRequest(String name) throws UnirestException, InvalidProtocolBufferException, IOException  {
        var body = HelloRequest.newBuilder()
            .setName(name)
            .build();

        var resp = Unirest.post("http://localhost:8080/proto")
                .header("Content-Type", "application/protobuf")
                .body(body.toByteArray())
                .asBinary();

        var reply = HelloReply.parseFrom(resp.getBody().readAllBytes());

        System.out.println(reply.getMessage());
    }
}

:bug: Fix NPE in protobuffer example test class [skip ci]


/*
 * The Alluxio Open Foundation licenses this work under the Apache License, version 2.0
 * (the "License"). You may not use this work except in compliance with the License, which is
 * available at www.apache.org/licenses/LICENSE-2.0
 *
 * This software is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
 * either express or implied, as more fully set forth in the License.
 *
 * See the NOTICE file distributed with this work for information regarding copyright ownership.
 */

package alluxio.retry;

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

/**
 * Tests for the {@link TimeoutRetry} class.
 */
public final class TimeoutRetryTest {

  /**
   * Tests that the provided timeout is respected.
   */
  @Test
  public void timeout() {
    final long timeoutMs = 50;
    final int sleepMs = 10;
    int attempts = 0;
    TimeoutRetry timeoutRetry = new TimeoutRetry(timeoutMs, sleepMs);
    Assert.assertEquals(0, timeoutRetry.getAttemptCount());
    long startMs = System.currentTimeMillis();
    while (timeoutRetry.attempt()) {
      attempts++;
    }
    long endMs = System.currentTimeMillis();
    Assert.assertTrue(attempts > 0);
    Assert.assertTrue((endMs - startMs) >= timeoutMs);
    Assert.assertEquals(attempts, timeoutRetry.getAttemptCount());
    Assert.assertTrue(attempts <= (timeoutMs / sleepMs) + 1);
  }
}

/*
 * The Alluxio Open Foundation licenses this work under the Apache License, version 2.0
 * (the "License"). You may not use this work except in compliance with the License, which is
 * available at www.apache.org/licenses/LICENSE-2.0
 *
 * This software is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
 * either express or implied, as more fully set forth in the License.
 *
 * See the NOTICE file distributed with this work for information regarding copyright ownership.
 */

package alluxio.retry;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;

import org.junit.Test;

/**
 * Tests for the {@link TimeoutRetry} class.
 */
public final class TimeoutRetryTest {

  /**
   * Tests that the provided timeout is respected.
   */
  @Test
  public void timeout() {
    final long timeoutMs = 50;
    final int sleepMs = 10;
    int attempts = 0;
    TimeoutRetry timeoutRetry = new TimeoutRetry(timeoutMs, sleepMs);
    assertEquals(0, timeoutRetry.getAttemptCount());
    long startMs = System.currentTimeMillis();
    while (timeoutRetry.attempt()) {
      attempts++;
    }
    long endMs = System.currentTimeMillis();
    assertTrue(attempts > 0);
    assertTrue((endMs - startMs) >= timeoutMs);
    assertEquals(attempts, timeoutRetry.getAttemptCount());
    assertTrue(attempts <= (timeoutMs / sleepMs) + 1);
  }
}

[SMALLFIX] Use static imports for standard test utilities

[SMALLFIX] Use static imports for standard test utilities

pr-link: Alluxio/alluxio#8823
change-id: cid-8d5f96ba6dd7d80c6f8c61a6d4698083a91ee043


package net.elprespufferfish.rssreader;

import android.provider.BaseColumns;

public class DatabaseSchema {

    public static interface FeedTable extends BaseColumns {
        public static final String TABLE_NAME = "feeds";
        public static final String FEED_NAME = "feed_name";
        public static final String FEED_URL = "feed_url";
    }

    public static interface ArticleTable extends BaseColumns {
        public static final String TABLE_NAME = "articles";
        public static final String ARTICLE_FEED = "article_feed";
        public static final String ARTICLE_NAME = "article_name";
        public static final String ARTICLE_URL = "article_url";
        public static final String ARTICLE_PUBLICATION_DATE = "article_pubdate";
        public static final String ARTICLE_DESCRIPTION = "article_description";
        public static final String ARTICLE_GUID = "article_guid";
        public static final String ARTICLE_IS_READ = "article_is_read";
    }

    private DatabaseSchema() {
        // prevent instantiations
    }
}

package net.elprespufferfish.rssreader;

import android.provider.BaseColumns;

public class DatabaseSchema {

    public interface FeedTable extends BaseColumns {
        String TABLE_NAME = "feeds";
        String FEED_NAME = "feed_name";
        String FEED_URL = "feed_url";
    }

    public interface ArticleTable extends BaseColumns {
        String TABLE_NAME = "articles";
        String ARTICLE_FEED = "article_feed";
        String ARTICLE_NAME = "article_name";
        String ARTICLE_URL = "article_url";
        String ARTICLE_PUBLICATION_DATE = "article_pubdate";
        String ARTICLE_DESCRIPTION = "article_description";
        String ARTICLE_GUID = "article_guid";
        String ARTICLE_IS_READ = "article_is_read";
    }

    private DatabaseSchema() {
        // prevent instantiations
    }
}

Remove redundant modifiers for interface fields