/*
 * Copyright 2009-2010 by The Regents of the University of California
 * 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 from
 *
 *     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 edu.uci.ics.asterix.aql.translator;

import edu.uci.ics.asterix.aql.base.Statement;
import edu.uci.ics.asterix.aql.expression.Query;

public class QueryResult {

    private final Query query;
    private final String resultPath;

    public QueryResult(Query statement, String resultPath) {
        this.query = statement;
        this.resultPath = resultPath;
    }

    public Statement getStatement() {
        return query;
    }

    public String getResultPath() {
        return resultPath;
    }

}

/*
 * Copyright 2009-2010 by The Regents of the University of California
 * 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 from
 *
 *     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 edu.uci.ics.asterix.aql.translator;

import edu.uci.ics.asterix.aql.base.Statement;
import edu.uci.ics.asterix.aql.expression.Query;
import edu.uci.ics.hyracks.api.dataset.ResultSetId;
import edu.uci.ics.hyracks.api.job.JobId;

public class QueryResult {

    private final Query query;

    private final ResultSetId resultSetId;

    private JobId jobId;

    public QueryResult(Query statement, ResultSetId resultSetId) {
        this.query = statement;
        this.resultSetId = resultSetId;
    }

    public void setJobId(JobId jobId) {
        this.jobId = jobId;
    }

    public JobId getJobId() {
        return jobId;
    }

    public Statement getStatement() {
        return query;
    }

    public ResultSetId getResultId() {
        return resultSetId;
    }

}

Store and implement the necessary data and methods for storing information about the job and result set id.

git-svn-id: d02d9bbead102d27982d5b07d77674fa86f521a4@1142 eaa15691-b419-025a-1212-ee371bd00084


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

package io.material.catalog.application;

import android.app.Application;
import dagger.BindsInstance;
import dagger.android.support.AndroidSupportInjectionModule;
import io.material.catalog.application.scope.ApplicationScope;
import io.material.catalog.main.MainActivity;

/** The Application's root component. */
@ApplicationScope
@dagger.Component(
  modules = {
    AndroidSupportInjectionModule.class,
    MainActivity.Module.class,
  }
)
public interface CatalogApplicationComponent {
  void inject(CatalogApplication app);

  /** The root component's builder. */
  @dagger.Component.Builder
  interface Builder {
    @BindsInstance
    CatalogApplicationComponent.Builder application(Application application);

    CatalogApplicationComponent build();
  }
}

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

package io.material.catalog.application;

import android.app.Application;
import dagger.BindsInstance;
import dagger.android.AndroidInjectionModule;
import io.material.catalog.application.scope.ApplicationScope;
import io.material.catalog.main.MainActivity;

/** The Application's root component. */
@ApplicationScope
@dagger.Component(
    modules = {
      AndroidInjectionModule.class,
      MainActivity.Module.class,
    })
public interface CatalogApplicationComponent {
  void inject(CatalogApplication app);

  /** The root component's builder. */
  @dagger.Component.Builder
  interface Builder {
    @BindsInstance
    CatalogApplicationComponent.Builder application(Application application);

    CatalogApplicationComponent build();
  }
}

Migrate from AndroidSupportInjectionModule to AndroidInjectionModule.

PiperOrigin-RevId: 220291186


package org.nanopub;

import java.io.IOException;
import java.io.OutputStream;
import java.io.Writer;

import org.openrdf.model.URI;
import org.openrdf.rio.trig.TriGWriter;

/**
 * @author Tobias Kuhn
 */
public class CustomTrigWriter extends TriGWriter {

	public CustomTrigWriter(OutputStream out) {
		super(out);
	}

	public CustomTrigWriter(Writer writer) {
		super(writer);
	}

	protected void writeURI(URI uri) throws IOException {
		String prefix = namespaceTable.get(uri.toString());
		if (prefix != null) {
			writer.write(prefix);
			writer.write(":");
		} else {
			super.writeURI(uri);
		}
	}

}

package org.nanopub;

import java.io.IOException;
import java.io.OutputStream;
import java.io.Writer;

import org.openrdf.model.URI;
import org.openrdf.rio.trig.TriGWriter;
import org.openrdf.rio.turtle.TurtleUtil;

/**
 * @author Tobias Kuhn
 */
public class CustomTrigWriter extends TriGWriter {

	public CustomTrigWriter(OutputStream out) {
		super(out);
	}

	public CustomTrigWriter(Writer writer) {
		super(writer);
	}

	@Override
	protected void writeURI(URI uri) throws IOException {
		String uriString = uri.toString();

		String prefix = namespaceTable.get(uriString);
		if (prefix != null) {
			// Exact match: no suffix required
			writer.write(prefix);
			writer.write(":");
			return;
		}

		prefix = null;

		int splitIdxNorm = TurtleUtil.findURISplitIndex(uriString);
		// Do also split at dots:
		int splitIdxDot = uriString.lastIndexOf(".") + 1;
		if (uriString.length() == splitIdxDot) splitIdxDot = -1;
		int splitIdx = Math.max(splitIdxNorm, splitIdxDot);
		if (splitIdx > 0) {
			String namespace = uriString.substring(0, splitIdx);
			prefix = namespaceTable.get(namespace);
		}

		if (prefix != null) {
			// Namespace is mapped to a prefix; write abbreviated URI
			writer.write(prefix);
			writer.write(":");
			writer.write(uriString.substring(splitIdx));
		} else {
			// Write full URI
			writer.write("<");
			writer.write(TurtleUtil.encodeURIString(uriString));
			writer.write(">");
		}
	}

}

Make sure prefixes are split at '.' when writing TriG


/*
 * JBoss, Home of Professional Open Source.
 * Copyright 2009, Red Hat Middleware LLC, and individual contributors
 * as indicated by the @author tags. See the copyright.txt file in the
 * distribution for a full listing of individual contributors.
 *
 * This is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License as
 * published by the Free Software Foundation; either version 2.1 of
 * the License, or (at your option) any later version.
 *
 * This software is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this software; if not, write to the Free
 * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
 * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
 */

package org.jboss.threads;

import java.util.concurrent.RejectedExecutionException;

class RejectingExecutor implements DirectExecutor {
    static final RejectingExecutor INSTANCE = new RejectingExecutor();

    private RejectingExecutor() {
    }

    public void execute(final Runnable command) {
        throw new RejectedExecutionException();
    }

    public String toString() {
        return "Rejecting executor";
    }
}

/*
 * JBoss, Home of Professional Open Source.
 * Copyright 2009, Red Hat Middleware LLC, and individual contributors
 * as indicated by the @author tags. See the copyright.txt file in the
 * distribution for a full listing of individual contributors.
 *
 * This is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License as
 * published by the Free Software Foundation; either version 2.1 of
 * the License, or (at your option) any later version.
 *
 * This software is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this software; if not, write to the Free
 * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
 * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
 */

package org.jboss.threads;

import java.util.concurrent.RejectedExecutionException;

class RejectingExecutor implements DirectExecutor {
    static final RejectingExecutor INSTANCE = new RejectingExecutor();

    private final String message;

    private RejectingExecutor() {
        message = null;
    }

    RejectingExecutor(final String message) {
        this.message = message;
    }

    public void execute(final Runnable command) {
        throw new RejectedExecutionException(message);
    }

    public String toString() {
        return "Rejecting executor";
    }
}

Allow rejecting executor to have a fixed message

git-svn-id: 56d4294a9e7c8b1ae21491ba4491dfc41c8d890d@92151 84be2c1e-ba19-0410-b317-a758671a6fc1


package com.github.arteam.jdbi3;

import com.codahale.metrics.annotation.Timed;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import org.jdbi.v3.sqlobject.customizer.Bind;
import org.jdbi.v3.sqlobject.statement.SqlQuery;
import org.jdbi.v3.stringtemplate4.UseStringTemplateSqlLocator;

import java.time.LocalDate;
import java.util.Optional;

@UseStringTemplateSqlLocator
public interface GameDao {

    @SqlQuery
    ImmutableList<Integer> findGameIds();

    @SqlQuery
    ImmutableSet<String> findAllUniqueHomeTeams();

    @SqlQuery
    Optional<Integer> findIdByTeamsAndDate(@Bind("home_team") String homeTeam,
                                           @Bind("visitor_team") String visitorTeam,
                                           @Bind("played_at") LocalDate date);

    @SqlQuery
    LocalDate getFirstPlayedSince(@Bind("up") LocalDate up);

    @SqlQuery
    @Timed(name = "get-last-played")
    Optional<LocalDate> getLastPlayedDateByTeams(@Bind("home_team") String homeTeam,
                                                 @Bind("visitor_team") String visitorTeam);

    @SqlQuery
    Optional<String> findHomeTeamByGameId(@Bind("id") Optional<Integer> id);
}

package com.github.arteam.jdbi3;

import com.codahale.metrics.annotation.Timed;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import org.jdbi.v3.sqlobject.customizer.Bind;
import org.jdbi.v3.sqlobject.statement.SqlQuery;
import org.jdbi.v3.stringtemplate4.UseStringTemplateSqlLocator;

import java.time.LocalDate;
import java.util.Optional;

@UseStringTemplateSqlLocator
@Timed(name = "game-dao")
public interface GameDao {

    @SqlQuery
    ImmutableList<Integer> findGameIds();

    @SqlQuery
    ImmutableSet<String> findAllUniqueHomeTeams();

    @SqlQuery
    Optional<Integer> findIdByTeamsAndDate(@Bind("home_team") String homeTeam,
                                           @Bind("visitor_team") String visitorTeam,
                                           @Bind("played_at") LocalDate date);

    @SqlQuery
    LocalDate getFirstPlayedSince(@Bind("up") LocalDate up);

    @SqlQuery
    @Timed(name = "last-played-date")
    Optional<LocalDate> getLastPlayedDateByTeams(@Bind("home_team") String homeTeam,
                                                 @Bind("visitor_team") String visitorTeam);

    @SqlQuery
    Optional<String> findHomeTeamByGameId(@Bind("id") Optional<Integer> id);
}

Use the `@Timed` annotation on SQLObjects

Looks more reasonable to me this way instead logging everything by default.


/*
 * Copyright 2019, TeamDev. All rights reserved.
 *
 * Redistribution and use in source and/or binary forms, with or without
 * modification, must retain the above copyright notice and the following
 * disclaimer.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */
package io.spine.server.transport.memory;

import io.grpc.Internal;
import io.spine.server.transport.ChannelId;
import io.spine.server.transport.Subscriber;

/**
 * An in-memory implementation of the {@link Subscriber}.
 *
 * <p>To use only in scope of the same JVM as {@linkplain InMemoryPublisher publishers}.
 */
@Internal
public class InMemorySubscriber extends Subscriber {

    public InMemorySubscriber(ChannelId id) {
        super(id);
    }
}

