package com.techcavern.wavetact.commands.utils;

import com.techcavern.wavetact.annot.CMD;
import com.techcavern.wavetact.objects.Command;
import com.techcavern.wavetact.utils.GeneralUtils;
import com.techcavern.wavetact.utils.PermUtils;
import org.pircbotx.hooks.events.MessageEvent;

public class CheckUserLevel extends Command {

    @CMD
    public CheckUserLevel() {
        super(GeneralUtils.toArray(" checkuserlevel level checklevel"), 0, "Checks User Level, 0 arguments");
    }

    @Override
    public void onCommand(MessageEvent<?> event, String... args) throws Exception {
        int i = PermUtils.getPermLevel(event.getBot(), event.getUser(), event.getChannel());
        if (i == 9001) {
            event.respond("You are my Master!");
        } else if (i == 15) {
            event.respond("You are a Channel Owner!");

        } else if (i == 10) {
            event.respond("You are a Channel Operator!");
        } else if (i == 5) {
            event.respond("You are a Trusted User!");
        } else {
            event.respond("You are a Regular User!");
        }
    }
}

package com.techcavern.wavetact.commands.utils;

import com.techcavern.wavetact.annot.CMD;
import com.techcavern.wavetact.objects.Command;
import com.techcavern.wavetact.utils.GeneralUtils;
import com.techcavern.wavetact.utils.PermUtils;
import org.pircbotx.hooks.events.MessageEvent;

public class CheckUserLevel extends Command {

    @CMD
    public CheckUserLevel() {
        super(GeneralUtils.toArray("checkuserlevel level checklevel"), 0, "Checks User Level, 0 arguments");
    }

    @Override
    public void onCommand(MessageEvent<?> event, String... args) throws Exception {
        int i = PermUtils.getPermLevel(event.getBot(), event.getUser(), event.getChannel());
        if (i == 9001) {
            event.respond("You are my Master!");
        } else if (i == 15) {
            event.respond("You are a Channel Owner!");

        } else if (i == 10) {
            event.respond("You are a Channel Operator!");
        } else if (i == 5) {
            event.respond("You are a Trusted User!");
        } else {
            event.respond("You are a Regular User!");
        }
    }
}

Fix spacing (More OCD, than anything else :S)


/*
 * Copyright 2015 The ISTLab. Use of this source code is governed by a GNU AFFERO GPL 3.0 license
 * that can be found in the LICENSE file.
 */

package gr.aueb.dmst.istlab.unixtools.plugin;

import org.eclipse.ui.plugin.AbstractUIPlugin;
import org.osgi.framework.BundleContext;

import gr.aueb.dmst.istlab.unixtools.util.PropertiesLoader;

/**
 * The activator class controls the plug-in life cycle
 */
public class Activator extends AbstractUIPlugin {

  /** The plug-in ID */
  public static final String PLUGIN_ID = "gr.aueb.dmst.istlab.unixtools.plugin";
  /** The shared instance */
  private static Activator plugin;

  public Activator() {}

  @Override
  public void start(BundleContext context) throws Exception {
    // load plugin's properties
    PropertiesLoader.loadPropertiesFile();
    super.start(context);
    plugin = this;
  }

  @Override
  public void stop(BundleContext context) throws Exception {
    plugin = null;
    // close properties file
    PropertiesLoader.closePropertiesFile();
    super.stop(context);
  }

  /**
   * Returns the shared instance
   *
   * @return the shared instance
   */
  public static Activator getDefault() {
    return plugin;
  }

}

/*
 * Copyright 2015 The ISTLab. Use of this source code is governed by a GNU AFFERO GPL 3.0 license
 * that can be found in the LICENSE file.
 */

package gr.aueb.dmst.istlab.unixtools.plugin;

import org.eclipse.ui.plugin.AbstractUIPlugin;
import org.osgi.framework.BundleContext;

import gr.aueb.dmst.istlab.unixtools.util.LoggerUtil;
import gr.aueb.dmst.istlab.unixtools.util.PropertiesLoader;

/**
 * The activator class controls the plug-in life cycle
 */
public class Activator extends AbstractUIPlugin {

  /** The plug-in ID */
  public static final String PLUGIN_ID = "gr.aueb.dmst.istlab.unixtools.plugin";
  /** The shared instance */
  private static Activator plugin;

  public Activator() {}

  @Override
  public void start(BundleContext context) throws Exception {
    // load plugin's properties
    super.start(context);
    plugin = this;
    LoggerUtil.configureLogger();
    PropertiesLoader.loadPropertiesFile();
  }

  @Override
  public void stop(BundleContext context) throws Exception {
    plugin = null;
    // close properties file
    PropertiesLoader.closePropertiesFile();
    super.stop(context);
  }

  /**
   * Returns the shared instance
   *
   * @return the shared instance
   */
  public static Activator getDefault() {
    return plugin;
  }

}

Fix issue with config file not loading correctly


package com.ForgeEssentials.permission.mcoverride;

import cpw.mods.fml.common.event.FMLServerStartingEvent;

// Hopefully we can transform the stuff in and we won't need this class.

public class OverrideManager
{

	public static void regOverrides(FMLServerStartingEvent e)
	{
		e.registerServerCommand(new CommandBanIp());
		e.registerServerCommand(new CommandBanlist());
		e.registerServerCommand(new CommandDebug());
		e.registerServerCommand(new CommandDefaultGameMode());
		e.registerServerCommand(new CommandDeop());
		e.registerServerCommand(new CommandDifficulty());
		e.registerServerCommand(new CommandGameRule());
		e.registerServerCommand(new CommandHelp());
		e.registerServerCommand(new CommandKick());
		e.registerServerCommand(new CommandMe());
		e.registerServerCommand(new CommandOp());
		e.registerServerCommand(new CommandPardonIp());
		e.registerServerCommand(new CommandPublish());
		e.registerServerCommand(new CommandSaveAll());
		e.registerServerCommand(new CommandSaveOff());
		e.registerServerCommand(new CommandSaveOn());
		e.registerServerCommand(new CommandSay());
		e.registerServerCommand(new CommandSeed());
		e.registerServerCommand(new CommandSetSpawn());
		e.registerServerCommand(new CommandStop());
		e.registerServerCommand(new CommandToggleDownfall());
		e.registerServerCommand(new CommandXP());
		e.registerServerCommand(new CommandTestFor());
	}

}

package com.ForgeEssentials.permission.mcoverride;

import cpw.mods.fml.common.event.FMLServerStartingEvent;

// Hopefully we can transform the stuff in and we won't need this class.

public class OverrideManager
{

	public static void regOverrides(FMLServerStartingEvent e)
	{
		e.registerServerCommand(new CommandBanIp());
		e.registerServerCommand(new CommandBanlist());
		e.registerServerCommand(new CommandDebug());
		e.registerServerCommand(new CommandDefaultGameMode());
		e.registerServerCommand(new CommandDeop());
		e.registerServerCommand(new CommandDifficulty());
		e.registerServerCommand(new CommandGameRule());
		e.registerServerCommand(new CommandKick());
		e.registerServerCommand(new CommandMe());
		e.registerServerCommand(new CommandOp());
		e.registerServerCommand(new CommandPardonIp());
		e.registerServerCommand(new CommandPublish());
		e.registerServerCommand(new CommandSaveAll());
		e.registerServerCommand(new CommandSaveOff());
		e.registerServerCommand(new CommandSaveOn());
		e.registerServerCommand(new CommandSay());
		e.registerServerCommand(new CommandSeed());
		e.registerServerCommand(new CommandSetSpawn());
		e.registerServerCommand(new CommandStop());
		e.registerServerCommand(new CommandToggleDownfall());
		e.registerServerCommand(new CommandXP());
		e.registerServerCommand(new CommandTestFor());
	}

}

Fix /help - part 2


package com.syntactec.subreddify.services;

import android.app.AlarmManager;
import android.app.IntentService;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.SystemClock;
import android.preference.PreferenceManager;
import android.util.Log;

/**
 * This class defines a service which will schedule the notification service to run at the user defined interval.
 */
public class SchedulerService extends IntentService {

    private final AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);

    public SchedulerService() {
        super("SchedulerService");
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        Intent serviceIntent = new Intent(this, PollerService.class);
        PendingIntent pendingIntent = PendingIntent.getService(this, 0, serviceIntent,
                PendingIntent.FLAG_CANCEL_CURRENT);

        Log.d("SchedulerService", "Canceling the active alarm.");
        alarmManager.cancel(pendingIntent);

        String sync_frequency = PreferenceManager.getDefaultSharedPreferences(this)
                .getString("sync_frequency", "-1");

        if (sync_frequency.equals("-1")) {
            return;
        }

        int syncMillis = 60000 * Integer.parseInt(sync_frequency);

        Log.d("SchedulerService", "Creating alarm manager: Preference is " + syncMillis);
        alarmManager.setInexactRepeating(AlarmManager.ELAPSED_REALTIME,
                SystemClock.elapsedRealtime(),
                syncMillis,
                pendingIntent);
    }
}

package com.syntactec.subreddify.services;

import android.app.AlarmManager;
import android.app.IntentService;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.SystemClock;
import android.preference.PreferenceManager;
import android.util.Log;

/**
 * This class defines a service which will schedule the notification service to run at the user defined interval.
 */
public class SchedulerService extends IntentService {

    private AlarmManager alarmManager;

    public SchedulerService() {
        super("SchedulerService");
    }

    @Override
    public void onCreate() {
        super.onCreate();

        alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        Intent serviceIntent = new Intent(this, PollerService.class);
        PendingIntent pendingIntent = PendingIntent.getService(this, 0, serviceIntent,
                PendingIntent.FLAG_CANCEL_CURRENT);

        Log.d("SchedulerService", "Canceling the active alarm.");
        alarmManager.cancel(pendingIntent);

        String sync_frequency = PreferenceManager.getDefaultSharedPreferences(this)
                .getString("sync_frequency", "-1");

        if (sync_frequency.equals("-1")) {
            return;
        }

        int syncMillis = 60000 * Integer.parseInt(sync_frequency);

        Log.d("SchedulerService", "Creating alarm manager: Preference is " + syncMillis);
        alarmManager.setInexactRepeating(AlarmManager.ELAPSED_REALTIME,
                SystemClock.elapsedRealtime(),
                syncMillis,
                pendingIntent);
    }
}

