package de.mvitz.jprops.core.api;

import static org.mockito.BDDMockito.given;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;

@RunWith(MockitoJUnitRunner.class)
public class PropertiesInjectorTest {

    @Mock
    private PropertyProvider provider;
    @InjectMocks
    private PropertiesInjector injector;

    @SuppressWarnings("unused")
    private UnknownType unknownType;

    @Test(expected = InvalidPropertiesException.class)
    public void shouldThrowExceptionForUnknownType() throws Exception {
        given(provider.get("unknownType")).willReturn("foo");
        injector.injectInto(this);
    }

    public interface UnknownType {
    }

}

package de.mvitz.jprops.core.api;

import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.failBecauseExceptionWasNotThrown;
import static org.mockito.BDDMockito.given;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;

@RunWith(MockitoJUnitRunner.class)
public class PropertiesInjectorTest {

    @Mock
    private PropertyProvider provider;
    @InjectMocks
    private PropertiesInjector injector;

    private UnknownType unknownType;

    @Test
    public void shouldThrowExceptionForUnknownType() throws Exception {
        given(provider.get("unknownType")).willReturn("foo");
        try {
            injector.injectInto(this);
            failBecauseExceptionWasNotThrown(InvalidPropertiesException.class);
        } catch (final InvalidPropertiesException e) {
            assertThat(e).hasNoCause().hasMessage("No converter found for type: UnknownType");
            assertThat(unknownType).isNull();
        }
    }

    public interface UnknownType {
    }

}

Use AssertJ instead of JUnit expected to assert thrown exception.


/*
 * Copyright 2015-2018 the original author or authors.
 *
 * All rights reserved. This program and the accompanying materials are
 * made available under the terms of the Eclipse Public License v2.0 which
 * accompanies this distribution and is available at
 *
 * http://www.eclipse.org/legal/epl-v20.html
 */

package example;

// tag::user_guide[]
import java.util.HashMap;

import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestReporter;

class TestReporterDemo {

	@Test
	void reportSingleValue(TestReporter testReporter) {
		testReporter.publishEntry("a key", "a value");
	}

	@Test
	void reportSeveralValues(TestReporter testReporter) {
		HashMap<String, String> values = new HashMap<>();
		values.put("user name", "dk38");
		values.put("award year", "1974");

		testReporter.publishEntry(values);
	}

}
// end::user_guide[]

/*
 * Copyright 2015-2018 the original author or authors.
 *
 * All rights reserved. This program and the accompanying materials are
 * made available under the terms of the Eclipse Public License v2.0 which
 * accompanies this distribution and is available at
 *
 * http://www.eclipse.org/legal/epl-v20.html
 */

package example;

// tag::user_guide[]
import java.util.HashMap;
import java.util.Map;

import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestReporter;

class TestReporterDemo {

	@Test
	void reportSingleValue(TestReporter testReporter) {
		testReporter.publishEntry("a key", "a value");
	}

	@Test
	void reportSeveralValues(TestReporter testReporter) {
		Map<String, String> values = new HashMap<>();
		values.put("user name", "dk38");
		values.put("award year", "1974");

		testReporter.publishEntry(values);
	}

}
// end::user_guide[]

Use interface instead of implementation class


package b_stream;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.stream.Stream;

class LongestWordInFile {

    public static void main(String[] args) throws IOException {
        Stream<String> lines = Files.lines(Paths.get("frankenstein.txt"));
        System.out.println(lines.flatMap(l -> Arrays.stream(l.split("[\\P{L}]+")))
                .max((lhs, rhs) -> Integer.compare(lhs.length(), rhs.length())).get());
    }
}

package b_stream;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.regex.Pattern;
import java.util.stream.Stream;

class LongestWordInFile {

    public static void main(String[] args) throws IOException {
        Pattern wordSeparator = Pattern.compile("[\\P{L}]+");

        try(Stream<String> lines = Files.lines(Paths.get("frankenstein.txt"))) {
            System.out.println(lines.flatMap(l -> wordSeparator.splitAsStream(l))
                    .max((lhs, rhs) -> Integer.compare(lhs.length(), rhs.length())).get());
        }

    }
}

Work with files in close with resources. Extract pattern for better readablity.


package org.aksw.kbox.kibe;

import java.net.MalformedURLException;
import java.net.URL;

import org.aksw.kbox.kns.CustomKNSServerList;
import org.aksw.kbox.kns.KNSServerListVisitor;

public class DefaultKNSServerList extends URLKNSServerList {

	// Default KNS table URL
	private final static String DEFAULT_KNS_TABLE_URL = "https://raw.githubusercontent.com/AKSW/KBox/master/kns/2.0/";

	private CustomKNSServerList customKNSServerList = new CustomKNSServerList();

	public DefaultKNSServerList() throws MalformedURLException {
		super(new URL(DEFAULT_KNS_TABLE_URL));
	}

	@Override
	public boolean visit(KNSServerListVisitor visitor) throws Exception {
		boolean next = super.visit(visitor);
		if(next) {
			next = customKNSServerList.visit(visitor);
		}
		return next;
	}
}

package org.aksw.kbox.kibe;

import java.net.MalformedURLException;
import java.net.URL;

import org.aksw.kbox.kns.CustomKNSServerList;
import org.aksw.kbox.kns.KNSServerListVisitor;

public class DefaultKNSServerList extends URLKNSServerList {

	// Default KNS table URL
//	private final static String DEFAULT_KNS_TABLE_URL = "https://raw.githubusercontent.com/AKSW/KBox/master/kns/2.0/";
	private final static String DEFAULT_KNS_TABLE_URL = "https://raw.githubusercontent.com/sahandilshan/KBox/dev/kns/2.0/";

	private CustomKNSServerList customKNSServerList = new CustomKNSServerList();

	public DefaultKNSServerList() throws MalformedURLException {
		super(new URL(DEFAULT_KNS_TABLE_URL));
	}

	@Override
	public boolean visit(KNSServerListVisitor visitor) throws Exception {
		boolean next = super.visit(visitor);
		if(next) {
			next = customKNSServerList.visit(visitor);
		}
		return next;
	}
}

Add temporary default KNS table URL

Add temporary default KNS table URL


package seedu.taskmanager.logic.parser;

import java.util.regex.Pattern;

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

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

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

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

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

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

package seedu.taskmanager.logic.parser;

import java.util.regex.Pattern;

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

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

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

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

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

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

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


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

import com.google.devtools.common.options.Option;
import com.google.devtools.common.options.OptionDocumentationCategory;
import com.google.devtools.common.options.OptionEffectTag;
import com.google.devtools.common.options.OptionsBase;

/**
 * Options that tune Bazel's performance in order to increase performance on workstations with an
 * SSD.
 */
public class SsdOptions extends OptionsBase {
  @Option(
    name = "experimental_multi_threaded_digest",
    defaultValue = "false",
    documentationCategory = OptionDocumentationCategory.UNCATEGORIZED,
    effectTags = {OptionEffectTag.UNKNOWN},
    help =
        "Whether to always compute MD5 digests of files with multiple threads. Might improve "
            + "performance when using an SSD."
  )
  public boolean experimentalMultiThreadedDigest;
}

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

import com.google.devtools.common.options.Option;
import com.google.devtools.common.options.OptionDocumentationCategory;
import com.google.devtools.common.options.OptionEffectTag;
import com.google.devtools.common.options.OptionsBase;

/**
 * Options that tune Bazel's performance in order to increase performance on workstations with an
 * SSD.
 */
public class SsdOptions extends OptionsBase {
  @Option(
      name = "experimental_multi_threaded_digest",
      defaultValue = "true",
      documentationCategory = OptionDocumentationCategory.UNCATEGORIZED,
      effectTags = {OptionEffectTag.UNKNOWN},
      help =
          "Whether to always compute MD5 digests of files with multiple threads. Setting this to "
              + "false may improve performance when using a spinning platter.")
  public boolean experimentalMultiThreadedDigest;
}

Switch the default for --experimental_multi_threaded_digest

It looks like this is fairly widely used now, and we recommend users who are still on spinning platters to upgrade their workstation. :-P

Progress on #6345.

PiperOrigin-RevId: 262317072


package net.hillsdon.reviki.jira.renderer;

import net.hillsdon.reviki.vc.PageReference;
import net.hillsdon.reviki.wiki.renderer.creole.LinkParts;
import net.hillsdon.reviki.wiki.renderer.creole.LinkResolutionContext;
import net.hillsdon.reviki.wiki.renderer.creole.SimpleLinkHandler;

public class JiraLinkHandler extends SimpleLinkHandler {

  public JiraLinkHandler(String fmat, LinkResolutionContext context) {
    super(fmat, context);
  }

  /**
   * Allow all LinkParts to be links, non-JIRA issues have been filtered
   * by JiraInternalLinker
   */
  @Override
  public boolean isAcronymNotLink(PageReference page, LinkParts parts) {
    return false;
  }
}

package net.hillsdon.reviki.jira.renderer;

import net.hillsdon.reviki.wiki.renderer.creole.LinkParts;
import net.hillsdon.reviki.wiki.renderer.creole.LinkResolutionContext;
import net.hillsdon.reviki.wiki.renderer.creole.SimpleLinkHandler;

public class JiraLinkHandler extends SimpleLinkHandler {

  public JiraLinkHandler(String fmat, LinkResolutionContext context) {
    super(fmat, context);
  }

  /**
   * Allow all LinkParts to be links, non-JIRA issues have been filtered
   * by JiraInternalLinker
   */
  @Override
  public boolean isAcronymNotLink(LinkParts parts) {
    return false;
  }
}

Correct method signature to match changes to Reviki.


package com.hamishrickerby.http_server;

import java.util.*;

/**
 * Created by rickerbh on 18/08/2016.
 */
public class Headers {
    private static String HEADER_SEPARATOR = ": ";

    Map<String, String> headers;

    public Headers() {
        headers = new HashMap<>();
    }

    public List<String> list() {
        List<String> headerList = new ArrayList<>();
        for (String key : headers.keySet()) {
            headerList.add(key + HEADER_SEPARATOR + headers.get(key));
        }
        return headerList;
    }

    public void put(String key, String value) {
        headers.put(key, value);
    }

    public void parse(String headerString) {
        String[] lines = headerString.split("\r\n");
        for (String line : Arrays.asList(lines)) {
            String[] components = line.split(":");
            put(components[0].trim(), components[1].trim());
        }
    }

    public String get(String key) {
        return headers.getOrDefault(key, "");
    }

}