/*
 * Copyright 2019, TeamDev. All rights reserved.
 *
 * Redistribution and use in source and/or binary forms, with or without
 * modification, must retain the above copyright notice and the following
 * disclaimer.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */
package io.spine.server.transport.memory;

import io.spine.server.transport.ChannelId;
import io.spine.server.transport.Subscriber;

/**
 * An in-memory implementation of the {@link Subscriber}.
 *
 * <p>To use only in scope of the same JVM as {@linkplain InMemoryPublisher publishers}.
 */

class InMemorySubscriber extends Subscriber {

    InMemorySubscriber(ChannelId id) {
        super(id);
    }
}

Reduce visibility where `public` is not required


package com.redhat.victims;

public class Resources {
	public static final String JAR_FILE = "testdata/junit-4.11/junit-4.11.jar";
	public static final String JAR_SHA1 = JAR_FILE + ".sha1";
	public static final String JAR_JSON = JAR_FILE + ".json";

	public static final String POM_FILE = "testdata/junit-4.11/junit-4.11.pom";
	public static final String POM_SHA1 = POM_FILE + ".sha1";
	public static final String POM_JSON = POM_FILE + ".json";

	public static final String RECORD_CLIENT_JAR = "testdata/records/victims-client-1.0-SNAPSHOT.jar.json";

	public static final String TEST_RESPONSE = "testdata/service/test.response";
	public static final String TEST_SHA512 = "testdata/service/test.sha512";
	public static final String TEST_CVE = "testdata/service/test.cve";

}

package com.redhat.victims;

public class Resources {
	public static final String JAR_FILE = "testdata/junit-4.11/junit-4.11.jar";
	public static final String JAR_SHA1 = JAR_FILE + ".sha1";
	public static final String JAR_JSON = JAR_FILE + ".json";

	public static final String POM_FILE = "testdata/junit-4.11/junit-4.11.pom";
	public static final String POM_SHA1 = POM_FILE + ".sha1";
	public static final String POM_JSON = POM_FILE + ".json";

	public static final String RECORD_CLIENT_JAR = "testdata/records/victims-client.jar.json";

	public static final String TEST_RESPONSE = "testdata/service/test.response";
	public static final String TEST_SHA512 = "testdata/service/test.sha512";
	public static final String TEST_CVE = "testdata/service/test.cve";

}

Fix typo in resource file path

Fix typo in resource file path


package com.vaadin.demo.featurebrowser;

import com.vaadin.ui.Accordion;
import com.vaadin.ui.CustomComponent;
import com.vaadin.ui.Label;
import com.vaadin.ui.TextField;
import com.vaadin.ui.VerticalLayout;

/**
 * Accordion is a derivative of TabSheet, a vertical tabbed layout that places
 * the tab contents between the vertical tabs.
 */
@SuppressWarnings("serial")
public class AccordionExample extends CustomComponent {
    public AccordionExample() {
        // Create a new accordion
        final Accordion accordion = new Accordion();
        setCompositionRoot(accordion);

        // Add a few tabs to the accordion.
        for (int i = 0; i < 5; i++) {
            // Create a root component for a accordion tab
            VerticalLayout layout = new VerticalLayout();
            accordion.addComponent(layout);

            // The accordion tab label is taken from the caption of the root
            // component. Notice that layouts can have a caption too.
            layout.setCaption("Tab " + (i + 1));

            // Add some components in each accordion tab
            Label label = new Label("These are the contents of Tab " + (i + 1)
                    + ".");
            layout.addComponent(label);

            TextField textfield = new TextField("Some text field");
            layout.addComponent(textfield);
        }
    }
}

package com.vaadin.demo.featurebrowser;

import com.vaadin.ui.Accordion;
import com.vaadin.ui.CustomComponent;
import com.vaadin.ui.Label;
import com.vaadin.ui.TextField;
import com.vaadin.ui.VerticalLayout;

/**
 * Accordion is a derivative of TabSheet, a vertical tabbed layout that places
 * the tab contents between the vertical tabs.
 */
@SuppressWarnings("serial")
public class AccordionExample extends CustomComponent {
    public AccordionExample() {
        // Create a new accordion
        final Accordion accordion = new Accordion();
        setCompositionRoot(accordion);

        // Add a few tabs to the accordion.
        for (int i = 0; i < 5; i++) {
            // Create a root component for a accordion tab
            VerticalLayout layout = new VerticalLayout();
            // The accordion tab label is taken from the caption of the root
            // component. Notice that layouts can have a caption too.
            layout.setCaption("Tab " + (i + 1));

            accordion.addComponent(layout);

            // Add some components in each accordion tab
            Label label = new Label("These are the contents of Tab " + (i + 1)
                    + ".");
            layout.addComponent(label);

            TextField textfield = new TextField("Some text field");
            layout.addComponent(textfield);
        }
    }
}

Fix FeatureBrowser Accordion example tab captions

svn changeset:8011/svn branch:6.0


package tars.commons.core;

/**
 * Container for user visible messages.
 */
public class Messages {

    public static final String MESSAGE_UNKNOWN_COMMAND = "Unknown command";
    public static final String MESSAGE_INVALID_COMMAND_FORMAT = "Invalid command format! \n%1$s";
    public static final String MESSAGE_INVALID_PERSON_DISPLAYED_INDEX = "The task index provided is invalid";
    public static final String MESSAGE_PERSONS_LISTED_OVERVIEW = "%1$d tasks listed!";

}

package tars.commons.core;

/**
 * Container for user visible messages.
 */
public class Messages {

    public static final String MESSAGE_UNKNOWN_COMMAND = "Unknown command";
    public static final String MESSAGE_INVALID_COMMAND_FORMAT = "Invalid command format! \n%1$s";
    public static final String MESSAGE_INVALID_DATE = "Invalid date";
    public static final String MESSAGE_INVALID_PERSON_DISPLAYED_INDEX = "The task index provided is invalid";
    public static final String MESSAGE_PERSONS_LISTED_OVERVIEW = "%1$d tasks listed!";

}

Add new message for invalid date

Add new message for invalid date


package thredds.catalog2;

import thredds.catalog.ServiceType;

import java.util.List;

/**
 * _more_
 *
 * @author edavis
 * @since 4.0
 */
public interface Dataset extends MetadataContainer
{
  public String getName();
  public String getId();
  public String getAlias();
  public List<Access> getAccesses();
  public Access getAccess( ServiceType type );
  public List<Dataset> getDatasets();
}

package thredds.catalog2;

import thredds.catalog.ServiceType;

import java.util.List;

/**
 * _more_
 *
 * @author edavis
 * @since 4.0
 */
public interface Dataset extends MetadataContainer
{
  public String getName();
  public String getId();
  public String getAlias();

  public boolean isAccessible();
  public List<Access> getAccesses();
  public Access getAccess( ServiceType type );

  public boolean isCollection();
  public List<Dataset> getDatasets();

  public Catalog getParentCatalog();
  public Dataset getParent();
}

Work on refactoring the thredds.catalog package.


package pro.cucumber;

import org.junit.Before;
import org.junit.Test;
import pro.cucumber.gitcli.GitCliRevisionProvider;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.regex.Pattern;

import static org.junit.Assert.assertTrue;

public abstract class RevisionProviderContract {
    private Path rootPath;

    @Before
    public void createScm() throws IOException {
        rootPath = Files.createTempDirectory("GitWC");
        Path subfolder = rootPath.resolve("subfolder");
        Files.createDirectory(subfolder);
        Files.createFile(subfolder.resolve("file"));
        Exec.cmd("git init", rootPath);
        Exec.cmd("git add -A", rootPath);
        Exec.cmd("git commit -am \"files\"", rootPath);
    }

    @Test
    public void findsRev() {
        String sha1Pattern = "^[a-f0-9]{40}$";
        RevisionProvider revisionProvider = makeRevisionProvider(rootPath);
        assertTrue("Expected a sha1", Pattern.matches(sha1Pattern, revisionProvider.getRev()));
    }

    protected abstract RevisionProvider makeRevisionProvider(Path rootPath);

}

package pro.cucumber;

import org.junit.Before;
import org.junit.Test;
import pro.cucumber.gitcli.GitCliRevisionProvider;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.regex.Pattern;

import static org.junit.Assert.assertTrue;

public abstract class RevisionProviderContract {
    private Path rootPath;

    @Before
    public void createScm() throws IOException {
        rootPath = Files.createTempDirectory("GitWC");
        Path subfolder = rootPath.resolve("subfolder");
        Files.createDirectory(subfolder);
        Files.createFile(subfolder.resolve("file"));
        Exec.cmd("git init", rootPath);
        Exec.cmd("git add -A", rootPath);
        Exec.cmd("git commit -am \"files\"", rootPath);
        System.out.println(Exec.cmd("ls -al", rootPath));
    }

    @Test
    public void findsRev() {
        String sha1Pattern = "^[a-f0-9]{40}$";
        RevisionProvider revisionProvider = makeRevisionProvider(rootPath);
        assertTrue("Expected a sha1", Pattern.matches(sha1Pattern, revisionProvider.getRev()));
    }

    protected abstract RevisionProvider makeRevisionProvider(Path rootPath);

}

Add some debugging for circle

Add some debugging for circle


package com.hubspot.jinjava.objects.serialization;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectWriter;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.hubspot.jinjava.util.WhitespaceUtils;
import java.util.Objects;

public class PyishObjectMapper {
  private static final ObjectWriter PYISH_OBJECT_WRITER = new ObjectMapper()
    .registerModule(
      new SimpleModule()
        .setSerializerModifier(PyishBeanSerializerModifier.INSTANCE)
        .addSerializer(PyishSerializable.class, PyishSerializer.INSTANCE)
    )
    .writer(PyishPrettyPrinter.INSTANCE)
    .with(PyishCharacterEscapes.INSTANCE);

  public static String getAsUnquotedPyishString(Object val) {
    if (val != null) {
      return WhitespaceUtils.unquoteAndUnescape(getAsPyishString(val));
    }
    return "";
  }

  public static String getAsPyishString(Object val) {
    try {
      return PYISH_OBJECT_WRITER
        .writeValueAsString(val)
        .replace("'", "\\'")
        // Replace double-quotes with single quote as they are preferred in Jinja
        .replaceAll("(?<!\\\\)(\\\\\\\\)*(?:\")", "$1'");
    } catch (JsonProcessingException e) {
      return Objects.toString(val, "");
    }
  }
}

package com.hubspot.jinjava.objects.serialization;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectWriter;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.hubspot.jinjava.util.WhitespaceUtils;
import java.util.Objects;

public class PyishObjectMapper {
  public static final ObjectWriter PYISH_OBJECT_WRITER = new ObjectMapper()
    .registerModule(
      new SimpleModule()
        .setSerializerModifier(PyishBeanSerializerModifier.INSTANCE)
        .addSerializer(PyishSerializable.class, PyishSerializer.INSTANCE)
    )
    .writer(PyishPrettyPrinter.INSTANCE)
    .with(PyishCharacterEscapes.INSTANCE);