Move static initialization into onCreate() method.


package org.blitzortung.android.app.controller;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import org.blitzortung.android.app.Main;
import org.blitzortung.android.app.R;

public class NotificationHandler {

    private final NotificationManager notificationService;
    private final Context context;

    public NotificationHandler(Context context) {
        notificationService = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
        this.context = context;

    }

    public void sendNotification(String notificationText) {
        if (notificationService != null) {
            Notification notification = new Notification(R.drawable.icon, notificationText, System.currentTimeMillis());
            PendingIntent contentIntent = PendingIntent.getActivity(context, 0, new Intent(context, Main.class), 0);
            notification.setLatestEventInfo(context, context.getResources().getText(R.string.app_name), notificationText, contentIntent);

            notificationService.notify(R.id.alarm_notification_id, notification);
        }
    }

    public void clearNotification() {
        if (notificationService != null) {
            notificationService.cancel(R.id.alarm_notification_id);
        }
    }
}

package org.blitzortung.android.app.controller;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.TaskStackBuilder;
import android.content.Context;
import android.content.Intent;
import org.blitzortung.android.app.Main;
import org.blitzortung.android.app.R;

public class NotificationHandler {

    private final NotificationManager notificationService;
    private final Context context;

    public NotificationHandler(Context context) {
        notificationService = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
        this.context = context;
    }

    public void sendNotification(String notificationText) {
        if (notificationService != null) {
            Intent intent = new Intent(context, Main.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
            PendingIntent contentIntent = PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);

            Notification.Builder notificationBuilder =
                    new Notification.Builder(context)
                            .setSmallIcon(R.drawable.icon)
                            .setContentTitle(context.getResources().getText(R.string.app_name))
                            .setContentText(notificationText)
                            .setContentIntent(contentIntent);

            notificationService.notify(R.id.alarm_notification_id, notificationBuilder.getNotification());
        }
    }

    public void clearNotification() {
        if (notificationService != null) {
            notificationService.cancel(R.id.alarm_notification_id);
        }
    }
}

Use NotificationBuilder instead of the Notification to create a new Notification


package com.reactnativeexample;

import android.app.Application;

import com.facebook.react.ReactApplication;
import com.facebook.react.ReactNativeHost;
import com.facebook.react.ReactPackage;
import com.facebook.react.shell.MainReactPackage;
import com.facebook.soloader.SoLoader;

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

import io.sentry.RNSentryPackage;

public class MainApplication extends Application implements ReactApplication {

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

        @Override
        protected List<ReactPackage> getPackages() {
            RNSentryPackage.useDeveloperSupport = this.getUseDeveloperSupport();
            return Arrays.<ReactPackage>asList(
                    new MainReactPackage(),
                    new RNSentryPackage()
            );
        }
    };

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

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

package com.reactnativeexample;

import android.app.Application;

import com.facebook.react.ReactApplication;
import com.facebook.react.ReactNativeHost;
import com.facebook.react.ReactPackage;
import com.facebook.react.shell.MainReactPackage;
import com.facebook.soloader.SoLoader;

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

import io.sentry.RNSentryPackage;

public class MainApplication extends Application implements ReactApplication {

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

        @Override
        protected List<ReactPackage> getPackages() {
            return Arrays.<ReactPackage>asList(
                    new MainReactPackage(),
                    new RNSentryPackage(MainApplication.this)
            );
        }
    };

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

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

Add right RNSentryPackage call in example project


package sfBugsNew;

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

public class Bug1219 {

    interface A {
    }

    interface B {
    }

    A objectA;

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

package sfBugsNew;

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

public class Bug1219 {

    interface A {
    }

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

    A objectA;

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

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

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

Add test case for when interfaces do have concrete implementations


package com.gurkensalat.osm.repository;

import com.gurkensalat.osm.entity.LinkedPlace;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.PagingAndSortingRepository;
import org.springframework.data.repository.query.Param;
import org.springframework.data.rest.core.annotation.RepositoryRestResource;

import javax.transaction.Transactional;

@RepositoryRestResource(collectionResourceRel = "linkedPlace", path = "linkedPlace")
public interface LinkedPlaceRepository extends PagingAndSortingRepository<LinkedPlace, Long>
{
    Iterable<LinkedPlace> findAllByOsmId(@Param("OSM_ID") String osmId);

    Iterable<LinkedPlace> findAllByDitibCode(@Param("DITIB_CODE") String ditibCode);

    @Modifying
    @Transactional
    @Query("update LinkedPlace set valid = 'f'")
    void invalidateAll();

    @Modifying
    @Transactional
    @Query("delete from LinkedPlace where valid = 'f'")
    void deleteAllInvalid();
}

package com.gurkensalat.osm.repository;

import com.gurkensalat.osm.entity.LinkedPlace;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.PagingAndSortingRepository;
import org.springframework.data.repository.query.Param;
import org.springframework.data.rest.core.annotation.RepositoryRestResource;

import javax.transaction.Transactional;

@RepositoryRestResource(collectionResourceRel = "linkedPlace", path = "linkedPlace")
public interface LinkedPlaceRepository extends PagingAndSortingRepository<LinkedPlace, Long>
{
    Iterable<LinkedPlace> findAllByOsmId(@Param("OSM_ID") String osmId);

    Iterable<LinkedPlace> findAllByDitibCode(@Param("DITIB_CODE") String ditibCode);

    @Modifying
    @Transactional
    @Query("update LinkedPlace set valid = false")
    void invalidateAll();

    @Modifying
    @Transactional
    @Query("delete from LinkedPlace where valid = false")
    void deleteAllInvalid();
}

Use proper syntax for boolean attributes


package com.facebook.presto.operator.aggregation;

import com.facebook.presto.block.Block;
import com.facebook.presto.block.BlockBuilder;

import static com.facebook.presto.operator.aggregation.CountColumnAggregation.COUNT_COLUMN;
import static com.facebook.presto.tuple.TupleInfo.SINGLE_LONG;

public class TestCountColumnAggregation
    extends AbstractTestAggregationFunction
{
    @Override
    public Block getSequenceBlock(int start, int length)
    {
        BlockBuilder blockBuilder = new BlockBuilder(SINGLE_LONG);
        for (int i = start; i < start + length; i++) {
            blockBuilder.append(i);
        }
        return blockBuilder.build();
    }

    @Override
    public AggregationFunction getFunction()
    {
        return COUNT_COLUMN;
    }

    @Override
    public Number getExpectedValue(int start, int length)
    {
        if (length == 0) {
            return null;
        }
        return (long) length;
    }
}

package com.facebook.presto.operator.aggregation;

import com.facebook.presto.block.Block;
import com.facebook.presto.block.BlockBuilder;

import static com.facebook.presto.operator.aggregation.CountColumnAggregation.COUNT_COLUMN;
import static com.facebook.presto.tuple.TupleInfo.SINGLE_LONG;

public class TestCountColumnAggregation
    extends AbstractTestAggregationFunction
{
    @Override
    public Block getSequenceBlock(int start, int length)
    {
        BlockBuilder blockBuilder = new BlockBuilder(SINGLE_LONG);
        for (int i = start; i < start + length; i++) {
            blockBuilder.append(i);
        }
        return blockBuilder.build();
    }

    @Override
    public AggregationFunction getFunction()
    {
        return COUNT_COLUMN;
    }

    @Override
    public Number getExpectedValue(int start, int length)
    {
        return (long) length;
    }
}

Fix broken tests for count column


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

package com.google.errorprone.refaster.testdata.template;

import com.google.common.truth.IterableSubject;
import com.google.errorprone.refaster.annotation.AfterTemplate;
import com.google.errorprone.refaster.annotation.BeforeTemplate;

import java.util.Collection;

/**
 * Tests for {@code UFreeIdent} accepting two references to the same wildcard.
 *
 * @author kak@google.com (Kurt Kluever)
 */
public class WildcardUnificationTemplate {
  @BeforeTemplate
  static void containsAllOf(IterableSubject<?, ?, ?> subject, Collection<?> expected) {
    subject.hasSize(expected.size());
    subject.containsAllIn(expected);
  }

  @AfterTemplate
  static void containsExactly(IterableSubject<?, ?, ?> subject, Collection<?> expected) {
    subject.containsExactlyElementsIn(expected);
  }
}

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

package com.google.errorprone.refaster.testdata.template;

import com.google.common.truth.IterableSubject;
import com.google.errorprone.refaster.annotation.AfterTemplate;
import com.google.errorprone.refaster.annotation.BeforeTemplate;

import java.util.Collection;

/**
 * Tests for {@code UFreeIdent} accepting two references to the same wildcard.
 *
 * @author Kurt Alfred Kluever
 */
public class WildcardUnificationTemplate {
  @BeforeTemplate
  static void containsAllOf(IterableSubject subject, Collection<?> expected) {
    subject.hasSize(expected.size());
    subject.containsAllIn(expected);
  }

  @AfterTemplate
  static void containsExactly(IterableSubject subject, Collection<?> expected) {
    subject.containsExactlyElementsIn(expected);
  }
}

Remove type parameters from IterableSubject, MultisetSubject, and MultimapSubject.


package controller;

import constant.Urls;
import domain.Protocol;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import repository.ProtocolRepository;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Controller
public class ProtocolController {

    ////////////////////////////////////////////////
    // ATTRIBUTES

    @Autowired
    private ProtocolRepository protocolRepository;

    ////////////////////////////////////////////////
    // METHODS

