/*
 * Copyright 2016 Lime - HighTech Solutions 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 io.getlime.rest.api.security.filter;

import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.container.ContainerRequestContext;
import javax.ws.rs.container.ContainerRequestFilter;
import javax.ws.rs.core.Context;
import java.io.IOException;

/**
 * Request filter that intercepts the request body, forwards it to the controller
 * as a request attribute named "X-PowerAuth-Request-Body" and resets the stream.
 *
 * @author Petr Dvorak
 *
 */
public class PowerAuthRequestFilter implements ContainerRequestFilter {

    @Context
    private HttpServletRequest httpRequest;

    @Override
    public void filter(ContainerRequestContext requestContext) throws IOException {
        PowerAuthRequestFilterBase.filterRequest(httpRequest);
    }

}

/*
 * Copyright 2016 Lime - HighTech Solutions 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 io.getlime.rest.api.security.filter;

import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.container.ContainerRequestContext;
import javax.ws.rs.container.ContainerRequestFilter;
import javax.ws.rs.core.Context;
import javax.ws.rs.ext.Provider;
import java.io.IOException;

/**
 * Request filter that intercepts the request body, forwards it to the controller
 * as a request attribute named "X-PowerAuth-Request-Body" and resets the stream.
 *
 * @author Petr Dvorak
 *
 */
@Provider
public class PowerAuthRequestFilter implements ContainerRequestFilter {

    @Context
    private HttpServletRequest httpRequest;

    @Override
    public void filter(ContainerRequestContext requestContext) throws IOException {
        PowerAuthRequestFilterBase.filterRequest(httpRequest);
    }

}

Use Provider annotation in filter with injected Context


package com.paritytrading.nassau.binaryfile;

import static com.paritytrading.nassau.Strings.*;
import static java.util.Arrays.*;
import static org.junit.Assert.*;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.util.List;
import org.junit.Test;

public class BinaryFILEWriterTest {

    @Test
    public void write() throws Exception {
        ByteArrayOutputStream stream = new ByteArrayOutputStream();

        BinaryFILEWriter writer = new BinaryFILEWriter(stream);

        List<String> messages = asList("foo", "bar", "baz", "quux", "");

        for (String message : messages)
            writer.write(wrap(message));

        byte[] writtenBytes  = stream.toByteArray();
        byte[] expectedBytes = toByteArray(getClass().getResourceAsStream("/binaryfile.dat"));

        assertArrayEquals(expectedBytes, writtenBytes);
    }

    private byte[] toByteArray(InputStream input) throws Exception {
        ByteArrayOutputStream output = new ByteArrayOutputStream();

        int b;

        while ((b = input.read()) != -1)
            output.write(b);

        return output.toByteArray();
    }

}

package com.paritytrading.nassau.binaryfile;

import static com.paritytrading.nassau.Strings.*;
import static java.util.Arrays.*;
import static org.junit.Assert.*;

import java.io.ByteArrayOutputStream;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;
import org.junit.Test;

public class BinaryFILEWriterTest {

    @Test
    public void write() throws Exception {
        ByteArrayOutputStream stream = new ByteArrayOutputStream();

        BinaryFILEWriter writer = new BinaryFILEWriter(stream);

        List<String> messages = asList("foo", "bar", "baz", "quux", "");

        for (String message : messages)
            writer.write(wrap(message));

        byte[] writtenBytes  = stream.toByteArray();
        byte[] expectedBytes = Files.readAllBytes(Paths.get(getClass().getResource("/binaryfile.dat").toURI()));

        assertArrayEquals(expectedBytes, writtenBytes);
    }

}

Clean up test for BinaryFILE writer


package org.knowm.xchange.examples.gdax;

import java.io.IOException;

import org.knowm.xchange.Exchange;
import org.knowm.xchange.ExchangeFactory;
import org.knowm.xchange.currency.CurrencyPair;
import org.knowm.xchange.dto.marketdata.Ticker;
import org.knowm.xchange.gdax.GDAXExchange;
import org.knowm.xchange.gdax.dto.marketdata.GDAXProductTicker;
import org.knowm.xchange.gdax.service.GDAXMarketDataServiceRaw;
import org.knowm.xchange.service.marketdata.MarketDataService;

public class GDAXTickerDemo {

  public static void main(String[] args) throws IOException {

    Exchange exchange = ExchangeFactory.INSTANCE.createExchange(GDAXExchange.class.getName());
    MarketDataService marketDataService = exchange.getMarketDataService();

    generic(marketDataService);
    raw((GDAXMarketDataServiceRaw) marketDataService);
  }

  private static void generic(MarketDataService marketDataService) throws IOException {

    Ticker ticker = marketDataService.getTicker(CurrencyPair.BTC_USD);

    System.out.println(ticker.toString());
  }

  private static void raw(GDAXMarketDataServiceRaw marketDataService) throws IOException {

    GDAXProductTicker bitstampTicker = marketDataService.getCoinbaseExProductTicker(CurrencyPair.BTC_USD);

    System.out.println(bitstampTicker.toString());
  }

}

package org.knowm.xchange.examples.gdax;

import java.io.IOException;

import org.knowm.xchange.Exchange;
import org.knowm.xchange.ExchangeFactory;
import org.knowm.xchange.currency.CurrencyPair;
import org.knowm.xchange.dto.marketdata.Ticker;
import org.knowm.xchange.gdax.GDAXExchange;
import org.knowm.xchange.gdax.dto.marketdata.GDAXProductTicker;
import org.knowm.xchange.gdax.service.GDAXMarketDataServiceRaw;
import org.knowm.xchange.service.marketdata.MarketDataService;

public class GDAXTickerDemo {

  public static void main(String[] args) throws IOException {

    Exchange exchange = ExchangeFactory.INSTANCE.createExchange(GDAXExchange.class.getName());
    MarketDataService marketDataService = exchange.getMarketDataService();

    generic(marketDataService);
    raw((GDAXMarketDataServiceRaw) marketDataService);
  }

  private static void generic(MarketDataService marketDataService) throws IOException {

    Ticker ticker = marketDataService.getTicker(CurrencyPair.BTC_USD);

    System.out.println(ticker.toString());
  }

  private static void raw(GDAXMarketDataServiceRaw marketDataService) throws IOException {

    GDAXProductTicker gdaxTicker = marketDataService.getCoinbaseExProductTicker(CurrencyPair.BTC_USD);

    System.out.println(gdaxTicker.toString());
  }

}

Update GDAXProductTicker obj name from bitstampTicker to gdaxTicker


package org.apereo.cas.services.util;

import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.dataformat.yaml.YAMLFactory;

/**
 * This is {@link RegisteredServiceYamlSerializer}.
 *
 * @author Misagh Moayyed
 * @since 5.0.0
 */
public class RegisteredServiceYamlSerializer extends DefaultRegisteredServiceJsonSerializer {
    private static final long serialVersionUID = -6026921045861422473L;

    @Override
    protected JsonFactory getJsonFactory() {
        return new YAMLFactory();
    }
}

package org.apereo.cas.services.util;

import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.dataformat.yaml.YAMLFactory;
import org.apache.commons.io.FileUtils;

import java.io.File;
import java.nio.charset.StandardCharsets;

/**
 * This is {@link RegisteredServiceYamlSerializer}.
 *
 * @author Misagh Moayyed
 * @since 5.0.0
 */
public class RegisteredServiceYamlSerializer extends DefaultRegisteredServiceJsonSerializer {
    private static final long serialVersionUID = -6026921045861422473L;

    @Override
    protected JsonFactory getJsonFactory() {
        return new YAMLFactory();
    }

    @Override
    public boolean supports(final File file) {
        try {
            final String contents = FileUtils.readFileToString(file, StandardCharsets.UTF_8.name()).trim();
            return contents.startsWith("--- !<");
        } catch (final Exception e) {
            return false;
        }
    }
}

Fix test failures with yaml


/*
 * Kurento Android Media: Android Media Library based on FFmpeg.
 * Copyright (C) 2011  Tikal Technologies
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License version 3
 * as published by the Free Software Foundation.
 *
 * This program 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 General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package com.kurento.kas.media.rx;

/**
 *
 * @author mparis
 *
 */
public class MediaRx {
	public static native int startVideoRx(String sdp_str, int maxDelay, VideoRx videoPlayer);
	public static native int stopVideoRx();

	public static native int startAudioRx(String sdp_str, int maxDelay, AudioRx audioPlayer);
	public static native int stopAudioRx();

	static {
		System.loadLibrary("kas-media-native");
	}

}

/*
 * Kurento Android Media: Android Media Library based on FFmpeg.
 * Copyright (C) 2011  Tikal Technologies
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License version 3
 * as published by the Free Software Foundation.
 *
 * This program 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 General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package com.kurento.kas.media.rx;

/**
 *
 * @author mparis
 *
 */
public class MediaRx {

	public static final int DEFAULT_MAX_DELAY = 200;

	public static native int startVideoRx(String sdp_str, int maxDelay, VideoRx videoPlayer);
	public static native int stopVideoRx();

	public static native int startAudioRx(String sdp_str, int maxDelay, AudioRx audioPlayer);
	public static native int stopAudioRx();

	static {
		System.loadLibrary("kas-media-native");
	}

}

Add DEFAULT_MAX_DELAY as 200 ms.


/**
 * Copyright (C) 2011 - present by OpenGamma Inc. and the OpenGamma group of companies
 *
 * Please see distribution for license.
 */
package com.opengamma.integration.timeseries.snapshot;

import com.opengamma.component.OpenGammaComponentServer;

/**
 * Historical timeseries snapshotter.
 */
public class HistoricalTimeSeriesSnapshotter extends OpenGammaComponentServer {

  /**
   * Main method to start an OpenGamma JVM process for development.
   *
   * @param args  the arguments
   */
  public static void main(String[] args) { // CSIGNORE
    if (args.length == 0) {
      // if no command line arguments, then use default arguments suitable for development in an IDE
      // the first argument is for verbose startup, to aid understanding
      // the second argument defines the start of a chain of properties files providing the configuration
      args = new String[] {"-v", "classpath:/htssnapshot/hts-snapshot.properties"};
    }
    new HistoricalTimeSeriesSnapshotter().run(args);
  }

}

/**
 * Copyright (C) 2011 - present by OpenGamma Inc. and the OpenGamma group of companies
 *
 * Please see distribution for license.
 */
package com.opengamma.integration.timeseries.snapshot;

import com.opengamma.component.OpenGammaComponentServer;