package com.hamishrickerby.http_server;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * Created by rickerbh on 18/08/2016.
 */
public class Headers {
    private static String HEADER_SEPARATOR = ": ";

    Map<String, String> headers;

    public Headers() {
        headers = new HashMap<>();
    }

    public List<String> list() {
        return headers.keySet().stream()
                .map(key -> key + HEADER_SEPARATOR + headers.get(key))
                .collect(Collectors.toList());
    }

    public void put(String key, String value) {
        headers.put(key, value);
    }

    public void parse(String headerString) {
        String[] lines = headerString.split("\r\n");
        for (String line : Arrays.asList(lines)) {
            String[] components = line.split(":");
            put(components[0].trim(), components[1].trim());
        }
    }

    public String get(String key) {
        return headers.getOrDefault(key, "");
    }

}

Refactor headers list() with map/collect


package com.royalrangers.dto.structure;

import lombok.Getter;
import lombok.Setter;

import java.util.Date;

@Getter
@Setter
public class PlatoonDto {
    private Long id;
    private Integer name;
    private Long cityId;
    private String history;
    private String logoUrl;
    private String address;
    private Date meetTime;
}

package com.royalrangers.dto.structure;

import lombok.Getter;
import lombok.Setter;

import java.util.Date;

@Getter
@Setter
public class PlatoonDto {
    private Integer name;
    private Long cityId;
    private String history;
    private String logoUrl;
    private String address;
    private Date meetTime;
}

Remove unused id in Platoon Dto

Remove unused id in Platoon Dto


package io.github.trevornelson.service;

import com.google.devrel.training.conference.domain.Profile;
import com.googlecode.objectify.Objectify;
import com.googlecode.objectify.ObjectifyFactory;
import com.googlecode.objectify.ObjectifyService;

/**
 * Custom Objectify Service that this application should use.
 */
public class OfyService {
    /**
     * This static block ensure the entity registration.
     */
    static {
        factory().register(Profile.class);
    }

    /**
     * Use this static method for getting the Objectify service object in order to make sure the
     * above static block is executed before using Objectify.
     * @return Objectify service object.
     */
    public static Objectify ofy() {
        return ObjectifyService.ofy();
    }

    /**
     * Use this static method for getting the Objectify service factory.
     * @return ObjectifyFactory.
     */
    public static ObjectifyFactory factory() {
        return ObjectifyService.factory();
    }
}

package io.github.trevornelson.service;

import com.googlecode.objectify.Objectify;
import com.googlecode.objectify.ObjectifyFactory;
import com.googlecode.objectify.ObjectifyService;
import io.github.trevornelson.Account;

/**
 * Custom Objectify Service that this application should use.
 */
public class OfyService {
    /**
     * This static block ensure the entity registration.
     */
    static {
        factory().register(Account.class);
    }

    /**
     * Use this static method for getting the Objectify service object in order to make sure the
     * above static block is executed before using Objectify.
     * @return Objectify service object.
     */
    public static Objectify ofy() {
        return ObjectifyService.ofy();
    }

    /**
     * Use this static method for getting the Objectify service factory.
     * @return ObjectifyFactory.
     */
    public static ObjectifyFactory factory() {
        return ObjectifyService.factory();
    }
}

Create ofy objectify service for persisting entities


package org.bouncycastle.crypto.tls;

/**
 * RFC 4366 2.3
 */
public class ExtensionType
{
    public static final int server_name = 0;
    public static final int max_fragment_length = 1;
    public static final int client_certificate_url = 2;
    public static final int trusted_ca_keys = 3;
    public static final int truncated_hmac = 4;
    public static final int status_request = 5;

    /*
     * RFC 4492
     */
    public static final int elliptic_curves = 10;
    public static final int ec_point_formats = 11;

    /*
     * RFC 5054 2.8.1
     */
    public static final int srp = 12;

    /*
     * RFC 5746 6
     */
    public static final int renegotiation_info = 0xff01;
}

package org.bouncycastle.crypto.tls;

public class ExtensionType
{
    /*
     * RFC 6066 1.1.
     */
    public static final int server_name = 0;
    public static final int max_fragment_length = 1;
    public static final int client_certificate_url = 2;
    public static final int trusted_ca_keys = 3;
    public static final int truncated_hmac = 4;
    public static final int status_request = 5;

    /*
     * RFC 4492 5.1.
     */
    public static final int elliptic_curves = 10;
    public static final int ec_point_formats = 11;

    /*
     * RFC 5054 2.8.1.
     */
    public static final int srp = 12;

    /*
     * RFC 5246 7.4.1.4.
     */
    public static final int signature_algorithms = 13;

    /*
     * RFC 5746 3.2.
     */
    public static final int renegotiation_info = 0xff01;
}

Add extension type from RFC 5246

Add extension type from RFC 5246


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

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

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

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

    @Inject
    private AuditEventService auditEventService;

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

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

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

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

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

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

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

    @Inject
    private AuditEventService auditEventService;

    @InitBinder
    public void initBinder(WebDataBinder binder) {
        binder.registerCustomEditor(LocalDateTime.class, new LocaleDateTimeEditor("MM/dd/yyyy hh:mm:ss a", false));
    }

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

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

Add the time to the format of the date

Add the time to the format of the date


package com.github.hisaichi5518.kise;

public interface UnitActions<ACTION_PARAM> {
    void customAction(ACTION_PARAM actionParam);

    void defaultAction(ACTION_PARAM actionParam);
}

package com.github.hisaichi5518.kise;

public interface UnitActions<ACTION_PARAM> {
    void customAction(ACTION_PARAM actionParam) throws Exception;

    void defaultAction(ACTION_PARAM actionParam);
}

Add "throws Exception" to customAction method.


package annotator.find;

import com.sun.source.tree.*;
import com.sun.source.util.TreePath;

/**
 * Represents the criterion that a program element is not enclosed by any
 * method (i.e. it's a field, class type parameter, etc.).
 */
final class NotInMethodCriterion implements Criterion {

  /**
   * {@inheritDoc}
   */
  public Kind getKind() {
    return Kind.NOT_IN_METHOD;
  }

  /** {@inheritDoc} */
  @Override
  public boolean isSatisfiedBy(TreePath path, Tree leaf) {
    assert path == null || path.getLeaf() == leaf;
    return isSatisfiedBy(path);
  }

  /** {@inheritDoc} */
  @Override
  public boolean isSatisfiedBy(TreePath path) {
    do {
      Tree tree = path.getLeaf();
      if (tree.getKind() == Tree.Kind.METHOD)
        return false;
      if (tree.getKind() == Tree.Kind.CLASS || tree.getKind() == Tree.Kind.NEW_CLASS) {
        return true;
      }
      path = path.getParentPath();
    } while (path != null && path.getLeaf() != null);

    return true;
  }

  /**
   * {@inheritDoc}
   */
  public String toString() {
    return "not in method";
  }

}

package annotator.find;

import com.sun.source.tree.*;
import com.sun.source.util.TreePath;

/**
 * Represents the criterion that a program element is not enclosed by any
 * method (i.e. it's a field, class type parameter, etc.).
 */
final class NotInMethodCriterion implements Criterion {

  /**
   * {@inheritDoc}
   */
  @Override
  public Kind getKind() {
    return Kind.NOT_IN_METHOD;
  }

  /** {@inheritDoc} */
  @Override
  public boolean isSatisfiedBy(TreePath path, Tree leaf) {
    assert path == null || path.getLeaf() == leaf;
    return isSatisfiedBy(path);
  }

  /** {@inheritDoc} */
  @Override
  public boolean isSatisfiedBy(TreePath path) {
    do {
      Tree tree = path.getLeaf();
      if (tree.getKind() == Tree.Kind.METHOD)
        return false;
      if (Criteria.isClassEquiv(tree)) {
        return true;
      }
      path = path.getParentPath();
    } while (path != null && path.getLeaf() != null);

    return true;
  }

  /**
   * {@inheritDoc}
   */
  @Override
  public String toString() {
    return "not in method";
  }

}

Call helper method instead of hard-coding class-equivalent structures here.


/**
 * The Totemic API.
 * This should provide some functionality for extending Totemic.
 */
@API(apiVersion = "2.1.0", owner = Totemic.MOD_ID, provides = "totemic|API")
package totemic_commons.pokefenn.api;

import net.minecraftforge.fml.common.API;
import totemic_commons.pokefenn.Totemic;

/**
 * The Totemic API.
 * This should provide some functionality for extending Totemic.
 */
@net.minecraftforge.fml.common.API(apiVersion = "2.1.1", owner = "totemic", provides = "totemic|API")
package totemic_commons.pokefenn.api;

Fix API not being compilable by itself

Fix API not being compilable by itself


package io.github.arpankapoor.country;

import com.google.i18n.phonenumbers.PhoneNumberUtil;

import java.util.Locale;

public class Country {
    private String name;
    private String isoCode;
    private int callingCode;

    public Country(String isoCode) {
        this.isoCode = isoCode.toUpperCase();
        this.name = new Locale("", this.isoCode).getDisplayCountry();
        this.callingCode = PhoneNumberUtil.getInstance().getCountryCodeForRegion(this.isoCode);
    }

    @Override
    public String toString() {
        return name + " (+" + callingCode + ")";
    }

    public int getCallingCode() {
        return callingCode;
    }

    public void setCallingCode(int callingCode) {
        this.callingCode = callingCode;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getIsoCode() {
        return isoCode;
    }

    public void setIsoCode(String isoCode) {
        this.isoCode = isoCode;
    }
}

package io.github.arpankapoor.country;

import android.support.annotation.NonNull;

import com.google.i18n.phonenumbers.PhoneNumberUtil;

import java.io.Serializable;
import java.util.Locale;

public class Country implements Comparable<Country>, Serializable {
    private static final long serialVersionUID = 8116297477768564397L;
    private String name;
    private String isoCode;
    private int callingCode;

    public Country(String isoCode) {
        setIsoCode(isoCode.toUpperCase());
        setName(new Locale("", getIsoCode()).getDisplayCountry());
        setCallingCode(PhoneNumberUtil.getInstance().getCountryCodeForRegion(getIsoCode()));
    }

    @Override
    public String toString() {
        return name + " (+" + callingCode + ")";
    }

    public int getCallingCode() {
        return callingCode;
    }