  public static String getAsUnquotedPyishString(Object val) {
    if (val != null) {
      return WhitespaceUtils.unquoteAndUnescape(getAsPyishString(val));
    }
    return "";
  }

  public static String getAsPyishString(Object val) {
    try {
      return PYISH_OBJECT_WRITER
        .writeValueAsString(val)
        .replace("'", "\\'")
        // Replace double-quotes with single quote as they are preferred in Jinja
        .replaceAll("(?<!\\\\)(\\\\\\\\)*(?:\")", "$1'");
    } catch (JsonProcessingException e) {
      return Objects.toString(val, "");
    }
  }
}

Make static PYISH_OBJECT_WRITER public so it can be used in PyishSerializable overrides


package org.cytoscape.commandDialog.internal.tasks;

import org.cytoscape.work.AbstractTask;
import org.cytoscape.work.ProvidesTitle;
import org.cytoscape.work.TaskMonitor;
import org.cytoscape.work.Tunable;

public class SleepCommandTask extends AbstractEmptyObservableTask {

	@ProvidesTitle
	public String getTitle() { return "Sleeping..."; }

	@Tunable(description="Duration of sleep in seconds")
	public double duration;

	public SleepCommandTask() {
		super();
	}

	@Override
	public void run(TaskMonitor arg0) throws Exception {
		if (duration != 0d) {
			arg0.showMessage(TaskMonitor.Level.INFO, "Sleeping for "+duration+" seconds");
			Thread.sleep((long)duration*1000);
			arg0.showMessage(TaskMonitor.Level.INFO, "Slept for "+duration+" seconds");
		}

	}
}

package org.cytoscape.commandDialog.internal.tasks;

import org.cytoscape.work.AbstractTask;
import org.cytoscape.work.ProvidesTitle;
import org.cytoscape.work.TaskMonitor;
import org.cytoscape.work.Tunable;

public class SleepCommandTask extends AbstractEmptyObservableTask {

	@ProvidesTitle
	public String getTitle() { return "Sleeping..."; }

	@Tunable(description="Duration of sleep in seconds",
	         longDescription="Enter the time in seconds to sleep",
	         exampleStringValue="5")
	public double duration;

	public SleepCommandTask() {
		super();
	}

	@Override
	public void run(TaskMonitor arg0) throws Exception {
		if (duration != 0d) {
			arg0.showMessage(TaskMonitor.Level.INFO, "Sleeping for "+duration+" seconds");
			Thread.sleep((long)duration*1000);
			arg0.showMessage(TaskMonitor.Level.INFO, "Slept for "+duration+" seconds");
		}

	}
}

Add longDescription and exampleStringValue to sleep


package com.allforfunmc.easyoreapi;

import cpw.mods.fml.common.IWorldGenerator;
import cpw.mods.fml.common.Mod;
import cpw.mods.fml.common.Mod.EventHandler;
import cpw.mods.fml.common.Mod.Instance;
import cpw.mods.fml.common.SidedProxy;
import cpw.mods.fml.common.event.FMLInitializationEvent;
import cpw.mods.fml.common.registry.GameRegistry;

@Mod (modid="oreapi", name="AllForFun's EasyOreAPI", version="Dev")
public class EasyOreApi {
	@Instance (value="GenericModID")
	public static EasyOreApi instance;
	@SidedProxy(clientSide="com.allforfunmc.easyoreapi.ClientProxy",serverSide="com.allforfunmc.easyoreapi.CommonProxy")
	public static CommonProxy proxy;
	@EventHandler()
	public void load(FMLInitializationEvent event) {
		proxy.registerRenderers();
	}
	@EventHandler()
	public void Init(FMLInitializationEvent event) {

	}
	@EventHandler()
	public void postInit(FMLInitializationEvent event){
		IWorldGenerator generator = new Generator();
		GameRegistry.registerWorldGenerator(generator, 21);
	}
}

package com.allforfunmc.easyoreapi;

import cpw.mods.fml.common.Mod;
import cpw.mods.fml.common.Mod.EventHandler;
import cpw.mods.fml.common.Mod.Instance;
import cpw.mods.fml.common.SidedProxy;
import cpw.mods.fml.common.event.FMLInitializationEvent;

@Mod (modid="oreapi", name="AllForFun's EasyOreAPI", version="Dev")
public class EasyOreApi {
	@Instance (value="GenericModID")
	public static EasyOreApi instance;
	@SidedProxy(clientSide="com.allforfunmc.easyoreapi.ClientProxy",serverSide="com.allforfunmc.easyoreapi.CommonProxy")
	public static CommonProxy proxy;
	@EventHandler()
	public void load(FMLInitializationEvent event) {
		proxy.registerRenderers();
	}
	@EventHandler()
	public void Init(FMLInitializationEvent event) {

	}
	@EventHandler()
	public void postInit(FMLInitializationEvent event){

	}
}

Revert "Updated What Im Working On File"

This reverts commit 51a8e6d27f762fa131da4ad94b8bdf409409f6c6, reversing
changes made to 40cc2cc801557622af48530c37c15a25403e44a2.


package liquibase.integration.ant;

import liquibase.resource.FileSystemResourceAccessor;
import liquibase.util.StringUtil;
import org.apache.tools.ant.AntClassLoader;

import java.io.File;

public class AntResourceAccessor extends FileSystemResourceAccessor {

    public AntResourceAccessor(AntClassLoader classLoader, String changeLogDirectory) {

        if (changeLogDirectory == null) {
            this.addRootPath(new File(".").getAbsoluteFile().toPath());
        } else {
            this.addRootPath(new File(changeLogDirectory).getAbsoluteFile().toPath());
        }

        final String classpath = StringUtil.trimToNull(classLoader.getClasspath());
        if (classpath != null) {
            for (String path : classpath.split(System.getProperty("path.separator"))) {
                this.addRootPath(new File(path).toPath());
            }
        }
    }

}

package liquibase.integration.ant;

import liquibase.resource.FileSystemResourceAccessor;
import liquibase.util.StringUtil;
import org.apache.tools.ant.AntClassLoader;

import java.io.File;

public class AntResourceAccessor extends FileSystemResourceAccessor {

    public AntResourceAccessor(AntClassLoader classLoader, String changeLogDirectory) {

        if (changeLogDirectory != null) {
            changeLogDirectory = changeLogDirectory.replace("\\", "/");
        }

        if (changeLogDirectory == null) {
            this.addRootPath(new File("").getAbsoluteFile().toPath());
            this.addRootPath(new File("/").getAbsoluteFile().toPath());
        } else {
            this.addRootPath(new File(changeLogDirectory).getAbsoluteFile().toPath());
        }

        final String classpath = StringUtil.trimToNull(classLoader.getClasspath());
        if (classpath != null) {
            for (String path : classpath.split(System.getProperty("path.separator"))) {
                this.addRootPath(new File(path).toPath());
            }
        }
    }

}

Handle path separator differences in AntLoader DAT-4036


package data;

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

import javax.enterprise.context.SessionScoped;
import javax.enterprise.inject.Default;
import javax.inject.Named;

import org.apache.deltaspike.data.api.EntityRepository;
import org.apache.deltaspike.data.api.Query;
import org.apache.deltaspike.data.api.Repository;

import com.darwinsys.todo.model.Task;

/**
 * This is a basic DAO-like interface for use by JSF or EJB.
 * Methods are implemented for us by Apache DeltaSpike Data.
 * The methods in the inherited interface suffice for many apps!
 * @author Ian Darwin
 */
@Named("todoList") @Default
@SessionScoped
@Repository
public interface TodoList extends Serializable, EntityRepository<Task, Long> {

	// The ordering of Priority is 0=Top..3=Lowest, so sort by prio asc is correct here
	@Query(value="select t from Task t where t.status < 3 order by t.priority asc, t.name asc")
	List<Task> findAll();
}

package data;

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

import javax.enterprise.context.SessionScoped;
import javax.enterprise.inject.Default;
import javax.inject.Named;

import org.apache.deltaspike.data.api.EntityRepository;
import org.apache.deltaspike.data.api.Query;
import org.apache.deltaspike.data.api.Repository;

import com.darwinsys.todo.model.Task;

/**
 * This is a basic DAO-like interface for use by JSF or EJB.
 * Methods are implemented for us by Apache DeltaSpike Data.
 * The methods in the inherited interface suffice for many apps!
 * @author Ian Darwin
 */
@Named("todoList") @Default
@SessionScoped
@Repository
public interface TodoList extends Serializable, EntityRepository<Task, Long> {

	// The ordering of Priority is 0=Top..3=Lowest, so sort by prio asc is correct here
	@Query(value="select t from Task t where t.status < 3 order by t.priority asc, lower(t.name) asc")
	List<Task> findAll();
}

Order by prio then lower(name)

Order by prio then lower(name)


import org.junit.Test;

import static org.junit.Assert.assertEquals;

public class AcronymTest {

    @Test
    public void fromTitleCasedPhrases() {
        final String phrase = "Portable Network Graphics";
        final String expected = "PNG";
        assertEquals(expected, Acronym.generate(phrase));
    }

    @Test
    public void fromOtherTitleCasedPhrases() {
        final String phrase = "Ruby on Rails";
        final String expected = "ROR";
        assertEquals(expected, Acronym.generate(phrase));
    }

    @Test
    public void fromInconsistentlyCasedPhrases() {
        final String phrase = "HyperText Markup Language";
        final String expected = "HTML";
        assertEquals(expected, Acronym.generate(phrase));
    }

    @Test
    public void fromPhrasesWithPunctuation() {
        final String phrase = "First In, First Out";
        final String expected = "FIFO";
        assertEquals(expected, Acronym.generate(phrase));
    }

    @Test
    public void fromOtherPhrasesWithPunctuation() {
        final String phrase = "PHP: Hypertext Preprocessor";
        final String expected = "PHP";
        assertEquals(expected, Acronym.generate(phrase));
    }

    @Test
    public void fromPhrasesWithPunctuationAndSentenceCasing() {
        final String phrase = "Complementary metal-oxide semiconductor";
        final String expected = "CMOS";
        assertEquals(expected, Acronym.generate(phrase));
    }

}

import org.junit.Test;

import static org.junit.Assert.assertEquals;

public class AcronymTest {

    @Test
    public void fromTitleCasedPhrases() {
        final String phrase = "Portable Network Graphics";
        final String expected = "PNG";
        assertEquals(expected, Acronym.generate(phrase));
    }

    @Test
    public void fromOtherTitleCasedPhrases() {
        final String phrase = "Ruby on Rails";
        final String expected = "ROR";
        assertEquals(expected, Acronym.generate(phrase));
    }

    @Test
    public void fromInconsistentlyCasedPhrases() {
        final String phrase = "HyperText Markup Language";
        final String expected = "HTML";
        assertEquals(expected, Acronym.generate(phrase));
    }