/**
 * Historical timeseries snapshotter.
 */
public class HistoricalTimeSeriesSnapshotter extends OpenGammaComponentServer {

  /**
   * Main method to start an OpenGamma JVM process for development.
   *
   * @param args  the arguments
   */
  public static void main(String[] args) { // CSIGNORE
    if (args.length == 0) {
      // if no command line arguments, then use default arguments suitable for development in an IDE
      // the first argument is for verbose startup, to aid understanding
      // the second argument defines the start of a chain of properties files providing the configuration
      args = new String[] {"-v", "classpath:/htssnapshot/hts-snapshot.properties"};
    }
    if (!new HistoricalTimeSeriesSnapshotter().run(args)) {
      System.exit(-1);
    }
  }
}

Exit with -1 status if server failed to start up


package org.openspaces.pu.container.jee.jetty.support;

import org.mortbay.jetty.webapp.WebAppClassLoader;
import org.mortbay.jetty.webapp.WebAppContext;
import org.jini.rio.boot.LoggableClassLoader;

import java.io.IOException;

/**
 * @author kimchy
 */
public class JettyWebAppClassLoader extends WebAppClassLoader implements LoggableClassLoader {

    private final String loggableName;

    public JettyWebAppClassLoader(ClassLoader parent, WebAppContext context, String loggableName) throws IOException {
        super(parent, context);
        this.loggableName = loggableName;
    }

    public String getLogName() {
        return loggableName;
    }
}

package org.openspaces.pu.container.jee.jetty.support;

import org.mortbay.jetty.webapp.WebAppClassLoader;
import org.mortbay.jetty.webapp.WebAppContext;
import org.jini.rio.boot.LoggableClassLoader;

import java.io.IOException;

/**
 * A simple extension for Jetty WebApp class loader just to make it loggable in the Service Grid.
 *
 * @author kimchy
 */
public class JettyWebAppClassLoader extends WebAppClassLoader implements LoggableClassLoader {

    private final String loggableName;

    public JettyWebAppClassLoader(ClassLoader parent, WebAppContext context, String loggableName) throws IOException {
        super(parent, context);
        this.loggableName = loggableName;
    }

    public String getLogName() {
        return loggableName;
    }
}

Enable context logging based on class loader for web applications as well


package de.otto.jlineup.image;

import org.junit.Test;

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

public class LABTest {

    @Test
    public void shouldCalculateCIEDE2000() {

        LAB lab1 = LAB.fromRGB(55,44,33, 0);
        LAB lab2 = LAB.fromRGB(66,55,44, 0);

        double v = LAB.ciede2000(lab1, lab2);

        assertThat(v, is(3.533443206558854d));
    }
}

package de.otto.jlineup.image;

import org.junit.Test;

import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;

public class LABTest {

    @Test
    public void shouldCalculateCIEDE2000() {

        LAB lab1 = LAB.fromRGB(55,44,33, 0);
        LAB lab2 = LAB.fromRGB(66,55,44, 0);

        double v = Math.round(LAB.ciede2000(lab1, lab2) * Math.pow(10, 12)) / Math.pow(10, 12);

        assertThat(v, is(3.533443206559));
    }
}

Fix precision issue on MacOS


package com.vaadin.components.grid.config;

import com.google.gwt.core.client.JavaScriptObject;
import com.google.gwt.core.client.js.JsProperty;
import com.google.gwt.core.client.js.JsType;
import com.vaadin.components.common.js.JSArray;

/**
 * This class is a JsInterop wrapper for the JS object editor handler request.
 */
@JsType
public interface JSDataRequest {
    @JsProperty
    int getIndex();

    @JsProperty
    void setIndex(int index);

    @JsProperty
    int getCount();

    @JsProperty
    void setCount(int count);

    @JsProperty
    JSArray<JSSortOrder> getSortOrder();

    @JsProperty
    void setSortOrder(JSArray<JSSortOrder> sortOrder);

    @JsProperty
    JSArray<?> getFilterData();

    @JsProperty
    void setFilterData(JSArray<?> filterData);

    @JsProperty
    JavaScriptObject getSuccess();

    @JsProperty
    void setSuccess(JavaScriptObject success);

    @JsProperty
    JavaScriptObject getFailure();

    @JsProperty
    void setFailure(JavaScriptObject failure);
}

package com.vaadin.components.grid.config;

import com.google.gwt.core.client.JavaScriptObject;
import com.google.gwt.core.client.js.JsProperty;
import com.google.gwt.core.client.js.JsType;
import com.vaadin.components.common.js.JSArray;

/**
 * This class is a JsInterop wrapper for the JS object editor handler request.
 */
@JsType
public interface JSDataRequest {
    @JsProperty
    int getIndex();

    @JsProperty
    void setIndex(int index);

    @JsProperty
    int getCount();

    @JsProperty
    void setCount(int count);

    @JsProperty
    JSArray<JSSortOrder> getSortOrder();

    @JsProperty
    void setSortOrder(JSArray<JSSortOrder> sortOrder);

    @JsProperty
    JavaScriptObject getSuccess();

    @JsProperty
    void setSuccess(JavaScriptObject success);

    @JsProperty
    JavaScriptObject getFailure();

    @JsProperty
    void setFailure(JavaScriptObject failure);
}

Remove unused filter parameters from data request.


package com.thinkabstract.exercise.news.api.service;

import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class NewsFeedServiceFactory {

  private static final String BASE_NEWS_FEED_URL =
      "https://ajax.googleapis.com/ajax/services/feed/";

  public static NewsFeedService createService() {
    Retrofit retrofit = new Retrofit.Builder().baseUrl(BASE_NEWS_FEED_URL)
        .addConverterFactory(GsonConverterFactory.create())
        .build();

    return retrofit.create(NewsFeedService.class);
  }
}

package com.thinkabstract.exercise.news.api.service;

import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class NewsFeedServiceFactory {

  private static final String BASE_NEWS_FEED_URL =
      "https://ajax.googleapis.com/ajax/services/feed/";

  public static NewsFeedService createService() {
    Retrofit retrofit = new Retrofit.Builder().baseUrl(BASE_NEWS_FEED_URL)
        .addConverterFactory(GsonConverterFactory.create())
        .client(buildClient())
        .build();

    return retrofit.create(NewsFeedService.class);
  }

  private static OkHttpClient buildClient() {
    return new OkHttpClient.Builder().addInterceptor(buildHttpLoggingInterceptor()).build();
  }

  private static HttpLoggingInterceptor buildHttpLoggingInterceptor() {
    HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
    interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
    return interceptor;
  }
}

Add client to retrofit service builder


package com.codenvy.ide.ext.datasource.client.sqllauncher;

import com.google.gwt.user.client.ui.TextArea;

// temporary class
public class SqlLauncherTextArea extends TextArea {

    SqlLauncherTextArea(boolean readOnly) {
        super();
        setReadOnly(readOnly);
        getElement().getStyle().setBackgroundColor("white");
        getElement().getStyle().setProperty("font-family", "monospace");
    }
}

package com.codenvy.ide.ext.datasource.client.sqllauncher;

import com.google.gwt.user.client.ui.TextArea;

// temporary class
public class SqlLauncherTextArea extends TextArea {

    SqlLauncherTextArea(boolean readOnly) {
        super();
        setReadOnly(readOnly);
        getElement().getStyle().setBackgroundColor("white");
        getElement().getStyle().setProperty("fontFamily", "monospace");
    }
}

Fix error when setting CSS property


package yokohama.unit.position;

import java.nio.file.Path;
import java.util.Optional;
import lombok.Value;

@Value
public class Span {
    private final Optional<Path> sourcePath;
    private final Position start;
    private final Position end;

    public String getFileName() {
        if (!sourcePath.isPresent()) return "?";

        Path path = sourcePath.get();
        int nameCount = path.getNameCount();

        if (nameCount == 0) return "?";

        String fileName = path.getName(nameCount -1).toString();

        return fileName.equals("") ? "?" : fileName;
    }

    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append(sourcePath.isPresent() ? sourcePath.get().toString() : "?");
        sb.append(":");
        sb.append(start.toString());
        if (!end.isDummy()) {
            sb.append("-");
            sb.append(end.toString());
        }
        return sb.toString();
    }

    public static Span of(Path path) {
        return new Span(Optional.of(path), Position.dummyPos(), Position.dummyPos());
    }

    public static Span of(Path path, Position start) {
        return new Span(Optional.of(path), start, Position.dummyPos());
    }

    static public Span of(Path path, Position start, Position end) {
        return new Span(Optional.of(path), start, end);
    }

    private static Span dummySpan =
            new Span(
                    Optional.empty(),
                    Position.dummyPos(),
                    Position.dummyPos());
    public static Span dummySpan() {
        return dummySpan;
    }
}

package yokohama.unit.position;

import java.nio.file.Path;
import java.util.Optional;
import lombok.Value;

@Value
public class Span {
    private final Optional<Path> sourcePath;
    private final Position start;
    private final Position end;

    public String getFileName() {
        if (!sourcePath.isPresent()) return "?";

        Path path = sourcePath.get();
        int nameCount = path.getNameCount();

        if (nameCount == 0) return "?";

        String fileName = path.getName(nameCount -1).toString();

        return fileName.equals("") ? "?" : fileName;
    }

    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append(sourcePath.isPresent() ? sourcePath.get().toString() : "?");
        sb.append(":");
        sb.append(start.toString());
        if (!end.isDummy()) {
            sb.append("-");
            sb.append(end.toString());
        }
        return sb.toString();
    }

    public static Span of(Path path) {
        return new Span(Optional.of(path), Position.dummyPos(), Position.dummyPos());
    }

    public static Span of(Path path, Position start) {
        return new Span(Optional.of(path), start, Position.dummyPos());
    }

    public static Span of(Path path, Position start, Position end) {
        return new Span(Optional.of(path), start, end);
    }

    private static Span dummySpan =
            new Span(
                    Optional.empty(),
                    Position.dummyPos(),
                    Position.dummyPos());
    public static Span dummySpan() {
        return dummySpan;
    }
}

Swap public and static for consistency


package de.plushnikov.intellij.lombok.util;

import com.intellij.psi.PsiType;

/**
 * Gets all of primitive types as PsiType
 * Attention: IntelliJ 11 returns PsiPrimitiveType instead of PsiType, so we need a facade here.
 * @author Plushnikov Michail
 */
public class PsiPrimitiveTypeUtil10Impl implements PsiPrimitiveTypeUtil {
  @Override
  public PsiType getBooleanType() {
    return PsiType.BOOLEAN;
  }