    public void setCallingCode(int callingCode) {
        this.callingCode = callingCode;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getIsoCode() {
        return isoCode;
    }

    public void setIsoCode(String isoCode) {
        this.isoCode = isoCode;
    }

    @Override
    public int compareTo(@NonNull Country another) {
        return this.name.compareTo(another.name);
    }
}

Implement Serializable and Comparable interfaces


/*
 * SafeUriStringImpl.java
 *
 * Copyright (C) 2009-11 by RStudio, Inc.
 *
 * This program is licensed to you under the terms of version 3 of the
 * GNU Affero General Public License. This program is distributed WITHOUT
 * ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,
 * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the
 * AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details.
 *
 */
package org.rstudio.core.client;

import com.google.gwt.safehtml.shared.SafeUri;

public class SafeUriStringImpl implements SafeUri
{
   public SafeUriStringImpl(String value)
   {
      value_ = value;
   }

   @Override
   public String asString()
   {
      return value_;
   }

   @Override
   public int hashCode()
   {
      return value_.hashCode();
   }

   @SuppressWarnings({"EqualsWhichDoesntCheckParameterClass"})
   @Override
   public boolean equals(Object o)
   {
      if (o == null ^ value_ == null)
         return false;
      if (value_ == null)
         return false;
      return value_.equals(o.toString());
   }

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

   private final String value_;
}

/*
 * SafeUriStringImpl.java
 *
 * Copyright (C) 2009-11 by RStudio, Inc.
 *
 * This program is licensed to you under the terms of version 3 of the
 * GNU Affero General Public License. This program is distributed WITHOUT
 * ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,
 * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the
 * AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details.
 *
 */
package org.rstudio.core.client;

import com.google.gwt.safehtml.shared.SafeUri;

public class SafeUriStringImpl implements SafeUri
{
   public SafeUriStringImpl(String value)
   {
      value_ = value;
   }

   @Override
   public String asString()
   {
      return value_;
   }

   @Override
   public int hashCode()
   {
      return value_.hashCode();
   }

   @Override
   public boolean equals(Object o)
   {
      if (o == null ^ value_ == null)
         return false;
      if (value_ == null)
         return false;
      return value_.equals(o.toString());
   }

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

   private final String value_;
}

Remove warning suppression that Eclipse doesn't like


package cpw.mods.fml.common.event;

import net.minecraft.server.MinecraftServer;
import cpw.mods.fml.common.LoaderState.ModState;

public class FMLServerStartingEvent extends FMLStateEvent
{

    private MinecraftServer server;

    public FMLServerStartingEvent(Object... data)
    {
        super(data);
        this.server = (MinecraftServer) data[0];
    }
    @Override
    public ModState getModState()
    {
        return ModState.AVAILABLE;
    }

    public MinecraftServer getServer()
    {
        return server;
    }
}

package cpw.mods.fml.common.event;

import net.minecraft.server.MinecraftServer;
import net.minecraft.src.CommandHandler;
import net.minecraft.src.ICommand;
import cpw.mods.fml.common.LoaderState.ModState;

public class FMLServerStartingEvent extends FMLStateEvent
{

    private MinecraftServer server;

    public FMLServerStartingEvent(Object... data)
    {
        super(data);
        this.server = (MinecraftServer) data[0];
    }
    @Override
    public ModState getModState()
    {
        return ModState.AVAILABLE;
    }

    public MinecraftServer getServer()
    {
        return server;
    }

    public void registerServerCommand(ICommand command)
    {
        CommandHandler ch = (CommandHandler) getServer().func_71187_D();
        ch.func_71560_a(command);
    }
}

Add in a helper on the server start event for adding commands to the server.


package me.nallar.javapatcher.mappings;

import java.util.*;

/**
 * Maps method/field/class names in patches to allow obfuscated code to be patched.
 */
public abstract class Mappings {
	/**
	 * Takes a list of Class/Method/FieldDescriptions and maps them all using the appropriate map(*Description)
	 *
	 * @param list List of Class/Method/FieldDescriptions
	 * @return Mapped List
	 */
	@SuppressWarnings("unchecked")
	public final <T> List<T> map(List<T> list) {
		List<T> mappedThings = new ArrayList();
		for (Object thing : list) {
			// TODO - cleaner way of doing this?
			if (thing instanceof MethodDescription) {
				mappedThings.add((T) map((MethodDescription) thing));
			} else if (thing instanceof ClassDescription) {
				mappedThings.add((T) map((ClassDescription) thing));
			} else if (thing instanceof FieldDescription) {
				mappedThings.add((T) map((FieldDescription) thing));
			} else {
				throw new IllegalArgumentException("Must be mappable: " + thing + "isn't!");
			}
		}
		return mappedThings;
	}

	public abstract MethodDescription map(MethodDescription methodDescription);

	public abstract ClassDescription map(ClassDescription classDescription);

	public abstract FieldDescription map(FieldDescription fieldDescription);

	public abstract MethodDescription unmap(MethodDescription methodDescription);

	public abstract String obfuscate(String code);
}

package me.nallar.javapatcher.mappings;

import java.util.*;

/**
 * Maps method/field/class names in patches to allow obfuscated code to be patched.
 */
public abstract class Mappings {
	/**
	 * Takes a list of Class/Method/FieldDescriptions and maps them all using the appropriate map(*Description)
	 *
	 * @param list List of Class/Method/FieldDescriptions
	 * @return Mapped List
	 */
	@SuppressWarnings("unchecked")
	public final <T> List<T> map(List<T> list) {
		List<T> mappedThings = new ArrayList<T>();
		for (Object thing : list) {
			// TODO - cleaner way of doing this?
			if (thing instanceof MethodDescription) {
				mappedThings.add((T) map((MethodDescription) thing));
			} else if (thing instanceof ClassDescription) {
				mappedThings.add((T) map((ClassDescription) thing));
			} else if (thing instanceof FieldDescription) {
				mappedThings.add((T) map((FieldDescription) thing));
			} else {
				throw new IllegalArgumentException("Must be mappable: " + thing + "isn't!");
			}
		}
		return mappedThings;
	}

	public abstract MethodDescription map(MethodDescription methodDescription);

	public abstract ClassDescription map(ClassDescription classDescription);

	public abstract FieldDescription map(FieldDescription fieldDescription);

	public abstract MethodDescription unmap(MethodDescription methodDescription);

	public abstract String obfuscate(String code);
}

Fix missed raw type ArrayList

Fix missed raw type ArrayList


package site;

import org.apache.felix.ipojo.configuration.Configuration;
import org.apache.felix.ipojo.configuration.Instance;

/**
 * Declares an instance of the asset controller to server $basedir/documentation.
 * The goal is to have the external documentation (reference, mojo and javadoc) structured as follows:
 *
 * {@literal documentation/reference/0.4}
 * {@literal documentation/reference/0.5-SNAPSHOT}
 * {@literal documentation/wisdom-maven-plugin/0.4}
 * {@literal documentation/wisdom-maven-plugin/0.5-SNAPSHOT}
 * {@literal documentation/apidocs/0.4}
 * {@literal documentation/apidocs/0.5-SNAPSHOT}
 * ...
 */
@Configuration
public class DocConfiguration {

    /**
     * Declares the instance of resource controller serving resources from 'basedir/documentation'.
     */
    Instance instance = Instance.instance().of("org.wisdom.resources.ResourceController")
            .named("Documentation-Resources")
            .with("path").setto("documentation");
}

package site;

import org.apache.felix.ipojo.configuration.Configuration;
import org.apache.felix.ipojo.configuration.Instance;

/**
 * Declares an instance of the asset controller to server $basedir/documentation.
 * The goal is to have the external documentation (reference, mojo and javadoc) structured as follows:
 * <p/>
 * {@literal documentation/reference/0.4}
 * {@literal documentation/reference/0.5-SNAPSHOT}
 * {@literal documentation/wisdom-maven-plugin/0.4}
 * {@literal documentation/wisdom-maven-plugin/0.5-SNAPSHOT}
 * {@literal documentation/apidocs/0.4}
 * {@literal documentation/apidocs/0.5-SNAPSHOT}
 * ...
 */
@Configuration
public class DocConfiguration {

    /**
     * Declares the instance of resource controller serving resources from 'basedir/documentation'.
     */
    public static Instance declareTheDocumentationController() {
        return Instance.instance().of("org.wisdom.resources.AssetController")
                .named("Documentation-Resources")
                .with("path").setto("documentation");
    }
}

Update the resource controller instance. The class has changed.

Signed-off-by: Clement Escoffier <6397137e57d1f87002962a37058f2a1c76fca9db@gmail.com>


package com.metacodestudio.hotsuploader;

import com.metacodestudio.hotsuploader.controllers.HomeController;
import io.datafx.controller.flow.Flow;
import io.datafx.controller.flow.FlowHandler;
import io.datafx.controller.flow.container.DefaultFlowContainer;
import io.datafx.controller.flow.context.ViewFlowContext;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;

public class Client extends Application {

    public static void main(String[] args) {
        Application.launch(Client.class, args);
    }

    @Override
    public void start(final Stage primaryStage) throws Exception {
        Flow flow = new Flow(HomeController.class);
        FlowHandler flowHandler = flow.createHandler(new ViewFlowContext());
        DefaultFlowContainer container = new DefaultFlowContainer();
        StackPane pane = flowHandler.start(container);
        primaryStage.setScene(new Scene(pane));
        primaryStage.setOnCloseRequest(event -> System.exit(0));
        primaryStage.show();
    }

}

package com.metacodestudio.hotsuploader;

import com.metacodestudio.hotsuploader.controllers.HomeController;
import io.datafx.controller.flow.Flow;
import io.datafx.controller.flow.FlowHandler;
import io.datafx.controller.flow.container.DefaultFlowContainer;
import io.datafx.controller.flow.context.ViewFlowContext;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;

import java.io.File;

public class Client extends Application {

    private static File hotsRoot;

    public static File getHotsRoot() {
        return hotsRoot;
    }

    public static void main(String[] args) {
        hotsRoot = getRootDirectory();
        Application.launch(Client.class, args);
    }

    private static File getRootDirectory() {
        StringBuilder builder = new StringBuilder(System.getProperty("user.home"));
        if (isWindows()) {
            builder.append("\\Documents\\Heroes of the Storm\\Accounts\\");
        } else if (isMacintosh()) {
            builder.append("/Library/Application Support/Blizzard/Heroes of the Storm/Accounts/");
        } else {
            throw new UnsupportedOperationException("This application requires Windows or Macintosh OSX to run");
        }
        return new File(builder.toString());
    }