    @ResponseBody
    @RequestMapping(value = Urls.PROTOCOL_API, method = RequestMethod.POST)
    public String createProtocol(@RequestBody Protocol protocol,
                                 HttpServletRequest request,
                                 HttpServletResponse response) throws IOException {
        String newProtocolId = protocolRepository.addProtocol(protocol);
        String protocolUrl = request.getContextPath() + Urls.PROTOCOL_API + '/' + newProtocolId;

        response.setStatus(HttpStatus.CREATED.value());
        response.sendRedirect(protocolUrl);

        return protocolUrl;
    }

    @ResponseBody
    @RequestMapping(value = Urls.PROTOCOL_API_TEMPLATE, method = RequestMethod.GET)
    public Protocol getProtocol(@PathVariable String id) {
        return protocolRepository.getById(id);
    }

    @RequestMapping(value = Urls.PROTOCOL_API_TEMPLATE, method = RequestMethod.PUT)
    public void updateProtocol(@PathVariable String id, @RequestBody Protocol protocol) {
        protocol.setId(id);
        protocolRepository.updateProtocol(protocol);
    }
}

package controller;

import constant.Urls;
import domain.Protocol;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import repository.ProtocolRepository;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@Controller
public class ProtocolController {

    ////////////////////////////////////////////////
    // ATTRIBUTES

    @Autowired
    private ProtocolRepository protocolRepository;

    ////////////////////////////////////////////////
    // METHODS

    @ResponseBody
    @RequestMapping(value = Urls.PROTOCOL_API, method = RequestMethod.POST)
    public String createProtocol(@RequestBody Protocol protocol,
                                 HttpServletRequest request,
                                 HttpServletResponse response) throws IOException {
        String newProtocolId = protocolRepository.addProtocol(protocol);
        String protocolUrl = request.getContextPath() + Urls.PROTOCOL_API + '/' + newProtocolId;

        response.setStatus(HttpStatus.CREATED.value());
        response.sendRedirect(protocolUrl);

        return protocolUrl;
    }

    @ResponseBody
    @RequestMapping(value = Urls.PROTOCOL_API, method = RequestMethod.GET)
    public List<Protocol> getProtocolList() {
        return protocolRepository.getAll();
    }

    @ResponseBody
    @RequestMapping(value = Urls.PROTOCOL_API_TEMPLATE, method = RequestMethod.GET)
    public Protocol getProtocol(@PathVariable String id) {
        return protocolRepository.getById(id);
    }

    @RequestMapping(value = Urls.PROTOCOL_API_TEMPLATE, method = RequestMethod.PUT)
    public void updateProtocol(@PathVariable String id, @RequestBody Protocol protocol) {
        protocol.setId(id);
        protocolRepository.updateProtocol(protocol);
    }
}

Add method to get protocol list


package seedu.ezdo.model.todo;

import seedu.ezdo.commons.exceptions.IllegalValueException;

/**
 * Represents the due date of a todo.
 */
public class DueDate {

    public static final String MESSAGE_DUEDATE_CONSTRAINTS =
            "Due dates should be in the format DD/MM/YYYY, and it should not be blank";

    public static final String DUEDATE_VALIDATION_REGEX = "([12][0-9]|3[01]|0?[1-9])/(0?[1-9]|1[012])/((?:19|20)\\d\\d)";

    public final String value;

    /**
     * Validates given due date.
     *
     * @throws IllegalValueException if given due date string is invalid.
     */
    public DueDate(String dueDate) throws IllegalValueException {
        assert dueDate != null;
        if (!isValidDueDate(dueDate)) {
            throw new IllegalValueException(MESSAGE_DUEDATE_CONSTRAINTS);
        }
        this.value = dueDate;
    }

    /**
     * Returns true if a given string is a valid due date.
     */
    public static boolean isValidDueDate(String test) {
        return test.matches(DUEDATE_VALIDATION_REGEX);
    }

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

    @Override
    public boolean equals(Object other) {
        return other == this // short circuit if same object
                || (other instanceof DueDate // instanceof handles nulls
                && this.value.equals(((DueDate) other).value)); // state check
    }

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

}

Add linebreak to improve readability


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

import java.nio.ByteBuffer;
import java.util.List;

import backtype.storm.tuple.Fields;

import static backtype.storm.utils.Utils.tuple;
import static java.util.Arrays.asList;

public class RawMultiScheme implements MultiScheme {
  @Override
  public Iterable<List<Object>> deserialize(ByteBuffer ser) {
    return asList(tuple(ser));
  }

  @Override
  public Fields getOutputFields() {
    return new Fields("bytes");
  }
}

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

import java.nio.ByteBuffer;
import java.util.List;

import backtype.storm.tuple.Fields;
import backtype.storm.utils.Utils;

import static backtype.storm.utils.Utils.tuple;
import static java.util.Arrays.asList;

public class RawMultiScheme implements MultiScheme {
  @Override
  public Iterable<List<Object>> deserialize(ByteBuffer ser) {
    return asList(tuple(Utils.toByteArray(ser)));
  }

  @Override
  public Fields getOutputFields() {
    return new Fields("bytes");
  }
}

Fix Kafka spout to maintain backward compatibility


package com.xtremelabs.robolectric;

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

import com.xtremelabs.robolectric.bytecode.RobolectricClassLoader;

@RunWith(WithTestDefaultsRunner.class)
public class RobolectricTestRunnerClassloaderSetup {

    @Test
    public void testUsingClassloader() throws ClassNotFoundException {
        ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
        Assert.assertEquals(classLoader.getClass().getName(), RobolectricClassLoader.class.getName());

    }
}

package com.xtremelabs.robolectric;

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

import com.xtremelabs.robolectric.bytecode.RobolectricClassLoader;

@RunWith(WithTestDefaultsRunner.class)
public class RobolectricTestRunnerClassLoaderSetup {

    @Test
    public void testUsingClassLoader() throws ClassNotFoundException {
        ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
        Assert.assertEquals(classLoader.getClass().getName(), RobolectricClassLoader.class.getName());
    }
}

Fix test class spelling, formatting


package com.addthis.hydra.data.query;

import org.junit.Test;

public class TestOpDateFormat extends TestOp {

    @Test
    public void testOpDateFormat() throws Exception {
        doOpTest(
                new DataTableHelper().
                        tr().td("140101").
                        tr().td("140108"),
                "datef=0:yyMMdd:yyww",
                new DataTableHelper().
                        tr().td("1401").
                        tr().td("1402")
        );
        doOpTest(
                new DataTableHelper().
                        tr().td("140101", "0").
                        tr().td("140108", "0"),
                "datef=0:yyMMdd:yyww:1",
                new DataTableHelper().
                        tr().td("140101", "1401").
                        tr().td("140108", "1402")
        );
        doOpTest(
                new DataTableHelper().
                        tr().td("1418078000000", "0"),
                "datef=0:unixmillis:yyMMdd:1",
                new DataTableHelper().
                        tr().td("1418078000000", "141208")
        );
    }
}

package com.addthis.hydra.data.query;

import org.joda.time.format.DateTimeFormat;
import org.junit.Test;

public class TestOpDateFormat extends TestOp {

    @Test
    public void testConvertDatesInPlace() throws Exception {
        doOpTest(
                new DataTableHelper().
                        tr().td("140101").
                        tr().td("140108"),
                "datef=0:yyMMdd:yyww",
                new DataTableHelper().
                        tr().td("1401").
                        tr().td("1402")
        );
    }

    @Test
    public void testConvertDatesDifferentColumn() throws Exception {
        doOpTest(
                new DataTableHelper().
                        tr().td("140101", "0").
                        tr().td("140108", "0"),
                "datef=0:yyMMdd:yyww:1",
                new DataTableHelper().
                        tr().td("140101", "1401").
                        tr().td("140108", "1402")
        );
    }

    @Test
    public void testParseUnixMillis() throws Exception {
        long testTimeMillis = 1418078000000l;
        String outputFormat = "yyMMdd";
        // Manually convert the test-time to yyMMdd in the local time zone
        String expectedResult = DateTimeFormat.forPattern(outputFormat).print(testTimeMillis);
        doOpTest(
                new DataTableHelper().
                        tr().td(Long.toString(testTimeMillis), "0"),
                String.format("datef=0:unixmillis:%s:1", outputFormat),
                new DataTableHelper().
                        tr().td(Long.toString(testTimeMillis), expectedResult)
        );
    }
}

Fix OpDateFormat test in other time zones and separate into dedicated methods


/*
 * Copyright 2017 Axway Software
 *
 * 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.axway.ats.log.autodb.events;

import org.apache.log4j.Logger;

import com.axway.ats.log.autodb.LifeCycleState;
import com.axway.ats.log.autodb.model.AbstractLoggingEvent;
import com.axway.ats.log.autodb.model.LoggingEventType;

@SuppressWarnings( "serial")
public class StartAfterClassEvent extends AbstractLoggingEvent {

    public StartAfterClassEvent( String loggerFQCN, Logger logger ) {
        super(loggerFQCN, logger, "Start after class execution", LoggingEventType.START_AFTER_CLASS);
    }

    @Override
    protected LifeCycleState getExpectedLifeCycleState( LifeCycleState state ) {

        return LifeCycleState.ATLEAST_RUN_STARTED;
    }

}

/*
 * Copyright 2017 Axway Software
 *
 * 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.axway.ats.log.autodb.events;

import org.apache.log4j.Logger;

import com.axway.ats.log.autodb.LifeCycleState;
import com.axway.ats.log.autodb.model.AbstractLoggingEvent;
import com.axway.ats.log.autodb.model.LoggingEventType;

@SuppressWarnings( "serial")
public class StartAfterClassEvent extends AbstractLoggingEvent {

    public StartAfterClassEvent( String loggerFQCN, Logger logger ) {
        super(loggerFQCN, logger, "Start after class execution", LoggingEventType.START_AFTER_CLASS);
    }

    @Override
    protected LifeCycleState getExpectedLifeCycleState( LifeCycleState state ) {
        /* This event is fired after a suite is already closed,
           since ATS (AtsTestngListener) could not be certain that @AfterClass will be available
         */
        return LifeCycleState.ATLEAST_RUN_STARTED;
    }

}