  @Override
  public PsiType getNullType() {
    return PsiType.NULL;
  }

  @Override
  public PsiType getVoidType() {
    return PsiType.VOID;
  }

  @Override
  public PsiType getByteType() {
    return PsiType.BYTE;
  }

  @Override
  public PsiType getCharType() {
    return PsiType.CHAR;
  }

  @Override
  public PsiType getFloatType() {
    return PsiType.FLOAT;
  }

  @Override
  public PsiType getDoubleType() {
    return PsiType.DOUBLE;
  }

  @Override
  public PsiType getShortType() {
    return PsiType.SHORT;
  }

  @Override
  public PsiType getIntType() {
    return PsiType.INT;
  }

  @Override
  public PsiType getLongType() {
    return PsiType.LONG;
  }
}

package de.plushnikov.intellij.lombok.util;

import com.intellij.psi.PsiKeyword;
import com.intellij.psi.PsiType;
import com.intellij.psi.impl.PsiElementFactoryImpl;

/**
 * Gets all of primitive types as PsiType
 * Attention: IntelliJ 11 returns PsiPrimitiveType instead of PsiType, so we need a facade here.
 * Before build 103.72 is was PsiType and after this build PsiPrimitiveType
 *
 * @author Plushnikov Michail
 */
public class PsiPrimitiveTypeUtil10Impl implements PsiPrimitiveTypeUtil {
  @Override
  public PsiType getBooleanType() {
    return PsiElementFactoryImpl.getPrimitiveType(PsiKeyword.BOOLEAN);
  }

  @Override
  public PsiType getNullType() {
    return PsiElementFactoryImpl.getPrimitiveType(PsiKeyword.NULL);
  }

  @Override
  public PsiType getVoidType() {
    return PsiElementFactoryImpl.getPrimitiveType(PsiKeyword.VOID);
  }

  @Override
  public PsiType getByteType() {
    return PsiElementFactoryImpl.getPrimitiveType(PsiKeyword.BYTE);
  }

  @Override
  public PsiType getCharType() {
    return PsiElementFactoryImpl.getPrimitiveType(PsiKeyword.CHAR);
  }

  @Override
  public PsiType getFloatType() {
    return PsiElementFactoryImpl.getPrimitiveType(PsiKeyword.FLOAT);
  }

  @Override
  public PsiType getDoubleType() {
    return PsiElementFactoryImpl.getPrimitiveType(PsiKeyword.DOUBLE);
  }

  @Override
  public PsiType getShortType() {
    return PsiElementFactoryImpl.getPrimitiveType(PsiKeyword.SHORT);
  }

  @Override
  public PsiType getIntType() {
    return PsiElementFactoryImpl.getPrimitiveType(PsiKeyword.INT);
  }

  @Override
  public PsiType getLongType() {
    return PsiElementFactoryImpl.getPrimitiveType(PsiKeyword.LONG);
  }
}

Fix incompatibility between IntelliJ<=10.0.2 and >10.0.2 (build 103.72)


import com.redhat.ceylon.compiler.typechecker.TypeChecker;
import com.redhat.ceylon.compiler.typechecker.TypeCheckerBuilder;
import com.redhat.ceylon.compiler.typechecker.tree.Tree;

import java.io.File;

/**
 * Some hack before a proper unit test harness is put in place
 *
 * @author Emmanuel Bernard <emmanuel@hibernate.org>
 */
public class MainForTest {
    /**
     * Files that are not under a proper module structure are placed under a <nomodule> module.
     */
    public static void main(String[] args) throws Exception {

        final TypeChecker typeChecker = new TypeCheckerBuilder()
                .verbose(false)
                .addSrcDirectory( new File("test") )
                .getTypeChecker();
        Tree.CompilationUnit compilationUnit = typeChecker.getCompilationUnitFromRelativePath("ceylon/language/BaseObject.ceylon");
        if ( compilationUnit == null ) {
            throw new RuntimeException("Failed to pass getCompilationUnitFromRelativePath for files in .src");
        }
        compilationUnit = typeChecker.getCompilationUnitFromRelativePath("capture/Capture.ceylon");
        if ( compilationUnit == null ) {
            throw new RuntimeException("Failed to pass getCompilationUnitFromRelativePath for files in real src dir");
        }
    }
}

import com.redhat.ceylon.compiler.typechecker.TypeChecker;
import com.redhat.ceylon.compiler.typechecker.TypeCheckerBuilder;
import com.redhat.ceylon.compiler.typechecker.tree.Tree;

import java.io.File;

/**
 * Some hack before a proper unit test harness is put in place
 *
 * @author Emmanuel Bernard <emmanuel@hibernate.org>
 */
public class MainForTest {
    /**
     * Files that are not under a proper module structure are placed under a <nomodule> module.
     */
    public static void main(String[] args) throws Exception {

        TypeChecker typeChecker = new TypeCheckerBuilder()
                .verbose(false)
                .addSrcDirectory( new File("test") )
                .getTypeChecker();
        Tree.CompilationUnit compilationUnit = typeChecker.getCompilationUnitFromRelativePath("ceylon/language/BaseObject.ceylon");
        if ( compilationUnit == null ) {
            throw new RuntimeException("Failed to pass getCompilationUnitFromRelativePath for files in .src");
        }
        compilationUnit = typeChecker.getCompilationUnitFromRelativePath("capture/Capture.ceylon");
        if ( compilationUnit == null ) {
            throw new RuntimeException("Failed to pass getCompilationUnitFromRelativePath for files in real src dir");
        }
        typeChecker = new TypeCheckerBuilder()
                .verbose(false)
                .addSrcDirectory( new File("test/capture") )
                .getTypeChecker();
        compilationUnit = typeChecker.getCompilationUnitFromRelativePath("Capture.ceylon");
        if ( compilationUnit == null ) {
            throw new RuntimeException("Failed to pass getCompilationUnitFromRelativePath for top level files (no package) in real src dir");
        }
    }
}

Add test for top level files (no package)


/*
 * Copyright 2016-2018 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 org.springframework.cloud.dataflow.rest.client.support;

import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;

import org.springframework.batch.core.StepExecution;

/**
 * Jackson MixIn for {@link StepExecution} de-serialization.
 *
 * @author Gunnar Hillert
 * @since 1.0
 */
@JsonIgnoreProperties({ "jobParameters", "jobExecutionId", "skipCount", "summary" })
public abstract class StepExecutionJacksonMixIn {

	@JsonCreator
	StepExecutionJacksonMixIn(@JsonProperty("stepName") String stepName) {
	}

}

/*
 * Copyright 2016-2020 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 org.springframework.cloud.dataflow.rest.client.support;

import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;

import org.springframework.batch.core.StepExecution;

/**
 * Jackson MixIn for {@link StepExecution} de-serialization.
 *
 * @author Gunnar Hillert
 * @since 1.0
 */
@JsonIgnoreProperties({ "jobExecution", "jobParameters", "jobExecutionId", "skipCount", "summary" })
public abstract class StepExecutionJacksonMixIn {

	@JsonCreator
	StepExecutionJacksonMixIn(@JsonProperty("stepName") String stepName) {
	}

}

Exclude jobExecution on client side


package uk.ac.ic.wlgitbridge.snapshot.base;

import com.google.gson.JsonElement;
import uk.ac.ic.wlgitbridge.git.exception.SnapshotAPIException;

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

public class MissingRepositoryException extends SnapshotAPIException {

    public static final String GENERIC_REASON =
        "This Overleaf project currently has no git access.\n" +
        "\n" +
        "If you think this is an error, contact support at support@overleaf.com.";

    public static final String EXPORTED_TO_V2 =
        "This Overleaf project has been moved to Overleaf v2, and git access is temporarily unsupported.\n" +
        "\n" +
        "See https://www.overleaf.com/help/342 for more information.";

    private String message = "";

    public MissingRepositoryException() {
    }

    public MissingRepositoryException(String message) {
        this.message = message;
    }

    @Override
    public void fromJSON(JsonElement json) {}

    @Override
    public String getMessage() {
        return message;
    }

    @Override
    public List<String> getDescriptionLines() {
        return Arrays.asList(getMessage());
    }

}

package uk.ac.ic.wlgitbridge.snapshot.base;

import com.google.gson.JsonElement;
import uk.ac.ic.wlgitbridge.git.exception.SnapshotAPIException;

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

public class MissingRepositoryException extends SnapshotAPIException {

    public static final String GENERIC_REASON =
        "This Overleaf project currently has no git access.\n" +
        "\n" +
        "If this problem persists, please contact us.";

    public static final String EXPORTED_TO_V2 =
        "This Overleaf project has been moved to Overleaf v2, and git access is temporarily unsupported.\n" +
        "\n" +
        "See https://www.overleaf.com/help/342 for more information.";

    private String message = "";

    public MissingRepositoryException() {
    }

    public MissingRepositoryException(String message) {
        this.message = message;
    }

    @Override
    public void fromJSON(JsonElement json) {}

    @Override
    public String getMessage() {
        return message;
    }

    @Override
    public List<String> getDescriptionLines() {
        return Arrays.asList(getMessage());
    }

}

Make GENERIC_REASON consistent with web messages.


/*
 * Copyright (C) 2013 ickStream GmbH
 * All rights reserved
 */

package com.ickstream.protocol.service.core;

public class AuthenticationProviderResponse {
    private String id;
    private String name;
    private String icon;
    private String url;

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

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

    public String getIcon() {
        return icon;
    }

    public void setIcon(String icon) {
        this.icon = icon;
    }

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }
}

/*
 * Copyright (C) 2013 ickStream GmbH
 * All rights reserved
 */

package com.ickstream.protocol.service.core;

public class AuthenticationProviderResponse {
    private String id;
    private String name;
    private String icon;
    private String url;
    private String addIdentityUrl;

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

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

    public String getIcon() {
        return icon;
    }

    public void setIcon(String icon) {
        this.icon = icon;
    }

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    public String getAddIdentityUrl() {
        return addIdentityUrl;
    }

    public void setAddIdentityUrl(String addIdentityUrl) {
        this.addIdentityUrl = addIdentityUrl;
    }
}

Add addIdentityUrl attribute to result from findAuthenticationProviders


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

import static org.junit.Assert.assertTrue;

import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Invocation;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.Response;
import it.EndpointTest;

import org.junit.Test;

public class LibertyServletTest extends EndpointTest {

    @Test
    public void testDeployment() {
        testEndpoint("/servlet", "Hello, from a Servlet!");
    }
}

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