    @Test
    public void fromPhrasesWithPunctuation() {
        final String phrase = "First In, First Out";
        final String expected = "FIFO";
        assertEquals(expected, Acronym.generate(phrase));
    }

    @Test
    public void fromOtherPhrasesWithPunctuation() {
        final String phrase = "PHP: Hypertext Preprocessor";
        final String expected = "PHP";
        assertEquals(expected, Acronym.generate(phrase));
    }

    @Test
    public void fromPhrasesWithPunctuationAndSentenceCasing() {
        final String phrase = "Complementary metal-oxide semiconductor";
        final String expected = "CMOS";
        assertEquals(expected, Acronym.generate(phrase));
    }

    @Test
    public void fromPhraseWithSingleLetterWord() {
        final String phrase = "Cat in a Hat";
        final String expected = "CIAH";
        assertEquals(expected, Acronym.generate(phrase));
    }

}

Add testcase to Acronym test for single letter word


package net.simpvp.NoSpam;

import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerCommandPreprocessEvent;

public class CommandListener implements Listener {

	public CommandListener(NoSpam plugin) {
		plugin.getServer().getPluginManager().registerEvents(this, plugin);
	}

	@EventHandler(priority=EventPriority.LOW, ignoreCancelled=false)
	public void onPlayerCommandPreprocessEvent(PlayerCommandPreprocessEvent event) {

		Player player = event.getPlayer();

		String message = event.getMessage().toLowerCase();

		/* Important: The spaces afterwards are necessary. Otherwise we get something like this being activated on /world because of /w */
		if (message.startsWith("/tell ")
				|| message.startsWith("/me ")
				|| message.startsWith("/msg ")
				|| message.startsWith("/w ")
				|| message.startsWith("/op ")
				|| message.equals("/op")) {

			boolean cancel = SpamHandler.isSpamming(player); // The Handler class checks if it's spam

			if ( cancel ) event.setCancelled(true);

		}

	}

}

package net.simpvp.NoSpam;

import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerCommandPreprocessEvent;

public class CommandListener implements Listener {

	public CommandListener(NoSpam plugin) {
		plugin.getServer().getPluginManager().registerEvents(this, plugin);
	}

	@EventHandler(priority=EventPriority.LOW, ignoreCancelled=false)
	public void onPlayerCommandPreprocessEvent(PlayerCommandPreprocessEvent event) {

		Player player = event.getPlayer();

		String message = event.getMessage().toLowerCase();

		/* Important: The spaces afterwards are necessary. Otherwise we get something like this being activated on /world because of /w */
		if (message.startsWith("/tell ")
				|| message.startsWith("/me ")
				|| message.startsWith("/msg ")
				|| message.startsWith("/w ")
				|| message.startsWith("/op ")
				|| message.startsWith("/r ")
				|| message.startsWith("/m ")
				|| message.equals("/op")) {

			boolean cancel = SpamHandler.isSpamming(player); // The Handler class checks if it's spam

			if ( cancel ) event.setCancelled(true);

		}

	}

}

Add /r and /m to muted commands

Add /r and /m to muted commands


package integration;

import hello.Application;
import org.fluentlenium.adapter.FluentTest;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.phantomjs.PhantomJSDriver;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.test.*;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

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

@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = Application.class)
@WebIntegrationTest("server.port:0")
public class GreetingTest extends FluentTest {
    @Value("${local.server.port}")
    private int port;

    private DesiredCapabilities capabilities = DesiredCapabilities.phantomjs();
    private WebDriver driver = new PhantomJSDriver(capabilities);

    @Override
    public WebDriver getDefaultDriver() {
        return driver;
    }

    @Test
    public void testGetIndex() {
        goTo("http://127.0.0.1:" + port + "/greeting?name=Sam");
        assertThat(pageSource()).contains("Hello, Sam!");

        goTo("http://127.0.0.1:" + port + "/greeting?name=Bob");
        assertThat(pageSource()).contains("Hello, Bob!");
    }
}

package integration;

import hello.Application;
import org.fluentlenium.adapter.FluentTest;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.phantomjs.PhantomJSDriver;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.test.*;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

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

@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = Application.class)
@WebIntegrationTest("server.port:0")
public class GreetingTest extends FluentTest {
    @Value("${local.server.port}")
    private int port;

    private DesiredCapabilities capabilities = DesiredCapabilities.phantomjs();
    private WebDriver driver = new PhantomJSDriver(capabilities);

    @Override
    public WebDriver getDefaultDriver() {
        return driver;
    }

    @Test
    public void testThymeleaf() {
        goTo("http://127.0.0.1:" + port + "/greeting?name=Sam");
        assertThat(pageSource()).contains("Hello, Sam!");

        goTo("http://127.0.0.1:" + port + "/greeting?name=Bob");
        assertThat(pageSource()).contains("Hello, Bob!");
    }

    @Test
    public void testJavascript() throws InterruptedException {
        goTo("http://127.0.0.1:" + port + "/greeting?name=Sam");
        Thread.sleep(1000); // There's probably a better way to wait for $(document).ready
        assertThat(pageSource()).contains("Hello from javascript!");
    }
}

Test confirming spring boot test runner loads external JARs


package com.github.mobile.android.core.repo;

import static org.eclipse.egit.github.core.event.Event.TYPE_FORK;

import org.eclipse.egit.github.core.Repository;
import org.eclipse.egit.github.core.event.Event;
import org.eclipse.egit.github.core.event.EventPayload;
import org.eclipse.egit.github.core.event.ForkPayload;

/**
 * Helper to find a {@link RepositoryEventMatcher} to open for an event
 */
public class RepositoryEventMatcher {

    /**
     * Get {@link Repository} from event
     *
     * @param event
     * @return gist or null if event doesn't apply
     */
    public Repository getRepository(final Event event) {
        if (event == null)
            return null;
        EventPayload payload = event.getPayload();
        if (payload == null)
            return null;
        String type = event.getType();
        if (TYPE_FORK.equals(type))
            return ((ForkPayload) payload).getForkee();
        else
            return null;
    }
}

package com.github.mobile.android.core.repo;

import static org.eclipse.egit.github.core.event.Event.TYPE_CREATE;
import static org.eclipse.egit.github.core.event.Event.TYPE_FORK;

import org.eclipse.egit.github.core.Repository;
import org.eclipse.egit.github.core.User;
import org.eclipse.egit.github.core.event.Event;
import org.eclipse.egit.github.core.event.EventPayload;
import org.eclipse.egit.github.core.event.EventRepository;
import org.eclipse.egit.github.core.event.ForkPayload;

/**
 * Helper to find a {@link RepositoryEventMatcher} to open for an event
 */
public class RepositoryEventMatcher {

    /**
     * Get {@link Repository} from event
     *
     * @param event
     * @return gist or null if event doesn't apply
     */
    public Repository getRepository(final Event event) {
        if (event == null)
            return null;
        EventPayload payload = event.getPayload();
        if (payload == null)
            return null;
        String type = event.getType();
        if (TYPE_FORK.equals(type))
            return ((ForkPayload) payload).getForkee();
        else if (TYPE_CREATE.equals(type)) {
            EventRepository repo = event.getRepo();
            if (repo != null) {
                String id = repo.getName();
                int slash = id.indexOf('/');
                if (slash > 0 && slash + 1 < id.length()) {
                    Repository full = new Repository();
                    full.setName(id.substring(slash + 1));
                    String login = id.substring(0, slash);
                    // Use actor if it matches login parsed from repository id
                    if (event.getActor() != null && login.equals(event.getActor().getLogin()))
                        full.setOwner(event.getActor());
                    else
                        full.setOwner(new User().setLogin(id.substring(0, slash)));
                    return full;
                }
            }
        }
        return null;
    }
}

Support opening repositories from create events


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

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

/** TestSuite for all of GWT's emul suites. */
public class AllTests {

  public static Test suite() {
    TestSuite suite = new TestSuite("All Emul tests");
    suite.addTest(BigDecimalSuite.suite());
    suite.addTest(BigIntegerSuite.suite());
    suite.addTest(CollectionsSuite.suite());
    suite.addTest(EmulSuite.suite());
    suite.addTest(EmulJava8Suite.suite());
    suite.addTest(TreeMapSuiteSub.suite());
    suite.addTest(TreeSetSuiteSub.suite());
    return suite;
  }
}

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

import org.junit.runner.RunWith;
import org.junit.runners.Suite;
import org.junit.runners.Suite.SuiteClasses;

/** TestSuite for all of GWT's emul suites. */
@RunWith(Suite.class)
@SuiteClasses({
  BigDecimalSuite.class,
  BigIntegerSuite.class,
  CollectionsSuite.class,
  EmulSuite.class,
  EmulJava8Suite.class,
})
public class AllTests {}

Import: Use @RunWith(Suite.class) for emul test suites.

...and update J2CL AllTests accordingly.

I will delete duplicated J2CL suites in another CL.

commit 032e49ff8d12170b00ac3232174f365df0182f4e
Author: Goktug Gokdogan <goktug@google.com>
Date:   Wed Apr 12 20:06:35 2017 -0700

    Use @RunWith(Suite.class) for emul test suites.

    Change-Id: I2fc94ccf4298714dfee8ba9628f9137e30cdb8a0

PiperOrigin-RevId: 153108807


package me.gowdru.notes.sort;

import java.util.Comparator;

/**
 * Defines contract for Sorter algorithm implementations
 */
public interface Sorter<T> {

    /**
     * sorts {@code items}i in an array by comparing them using {@code comparator}
     * @param items items to be sorted
     * @param comparator comparison assistant
     */
    public void sort(T[] items, Comparator<T> comparator);

}

package me.gowdru.notes.sort;

import java.util.Comparator;

/**
 * Defines contract for Sorter algorithm implementations
 */
public interface Sorter<T> {

    /**
     * sorts {@code items}i in an array by comparing them using {@code comparator}
     * @param items items to be sorted
     * @param comparator comparison assistant
     */
    public void sort(T[] items, Comparator<T> comparator);

    /**
     * swaps a pair of elements in array
     * @param array - array of items
     * @param pos1 position of an item to be swapped to/with
     * @param pos2 position of another item to be swapped to/with
     */
    public default void swap(T[] array, int pos1, int pos2){
        T tmp = array[pos1];
        array[pos1] = array[pos2];
        array[pos2] = tmp;
    }
}

Add swap method to base class

Add swap method to base class


package uk.ac.ox.ndm.grails.utils.validator;

import com.google.common.base.Strings;

/**
 * @since 14/08/2015
 */
public class NhsNumberValidator implements Validator<String> {