    private static boolean isMacintosh() {
        // TODO DETERMINE MACINTOSH PROPERTIES
        throw new UnsupportedOperationException("Macintosh check not yet implemented");
    }

    private static boolean isWindows() {
        String osName = System.getProperty("os.name");
        return osName.contains("Windows");
    }

    @Override
    public void start(final Stage primaryStage) throws Exception {
        Flow flow = new Flow(HomeController.class);
        FlowHandler flowHandler = flow.createHandler(new ViewFlowContext());
        DefaultFlowContainer container = new DefaultFlowContainer();
        StackPane pane = flowHandler.start(container);
        primaryStage.setScene(new Scene(pane));
        primaryStage.setOnCloseRequest(event -> System.exit(0));
        primaryStage.show();
    }

}

Add reference to root file

Add reference to root file


/*
 * Copyright 2013-present Facebook, 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.facebook.buck.testutil;

import com.google.common.base.Function;

import java.nio.file.Path;
import java.nio.file.Paths;

public class IdentityPathRelativizer {

  private IdentityPathRelativizer() {
    // Utility class
  }

  public static Function<String, Path> getIdentityRelativizer() {
    return new Function<String, Path>() {
      @Override
      public Path apply(String input) {
        return Paths.get(input);
      }
    };
  }
}

/*
 * Copyright 2013-present Facebook, 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.facebook.buck.testutil;

import com.google.common.base.Function;

import java.nio.file.Path;
import java.nio.file.Paths;

public class IdentityPathRelativizer {

  /** Utility class: do not instantiate. */
  private IdentityPathRelativizer() {}

  public static Function<String, Path> getIdentityRelativizer() {
    return new Function<String, Path>() {
      @Override
      public Path apply(String input) {
        return Paths.get(input);
      }
    };
  }
}

Use consistent comment for utility class constructor.

Summary: This also reduces the number of executable lines by one according to EMMA.

Test Plan: Sandcastle builds.


package org.bouncycastle.math.field;

import java.math.BigInteger;

public abstract class FiniteFields
{
    static final FiniteField GF_2 = new PrimeField(BigInteger.valueOf(2));
    static final FiniteField GF_3 = new PrimeField(BigInteger.valueOf(3));

    public static PolynomialExtensionField getBinaryExtensionField(int[] exponents)
    {
        return new GenericPolynomialExtensionField(GF_2, new GF2Polynomial(exponents));
    }

    public static FiniteField getPrimeField(BigInteger characteristic)
    {
        characteristic = characteristic.abs();

        int bitLength = characteristic.bitLength();
        if (bitLength < 3)
        {
            if (bitLength < 2)
            {
                throw new IllegalArgumentException("'characteristic' must be >= 2");
            }

            switch (characteristic.intValue())
            {
            case 2:
                return GF_2;
            case 3:
                return GF_3;
            }
        }

        return new PrimeField(characteristic);
    }
}

package org.bouncycastle.math.field;

import java.math.BigInteger;

public abstract class FiniteFields
{
    static final FiniteField GF_2 = new PrimeField(BigInteger.valueOf(2));
    static final FiniteField GF_3 = new PrimeField(BigInteger.valueOf(3));

    public static PolynomialExtensionField getBinaryExtensionField(int[] exponents)
    {
        if (exponents[0] != 0)
        {
            throw new IllegalArgumentException("Irreducible polynomials in GF(2) must have constant term");
        }
        for (int i = 1; i < exponents.length; ++i)
        {
            if (exponents[i] <= exponents[i - 1])
            {
                throw new IllegalArgumentException("Polynomial exponents must be montonically increasing");
            }
        }

        return new GenericPolynomialExtensionField(GF_2, new GF2Polynomial(exponents));
    }

//    public static PolynomialExtensionField getTernaryExtensionField(Term[] terms)
//    {
//        return new GenericPolynomialExtensionField(GF_3, new GF3Polynomial(terms));
//    }

    public static FiniteField getPrimeField(BigInteger characteristic)
    {
        int bitLength = characteristic.bitLength();
        if (characteristic.signum() <= 0 || bitLength < 2)
        {
            throw new IllegalArgumentException("'characteristic' must be >= 2");
        }

        if (bitLength < 3)
        {
            switch (characteristic.intValue())
            {
            case 2:
                return GF_2;
            case 3:
                return GF_3;
            }
        }

        return new PrimeField(characteristic);
    }
}

Improve argument checks and add hint of future ternary extensions


package eu.kanade.mangafeed.data.database;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.support.annotation.NonNull;

import eu.kanade.mangafeed.data.database.tables.ChapterSyncTable;
import eu.kanade.mangafeed.data.database.tables.ChapterTable;
import eu.kanade.mangafeed.data.database.tables.MangaTable;

public class DbOpenHelper extends SQLiteOpenHelper {

    public static final String DATABASE_NAME = "mangafeed.db";
    public static final int DATABASE_VERSION = 2;

    public DbOpenHelper(@NonNull Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    @Override
    public void onCreate(@NonNull SQLiteDatabase db) {
        db.execSQL(MangaTable.getCreateTableQuery());
        db.execSQL(ChapterTable.getCreateTableQuery());
    }

    @Override
    public void onUpgrade(@NonNull SQLiteDatabase db, int oldVersion, int newVersion) {
        if (oldVersion == 1)
            db.execSQL(ChapterSyncTable.getCreateTableQuery());
    }

    @Override
    public void onConfigure(SQLiteDatabase db){
        db.setForeignKeyConstraintsEnabled(true);
    }

}

package eu.kanade.mangafeed.data.database;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.support.annotation.NonNull;

import eu.kanade.mangafeed.data.database.tables.ChapterSyncTable;
import eu.kanade.mangafeed.data.database.tables.ChapterTable;
import eu.kanade.mangafeed.data.database.tables.MangaTable;

public class DbOpenHelper extends SQLiteOpenHelper {

    public static final String DATABASE_NAME = "mangafeed.db";
    public static final int DATABASE_VERSION = 2;

    public DbOpenHelper(@NonNull Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    @Override
    public void onCreate(@NonNull SQLiteDatabase db) {
        db.execSQL(MangaTable.getCreateTableQuery());
        db.execSQL(ChapterTable.getCreateTableQuery());
        db.execSQL(ChapterSyncTable.getCreateTableQuery());
    }

    @Override
    public void onUpgrade(@NonNull SQLiteDatabase db, int oldVersion, int newVersion) {
        if (oldVersion == 1)
            db.execSQL(ChapterSyncTable.getCreateTableQuery());
    }

    @Override
    public void onConfigure(SQLiteDatabase db){
        db.setForeignKeyConstraintsEnabled(true);
    }

}

Create chaptersync table for new databases


package yuku.alkitab.base.widget;

import android.text.style.ClickableSpan;
import android.view.View;

public abstract class VerseInlineLinkSpan extends ClickableSpan {
	public interface Factory {
		VerseInlineLinkSpan create(final Type type, final int arif);
	}

	private final Type type;
	private final int arif;
	private final Object source;

	public enum Type {
		footnote,
		xref,
	}

	public VerseInlineLinkSpan(final Type type, final int arif, final Object source) {
		this.type = type;
		this.arif = arif;
		this.source = source;
	}

	@Override
	public final void onClick(final View widget) {
		onClick(type, arif, source);
	}

	public abstract void onClick(final Type type, final int arif, final Object source);
}

package yuku.alkitab.base.widget;

import android.text.TextPaint;
import android.text.style.ClickableSpan;
import android.view.View;

public abstract class VerseInlineLinkSpan extends ClickableSpan {
	public interface Factory {
		VerseInlineLinkSpan create(final Type type, final int arif);
	}

	private final Type type;
	private final int arif;
	private final Object source;

	public enum Type {
		footnote,
		xref,
	}

	public VerseInlineLinkSpan(final Type type, final int arif, final Object source) {
		this.type = type;
		this.arif = arif;
		this.source = source;
	}

	@Override
	public final void onClick(final View widget) {
		onClick(type, arif, source);
	}

	public abstract void onClick(final Type type, final int arif, final Object source);

	@Override
	public void updateDrawState(final TextPaint ds) {
		// don't call super to prevent link underline and link coloring
		// NOP
	}
}

Remove coloring and underlining of verse inline links.


package org.atlasapi.neo4j;

import org.neo4j.driver.v1.AuthToken;
import org.neo4j.driver.v1.Config;
import org.neo4j.driver.v1.Driver;
import org.neo4j.driver.v1.GraphDatabase;
import org.neo4j.driver.v1.Session;

import static com.google.common.base.Preconditions.checkNotNull;

public class Neo4jSessionFactory {

    private final Driver driver;

    private Neo4jSessionFactory(Driver driver) {
        this.driver = checkNotNull(driver);
    }

    public static Neo4jSessionFactory create(
            String host, int port, AuthToken authToken, int maxIdleSessions
    ) {
        return new Neo4jSessionFactory(GraphDatabase
                .driver(
                        "bolt://" + host + ":" + port,
                        authToken,
                        Config.build()
                                .withMaxIdleSessions(maxIdleSessions)
                                .withEncryptionLevel(Config.EncryptionLevel.NONE)
                                .toConfig()
                ));
    }

    public Session getSession() {
        return driver.session();
    }

    public void close() {
        driver.close();
    }
}

package org.atlasapi.neo4j;

import org.neo4j.driver.v1.AuthToken;
import org.neo4j.driver.v1.Config;
import org.neo4j.driver.v1.Driver;
import org.neo4j.driver.v1.GraphDatabase;
import org.neo4j.driver.v1.Session;

import static com.google.common.base.Preconditions.checkNotNull;

public class Neo4jSessionFactory {

    private final Driver driver;

    private Neo4jSessionFactory(Driver driver) {
        this.driver = checkNotNull(driver);
    }

    public static Neo4jSessionFactory create(
            String host, int port, AuthToken authToken, int maxIdleSessions
    ) {
        return new Neo4jSessionFactory(GraphDatabase
                .driver(
                        "bolt://" + checkNotNull(host) + ":" + port,
                        checkNotNull(authToken),
                        Config.build()
                                .withMaxIdleSessions(maxIdleSessions)
                                .withEncryptionLevel(Config.EncryptionLevel.NONE)
                                .toConfig()
                ));
    }

    public Session getSession() {
        return driver.session();
    }