import it.EndpointTest;

import org.junit.Test;

public class LibertyServletTest extends EndpointTest {

    @Test
    public void testDeployment() {
        testEndpoint("/servlet", "Hello, from a Servlet!");
    }
}

Remove unused imports in web tech type.


package entities;

import java.awt.Color;
import java.awt.Graphics2D;
import java.util.Random;

import snake.Screen;

public class Food extends Entity {
  private final int SIZE = Snake.SIZE;
  private int x, y;

  public Food() {
    r = new Random();
    update();
  }

  @Override
  public void draw(Graphics2D g2d) {
    g2d.setColor(Color.RED);
    g2d.fillOval(cellX, cellY, SIZE, SIZE);
  }

  @Override
  public void update() {
    x = r.nextInt(Screen.WIDTH);
    y = r.nextInt(Screen.HEIGHT);
    cellX = x / SIZE * SIZE;
    cellY = y / SIZE * SIZE;
    for (Entity wall : Screen.walls) {
      if (collide(wall)) {
        update();
      }
    }
    for (Entity bodyPiece : Snake.body) {
      if (collide(bodyPiece)) {
        update();
      }
    }
    if (collide(Snake.self)) {
      update();
    }
  }
}

package entities;

import java.awt.Color;
import java.awt.Graphics2D;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Random;

import snake.Screen;

public class Food extends Entity {
  private final int SIZE = Snake.SIZE;
  private int x, y;
  private Color color;

  public Food() {
    r = new Random();
    color = chooseColour();
    update();
  }

  @Override
  public void draw(Graphics2D g2d) {
    g2d.setColor(color);
    g2d.fillOval(cellX, cellY, SIZE, SIZE);
  }

  @Override
  public void update() {
    color = chooseColour();
    x = r.nextInt(Screen.WIDTH);
    y = r.nextInt(Screen.HEIGHT);
    cellX = x / SIZE * SIZE;
    cellY = y / SIZE * SIZE;
    for (Entity wall : Screen.walls) {
      if (collide(wall)) {
        update();
      }
    }
    for (Entity bodyPiece : Snake.body) {
      if (collide(bodyPiece)) {
        update();
      }
    }
    if (collide(Snake.self)) {
      update();
    }
  }

  private Color chooseColour() {
    float a = r.nextFloat() / 4 + 0.7f;
    float b = r.nextFloat() / 4 + 0.1f;
    float c = r.nextFloat() / 4 + 0.1f;
    List<Float> colours = new ArrayList<Float>();
    colours.add(a);
    colours.add(b);
    colours.add(c);
    Collections.shuffle(colours);
    return new Color(
        colours.get(0),
        colours.get(1),
        colours.get(2));
  }
}

Choose a random (brightish) colour for food


package com.alexrnl.commons.error;

import java.util.Objects;
import java.util.logging.Logger;

/**
 * TODO
 * @author Alex
 */
public final class ExceptionUtils {
	/** Logger */
	private static Logger	lg	= Logger.getLogger(ExceptionUtils.class.getName());

	/**
	 * Constructor #1.

	 * Default private constructor.
	 */
	private ExceptionUtils () {
		super();
	}

	/**
	 *
	 * @param e
	 *        the throwable object to display.
	 * @return a {@link String} containing the class and the message of the exception.
	 * @throws NullPointerException
	 *         if the {@link Throwable} is null.
	 */
	public static String displayClassAndMessage (final Throwable e) throws NullPointerException {
		Objects.requireNonNull(e);
		return e.getClass() + "; " + e.getMessage();
	}
}

package com.alexrnl.commons.error;

import java.util.logging.Logger;

/**
 * Utility methods for exception handling.

 * @author Alex
 */
public final class ExceptionUtils {
	/** Logger */
	private static Logger	lg	= Logger.getLogger(ExceptionUtils.class.getName());

	/**
	 * Constructor #1.

	 * Default private constructor.
	 */
	private ExceptionUtils () {
		super();
	}

	/**
	 * Print a nice message with the {@link Class} and the {@link Throwable#getMessage() message}
	 * of the exception.

	 * @param e
	 *        the throwable object to display.
	 * @return a {@link String} containing the class and the message of the exception.
	 */
	public static String displayClassAndMessage (final Throwable e) {
		if (e == null) {
			lg.warning("Cannot display null exception.");
			return "null exception caught";
		}
		return e.getClass() + "; " + e.getMessage();
	}
}

Complete javadoc and don't throw NPE


/**
 * Copyright (C) 2010 openecho
 *
 * 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 kinetic.math.statistic;

import java.lang.reflect.Array;

/**
 * Standard Deviation Utility
 *
 * @author openecho
 * @version 1.0.1
 */
public class StandardDeviation {
    public static Double evaluate(Double[] data) {
        if(data==null) {
            throw new NullPointerException();
        }
        int length = Array.getLength(data);
        if(length < 2) {
            throw new RuntimeException("More than two values are required to calculate a standard deviation");
        }
        double mean = Mean.evaluate(data);
        double sumDifferenceSquared = 0;
        for(int i=0;i<length;i++) {
            sumDifferenceSquared += Math.pow(data[i]-mean,2);
        }
        return Math.sqrt(sumDifferenceSquared/(length-1));
    }
}

/**
 * Copyright (C) 2010 openecho
 *
 * 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 kinetic.math.statistic;

import java.lang.reflect.Array;

/**
 * Standard Deviation Utility
 *
 * @author openecho
 * @version 1.0.1
 */
public class StandardDeviation {

    public static Double evaluate(Double[] data) {
        return StandardDeviation.evaluate(data, true);
    }

    public static Double evaluate(Double[] data, boolean partialPopulation) {
        if(data==null) {
            throw new NullPointerException();
        }
        int length = Array.getLength(data);
        if(length < 2) {
            throw new RuntimeException("More than two values are required to calculate a standard deviation");
        }
        double mean = Mean.evaluate(data);
        double sumDifferenceSquared = 0;
        for(int i=0;i<length;i++) {
            sumDifferenceSquared += Math.pow(data[i]-mean,2);
        }
        return Math.sqrt(sumDifferenceSquared/((partialPopulation) ? (length-1) : (length)));
    }
}

Add population based divide option


package io.quarkus.smallrye.context.runtime;

import java.util.concurrent.ExecutorService;

import javax.enterprise.context.ApplicationScoped;
import javax.enterprise.inject.Produces;
import javax.inject.Singleton;

import org.eclipse.microprofile.context.ManagedExecutor;
import org.eclipse.microprofile.context.ThreadContext;

import io.smallrye.context.impl.ManagedExecutorImpl;
import io.smallrye.context.impl.ThreadContextImpl;

@ApplicationScoped
public class SmallRyeContextPropagationProvider {

    private volatile ManagedExecutorImpl managedExecutor;

    void initialize(ExecutorService executorService) {
        managedExecutor = new ManagedExecutorImpl(-1, -1, (ThreadContextImpl) getAllThreadContext(), executorService, "no-ip");
    }

    @Produces
    @Singleton
    public ThreadContext getAllThreadContext() {
        return ThreadContext.builder().propagated(ThreadContext.ALL_REMAINING).cleared().unchanged().build();
    }

    @Produces
    @Singleton
    public ManagedExecutor getAllManagedExecutor() {
        return managedExecutor;
    }

}

package io.quarkus.smallrye.context.runtime;

import java.util.List;
import java.util.concurrent.ExecutorService;

import javax.enterprise.context.ApplicationScoped;
import javax.enterprise.inject.Produces;
import javax.inject.Singleton;

import org.eclipse.microprofile.context.ManagedExecutor;
import org.eclipse.microprofile.context.ThreadContext;

import io.smallrye.context.impl.ManagedExecutorImpl;
import io.smallrye.context.impl.ThreadContextImpl;

@ApplicationScoped
public class SmallRyeContextPropagationProvider {

    private volatile ManagedExecutorImpl managedExecutor;

    void initialize(ExecutorService executorService) {
        managedExecutor = new ManagedExecutorImpl(-1, -1, (ThreadContextImpl) getAllThreadContext(), executorService, "no-ip") {
            @Override
            public void shutdown() {
                throw new IllegalStateException("This executor is managed by the container and cannot be shut down.");
            }

            @Override
            public List<Runnable> shutdownNow() {
                throw new IllegalStateException("This executor is managed by the container and cannot be shut down.");
            }
        };
    }

    @Produces
    @Singleton
    public ThreadContext getAllThreadContext() {
        return ThreadContext.builder().propagated(ThreadContext.ALL_REMAINING).cleared().unchanged().build();
    }

    @Produces
    @Singleton
    public ManagedExecutor getAllManagedExecutor() {
        return managedExecutor;
    }

}

Make sure we follow the MP-CP spec and disallow our container-managed executor to be shut down


package org.fountanio.world;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.Reader;
import java.util.ArrayList;

import org.fountanio.world.Tile;
import org.fountanio.juancode.out.Main;

public class World  {

	private Tile[] world;
	public final int MAX_WIDTH = 120;
	public final int MAX_HEIGHT = 40;
	private int tick = 0;

	public void loadWorld(String path) throws IOException {
		File file = new File(path);
		Reader re = new FileReader(file);
		BufferedReader reader = new BufferedReader(re);
		if (file.exists()) {
			Main.getConsole().println("Reading map...");
			while (reader.ready()) {
				String parse[] = reader.readLine().trim().split(",");

				tick++;
			}
			Main.getConsole().println("Done!");
			re.close();
			reader.close();
		} else {
			Main.getConsole().errorln(path + " was not found!");
		}
	}

	public void render() {

	}
}

package org.fountanio.world;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.Reader;
import java.util.ArrayList;

import org.fountanio.world.Tile;
import org.fountanio.juancode.out.Main;

public class World  {

	private Tile[] world;
	public static final int MAX_WIDTH = 120;
	public static final int MAX_HEIGHT = 40;
	private int tick = 0;

	public void loadWorld(String path) throws IOException {
		File file = new File(path);
		Reader re = new FileReader(file);
		BufferedReader reader = new BufferedReader(re);
		if (file.exists()) {
			Main.getConsole().println("Reading map...");
			while (reader.ready()) {
				String parse[] = reader.readLine().trim().split(",");

				tick++;
			}
			Main.getConsole().println("Done!");
			re.close();
			reader.close();
		} else {
			Main.getConsole().errorln(path + " was not found!");
		}
	}

	public void render() {
		// lil wot
	}
}