Add comment for event state


package com.hyprion.beckon;

import sun.misc.Signal;
import sun.misc.SignalHandler;

import java.util.List;

import java.util.concurrent.Callable;

public class SignalFolder implements SignalHandler {
    final private Callable[] fns;

    public SignalFolder(List funs) {
        fns = new Callable[funs.size()];
        for (int i = 0; i < fns.length; i++) {
            fns[i] = (Callable) funs.get(i);
        }
    }

    public void handle(Signal sig) {
        for (Callable c : fns) {
            boolean res = false;
            try {
                res = (Boolean) c.call(); // No input elems?
            }
            catch (Exception e) {}
            finally {
                if (!res) {
                    break;
                }
            }
        }
    }
}

package com.hyprion.beckon;

import sun.misc.Signal;
import sun.misc.SignalHandler;

import java.util.List;

import java.util.concurrent.Callable;

public class SignalFolder implements SignalHandler {
    final private Callable[] fns;

    public SignalFolder(List funs) {
        fns = new Callable[funs.size()];
        for (int i = 0; i < fns.length; i++) {
            fns[i] = (Callable) funs.get(i);
        }
    }

    public void handle(Signal sig) {
        for (Callable c : fns) {
            boolean cont = true;
            try {
                Object oRes = c.call();
                if (oRes == false || oRes == null) {
                    cont = false;
                }
            }
            catch (Exception e) {}
            finally {
                if (!cont) {
                    break;
                }
            }
        }
    }
}

Allow caller to return any kind of value.


package BSChecker;
import java.util.ArrayList;
/**
 *
 * @author tedpyne
 * Defines abstract class for types of grammatical errors
 */
public abstract class Error {
	/**
	 * @param text The block of text to find errors in
	 * @return an ArrayList of int[2] pointers to the start and end indices of the roor in the submitted text
	 * 			int[0],int[1] are start and end tokens in error
	 */
	public abstract ArrayList<int[]> findErrors(String text);

	/**
	 *
	 * @param line The text to search through
	 * @param string The word to find in the text
	 * @param found The number of occurrences already found
	 * @return The location of the n+1th instance
	 */
	public static int locationOf(String line, String string, int found) {
		int loc = 0;
		for(int i = 0; i <= found; i++){
			loc = line.indexOf(string,loc) +1;
		}
		return loc;
	}

}

package BSChecker;
import java.util.ArrayList;
import java.util.Comparator;
/**
 *
 * @author tedpyne
 * Defines abstract class for types of grammatical errors
 */
public abstract class Error {
	/**
	 * @param text The block of text to find errors in
	 * @return an ArrayList of int[2] pointers to the start and end indices of the roor in the submitted text
	 * 			int[0],int[1] are start and end tokens in error
	 */
	public abstract ArrayList<int[]> findErrors(String text);

	/**
	 *
	 * @param line The text to search through
	 * @param string The word to find in the text
	 * @param found The number of occurrences already found
	 * @return The location of the n+1th instance
	 */
	public static int locationOf(String line, String string, int found) {
		int loc = 0;
		for(int i = 0; i <= found; i++){
			loc = line.indexOf(string,loc) +1;
		}
		return loc;
	}

	/**
	 * Sorts the list of all errors by location.
	 * @param list All the located errors
	 */
	public static void sort(ArrayList<int[]> list)
	{
		list.sort(new Comparator<int[]>()
		{
			public int compare(int[] o1, int[] o2)
			{
				if(o1[0] == o2[0]) return 0;
				else if(o1[0] < o2[0]) return -1;
				else return 1;
			}
		});
	}
}

Sort method for list of errors


package com.custardsource.parfait;

import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;

import java.util.Collection;

import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;

public class CompositeMonitoringViewTest {

    @Mock
    MonitoringView monitoringView1;

    @Mock
    MonitoringView monitoringView2;

    CompositeMonitoringView compositeMonitoringView;

    @Mock
    Collection<Monitorable<?>> monitorables;

    @Before
    public void setUp() {

        MockitoAnnotations.initMocks(this);

        when(monitoringView1.isRunning()).thenReturn(false);
        when(monitoringView2.isRunning()).thenReturn(true);

        when(monitorables.size()).thenReturn(2);

        this.compositeMonitoringView = new CompositeMonitoringView(monitoringView1, monitoringView2);
    }

    @Test
    public void testStartMonitoring() {

        compositeMonitoringView.startMonitoring(monitorables);

        verify(monitoringView1).startMonitoring(monitorables);
        verify(monitoringView2).startMonitoring(monitorables);

    }

    @Test
    public void testStopMonitoring() {
        compositeMonitoringView.stopMonitoring(monitorables);

        verify(monitoringView1).stopMonitoring(monitorables);
        verify(monitoringView2).stopMonitoring(monitorables);
    }

    @Test
    public void testIsRunning() {
        assertTrue(compositeMonitoringView.isRunning());
    }
}

package com.custardsource.parfait;

import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;

import java.util.Collection;

import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;

public class CompositeMonitoringViewTest {

    @Mock
    MonitoringView monitoringView1;

    @Mock
    MonitoringView monitoringView2;

    CompositeMonitoringView compositeMonitoringView;

    @Mock
    Collection<Monitorable<?>> monitorables;

    @Before
    public void setUp() {

        MockitoAnnotations.initMocks(this);

        when(monitoringView1.isRunning()).thenReturn(false);
        when(monitoringView2.isRunning()).thenReturn(true);

        when(monitorables.size()).thenReturn(2);

        this.compositeMonitoringView = new CompositeMonitoringView(monitoringView1, monitoringView2);
    }

    @Test
    public void startMonitoringShouldStartAllViews() {

        compositeMonitoringView.startMonitoring(monitorables);

        verify(monitoringView1).startMonitoring(monitorables);
        verify(monitoringView2).startMonitoring(monitorables);

    }

    @Test
    public void stopMonitoringShouldStopAllViews() {
        compositeMonitoringView.stopMonitoring(monitorables);

        verify(monitoringView1).stopMonitoring(monitorables);
        verify(monitoringView2).stopMonitoring(monitorables);
    }

    @Test
    public void isRunningReturnsTrueIfAnyRunning() {
        assertTrue(compositeMonitoringView.isRunning());
    }

    @Test
    public void isRunningReturnsFalseIfAllAreNotRunning() {
        CompositeMonitoringView monitoringView = new CompositeMonitoringView(monitoringView1);
        assertFalse(monitoringView.isRunning());
    }
}