    public void close() {
        driver.close();
    }
}

Add missing null-checks for Neo4j session factory instantiation


/*
 * 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.heartbeat;

import com.google.common.collect.ImmutableList;
import org.junit.Assert;
import org.junit.Test;

/**
 * Unit tests for {@link HeartbeatContext}.
 */
public final class HeartbeatContextTest {
  @Test
  public void allThreadsUseSleepingTimer() {
    for (String threadName : HeartbeatContext.getTimerClasses().keySet()) {
      Class<? extends HeartbeatTimer> timerClass = HeartbeatContext.getTimerClass(threadName);
      Assert.assertTrue(timerClass.isAssignableFrom(SleepingTimer.class));
    }
  }

  @Test
  public void canTemporarilySwitchToScheduledTimer() throws Exception {
    try (ManuallyScheduleHeartbeat.Resource h =
        new ManuallyScheduleHeartbeat.Resource(ImmutableList.of(HeartbeatContext.WORKER_CLIENT))) {
      Assert.assertTrue(HeartbeatContext.getTimerClass(HeartbeatContext.WORKER_CLIENT)
          .isAssignableFrom(ScheduledTimer.class));
    }
    Assert.assertTrue(HeartbeatContext.getTimerClass(HeartbeatContext.WORKER_CLIENT)
        .isAssignableFrom(SleepingTimer.class));
  }
}

/*
 * 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.heartbeat;

import static org.junit.Assert.assertTrue;

import com.google.common.collect.ImmutableList;
import org.junit.Test;

/**
 * Unit tests for {@link HeartbeatContext}.
 */
public final class HeartbeatContextTest {
  @Test
  public void allThreadsUseSleepingTimer() {
    for (String threadName : HeartbeatContext.getTimerClasses().keySet()) {
      Class<? extends HeartbeatTimer> timerClass = HeartbeatContext.getTimerClass(threadName);
      assertTrue(timerClass.isAssignableFrom(SleepingTimer.class));
    }
  }

  @Test
  public void canTemporarilySwitchToScheduledTimer() throws Exception {
    try (ManuallyScheduleHeartbeat.Resource h =
        new ManuallyScheduleHeartbeat.Resource(ImmutableList.of(HeartbeatContext.WORKER_CLIENT))) {
      assertTrue(HeartbeatContext.getTimerClass(HeartbeatContext.WORKER_CLIENT)
          .isAssignableFrom(ScheduledTimer.class));
    }
    assertTrue(HeartbeatContext.getTimerClass(HeartbeatContext.WORKER_CLIENT)
        .isAssignableFrom(SleepingTimer.class));
  }
}

[SMALLFIX] Use static imports for standard test utilities

Change

import org.junit.Assert;

to

import static org.junit.Assert.assertTrue;

AND

Update all

Assert.{{ method }}*

to

{{ method }}*

For example

update

Assert.assertTrue(mGraph.getRoots().isEmpty());

to

assertTrue(mGraph.getRoots().isEmpty());

pr-link: Alluxio/alluxio#8978
change-id: cid-f0f493a5f4a13d9842194a5b2aa92a3f289fd7a6


package org.jevon.cordova.parse.pushplugin;

import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaPlugin;
import org.json.JSONArray;
import org.json.JSONException;

import com.parse.Parse;
import com.parse.ParseInstallation;

public class ParsePushPlugin extends CordovaPlugin {

	public static final String ACTION_INITIALIZE = "initialize";

	@Override
	public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {
		if (action.equals(ACTION_INITIALIZE)) {
			this.initialize(callbackContext, args);
			return true;
		}
		// TODO more actions...
		return false;	// false == NoSuchMethod
	}

	private void initialize(final CallbackContext context, final JSONArray args) throws JSONException {
		if (args.length() >= 1) {
			String appId = args.getString(0);
			String clientKey = args.getString(1);
			Parse.initialize(cordova.getActivity(), appId, clientKey);

			// "Also, save the current installation to Parse"
			ParseInstallation.getCurrentInstallation().saveInBackground();

			context.success();
		} else {
			context.error("Expected two arguments");
		}
	}

}

package org.jevon.cordova.parse.pushplugin;

import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaPlugin;
import org.json.JSONArray;
import org.json.JSONException;

import com.parse.Parse;
import com.parse.ParseInstallation;

public class ParsePushPlugin extends CordovaPlugin {

	public static final String ACTION_INITIALIZE = "initialize";

	@Override
	public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {
		if (action.equals(ACTION_INITIALIZE)) {
			this.initialize(callbackContext, args);
			return true;
		}
		// TODO more actions...
		return false;	// false == NoSuchMethod
	}

	private void initialize(final CallbackContext context, final JSONArray args) throws JSONException {
		if (args.length() >= 1) {
			final String appId = args.getString(0);
			final String clientKey = args.getString(1);

			// "exec() to initialize blocked the main thread; Plugin should use CordovaInterface.getThreadPool()"
			cordova.getThreadPool().execute(new Runnable() {
				@Override
				public void run() {
					Parse.initialize(cordova.getActivity(), appId, clientKey);

					// "Also, save the current installation to Parse"
					ParseInstallation.getCurrentInstallation().saveInBackground();

					context.success();
				}
			});
		} else {
			context.error("Expected two arguments");
		}
	}

}

Use Cordova ThreadPool for Parse.initialize


package info.u_team.u_team_core.gui;

import net.minecraft.client.gui.screen.inventory.ContainerScreen;
import net.minecraft.entity.player.PlayerInventory;
import net.minecraft.inventory.container.Container;
import net.minecraft.util.text.ITextComponent;

public abstract class FluidContainerScreen<T extends Container> extends ContainerScreen<T> {

	public FluidContainerScreen(T screenContainer, PlayerInventory inv, ITextComponent titleIn) {
		super(screenContainer, inv, titleIn);
	}

	@Override
	protected void drawGuiContainerForegroundLayer(int mouseX, int mouseY) {
	}

}

package info.u_team.u_team_core.gui;

import info.u_team.u_team_core.container.*;
import net.minecraft.client.gui.screen.inventory.ContainerScreen;
import net.minecraft.entity.player.PlayerInventory;
import net.minecraft.inventory.container.Container;
import net.minecraft.util.text.ITextComponent;
import net.minecraftforge.api.distmarker.*;

@OnlyIn(Dist.CLIENT)
public abstract class FluidContainerScreen<T extends Container> extends ContainerScreen<T> {

	public FluidContainerScreen(T screenContainer, PlayerInventory inv, ITextComponent titleIn) {
		super(screenContainer, inv, titleIn);
	}

	@Override
	protected void drawGuiContainerForegroundLayer(int mouseX, int mouseY) {
		if (container instanceof FluidContainer) {
			final FluidContainer fluidContainer = (FluidContainer) container;
			for (int index = 0; index < fluidContainer.fluidSlots.size(); index++) {
				drawFluidSlot(fluidContainer.fluidSlots.get(index));
			}
		}
	}

	private void drawFluidSlot(FluidSlot slot) {
		// final int x = slot.getX();
		// final int y = slot.getY();
		// final FluidStack stack = slot.getStack();
		// TODO
	}

}

Implement basic draw fluid slot method (unused still TODO)


package net.glowstone.block.blocktype;

import net.glowstone.block.GlowBlock;
import net.glowstone.block.entity.TEContainer;
import net.glowstone.block.entity.TileEntity;
import net.glowstone.entity.GlowPlayer;
import org.bukkit.block.BlockFace;
import org.bukkit.util.Vector;

/**
 * Base BlockType for containers.
 */
public class BlockContainer extends BlockType {

    @Override
    public boolean blockInteract(GlowPlayer player, GlowBlock block, BlockFace face, Vector clickedLoc) {
        TileEntity te = block.getTileEntity();
        if (te instanceof TEContainer) {
            // todo: animation?
            player.openInventory(((TEContainer) te).getInventory());
            return true;
        }
        return false;
    }

}

package net.glowstone.block.blocktype;

import net.glowstone.block.GlowBlock;
import net.glowstone.block.entity.TEContainer;
import net.glowstone.block.entity.TileEntity;
import net.glowstone.entity.GlowPlayer;
import org.bukkit.block.BlockFace;
import org.bukkit.inventory.ItemStack;
import org.bukkit.util.Vector;

import java.util.Collection;
import java.util.LinkedList;

/**
 * Base BlockType for containers.
 */
public class BlockContainer extends BlockType {

    @Override
    public boolean blockInteract(GlowPlayer player, GlowBlock block, BlockFace face, Vector clickedLoc) {
        TileEntity te = block.getTileEntity();
        if (te instanceof TEContainer) {
            // todo: animation?
            player.openInventory(((TEContainer) te).getInventory());
            return true;
        }
        return false;
    }

    @Override
    public Collection<ItemStack> getDrops(GlowBlock block) {
        LinkedList<ItemStack> list = new LinkedList<ItemStack>();

        list.add(new ItemStack(block.getType(), 1));

        for (ItemStack i : ((TEContainer) block.getTileEntity()).getInventory().getContents()) {
            if (i != null) {
                list.add(i);
            }
        }
        return list;
    }

}

Implement container blocks dropping their contents.

Fixes containers losing their contents and dropping incorrect blocks when
broken.


package com.elmakers.mine.bukkit.action;

import com.elmakers.mine.bukkit.api.action.ActionHandler;
import com.elmakers.mine.bukkit.api.action.CastContext;
import com.elmakers.mine.bukkit.api.spell.SpellResult;

public abstract class CheckAction extends CompoundAction {

    protected abstract boolean isAllowed(CastContext context);

    @Override
    public SpellResult step(CastContext context) {
        boolean allowed = isAllowed(context);
        ActionHandler actions = getHandler("actions");
        if (actions == null || actions.size() == 0) {
            return allowed ? SpellResult.CAST : SpellResult.STOP;
        }

        if (!allowed) {
            return SpellResult.NO_TARGET;
        }
        return startActions();
    }
}

package com.elmakers.mine.bukkit.action;

import org.bukkit.configuration.ConfigurationSection;

import com.elmakers.mine.bukkit.api.action.ActionHandler;
import com.elmakers.mine.bukkit.api.action.CastContext;
import com.elmakers.mine.bukkit.api.spell.Spell;
import com.elmakers.mine.bukkit.api.spell.SpellResult;

public abstract class CheckAction extends CompoundAction {

    protected abstract boolean isAllowed(CastContext context);

    @Override
    protected void addHandlers(Spell spell, ConfigurationSection parameters) {
        addHandler(spell, "actions");
        addHandler(spell, "fail");
    }