Make MAX_WIDTH and MAX_HEIGHT static


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.getFit.getAddCommand());
        assertTrue(taskListPanel.isListMatching(td.getFit));
        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("All tasks has been cleared!");
    }
}

package guitests;

import static org.junit.Assert.assertTrue;

import org.junit.Test;

public class ClearCommandTest extends TaskManagerGuiTest {

    @Test
    public void clear() {
        System.out.println(taskListPanel.getTask(4));
        //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.getFit.getAddCommand());
        assertTrue(taskListPanel.isListMatching(td.getFit));
        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("All tasks has been cleared!");
    }
}

Fix ClearCommand Unit Test Failing


package guitests;

import static org.junit.Assert.assertTrue;

import org.junit.Test;

public class ClearCommandTest extends EzDoGuiTest {

    @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(false));
        assertTrue(taskListPanel.isListMatching(td.hoon));
        commandBox.runCommand("kill 1");
        assertListSize(0);

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

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

package guitests;

import static org.junit.Assert.assertTrue;

import org.junit.Test;

public class ClearCommandTest extends EzDoGuiTest {

    @Test
    public void clear() {

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

        //verify a non-empty list can be cleared using the short clear command
        commandBox.runCommand(td.jack.getAddCommand(true));
        assertListSize(1);
        assertClearCommandSuccess(true);

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

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

    private void assertClearCommandSuccess(boolean usesShortCommand) {
        if (usesShortCommand) {
            commandBox.runCommand("c");
        } else {
            commandBox.runCommand("clear");
        }
        assertListSize(0);
        assertResultMessage("EzDo has been cleared!");
    }
}

Add test for shortened clear command


package cpw.mods.fml.common.network;

import net.minecraft.src.NetHandler;
import net.minecraft.src.NetworkManager;

public class ModMissingPacket extends FMLPacket
{

    public ModMissingPacket()
    {
        super(Type.MOD_MISSING);
    }

    @Override
    public byte[] generatePacket(Object... data)
    {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public FMLPacket consumePacket(byte[] data)
    {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public void execute(NetworkManager network, FMLNetworkHandler handler, NetHandler netHandler, String userName)
    {
        // TODO Auto-generated method stub

    }

}

package cpw.mods.fml.common.network;

import java.util.List;

import net.minecraft.src.NetHandler;
import net.minecraft.src.NetworkManager;

public class ModMissingPacket extends FMLPacket
{

    public ModMissingPacket()
    {
        super(Type.MOD_MISSING);
    }

    @Override
    public byte[] generatePacket(Object... data)
    {
        // TODO
        List<String> missing = (List<String>) data[0];
        List<String> badVersion = (List<String>) data[1];

        return new byte[0];
    }

    @Override
    public FMLPacket consumePacket(byte[] data)
    {
        // TODO
        return this;
    }

    @Override
    public void execute(NetworkManager network, FMLNetworkHandler handler, NetHandler netHandler, String userName)
    {
        // TODO
    }

}

Fix NPE on missing mods - still need to actually handle missing mods properly on client


/**
 * Part of Employ
 */

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

public abstract class CommonFrame extends JFrame {

  JPanel panelHeading;
  JLabel labelHeading;

  // define common settings for all frame
  public CommonFrame(String heading) {
    super("Employ - " + heading);

    setSize(400, 200);
    setResizable(false);
    setLocationRelativeTo(null);
    setLayout(new FlowLayout());

    panelHeading = new JPanel();
    labelHeading = new JLabel(heading);

    add(panelHeading);
    add(labelHeading);

    setDefaultCloseOperation(EXIT_ON_CLOSE);
  }

}

/**
 * Part of Employ
 */

import javax.swing.*;

public abstract class CommonFrame extends JFrame {

  JPanel panelHeading = new JPanel();

  // define common settings for all frame
  public CommonFrame(String heading) {
    super("Employ - " + heading);

    setSize(400, 200);
    setResizable(false);
    setLocationRelativeTo(null);
    setLayout(new BoxLayout(getContentPane(), BoxLayout.Y_AXIS));

    JLabel labelHeading = new JLabel(heading);
    panelHeading.add(labelHeading);
    add(panelHeading);

    setDefaultCloseOperation(EXIT_ON_CLOSE);
  }

}

Use BoxLayout for better component arrangement


package org.aslak.github.merge;

import java.io.IOException;
import java.util.regex.Pattern;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;

@WebFilter(filterName= "HTML5RewriteFilter", urlPatterns = {"/*"})
public class HTML5RewriteFilter implements Filter {

    public static final Pattern PATTERN = Pattern.compile("(^.*/api/|\\.(css|js|png|jpg))");
    public static final String APP_INDEX = "/app/index.jsp";

    @Override
    public void init(FilterConfig filterConfig) throws ServletException { }

    @Override
    public void destroy() {}

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest httpRequest = (HttpServletRequest)request;
        request.setAttribute("BASE_ROOT", httpRequest.getContextPath());

        if(PATTERN.matcher(httpRequest.getRequestURI()).find()) {
            chain.doFilter(request, response);
        } else {
            request.getRequestDispatcher(APP_INDEX).forward(request, response);
        }
    }
}

package org.aslak.github.merge;

import java.io.IOException;
import java.util.regex.Pattern;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;

@WebFilter(filterName= "HTML5RewriteFilter", urlPatterns = {"/*"})
public class HTML5RewriteFilter implements Filter {

    public static final Pattern PATTERN = Pattern.compile("(^.*/api/|\\.(css|js|png|jpg|html))");
    public static final String APP_INDEX = "/app/index.jsp";

    @Override
    public void init(FilterConfig filterConfig) throws ServletException { }

    @Override
    public void destroy() {}

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest httpRequest = (HttpServletRequest)request;
        request.setAttribute("BASE_ROOT", httpRequest.getContextPath());

        if(PATTERN.matcher(httpRequest.getRequestURI()).find()) {
            chain.doFilter(request, response);
        } else {
            request.getRequestDispatcher(APP_INDEX).forward(request, response);
        }
    }
}

Allow HTML files to pass through Rewrite filter


package com.skraylabs.poker;

import static org.junit.Assert.fail;

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

public class ApplicationTest {

  @Before
  public void setUp() throws Exception {}

  @After
  public void tearDown() throws Exception {}

  @Test
  public void test() {
    fail("Not yet implemented");
  }

}

package com.skraylabs.poker;

import static org.hamcrest.CoreMatchers.allOf;
import static org.hamcrest.CoreMatchers.containsString;
import static org.hamcrest.MatcherAssert.assertThat;

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

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

public class ApplicationTest {

  @Before
  public void setUp() throws Exception {}

  @After
  public void tearDown() throws Exception {}

  @Test
  public void testShowUsageForTooFewArguments() {
    // Set up
    ByteArrayOutputStream output = new ByteArrayOutputStream();
    PrintStream console = System.out;
    try {
      System.setOut(new PrintStream(output));
      String[] args = {""};
      // Exercise
      Application.main(args);
    } finally {
      // Tear down
      System.setOut(console);
    }
    // Verify
    String outputString = output.toString();
    assertThat(outputString, allOf(containsString("Too few arguments"),
        containsString("Usage: PokerCalculator filepath")));
  }

}

Implement test for too few arguments.


package protocolsupport.protocol.packet.middleimpl.serverbound.play.v_4_5_6;

import io.netty.buffer.ByteBuf;
import protocolsupport.protocol.packet.middle.serverbound.play.MiddleClientCommand;

public class ClientCommand extends MiddleClientCommand {

	@Override
	public void readFromClientData(ByteBuf clientdata) {
		clientdata.readByte();
	}

}

package protocolsupport.protocol.packet.middleimpl.serverbound.play.v_4_5_6;

import io.netty.buffer.ByteBuf;
import protocolsupport.protocol.packet.middle.serverbound.play.MiddleClientCommand;

public class ClientCommand extends MiddleClientCommand {

	@Override
	public void readFromClientData(ByteBuf clientdata) {
		clientdata.readByte();
		command = Command.REQUEST_RESPAWN;
	}

}

Fix <= 1.6 clients not being able to respawn


package com.annimon.jmr;

import com.annimon.jmr.controllers.MainController;
import java.io.IOException;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Scene;
import javafx.stage.Stage;

public class Main extends Application {

    public static void main(String[] args) {
        launch(args);
    }

    @Override
    public void start(Stage primaryStage) throws IOException {
        FXMLLoader loader = new FXMLLoader(getClass().getResource("/fxml/Main.fxml"));
        Scene scene = new Scene(loader.load());
        primaryStage.setTitle("JMethodRearranger");
        primaryStage.setScene(scene);
        MainController controller = loader.getController();
        controller.setPrimaryStage(primaryStage);
        primaryStage.show();
    }
}

package com.annimon.jmr;

import com.annimon.jmr.controllers.MainController;
import java.io.IOException;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Scene;
import javafx.stage.Stage;

public class Main extends Application {

    public static void main(String[] args) {
        launch(args);
    }

    @Override
    public void start(Stage primaryStage) throws IOException {
        FXMLLoader loader = new FXMLLoader(getClass().getResource("/fxml/main.fxml"));
        Scene scene = new Scene(loader.load());
        primaryStage.setTitle("JMethodRearranger");
        primaryStage.setScene(scene);
        MainController controller = loader.getController();
        controller.setPrimaryStage(primaryStage);
        primaryStage.show();
    }
}

Fix typo in fxml name


package net.mcft.copy.betterstorage;

import net.mcft.copy.betterstorage.items.ItemKey;
import net.mcft.copy.betterstorage.items.ItemLock;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.inventory.IInventory;
import net.minecraft.item.ItemStack;
import cpw.mods.fml.common.ICraftingHandler;

/** Handles key and lock crafting. */
public class CraftingHandler implements ICraftingHandler {

	@Override
	public void onCrafting(EntityPlayer player, ItemStack item, IInventory craftMatrix) {
		// If item crafted is a key, set its damage value to ..
		if (item.getItem() instanceof ItemKey) {
			int damage;
			// .. another key's damage value, if it was crafted with one.
			ItemStack stack = craftMatrix.getStackInSlot(6);
			if (stack != null && stack.getItem() instanceof ItemKey)
				damage = stack.getItemDamage();
			// .. a random value, if not.
			else damage = -32000 + BetterStorage.random.nextInt(64000);
			item.setItemDamage(damage);
		}
		// If item crafted is a lock, copy the damage value from the key.
		if (item.getItem() instanceof ItemLock)
			item.setItemDamage(craftMatrix.getStackInSlot(4).getItemDamage());
	}
	@Override
	public void onSmelting(EntityPlayer player, ItemStack item) {  }

}

package net.mcft.copy.betterstorage;

import net.mcft.copy.betterstorage.items.ItemKey;
import net.mcft.copy.betterstorage.items.ItemLock;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.inventory.IInventory;
import net.minecraft.item.ItemStack;
import cpw.mods.fml.common.ICraftingHandler;

/** Handles key and lock crafting. */
public class CraftingHandler implements ICraftingHandler {