Make test names more readable and add missing test case (Cowan's review comments)


package com.tngtech.jgiven.report.html5;

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

import com.tngtech.jgiven.CurrentStep;
import com.tngtech.jgiven.Stage;
import com.tngtech.jgiven.annotation.ExpectedScenarioState;
import com.tngtech.jgiven.attachment.Attachment;
import com.tngtech.jgiven.attachment.MediaType;
import java.io.File;
import java.util.List;
import org.openqa.selenium.*;

public class Html5AppStage<SELF extends Html5AppStage<?>> extends Stage<SELF> {
    @ExpectedScenarioState
    protected CurrentStep currentStep;

    @ExpectedScenarioState
    protected WebDriver webDriver;

    @ExpectedScenarioState
    protected File targetReportDir;

    protected void takeScreenshot() {
        String base64 = ((TakesScreenshot) webDriver).getScreenshotAs(OutputType.BASE64);
        currentStep.addAttachment(Attachment.fromBase64(base64, MediaType.PNG).withTitle("Screenshot"));
    }

    protected WebElement findTagWithName(String tagName) {
        List<WebElement> links = webDriver.findElements(
                By.xpath(String.format("//a/span[contains(@class,'tag') and contains(text(), '%s')]/..", tagName)));
        assertThat(links).isNotEmpty();
        return links.get(0);
    }

}

package com.tngtech.jgiven.report.html5;

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

import com.tngtech.jgiven.CurrentStep;
import com.tngtech.jgiven.Stage;
import com.tngtech.jgiven.annotation.ExpectedScenarioState;
import com.tngtech.jgiven.attachment.Attachment;
import com.tngtech.jgiven.attachment.MediaType;
import java.io.File;
import java.util.List;
import org.openqa.selenium.*;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;

public class Html5AppStage<SELF extends Html5AppStage<?>> extends Stage<SELF> {
    private static final int WEBDRIVER_FIND_TIMEOUT_SECONDS = 120;
    @ExpectedScenarioState
    protected CurrentStep currentStep;

    @ExpectedScenarioState
    protected WebDriver webDriver;

    @ExpectedScenarioState
    protected File targetReportDir;

    protected void takeScreenshot() {
        String base64 = ((TakesScreenshot) webDriver).getScreenshotAs(OutputType.BASE64);
        currentStep.addAttachment(Attachment.fromBase64(base64, MediaType.PNG).withTitle("Screenshot"));
    }

    protected WebElement findTagWithName(String tagName) {
        By elementLocator = By.xpath(String.format("//a/span[contains(@class,'tag') and contains(text(), '%s')]/..",
                                                   tagName));
        WebDriverWait timeoutSetter = new WebDriverWait(webDriver, WEBDRIVER_FIND_TIMEOUT_SECONDS);
        timeoutSetter.until(ExpectedConditions.visibilityOfElementLocated(elementLocator));

        List<WebElement> links = webDriver.findElements(elementLocator);
        assertThat(links).isNotEmpty();
        return links.get(0);
    }

}

Add bigger timeout for xpath element locator


package com.jetbrains.python.codeInsight;

import com.intellij.codeInsight.navigation.GotoTargetRendererProvider;
import com.intellij.ide.util.PsiElementListCellRenderer;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiNamedElement;
import com.jetbrains.python.psi.PyElement;

/**
 * @author yole
 */
public class PyGotoTargetRendererProvider implements GotoTargetRendererProvider {
  public PsiElementListCellRenderer getRenderer(final PsiElement[] elements) {
    for(PsiElement element: elements) {
      if (!(element instanceof PyElement) || !(element instanceof PsiNamedElement)) return null;
    }
    return new PyElementListCellRenderer();
  }

}

package com.jetbrains.python.codeInsight;

import com.intellij.codeInsight.navigation.GotoTargetRendererProvider;
import com.intellij.ide.util.PsiElementListCellRenderer;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiNamedElement;
import com.jetbrains.python.psi.PyElement;

/**
 * @author yole
 */
public class PyGotoTargetRendererProvider implements GotoTargetRendererProvider {
  public PsiElementListCellRenderer getRenderer(final PsiElement element) {
    if (element instanceof PyElement && element instanceof PsiNamedElement) return new PyElementListCellRenderer();
    return null;
  }

}

Create Test: refactoring + small fixes


package com.intel.alex.Utils;

/**
 * Created by root on 3/7/16.
 */
public class ExcelUtil {
}

package com.intel.alex.Utils;

import jxl.Workbook;

import jxl.write.*;

import java.io.*;
import java.lang.*;

/**
 * Created by root on 3/7/16.
 */
public class ExcelUtil {
    private final String logDir;

    public ExcelUtil(String logDir) {
        this.logDir = logDir;
    }

    public void csv2Excel() {
        File csvFile = new File(logDir + "/run-logs/BigBenchTimes.csv");
        FileReader fileReader;
        try{
            WritableWorkbook book;//
            File excFile = new File("/home/BigBenchTimes.xls");//
            book = Workbook.createWorkbook(excFile);//
            int num = book.getNumberOfSheets();
            WritableSheet sheet0 = book.createSheet("BigBenchTimes",num);
            WritableSheet sheet1 = book.createSheet("PowerTestTime",num+1); //1 is needed to change
            WritableSheet sheet2 = book.createSheet("ThroughPutTestTime_allstreams",num+2);

            fileReader = new FileReader(csvFile);
            BufferedReader br = new BufferedReader(fileReader);
            int i=0;
            int p=0;
            int t=0;
            String line ;
            while ((line=br.readLine())!=null){
                String s[]= line.split(";");
                if(s.length > 3){
                    for(int j=0; j< s.length; j++){
                        Label label = new Label(j, i, s[j]);
                        sheet0.addCell(label);
                    }
                    if(s[1].equals("POWER_TEST")){
                        for(int j =0; j< s.length; j++){
                            Label label =new Label(j,p,s[j]);
                            sheet1.addCell(label);
                        }
                        p++;
                    }
                    if(s[1].equals("THROUGHPUT_TEST_1")){
                        for(int j =0; j< s.length; j++){
                            Label label =new Label(j,t,s[j]);
                            sheet2.addCell(label);
                        }
                        t++;
                    }
                }
                i++;
            }
            br.close();
            fileReader.close();
            book.write();
            book.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}

Add the function of generating excel file.


package net.redwarp.library.testapplication;

import android.os.Build;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.MenuItem;
import android.widget.TextView;

import butterknife.Bind;
import butterknife.ButterKnife;

public class DetailActivity extends AppCompatActivity {

  @Bind(R.id.text) TextView mTextView;

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_detail);
    ButterKnife.bind(this);
    if (getActionBar() != null) {
      getActionBar().setDisplayHomeAsUpEnabled(true);
    }

    long userId = getIntent().getLongExtra(MainActivity.EXTRA_USER_ID, -1);
    if (userId != -1) {
      RandomUser user = TestApplication.getDatabaseHelper().getWithId(RandomUser.class, userId);
      if (user != null) {
        mTextView.setText(user.name);
      }
    }
  }

  @Override
  public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
      // Respond to the action bar's Up/Home button
      case android.R.id.home:
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
          finishAfterTransition();
        } else {
          finish();
        }
        return true;
    }
    return super.onOptionsItemSelected(item);
  }
}

package net.redwarp.library.testapplication;

import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.view.MenuItem;
import android.widget.TextView;

import butterknife.Bind;
import butterknife.ButterKnife;

public class DetailActivity extends AppCompatActivity {

  @Bind(R.id.text) TextView mTextView;

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_detail);
    ButterKnife.bind(this);
    if (getActionBar() != null) {
      getActionBar().setDisplayHomeAsUpEnabled(true);
    }

    long userId = getIntent().getLongExtra(MainActivity.EXTRA_USER_ID, -1);
    if (userId != -1) {
      RandomUser user = TestApplication.getDatabaseHelper().getWithId(RandomUser.class, userId);
      if (user != null) {
        mTextView.setText(user.name);
      }
    }
  }

  @Override
  public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
      // Respond to the action bar's Up/Home button
      case android.R.id.home:
        ActivityCompat.finishAfterTransition(this);
        return true;
    }
    return super.onOptionsItemSelected(item);
  }
}

Use ActivityCompat instead of reinventing the wheel


package org.robockets.stronghold.robot.intake;

import org.robockets.stronghold.robot.Robot;
import org.robockets.stronghold.robot.drivetrain.AssistedDrive;
import org.robockets.stronghold.robot.drivetrain.AssistedRotateType;
import org.robockets.stronghold.robot.drivetrain.AssistedTranslateType;

import edu.wpi.first.wpilibj.command.CommandGroup;

/**
 *
 */
public class ChevalDeFrise extends CommandGroup {

	double encooder; // Dummy variable for now until a method is made for receiving encoder output
	// Assuming position fully down is 0 and fully up is 90.
    public ChevalDeFrise() {
    	Robot.driveTrain.gyroPID.setSetpoint(0); // 0 for now -Jake B. 2016
    	if (encooder > 80) { // Temporary way to check if arm is up
    		addSequential(new SetIntake(0));
    	} else if (encooder < 80) { // Temporary way to check if arm is down
    		addSequential(new SetIntake(90));
    		addSequential(new SetIntake(0));
    	}

        addSequential(new AssistedDrive(AssistedTranslateType.ENCODER, AssistedRotateType.GYRO, 1, 0)); // Dummy inputs for distance and relativeAngle
    	addParallel(new SetIntake(90)); // Slowly lift arm as robot moves across
    }
}

package org.robockets.stronghold.robot.intake;

import org.robockets.stronghold.robot.Robot;
import org.robockets.stronghold.robot.drivetrain.AssistedDrive;
import org.robockets.stronghold.robot.drivetrain.AssistedRotateType;
import org.robockets.stronghold.robot.drivetrain.AssistedTranslateType;

import edu.wpi.first.wpilibj.command.CommandGroup;

/**
 *
 */
public class ChevalDeFrise extends CommandGroup {

	double encooder; // Dummy variable for now until a method is made for receiving encoder output
	// Assuming position fully down is 0 and fully up is 90.
    public ChevalDeFrise(IntakeSide intakeSide) {
    	Robot.driveTrain.gyroPID.setSetpoint(0); // 0 for now -Jake B. 2016
    	if (encooder > 80) { // Temporary way to check if arm is up
    		addSequential(new SetIntake(0, intakeSide));
    	} else if (encooder < 80) { // Temporary way to check if arm is down
    		addSequential(new SetIntake(90, intakeSide));
    		addSequential(new SetIntake(0, intakeSide));
    	}

        addSequential(new AssistedDrive(AssistedTranslateType.ENCODER, AssistedRotateType.GYRO, 1, 0)); // Dummy inputs for distance and relativeAngle
    	addParallel(new SetIntake(90, intakeSide)); // Slowly lift arm as robot moves across
    }
}

Update cheval de frise to be used with updated intake


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

package com.googlesource.gerrit.plugins.hooks.its;

import com.google.gerrit.pgm.init.InitStep;
import com.google.gerrit.pgm.init.Section;
import com.google.gerrit.pgm.util.ConsoleUI;

public class InitIts implements InitStep {

  public static String COMMENT_LINK_SECTION = "commentLink";

  public static enum YesNoEnum {
    Y, N;
  }

  public static enum TrueFalseEnum {
    TRUE, FALSE;
  }

  @Override
  public void run() throws Exception {
  }

  public boolean isConnectivityRequested(ConsoleUI ui, String url) {
    YesNoEnum wantToTest =
        ui.readEnum(YesNoEnum.N, "Test connectivity to %s", url);
    return wantToTest == YesNoEnum.Y;
  }

  public boolean enterSSLVerify(Section section) {
    return TrueFalseEnum.TRUE == section.select("Verify SSL Certificates",
        "sslVerify", TrueFalseEnum.TRUE);
  }
}

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

package com.googlesource.gerrit.plugins.hooks.its;

import com.google.gerrit.pgm.init.InitStep;
import com.google.gerrit.pgm.init.Section;
import com.google.gerrit.pgm.util.ConsoleUI;

public class InitIts implements InitStep {

  public static String COMMENT_LINK_SECTION = "commentLink";

  public static enum TrueFalseEnum {
    TRUE, FALSE;
  }

  @Override
  public void run() throws Exception {
  }

  public boolean isConnectivityRequested(ConsoleUI ui, String url) {
    return ui.yesno(false, "Test connectivity to %s", url);
  }

  public boolean enterSSLVerify(Section section) {
    return TrueFalseEnum.TRUE == section.select("Verify SSL Certificates",
        "sslVerify", TrueFalseEnum.TRUE);
  }
}

Remove custom YesNoEnum and use yesno method from ConsoleUI


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

public final class AstWriteAbortedNode extends AstEventNode {

    @Override
    public <R, P> R accept(Visitor<R, P> visitor, P parameter) {
        return visitor.visit(this, parameter);
    }

    @Override
    protected int hashTo() {
        return getClass().hashCode();
    }

    @Override
    protected boolean equalTo(AstRegion that) {
        return that instanceof AstWriteAbortedNode;
    }

    @Override
    protected void describe(StringBuilder buf) {
        super.describe(buf);
        buf.append("read aborted\n");
    }
}

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

public final class AstWriteAbortedNode extends AstEventNode {

