package ceylon.language;

import com.redhat.ceylon.compiler.java.metadata.Ceylon;
import com.redhat.ceylon.compiler.java.metadata.Ignore;

@Ignore
@Ceylon(major = 1)
class StringOfNone extends String implements None<Character> {

    static StringOfNone instance = new StringOfNone();

    private StringOfNone() {
        super("");
    }

    @Override
    public long getSize() {
        return 0;
    }

    @Override
    public boolean getEmpty() {
        return true;
    }

    @Override
    public Character getFirst() {
        return null;
    }

    @Override
    @Ignore
    public Iterable<? extends Character> getSequence() {
        return Iterable$impl._getSequence(this);
    }
    @Override
    @Ignore
    public Character find(Callable<? extends Boolean> f) {
        return Iterable$impl._find(this, f);
    }
    @Override
    @Ignore
    public Iterable<? extends Character> sorted(Callable<? extends Comparison> f) {
        return Iterable$impl._sorted(this, f);
    }
    @Override
    @Ignore
    public <Result> Iterable<Result> map(Callable<? extends Result> f) {
        return new MapIterable<Character, Result>(this, f);
    }
    @Override
    @Ignore
    public Iterable<? extends Character> filter(Callable<? extends Boolean> f) {
        return new FilterIterable<Character>(this, f);
    }
    @Override
    @Ignore
    public <Result> Result fold(Result ini, Callable<? extends Result> f) {
        return Iterable$impl._fold(this, ini, f);
    }
}

package ceylon.language;

import com.redhat.ceylon.compiler.java.metadata.Ceylon;
import com.redhat.ceylon.compiler.java.metadata.Ignore;

@Ignore
@Ceylon(major = 1)
class StringOfNone extends String implements None<Character> {

    static StringOfNone instance = new StringOfNone();

    private StringOfNone() {
        super("");
    }

    @Override
    public long getSize() {
        return 0;
    }

    @Override
    public boolean getEmpty() {
        return true;
    }

    @Override
    public Character getFirst() {
        return null;
    }

    @Override
    @Ignore
    public Iterable<? extends Character> getSequence() {
        return Iterable$impl._getSequence(this);
    }
    @Override
    @Ignore
    public Character find(Callable<? extends Boolean> f) {
        return Iterable$impl._find(this, f);
    }
    @Override
    @Ignore
    public Iterable<? extends Character> sorted(Callable<? extends Comparison> f) {
        return this;
    }
    @Override
    @Ignore
    public <Result> Iterable<Result> map(Callable<? extends Result> f) {
        return new MapIterable<Character, Result>(this, f);
    }
    @Override
    @Ignore
    public Iterable<? extends Character> filter(Callable<? extends Boolean> f) {
        return this;
    }
    @Override
    @Ignore
    public <Result> Result fold(Result ini, Callable<? extends Result> f) {
        return ini;
    }
    @Override @Ignore
    public boolean any(Callable<? extends Boolean> f) {
        return false;
    }
    @Override @Ignore
    public boolean every(Callable<? extends Boolean> f) {
        return false;
    }
}