	@Override
	public void onCrafting(EntityPlayer player, ItemStack item, IInventory craftMatrix) {
		// If item crafted is a key, set its damage value to ..
		if (item.getItem() instanceof ItemKey) {
			int damage;
			// .. another key's damage value, if it was crafted with one ..
			ItemStack stack = craftMatrix.getStackInSlot(6);
			if (stack == null) stack = craftMatrix.getStackInSlot(7);
			if (stack != null && stack.getItem() instanceof ItemKey)
				damage = stack.getItemDamage();
			// .. or a random value, if not.
			else damage = -32000 + BetterStorage.random.nextInt(64000);
			item.setItemDamage(damage);
		}
		// If item crafted is a lock, copy the damage value from the key.
		if (item.getItem() instanceof ItemLock)
			item.setItemDamage(craftMatrix.getStackInSlot(4).getItemDamage());
	}
	@Override
	public void onSmelting(EntityPlayer player, ItemStack item) {  }

}

Fix duplicated key not copying ID correctly


/*
 * Copyright (C) 2009 the original author(s).
 *
 * 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.
 */

/**
 * ???
 *
 * @since 2.0
 */
package org.sonatype.gshell.vfs.selector;

/*
 * Copyright (C) 2009 the original author(s).
 *
 * 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.
 */

/**
 * VFS selectors.
 *
 * @since 2.0
 */
package org.sonatype.gshell.vfs.selector;

Add meat to the docs


package org.knowm.xchange.bitbay.v3.service;

import java.io.IOException;
import java.util.UUID;
import java.util.regex.Pattern;
import org.knowm.xchange.Exchange;
import org.knowm.xchange.bitbay.v3.dto.trade.BitbayUserTrades;
import org.knowm.xchange.bitbay.v3.dto.trade.BitbayUserTradesQuery;
import org.knowm.xchange.exceptions.ExchangeException;
import org.knowm.xchange.utils.ObjectMapperHelper;

/** @author walec51 */
public class BitbayTradeServiceRaw extends BitbayBaseService {

  private static final Pattern WHITESPACES = Pattern.compile("\\s\\s");

  BitbayTradeServiceRaw(Exchange exchange) {
    super(exchange);
  }

  public BitbayUserTrades getBitbayTransactions(BitbayUserTradesQuery query)
      throws IOException, ExchangeException {
    String jsonQuery = ObjectMapperHelper.toJSON(query);
    jsonQuery = WHITESPACES.matcher(jsonQuery).replaceAll("");
    BitbayUserTrades response =
        bitbayAuthenticated.getTransactionHistory(
            apiKey, sign, exchange.getNonceFactory(), UUID.randomUUID(), jsonQuery);
    checkError(response);
    return response;
  }
}

package org.knowm.xchange.bitbay.v3.service;

import java.io.IOException;
import java.util.UUID;
import org.knowm.xchange.Exchange;
import org.knowm.xchange.bitbay.v3.dto.trade.BitbayUserTrades;
import org.knowm.xchange.bitbay.v3.dto.trade.BitbayUserTradesQuery;
import org.knowm.xchange.exceptions.ExchangeException;
import org.knowm.xchange.utils.ObjectMapperHelper;

/** @author walec51 */
public class BitbayTradeServiceRaw extends BitbayBaseService {

  BitbayTradeServiceRaw(Exchange exchange) {
    super(exchange);
  }

  public BitbayUserTrades getBitbayTransactions(BitbayUserTradesQuery query)
      throws IOException, ExchangeException {
    final String jsonQuery = ObjectMapperHelper.toCompactJSON(query);
    final BitbayUserTrades response =
        bitbayAuthenticated.getTransactionHistory(
            apiKey, sign, exchange.getNonceFactory(), UUID.randomUUID(), jsonQuery);
    checkError(response);
    return response;
  }
}

Use compact JSON instead of replacing whitespaces in String


import java.util.*;

class Carrinho{
	ArrayList<Produto> prod = new ArrayList<Produto>();

	public double calculaPeso(Produto P){
		double peso = 0.0;
		for(int i = 0; i < prod.size(); i++) peso += prod.get(i).getPeso();
		System.out.println(">>> " + peso);
		return peso;
	}

	public double calculaFrete(double a, double b){
		Produto p = null;
		return a * calculaPeso(p);
	}

	public double calculaPreço(Produto P){
		double preço = 0.0;
		for(int i = 0; i < prod.size(); i++) preço += prod.get(i).getPreço();
		return preço;
	}

	public Produto adicionaProduto(Produto p){
		prod.add(p);
		return p;
	}

	public void removeProduto(Produto p){
		prod.remove(p);
	}

	public double preçototal(double a, double b){
		int i;
		double resp = 0;
		for(i = 0; i < prod.size(); i++){
			resp += prod.get(i).getPreço();
		}
		return resp + calculaFrete(a, 23.5);
	}

}

import java.util.*;

class Carrinho{
	ArrayList<Produto> prod = new ArrayList<Produto>();

	public double calculaPeso(Produto P){
		double peso = 0.0;
		for(int i = 0; i < prod.size(); i++) peso += prod.get(i).getPeso();
		System.out.println(">>> " + peso);
		return peso;
	}

	public double calculaFrete(double a, double b){
		Produto p = null;
		return (a * calculaPeso(p)) + (2 * b);
	}

	public double calculaPreço(Produto P){
		double preço = 0.0;
		for(int i = 0; i < prod.size(); i++) preço += prod.get(i).getPreço();
		return preço;
	}

	public Produto adicionaProduto(Produto p){
		prod.add(p);
		return p;
	}

	public void removeProduto(Produto p){
		prod.remove(p);
	}

	public double preçototal(double a, double b){
		int i;
		double resp = 0;
		for(i = 0; i < prod.size(); i++){
			resp += prod.get(i).getPreço();
		}
		return resp + calculaFrete(a, 23.5);
	}

}

Add Calculo de distancia no frete


/**
 * Copyright 2017 Pivotal Software, Inc.
 *

 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *

 * http://www.apache.org/licenses/LICENSE-2.0
 *

 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package io.micrometer.core.instrument;

import io.micrometer.core.instrument.histogram.HistogramConfig;
import io.micrometer.core.instrument.histogram.TimeWindowHistogram;

public abstract class AbstractDistributionSummary extends AbstractMeter implements DistributionSummary {
    private final TimeWindowHistogram histogram;

    public AbstractDistributionSummary(Id id, Clock clock, HistogramConfig histogramConfig) {
        super(id);
        this.histogram = new TimeWindowHistogram(clock, histogramConfig);
    }

    @Override
    public final void record(double amount) {
        if (amount >= 0) {
            histogram.record((long) amount);
            recordNonNegative(amount);
        }
    }

    protected abstract void recordNonNegative(double amount);

    @Override
    public double percentile(double percentile) {
        return histogram.percentile(percentile);
    }

    @Override
    public double histogramCountAtValue(long value) {
        return histogram.histogramCountAtValue(value);
    }
}

/**
 * Copyright 2017 Pivotal Software, Inc.
 *

 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *

 * http://www.apache.org/licenses/LICENSE-2.0
 *

 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package io.micrometer.core.instrument;

import io.micrometer.core.instrument.histogram.HistogramConfig;
import io.micrometer.core.instrument.histogram.TimeWindowHistogram;

public abstract class AbstractDistributionSummary extends AbstractMeter implements DistributionSummary {
    private final TimeWindowHistogram histogram;

    public AbstractDistributionSummary(Id id, Clock clock, HistogramConfig histogramConfig) {
        super(id);
        this.histogram = new TimeWindowHistogram(clock, histogramConfig);
    }

    @Override
    public final void record(double amount) {
        if (amount >= 0) {
            histogram.record(amount);
            recordNonNegative(amount);
        }
    }

    protected abstract void recordNonNegative(double amount);

    @Override
    public double percentile(double percentile) {
        return histogram.percentile(percentile);
    }

    @Override
    public double histogramCountAtValue(long value) {
        return histogram.histogramCountAtValue(value);
    }
}

Remove erroneous cast to long in summary histogram recording


package org.sejda.core.support.prefix.processor;

import org.junit.Test;
import org.sejda.core.support.prefix.model.NameGenerationRequest;

import java.io.File;
import java.io.IOException;

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

public class TextPrefixProcessorTest {

    @Test
    public void producesFilenameFriendlyResults() throws IOException {
        String text = "This is an example\nof\t\f\r\n text;\\// that` is \" '' not filename friendly";
        NameGenerationRequest req = NameGenerationRequest.nameRequest().text(text);
        String actual = new TextPrefixProcessor().process("prefix-[TEXT]-suffix", req);
        assertEquals("prefix-This is an exampleof text that is   not filename friendly-suffix", actual);

        File file = File.createTempFile(actual, ".pdf");
        assertTrue(file.exists());
    }
}

package org.sejda.core.support.prefix.processor;

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

import java.io.File;
import java.io.IOException;

import org.junit.Test;
import org.sejda.core.support.prefix.model.NameGenerationRequest;

public class TextPrefixProcessorTest {

    @Test
    public void producesFilenameFriendlyResults() throws IOException {
        String text = "This is an example\nof\t\f\r\n text;\\// that` is \" '' not filename friendly";
        NameGenerationRequest req = NameGenerationRequest.nameRequest().text(text);
        String actual = new TextPrefixProcessor().process("prefix-[TEXT]-suffix", req);
        assertEquals("prefix-This is an exampleof text that is   not filename friendly-suffix", actual);

        File file = File.createTempFile(actual, ".pdf");
        assertTrue(file.exists());
        file.delete();
    }
}

Delete test file after creation


package com.annimon.jecp;

/**
 *
 * @author aNNiMON
 */
public interface ApplicationListener {

    public void onStartApp();

    public void onPauseApp();

    public void onDestroyApp();

    public void onPaint(JecpGraphics g);
}

package com.annimon.jecp;

/**
 *
 * @author aNNiMON
 */
public interface ApplicationListener {

    public void onStartApp(int width, int height);