    public Object isValid(String nhsNumberStr) {
        if (!Strings.isNullOrEmpty(nhsNumberStr)) {

            nhsNumberStr = nhsNumberStr.replaceAll(" ", "");
            if (nhsNumberStr.length() != 10) {
                return "validation.nhsnumber.wronglength";
            }
            try {
                int checkDigit = 0;
                int[] nhsNumber = new int[nhsNumberStr.length()];
                for (int i = 0; i < nhsNumberStr.length(); i++) {
                    nhsNumber[i] = Integer.parseInt(nhsNumberStr.charAt(i) + "");
                }
                if (nhsNumber.length == 10) {
                    for (int i = 0; i <= 8; i++) {
                        checkDigit += nhsNumber[i] * (10 - i);
                    }
                    checkDigit = (11 - (checkDigit % 11));
                    if (checkDigit == 11) checkDigit = 0;
                    if (checkDigit != 10) return checkDigit == nhsNumber[9];
                }
            } catch (NumberFormatException ignored) {
                // Just ignore this as we will return false
            }
        }
        return "validation.empty";
    }
}

package uk.ac.ox.ndm.grails.utils.validator;

import com.google.common.base.Strings;

/**
 * @since 14/08/2015
 */
public class NhsNumberValidator implements Validator<String> {

    public Object isValid(String nhsNumberStr) {
        if (!Strings.isNullOrEmpty(nhsNumberStr)) {

            nhsNumberStr = nhsNumberStr.replaceAll(" ", "");
            if (nhsNumberStr.length() != 10) {
                return "validation.nhsnumber.wronglength";
            }
            try {
                int checkDigit = 0;
                int[] nhsNumber = new int[nhsNumberStr.length()];
                for (int i = 0; i < nhsNumberStr.length(); i++) {
                    nhsNumber[i] = Integer.parseInt(nhsNumberStr.charAt(i) + "");
                }
                if (nhsNumber.length == 10) {
                    for (int i = 0; i <= 8; i++) {
                        checkDigit += nhsNumber[i] * (10 - i);
                    }
                    checkDigit = (11 - (checkDigit % 11));
                    if (checkDigit == 11) checkDigit = 0;
                    if (checkDigit != 10)
                        return checkDigit == nhsNumber[9] ? true : "validation.nhsnumber.invalid";
                }
            } catch (NumberFormatException ignored) {
                return "validation.nhsnumber.not.numeric";
            }
        }
        return "validation.empty";
    }
}

Add error return strings to the NHS number validator


package example;

import ethanjones.cubes.block.Block;

public class MyBlock extends Block {

  public MyBlock() {
    super("MyMod:block/texture.png");
  }
}

package example;

import ethanjones.cubes.block.Block;

public class MyBlock extends Block {

  public MyBlock() {
    super("MyMod:block/texture");
  }
}

Remove .png (automatically added now)

Remove .png (automatically added now)


package com.volumetricpixels.vitals.main;

import org.spout.api.command.annotated.AnnotatedCommandRegistrationFactory;
import org.spout.api.command.annotated.SimpleInjector;
import org.spout.api.plugin.CommonPlugin;

import com.volumetricpixels.vitals.main.commands.AdminCommands;
import com.volumetricpixels.vitals.main.commands.GeneralCommands;
import com.volumetricpixels.vitals.main.configuration.VitalsConfiguration;

public class Vitals extends CommonPlugin {

        private VitalsConfiguration config;

        @Override
        public void onDisable() {
                getLogger().info("[Vitals] v" + getDescription().getVersion() + " disabled!");
        }

        @Override
        public void onEnable() {
                config = new VitalsConfiguration(getDataFolder());

		// Register commands.
                AnnotatedCommandRegistrationFactory commandRegistration = new AnnotatedCommandRegistrationFactory(new SimpleInjector(this));
                getEngine().getRootCommand().addSubCommands(this, AdminCommands.class, commandRegistration);
                getEngine().getRootCommand().addSubCommands(this, GeneralCommands.class, commandRegistration);

                getLogger().info("[Vitals] v" + getDescription().getVersion() + " enabled!");
        }

        public VitalsConfiguration getConfig() {
                return config;
        }

}

package com.volumetricpixels.vitals.main;

import org.spout.api.command.annotated.AnnotatedCommandRegistrationFactory;
import org.spout.api.command.annotated.SimpleInjector;
import org.spout.api.plugin.CommonPlugin;

import com.volumetricpixels.vitals.main.commands.AdminCommands;
import com.volumetricpixels.vitals.main.commands.GeneralCommands;
import com.volumetricpixels.vitals.main.commands.ProtectionCommands;
import com.volumetricpixels.vitals.main.commands.WorldCommands;
import com.volumetricpixels.vitals.main.configuration.VitalsConfiguration;

public class Vitals extends CommonPlugin {

        private VitalsConfiguration config;

        @Override
        public void onDisable() {
                getLogger().info("[Vitals] v" + getDescription().getVersion() + " disabled!");
        }

        @Override
        public void onEnable() {
                config = new VitalsConfiguration(getDataFolder());

		// Register commands.
                AnnotatedCommandRegistrationFactory commandRegistration = new AnnotatedCommandRegistrationFactory(new SimpleInjector(this));
                getEngine().getRootCommand().addSubCommands(this, AdminCommands.class, commandRegistration);
                getEngine().getRootCommand().addSubCommands(this, GeneralCommands.class, commandRegistration);
                getEngine().getRootCommand().addSubCommands(this, ProtectionCommands.class, commandRegistration);
                getEngine().getRootCommand().addSubCommands(this, WorldCommands.class, commandRegistration);

                getLogger().info("[Vitals] v" + getDescription().getVersion() + " enabled!");
        }

        public VitalsConfiguration getConfig() {
                return config;
        }

}

Add registration of world + protection cmds

Signed-off-by: Ollie <caf5c3fc6dbe0c347eab97fff2fea94d86d406b9@live.co.uk>


package com.uwetrottmann.trakt5.enums;

/**
 * By default, all methods will return minimal info for movies, shows, episodes, and users. Minimal info is typically
 * all you need to match locally cached items and includes the title, year, and ids. However, you can request different
 * extended levels of information.
 */
public enum Extended implements TraktEnum {

    /** Default. Returns enough info to match locally. */
    DEFAULT_MIN("min"),
    /** Complete info for an item. */
    FULL("full"),
    /** Only works with sync watchedShows. */
    NOSEASONS("noseasons"),
    /** Only works with seasons/summary */
    EPISODES("episodes"),
    /** Only works with seasons/summary */
    FULLEPISODES("full,episodes");

    private final String value;

    Extended(String value) {
        this.value = value;
    }

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

package com.uwetrottmann.trakt5.enums;

/**
 * By default, all methods will return minimal info for movies, shows, episodes, and users. Minimal info is typically
 * all you need to match locally cached items and includes the title, year, and ids. However, you can request different
 * extended levels of information.
 */
public enum Extended implements TraktEnum {

    /** Complete info for an item. */
    FULL("full"),
    /** Only works with sync watchedShows. */
    NOSEASONS("noseasons"),
    /** Only works with seasons/summary */
    EPISODES("episodes"),
    /** Only works with seasons/summary */
    FULLEPISODES("full,episodes");

    private final String value;

    Extended(String value) {
        this.value = value;
    }

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

Remove extended default value, should pass null instead.


package net.folab.fo.runtime;

import static org.junit.Assert.*;
import static org.hamcrest.CoreMatchers.*;

import java.lang.reflect.Field;

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

public class GeneratedCodeTest {

    private Class<?> genClass;

    @Before
    public void setUp() throws ClassNotFoundException {
        genClass = Class.forName("net.folab.fo.runtime._");
    }

    @Test
    public void test() throws SecurityException, NoSuchFieldException,
            IllegalArgumentException, IllegalAccessException {

        test("_a", "1");
        test("_b", "2");
        test("_c", "3");
        test("_d", "4");
        test("_e", "5");
        test("_f", "false");
        test("_t", "true");

    }

    public void test(String name, String string) throws NoSuchFieldException,
            IllegalAccessException {
        Field field = genClass.getField(name);
        Evaluable<?> value = (Evaluable<?>) field.get(null);
        assertThat(value.evaluate().toString(), is(string));
    }

}

package net.folab.fo.runtime;

import static org.junit.Assert.*;
import static org.hamcrest.CoreMatchers.*;

import java.lang.reflect.Field;

import net.folab.fo.runtime._fo._lang.Boolean;
import net.folab.fo.runtime._fo._lang.Integer;

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

public class GeneratedCodeTest {

    private Class<?> genClass;

    @Before
    public void setUp() throws ClassNotFoundException {
        genClass = Class.forName("net.folab.fo.runtime._");
    }

    @Test
    public void test() throws SecurityException, NoSuchFieldException,
            IllegalArgumentException, IllegalAccessException {

        test("_a", Integer.valueOf(1));
        test("_b", Integer.valueOf(2));
        test("_c", Integer.valueOf(3));
        test("_d", Integer.valueOf(4));
        test("_e", Integer.valueOf(5));
        test("_f", Boolean.FALSE);
        test("_t", Boolean.TRUE);

    }

    public <T extends Evaluable<T>> void test(String name, Evaluable<T> expected)
            throws NoSuchFieldException, IllegalAccessException {
        Field field = genClass.getField(name);
        @SuppressWarnings("unchecked")
        Evaluable<T> value = (Evaluable<T>) field.get(null);
        assertThat(value.evaluate(), is(expected));
    }

}

Update test code to compare with real type rather than string value.


package org.scribe.utils;

import java.io.ByteArrayInputStream;
import java.io.InputStream;

import org.junit.Test;

import static org.junit.Assert.*;

public class StreamUtilsTest
{

  @Test
  public void shouldCorrectlyDecodeAStream()
  {
    String value = "expected";
    InputStream is = new ByteArrayInputStream(value.getBytes());
    String decoded = StreamUtils.getStreamContents(is);
    assertEquals("expected", decoded);
  }

  @Test(expected = IllegalArgumentException.class)
  public void shouldFailForNullParameter()
  {
    InputStream is = null;
    StreamUtils.getStreamContents(is);
    fail("Must throw exception before getting here");
  }
}

package org.scribe.utils;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;

import org.junit.Test;

import static org.junit.Assert.*;

public class StreamUtilsTest
{

  @Test
  public void shouldCorrectlyDecodeAStream()
  {
    String value = "expected";
    InputStream is = new ByteArrayInputStream(value.getBytes());
    String decoded = StreamUtils.getStreamContents(is);
    assertEquals("expected", decoded);
  }

  @Test(expected = IllegalArgumentException.class)
  public void shouldFailForNullParameter()
  {
    InputStream is = null;
    StreamUtils.getStreamContents(is);
    fail("Must throw exception before getting here");
  }