    @Override
    public <R, P> R accept(Visitor<R, P> visitor, P parameter) {
        return visitor.visit(this, parameter);
    }

    @Override
    protected int hashTo() {
        return getClass().hashCode();
    }

    @Override
    protected boolean equalTo(AstRegion that) {
        return that instanceof AstWriteAbortedNode;
    }

    @Override
    protected void describe(StringBuilder buf) {
        super.describe(buf);
        buf.append("write aborted\n");
    }
}

Fix typo in write aborted description


package com.alexstyl.specialdates.events;

import com.alexstyl.specialdates.date.DateDisplayStringCreator;
import com.alexstyl.specialdates.date.Date;

import org.junit.BeforeClass;
import org.junit.Test;

import static org.fest.assertions.api.Assertions.assertThat;

public class DateDisplayStringCreatorTest {
    private static final String EXPECTED_STRING = "1995-05-05";
    private static final String EXPECTED_STRING_NO_YEAR = "--05-05";

    private static DateDisplayStringCreator creator;

    @BeforeClass
    public static void init() {
        creator = DateDisplayStringCreator.INSTANCE;
    }

    @Test
    public void givenDateWithYear_thenReturningStringIsCorrect() {
        Date date = Date.on(5, 5, 1995);
        String dateToString = creator.stringOf(date);
        assertThat(dateToString).isEqualTo(EXPECTED_STRING);
    }

    @Test
    public void givenDateWithNoYear_thenReturningStringIsCorrect() {
        Date date = Date.on(5, 5);
        String dateToString = creator.stringOf(date);
        assertThat(dateToString).isEqualTo(EXPECTED_STRING_NO_YEAR);
    }

}

package com.alexstyl.specialdates.events;

import com.alexstyl.specialdates.date.DateDisplayStringCreator;
import com.alexstyl.specialdates.date.Date;

import org.junit.BeforeClass;
import org.junit.Test;

import static com.alexstyl.specialdates.date.DateConstants.MAY;
import static org.fest.assertions.api.Assertions.assertThat;

public class DateDisplayStringCreatorTest {

    private static DateDisplayStringCreator creator;

    @BeforeClass
    public static void init() {
        creator = DateDisplayStringCreator.INSTANCE;
    }

    @Test
    public void givenDateWithYear_thenReturningStringIsCorrect() {
        Date date = Date.on(5, MAY, 1995);
        String dateToString = creator.stringOf(date);
        assertThat(dateToString).isEqualTo("1995-05-05");
    }

    @Test
    public void givenDateWithNoYear_thenReturningStringIsCorrect() {
        Date date = Date.on(5, MAY);
        String dateToString = creator.stringOf(date);
        assertThat(dateToString).isEqualTo("--05-05");
    }

}

Replace magic numbers with constants


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

import com.google.inject.Binder;
import com.google.inject.Module;
import com.google.inject.Scopes;
import org.weakref.jmx.guice.ExportBinder;

import static io.airlift.configuration.ConfigurationModule.bindConfig;
import static io.airlift.http.client.HttpClientBinder.httpClientBinder;

public class FailureDetectorModule
        implements Module
{
    @Override
    public void configure(Binder binder)
    {
        httpClientBinder(binder)
                .bindAsyncHttpClient("failure-detector", ForFailureDetector.class)
                .withTracing();

        bindConfig(binder).to(FailureDetectorConfig.class);

        binder.bind(HeartbeatFailureDetector.class).in(Scopes.SINGLETON);

        binder.bind(FailureDetector.class)
                .to(HeartbeatFailureDetector.class)
                .in(Scopes.SINGLETON);

        ExportBinder.newExporter(binder)
                .export(HeartbeatFailureDetector.class)
                .withGeneratedName();
    }
}

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

import com.google.inject.Binder;
import com.google.inject.Module;
import com.google.inject.Scopes;
import org.weakref.jmx.guice.ExportBinder;

import static io.airlift.configuration.ConfigurationModule.bindConfig;
import static io.airlift.http.client.HttpClientBinder.httpClientBinder;

public class FailureDetectorModule
        implements Module
{
    @Override
    public void configure(Binder binder)
    {
        httpClientBinder(binder)
                .bindAsyncHttpClient("failure-detector", ForFailureDetector.class)
                .withPrivateIoThreadPool()
                .withTracing();

        bindConfig(binder).to(FailureDetectorConfig.class);

        binder.bind(HeartbeatFailureDetector.class).in(Scopes.SINGLETON);

        binder.bind(FailureDetector.class)
                .to(HeartbeatFailureDetector.class)
                .in(Scopes.SINGLETON);

        ExportBinder.newExporter(binder)
                .export(HeartbeatFailureDetector.class)
                .withGeneratedName();
    }
}

Use a private I/O thread pool for failure detector


package il.ac.technion.ie.experiments.Utils;

import org.apache.log4j.Logger;

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

/**
 * Created by I062070 on 10/09/2015.
 */
public class ExpFileUtils {
    static final Logger logger = Logger.getLogger(ExpFileUtils.class);

    public static File createFile(String pathToFile) {
        File outputFile = new File(pathToFile);
        if (outputFile.exists()) {
            logger.info("Output file exists. Deleting " + pathToFile);
            if (!outputFile.delete()) {
                logger.warn("Failed to delete output file");
            }
        }
        try {
            logger.info("Creating the output file");
            outputFile.createNewFile();
        } catch (IOException e) {
            logger.error("Failed to create output file", e);
        }
        return outputFile;
    }

    public static String getOutputFilePath(String fileName, String fileSuffix) {
        File runningDir = new File(System.getProperty("user.dir"));
        File parentFile = runningDir.getParentFile();
        return parentFile.getAbsolutePath() + File.separator + fileName + fileSuffix;
    }
}

package il.ac.technion.ie.experiments.Utils;

import org.apache.commons.io.FileUtils;
import org.apache.log4j.Logger;

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

/**
 * Created by I062070 on 10/09/2015.
 */
public class ExpFileUtils {
    static final Logger logger = Logger.getLogger(ExpFileUtils.class);

    public static File createFile(String pathToFile) {
        File outputFile = new File(pathToFile);
        if (outputFile.exists()) {
            logger.info("Output file exists. Deleting " + pathToFile);
            if (!outputFile.delete()) {
                logger.warn("Failed to delete output file");
            }
        }
        try {
            logger.info("Creating the output file");
            outputFile.createNewFile();
        } catch (IOException e) {
            logger.error("Failed to create output file", e);
        }
        return outputFile;
    }

    public static String getOutputFilePath(String fileName, String fileSuffix) {
        File runningDir = new File(System.getProperty("user.dir"));
        File parentFile = runningDir.getParentFile();
        return parentFile.getAbsolutePath() + File.separator + fileName + fileSuffix;
    }

    public static File createOutputFile(String filename) {
        File expResults = null;
        try {
            expResults = new File(filename);
            if (expResults.exists()) {
                FileUtils.forceDelete(expResults);
            }
            if (!expResults.createNewFile()) {
                expResults = null;
            }
        } catch (IOException e) {
            logger.error("Failed to create file for measurements of Experiment", e);
        }
        return expResults;
    }
}

Add a generic method that creates an output file


package com.web4enterprise.pdf.core.font;

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

import com.web4enterprise.pdf.core.BoundingBox;

public abstract class Font {
	protected static Map<String, Font> fonts = new HashMap<>();
	protected static Map<Byte, Integer> widths = new HashMap<>();
	protected static Map<Byte, BoundingBox> boxes = new HashMap<>();

	static {
		fonts.put("Times-Roman", new TimesRoman());
	}

	public int getWidth(Integer size, String text) {
		int fullWidth = 0;
		for(byte letter : text.getBytes()) {
			fullWidth += widths.get(letter);
		}
		return (int) Math.round(fullWidth * size / 1000.0f);
	}

	public int getHeight(Integer size, String text) {
		int greaterHeight = 0;
		for(byte letter : text.getBytes()) {
			BoundingBox letterBox = boxes.get(letter);
			int height = letterBox.getHeight();
			if(height > greaterHeight) {
				greaterHeight = height;
			}
		}
		return (int) Math.round(greaterHeight * size / 1000.0f);
	}

	public static Font getFont(String name) {
		return fonts.get(name);
	}
}

package com.web4enterprise.pdf.core.font;

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

import com.web4enterprise.pdf.core.BoundingBox;

public abstract class Font {
	protected static Map<String, Font> fonts = new HashMap<>();
	protected static Map<Byte, Integer> widths = new HashMap<>();
	protected static Map<Byte, BoundingBox> boxes = new HashMap<>();

	public static Font TIMES_ROMAN = new TimesRoman();
	static {
		fonts.put("Times-Roman", TIMES_ROMAN);
	}

	public int getWidth(Integer size, String string) {
		int fullWidth = 0;
		for(byte letter : string.getBytes()) {
			Integer width = widths.get(letter);
			if(width != null) {
				fullWidth += width;
			}
		}
		return (int) Math.round(fullWidth * size / 1000.0f);
	}

	public int getHeight(Integer size, String string) {
		int greaterHeight = 0;
		for(byte letter : string.getBytes()) {
			BoundingBox letterBox = boxes.get(letter);
			int height = letterBox.getHeight();
			if(height > greaterHeight) {
				greaterHeight = height;
			}
		}
		return (int) Math.round(greaterHeight * size / 1000.0f);
	}

	public static Font getFont(String name) {
		return fonts.get(name);
	}
}

Handle case when getting the width of a text, if a letter is not recognized, the width is not incremented instead of throwing a NullPointerException.


package binary;

import quark.concurrent.Context;
import binary.Binary;

public class ServerMain {

    public static void main(String[] args) {
        quark.Runtime runtime = Context.runtime();
        runtime.serveWS("ws://127.0.0.1:8910/binary", new Binary(runtime));
    }

}

package binary;

import quark.concurrent.Context;
import binary.Binary;

public class ServerMain {