    public void onPauseApp();

    public void onDestroyApp();

    public void onPaint(JecpGraphics g);
}

Add screen size to onStartApp method


package org.gbif.checklistbank.nub.source;

import org.gbif.api.vocabulary.Rank;
import org.gbif.checklistbank.nub.model.SrcUsage;

import java.util.List;
import java.util.UUID;

import org.junit.Test;

import static org.junit.Assert.assertEquals;

public class ClasspathUsageSourceTest {

  /**
   * integration test with prod registry
   * @throws Exception
   */
  @Test
  public void testListSources() throws Exception {
    ClasspathUsageSource src = ClasspathUsageSource.allSources();
    List<NubSource> sources = src.listSources();
    assertEquals(26, sources.size());
    assertEquals(1, sources.get(0).priority);
    assertEquals(Rank.FAMILY, sources.get(0).ignoreRanksAbove);
  }

  @Test
  public void testIterateSource() throws Exception {
    ClasspathUsageSource src = ClasspathUsageSource.emptySource();
    NubSource fungi = new NubSource();
    fungi.name = "squirrels";
    fungi.key = UUID.fromString("d7dddbf4-2cf0-4f39-9b2a-99b0e2c3aa01");
    fungi.ignoreRanksAbove = Rank.SPECIES;
    int counter = 0;
    for (SrcUsage u : src.iterateSource(fungi)) {
      counter++;
      System.out.print(u.key + "  ");
      System.out.println(u.scientificName);
    }
    assertEquals(9, counter);
  }
}

package org.gbif.checklistbank.nub.source;

import org.gbif.api.vocabulary.Rank;
import org.gbif.checklistbank.nub.model.SrcUsage;

import java.util.List;
import java.util.UUID;

import org.junit.Test;

import static org.junit.Assert.assertEquals;

public class ClasspathUsageSourceTest {

  /**
   * integration test with prod registry
   * @throws Exception
   */
  @Test
  public void testListSources() throws Exception {
    ClasspathUsageSource src = ClasspathUsageSource.allSources();
    List<NubSource> sources = src.listSources();
    assertEquals(27, sources.size());
    assertEquals(1, sources.get(0).priority);
    assertEquals(Rank.FAMILY, sources.get(0).ignoreRanksAbove);
  }

  @Test
  public void testIterateSource() throws Exception {
    ClasspathUsageSource src = ClasspathUsageSource.emptySource();
    NubSource fungi = new NubSource();
    fungi.name = "squirrels";
    fungi.key = UUID.fromString("d7dddbf4-2cf0-4f39-9b2a-99b0e2c3aa01");
    fungi.ignoreRanksAbove = Rank.SPECIES;
    int counter = 0;
    for (SrcUsage u : src.iterateSource(fungi)) {
      counter++;
      System.out.print(u.key + "  ");
      System.out.println(u.scientificName);
    }
    assertEquals(9, counter);
  }
}

Update test to latest number of 27 nub sources


package mirror;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;

public class Queues {

  // this is probably too large, but hopefully it will avoid inotify overflow exceptions
  public final BlockingQueue<Update> incomingQueue = new ArrayBlockingQueue<>(1_000_000);
  public final BlockingQueue<Update> saveToLocal = new ArrayBlockingQueue<>(1_000);
  public final BlockingQueue<Update> saveToRemote = new ArrayBlockingQueue<>(1_000);

}

package mirror;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

public class Queues {

  // this is probably too large, but hopefully it will avoid inotify overflow exceptions
  public final BlockingQueue<Update> incomingQueue = new LinkedBlockingQueue<>(1_000_000);
  // These need to be large enough so that when the SyncLogic thread is outputting the
  // results of a diff, and there are ~10k/100k new files to send, that it can completely
  // offload those Updates to the saveToRemote queue, so that it can unblock, and start
  // accepting new Updates from the incomingQueue.
  public final BlockingQueue<Update> saveToLocal = new LinkedBlockingQueue<>(1_000_000);
  public final BlockingQueue<Update> saveToRemote = new LinkedBlockingQueue<>(1_000_000);

}

Fix sends blocking due to small queue size.


package models;

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

import javax.persistence.Entity;
import javax.persistence.OneToMany;

import play.data.validation.MaxSize;
import play.data.validation.Required;
import play.db.jpa.Model;

@Entity
public class Track extends Model implements Comparable<Track>{
	@Required
	public String title;

	@Required
	@MaxSize(1)
	public Integer order;

	@OneToMany(mappedBy = "track")
	public List<Talk> talks = new ArrayList<Talk>();

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

	@Override
	public int compareTo(Track other) {
		return order.compareTo(other.order);
	}
}

package models;

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

import javax.persistence.Entity;
import javax.persistence.OneToMany;

import play.data.validation.MaxSize;
import play.data.validation.Required;
import play.db.jpa.Model;

@Entity
public class Track extends Model implements Comparable<Track>{
	@Required
	public String title;

	@Required
	@MaxSize(1)
	public int position;

	@OneToMany(mappedBy = "track")
	public List<Talk> talks = new ArrayList<Talk>();

	@Override
	public String toString(){
		return "[" + position + "] " + title;
	}

	@Override
	public int compareTo(Track other) {
		//return order.compareTo(other.order);
		return position - other.position;
	}
}

Rename "order" to "position" in the track object


package com.github.aureliano.evtbridge.core.matcher;

import java.util.regex.Pattern;

import com.github.aureliano.evtbridge.common.helper.StringHelper;

public class SingleLineMatcher implements IMatcher {

	private String prefixRegex;
	private String suffixRegex;

	private Pattern pattern;

	public SingleLineMatcher() {
		this(null);
	}

	public SingleLineMatcher(String prefixRegex) {
		this.prefixRegex = prefixRegex;
		this.suffixRegex = ".+$";

		if (StringHelper.isEmpty(this.prefixRegex)) {
			this.prefixRegex = "^(.+)";
			this.suffixRegex = "$";
		}

		this.pattern = Pattern.compile(this.prefixRegex);
	}

	@Override
	public boolean partialMatch(String text) {
		return this.pattern.matcher(text).find();
	}

	@Override
	public boolean matches(String text) {
		return text.matches(this.prefixRegex + this.suffixRegex);
	}

	@Override
	public String endMatch(String text) {
		return this.matches(text) ? text : null;
	}

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

package com.github.aureliano.evtbridge.core.matcher;

import java.util.regex.Pattern;

import com.github.aureliano.evtbridge.common.helper.StringHelper;

public class SingleLineMatcher implements IMatcher {

	private String prefixRegex;
	private String suffixRegex;

	private Pattern pattern;

	public SingleLineMatcher() {
		this(null);
	}

	public SingleLineMatcher(String prefixRegex) {
		this.prefixRegex = prefixRegex;
		this.suffixRegex = ".*$";

		if (StringHelper.isEmpty(this.prefixRegex)) {
			this.prefixRegex = "^(.*)";
			this.suffixRegex = "$";
		}

		this.pattern = Pattern.compile(this.prefixRegex);
	}

	@Override
	public boolean partialMatch(String text) {
		return this.pattern.matcher(text).find();
	}

	@Override
	public boolean matches(String text) {
		return text.matches(this.prefixRegex + this.suffixRegex);
	}

	@Override
	public String endMatch(String text) {
		return this.matches(text) ? text : null;
	}

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

Fix regular expression to also match an empty line.


package org.lvcp.eepperly.expr;

import java.util.List;

/**
 * Created by eepperly16 on 12/11/15.
 */
public class Variable implements Expr {
	private String varName;
	public Variable(List<Expr> arguments) {
		varName = "X";
	}

	public Expr differentiate(){
		return Expr.ONE;
	}
	public double evaluate(double value){ return value; }
	public String toString(){
		return varName;
	}
	public boolean equals(Object obj){
		return obj instanceof Variable;
	}
}

package org.lvcp.eepperly.expr;

import java.util.List;

/**
 * Created by eepperly16 on 12/11/15.
 */
public class Variable implements Expr {
	private String varName;
	public Variable() {
		varName = "X";
	}
	public Variable(String varName){
		this.varName = varName;
	}

	@Override
	public Expr differentiate(){
		return Expr.ONE;
	}

	@Override
	public double evaluate(double value){ return value; }

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

	public String getVarName() {
		return varName;
	}

	@Override
	public boolean equals(Object o) {
		if (this == o) return true;
		if (o == null || getClass() != o.getClass()) return false;

		Variable variable = (Variable) o;

		return !(varName != null ? !varName.equals(variable.varName) : variable.varName != null);

	}

	@Override
	public int hashCode() {
		return varName != null ? varName.hashCode() : 0;
	}
}

Add variable equality and improve constructor


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

import com.streamsets.pipeline.api.base.BaseEnumChooserValues;
import com.streamsets.pipeline.config.DataFormat;

public class DataFormatChooserValues extends BaseEnumChooserValues<DataFormat> {

  public DataFormatChooserValues() {
    super(
        DataFormat.SYSLOG,
        DataFormat.NETFLOW
    );
  }

}

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

import com.streamsets.pipeline.api.base.BaseEnumChooserValues;
import com.streamsets.pipeline.config.DataFormat;

public class DataFormatChooserValues extends BaseEnumChooserValues<DataFormat> {

  public DataFormatChooserValues() {
    super(
        DataFormat.AVRO,
        DataFormat.DELIMITED,
        DataFormat.JSON,
        DataFormat.LOG,
        DataFormat.NETFLOW,
        DataFormat.PROTOBUF,
        DataFormat.SYSLOG,
        DataFormat.XML
    );
  }

}

Add additional data formats to DataParser processor


package org.apache.lucene.spatial.test.strategy;

import org.apache.lucene.spatial.base.context.SpatialContext;
import org.apache.lucene.spatial.base.prefix.GeohashSpatialPrefixGrid;
import org.apache.lucene.spatial.strategy.SimpleSpatialFieldInfo;
import org.apache.lucene.spatial.strategy.prefix.DynamicPrefixStrategy;
import org.apache.lucene.spatial.test.SpatialMatchConcern;
import org.apache.lucene.spatial.test.StrategyTestCase;
import org.junit.Test;

import java.io.IOException;

public abstract class BaseGeohashStrategyTestCase extends StrategyTestCase<SimpleSpatialFieldInfo> {

  protected abstract SpatialContext getSpatialContext();