    @Override
    public SpellResult step(CastContext context) {
        boolean allowed = isAllowed(context);
        if (!allowed) {
            ActionHandler fail = getHandler("fail");
            if (fail != null && fail.size() != 0) {
                return startActions("fail");
            }
        }
        ActionHandler actions = getHandler("actions");
        if (actions == null || actions.size() == 0) {
            return allowed ? SpellResult.CAST : SpellResult.STOP;
        }

        if (!allowed) {
            return SpellResult.NO_TARGET;
        }
        return startActions();
    }
}

Add optional "fail" action handler to Check actions


package seedu.todo.ui.components;

import javafx.fxml.FXML;
import javafx.scene.layout.Pane;
import javafx.scene.text.Text;
import javafx.stage.Stage;
import seedu.todo.models.Task;
import seedu.todo.ui.UiPartLoader;

public class TaskListTaskItem extends MultiComponent {

    private static final String FXML_PATH = "components/TaskListTaskItem.fxml";
    private static final String DOT = ".";

    // Props
    public Task task;
    public int displayIndex;

    // FXML
    @FXML
    private Text taskText;

    public static TaskListTaskItem load(Stage primaryStage, Pane placeholderPane) {
        return UiPartLoader.loadUiPart(primaryStage, placeholderPane, new TaskListTaskItem());
    }

    @Override
    public String getFxmlPath() {
        return FXML_PATH;
    }

    @Override
    public void componentDidMount() {
        taskText.setText(formatTaskText(displayIndex, task.getName()));
    }

    private String formatTaskText(int index, String taskName) {
        return String.format("%s %s", index + DOT, taskName);
    }

}

package seedu.todo.ui.components;

import javafx.fxml.FXML;
import javafx.scene.layout.Pane;
import javafx.scene.text.Text;
import javafx.stage.Stage;
import seedu.todo.models.Task;
import seedu.todo.ui.UiPartLoader;

public class TaskListTaskItem extends MultiComponent {

    private static final String FXML_PATH = "components/TaskListTaskItem.fxml";

    // Props
    public Task task;
    public int displayIndex;

    // FXML
    @FXML
    private Text taskText;

    public static TaskListTaskItem load(Stage primaryStage, Pane placeholderPane) {
        return UiPartLoader.loadUiPart(primaryStage, placeholderPane, new TaskListTaskItem());
    }

    @Override
    public String getFxmlPath() {
        return FXML_PATH;
    }

    @Override
    public void componentDidMount() {
        taskText.setText(formatTaskText(displayIndex, task.getName()));
    }

    private String formatTaskText(int index, String taskName) {
        return String.format("%s. %s", index, taskName);
    }

}

Remove extract magic string for DOT, use String.format for greater clarity


package bisq.asset.coins;

import bisq.asset.Coin;
import bisq.asset.LiquidBitcoinAddressValidator;

public class TetherUSDLiquid extends Coin {
    public TetherUSDLiquid() {
        // If you add a new USDT variant or want to change this ticker symbol you should also look here:
        // core/src/main/java/bisq/core/provider/price/PriceProvider.java:getAll()
        super("Tether USD (Liquid Bitcoin)", "L-USDT", new LiquidBitcoinAddressValidator());
    }
}

package bisq.asset.coins;

import bisq.asset.Coin;
import bisq.asset.LiquidBitcoinAddressValidator;

public class TetherUSDLiquid extends Coin {
    public TetherUSDLiquid() {
        // If you add a new USDT variant or want to change this ticker symbol you should also look here:
        // core/src/main/java/bisq/core/provider/price/PriceProvider.java:getAll()
        super("Tether USD (Liquid)", "L-USDT", new LiquidBitcoinAddressValidator());
    }
}

Fix name of L-USDT asset to Tether USD (Liquid)


package seedu.tache.logic.commands;

import seedu.tache.logic.commands.exceptions.CommandException;

public class UndoCommand extends Command {

    public static final String COMMAND_WORD = "undo";
    public static final String MESSAGE_USAGE = COMMAND_WORD + ":\n" + "Undoes the last change to the address book.\n\t"
            + "Example: " + COMMAND_WORD;

    public static final String MESSAGE_SUCCESS = "Undone: %s";
    public static final String MESSAGE_EMPTY_HISTORY = "Nothing to undo!";
    public static final String MESSAGE_FAILURE = "Failed to undo: %s";

    @Override
    public CommandResult execute() {
        // TODO Auto-generated method stub
        if (undoHistory.isEmpty()) {
            return new CommandResult(MESSAGE_EMPTY_HISTORY);
        } else {
            Undoable lastCommand = undoHistory.pop();
            assert lastCommand.isUndoable();
            try {
                String undoResult = lastCommand.undo();
                return new CommandResult(String.format(MESSAGE_SUCCESS, undoResult));
            } catch (CommandException e) {
                return new CommandResult(String.format(MESSAGE_FAILURE, e.getMessage()));
            }
        }
    }

}

package seedu.tache.logic.commands;

import seedu.tache.logic.commands.exceptions.CommandException;

public class UndoCommand extends Command {

    public static final String COMMAND_WORD = "undo";
    public static final String MESSAGE_USAGE = COMMAND_WORD + ":\n" + "Undoes the last change to the address book.\n\t"
            + "Example: " + COMMAND_WORD;

    public static final String MESSAGE_SUCCESS = "Undone: %s";
    public static final String MESSAGE_EMPTY_HISTORY = "Nothing to undo!";
    public static final String MESSAGE_FAILURE = "Failed to undo: %s";

    @Override
    public CommandResult execute() {
        // TODO Auto-generated method stub
        if (undoHistory.isEmpty()) {
            return new CommandResult(MESSAGE_EMPTY_HISTORY);
        } else {
            Undoable lastCommand = undoHistory.pop();
            assert lastCommand.isUndoable() : "The popped command can't be undone!";
            try {
                String undoResult = lastCommand.undo();
                return new CommandResult(String.format(MESSAGE_SUCCESS, undoResult));
            } catch (CommandException e) {
                return new CommandResult(String.format(MESSAGE_FAILURE, e.getMessage()));
            }
        }
    }

}

Update assert to be more verbose

Update assert to be more verbose


/*
 * 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.jdbi.v3.jpa;

import org.jdbi.v3.sqlobject.Binder;
import org.jdbi.v3.sqlobject.BinderFactory;

import java.lang.annotation.Annotation;

public class BindAnnoFactory implements BinderFactory {

    @Override
    public Binder<BindAnno, Object> build(Annotation annotation) {
        return (q, parameter, bind, arg) -> {
            final String prefix;
            if ("___jdbi_bare___".equals(bind.value())) {
                prefix = "";
            } else {
                prefix = bind.value() + ".";
            }

            try {
                AnnoClass<?> annos = AnnoClass.get(arg.getClass());
                for (AnnoMember anno : annos.getters()) {
                    q.bind(prefix + anno.getName(), anno.read(arg));
                }
            } catch (Exception e) {
                throw new IllegalStateException(
                        "unable to bind bean properties", e);
            }
        };
    }
}

/*
 * 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.jdbi.v3.jpa;

import org.jdbi.v3.sqlobject.Binder;
import org.jdbi.v3.sqlobject.BinderFactory;

import java.lang.annotation.Annotation;

public class BindAnnoFactory implements BinderFactory<BindAnno, Object> {

    @Override
    public Binder<BindAnno, Object> build(BindAnno annotation) {
        return (q, parameter, bind, arg) -> {
            final String prefix;
            if ("___jdbi_bare___".equals(bind.value())) {
                prefix = "";
            } else {
                prefix = bind.value() + ".";
            }

            try {
                AnnoClass<?> annos = AnnoClass.get(arg.getClass());
                for (AnnoMember anno : annos.getters()) {
                    q.bind(prefix + anno.getName(), anno.read(arg));
                }
            } catch (Exception e) {
                throw new IllegalStateException(
                        "unable to bind bean properties", e);
            }
        };
    }
}

Update generics to match changes in jdbi3 branch


package com.wolfninja.keystore.redis;

import org.easymock.EasyMock;
import org.testng.Assert;
import org.testng.annotations.Test;

import redis.clients.jedis.JedisPool;

import com.wolfninja.keystore.api.Keyspace;

@SuppressWarnings("javadoc")
@Test
public class RedisAdapterTest {

	@Test
	public void create() {
		final JedisPool mockPool = EasyMock.createMock(JedisPool.class);

		final RedisAdapter actual = RedisAdapter.create(mockPool);

		Assert.assertNotNull(actual);
	}

	@Test
	public void getKeyspace() {
		final JedisPool mockPool = EasyMock.createMock(JedisPool.class);

		final RedisAdapter adapter = RedisAdapter.create(mockPool);
		final Keyspace actual = adapter.getKeyspace("my.keyspace");

		Assert.assertEquals(actual.getClass(), RedisKeyspace.class);
	}
}

package com.wolfninja.keystore.redis;

import java.util.Optional;

import org.easymock.EasyMock;
import org.testng.Assert;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;

import com.wolfninja.keystore.api.Keyspace;

import redis.clients.jedis.JedisPool;

@SuppressWarnings("javadoc")
@Test
public class RedisAdapterTest {

	@Test(dataProvider = "buildKeyspaceNameData")
	public void buildKeyspaceName(final String inputPrefix, final String expected) {
		final JedisPool mockPool = EasyMock.createMock(JedisPool.class);

		final RedisAdapter adapter = RedisAdapter.create(mockPool, inputPrefix);
		final String actual = adapter.buildKeyspaceName("myKeyspace");
		Assert.assertEquals(actual, expected);
	}

	@DataProvider
	Object[][] buildKeyspaceNameData() {
		return new Object[][] { //
				{ null, "myKeyspace" }, //
				{ "nice_", "nice_myKeyspace" }, //
		};
	}

	@Test
	public void create() {
		final JedisPool mockPool = EasyMock.createMock(JedisPool.class);

		final RedisAdapter actual = RedisAdapter.create(mockPool);

		Assert.assertNotNull(actual);
	}

	@Test
	public void createWithPrefix() {
		final JedisPool mockPool = EasyMock.createMock(JedisPool.class);

		final RedisAdapter actual = RedisAdapter.create(mockPool, "asdf_");

		Assert.assertNotNull(actual);
		Assert.assertEquals(actual.getKeyspacePrefix(), Optional.of("asdf_"));
	}

	@Test
	public void getKeyspace() {
		final JedisPool mockPool = EasyMock.createMock(JedisPool.class);

		final RedisAdapter adapter = RedisAdapter.create(mockPool);
		final Keyspace actual = adapter.getKeyspace("my.keyspace");

		Assert.assertEquals(actual.getClass(), RedisKeyspace.class);
	}
}

Add test coverage for prefix

Add test coverage for prefix


package tech.tablesaw.io.saw;

/*
 * 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.
 */

import com.google.common.annotations.Beta;

/**
 * Utilities and constants for reading and writing data in Tablesaw's own compressed,
 * column-oriented file format aka "saw"
 */
@Beta
class SawUtils {