    public static void main(String[] args) {
        quark.Runtime runtime = Context.runtime();
        System.out.println("Java binary server starting");
        runtime.serveWS("ws://127.0.0.1:8910/binary", new Binary(runtime));
    }

}

Add binary server output on start


import java.io.*;

public class TwoStreams {
	public void twoStreamsWrong() throws IOException {
		BufferedReader r = null;
		Writer w = null;

		try {
			r = new BufferedReader(new InputStreamReader(new FileInputStream("hello")));
			String l = r.readLine();
			w = new OutputStreamWriter(new FileOutputStream("blah"));
			w.write(l);
		} finally {
			if (r != null) {
				r.close();
			}
			if (w != null) {
				try {
					w.close();
				} catch (IOException e) {
				}
			}
		}
	}

	public void twoStreamsRight() throws IOException {
		BufferedReader r = null;
		Writer w = null;

		try {
			r = new BufferedReader(new InputStreamReader(new FileInputStream("hello")));
			String l = r.readLine();
			w = new OutputStreamWriter(new FileOutputStream("blah"));
			w.write(l);
		} finally {
			if (w != null) {
				try {
					w.close();
				} catch (IOException e) {
				}
			}
			if (r != null) {
				r.close();
			}
		}
	}
}

import java.io.*;

public class TwoStreams {
	int x;
	public void twoStreamsWrong() throws IOException {
		BufferedReader r = null;
		Writer w = null;

		try {
			r = new BufferedReader(new InputStreamReader(new FileInputStream("hello")));
			String l = r.readLine();
			w = new OutputStreamWriter(new FileOutputStream("blah"));
			w.write(l);
		} finally {
			if (r != null) {
				r.close();
			}
			if (w != null) {
				try {
					w.close();
				} catch (IOException e) {
				}
			}
		}
	}

	public void nullDereferenceCheck(TwoStreams o) throws IOException {
		BufferedReader r = new BufferedReader(
			new InputStreamReader(
			new FileInputStream("hello")));
		int i = o.x;
		r.close();
		}
	public void twoStreamsRight() throws IOException {
		BufferedReader r = null;
		Writer w = null;

		try {
			r = new BufferedReader(new InputStreamReader(new FileInputStream("hello")));
			String l = r.readLine();
			w = new OutputStreamWriter(new FileOutputStream("blah"));
			w.write(l);
		} finally {
			if (w != null) {
				try {
					w.close();
				} catch (IOException e) {
				}
			}
			if (r != null) {
				r.close();
			}
		}
	}
}

Check for potential null pointer exception


/*
 * Copyright 2017 ThoughtWorks, 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.thoughtworks.go.utils;

public class AssertJava8 {
    public static void assertVMVersion() {
        String jvmVersion = System.getProperty("java.vm.specification.version");

        if (!"1.8".equals(jvmVersion)) {
            System.err.println("Running GoCD requires Java version 1.8. You are currently running with Java version " + jvmVersion + ". GoCD will now exit!");
            System.exit(1);
        }
    }
}

/*
 * Copyright 2017 ThoughtWorks, 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.thoughtworks.go.utils;

import org.apache.commons.lang3.JavaVersion;

import java.util.Arrays;
import java.util.TreeSet;

public class AssertJava8 {
    private static TreeSet<JavaVersion> SUPPORTED_VERSIONS = new TreeSet<>(Arrays.asList(
            JavaVersion.JAVA_1_8,
            JavaVersion.JAVA_9,
            JavaVersion.JAVA_10
    ));

    public static void assertVMVersion() {
        checkSupported(JavaVersion.JAVA_RECENT);
    }

    private static void checkSupported(JavaVersion currentJavaVersion) {
        if (!SUPPORTED_VERSIONS.contains(currentJavaVersion)) {
            System.err.println("Running GoCD requires Java version >= " + SUPPORTED_VERSIONS.first().name() +
                    " and <= " + SUPPORTED_VERSIONS.last() +
                    ". You are currently running with Java version " + currentJavaVersion + ". GoCD will now exit!");
            System.exit(1);
        }
    }
}

Allow running on java 8-10


package com.bbn.bue.common.serialization.jackson;

import com.bbn.bue.common.evaluation.FMeasureCounts;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.ImmutableMap;
import junit.framework.TestCase;
import org.junit.Test;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import static org.junit.Assert.assertEquals;

public class TestSerialization extends TestCase {
    private ObjectMapper mapper;

    @Override
    protected void setUp() {
        mapper = new ObjectMapper();
        mapper.findAndRegisterModules();
        mapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
    }

    @Test
    public void testFMeasureCounts() throws IOException {
        final RootObject foo = new RootObject();
        foo.o = ImmutableMap.of("Hello",
                FMeasureCounts.from(1, 2, 3));
        final File tmp = File.createTempFile("foo", "bar");
        tmp.deleteOnExit();
        mapper.writeValue(tmp, foo);
        final Map<String, FMeasureCounts> bar = (Map<String,FMeasureCounts>)mapper.readValue(tmp,
                RootObject.class).o;
        assertEquals(foo.o, bar);
    }

    public static class RootObject {

        public RootObject() {
            o = null;
        }

        @JsonCreator
        public RootObject(@JsonProperty("obj") Object o) {
            this.o = o;
        }

        @JsonProperty("obj")
        public Object obj() {
            return o;
        }

        public Object o;
    }
}

package com.bbn.bue.common.serialization.jackson;

import com.bbn.bue.common.evaluation.FMeasureCounts;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.ImmutableMap;
import junit.framework.TestCase;
import org.junit.Test;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import static org.junit.Assert.assertEquals;

public class TestSerialization extends TestCase {
    private final JacksonSerializer serializer = JacksonSerializer.forNormalJSON();

    @Test
    public void testFMeasureCounts() throws IOException {
        final Map<String, FMeasureCounts> foo = ImmutableMap.of("Hello",
                FMeasureCounts.from(1, 2, 3));
        final File tmp = File.createTempFile("foo", "bar");
        tmp.deleteOnExit();

        assertEquals(foo, JacksonTestUtils.roundTripThroughSerializer(foo, serializer));
    }

}

Fix Jackson serialization test for changes to Jackson serialization wrpaper


/*
 * (c) Copyright 2014 Hewlett-Packard Development Company, L.P.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Apache License v2.0 which accompany this distribution.
 *
 * The Apache License is available at
 * http://www.apache.org/licenses/LICENSE-2.0
 */
package org.openscore.lang.compiler;

import org.openscore.lang.compiler.modeller.model.Executable;
import org.openscore.lang.entities.CompilationArtifact;

import java.io.Serializable;
import java.util.Map;
import java.util.Set;

//todo: Eliya - add JavaDoc
public interface SlangCompiler {

    CompilationArtifact compile(SlangSource source, Set<SlangSource> path);

    /**
     * Pre-compile a Slang file into a list of Executables
     * @param source the slang source file
     * @return a list of Executable objects, containing either a flow or a list of all the operations in the file
     */
    Executable preCompile(SlangSource source);

    /**
     * Load system property sources written in slang and map them to fully qualified names
     * @param sources the slang sources containing the system properties
     * @return map containing all of the system properties with fully qualified keys
     */
    Map<String, ? extends Serializable> loadSystemProperties(SlangSource... sources);

}

/*
 * (c) Copyright 2014 Hewlett-Packard Development Company, L.P.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Apache License v2.0 which accompany this distribution.
 *
 * The Apache License is available at
 * http://www.apache.org/licenses/LICENSE-2.0
 */
package org.openscore.lang.compiler;

import org.openscore.lang.compiler.modeller.model.Executable;
import org.openscore.lang.entities.CompilationArtifact;

import java.io.Serializable;
import java.util.Map;
import java.util.Set;

public interface SlangCompiler {

    /**
     * Compile a Slang source & its path to a CompilationArtifact object
     * @param source the slang source file
     * @param path a set of slang sources containing the source dependencies
     * @return the compiled CompilationArtifact
     */
    CompilationArtifact compile(SlangSource source, Set<SlangSource> path);

    /**
     * Pre-compile a Slang source into an Executable
     * @param source the slang source file
     * @return an Executable object, containing either a flow or operation in the file.
     *          Returns null if the source contains Slang system properties
     */
    Executable preCompile(SlangSource source);

    /**
     * Load system property sources written in slang and map them to fully qualified names
     * @param sources the slang sources containing the system properties
     * @return map containing all of the system properties with fully qualified keys
     */
    Map<String, ? extends Serializable> loadSystemProperties(SlangSource... sources);

}

Add & update Java Docs


package com.usepropeller.routable;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;

public class RouterActivity extends Activity {
	@Override
	public void onCreate(Bundle savedInstanceState) {
	    super.onCreate(savedInstanceState);

	    Intent intent = getIntent();
	    String url;

	    Bundle extras = intent.getExtras();
	    if (extras.containsKey("url")) {
	    	url = extras.getString("url");
	    }
	    else {
		    Uri data = intent.getData();
		    url = data.getPath();
		    if (url.startsWith("/")) {
		    	url = url.substring(1);
		    }
		    if (Router.sharedRouter().getRootUrl() != null) {
			    Router.sharedRouter().open(Router.sharedRouter().getRootUrl());
		    }
	    }

	    Router.sharedRouter().open(url);

	    setResult(RESULT_OK, null);
	    finish();
	}
}

package com.usepropeller.routable;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;

public class RouterActivity extends Activity {
	@Override
	public void onCreate(Bundle savedInstanceState) {
	    super.onCreate(savedInstanceState);

	    Intent intent = getIntent();
	    String url;

	    Bundle extras = intent.getExtras();
	    if (extras.containsKey("url")) {
	    	url = extras.getString("url");
	    }
	    else {
		    Uri data = intent.getData();
		    String protocol = data.getScheme() + "://";
		    url = data.toString().replaceFirst(protocol, "");
		    if (Router.sharedRouter().getRootUrl() != null) {
			    Router.sharedRouter().open(Router.sharedRouter().getRootUrl());
		    }
	    }

	    Router.sharedRouter().open(url);

	    setResult(RESULT_OK, null);
	    finish();
	}
}