  @Override
  public void setUp() throws Exception {
    super.setUp();
    int maxLength = GeohashSpatialPrefixGrid.getMaxLevelsPossible();
    // SimpleIO
    this.shapeIO = getSpatialContext();
    this.strategy = new DynamicPrefixStrategy(new GeohashSpatialPrefixGrid(
        shapeIO, maxLength ));
    this.fieldInfo = new SimpleSpatialFieldInfo( "geohash" );
  }

  @Test
  public void testGeohashStrategy() throws IOException {
    getAddAndVerifyIndexedDocuments(DATA_WORLD_CITIES_POINTS);
    executeQueries(SpatialMatchConcern.FILTER, QTEST_Cities_IsWithin_BBox);
  }
}

package org.apache.lucene.spatial.test.strategy;

import org.apache.lucene.spatial.base.context.SpatialContext;
import org.apache.lucene.spatial.base.prefix.GeohashSpatialPrefixGrid;
import org.apache.lucene.spatial.strategy.SimpleSpatialFieldInfo;
import org.apache.lucene.spatial.strategy.prefix.DynamicPrefixStrategy;
import org.apache.lucene.spatial.test.SpatialMatchConcern;
import org.apache.lucene.spatial.test.StrategyTestCase;
import org.junit.Test;

import java.io.IOException;

public abstract class BaseGeohashStrategyTestCase extends StrategyTestCase<SimpleSpatialFieldInfo> {

  private int maxLength;

  protected abstract SpatialContext getSpatialContext();

  @Override
  public void setUp() throws Exception {
    super.setUp();
    maxLength = GeohashSpatialPrefixGrid.getMaxLevelsPossible();
    // SimpleIO
    this.shapeIO = getSpatialContext();
    this.strategy = new DynamicPrefixStrategy(new GeohashSpatialPrefixGrid(
        shapeIO, maxLength ));
    this.fieldInfo = new SimpleSpatialFieldInfo( "geohash" );
  }

  @Test
  public void testGeohashStrategy() throws IOException {
    getAddAndVerifyIndexedDocuments(DATA_WORLD_CITIES_POINTS);

    //execute queries for each prefix grid scan level
    for(int i = 0; i <= maxLength; i++) {
      ((DynamicPrefixStrategy)strategy).setPrefixGridScanLevel(i);
      executeQueries(SpatialMatchConcern.FILTER, QTEST_Cities_IsWithin_BBox);
    }
  }
}

Test DynamicPrefixStrategy for each grid scan level (an internal threshold) to tease out possible bugs.


package com.tmitim.twittercli.commands;

import java.util.List;

import org.apache.commons.lang3.StringUtils;

import com.github.rvesse.airline.SingleCommand;
import com.github.rvesse.airline.annotations.Arguments;
import com.github.rvesse.airline.annotations.Command;
import com.github.rvesse.airline.annotations.Option;

import twitter4j.Status;
import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;

/**
 * Tweet to twitter
 *
 */
@Command(name = "tweet", description = "Tweet your thoughts")
public class Tweet implements Runnable {

	@Option(name = { "-f", "--flag" }, description = "An option that requires no values")
	private boolean flag = false;

	@Arguments(description = "Additional arguments")
	private List<String> args;

	public static void main(String[] args) {
		SingleCommand<Tweet> parser = SingleCommand.singleCommand(Tweet.class);
		Tweet cmd = parser.parse(args);
		cmd.run();
	}

	public void run() {
		Twitter twitter = TwitterFactory.getSingleton();

		try {
			Status status = twitter.updateStatus(StringUtils.join(args, " "));
			System.out.println("Successfully updated the status to [" + status.getText() + "].");

		} catch (TwitterException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		System.out.println("Flag was " + (this.flag ? "set" : "not set"));
		if (args != null)
			System.out.println("Arguments were " + StringUtils.join(args, " "));
	}
}

package com.tmitim.twittercli.commands;

import java.util.List;

import org.apache.commons.lang3.StringUtils;

import com.github.rvesse.airline.SingleCommand;
import com.github.rvesse.airline.annotations.Arguments;
import com.github.rvesse.airline.annotations.Command;
import twitter4j.Status;
import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;

/**
 * Tweet to twitter
 *
 */
@Command(name = "tweet", description = "Tweet your thoughts")
public class Tweet implements Runnable {

	@Arguments(description = "Additional arguments")
	private List<String> args;

	public static void main(String[] args) {
		SingleCommand<Tweet> parser = SingleCommand.singleCommand(Tweet.class);
		Tweet cmd = parser.parse(args);
		cmd.run();
	}

	@Override
	public void run() {
		Twitter twitter = TwitterFactory.getSingleton();

		try {
			Status status = twitter.updateStatus(StringUtils.join(args, " "));
			System.out.println("Successfully updated the status to [" + status.getText() + "].");

		} catch (TwitterException e) {
			e.printStackTrace();
		}
	}
}

Remove unused argument/flag when tweeting


package com.khmelenko.lab.sensorsclient.network;

import com.khmelenko.lab.sensorsclient.network.response.Device;
import com.khmelenko.lab.sensorsclient.network.response.WeatherData;

import java.util.List;

import retrofit.http.GET;
import rx.Observable;

/**
 * API Service
 *
 * @author Dmytro Khmelenko
 */
public interface ApiService {

    @GET("/devices")
    Observable<List<Device>> getDevices();

    @GET("/devices/{name}/current")
    Observable<Device> getCurrentData();

    @GET("/devices/{name}/history")
    Observable<List<WeatherData>> getHistory();

}

package com.khmelenko.lab.sensorsclient.network;

import com.khmelenko.lab.sensorsclient.network.response.Device;
import com.khmelenko.lab.sensorsclient.network.response.WeatherData;

import java.util.List;

import retrofit.http.GET;
import rx.Observable;

/**
 * API Service
 *
 * @author Dmytro Khmelenko
 */
public interface ApiService {

    @GET("/devices")
    Observable<List<Device>> getDevices();

    @GET("/devices/{name}/current")
    Observable<WeatherData> getCurrentData();

    @GET("/devices/{name}/history")
    Observable<List<WeatherData>> getHistory();

}

Update API usage in client app


package nallar.tickthreading.mixin.world;

import me.nallar.mixin.Add;
import me.nallar.mixin.Mixin;
import net.minecraft.world.World;

@Mixin
public abstract class MixinWorld extends World {
	@Add
	public boolean unloaded_;
	@Add
	private String cachedName_;

	protected MixinWorld() {
		super(null, null, null, null, false);
	}

	@Add
	public int getDimensionId() {
		return provider.getDimensionType().getId();
	}

	@Add
	public String getName() {
		String name = cachedName;
		if (name != null) {
			return name;
		}
		int dimensionId = getDimensionId();
		name = worldInfo.getWorldName();
		if (name.equals("DIM" + dimensionId) || "world".equals(name)) {
			name = provider.getDimensionType().getName();
		}
		if (name.startsWith("world_") && name.length() != 6) {
			name = name.substring(6);
		}
		name += '/' + dimensionId + (isRemote ? "-r" : "");
		cachedName = name;
		return name;
	}
}

package nallar.tickthreading.mixin.world;

import me.nallar.mixin.Add;
import me.nallar.mixin.Mixin;
import net.minecraft.world.World;

@Mixin
public abstract class MixinWorld extends World {
	@Add
	public boolean unloaded_;
	@Add
	private String cachedName_;

	protected MixinWorld() {
		super(null, null, null, null, false);
	}

	@Add
	public int getDimensionId() {
		return provider.getDimensionType().getId();
	}

	@Add
	public String getName() {
		String name = cachedName;
		if (name != null) {
			return name;
		}
		int dimensionId = getDimensionId();
		name = worldInfo.getWorldName();
		if (name.equals("DIM" + dimensionId) || "world".equals(name)) {
			name = provider.getDimensionType().getName();
		}
		if (name.startsWith("world_") && name.length() != 6) {
			name = name.substring(6);
		}
		name += '/' + dimensionId + (isRemote ? "-r" : "");
		cachedName = name;
		return name;
	}

	@Add
	public String toString() {
		return "World " + System.identityHashCode(this) + " " + getName();
	}
}

Add more useful toString for World than the default


package core;

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

import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;

import static org.junit.Assert.*;

/**
 * Created by user on 18-5-2016.
 */
public class ParserTest {
    public Parser p;

    /**
     * Initialize the Parser before testing it.
     */
    @Before
    public void setUp() {
        p = new Parser();
    }

    /**
     * Test the constructor.
     */
    @Test
    public void testConstructor() {
        assertNotNull(p);
    }

    /**
     * Test the readGFA method.
     */
    @Test
    public void readGFA() {
        HashMap<Integer, Node> map = new HashMap<Integer, Node>();
        InputStream is = getClass().getResourceAsStream("/TBTestFile.gfa");

        try {
            map = p.readGFA(is);
            is.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

        assertEquals(4, map.size());

        for (int i = 1; i <= 4; i++) {
            Node n = map.get(i);
            assertEquals(i, n.getId());
            assertEquals(Character.toString((char) ('A' + i - 1)), n.getSequence());
            assertEquals(i, n.getzIndex());
            assertEquals("GENOME_1", n.getGenomes().get(0));
            assertEquals(new Integer(i + 1), n.getLinks().get(0));
        }
    }

}

package core;

import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import org.junit.Before;
import org.junit.Test;

import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;

import static org.junit.Assert.*;

/**
 * Created by user on 18-5-2016.
 */
public class ParserTest {
    public Parser p;

    /**
     * Initialize the Parser before testing it.
     */
    @Before
    public void setUp() {
        p = new Parser();
    }

    /**
     * Test the constructor.
     */
    @Test
    public void testConstructor() {
        assertNotNull(p);
    }

    /**
     * Test the readGFA method.
     */
    @SuppressFBWarnings("OBL_UNSATISFIED_OBLIGATION_EXCEPTION_EDGE")
    @Test
    public void readGFA() {
        HashMap<Integer, Node> map = new HashMap<Integer, Node>();
        InputStream is = getClass().getResourceAsStream("/TBTestFile.gfa");

        try {
            map = p.readGFA(is);
            is.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

        assertEquals(4, map.size());

        for (int i = 1; i <= 4; i++) {
            Node n = map.get(i);
            assertEquals(i, n.getId());
            assertEquals(Character.toString((char) ('A' + i - 1)), n.getSequence());
            assertEquals(i, n.getzIndex());
            assertEquals("GENOME_1", n.getGenomes().get(0));
            assertEquals(Integer.valueOf(i + 1), n.getLinks().get(0));
        }
    }

}

Fix FindBugs warnings in Parser Test.