  private SawUtils() {}

  static final String FLOAT = "FLOAT";
  static final String DOUBLE = "DOUBLE";
  static final String INTEGER = "INTEGER";
  static final String LONG = "LONG";
  static final String SHORT = "SHORT";
  static final String STRING = "STRING";
  static final String TEXT = "TEXT";
  static final String INSTANT = "INSTANT";
  static final String LOCAL_DATE = "LOCAL_DATE";
  static final String LOCAL_TIME = "LOCAL_TIME";
  static final String LOCAL_DATE_TIME = "LOCAL_DATE_TIME";
  static final String BOOLEAN = "BOOLEAN";
}

/*
 * 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 tech.tablesaw.io.saw;

import com.google.common.annotations.Beta;

/**
 * Utilities and constants for reading and writing data in Tablesaw's own compressed,
 * column-oriented file format aka "saw"
 */
@Beta
class SawUtils {

  private SawUtils() {}

  static final String FLOAT = "FLOAT";
  static final String DOUBLE = "DOUBLE";
  static final String INTEGER = "INTEGER";
  static final String LONG = "LONG";
  static final String SHORT = "SHORT";
  static final String STRING = "STRING";
  static final String TEXT = "TEXT";
  static final String INSTANT = "INSTANT";
  static final String LOCAL_DATE = "LOCAL_DATE";
  static final String LOCAL_TIME = "LOCAL_TIME";
  static final String LOCAL_DATE_TIME = "LOCAL_DATE_TIME";
  static final String BOOLEAN = "BOOLEAN";
}

Put license at top of file

Put license at top of file


package com.jenzz.buildconstants.sample;

import android.support.v7.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {

}

package com.jenzz.buildconstants.sample;

import android.content.res.Resources;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {

  @SuppressWarnings("unused")
  @Override
  protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    // Java constants
    String javaString = SampleBuildConstants.ASTRING;
    boolean javaBoolean = SampleBuildConstants.ABOOLEAN;
    int javaNumber = SampleBuildConstants.ANUMBER;

    // XML constants
    Resources res = getResources();
    String xmlString = res.getString(R.string.astring);
    boolean xmlBoolean = res.getBoolean(R.bool.aboolean);
    int xmlNumber = res.getInteger(R.integer.anumber);
  }
}

Use generated constants in sample project


/*
 * Copyright 2015 EuregJUG.
 *
 * 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 eu.euregjug.site.events;

import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;

/**
 * @author Michael J. Simons, 2015-12-26
 */
public interface EventRepository extends JpaRepository<EventEntity, Integer> {
    List<EventEntity> findUpcomingEvents();
}

/*
 * Copyright 2015 EuregJUG.
 *
 * 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 eu.euregjug.site.events;

import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.transaction.annotation.Transactional;

/**
 * @author Michael J. Simons, 2015-12-26
 */
public interface EventRepository extends JpaRepository<EventEntity, Integer> {
    @Transactional(readOnly = true)
    List<EventEntity> findUpcomingEvents();
}

Fix loading of posts (lob) (again)

Fix loading of posts (lob) (again)


package javax.jmi.reflect;

import java.util.Collection;
import java.util.List;

public interface RefClass extends RefFeatured {
    public RefObject refCreateInstance(List args);
    public Collection refAllOfType();
    public Collection refAllOfClass();
    public RefStruct refCreateStruct(RefObject struct, List params);
    public RefStruct refCreateStruct(String structName, List params);
    public RefEnum refGetEnum(RefObject enum, String name);
    public RefEnum refGetEnum(String enumName, String name);
}

package javax.jmi.reflect;

import java.util.Collection;
import java.util.List;

public interface RefClass extends RefFeatured {
    public RefObject refCreateInstance(List args);
    public Collection refAllOfType();
    public Collection refAllOfClass();
    public RefStruct refCreateStruct(RefObject struct, List params);
    public RefStruct refCreateStruct(String structName, List params);
    public RefEnum refGetEnum(RefObject enum_, String name);
    public RefEnum refGetEnum(String enumName, String name);
}

MONDRIAN: Rename parameter: 'enum' is a reserved word in JDK 1.5. Now builds, and all tests pass, under JDK 1.5.

[git-p4: depot-paths = "//open/mondrian/": change = 3383]


package org.realityforge.ssf;

import org.testng.annotations.Test;
import static org.testng.Assert.*;

public class SimpleSessionManagerTest
{
  @Test
  public void basicWorkflow()
    throws Exception
  {
    final SimpleSessionManager sm = new SimpleSessionManager();
    assertEquals( sm.getSessionKey(), "sid" );
    assertEquals( sm.getSession( "MySessionID" ), null );
    final SessionInfo sessionInfo = sm.createSession();
    assertNotNull( sessionInfo );
    assertNotNull( sessionInfo.getSessionID() );
    assertEquals( sessionInfo.getAttribute( "Username" ), null );
    sessionInfo.setAttribute( "Username", "Bob" );
    assertEquals( sessionInfo.getAttribute( "Username" ), "Bob" );
    sessionInfo.removeAttribute( "Username" );
    assertEquals( sessionInfo.getAttribute( "Username" ), null );
    assertEquals( sessionInfo.getCreatedAt(), sessionInfo.getLastAccessedAt() );
    assertTrue( System.currentTimeMillis() - sessionInfo.getCreatedAt() < 100L );
    assertTrue( System.currentTimeMillis() - sessionInfo.getLastAccessedAt() < 100L );
    Thread.sleep( 1 );

    // The next line should update the last accessed time too!
    assertEquals( sm.getSession( sessionInfo.getSessionID() ), sessionInfo );
    assertNotEquals( sessionInfo.getCreatedAt(), sessionInfo.getLastAccessedAt() );

    assertTrue( sm.invalidateSession( sessionInfo.getSessionID() ) );
    assertFalse( sm.invalidateSession( sessionInfo.getSessionID() ) );
    assertNull( sm.getSession( sessionInfo.getSessionID() ) );
  }
}

package org.realityforge.ssf;

import org.testng.annotations.Test;
import static org.testng.Assert.*;

public class SimpleSessionManagerTest
{
  @Test
  public void basicWorkflow()
    throws Exception
  {
    final SimpleSessionManager sm = new SimpleSessionManager();
    assertEquals( sm.getSessionKey(), "sid" );
    assertEquals( sm.getSession( "MySessionID" ), null );
    final SessionInfo sessionInfo = sm.createSession();
    assertNotNull( sessionInfo );
    assertNotNull( sessionInfo.getSessionID() );
    assertEquals( sessionInfo.getAttribute( "Username" ), null );
    sessionInfo.setAttribute( "Username", "Bob" );
    assertEquals( sessionInfo.getAttribute( "Username" ), "Bob" );
    sessionInfo.removeAttribute( "Username" );
    assertEquals( sessionInfo.getAttribute( "Username" ), null );
    assertEquals( sessionInfo.getCreatedAt(), sessionInfo.getLastAccessedAt() );
    assertTrue( System.currentTimeMillis() - sessionInfo.getCreatedAt() < 100L );
    assertTrue( System.currentTimeMillis() - sessionInfo.getLastAccessedAt() < 100L );
    Thread.sleep( 1 );

    // Make sure we can also get it thorugh the map interface
    assertEquals( sm.getSessions().get(  sessionInfo.getSessionID() ), sessionInfo );

    // The next line should update the last accessed time too!
    assertEquals( sm.getSession( sessionInfo.getSessionID() ), sessionInfo );
    assertNotEquals( sessionInfo.getCreatedAt(), sessionInfo.getLastAccessedAt() );

    assertTrue( sm.invalidateSession( sessionInfo.getSessionID() ) );
    assertFalse( sm.invalidateSession( sessionInfo.getSessionID() ) );
    assertNull( sm.getSession( sessionInfo.getSessionID() ) );
  }
}

Add test for getSession method

Add test for getSession method


package de.morphbit.thymeleaf.dialect;

import java.util.HashSet;
import java.util.Set;

import org.thymeleaf.dialect.AbstractProcessorDialect;
import org.thymeleaf.processor.IProcessor;
import org.thymeleaf.standard.StandardDialect;

import de.morphbit.thymeleaf.model.ThymeleafComponent;
import de.morphbit.thymeleaf.processor.ComponentNamedElementProcessor;
import de.morphbit.thymeleaf.processor.OnceAttributeTagProcessor;

public class ComponentDialect extends AbstractProcessorDialect {

	public static final String NAME = "Component Dialect";

	private final Set<ThymeleafComponent> components;

	public ComponentDialect() {
		this(null);
	}

	public ComponentDialect(Set<ThymeleafComponent> components) {
		super(NAME, "tc", StandardDialect.PROCESSOR_PRECEDENCE);
		this.components = components;
	}

	@Override
	public Set<IProcessor> getProcessors(String dialectPrefix) {
		Set<IProcessor> processors = new HashSet<>();
		processors.add(new OnceAttributeTagProcessor(dialectPrefix));

		if (this.components != null) {
			for (ThymeleafComponent comp : this.components) {
				processors.add(new ComponentNamedElementProcessor(dialectPrefix,
				    comp.getName(), comp.getFragmentTemplate()));
			}
		}
		return processors;
	}

}

package de.morphbit.thymeleaf.dialect;

import java.util.HashSet;
import java.util.Set;

import org.thymeleaf.dialect.AbstractProcessorDialect;
import org.thymeleaf.processor.IProcessor;
import org.thymeleaf.standard.StandardDialect;

import de.morphbit.thymeleaf.model.ThymeleafComponent;
import de.morphbit.thymeleaf.processor.ComponentNamedElementProcessor;
import de.morphbit.thymeleaf.processor.OnceAttributeTagProcessor;

public class ComponentDialect extends AbstractProcessorDialect {

	public static final String NAME = "Component Dialect";
	public static final String PREFIX = "tc";
	public static final int PRECEDENCE = 1000;

	private final Set<ThymeleafComponent> components;