  @Test(expected = IllegalStateException.class)
  public void shouldFailWithBrokenStream()
  {
    // This object simulates problems with input stream.
    final InputStream is = new InputStream()
    {
      @Override
      public int read() throws IOException
      {
        throw new IOException();
      }
    };
    StreamUtils.getStreamContents(is);
    fail("Must throw exception before getting here");
  }

}

Add negative test for StreamUtils.getStreamContents


package edu.northwestern.bioinformatics.studycalendar.domain.auditing;

import java.util.Date;

/**
 * Subclass of core-commons' DataAuditInfo that aliases the "on" property as "time".
 * This is so that it can be used in HQL queries ("on" is apparently a reserved word).
 *
 * @author Rhett Sutphin
 */
public class DataAuditInfo extends edu.nwu.bioinformatics.commons.DataAuditInfo {
    public DataAuditInfo() { }

    public DataAuditInfo(String by, String ip) {
        super(by, ip);
    }

    public DataAuditInfo(String by, String ip, Date on) {
        super(by, ip, on);
    }

    public static DataAuditInfo copy(edu.nwu.bioinformatics.commons.DataAuditInfo source) {
        return new DataAuditInfo(
            source.getBy(), source.getIp(), source.getOn()
        );
    }

    public Date getTime() {
        return getOn();
    }

    public void setTime(Date on) {
        setOn(on);
    }

    /* Have to duplicate other accessors so that it will work with annotations without
       annotating the superclass. */
    public String getUsername() { return super.getBy(); }
    public void setUsername(String by) { super.setBy(by); }
    public String getIp() { return super.getIp(); }
    public void setIp(String ip) { super.setIp(ip); }
}

package edu.northwestern.bioinformatics.studycalendar.domain.auditing;

import org.hibernate.annotations.Type;

import java.util.Date;
import java.sql.Timestamp;

/**
 * Subclass of core-commons' DataAuditInfo that aliases the "on" property as "time".
 * This is so that it can be used in HQL queries ("on" is apparently a reserved word).
 *
 * @author Rhett Sutphin
 */
public class DataAuditInfo extends edu.nwu.bioinformatics.commons.DataAuditInfo {
    public DataAuditInfo() { }

    public DataAuditInfo(String by, String ip) {
        super(by, ip);
    }

    public DataAuditInfo(String by, String ip, Date on) {
        super(by, ip, on);
    }

    public static DataAuditInfo copy(edu.nwu.bioinformatics.commons.DataAuditInfo source) {
        return new DataAuditInfo(
            source.getBy(), source.getIp(), source.getOn()
        );
    }

    @Type(type = "timestamp")
    public Date getTime() {
        return getOn();
    }

    public void setTime(Date on) {
        setOn(on);
    }

    /* Have to duplicate other accessors so that it will work with annotations without
       annotating the superclass. */
    public String getUsername() { return super.getBy(); }
    public void setUsername(String by) { super.setBy(by); }
    public String getIp() { return super.getIp(); }
    public void setIp(String ip) { super.setIp(ip); }
}

Add timestamp type to time property for oracle

git-svn-id: 4b387fe5ada7764508e2ca96c335714e4c1692c6@947 0d517254-b314-0410-acde-c619094fa49f


/*
 * Copyright 2014 Red Hat, Inc. and/or its affiliates.
 *
 * Licensed under the Eclipse Public License version 1.0, available at
 * http://www.eclipse.org/legal/epl-v10.html
 */
package org.jboss.forge.plugin.idea.ui.component;

import org.jboss.forge.addon.ui.input.InputComponent;

/**
 * A factory for {@link ComponentBuilder} instances.
 *
 * @author George Gastaldi
 */
public enum ComponentBuilderRegistry
{
    INSTANCE;

    private ComponentBuilder[] componentBuilders = {
            new CheckboxComponentBuilder(),
            new ComboComponentBuilder(),
            new RadioComponentBuilder(),
            new FileChooserComponentBuilder(),
            new DirectoryChooserComponentBuilder(),
            new JavaClassChooserComponentBuilder(),
            new JavaPackageChooserComponentBuilder(),
            new TextBoxComponentBuilder(),
            new PasswordComponentBuilder(),
            new TextAreaComponentBuilder(),
            new FallbackTextBoxComponentBuilder()};

    public ComponentBuilder getBuilderFor(InputComponent<?, ?> input)
    {
        for (ComponentBuilder builder : componentBuilders)
        {
            if (builder.handles(input))
            {
                return builder;
            }
        }
        throw new IllegalArgumentException(
                "No UI component found for input type of "
                        + input.getValueType()
        );
    }
}

/*
 * Copyright 2014 Red Hat, Inc. and/or its affiliates.
 *
 * Licensed under the Eclipse Public License version 1.0, available at
 * http://www.eclipse.org/legal/epl-v10.html
 */
package org.jboss.forge.plugin.idea.ui.component;

import org.jboss.forge.addon.ui.input.InputComponent;

/**
 * A factory for {@link ComponentBuilder} instances.
 *
 * @author George Gastaldi
 */
public enum ComponentBuilderRegistry
{
    INSTANCE;

    private ComponentBuilder[] componentBuilders = {
            new CheckboxComponentBuilder(),
            new ComboComponentBuilder(),
            new RadioComponentBuilder(),
            new TextBoxComponentBuilder(),
            new PasswordComponentBuilder(),
            new TextAreaComponentBuilder(),
            new FileChooserComponentBuilder(),
            new DirectoryChooserComponentBuilder(),
            new JavaClassChooserComponentBuilder(),
            new JavaPackageChooserComponentBuilder(),
            new FallbackTextBoxComponentBuilder()};

    public ComponentBuilder getBuilderFor(InputComponent<?, ?> input)
    {
        for (ComponentBuilder builder : componentBuilders)
        {
            if (builder.handles(input))
            {
                return builder;
            }
        }
        throw new IllegalArgumentException(
                "No UI component found for input type of "
                        + input.getValueType()
        );
    }
}

Fix ComponentBuilder order in registry

Fix ComponentBuilder order in registry


package com.aayaffe.sailingracecoursemanager.communication;

import java.io.Serializable;

/**
 * Created by aayaffe on 30/09/2015.
 */
public enum ObjectTypes {
    RaceManager(0),
    WorkerBoat(1),
    Buoy(2),
    FlagBuoy(3),
    TomatoBuoy(4),
    TriangleBuoy(5),
    StartLine(6),
    FinishLine(7),
    StartFinishLine(8),
    Gate(9),
    ReferencePoint(10),
    Other(11);

    private int value;

    ObjectTypes(int value) {
        this.value = value;
    }

    public int getValue() {
        return value;
    }
}

package com.aayaffe.sailingracecoursemanager.communication;

import java.io.Serializable;

/**
 * Created by aayaffe on 30/09/2015.
 */
public enum ObjectTypes {
    WorkerBoat,
    FlagBuoy,
    TomatoBuoy,
    TriangleBuoy,
    StartLine,
    FinishLine,
    StartFinishLine,

    RaceManager,  //from here, the relevant ObjectTypes:
    Buoy,
    Gate,
    Satellite,
    ReferencePoint,
    Other
}

Revert "Updated object types in Dev"

Revert "Updated object types in Dev"

This reverts commit 9dcc2cb8e65c1f558a431a8cd700ce6696a6d8f3.


package com.seaglasslookandfeel.demo;

import java.awt.BorderLayout;
import java.awt.Dimension;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollBar;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;

public class TestScrollBars {

    public static void main(String[] args) {
        try {
            UIManager.setLookAndFeel("com.seaglasslookandfeel.SeaGlassLookAndFeel");
        } catch (Exception e) {
            e.printStackTrace();
        }

        SwingUtilities.invokeLater(new Runnable() {
            public void run() {

                JScrollBar scrollBar = new JScrollBar(JScrollBar.VERTICAL);
                scrollBar.setPreferredSize(new Dimension(15, 300));

                JPanel panel = new JPanel();
                panel.add(scrollBar, BorderLayout.CENTER);

                JFrame frame = new JFrame();
                frame.add(panel, BorderLayout.CENTER);
                frame.setSize(275, 125);
                frame.setLocationRelativeTo(null);
                frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
                frame.setVisible(true);
            }
        });
    }

}

package com.seaglasslookandfeel.demo;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;

public class TestScrollBars {