Add any/every, and optimize some functions (knowing it's empty string)


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

import net.kuujo.vertigo.messaging.JsonMessage;

import org.vertx.java.core.json.JsonObject;

/**
 * A source condition.
 *
 * @author Jordan Halterman
 */
public class SourceCondition implements Condition {
  private String source;

  public SourceCondition() {
  }

  public SourceCondition(String source) {
    this.source = source;
  }

  @Override
  public JsonObject getState() {
    return new JsonObject().putString("source", source);
  }

  @Override
  public void setState(JsonObject state) {
    source = state.getString("source");
  }

  @Override
  public boolean isValid(JsonMessage message) {
    String source = message.source();
    return source != null && source.equals(source);
  }

}

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

import net.kuujo.vertigo.messaging.JsonMessage;

import org.vertx.java.core.json.JsonObject;

/**
 * A source condition.
 *
 * @author Jordan Halterman
 */
public class SourceCondition implements Condition {
  private String source;

  public SourceCondition() {
  }

  public SourceCondition(String source) {
    this.source = source;
  }

  @Override
  public JsonObject getState() {
    return new JsonObject().putString("source", source);
  }

  @Override
  public void setState(JsonObject state) {
    source = state.getString("source");
  }

  @Override
  public boolean isValid(JsonMessage message) {
    String source = message.source();
    return source != null && source.equals(this.source);
  }

}

Fix variable conflict in source condition.


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

import java.security.NoSuchAlgorithmException;

import javax.net.ssl.SSLContext;

import org.apache.tomcat.util.net.Constants;

/**
 * This class checks for the availability of TLS features.
 */
public class TLS {

    private static final boolean tlsv13Available;

    static {
        boolean ok = false;
        try {
            SSLContext sc = SSLContext.getInstance(Constants.SSL_PROTO_TLSv1_3);
            ok = true;
        } catch (NoSuchAlgorithmException ex) {
        }
        tlsv13Available = ok;
    }

    public static boolean isTlsv13Available() {
        return tlsv13Available;
    }

}

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

import java.security.NoSuchAlgorithmException;

import javax.net.ssl.SSLContext;

import org.apache.tomcat.util.net.Constants;

/**
 * This class checks for the availability of TLS features.
 */
public class TLS {

    private static final boolean tlsv13Available;

    static {
        boolean ok = false;
        try {
            SSLContext.getInstance(Constants.SSL_PROTO_TLSv1_3);
            ok = true;
        } catch (NoSuchAlgorithmException ex) {
        }
        tlsv13Available = ok;
    }

    public static boolean isTlsv13Available() {
        return tlsv13Available;
    }

}

Fix IDE nag (unused variable)


/*
 * Copyright 2000-2013 JetBrains s.r.o.
 *
 * 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 matt_richardson.teamCity.buildTriggers.octopusDeploy;

final class OctopusBuildTriggerUtil {
  public static String OCTOPUS_URL = "octopus.build.trigger.url";
  public static String OCTOPUS_APIKEY = "octopus.build.trigger.apikey";
  public static String OCTOPUS_PROJECT_ID = "octopus.build.trigger.project.url";
  public static String OCTOPUS_TRIGGER_ONLY_ON_SUCCESSFUL_DEPLOYMENT = "octopus.build.trigger.only.on.successful.deployment";

  public static String POLL_INTERVAL_PROP = "octops.build.trigger.poll.interval";
  public static final Integer DEFAULT_POLL_INTERVAL = 30; // seconds

  public static final String CONNECTION_TIMEOUT_PROP = "octopus.build.trigger.connection.timeout";
  public static final Integer DEFAULT_CONNECTION_TIMEOUT = 60 * 1000; // milliseconds
}

/*
 * Copyright 2000-2013 JetBrains s.r.o.
 *
 * 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 matt_richardson.teamCity.buildTriggers.octopusDeploy;

public final class OctopusBuildTriggerUtil {
  public static String OCTOPUS_URL = "octopus.build.trigger.url";
  public static String OCTOPUS_APIKEY = "octopus.build.trigger.apikey";
  public static String OCTOPUS_PROJECT_ID = "octopus.build.trigger.project.url";
  public static String OCTOPUS_TRIGGER_ONLY_ON_SUCCESSFUL_DEPLOYMENT = "octopus.build.trigger.only.on.successful.deployment";

  public static String POLL_INTERVAL_PROP = "octops.build.trigger.poll.interval";
  public static final Integer DEFAULT_POLL_INTERVAL = 30; // seconds

  public static final String CONNECTION_TIMEOUT_PROP = "octopus.build.trigger.connection.timeout";
  public static final Integer DEFAULT_CONNECTION_TIMEOUT = 60 * 1000; // milliseconds
}

Make public - otherwise not visible to the UI (JSP)


package org.jstanier;

import static org.mockito.Mockito.when;

import java.io.StringReader;

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

import com.jstanier.InputParser;
import com.jstanier.InputReader;

@RunWith(MockitoJUnitRunner.class)
public class InputParserTest {

    private static final String ONE_LINE_VALID_CSV = "1,\"The content of your tweet\"";

    @Mock
    private InputReader inputReader;

    @InjectMocks
    private InputParser inputParser;

    @Test
    public void parseInput_givenGivenOneCsvLine_thenOneTweetToScheduleIsReturned() {
        when(inputReader.getInputReader(Mockito.anyString())).thenReturn(
                new StringReader(ONE_LINE_VALID_CSV));
        inputParser.parseInput(ONE_LINE_VALID_CSV);
    }
}

package org.jstanier;

import static org.mockito.Mockito.when;

import java.io.StringReader;

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

import com.jstanier.InputParser;
import com.jstanier.InputReader;

@RunWith(MockitoJUnitRunner.class)
public class InputParserTest {

    private static final String ONE_LINE_VALID_CSV = "1,\"The content of your tweet\"";
    private static final String ONE_LINE_INVALID_DELIMITER_CSV = "1;\"The content of your tweet\"";
    private static final String NUMBER_STRING = "1";

    @Mock
    private InputReader inputReader;

    @InjectMocks
    private InputParser inputParser;

    @Test
    public void parseInput_givenGivenOneCsvLine_thenOneTweetToScheduleIsReturned() {
        when(inputReader.getInputReader(Mockito.anyString())).thenReturn(
                new StringReader(ONE_LINE_VALID_CSV));
        inputParser.parseInput(ONE_LINE_VALID_CSV);
    }

    @Test(expected = NumberFormatException.class)
    public void parseInput_givenGivenOneCsvLineWithInvalidDelimiter_thenANumberFormatExceptionIsThrown() {
        when(inputReader.getInputReader(Mockito.anyString())).thenReturn(
                new StringReader(ONE_LINE_INVALID_DELIMITER_CSV));
        inputParser.parseInput(ONE_LINE_INVALID_DELIMITER_CSV);
    }

    @Test(expected = ArrayIndexOutOfBoundsException.class)
    public void parseInput_givenAStringWithOnlyANumber_thenAnArrayIndexOutOfBoundsExceptionIsThrown() {
        when(inputReader.getInputReader(Mockito.anyString())).thenReturn(
                new StringReader(NUMBER_STRING));
        inputParser.parseInput(NUMBER_STRING);
    }
}

Add tests for incorrect input


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

package alluxio;

import org.junit.Assert;
import org.junit.Test;
import org.junit.runners.model.Statement;

import java.io.ByteArrayOutputStream;
import java.io.PrintStream;

/**
 * Unit tests for {@link SystemErrRule}.
 */
public class SystemErrRuleTest {
  private static final ByteArrayOutputStream OUTPUT = new ByteArrayOutputStream();
  private static final PrintStream ORIGINAL_SYSTEM_ERR = System.err;

  private Statement mStatement = new Statement() {
    @Override
    public void evaluate() throws Throwable {
      System.err.println("2048");
      Assert.assertEquals("2048\n", OUTPUT.toString());
      OUTPUT.reset();

      System.err.println("1234");
      Assert.assertEquals("1234\n", OUTPUT.toString());
    }
  };

  @Test
  public void testSystemErrRule() throws Throwable {
    new SystemErrRule(OUTPUT).apply(mStatement, null).evaluate();
    Assert.assertEquals(System.err, ORIGINAL_SYSTEM_ERR);
  }
}

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

package alluxio;

import static org.junit.Assert.assertEquals;

import org.junit.Test;
import org.junit.runners.model.Statement;

import java.io.ByteArrayOutputStream;
import java.io.PrintStream;

/**
 * Unit tests for {@link SystemErrRule}.
 */
public class SystemErrRuleTest {
  private static final ByteArrayOutputStream OUTPUT = new ByteArrayOutputStream();
  private static final PrintStream ORIGINAL_SYSTEM_ERR = System.err;

  private Statement mStatement = new Statement() {
    @Override
    public void evaluate() throws Throwable {
      System.err.println("2048");
      assertEquals("2048\n", OUTPUT.toString());
      OUTPUT.reset();

      System.err.println("1234");
      assertEquals("1234\n", OUTPUT.toString());
    }
  };

  @Test
  public void testSystemErrRule() throws Throwable {
    new SystemErrRule(OUTPUT).apply(mStatement, null).evaluate();
    assertEquals(System.err, ORIGINAL_SYSTEM_ERR);
  }
}

Use static import for standard test utilities


package net.unit8.falchion;

import org.junit.Test;

import java.io.File;

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

/**
 * @author syobochim
 */
public class ContainerTest {

    @Test
    public void createClasspathWithBaseDirAndAplVersion() throws Exception {
        Container sut = new Container(1);
        String basePath = new File(ContainerTest.class.getClassLoader().getResource("containerTestResources").getPath())
                .getAbsolutePath();

        String versionFolder = basePath + File.separator + "0.1.0" + File.separator;
        assertThat(sut.createClasspath(basePath, "0.1.0"),
                is(basePath + ":" + versionFolder + "applicationA.jar:"
                        + versionFolder + "subDir" + File.separator + "applicationB.jar"));
        assertThat(sut.createClasspath(basePath, "0.1.1"), is(basePath));
    }

    @Test
    public void returnBaseDirWhenFileNotFound() throws Exception {
        Container sut = new Container(1);
        String basePath = new File(ContainerTest.class.getClassLoader().getResource("containerTestResources").getPath())
                .getAbsolutePath();
        assertThat(sut.createClasspath(basePath, "0.2.0"), is(basePath));
    }
}

package net.unit8.falchion;

import org.junit.Test;

import java.io.File;

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

/**
 * @author syobochim
 */
public class ContainerTest {

    @Test
    public void createClasspathWithBaseDirAndAplVersion() throws Exception {
        Container sut = new Container(1);
        String basePath = new File(ContainerTest.class.getClassLoader().getResource("containerTestResources").getPath())
                .getAbsolutePath();

        String versionFolder = basePath + File.separator + "0.1.0" + File.separator;
        assertThat(sut.createClasspath(basePath, "0.1.0"), startsWith(basePath + ":"));
        assertThat(sut.createClasspath(basePath, "0.1.0"), containsString(versionFolder + "applicationA.jar"));
        assertThat(sut.createClasspath(basePath, "0.1.0"),
                containsString(versionFolder + "subDir" + File.separator + "applicationB.jar"));
        assertThat(sut.createClasspath(basePath, "0.1.1"), is(basePath));
    }

    @Test
    public void returnBaseDirWhenFileNotFound() throws Exception {
        Container sut = new Container(1);
        String basePath = new File(ContainerTest.class.getClassLoader().getResource("containerTestResources").getPath())
                .getAbsolutePath();
        assertThat(sut.createClasspath(basePath, "0.2.0"), is(basePath));
    }
}

Change assert, because the order of filepath is not guaranteed.


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

import java.util.LinkedList;

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

public class ListUtils {

	@TruffleBoundary
	public static <T> IPersistentStack<T> reverse(IPersistentStack<T> list) {
		final PersistentList<T> plist = (PersistentList<T>) list;

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

}

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

import java.util.LinkedList;

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

public class ListUtils {

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

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

}

Handle empty list reversal corner case


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

package smoketest.batch;

import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.test.system.CapturedOutput;
import org.springframework.boot.test.system.OutputCaptureExtension;

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

@ExtendWith(OutputCaptureExtension.class)
class SampleBatchApplicationTests {

	@Test
	void testDefaultSettings(CapturedOutput output) {
		assertThat(SpringApplication.exit(SpringApplication.run(SampleBatchApplication.class))).isEqualTo(0);
		assertThat(output).contains("completed with the following parameters");
	}

	public static void main(String[] args) throws ClassNotFoundException {
		System.getProperties().forEach((k, v) -> System.out.println(k + "=" + v));
		Class.forName("org.springframework.boot.web.servlet.context.ServletWebServerApplicationContextFactory");
	}

}

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

package smoketest.batch;

import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.test.system.CapturedOutput;
import org.springframework.boot.test.system.OutputCaptureExtension;

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

@ExtendWith(OutputCaptureExtension.class)
class SampleBatchApplicationTests {

	@Test
	void testDefaultSettings(CapturedOutput output) {
		assertThat(SpringApplication.exit(SpringApplication.run(SampleBatchApplication.class))).isEqualTo(0);
		assertThat(output).contains("completed with the following parameters");
	}

}

Remove accidentally committed debug code


package zielu.gittoolbox.ui.statusBar;

import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.project.DumbAwareAction;
import git4idea.i18n.GitBundle;
import git4idea.repo.GitRepository;
import org.jetbrains.annotations.NotNull;
import zielu.gittoolbox.fetch.GtFetchUtil;

public class FetchAction extends DumbAwareAction {
    private final GitRepository myRepository;

    public FetchAction(@NotNull GitRepository repository) {
        super(GitBundle.getString("fetch.action.name"));
        myRepository = repository;
    }

    @Override
    public void actionPerformed(AnActionEvent e) {
        GtFetchUtil.fetch(myRepository);
    }
}

package zielu.gittoolbox.ui.statusBar;

import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.Presentation;
import com.intellij.openapi.project.DumbAwareAction;
import git4idea.GitLocalBranch;
import git4idea.GitRemoteBranch;
import git4idea.i18n.GitBundle;
import git4idea.repo.GitRepository;
import org.jetbrains.annotations.NotNull;
import zielu.gittoolbox.fetch.GtFetchUtil;

public class FetchAction extends DumbAwareAction {
    private final GitRepository myRepository;

    public FetchAction(@NotNull GitRepository repository) {
        super(GitBundle.getString("fetch.action.name"));
        myRepository = repository;
    }

    @Override
    public void update(AnActionEvent e) {
        super.update(e);
        Presentation presentation = e.getPresentation();
        presentation.setEnabled(false);
        GitLocalBranch branch = myRepository.getCurrentBranch();
        if (branch != null) {
            GitRemoteBranch trackedBranch = branch.findTrackedBranch(myRepository);
            if (trackedBranch != null) {
                presentation.setText(GitBundle.getString("fetch.action.name")+" "+trackedBranch.getNameForLocalOperations());
                presentation.setEnabled(true);
            }
        }
    }

    @Override
    public void actionPerformed(AnActionEvent e) {
        GtFetchUtil.fetch(myRepository);
    }
}

Include branch name in fetch


package org.cat.eye.engine.container.unit.deployment;

import org.cat.eye.engine.common.deployment.BundleClassLoader;
import org.cat.eye.engine.common.deployment.BundleDeployer;
import org.cat.eye.engine.common.deployment.management.BundleManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Created by Kotov on 30.11.2017.
 */
public class UnitBundleDeployerImpl implements BundleDeployer {

    private final static Logger LOGGER = LoggerFactory.getLogger(UnitBundleDeployerImpl.class);

    private BundleManager bundleManager;

    @Override
    public void deploy(String classPath, String domain) {

        ClassLoader bundleClassLoader = Thread.currentThread().getContextClassLoader(); // new BundleClassLoader();

        // create and start thread for bundle deploying
        Thread deployingThread = new Thread(new UnitDeployingProcess(classPath, domain, bundleManager));
        deployingThread.setContextClassLoader(bundleClassLoader);
        deployingThread.start();
        try {
            deployingThread.join();
        } catch (InterruptedException e) {
            LOGGER.error("deploy - can't deploy bundle: " + classPath, e);
        }
    }

    @Override
    public void setBundleManager(BundleManager bundleManager) {
        this.bundleManager = bundleManager;
    }
}

package org.cat.eye.engine.container.unit.deployment;

import org.cat.eye.engine.common.deployment.BundleDeployer;
import org.cat.eye.engine.common.deployment.management.BundleManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Created by Kotov on 30.11.2017.
 */
public class UnitBundleDeployerImpl implements BundleDeployer {

    private final static Logger LOGGER = LoggerFactory.getLogger(UnitBundleDeployerImpl.class);

    private BundleManager bundleManager;

    @Override
    public void deploy(String classPath, String domain) {

        ClassLoader bundleClassLoader = Thread.currentThread().getContextClassLoader(); // new BundleClassLoader();

        // create and start thread for bundle deploying
        Thread deployingThread = new Thread(new UnitDeployingProcess(classPath, domain, bundleManager));
        deployingThread.setContextClassLoader(bundleClassLoader);
        deployingThread.start();
        try {
            deployingThread.join();
        } catch (InterruptedException e) {
            LOGGER.error("deploy - can't deploy bundle: " + classPath, e);
        }
    }

    @Override
    public void setBundleManager(BundleManager bundleManager) {
        this.bundleManager = bundleManager;
    }
}

Access to computation context service through actors was implemented.


/*
 * See the NOTICE file distributed with this work for additional
 * information regarding copyright ownership.
 *
 * 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.xwiki.extension.repository.aether.internal;

import org.sonatype.aether.graph.Dependency;
import org.xwiki.extension.AbstractExtensionDependency;

public class AetherExtensionDependency extends AbstractExtensionDependency
{
    private Dependency aetherDependency;

    public AetherExtensionDependency(Dependency aetherDependency)
    {
        super(aetherDependency.getArtifact().getGroupId() + ':' + aetherDependency.getArtifact().getArtifactId(),
            aetherDependency.getArtifact().getVersion());
    }

    public Dependency getAetherDependency()
    {
        return this.aetherDependency;
    }
}

/*
 * See the NOTICE file distributed with this work for additional
 * information regarding copyright ownership.
 *
 * 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.xwiki.extension.repository.aether.internal;

import org.sonatype.aether.graph.Dependency;
import org.xwiki.extension.AbstractExtensionDependency;

public class AetherExtensionDependency extends AbstractExtensionDependency
{
    private Dependency aetherDependency;

    public AetherExtensionDependency(Dependency aetherDependency)
    {
        super(AetherUtils.createExtensionId(aetherDependency.getArtifact()).getId(), aetherDependency.getArtifact()
            .getVersion());
    }

    public Dependency getAetherDependency()
    {
        return this.aetherDependency;
    }
}

Add support for classifier in Maven/Aether repository handler Set proper dependency id


package foam.lib.json;

import foam.lib.parse.*;

public class FloatParser implements Parser {
  public PStream parse(PStream ps, ParserContext x) {
    StringBuilder n = new StringBuilder();
    boolean decimalFound = false;

    if ( ! ps.valid() ) return null;

    char c = ps.head();

    if ( c == '-' ) {
      n.append(c);
      ps = ps.tail();
      if ( ! ps.valid() ) return null;
      c = ps.head();
    }

    // Float numbers must start with a digit: 0.1, 4.0
    if ( Character.isDigit(c) ) n.append(c);
    else return null;

    ps = ps.tail();

    while ( ps.valid() ) {
      c = ps.head();
      if ( Character.isDigit(c) ) {
          n.append(c);
      } else if ( c == '.' ) { // TODO: localization
        if (decimalFound) {
          return null;
        }
        decimalFound = true;
        n.append(c);
      } else {
        break;
      }
      ps = ps.tail();
    }

    return ps.setValue(n.length() > 0 ? Float.valueOf(n.toString()) : 0.0);
  }
}

package foam.lib.json;

import foam.lib.parse.*;

public class FloatParser implements Parser {
  public PStream parse(PStream ps, ParserContext x) {
    StringBuilder n = new StringBuilder();
    boolean decimalFound = false;

    if ( ! ps.valid() ) return null;

    char c = ps.head();

    if ( c == '-' ) {
      n.append(c);
      ps = ps.tail();
      if ( ! ps.valid() ) return null;
      c = ps.head();
    }

    // Float numbers must start with a digit: 0.1, 4.0
    if ( Character.isDigit(c) ) n.append(c);
    else return null;

    ps = ps.tail();

    while ( ps.valid() ) {
      c = ps.head();
      if ( Character.isDigit(c) ) {
          n.append(c);
      } else if ( c == '.' ) { // TODO: localization
        if (decimalFound) {
          return null;
        }
        decimalFound = true;
        n.append(c);
      } else {
        break;
      }
      ps = ps.tail();
    }

    return ps.setValue(n.length() > 0 ? Float.valueOf(n.toString()) : null);
  }
}

Change behaviour to fail on number string of length 0 (zero)


package com.placeholder.rich.todotreeprototype.model;

public class Item {
    private final String name;
    private boolean complete;

    public Item(String name) {
        this(name, false);
    }

    public Item(String name, boolean complete) {
        this.name = name;
        this.complete = complete;
    }

    public String getName() {
        return name;
    }

    public boolean isComplete() {
        return complete;
    }

    public boolean toggleComplete() {
        return complete = !complete;
    }

}

package com.placeholder.rich.todotreeprototype.model;

public class Item {
    private final String name;
    private boolean complete;
    private int nSubItems;
    private int nItemsLeft;

    public Item(String name) {
        this(name, false, 0, 0);
    }

    public Item(String name, boolean complete) {
        this(name, complete, 0, 0);
    }

    public Item(String name, boolean complete, int nSubItems, int nItemsLeft) {
        this.name = name;
        this.complete = complete;
        this.nSubItems = nSubItems;
        this.nItemsLeft = nItemsLeft;
    }

    public String getName() {
        return name;
    }

    public boolean isComplete() {
        return complete;
    }

    public boolean toggleComplete() {
        return complete = !complete;
    }

    public int getNSubItems() {
        return nSubItems;
    }

    public int getNItemsLeft() {
        return nItemsLeft;
    }

    public boolean hasSubItems() {
        return nSubItems > 0;
    }

}

Add number of sub items to model


package io.sphere.sdk.play.metrics;

import io.sphere.sdk.http.HttpClient;
import io.sphere.sdk.http.HttpRequest;
import io.sphere.sdk.http.HttpResponse;
import play.mvc.Http;

import java.util.List;
import java.util.Optional;
import java.util.concurrent.CompletionStage;

public class MetricHttpClient implements HttpClient {
    private final HttpClient underlying;

    private MetricHttpClient(final HttpClient underlying) {
        this.underlying = underlying;
    }

    @Override
    public CompletionStage<HttpResponse> execute(final HttpRequest httpRequest) {
        final Optional<Http.Context> contextOptional = Optional.ofNullable(Http.Context.current.get());
        final CompletionStage<HttpResponse> result = underlying.execute(httpRequest);
        final long startTimestamp = System.currentTimeMillis();
        contextOptional.ifPresent(context ->
                result.thenAccept(response -> {
                    final long stopTimestamp = System.currentTimeMillis();
                    report(context, httpRequest, response, startTimestamp, stopTimestamp);
                }));
        return result;
    }

    @SuppressWarnings("unchecked")
    private void report(final Http.Context context, final HttpRequest httpRequest, final HttpResponse response, long startTimestamp, long stopTimestamp) {
        final List<ReportRawData> data = (List<ReportRawData>) context.args.get(MetricAction.KEY);
        data.add(new ReportRawData(httpRequest, response, startTimestamp, stopTimestamp));
    }

    @Override
    public void close() {
        underlying.close();
    }

    public static MetricHttpClient of(final HttpClient underlying) {
        return new MetricHttpClient(underlying);
    }
}

package io.sphere.sdk.play.metrics;

import io.sphere.sdk.http.HttpClient;
import io.sphere.sdk.http.HttpRequest;
import io.sphere.sdk.http.HttpResponse;
import play.mvc.Http;

import java.util.List;
import java.util.Optional;
import java.util.concurrent.CompletionStage;

public class MetricHttpClient implements HttpClient {
    private final HttpClient underlying;

    private MetricHttpClient(final HttpClient underlying) {
        this.underlying = underlying;
    }

    @Override
    public CompletionStage<HttpResponse> execute(final HttpRequest httpRequest) {
        final Optional<Http.Context> contextOptional = Optional.ofNullable(Http.Context.current.get());
        final CompletionStage<HttpResponse> result = underlying.execute(httpRequest);
        final long startTimestamp = System.currentTimeMillis();
        contextOptional.ifPresent(context ->
                result.thenAccept(response -> {
                    final long stopTimestamp = System.currentTimeMillis();
                    report(context, httpRequest, response, startTimestamp, stopTimestamp);
                }));
        return result;
    }

    @SuppressWarnings("unchecked")
    private void report(final Http.Context context, final HttpRequest httpRequest, final HttpResponse response, long startTimestamp, long stopTimestamp) {
        final Optional<List<ReportRawData>> dataOption = Optional.ofNullable((List<ReportRawData>) context.args.get(MetricAction.KEY));
        dataOption.ifPresent(data -> data.add(new ReportRawData(httpRequest, response, startTimestamp, stopTimestamp)));
    }

    @Override
    public void close() {
        underlying.close();
    }

    public static MetricHttpClient of(final HttpClient underlying) {
        return new MetricHttpClient(underlying);
    }
}

Improve metric http client to deal with missing report data list.


package ca.junctionbox.cljbuck.build;

import org.junit.Test;

import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;

public class TestIntegration {
    @Test
    public void Test_fail() {
        assertThat("tests written: you've been a very naughty boy...", 0, is(10));
    }
}

package ca.junctionbox.cljbuck.build;

import org.junit.Test;

import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;

public class TestIntegration {
    @Test
    public void Test_fail() {
        assertThat("tests written: you've been a very naughty boy...", 0, is(0));
    }
}

Revert "Test failing build with buck-out/cache on Travis."


package org.nwapw.abacus.number;

public abstract class Function {

    protected abstract boolean matchesParams(Number[] params);
    protected abstract Number applyInternal(Number[] params);

    public Number apply(Number...params) {
        if(!matchesParams(params)) return null;
        return applyInternal(params);
    }

}

package org.nwapw.abacus.number;

import java.util.HashMap;

public abstract class Function {

    private static final HashMap<Class<? extends Number>, Integer> priorityMap =
            new HashMap<Class<? extends Number>, Integer>() {{
                put(NaiveNumber.class, 0);
            }};

    protected abstract boolean matchesParams(Number[] params);
    protected abstract Number applyInternal(Number[] params);

    public Number apply(Number...params) {
        if(!matchesParams(params)) return null;
        return applyInternal(params);
    }

}

Add a map to promoting priorities.


package com.freshplanet.ane.AirAACPlayer.functions;

import com.adobe.fre.FREContext;
import com.adobe.fre.FREFunction;
import com.adobe.fre.FREObject;
import com.freshplanet.ane.AirAACPlayer.Extension;
import com.freshplanet.ane.AirAACPlayer.ExtensionContext;

public class CloseFunction implements FREFunction
{

    @Override
    public FREObject call(FREContext context, FREObject[] arg1)
    {
        try
        {
            ExtensionContext extensionContext = (ExtensionContext) context;

            extensionContext.getPlayer().stop();
            extensionContext.getPlayer().release();
            extensionContext.setPlayer(null);
        }
        catch (Exception e)
        {
            Extension.context.dispatchStatusEventAsync("LOGGING", "[Error] Error on close");
            e.printStackTrace();
        }

        return null;
    }

}

package com.freshplanet.ane.AirAACPlayer.functions;

import com.adobe.fre.FREContext;
import com.adobe.fre.FREFunction;
import com.adobe.fre.FREObject;
import com.freshplanet.ane.AirAACPlayer.Extension;
import com.freshplanet.ane.AirAACPlayer.ExtensionContext;

public class CloseFunction implements FREFunction
{

    @Override
    public FREObject call(FREContext context, FREObject[] arg1)
    {
        try
        {
            ExtensionContext extensionContext = (ExtensionContext) context;

            extensionContext.getPlayer().stop();
            extensionContext.getPlayer().release();
            extensionContext.setMediaUrl(null);
            extensionContext.setPlayer(null);
        }
        catch (Exception e)
        {
            Extension.context.dispatchStatusEventAsync("LOGGING", "[Error] Error on close");
            e.printStackTrace();
        }

        return null;
    }

}

Add null url on close


package toolbox;

import java.util.ArrayList;

public class ActivationEmail implements IContentProvider
{

    private String activationKey;

    public ActivationEmail(String activationKey)
    {
        this.activationKey = activationKey;
    }

    @Override
    public ArrayList<String> getLines()
    {
        ArrayList<String> lines = new ArrayList<String>();

        lines.add("
Activation
");

        lines.add(String.format("Activate now", this.activationKey));

        return lines;
    }

}

Correct path to the activation link


package de.tudresden.inf.lat.born.main;

import java.awt.Dimension;
import java.util.Objects;

import javax.swing.JFrame;

import org.semanticweb.owlapi.apibinding.OWLManager;

/**
 * This is used to start the graphical user interface.
 *
 * @author Julian Mendez
 */
public class BornStandalone {

	/**
	 * Starts the application from the command line. The parameters are ignored.
	 *
	 * @param args
	 *            parameters (which are ignored)
	 */
	public static void main(String[] args) {
		Objects.requireNonNull(args);
		(new BornStandalone()).run();
	}

	/**
	 * Starts the graphical user interface.
	 */
	public void run() {
		BornStarter starter = new BornStarter(OWLManager.createOWLOntologyManager());
		JFrame frame = new JFrame();
		frame.add(starter.getPanel().getView().getPanel());
		frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
		frame.setSize(new Dimension(1024, 720));
		frame.setVisible(true);
	}

}

package de.tudresden.inf.lat.born.main;

import java.awt.Dimension;
import java.util.Objects;

import javax.swing.JFrame;

import org.semanticweb.owlapi.apibinding.OWLManager;

/**
 * This is used to start the graphical user interface.
 *
 * @author Julian Mendez
 */
public class BornStandalone {

	/**
	 * Starts the application from the command line. The parameters are ignored.
	 *
	 * @param args
	 *            parameters (which are ignored)
	 */
	public static void main(String[] args) {
		Objects.requireNonNull(args);
		(new BornStandalone()).run();
	}

	/**
	 * Starts the graphical user interface.
	 */
	public void run() {
		BornStarter starter = new BornStarter(OWLManager.createOWLOntologyManager());
		JFrame frame = new JFrame();
		frame.add(starter.getPanel().getView().getPanel());
		frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
		frame.setSize(new Dimension(1024, 800));
		frame.setVisible(true);
	}

}

Make small change in panel size


package net.java.sip.communicator.impl.osdependent.macosx;

import net.java.sip.communicator.impl.osdependent.*;

import com.apple.eawt.*;

/**
 * MacOSX specific dock icon, which will add a dock icon listener in order to
 * show the application each time user clicks on the dock icon.
 *
 * @author Yana Stamcheva
 */
@SuppressWarnings("deprecation")
public class MacOSXDockIcon
{
    /**
     * Adds a dock icon listener in order to show the application each time user
     * clicks on the dock icon.
     */
    public static void addDockIconListener()
    {
        Application application = Application.getApplication();
        if (application != null)
        {
            application.addApplicationListener(new ApplicationAdapter()
            {
                /**
                 * Handles re-open application event. Shows the contact list
                 * window.
                 */
                public void handleReOpenApplication(
                    ApplicationEvent applicationevent)
                {
                    OsDependentActivator.getUIService().setVisible(true);
                }
            });
        }
    }
}

package net.java.sip.communicator.impl.osdependent.macosx;

import net.java.sip.communicator.impl.osdependent.*;
import net.java.sip.communicator.service.gui.*;

import com.apple.eawt.*;

/**
 * MacOSX specific dock icon, which will add a dock icon listener in order to
 * show the application each time user clicks on the dock icon.
 *
 * @author Yana Stamcheva
 */
@SuppressWarnings("deprecation")
public class MacOSXDockIcon
{
    /**
     * Adds a dock icon listener in order to show the application each time user
     * clicks on the dock icon.
     */
    public static void addDockIconListener()
    {
        Application application = Application.getApplication();
        if (application != null)
        {
            application.addApplicationListener(new ApplicationAdapter()
            {
                /**
                 * Handles re-open application event. Shows the contact list
                 * window.
                 */
                public void handleReOpenApplication(
                    ApplicationEvent applicationevent)
                {
                    UIService uiService = OsDependentActivator.getUIService();

                    if (uiService != null && !uiService.isVisible())
                        uiService.setVisible(true);
                }
            });
        }
    }
}

Check if the UIService is already visible before setting it to visible.


package org.mydalayer.parsing.builder;

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

import org.mydalayer.client.support.Configuration;

/**
 *
 * @author mydalayer#gmail.com
 * @version 1.0.0
 */
public abstract class BaseBuilder {
  protected final Configuration configuration;

  public BaseBuilder(Configuration configuration) {
    this.configuration = configuration;
  }

  public Configuration getConfiguration() {
    return configuration;
  }

  /**
   * 功能描述：是否为空，为空则赋默认值

   * 返回值: Boolean <说明>
   */
  protected Boolean booleanValueOf(String value, Boolean defaultValue) {
    return value == null ? defaultValue : Boolean.valueOf(value);
  }

  /**
   * 功能描述：是否为空，为空则赋默认值

   * 返回值: Integer <说明>
   */
  protected Integer integerValueOf(String value, Integer defaultValue) {
    return value == null ? defaultValue : Integer.valueOf(value);
  }

  /**
   * 功能描述：是否为空，为空则赋默认值

   * 返回值: Set<String> <说明>
   */
  protected Set<String> stringSetValueOf(String value, String defaultValue) {
    String value1 = value == null ? defaultValue : value;
    return new HashSet<String>(Arrays.asList(value1.split(",")));
  }

}

package org.mydalayer.parsing.builder;

import org.mydalayer.client.support.Configuration;

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

/**
 *
 * @author mydalayer#gmail.com
 * @version 1.0.0
 */
public abstract class BaseBuilder {
  protected final Configuration configuration;

  public BaseBuilder(Configuration configuration) {
    this.configuration = configuration;
  }

  public Configuration getConfiguration() {
    return configuration;
  }

  /**
   * String "true"/"false" to Boolean Obj.

   *
   * @return Boolean
   */
  protected Boolean booleanValueOf(String value, Boolean defaultValue) {
    return value == null ? defaultValue : Boolean.valueOf(value);
  }

  /**
   * String number to Integer Obj.

   *
   * @return Integer
   */
  protected Integer integerValueOf(String value, Integer defaultValue) {
    return value == null ? defaultValue : Integer.valueOf(value);
  }

  /**
   * String str split by "," to Set Obj.

   *
   * @return Set type String
   */
  protected Set<String> stringSetValueOf(String value, String defaultValue) {
    String value1 = value == null ? defaultValue : value;
    return new HashSet<String>(Arrays.asList(value1.split(",")));
  }

}

Modify using Google Java code style and format


package me.eddiep.lifxbulb.rave.system;

import com.github.besherman.lifx.LFXHSBKColor;
import com.github.besherman.lifx.LFXLight;

import java.awt.*;

public class LightHolder {
    private LFXLight light;
    private Color originalColor;
    private int r, g, b;
    private int kelvin;

    public LightHolder(LFXLight light) {
        this.light = light;

        LFXHSBKColor color = light.getColor();
        this.originalColor = Color.getHSBColor(color.getHue(), color.getSaturation(), color.getBrightness());

        this.r = originalColor.getRed();
        this.g = originalColor.getGreen();
        this.b = originalColor.getBlue();
        this.kelvin = color.getKelvin();
    }

    public void raveWithValue(float num) {
        int newR = Math.min((int)(r * num), 255), newG = Math.min((int)(g * num), 255), newB = Math.min((int)(b * num), 255);

        Color color = new Color(newR, newG, newB);
        light.setColor(new LFXHSBKColor(color, kelvin));
    }
}

package me.eddiep.lifxbulb.rave.system;

import com.github.besherman.lifx.LFXHSBKColor;
import com.github.besherman.lifx.LFXLight;

import java.awt.*;

public class LightHolder {
    private LFXLight light;
    private Color originalColor;
    private int r, g, b;
    private int kelvin;

    public LightHolder(LFXLight light) {
        this.light = light;

        LFXHSBKColor color = light.getColor();
        this.originalColor = Color.getHSBColor(color.getHue(), color.getSaturation(), color.getBrightness());

        this.r = originalColor.getRed();
        this.g = originalColor.getGreen();
        this.b = originalColor.getBlue();
        this.kelvin = color.getKelvin();
    }

    public void raveWithValue(float num) {
        int newR = Math.min((int)(r * num), 255), newG = Math.min((int)(g * num), 255), newB = Math.min((int)(b * num), 255);

        Color color = new Color(newR, newG, newB);
        light.setColor(new LFXHSBKColor(color, kelvin), 1);
    }
}

Set fade duration to 1


package com.ebudgie;

import android.app.Application;
import android.util.Log;

import com.facebook.react.ReactApplication;
import io.underscope.react.fbak.RNAccountKitPackage;
import com.cboy.rn.splashscreen.SplashScreenReactPackage;
import com.oblador.vectoricons.VectorIconsPackage;
import com.facebook.react.ReactInstanceManager;
import com.facebook.react.ReactNativeHost;
import com.facebook.react.ReactPackage;
import com.facebook.react.shell.MainReactPackage;
import com.facebook.soloader.SoLoader;

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

public class MainApplication extends Application implements ReactApplication {

  private final ReactNativeHost mReactNativeHost = new ReactNativeHost(this) {
    @Override
    protected boolean getUseDeveloperSupport() {
      return BuildConfig.DEBUG;
    }

    @Override
    protected List<ReactPackage> getPackages() {
      return Arrays.<ReactPackage>asList(
          new MainReactPackage(),
            new RNAccountKitPackage(),
            new SplashScreenReactPackage(),
            new VectorIconsPackage()
      );
    }
  };

  @Override
  public ReactNativeHost getReactNativeHost() {
    return mReactNativeHost;
  }

  @Override
  public void onCreate() {
    super.onCreate();
    SoLoader.init(this, /* native exopackage */ false);
  }
}

package com.ebudgie;

import android.app.Application;
import android.util.Log;

import com.facebook.react.ReactApplication;
import io.underscope.react.fbak.RNAccountKitPackage;
import com.cboy.rn.splashscreen.SplashScreenReactPackage;
import com.oblador.vectoricons.VectorIconsPackage;
import com.facebook.react.modules.storage.ReactDatabaseSupplier;
import com.facebook.react.ReactInstanceManager;
import com.facebook.react.ReactNativeHost;
import com.facebook.react.ReactPackage;
import com.facebook.react.shell.MainReactPackage;
import com.facebook.soloader.SoLoader;

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

public class MainApplication extends Application implements ReactApplication {

  private final ReactNativeHost mReactNativeHost = new ReactNativeHost(this) {
    @Override
    protected boolean getUseDeveloperSupport() {
      return BuildConfig.DEBUG;
    }

    @Override
    protected List<ReactPackage> getPackages() {
      long size = 100L * 1024L * 1024L; // 100 MB
      ReactDatabaseSupplier.getInstance(getApplicationContext()).setMaximumSize(size);

      return Arrays.<ReactPackage>asList(
          new MainReactPackage(),
            new RNAccountKitPackage(),
            new SplashScreenReactPackage(),
            new VectorIconsPackage()
      );
    }
  };

  @Override
  public ReactNativeHost getReactNativeHost() {
    return mReactNativeHost;
  }

  @Override
  public void onCreate() {
    super.onCreate();
    SoLoader.init(this, /* native exopackage */ false);
  }
}

Increase the AsyncStorage capacity fromm 5mb to 100mb


package org.wikipedia.gallery;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.google.gson.annotations.SerializedName;

import org.apache.commons.lang3.StringUtils;

import java.io.Serializable;

@SuppressWarnings("unused")
public class MediaListItem implements Serializable {
    @Nullable private String title;
    @SerializedName("section_id") private int sectionId;
    @Nullable private String type;
    @Nullable private TextInfo caption;
    private boolean showInGallery;

    public MediaListItem() {
    }

    public MediaListItem(@NonNull String title) {
        this.title = title;
    }

    @NonNull
    public String getType() {
        return StringUtils.defaultString(type);
    }

    @Nullable
    public TextInfo getCaption() {
        return caption;
    }

    public boolean showInGallery() {
        return showInGallery;
    }

    @NonNull
    public String getTitle() {
        return StringUtils.defaultString(title);
    }
}

package org.wikipedia.gallery;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.google.gson.annotations.SerializedName;

import org.apache.commons.lang3.StringUtils;

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

@SuppressWarnings("unused")
public class MediaListItem implements Serializable {
    @Nullable private String title;
    @SerializedName("section_id") private int sectionId;
    @Nullable private String type;
    @Nullable private TextInfo caption;
    private boolean showInGallery;
    @Nullable @SerializedName("srcset") private List<ImageSrcSet> srcSets;

    public MediaListItem() {
    }

    public MediaListItem(@NonNull String title) {
        this.title = title;
    }

    @NonNull
    public String getType() {
        return StringUtils.defaultString(type);
    }

    @Nullable
    public TextInfo getCaption() {
        return caption;
    }

    public boolean showInGallery() {
        return showInGallery;
    }

    @NonNull
    public String getTitle() {
        return StringUtils.defaultString(title);
    }

    @NonNull
    public List<ImageSrcSet> getSrcSets() {
        return srcSets != null ? srcSets : Collections.emptyList();
    }

    public class ImageSrcSet implements Serializable {
        @Nullable private String src;
        @Nullable private String scale;

        @Nullable
        public String getSrc() {
            return src;
        }

        @Nullable
        public String getScale() {
            return scale;
        }
    }
}

Add src set data class for media-list endpoint


package org.clafer.ir;

import org.clafer.ir.IrQuickTest.Solution;
import static org.clafer.ir.Irs.*;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.chocosolver.solver.constraints.Constraint;
import org.chocosolver.solver.constraints.ICF;
import org.chocosolver.solver.variables.IntVar;

/**
 *
 * @author jimmy
 */
@RunWith(IrQuickTest.class)
public class IrAddTest {

    @Test(timeout = 60000)
    public IrBoolExpr setup(IrIntVar[] is, IrIntVar sum) {
        return equal(add(is), sum);
    }

    @Solution
    public Constraint setup(IntVar[] is, IntVar sum) {
        return ICF.sum(is, sum);
    }
}

package org.clafer.ir;

import org.clafer.ir.IrQuickTest.Solution;
import static org.clafer.ir.Irs.*;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.chocosolver.solver.constraints.Constraint;
import org.chocosolver.solver.constraints.ICF;
import org.chocosolver.solver.variables.IntVar;

/**
 *
 * @author jimmy
 */
@RunWith(IrQuickTest.class)
public class IrAddTest {

    @Test(timeout = 60000)
    public IrBoolExpr setup(IrIntVar[] is, IrIntVar sum) {
        return equal(add(is), sum);
    }

    @Solution
    public Constraint setup(IntVar[] is, IntVar sum) {
        return is.length > 0 ? ICF.sum(is, sum) : ICF.arithm(sum, "=", 0);
    }
}

Fix test for empty summation.


//
// $Id$

package playn.java;

import org.junit.Test;
import static org.junit.Assert.*;

import playn.core.PlayN;
import playn.core.Log;
import playn.core.Image;
import playn.tests.AbstractPlayNTest;

/**
 * Tests various JavaImage behavior.
 */
public class JavaImageTest extends AbstractPlayNTest {

  @Test
  public void testMissingImage() {
    final StringBuilder buf = new StringBuilder();
    PlayN.log().setCollector(new Log.Collector() {
      public void logged(Log.Level level, String msg, Throwable cause) {
        buf.append(msg).append("\n");
      }
    });

    Image missing;
    try {
      missing = PlayN.assets().getImage("missing.png");
    } finally {
      PlayN.log().setCollector(null);
    }

    assertNotNull(missing);

    // ensure that width/height do not NPE
    missing.width();
    missing.height();

    // TODO: depending on the error text is somewhat fragile, but I want to be sure that a
    // reasonably appropriate error was logged
    String errlog = buf.toString();
    assertTrue(errlog.startsWith("Could not load image"));
    assertTrue(errlog.contains("missing.png"));

  }
}

//
// $Id$

package playn.java;

import org.junit.Test;
import static org.junit.Assert.*;

import playn.core.PlayN;
import playn.core.Log;
import playn.core.Image;
import playn.tests.AbstractPlayNTest;

/**
 * Tests various JavaImage behavior.
 */
public class JavaImageTest extends AbstractPlayNTest {

  @Test
  public void testMissingImage() {
    final StringBuilder buf = new StringBuilder();
    PlayN.log().setCollector(new Log.Collector() {
      public void logged(Log.Level level, String msg, Throwable cause) {
        buf.append(msg).append("\n");
      }
    });

    Image missing;
    try {
      missing = PlayN.assets().getImageSync("missing.png");
    } finally {
      PlayN.log().setCollector(null);
    }

    assertNotNull(missing);

    // ensure that width/height do not NPE
    missing.width();
    missing.height();

    // TODO: depending on the error text is somewhat fragile, but I want to be sure that a
    // reasonably appropriate error was logged
    String errlog = buf.toString();
    assertTrue(errlog + " must contain 'Could not load image'",
               errlog.startsWith("Could not load image"));
    assertTrue(errlog + " must contain 'missing.png'",
               errlog.contains("missing.png"));
  }
}

Load the missing image synchronously, improve assert error messages.


package de.cketti.matelight;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.Socket;

public class MateLight {
    private static final String HOST = "matelight.cbrp3.c-base.org";
    private static final int PORT = 1337;
    private static final String SUCCESS = "KTHXBYE!";
    private static final int TIMEOUT = 60 * 1000;

    private Socket mSocket;

    public void sendMessage(String message) throws IOException {
        mSocket = new Socket();
        mSocket.connect(new InetSocketAddress(HOST, PORT));
        try {
            OutputStream out = mSocket.getOutputStream();
            try {
                mSocket.setSoTimeout(TIMEOUT);

                out.write(message.getBytes());
                out.write('\n');
                out.flush();

                InputStream in = mSocket.getInputStream();
                try {
                    BufferedReader buf = new BufferedReader(new InputStreamReader(in));
                    String response = buf.readLine();

                    if (!SUCCESS.equals(response)) {
                        throw new RuntimeException("No success message from server");
                    }
                } finally {
                    in.close();
                }
            } finally {
                out.close();
            }
        } finally {
            mSocket.close();
        }
    }

    public void cancel() {
        try {
            mSocket.close();
        } catch (Exception e) {
            // ignore
        }
    }
}

package de.cketti.matelight;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.Socket;

public class MateLight {
    private static final String HOST = "ml.jaseg.net";
    private static final int PORT = 1337;
    private static final String SUCCESS = "KTHXBYE!";
    private static final int TIMEOUT = 60 * 1000;

    private Socket mSocket;

    public void sendMessage(String message) throws IOException {
        mSocket = new Socket();
        mSocket.connect(new InetSocketAddress(HOST, PORT));
        try {
            OutputStream out = mSocket.getOutputStream();
            try {
                mSocket.setSoTimeout(TIMEOUT);

                out.write(message.getBytes());
                out.write('\n');
                out.flush();

                InputStream in = mSocket.getInputStream();
                try {
                    BufferedReader buf = new BufferedReader(new InputStreamReader(in));
                    String response = buf.readLine();

                    if (!SUCCESS.equals(response)) {
                        throw new RuntimeException("No success message from server");
                    }
                } finally {
                    in.close();
                }
            } finally {
                out.close();
            }
        } finally {
            mSocket.close();
        }
    }

    public void cancel() {
        try {
            mSocket.close();
        } catch (Exception e) {
            // ignore
        }
    }
}

Change host name to ml.jaseg.net


package fp.grados.tipos;

import java.time.LocalDate;
import java.util.Comparator;
import java.util.Optional;
import java.util.SortedMap;
import java.util.TreeMap;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class AlumnoImpl2 extends AlumnoImpl implements Alumno {

	public AlumnoImpl2(String DNI, String nombre, String apellidos, LocalDate fecha, String email){
		super(DNI, nombre, apellidos, fecha, email);
	}

	public AlumnoImpl2(String s) {
		super(s);
	}

	@Override
	public Integer getCurso() {
		Integer res = 0;
		Stream<Asignatura> stream = this.getAsignaturas().stream();
		Optional<Asignatura> opt = stream.max(Comparator.comparing(Asignatura::getCurso));
		if(opt.isPresent()) {
			res = opt.get().getCurso();
		}

		return res;
	}

	public SortedMap<Asignatura, Calificacion> getCalificacionPorAsignatura() {
		return this.getExpediente().getNotas().stream().collect(Collectors.toMap(Nota::getAsignatura, Nota::getCalificacion, (p1, p2) -> p1, TreeMap::new));
	}
}

package fp.grados.tipos;

import java.time.LocalDate;
import java.util.Comparator;
import java.util.Map;
import java.util.Optional;
import java.util.SortedMap;
import java.util.TreeMap;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class AlumnoImpl2 extends AlumnoImpl implements Alumno {

	public AlumnoImpl2(String DNI, String nombre, String apellidos, LocalDate fecha, String email){
		super(DNI, nombre, apellidos, fecha, email);
	}

	public AlumnoImpl2(String s) {
		super(s);
	}

	@Override
	public Integer getCurso() {
		Integer res = 0;
		Stream<Asignatura> stream = this.getAsignaturas().stream();
		Optional<Asignatura> opt = stream.max(Comparator.comparing(Asignatura::getCurso));
		if(opt.isPresent()) {
			res = opt.get().getCurso();
		}

		return res;
	}

	public SortedMap<Asignatura, Calificacion> getCalificacionPorAsignatura() {
		Map<Asignatura, Calificacion> res = getExpediente().getNotas().stream().collect(Collectors.toMap(n -> n.getAsignatura(), n -> n.getCalificacion(), (p1, p2)->calificacionMayor(p1, p2)));
		return new TreeMap<Asignatura, Calificacion>(res);
	}

	private Calificacion calificacionMayor(Calificacion c1, Calificacion c2) {
		if (c1.compareTo(c2) >= 0) {
			return c1;
		} else {
			return c2;
		}
	}

}

Fix ALL failures in Java


import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/location")
public class LocationServlet extends HttpServlet {
    private Double latitude = 0.0;
    private Double longitude = 0.0;
    private final String BASE_URL = "https://maps.googleapis.com/maps/api/geocode/json?";
    private final String API_KEY = ""; // Insert actual API key to test.

    @Override
    public void doGet(HttpServletRequest request, HttpServletResponse response) {

    }

}

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/location")
public class LocationServlet extends HttpServlet {
    private double latitude = 0.0;
    private double longitude = 0.0;
    private final String BASE_URL = "https://maps.googleapis.com/maps/api/geocode/json?";
    private final String API_KEY = ""; // Insert actual API key to test.

    @Override
    public void doGet(HttpServletRequest request, HttpServletResponse response) {
      String queryParam = String.format("latlng=%1$f,%2$f", latitude, longitude);
      String apiKeyParam = String.format("&key=%s", API_KEY);
      String fullPath = BASE_URL + queryParam + apiKeyParam;
      try {
        URL url = new URL(queryPath);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("GET");
        connection.connect();
        int responseCode = connection.getResponseCode();
        if (responseCode == 200) {
          String json = getJson(url);
          System.out.println(json); // test
        } else {
          System.out.println("Error: connection response code is: " + responseCode);
        }
      } catch(Exception e) {
        e.printStackTrace();
     }
    }

    public void getJson() {
      // TODO: implement this method.
    }

}

Implement doGet for location servlet (not yet tested.


package com.coreoz.plume.file.services.cache;

import java.util.concurrent.TimeUnit;
import java.util.function.Function;

import javax.inject.Singleton;

import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;

@Singleton
public class FileCacheServiceGuava implements FileCacheService {

	@Override
	public LoadingCache<Long, CachedFile> newCache(Function<Long, CachedFile> loadingData) {
		return CacheBuilder
			.newBuilder()
			.expireAfterWrite(1, TimeUnit.HOURS)
			.maximumSize(100)
			.build(CacheLoader.from(loadingData::apply));
	}

}

package com.coreoz.plume.file.services.cache;

import java.util.concurrent.TimeUnit;
import java.util.function.Function;

import javax.inject.Singleton;

import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;

@Singleton
public class FileCacheServiceGuava implements FileCacheService {

	@Override
	public LoadingCache<Long, CachedFile> newCache(Function<Long, CachedFile> loadingData) {
		return CacheBuilder
			.newBuilder()
			.expireAfterAccess(1, TimeUnit.DAYS)
			.maximumSize(100)
			.build(CacheLoader.from(loadingData::apply));
	}

}

Remove only unused files from cache


/*
 * Author:  Filip Dvořák <filip.dvorak@runbox.com>
 *
 * Copyright (c) 2013 Filip Dvořák <filip.dvorak@runbox.com>, all rights reserved
 *
 * Publishing, providing further or using this program is prohibited
 * without previous written permission of the author. Publishing or providing
 * further the contents of this file is prohibited without previous written
 * permission of the author.
 */
package fape.scripting;

import fape.core.planning.Planner;
import java.io.File;
import java.io.FileFilter;

/**
 *
 * @author FD
 */
public class Exp1 extends ExperimentRunner {

    public static void main(String[] args) throws InterruptedException {
        run("C:/ROOT/PROJECTS/fape/FAPE/problems/generated");
    }

}

/*
 * Author:  Filip Dvořák <filip.dvorak@runbox.com>
 *
 * Copyright (c) 2013 Filip Dvořák <filip.dvorak@runbox.com>, all rights reserved
 *
 * Publishing, providing further or using this program is prohibited
 * without previous written permission of the author. Publishing or providing
 * further the contents of this file is prohibited without previous written
 * permission of the author.
 */
package fape.scripting;

import fape.core.planning.Planner;
import java.io.File;
import java.io.FileFilter;

/**
 *
 * @author FD
 */
public class Exp1 extends ExperimentRunner {

    public static void main(String[] args) throws InterruptedException {
        run("problems/generated");
    }

}

Make the problems/generated directory usage relative


package org.slc.sli.util;

import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;

import org.slc.sli.security.SLIPrincipal;

/**
 * Class, which allows user to access security context
 * @author svankina
 *
 */
public class SecurityUtil {

    public static UserDetails getPrincipal() {
        return  (UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
    }

    public static String getToken() {
        UserDetails user = getPrincipal();
        if (user instanceof SLIPrincipal) {
            return ((SLIPrincipal) user).getId();
        }

        return null;
    }

}

package org.slc.sli.util;

import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;

import org.slc.sli.security.SLIPrincipal;

/**
 * Class, which allows user to access security context
 * @author svankina
 *
 */
public class SecurityUtil {

    public static UserDetails getPrincipal() {
        return  (UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
    }

    public static String getToken() {
        UserDetails user = getPrincipal();
        if (user instanceof SLIPrincipal) {
            return ((SLIPrincipal) user).getId();
        } else {
            // gets here in mock server mode
            return user.getUsername();
        }
    }

}

Make security util to work for mock dashboard server mode.


package com.fasterxml.sort.util;

import java.io.IOException;
import java.io.InterruptedIOException;
import java.util.concurrent.BlockingQueue;

import com.fasterxml.sort.DataReader;

/**
 * Base implementation for {@link DataReader} that uses a
 * {@link BlockingQueue} for getting input.
 * The only missing part is implementation for
 * {@link #estimateSizeInBytes(Object)}, since there is no way
 * to provide a meaningful estimate without knowing object type.
 */
public abstract class BlockingQueueReader<E>
    extends DataReader<E>
{
    protected final BlockingQueue<E> _queue;

    public BlockingQueueReader(BlockingQueue<E> q) {
        _queue = q;
    }

    @Override
    public void close() throws IOException {
        // no-op
    }

    @Override
    public abstract int estimateSizeInBytes(E item);

    @Override
    public E readNext() throws IOException {
        try {
            return _queue.take();
        } catch (InterruptedException e) {
            InterruptedIOException ie = new InterruptedIOException();
            ie.initCause(e);
            throw ie;
        }
    }

}

package com.fasterxml.sort.util;

import java.io.IOException;
import java.io.InterruptedIOException;
import java.util.concurrent.BlockingQueue;

import com.fasterxml.sort.DataReader;

/**
 * Base implementation for {@link DataReader} that uses a
 * {@link BlockingQueue} for getting input.
 * The only missing part is implementation for
 * {@link #estimateSizeInBytes(Object)}, since there is no way
 * to provide a meaningful estimate without knowing object type.
 */
public abstract class BlockingQueueReader<E>
    extends DataReader<E>
{
    protected final BlockingQueue<E> _queue;

    protected final E _endMarker;

    protected boolean _closed;

    @Deprecated
    public BlockingQueueReader(BlockingQueue<E> q) {
        this(q, null);
    }

    /**
     * @param q Queue to read entries from
     * @param endMarker Value that is used to signal end-of-input; when this value
     *   is gotten from queue, reader assumes that no more input is coming and
     *   will return null from {@link #readNext}.
     */
    public BlockingQueueReader(BlockingQueue<E> q, E endMarker) {
        _queue = q;
        _endMarker = endMarker;
    }

    @Override
    public void close() throws IOException {
        _closed = true;
    }

    @Override
    public abstract int estimateSizeInBytes(E item);

    @Override
    public E readNext() throws IOException {
        if (_closed) {
            return null;
        }
        try {
            E value = _queue.take();
            if (value == _endMarker) {
                _closed = true;
                return null;
            }
            return value;
        } catch (InterruptedException e) {
            InterruptedIOException ie = new InterruptedIOException();
            ie.initCause(e);
            throw ie;
        }
    }
}

Add support for end-marker token


package net.darkmist.alib.generics;

public class GenericFudge
{
	@SuppressWarnings("unchecked")
	static public <T> Class<? extends T> getClass(T obj)
	{
		return (Class<? extends T>)obj.getClass();
	}
}

package net.darkmist.alib.generics;

import java.util.Map;

/**
 * Static methods to get around issues with generics...
 */
@SuppressWarnings("unchecked")
public class GenericFudge
{
	/** Only static methods. */
	private GenericFudge()
	{
	}

	/**
	 * Fudge the return from getClass to include the generic.
	 */
	static public <T> Class<? extends T> getClass(T obj)
	{
		return (Class<? extends T>)obj.getClass();
	}

	/**
	 * Fudge a ungenericified map to be one.
	 */
	static public <K,V> Map<K,V> map(Map map)
	{
		return map;
	}
}

Add method to allow ungenericed map to genericed map fudge


package fi.evident.apina.model.settings;

import fi.evident.apina.utils.PatternSet;

import java.util.Collection;
import java.util.Set;
import java.util.TreeMap;
import java.util.TreeSet;

import static java.util.Collections.unmodifiableCollection;

/**
 * Various settings guiding the translation.
 */
public final class TranslationSettings {

    public final PatternSet blackBoxClasses = new PatternSet();
    private final TreeMap<String, ImportDefinition> importsByModule = new TreeMap<>();
    private final Set<String> importedTypes = new TreeSet<>();

    public boolean isBlackBoxClass(String name) {
        return blackBoxClasses.test(name);
    }

    public void addImport(String typeName, String moduleName) {
        if (!importedTypes.add(typeName))
            throw new IllegalArgumentException("type " + typeName + " is already imported");

        importsByModule.computeIfAbsent(moduleName, ImportDefinition::new).addType(typeName);
    }

    public Collection<ImportDefinition> getImports() {
        return unmodifiableCollection(importsByModule.values());
    }

    public boolean isImported(String typeName) {
        return importedTypes.contains(typeName);
    }
}

package fi.evident.apina.model.settings;

import fi.evident.apina.utils.PatternSet;

import java.util.Collection;
import java.util.Set;
import java.util.TreeMap;
import java.util.TreeSet;

import static java.util.Collections.unmodifiableCollection;

/**
 * Various settings guiding the translation.
 */
public final class TranslationSettings {

    public final PatternSet blackBoxClasses = new PatternSet();
    private final TreeMap<String, ImportDefinition> importsByModule = new TreeMap<>();
    private final Set<String> importedTypes = new TreeSet<>();

    public boolean isBlackBoxClass(String name) {
        return blackBoxClasses.test(name);
    }

    public void addImport(String moduleName, Collection<String> types) {
        ImportDefinition importDefinition = importsByModule.computeIfAbsent(moduleName, ImportDefinition::new);

        for (String type : types) {
            if (!importedTypes.add(type))
                throw new IllegalArgumentException("type " + type + " is already imported");

            importDefinition.addType(type);
        }
    }

    public Collection<ImportDefinition> getImports() {
        return unmodifiableCollection(importsByModule.values());
    }

    public boolean isImported(String typeName) {
        return importedTypes.contains(typeName);
    }
}

Allow multiple types to be imported with single call


package com.jcwhatever.bukkit.musical;

import com.jcwhatever.bukkit.generic.GenericsPlugin;
import com.jcwhatever.bukkit.musical.commands.CommandHandler;
import com.jcwhatever.bukkit.musical.regions.RegionManager;
import org.bukkit.ChatColor;

public class MusicalRegions extends GenericsPlugin {

	private static MusicalRegions _instance;

	private RegionManager _regionManager;

	public static MusicalRegions getInstance() {
		return _instance;
	}

	public MusicalRegions() {
		super();
	}

	@Override
	protected void init() {
		_instance = this;
	}

    @Override
	public String getChatPrefix() {
		return ChatColor.LIGHT_PURPLE + "[Music] " + ChatColor.RESET;
	}

	@Override
	public String getConsolePrefix() {
		return "[Music] ";
	}

	public RegionManager getRegionManager() {
		return _regionManager;
	}

    @Override
    protected void onEnablePlugin() {
        registerCommands(new CommandHandler());
        registerEventListeners(new EventListener());

        _regionManager = new RegionManager(this.getSettings().getNode("regions"));
    }

    @Override
    protected void onDisablePlugin() {

    }

}

package com.jcwhatever.bukkit.musical;

import com.jcwhatever.bukkit.generic.GenericsPlugin;
import com.jcwhatever.bukkit.musical.commands.CommandHandler;
import com.jcwhatever.bukkit.musical.regions.RegionManager;
import org.bukkit.ChatColor;

public class MusicalRegions extends GenericsPlugin {

	private static MusicalRegions _instance;

	private RegionManager _regionManager;

	public static MusicalRegions getInstance() {
		return _instance;
	}

	public MusicalRegions() {
		super();
	}

	@Override
	protected void init() {
		_instance = this;
	}

    @Override
	public String getChatPrefix() {
		return ChatColor.LIGHT_PURPLE + "[Music] " + ChatColor.RESET;
	}

	@Override
	public String getConsolePrefix() {
		return "[Music] ";
	}

	public RegionManager getRegionManager() {
		return _regionManager;
	}

    @Override
    protected void onEnablePlugin() {
        registerCommands(new CommandHandler());
        registerEventListeners(new EventListener());

        _regionManager = new RegionManager(this.getDataNode().getNode("regions"));
    }

    @Override
    protected void onDisablePlugin() {

    }

}

Add comments to GenericsPlugin, refactor GenericsPlugin.getSettings to getDataNode


package uk.ac.ebi.quickgo.ontology.traversal.read;

/**
 * Enumeration representing the columns of the relationship source files.
 *
 * CHILD_ID, PARENT_ID, RELATIONSHIP_TYPE
 *
 * Created 18/05/16
 * @author Edd
 */
public enum Columns {
    COLUMN_CHILD(0, "child"),
    COLUMN_PARENT(1, "parent"),
    COLUMN_RELATIONSHIP(2,"relationship");

    private int position;
    private String columnName;

    Columns(int position, String columnName) {
        this.position = position;
        this.columnName = columnName;
    }

    public int getPosition() {
        return position;
    }

    public String getName() {
        return columnName;
    }

    public static int numColumns() {
        return Columns.values().length;
    }
}

package uk.ac.ebi.quickgo.ontology.traversal.read;

/**
 * Enumeration representing the columns of the relationship source files.
 *
 * Columns: CHILD_ID, PARENT_ID, RELATIONSHIP_TYPE
 *
 * Created 18/05/16
 * @author Edd
 */
public enum Columns {
    COLUMN_CHILD(0, "child"),
    COLUMN_PARENT(1, "parent"),
    COLUMN_RELATIONSHIP(2,"relationship");

    private int position;
    private String columnName;

    Columns(int position, String columnName) {
        this.position = position;
        this.columnName = columnName;
    }

    public int getPosition() {
        return position;
    }

    public String getName() {
        return columnName;
    }

    public static int numColumns() {
        return Columns.values().length;
    }
}

Clarify comments for columns of the ontology relations datafiles


package com.google.maps.android.data.kml;

import com.google.maps.android.data.Geometry;

import java.util.ArrayList;

/**
 * Created by thorin on 22/02/2017.
 */

public class KmlMultiTrack extends KmlMultiGeometry {
    /**
     * Creates a new MultiGeometry object
     *
     * @param tracks array of KmlTrack objects contained in the MultiGeometry
     */
    public KmlMultiTrack(ArrayList<KmlTrack> tracks) {
        super(createGeometries(tracks));
    }

    private static ArrayList<Geometry> createGeometries(ArrayList<KmlTrack> tracks) {
        ArrayList <Geometry> geometries = new ArrayList<>();

        for (KmlTrack track : tracks) {
            geometries.add(track);
        }

        return geometries;
    }
}

package com.google.maps.android.data.kml;

import com.google.maps.android.data.Geometry;

import java.util.ArrayList;

/**
 * Created by thorin on 22/02/2017.
 */

public class KmlMultiTrack extends KmlMultiGeometry {
    /**
     * Creates a new MultiGeometry object
     *
     * @param tracks array of KmlTrack objects contained in the MultiGeometry
     */
    public KmlMultiTrack(ArrayList<KmlTrack> tracks) {
        super(createGeometries(tracks));
    }

    private static ArrayList<Geometry> createGeometries(ArrayList<KmlTrack> tracks) {
        ArrayList <Geometry> geometries = new ArrayList<>();

        if (tracks == null) {
            throw new IllegalArgumentException("Tracks cannot be null");
        }

        for (KmlTrack track : tracks) {
            geometries.add(track);
        }

        return geometries;
    }
}

Throw IllegalArgumentException if constructor is called with a null argument


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

BREAK BUILD

/**
 * Interface implemented by components that can be named, such as via configuration, and wish to have that name
 * set once it has been configured.
 *
 * @author Les Hazlewood
 * @since 0.9
 */
public interface Nameable {

    /**
     * Sets the (preferably application unique) name for this component.
     * @param name the preferably application unique name for this component.
     */
    void setName(String name);
}

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

/**
 * Interface implemented by components that can be named, such as via configuration, and wish to have that name
 * set once it has been configured.
 *
 * @author Les Hazlewood
 * @since 0.9
 */
public interface Nameable {

    /**
     * Sets the (preferably application unique) name for this component.
     * @param name the preferably application unique name for this component.
     */
    void setName(String name);
}

Fix the build to test Hudson


package guitests;

import static org.junit.Assert.assertTrue;

import org.junit.Test;

public class ClearCommandTest extends TaskManagerGuiTest {

    @Test
    public void clear() {

        //verify a non-empty list can be cleared
        assertTrue(taskListPanel.isListMatching(td.getTypicalTasks()));
        assertClearCommandSuccess();

        //verify other commands can work after a clear command
        commandBox.runCommand(td.hoon.getAddCommand());
        assertTrue(taskListPanel.isListMatching(td.hoon));
        commandBox.runCommand("delete 1");
        assertListSize(0);

        //verify clear command works when the list is empty
        assertClearCommandSuccess();
    }

    private void assertClearCommandSuccess() {
        commandBox.runCommand("clear");
        assertListSize(0);
        assertResultMessage("Task manager has been cleared!");
    }
}

package guitests;

import static org.junit.Assert.assertTrue;

import org.junit.Test;

public class ClearCommandTest extends TaskManagerGuiTest {

    @Test
    public void clear() {

        //verify a non-empty list can be cleared
        assertTrue(taskListPanel.isListMatching(td.getTypicalTasks()));
        assertClearCommandSuccess();

        //verify other commands can work after a clear command
        commandBox.runCommand(td.hoon.getAddCommand());
        assertTrue(taskListPanel.isListMatching(td.hoon));
        commandBox.runCommand("delete 1");
        assertListSize(0);

        //verify clear command works when the list is empty
        assertClearCommandSuccess();
    }

    private void assertClearCommandSuccess() {
        commandBox.runCommand("clear");
        assertListSize(0);
        assertResultMessage("Task Manager has been cleared!");
    }
}

Change clear command success message


package com.ushahidi.android.domain.repository;

import com.ushahidi.android.domain.entity.FormAttribute;
import com.ushahidi.android.domain.entity.From;

import java.util.List;

import rx.Observable;

/**
 * @author Ushahidi Team <team@ushahidi.com>
 */
public interface FormAttributeRepository {

    /**
     * Get a list of {@link FormAttribute} from either the database or online.
     *
     * @param deploymentId An ID of {@link com.ushahidi.android.domain.entity.Deployment}
     * @param from         Where to get the formattribute from. Either from local storage or online
     * @return The retrieved form attribute.
     */
    Observable<List<FormAttribute>> getForms(Long deploymentId, From from);

    /**
     * Add/Update a {@link FormAttribute}.
     *
     * @param form The FormAttribute to be saved.
     * @return The row affected
     */
    Observable<Long> putForm(FormAttribute form);
}

Add repo for form attribute


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

import org.junit.Test;
import static org.junit.Assert.*;

public class ChangeEventTest {

  @Test
  public void shouldRejectMissingMandatoryFields() {
    ChangeEvent bogusEvent = new ChangeEvent();
    assertFalse(bogusEvent.containsMandatoryFields());
  }

  @Test
  public void shouldAcceptMinimumFields() {
    ChangeEvent validEvent = new ChangeEvent();
    validEvent.setId("id");
    validEvent.setVersion("vsn");
    assertTrue(validEvent.containsMandatoryFields());
  }
}

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

import org.junit.Test;
import org.junit.experimental.theories.DataPoint;
import org.junit.experimental.theories.Theories;
import org.junit.experimental.theories.Theory;
import org.junit.runner.RunWith;

import static org.junit.Assert.*;

@RunWith(Theories.class)
public class ChangeEventTest {

  @DataPoint public static ChangeEvent completelyEmptyEvent = new ChangeEvent();
  @DataPoint public static ChangeEvent nullIdWithValidVersion = new ChangeEvent(null,"vsn", null, null, null);
  @DataPoint public static ChangeEvent emptyIdWithValidVersion = new ChangeEvent("" ,"vsn", null, null, null);
  @DataPoint public static ChangeEvent validIdWithEmptyVersion = new ChangeEvent("id" , "", null, null, null);
  @DataPoint public static ChangeEvent validIdWithNullVersion = new ChangeEvent("id" , null, null, null, null);

  @Theory
  public void shouldRejectMissingMandatoryFields(ChangeEvent bogusEvent) {
    assertFalse(bogusEvent.containsMandatoryFields());
  }

  @Test
  public void shouldAcceptMinimumFields() {
    ChangeEvent validEvent = new ChangeEvent();
    validEvent.setId("id");
    validEvent.setVersion("vsn");
    assertTrue(validEvent.containsMandatoryFields());
  }
}

Add some more data points to ChangeEvent check


package prims;

import prims.Prims;

/*
	This class tests class Prims (Minimum Spanning Tree Algorithm)
*/

class TestPrims{

	// Tests MST and prints MST edges

	public static void testMST1(){

		int N = 9;		// No. of Vertices
		int M = 14;		// No. of Edges

		int[][] edges = {	{1,2,4}, 	// Edges
							{1,8,8},
							{2,8,11},
							{2,3,8},
							{3,4,7},
							{3,9,2},
							{3,6,4},
							{4,6,14},
							{4,5,9},
							{5,6,10},
							{6,7,2},
							{7,8,1},
							{7,9,6},
							{8,9,7}
						  };

		Prims prims = new Prims(N, M, edges);
		prims.findMST();
		System.out.println("MST Edges are: ");
		prims.printMSTEdges();
	}

	public static void main(String args[]){

		// Call testMST1
		testMST1();
	}
}

Add test class for prims MST


package hudson.plugins.git.browser;

import hudson.plugins.git.GitChangeSet;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import org.junit.Test;
import static org.junit.Assert.*;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;

@RunWith(Parameterized.class)
public class GitilesTest {

    private final String repoUrl = "https://gwt.googlesource.com/gwt/";

    private final boolean useAuthorName;
    private final GitChangeSetSample sample;

    public GitilesTest(String useAuthorName) {
        this.useAuthorName = Boolean.valueOf(useAuthorName);
        sample = new GitChangeSetSample(this.useAuthorName);
    }

    @Parameterized.Parameters(name = "{0}")
    public static Collection permuteAuthorName() {
        List<Object[]> values = new ArrayList<Object[]>();
        String[] allowed = {"true", "false"};
        for (String authorName : allowed) {
            Object[] combination = {authorName};
            values.add(combination);
        }
        return values;
    }

    @Test
    public void testGetChangeSetLink() throws Exception {
        URL result = (new Gitiles(repoUrl)).getChangeSetLink(sample.changeSet);
        assertEquals(new URL(repoUrl + "+/" + sample.id + "%5E%21"), result);
    }

    @Test
    public void testGetDiffLink() throws Exception {
        Gitiles gitiles = new Gitiles(repoUrl);
        for (GitChangeSet.Path path : sample.changeSet.getPaths()) {
            URL diffLink = gitiles.getDiffLink(path);
            URL expectedDiffLink = new URL(repoUrl + "+/" + sample.id + "%5E%21");
            String msg = "Wrong link for path: " + path.getPath() + ", edit type: " + path.getEditType().getName();
            assertEquals(msg, expectedDiffLink, diffLink);
        }
    }

    @Test
    public void testGetFileLink() throws Exception {
        Gitiles stash = new Gitiles(repoUrl);
        for (GitChangeSet.Path path : sample.changeSet.getPaths()) {
            URL fileLink = stash.getFileLink(path);
            URL expectedFileLink = new URL(repoUrl + "+blame/" + sample.id + "/" + path.getPath());
            String msg = "Wrong link for path: " + path.getPath() + ", edit type: " + path.getEditType().getName();
            assertEquals(msg, expectedFileLink, fileLink);
        }
    }
}

Add test for Gitiles repo browser


package org.apache.ddlutils.platform;

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

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

import org.apache.ddlutils.PlatformInfo;
import org.apache.ddlutils.TestPlatformBase;
import org.apache.ddlutils.model.Database;

/**
 * Test the SqlBuilder (abstract) class.
 *
 * @author Martin van den Bemt
 * @version $Revision: $
 */
public class SqlBuilderTest extends TestPlatformBase {

    String xml = "<?xml version='1.0' encoding='ISO-8859-1'?>\n"+
                 "<database name='ddlutils'>\n"+
                 "
\n"+
                 "    <column name='id' autoIncrement='true' type='INTEGER' primaryKey='true'/>\n"+
                 "    <column name='name' type='VARCHAR' size='15'/>\n"+
                 "
\n"+
                 "</database>";

    public void setUp()
    {
    }

    /**
     * Test the updateSql method
     */
    public void testUpdateSql()
    {
        SqlBuilder sqlBuilder = new SqlBuilderImpl(new PlatformInfo());
        Database database = parseDatabaseFromString(xml);
        Map map = new HashMap();
        map.put("name", "ddlutils");
        map.put("id", new Integer(0));
        String sql = sqlBuilder.getUpdateSql(database.getTable(0), map, false);
        assertEquals("UPDATE \"TestTable\" SET \"name\" = 'ddlutils' WHERE \"id\" = '0'", sql);
    }

    protected String getDatabaseName() {
        return null;
    }

    public class SqlBuilderImpl extends SqlBuilder {

        public SqlBuilderImpl(PlatformInfo info) {
            super(info);
        }
    }
}

Add test for updateSql. Far from complete, but a start..