	public ComponentDialect() {
		this(null);
	}

	public ComponentDialect(Set<ThymeleafComponent> components) {
		super(NAME, PREFIX, PRECEDENCE);
		this.components = components;
	}

	@Override
	public Set<IProcessor> getProcessors(String dialectPrefix) {
		Set<IProcessor> processors = new HashSet<>();
		processors.add(new OnceAttributeTagProcessor(dialectPrefix));

		if (this.components != null) {
			for (ThymeleafComponent comp : this.components) {
				processors.add(new ComponentNamedElementProcessor(dialectPrefix,
				    comp.getName(), comp.getFragmentTemplate()));
			}
		}
		return processors;
	}

}

Make variables static and do not use StandardDialect variable


import javax.annotation.Generated;
import javax.annotation.Nonnull;
import org.realityforge.arez.ArezContext;
import org.realityforge.arez.Observable;

@Generated( "org.realityforge.arez.processor.ArezProcessor" )
public final class Arez_TimeModel
  extends TimeModel
{
  private final ArezContext $arez$_context;
  private final Observable $arez$_time;

  protected Arez_TimeModel( @Nonnull final ArezContext $arez$_context, final long time )
  {
    super( time );
    this.$arez$_context = $arez$_context;
    this.$arez$_time = $arez$_context.createObservable( "Time.time" );
  }

  @Override
  public long getTime()
  {
    this.$arez$_time.reportObserved();
    return super.getTime();
  }

  @Override
  public void setTime( final long time )
  {
    if ( super.getTime() != time )
    {
      this.$arez$_time.reportChanged();
      super.setTime( time );
    }
  }

  @Override
  public void updateTime()
  {
    this.$arez$_context.safeProcedure( "Time.updateTime", true, () -> super.updateTime() );
  }
}

import javax.annotation.Generated;
import javax.annotation.Nonnull;
import org.realityforge.arez.ArezContext;
import org.realityforge.arez.Observable;

@Generated( "org.realityforge.arez.processor.ArezProcessor" )
public final class Arez_TimeModel
  extends TimeModel
{
  private final ArezContext $arez$_context;
  private final Observable $arez$_time;

  protected Arez_TimeModel( @Nonnull final ArezContext $arez$_context, final long time )
  {
    super( time );
    this.$arez$_context = $arez$_context;
    this.$arez$_time = $arez$_context.createObservable( "Time.time" );
  }

  @Override
  public long getTime()
  {
    this.$arez$_time.reportObserved();
    return super.getTime();
  }

  @Override
  public void setTime( final long time )
  {
    if ( super.getTime() != time )
    {
      super.setTime( time );
      this.$arez$_time.reportChanged();
    }
  }

  @Override
  public void updateTime()
  {
    this.$arez$_context.safeProcedure( "Time.updateTime", true, () -> super.updateTime() );
  }
}

Move reportChange to after change occurs


package info.u_team.u_team_test.init;

import info.u_team.u_team_core.item.armor.UArmorMaterialVanilla;
import net.minecraft.item.IArmorMaterial;
import net.minecraft.item.crafting.Ingredient;

public class TestArmorMaterial {

	public static final IArmorMaterial BASIC = new UArmorMaterialVanilla(20, new int[] { 5, 6, 8, 2 }, 20, TestSounds.BETTER_ENDERPEARL_USE, 1, () -> Ingredient.fromItems(TestItems.BASIC.get()));

}

package info.u_team.u_team_test.init;

import info.u_team.u_team_core.item.armor.UArmorMaterialVanilla;
import net.minecraft.item.IArmorMaterial;
import net.minecraft.item.crafting.Ingredient;

public class TestArmorMaterial {

	public static final IArmorMaterial BASIC = new UArmorMaterialVanilla(20, new int[] { 5, 6, 8, 2 }, 20, TestSounds.BETTER_ENDERPEARL_USE, 1, 1, () -> Ingredient.fromItems(TestItems.BASIC.get()));

}

Add knockback resistance parameter to fix the test armor material class


package ${packageName};

public class ${productionClassName} ${extendsAndImplementsClause} {

    public static ${productionClassName} one() { return new ${productionClassName}(); }

    private final String property;
    <% extraFields.each { %>
    ${it.modifier} ${it.type} ${it.name} = ${it.type}.one();
    <% } %>

    public ${productionClassName}(){
        this.property = null;
    }

    public ${productionClassName}(String param) {
        this.property = param;
    }

    public String getProperty() {
        return property;
    }
<% propertyCount.times { %>
    private String prop${it};

    public String getProp${it}() {
        return prop${it};
    }

    public void setProp${it}(String value) {
        prop${it} = value;
    }
<% } %>
}

package ${packageName};

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

public class ${productionClassName} ${extendsAndImplementsClause} {

    public static ${productionClassName} one() { return new ${productionClassName}(); }

    private final String property;
    <% extraFields.each { %>
    ${it.modifier} ${it.type} ${it.name} = ${it.type}.one();

    public boolean check(${it.type} o) {
        // dummy code to add arbitrary compile time
        String p = o.getProperty();
        p = p.toUpperCase();
        List<String> strings = Arrays.asList(p, this.getProperty());
        int len = 0;
        for (String s: strings) {
            len += s.length();
            <% propertyCount.times { %>
            len += o.getProp${it}().length();
            <%}%>
        }
        return len>10;
    }
    <% } %>

    public ${productionClassName}(){
        this.property = null;
    }

    public ${productionClassName}(String param) {
        this.property = param;
    }

    public String getProperty() {
        return property;
    }
<% propertyCount.times { %>
    private String prop${it};

    public String getProp${it}() {
        return prop${it};
    }

    public void setProp${it}(String value) {
        prop${it} = value;
    }
<% } %>
}

Add arbitrary code to make compile time longer
   * the original code was too fast to compile to make compile avoidance relevant
   * the original code didn't represent what we could find in "real" code

+review REVIEW-5688


package org.codehaus.xfire.aegis;

import javax.xml.namespace.QName;

/**
 * Writes messages to an output stream.
 *
 * @author Dan Diephouse
 */
public interface MessageWriter
{
    void writeValue( Object value );

    void writeValueAsInt( Integer i );

    void writeValueAsDouble(Double double1);

    void writeValueAsLong(Long l);

    void writeValueAsFloat(Float f);

    void writeValueAsBoolean(boolean b);

    MessageWriter getAttributeWriter(String name);

    MessageWriter getAttributeWriter(String name, String namespace);

    MessageWriter getAttributeWriter(QName qname);

    MessageWriter getElementWriter(String name);

    MessageWriter getElementWriter(String name, String namespace);

    MessageWriter getElementWriter(QName qname);

    /**
     * Tells the MessageWriter that writing operations are completed so
     * it can write the end element.
     */
    void close();
}

package org.codehaus.xfire.aegis;

import javax.xml.namespace.QName;

/**
 * Writes messages to an output stream.
 *
 * @author Dan Diephouse
 */
public interface MessageWriter
{
    void writeValue( Object value );

    void writeValueAsInt( Integer i );

    void writeValueAsDouble(Double double1);

    void writeValueAsLong(Long l);

    void writeValueAsFloat(Float f);

    void writeValueAsBoolean(boolean b);

    MessageWriter getAttributeWriter(String name);

    MessageWriter getAttributeWriter(String name, String namespace);

    MessageWriter getAttributeWriter(QName qname);

    MessageWriter getElementWriter(String name);

    MessageWriter getElementWriter(String name, String namespace);

    MessageWriter getElementWriter(QName qname);

    String getPrefixForNamespace( String namespace );

    /**
     * Tells the MessageWriter that writing operations are completed so
     * it can write the end element.
     */
    void close();
}

Add ability to get the prefix for a given namespace

git-svn-id: 9326b53cbc4a8f4c3d02979b62b178127d5150fe@889 c7d0bf07-ec0d-0410-b2cc-d48fa9be22ba


package entity;

import org.bukkit.entity.EntityType;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;

import init.InitializePlatform;
import protocolsupport.protocol.types.networkentity.NetworkEntityType;

public class NetworkEntityTypeTests extends InitializePlatform {

	@Test
	protected void testFilled() {
		for (EntityType bukkitType : EntityType.values()) {
			if (bukkitType != EntityType.UNKNOWN) {
				Assertions.assertNotEquals(NetworkEntityType.getByBukkitType(bukkitType), NetworkEntityType.NONE, "NetworkEntityType for Bukkit EntityType " + bukkitType);
			}
		}
	}

}

package entity;

import org.bukkit.entity.EntityType;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;

import init.InitializePlatform;
import protocolsupport.protocol.types.networkentity.NetworkEntityType;

public class NetworkEntityTypeTests extends InitializePlatform {

//	@Test
//	protected void testFilled() {
//		for (EntityType bukkitType : EntityType.values()) {
//			if (bukkitType != EntityType.UNKNOWN) {
//				Assertions.assertNotEquals(NetworkEntityType.getByBukkitType(bukkitType), NetworkEntityType.NONE, "NetworkEntityType for Bukkit EntityType " + bukkitType);
//			}
//		}
//	}

}

Disable test that needs platform init until it is fixed


package com.techcavern.wavetact.commands.Fun;

import com.techcavern.wavetact.objects.Command;
import com.techcavern.wavetact.utils.GeneralRegistry;
import org.apache.commons.lang3.StringUtils;
import org.pircbotx.hooks.events.MessageEvent;

public class Nom extends Command {

    public Nom() {
        super("nom", 0, "nom [something]");
    }

    @Override
    public void onCommand(MessageEvent<?> event, String... args) throws Exception {
        event.getChannel().send().action("noms on " + StringUtils.join(args, " "));
        event.getChannel().send().message("mmhmm");
    }
}

package com.techcavern.wavetact.commands.Fun;

import com.techcavern.wavetact.objects.Command;
import com.techcavern.wavetact.utils.GeneralRegistry;
import org.apache.commons.lang3.StringUtils;
import org.pircbotx.hooks.events.MessageEvent;

public class Nom extends Command {

    public Nom() {
        super("nom", 0, "nom [something]");
    }

    @Override
    public void onCommand(MessageEvent<?> event, String... args) throws Exception {
        if (args.length > 0) {
            event.getChannel().send().action("noms on " + StringUtils.join(args, " "));
        } else {
            event.getChannel().send().action("noms on " + event.getUser().getNick());
        }
        event.getChannel().send().message("mmhmm");
    }
}

Add a fun "easter egg"

Add a fun "easter egg"