    public static void main(String[] args) {
        if (true) {
            try {
                UIManager.setLookAndFeel("com.seaglasslookandfeel.SeaGlassLookAndFeel");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        SwingUtilities.invokeLater(new Runnable() {
            public void run() {

                JPanel panel = new JPanel();
                panel.setPreferredSize(new Dimension(500, 500));
                panel.setBackground(Color.WHITE);

                JScrollPane scrollPane = new JScrollPane(panel);

                JFrame frame = new JFrame();
                frame.add(scrollPane, BorderLayout.CENTER);
                frame.setSize(275, 125);
                frame.setLocationRelativeTo(null);
                frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
                frame.setVisible(true);
            }
        });
    }

}

Use a scroll pane for the scroll bar test.


/* Copyright 2018 Telstra Open Source
 *
 *   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.openkilda.northbound.dto.flows;

import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.Value;

@Value
public class VerificationInput {
    @JsonProperty("timeout")
    private int timeoutMillis;

    @JsonCreator
    public VerificationInput(
            @JsonProperty("timeout") int timeoutMillis) {
        this.timeoutMillis = timeoutMillis;
    }
}

/* Copyright 2018 Telstra Open Source
 *
 *   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.openkilda.northbound.dto.flows;

import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.Value;

import java.util.Optional;

@Value
public class VerificationInput {
    public static final int DEFAULT_TIMEOUT = 2000;

    @JsonProperty("timeout")
    private int timeoutMillis;

    @JsonCreator
    public VerificationInput(
            @JsonProperty("timeout") Integer timeoutMillis) {
        this.timeoutMillis = Optional.ofNullable(timeoutMillis).orElse(DEFAULT_TIMEOUT);
    }
}

Make timeout value optional in flow verification request


package net.izenith.Commands;

import org.bukkit.Bukkit;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.permissions.Permission;

import net.izenith.Main.Util;
import net.md_5.bungee.api.ChatColor;

public class PlayTime implements HubCommand{

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

	@Override
	public String[] getAliases() {
		return new String[]{"play","givemearimjobandbitemyear"};
	}

	@Override
	public void onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args) {
		Long time = Util.getOnlineTime(Bukkit.getPlayer(args[0]));
		Double timeHours = new Double(time)/(1000*60*60);
		sender.sendMessage(ChatColor.BLUE + args[0] + " has played for " + ChatColor.GREEN + timeHours + " hours");
	}

	@Override
	public boolean onlyPlayers() {
		return false;
	}

	@Override
	public boolean hasPermission() {
		return false;
	}

	@Override
	public Permission getPermission() {
		return null;
	}

}

package net.izenith.Commands;

import java.text.DecimalFormat;

import org.bukkit.Bukkit;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.permissions.Permission;

import net.izenith.Main.Util;
import net.md_5.bungee.api.ChatColor;

public class PlayTime implements HubCommand{

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

	@Override
	public String[] getAliases() {
		return new String[]{"play","givemearimjobandbitemyear"};
	}

	@Override
	public void onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args) {
		Long time = Util.getOnlineTime(Bukkit.getPlayer(args[0]));
		Double timeHours = new Double(time)/(1000*60*60);
		DecimalFormat df = new DecimalFormat("#.##");
		String shortTime = df.format(timeHours);
		sender.sendMessage(ChatColor.BLUE + args[0] + " has played for " + ChatColor.GREEN + shortTime + " hours");
	}

	@Override
	public boolean onlyPlayers() {
		return false;
	}

	@Override
	public boolean hasPermission() {
		return false;
	}

	@Override
	public Permission getPermission() {
		return null;
	}

}

Fix to long decimal places

Fix to long decimal places


package sfBugsNew;

import edu.umd.cs.findbugs.annotations.Confidence;
import edu.umd.cs.findbugs.annotations.ExpectWarning;
import edu.umd.cs.findbugs.annotations.NoWarning;

public class Bug1219 {

    interface A {
    }

    interface B {
    }
    interface C {
    }
    interface D {
    }
    static class CC implements C {}
    static class DC implements D {}

    A objectA;

    @NoWarning(value="EC_UNRELATED_TYPES_USING_POINTER_EQUALITY", confidence=Confidence.MEDIUM)
    public boolean compare(B objectB) {
        return (objectA == objectB);
    }

    @NoWarning(value="EC_UNRELATED_TYPES_USING_POINTER_EQUALITY", confidence=Confidence.MEDIUM)
      public boolean compare(C objectC) {
        return (objectA == objectC);
    }

    @ExpectWarning(value="EC_UNRELATED_TYPES_USING_POINTER_EQUALITY", confidence=Confidence.MEDIUM)
    public static boolean compare(C objectC, D objectD) {
      return (objectC == objectD);
  }
}

package sfBugsNew;

import edu.umd.cs.findbugs.annotations.Confidence;
import edu.umd.cs.findbugs.annotations.ExpectWarning;
import edu.umd.cs.findbugs.annotations.NoWarning;

public class Bug1219 {

    interface A {
    }

    interface B {
    }
    interface C {
    }
    interface D {
    }
    static class CC implements C {}
    static class DC implements D {}

    A objectA;

    @NoWarning(value="EC_UNRELATED_TYPES_USING_POINTER_EQUALITY", confidence=Confidence.MEDIUM)
    @ExpectWarning(value="EC_UNRELATED_TYPES_USING_POINTER_EQUALITY", confidence=Confidence.LOW)
    public boolean compare(B objectB) {
        return (objectA == objectB);
    }

    @NoWarning(value="EC_UNRELATED_TYPES_USING_POINTER_EQUALITY", confidence=Confidence.MEDIUM)
    @ExpectWarning(value="EC_UNRELATED_TYPES_USING_POINTER_EQUALITY", confidence=Confidence.LOW)
      public boolean compare(C objectC) {
        return (objectA == objectC);
    }

    @ExpectWarning(value="EC_UNRELATED_TYPES_USING_POINTER_EQUALITY", confidence=Confidence.MEDIUM)
    public static boolean compare(C objectC, D objectD) {
      return (objectC == objectD);
  }
}

Make sure we don't miss "low" confidence warnings

git-svn-id: e7d6bde23f017c9ff4efd468d79d66def666766b@14961 eae3c2d3-9b19-0410-a86e-396b6ccb6ab3


package ceylon;

public final class Boolean extends Object {
    private final boolean value;

    private Boolean(boolean b) {
        value = b;
    }

    public static ceylon.Boolean instance(boolean b) {
        return new ceylon.Boolean(b);
    }

    @Extension
    public ceylon.String string() {
        return ceylon.String.instance(java.lang.Boolean.toString(value));
    }

    public boolean booleanValue() {
        return value;
    }
}

package ceylon;

public final class Boolean extends Object {
    private final boolean value;

    private Boolean(boolean b) {
        value = b;
    }

    public static ceylon.Boolean instance(boolean b) {
        return new ceylon.Boolean(b);
    }

    @Extension
    public ceylon.String string() {
        return ceylon.String.instance(java.lang.Boolean.toString(value));
    }

    @Extension
    public boolean booleanValue() {
        return value;
    }
}

Allow extension to primitive Java types

Allow extension to primitive Java types


package com.sb.elsinore.html;

import java.io.IOException;

import org.rendersnake.HtmlCanvas;
import org.rendersnake.Renderable;

import com.sb.elsinore.LaunchControl;

import static org.rendersnake.HtmlAttributesFactory.*;

/**
 * Create a top bar for the web page.
 * @author Doug Edey
 */
public class TopBar implements Renderable {

    @Override
    public final void renderOn(HtmlCanvas htmlCanvas) throws IOException {
        htmlCanvas.div(id("topbar").class_("col-md-12"))
            .div(id("breweryTitle").class_("left  col-md-2"))
                .h1(class_("breweryNameHeader").onClick("editBreweryName()"))
                    .div(id("breweryName")).write("Elsinore")._div()
                    .small()
                        .a(href(LaunchControl.RepoURL))
                            .content("StrangeBrew Elsinore")
                    ._small()
                ._h1()
            ._div()
            .div(class_("center-left col-md-4"))._div()
            .div(class_("center-right col-md-4"))._div()
        ._div()
        .div(id("messages").style("display:none"))
            .div(class_("panel panel-warning"))
                .div(id("messages-title").class_("title panel-heading"))._div()
                .div(id("messages-body").class_("panel-body"))._div()
            ._div()
        ._div();
    }

}

package com.sb.elsinore.html;

import java.io.IOException;

import org.rendersnake.HtmlCanvas;
import org.rendersnake.Renderable;

import com.sb.elsinore.LaunchControl;

import static org.rendersnake.HtmlAttributesFactory.*;

/**
 * Create a top bar for the web page.
 * @author Doug Edey
 */
public class TopBar implements Renderable {

    @Override
    public final void renderOn(HtmlCanvas htmlCanvas) throws IOException {
        htmlCanvas.div(id("topbar").class_("row"))
            .div(id("breweryTitle").class_("left col-md-2"))
                .h1(class_("breweryNameHeader").onClick("editBreweryName()"))
                    .div(id("breweryName")).write("Elsinore")._div()
                    .small()
                        .a(href(LaunchControl.RepoURL))
                            .content("StrangeBrew Elsinore")
                    ._small()
                ._h1()
            ._div()
            .div(class_("center-left col-md-4"))._div()
            .div(class_("center-right col-md-4"))._div()
        ._div()
        .div(id("messages").class_("row").style("display:none"))
            .div(class_("panel panel-warning"))
                .div(id("messages-title").class_("title panel-heading"))._div()
                .div(id("messages-body").class_("panel-body"))._div()
            ._div()
        ._div();
    }

}

Improve the top bar for the error messages.


package fr.minepod.bootstrap;

import java.awt.HeadlessException;
import java.io.IOException;

public class CrashReport {
	public static String DebugFilePath = Config.DebugFilePath;

	public static void SendReport(String exception, String when) {
		try {
			if(Config.Logger != null)
				Config.Logger.severe(exception);
			javax.swing.JOptionPane.showMessageDialog(null, exception + "\n" +  Langage.WHEN.toString() + when + "\n\n\n" + Langage.DEBUGINFORMATIONS.toString() + ":\n\n" + fr.minepod.Utils.Files.ReadFile(DebugFilePath), Langage.ERROR.toString(), javax.swing.JOptionPane.ERROR_MESSAGE);
		} catch (HeadlessException e) {
			if(Config.Logger != null)
				Config.Logger.severe(e.toString());
			javax.swing.JOptionPane.showMessageDialog(null, e.toString(),  Langage.ERROR.toString(), javax.swing.JOptionPane.ERROR_MESSAGE);
		} catch (IOException e) {
			if(Config.Logger != null)
				Config.Logger.severe(e.toString());
			javax.swing.JOptionPane.showMessageDialog(null, e.toString(),  Langage.ERROR.toString(), javax.swing.JOptionPane.ERROR_MESSAGE);
		}
        System.exit(0);
	}
}

package fr.minepod.bootstrap;

import java.awt.HeadlessException;
import java.io.File;
import java.io.IOException;

public class CrashReport {
	public static void SendReport(String exception, String when) {
		try {
			if(Config.Logger != null)
				Config.Logger.severe(exception);

			String debugMsg = "";

			if(new File(Config.DebugFilePath).exists())
				debugMsg = fr.minepod.Utils.Files.ReadFile(Config.DebugFilePath);

			javax.swing.JOptionPane.showMessageDialog(null, exception + "\n" +  Langage.WHEN.toString() + when + "\n\n\n" + Langage.DEBUGINFORMATIONS.toString() + ":\n\n" + debugMsg, Langage.ERROR.toString(), javax.swing.JOptionPane.ERROR_MESSAGE);
		} catch (HeadlessException e) {
			if(Config.Logger != null)
				Config.Logger.severe(e.toString());
			javax.swing.JOptionPane.showMessageDialog(null, e.toString(),  Langage.ERROR.toString(), javax.swing.JOptionPane.ERROR_MESSAGE);
		} catch (IOException e) {
			if(Config.Logger != null)
				Config.Logger.severe(e.toString());
			javax.swing.JOptionPane.showMessageDialog(null, e.toString(),  Langage.ERROR.toString(), javax.swing.JOptionPane.ERROR_MESSAGE);
		}
        System.exit(0);
	}
}

Check if debug file exists

Check if debug file exists


package sizebay.catalog.client.model;

import java.util.*;
import com.fasterxml.jackson.annotation.JsonValue;
import lombok.*;

@Getter
@Setter
public class Modeling   {

  private Long id;
  private String name;

  private Gender gender;
  private String gMerchantBrandName;
  private String gMerchantAgeGroup;
  private String gMerchantSizeType;

  private TypeEnum type;
  private Long brandId;
  private Long categoryId;
  private List<ModelingSizeMeasures> measures = new ArrayList<>();

  private Integer strongCategoryTypeId;
  private String strongCategoryTypeName;

  private int isShoe;

  @Getter
  @RequiredArgsConstructor
  public enum TypeEnum {
    PRODUCT("product"),
    BODY("body");

    final private String value;

    @Override
    @JsonValue
    public String toString() {
      return value;
    }
  }

  @Getter
  @RequiredArgsConstructor
  public enum Gender {
    M("M"), F("F"), U("U");

    final private String value;

    @Override
    @JsonValue
    public String toString() {
      return value;
    }
  }
}

package sizebay.catalog.client.model;

import java.util.*;
import com.fasterxml.jackson.annotation.JsonValue;
import lombok.*;

@Getter
@Setter
public class Modeling   {

  private Long id;
  private String name;

  private Gender gender;
  private String gMerchantBrandName;
  private String gMerchantAgeGroup;
  private String gMerchantSizeType;
  private String observation;

  private TypeEnum type;
  private Long brandId;
  private Long categoryId;
  private List<ModelingSizeMeasures> measures = new ArrayList<>();

  private Integer strongCategoryTypeId;
  private String strongCategoryTypeName;

  private int isShoe;

  @Getter
  @RequiredArgsConstructor
  public enum TypeEnum {
    PRODUCT("product"),
    BODY("body");

    final private String value;

    @Override
    @JsonValue
    public String toString() {
      return value;
    }
  }

  @Getter
  @RequiredArgsConstructor
  public enum Gender {
    M("M"), F("F"), U("U");

    final private String value;

    @Override
    @JsonValue
    public String toString() {
      return value;
    }
  }
}

Fix: Add attribute observation in measures table


public class item55_optimize_judiciously {
    public static void main(String[] args) {
        System.out.println("do not strive to write fast programs—strive to write good ones; speed will follow.");
    }
}

Add to item55 with a quote from the book


package com.nelsonjrodrigues.pchud;

import java.io.IOException;

import com.nelsonjrodrigues.pchud.net.MessageListener;
import com.nelsonjrodrigues.pchud.net.NetThread;
import com.nelsonjrodrigues.pchud.net.PcMessage;
import com.nelsonjrodrigues.pchud.world.Worlds;

import lombok.extern.slf4j.Slf4j;

@Slf4j
public class PcHud {

    public static void main(String[] args) {

        Thread.setDefaultUncaughtExceptionHandler((t, e) -> {
            log.error("Uncaught thread exception, exiting", t.getName(), e);
            System.exit(-1);
        });

        Worlds worlds = new Worlds();
        worlds.addPropertyChangeListener(evt -> {
            log.debug("{}", worlds);
        });

        try {
            NetThread netThread = new NetThread();
            netThread.addMessageListener(new LogMessageListener());
            netThread.addMessageListener(worlds);
            netThread.start();

            netThread.join();
        }
        catch (IOException | InterruptedException e) {
            log.error(e.getMessage(), e);
        }
        log.debug("Exiting");

    }

    @Slf4j
    private static class LogMessageListener implements MessageListener {

        @Override
        public void onMessage(PcMessage message) {
            log.debug("OnMessage {}", message);
        }

        @Override
        public void onTimeout() {
            log.debug("OnTimeout");
        }

    }

}

package com.nelsonjrodrigues.pchud;

import java.io.IOException;

import com.nelsonjrodrigues.pchud.net.MessageListener;
import com.nelsonjrodrigues.pchud.net.NetThread;
import com.nelsonjrodrigues.pchud.net.PcMessage;
import com.nelsonjrodrigues.pchud.world.Worlds;

import lombok.extern.slf4j.Slf4j;

@Slf4j
public class PcHud {

    public static void main(String[] args) {

        Thread.setDefaultUncaughtExceptionHandler((t, e) -> {
            log.error("Uncaught thread exception, exiting", e);
            System.exit(-1);
        });

        Worlds worlds = new Worlds();
        worlds.addPropertyChangeListener(evt -> {
            log.debug("{}", worlds);
        });

        try {
            NetThread netThread = new NetThread();
            netThread.addMessageListener(new LogMessageListener());
            netThread.addMessageListener(worlds);
            netThread.start();

            netThread.join();
        }
        catch (IOException | InterruptedException e) {
            log.error(e.getMessage(), e);
        }
        log.debug("Exiting");

    }

    @Slf4j
    private static class LogMessageListener implements MessageListener {

        @Override
        public void onMessage(PcMessage message) {
            log.debug("OnMessage {}", message);
        }

        @Override
        public void onTimeout() {
            log.debug("OnTimeout");
        }

    }

}

Remove unused log message param

Remove unused log message param


package com.padakeji.android.ui.autowraplayoutmanager.example;

import android.content.Context;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.widget.ScrollView;

/**
 * Created by atanl on 2016/3/5.
 */
public class MyScrollView extends ScrollView {

    private int downX;
    private int downY;
    private int mTouchSlop;

    public MyScrollView(Context context) {
        super(context);
    }

    public MyScrollView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public MyScrollView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    public boolean onInterceptTouchEvent(MotionEvent e) {
        int action = e.getAction();
        switch (action) {
            case MotionEvent.ACTION_DOWN:
                downX = (int) e.getRawX();
                downY = (int) e.getRawY();
                break;
            case MotionEvent.ACTION_MOVE:
                int moveY = (int) e.getRawY();
                if (Math.abs(moveY - downY) > mTouchSlop) {
                    return true;
                }
        }
        return super.onInterceptTouchEvent(e);
    }
}

package com.padakeji.android.ui.autowraplayoutmanager.example;

import android.content.Context;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.ViewConfiguration;
import android.widget.ScrollView;

/**
 * 继承于ScrollView，禁止了滑动事件向下传递。
 *
 * Created by atanl on 2015/10/20.
 */
public class MyScrollView extends ScrollView {

    public interface OnScrollListener {
        void onScroll();
    }

    private int downX;
    private int downY;
    private int mTouchSlop;

    public MyScrollView(Context context) {
        super(context);
        mTouchSlop = ViewConfiguration.get(context).getScaledTouchSlop();
    }

    public MyScrollView(Context context, AttributeSet attrs) {
        super(context, attrs);
        mTouchSlop = ViewConfiguration.get(context).getScaledTouchSlop();
    }

    public MyScrollView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        mTouchSlop = ViewConfiguration.get(context).getScaledTouchSlop();
    }

    @Override
    protected void onScrollChanged(int l, int t, int oldl, int oldt) {
        super.onScrollChanged(l, t, oldl, oldt);
    }

    @Override
    public boolean onInterceptTouchEvent(MotionEvent e) {
        int action = e.getAction();
        switch (action) {
            case MotionEvent.ACTION_DOWN:
                downX = (int) e.getRawX();
                downY = (int) e.getRawY();
                break;
            case MotionEvent.ACTION_MOVE:
                int moveY = (int) e.getRawY();
                if (Math.abs(moveY - downY) > mTouchSlop) {
                    return true;
                }
        }
        return super.onInterceptTouchEvent(e);
    }
}

Change the example module fixing scroll problem.


package uk.gov.register.core;

import uk.gov.register.core.Entry;
import uk.gov.mint.Item;

public class FatEntry {
    public final Entry entry;
    public final Item item;