Change protocol format to use the FULL url instead of just the path


package edu.usc.glidein.service.impl;

import java.rmi.RemoteException;

import org.apache.axis.message.addressing.EndpointReferenceType;
import org.globus.wsrf.ResourceContext;

import edu.usc.glidein.stubs.types.EmptyObject;
import edu.usc.glidein.stubs.types.Site;

public class SiteService
{
	private SiteResource getResource() throws RemoteException
	{
		try {
			return (SiteResource) ResourceContext.getResourceContext().getResource();
		} catch (Exception e) {
			throw new RemoteException("Unable to find site resource", e);
		}
	}

	public Site getSite(EmptyObject empty) throws RemoteException
	{
		return getResource().getSite();
	}

	public EmptyObject submit(EndpointReferenceType credential) throws RemoteException
	{
		getResource().submit(credential);
		return new EmptyObject();
	}

	public EmptyObject remove(boolean force) throws RemoteException
	{
		getResource().remove(force);
		return new EmptyObject();
	}
}

package edu.usc.glidein.service.impl;

import java.rmi.RemoteException;

import org.apache.axis.message.addressing.EndpointReferenceType;
import org.globus.wsrf.ResourceContext;

import edu.usc.glidein.stubs.RemoveRequest;
import edu.usc.glidein.stubs.types.EmptyObject;
import edu.usc.glidein.stubs.types.Site;

public class SiteService
{
	private SiteResource getResource() throws RemoteException
	{
		try {
			return (SiteResource) ResourceContext.getResourceContext().getResource();
		} catch (Exception e) {
			throw new RemoteException("Unable to find site resource", e);
		}
	}

	public Site getSite(EmptyObject empty) throws RemoteException
	{
		return getResource().getSite();
	}

	public EmptyObject submit(EndpointReferenceType credential) throws RemoteException
	{
		getResource().submit(credential);
		return new EmptyObject();
	}

	public EmptyObject remove(RemoveRequest request) throws RemoteException
	{
		boolean force = request.isForce();
		EndpointReferenceType credential = request.getCredential();
		getResource().remove(force,credential);
		return new EmptyObject();
	}
}

Add delegated credential to remove operation


package com.socrata.ssync;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.io.*;

public class PatchBuilder {
    private final OutputStreamWriteHelper out;
    private final int maxDataBlockSize;

    // Does NOT take ownership of the outputstream!
    public PatchBuilder(OutputStream outStream, String checksumAlgorithm, int blockSize) throws IOException, NoSuchAlgorithmException {
        this.out = new OutputStreamWriteHelper(outStream, MessageDigest.getInstance(checksumAlgorithm));

        if(blockSize <= 0 || blockSize >= Patch.MaxBlockSize)
            throw new IllegalArgumentException("blockSize");
        this.maxDataBlockSize = blockSize * 2;

        out.writeCheckumNameWithoutUpdatingChecksum();
        out.writeInt(blockSize);
    }

    public void writeEnd() throws IOException {
        writeOp(Patch.End);
        out.writeChecksumWithoutUpdatingChecksum();
    }

    public void writeBlockNum(int blockNum) throws IOException {
        writeOp(Patch.Block);
        out.writeInt(blockNum);
    }

    public void writeData(byte[] data) throws IOException {
        writeData(data, 0, data.length);
    }

    public void writeData(byte[] data, int offset, int length) throws IOException {
        while(length != 0) {
            writeOp(Patch.Data);
            int toWrite = Math.min(length, maxDataBlockSize);
            out.writeInt(toWrite);
            out.writeBytes(data, offset, toWrite);
            length -= toWrite;
            offset += toWrite;
        }
    }

    private void writeOp(int op) throws IOException {
        out.writeByte(op);
    }
}

package com.socrata.ssync;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.io.*;

public class PatchBuilder {
    private final OutputStreamWriteHelper out;
    private final int blockSize;

    // Does NOT take ownership of the outputstream!
    public PatchBuilder(OutputStream outStream, String checksumAlgorithm, int blockSize) throws IOException, NoSuchAlgorithmException {
        this.out = new OutputStreamWriteHelper(outStream, MessageDigest.getInstance(checksumAlgorithm));

        if(blockSize <= 0 || blockSize >= Patch.MaxBlockSize)
            throw new IllegalArgumentException("blockSize");
        this.blockSize = blockSize;

        out.writeCheckumNameWithoutUpdatingChecksum();
        out.writeInt(blockSize);
    }

    public void writeEnd() throws IOException {
        writeOp(Patch.End);
        out.writeChecksumWithoutUpdatingChecksum();
    }

    public void writeBlockNum(int blockNum) throws IOException {
        writeOp(Patch.Block);
        out.writeInt(blockNum);
    }

    public void writeData(byte[] data) throws IOException {
        writeData(data, 0, data.length);
    }

    public void writeData(byte[] data, int offset, int length) throws IOException {
        while(length != 0) {
            writeOp(Patch.Data);
            int toWrite = Math.min(length, blockSize);
            out.writeInt(toWrite);
            out.writeBytes(data, offset, toWrite);
            length -= toWrite;
            offset += toWrite;
        }
    }

    private void writeOp(int op) throws IOException {
        out.writeByte(op);
    }
}

Remove one last vestage of compressed data chunks


package com.bbn.bue.common.primitives;

import org.junit.Test;

import static org.junit.Assert.assertEquals;

/**
 * Created by rgabbard on 1/25/16.
 */
public class DoubleUtilsTest {

  private static final double EPSILON = 1e-6;

  @Test(expected = IllegalArgumentException.class)
  public void testBadBounds() {
    DoubleUtils.clip(2.0, -1.0);
  }

  @Test
  public void testClipping() {
    assertEquals(-2.0, DoubleUtils.clip(-5.0, 2.0), EPSILON);
    assertEquals(2.0, DoubleUtils.clip(5.0, 2.0), EPSILON);
    assertEquals(1.0, DoubleUtils.clip(1.0, 2.0), EPSILON);
  }
}

package com.bbn.bue.common.primitives;

import org.junit.Test;

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

/**
 * Created by rgabbard on 1/25/16.
 */
public class DoubleUtilsTest {

  private static final double EPSILON = 1e-6;

  @Test(expected = IllegalArgumentException.class)
  public void testBadBounds() {
    DoubleUtils.clip(2.0, -1.0);
  }

  @Test
  public void testClipping() {
    assertEquals(-2.0, DoubleUtils.clip(-5.0, 2.0), EPSILON);
    assertEquals(2.0, DoubleUtils.clip(5.0, 2.0), EPSILON);
    assertEquals(1.0, DoubleUtils.clip(1.0, 2.0), EPSILON);
    assertEquals(-2.0, DoubleUtils.clip(Double.NEGATIVE_INFINITY, 2.0), EPSILON);
    assertEquals(2.0, DoubleUtils.clip(Double.POSITIVE_INFINITY, 2.0), EPSILON);
    assertTrue(Double.isNaN(DoubleUtils.clip(Double.NaN, 2.0)));
  }

}

Add clipping test cases for infinities and NaN


package fr.openwide.core.jpa.more.business.search.query;

import java.util.List;
import java.util.Map;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import org.springframework.transaction.annotation.Transactional;

import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;

import fr.openwide.core.jpa.more.business.sort.ISort;
import fr.openwide.core.jpa.more.business.sort.ISort.SortOrder;

public abstract class AbstractSearchQuery<T, S extends ISort<?>> implements ISearchQuery<T, S> /* NOT Serializable */ {

	@PersistenceContext
	protected EntityManager entityManager;

	protected List<S> defaultSorts;
	protected Map<S, SortOrder> sortMap;

	@SafeVarargs
	protected AbstractSearchQuery(S ... defaultSorts) {
		this.defaultSorts = ImmutableList.copyOf(defaultSorts);
	}

	// Sort
	@Override
	public ISearchQuery<T, S> sort(Map<S, SortOrder> sortMap) {
		this.sortMap = ImmutableMap.copyOf(sortMap);
		return this;
	}

	// May be overridden for performance purposes
	@Override
	@Transactional(readOnly = true)
	public List<T> fullList() {
		return list(0, Long.MAX_VALUE);
	}
}

package fr.openwide.core.jpa.more.business.search.query;

import java.util.List;
import java.util.Map;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;

import fr.openwide.core.jpa.more.business.sort.ISort;
import fr.openwide.core.jpa.more.business.sort.ISort.SortOrder;

public abstract class AbstractSearchQuery<T, S extends ISort<?>> implements ISearchQuery<T, S> /* NOT Serializable */ {

	@PersistenceContext
	protected EntityManager entityManager;

	protected List<S> defaultSorts;
	protected Map<S, SortOrder> sortMap;

	@SafeVarargs
	protected AbstractSearchQuery(S ... defaultSorts) {
		this.defaultSorts = ImmutableList.copyOf(defaultSorts);
	}

	// Sort
	@Override
	public ISearchQuery<T, S> sort(Map<S, SortOrder> sortMap) {
		this.sortMap = ImmutableMap.copyOf(sortMap);
		return this;
	}
}

Remove default implementation of fullList()


package io.gravitee.am.gateway.handler.oauth2.userdetails;

import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import java.util.Collections;

/**
 * @author David BRASSELY (david.brassely at graviteesource.com)
 * @author GraviteeSource Team
 */
public class CustomUserDetailsService implements UserDetailsService {

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        return new User("toto", "password", Collections.emptyList());
    }
}

package io.gravitee.am.gateway.handler.oauth2.userdetails;

import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import java.util.Collections;

/**
 * @author David BRASSELY (david.brassely at graviteesource.com)
 * @author GraviteeSource Team
 */
public class CustomUserDetailsService implements UserDetailsService {

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        return new User(username, "password", Collections.emptyList());
    }
}

Use same username for userDetails