    public FatEntry(Entry entry, Item item) {
        this.entry = entry;
        this.item = item;
    }
}

package uk.gov.register.core;

import uk.gov.mint.Item;

public class FatEntry {
    public final Entry entry;
    public final Item item;

    public FatEntry(Entry entry, Item item) {
        this.entry = entry;
        this.item = item;
    }
}

Remove unused Entry from mint import

Remove unused Entry from mint import


/**
 * Part of Employ
 */

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

public class DashboardFrame extends CommonFrame implements ActionListener {

  // define dashboard for special frame
  public DashboardFrame() {
    super("Dashboard");

    JButton buttonAddData = new JButton("Add");
    buttonAddData.addActionListener(this);
    add(buttonAddData);
  }

  // define listener action when button "Add" is clicked
  public void actionPerformed(ActionEvent event) {
    getContentPane().setBackground(Color.white);
    repaint();
  }

}

/**
 * Part of Employ
 */

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

public class DashboardFrame extends CommonFrame implements ActionListener {

  JButton buttonAddData = new JButton("Add");
  JButton buttonDeleteData = new JButton("Delete");
  JTextField textNumber = new JTextField(10);
  JTextField textOutput = new JTextField(10);

  // define dashboard for special frame
  public DashboardFrame() {
    super("Dashboard");

    buttonAddData.setActionCommand("addData");
    buttonDeleteData.setActionCommand("deleteData");

    buttonAddData.addActionListener(this);
    buttonDeleteData.addActionListener(this);
    textNumber.addActionListener(this);

    add(buttonAddData);
    add(buttonDeleteData);
    add(textNumber);
    add(textOutput);
  }

  // define listener action when button "Add" is clicked
  public void actionPerformed(ActionEvent event) {
    String inputNumber = textNumber.getText();
    textOutput.setText(inputNumber);

    if (event.getActionCommand().equals("addData"))
      getContentPane().setBackground(Color.white);
    else if (event.getActionCommand().equals("deleteData"))
      getContentPane().setBackground(Color.darkGray);
    else
      getContentPane().setBackground(Color.black);

    repaint();
  }

}

Add label and text field with application code


/**
 * Part of Employ
 */

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

public class DashboardFrame extends CommonFrame implements ActionListener {

  JButton buttonAddData = new JButton("Add");
  JButton buttonDeleteData = new JButton("Delete");
  JTextField textNumber = new JTextField(10);
  JTextField textOutput = new JTextField(10);

  // define dashboard for special frame
  public DashboardFrame() {
    super("Dashboard");

    buttonAddData.setActionCommand("addData");
    buttonDeleteData.setActionCommand("deleteData");

    buttonAddData.addActionListener(this);
    buttonDeleteData.addActionListener(this);
    textNumber.addActionListener(this);

    add(buttonAddData);
    add(buttonDeleteData);
    add(textNumber);
    add(textOutput);
  }

  // define listener action when button "Add" is clicked
  public void actionPerformed(ActionEvent event) {
    String inputNumber = textNumber.getText();
    textOutput.setText(inputNumber);

    if (event.getActionCommand().equals("addData"))
      getContentPane().setBackground(Color.white);
    else if (event.getActionCommand().equals("deleteData"))
      getContentPane().setBackground(Color.darkGray);
    else
      getContentPane().setBackground(Color.black);

    repaint();
  }

}

/**
 * Part of Employ
 */

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

public class DashboardFrame extends CommonFrame implements ActionListener {

  JButton buttonAddData = new JButton("Add");
  JButton buttonDeleteData = new JButton("Delete");
  JTextField textInputNumber = new JTextField(10);
  JTextField textOutputNumber = new JTextField(10);

  // define dashboard for special frame
  public DashboardFrame() {
    super("Dashboard");

    buttonAddData.setActionCommand("addData");
    buttonDeleteData.setActionCommand("deleteData");

    buttonAddData.addActionListener(this);
    buttonDeleteData.addActionListener(this);
    textInputNumber.addActionListener(this);
    textOutputNumber.setEditable(false);

    add(buttonAddData);
    add(buttonDeleteData);
    add(textInputNumber);
    add(textOutputNumber);
  }

  // get input number in text input
  void getTextInput() {
    String inputNumber = textInputNumber.getText();
    textOutputNumber.setText(inputNumber);
  }

  // clear input number in text input
  void clearInputNumber() {
    textOutputNumber.setText("");
  }

  // define listener action when button is clicked
  public void actionPerformed(ActionEvent event) {
    if (event.getActionCommand().equals("addData"))
      getTextInput();
    else if (event.getActionCommand().equals("deleteData"))
      clearInputNumber();
    else
      getContentPane().setBackground(Color.white);

    repaint();
  }

}

Create button event with method

Create button event with method

Change variable name to be better described.
Optimize output flow by disable its editable.
Remove unnecessary color changer.