package nallar.tickthreading.mixin.world;

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

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

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

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

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

package nallar.tickthreading.mixin.world;

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

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

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

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

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

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

Add more useful toString for World than the default


package core;

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

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

import static org.junit.Assert.*;

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

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

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

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

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

        assertEquals(4, map.size());

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

}

package core;

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

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

import static org.junit.Assert.*;

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

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

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

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

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

        assertEquals(4, map.size());

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

}

Fix FindBugs warnings in Parser Test.

Fix FindBugs warnings in Parser Test.


package xhl.core;

import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

import xhl.core.elements.CodeList;
import xhl.core.exceptions.EvaluationException;

/**
 * LanguageProcessor, which reads code from the file and outputs error messages
 * to the standard error output.
 *
 * @author Sergej Chodarev
 */
public class ConsoleLanguageProcessor extends LanguageProcessor {

    public ConsoleLanguageProcessor(Language lang) {
        super(lang);
    }

    public void process(String filename) throws FileNotFoundException,
            IOException {
        Reader reader = new Reader();
        CodeList program = reader.read(new FileReader(filename));
        try {
            execute(program);
        } catch (EvaluationException e) {
            System.err.printf("%s: %s", e.getPosition(), e);
        }
    }
}

package xhl.core;

import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

import xhl.core.elements.CodeList;
import xhl.core.exceptions.EvaluationException;

/**
 * LanguageProcessor, which reads code from the file and outputs error messages
 * to the standard error output.
 *
 * @author Sergej Chodarev
 */
public class ConsoleLanguageProcessor extends LanguageProcessor {

    public ConsoleLanguageProcessor(Language lang) {
        super(lang);
    }

    public void process(String filename) throws FileNotFoundException,
            IOException {
        Reader reader = new Reader();
        CodeList program = reader.read(new FileReader(filename));
        try {
            execute(program);
        } catch (EvaluationException e) {
            System.err.printf("%s: %s\n", e.getPosition(), e);
        }
    }
}

Add new line at the end of error message


package edu.deanza.calendar.models;

//constructor for localDateTime: LocalDateTime(int year, int monthOfYear, int dayOfMonth, int hourOfDay, int minuteOfHour)

import org.joda.time.LocalTime;

/**
 * Created by Sara on 5/28/2016.
 */
public class Event {
    protected String name, description, location;
    protected LocalTime startTime, endTime;
    protected enum source {
        Facebook, ClubMeeting, TransferAppointment, Website
    }
    // TODO: add `categories` field

    Event(String name, String description, String location, String startTime,
          String endTime)
    {
        this.name = name;
        this.description = description;
        this.location = location;
        this.startTime = LocalTime.parse(startTime);
        this.endTime = LocalTime.parse(endTime);

    }

}

package edu.deanza.calendar.models;

//constructor for localDateTime: LocalDateTime(int year, int monthOfYear, int dayOfMonth, int hourOfDay, int minuteOfHour)

import org.joda.time.LocalTime;

/**
 * Created by Sara on 5/28/2016.
 */
public class Event {
    protected String name, description, location;
    protected LocalTime startTime, endTime;
    // TODO: add `categories` field

    Event(String name, String description, String location, String startTime,
          String endTime)
    {
        this.name = name;
        this.description = description;
        this.location = location;
        this.startTime = LocalTime.parse(startTime);
        this.endTime = LocalTime.parse(endTime);

    }

}

Remove `source` field; type and container will have this info


package me.nallar.collections;

import me.nallar.tickthreading.Log;
import net.minecraft.world.World;

public class ListSet extends SynchronizedList {
	@Override
	public synchronized boolean add(final Object o) {
		if (o instanceof World) {
			World world = (World) o;
			for (World world_ : (Iterable<World>) this) {
				if (world_ == world) {
					return false;
				} else if (world.provider.dimensionId == world_.provider.dimensionId) {
					Log.severe("Attempted to add " + Log.dumpWorld(world) + " to bukkit dimensions when " + Log.dumpWorld(world_) + " is already in it.", new Throwable());
					return false;
				}
			}
			return super.add(o);
		}
		return !this.contains(o) && super.add(o);
	}
}

package me.nallar.collections;

import java.util.Iterator;

import me.nallar.tickthreading.Log;
import net.minecraft.world.World;
import net.minecraft.world.WorldProvider;

public class ListSet extends SynchronizedList {
	@Override
	public synchronized boolean add(final Object o) {
		if (o instanceof World) {
			World world = (World) o;
			WorldProvider provider = world.provider;
			if (provider == null) {
				Log.severe("Tried to add world " + world + " with null provider to bukkit dimensions.", new Throwable());
				return false;
			}
			Iterator<World> iterator = this.iterator();
			while (iterator.hasNext()) {
				World world_ = iterator.next();
				if (world_ == world) {
					return false;
				} else if (world_.provider == null) {
					Log.severe("World " + world_ + " with null provider still in bukkit dimensions.", new Throwable());
					iterator.remove();
				} else if (provider.dimensionId == world_.provider.dimensionId) {
					Log.severe("Attempted to add " + Log.dumpWorld(world) + " to bukkit dimensions when " + Log.dumpWorld(world_) + " is already in it.", new Throwable());
					return false;
				}
			}
			return super.add(o);
		}
		return !this.contains(o) && super.add(o);
	}
}

Fix crash on login with broken bukkit dimensions list

Signed-off-by: Ross Allan <ca2c77e14df1e7ee673215c1ef658354e220f471@gmail.com>


package test.issues.strava;

import static org.junit.Assert.assertNull;
import javastrava.api.v3.model.StravaSegmentEffort;
import javastrava.api.v3.service.exception.NotFoundException;
import javastrava.api.v3.service.impl.retrofit.Retrofit;
import javastrava.api.v3.service.impl.retrofit.SegmentEffortServicesRetrofit;

import org.junit.Test;

import test.utils.TestUtils;

/**
 *

 * These tests should PASS if issue javastrava-api #32 still exists
 *

 *
 * @author Dan Shannon
 * @see https://github.com/danshannon/javastravav3api/issues/32
 *
 */
public class Issue27 {
	@Test
	public void testIssue() throws NotFoundException {
		SegmentEffortServicesRetrofit retrofit = Retrofit.retrofit(SegmentEffortServicesRetrofit.class, TestUtils.getValidToken());
		StravaSegmentEffort effort = retrofit.getSegmentEffort(5591276015L);
		assertNull(effort.getAthlete().getResourceState());
	}
}

package test.issues.strava;

import static org.junit.Assert.assertNull;
import javastrava.api.v3.model.StravaSegmentEffort;
import javastrava.api.v3.service.exception.NotFoundException;
import javastrava.api.v3.service.impl.retrofit.Retrofit;
import javastrava.api.v3.service.impl.retrofit.SegmentEffortServicesRetrofit;

import org.junit.Test;

import test.utils.TestUtils;

/**
 *

 * These tests should PASS if issue javastrava-api #27 still exists
 *

 *
 * @author Dan Shannon
 * @see https://github.com/danshannon/javastravav3api/issues/27
 *
 */
public class Issue27 {
	@Test
	public void testIssue() throws NotFoundException {
		SegmentEffortServicesRetrofit retrofit = Retrofit.retrofit(SegmentEffortServicesRetrofit.class, TestUtils.getValidToken());
		StravaSegmentEffort effort = retrofit.getSegmentEffort(5591276015L);
		assertNull(effort.getAthlete().getResourceState());
	}
}

Correct issue number in documentation

Correct issue number in documentation


package org.granchi.hollywood;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.junit.MockitoJUnitRunner;

import static com.google.common.truth.Truth.assertThat;

@RunWith(MockitoJUnitRunner.class)
public class ModelTest {
    @Test
    public void testGetSubmodelsOfSameType() throws Exception {
        ParentModel model = new ParentModel();

        assertThat(model.getSubmodelsOfType(ParentModel.class)).containsExactly(model);
    }

    @Test
    public void testGetSubmodelsOfParentType() throws Exception {
        ChildModel model = new ChildModel();

        assertThat(model.getSubmodelsOfType(ParentModel.class)).containsExactly(model);
    }

    @Test
    public void testGetSubmodelsOfChildType() throws Exception {
        ParentModel model = new ParentModel();

        assertThat(model.getSubmodelsOfType(ChildModel.class)).isEmpty();
    }

    @Test
    public void testGetSubmodelsOfUnrelatedType() throws Exception {
        ParentModel model = new ParentModel();

        assertThat(model.getSubmodelsOfType(OtherParentModel.class)).isEmpty();
    }

    private class ParentModel extends Model {
        @Override
        protected Model actUpon(Action action) {
            return null;
        }
    }

    private class ChildModel extends ParentModel {
        @Override
        protected Model actUpon(Action action) {
            return null;
        }
    }

    public class OtherParentModel extends Model {
        @Override
        protected Model actUpon(Action action) {
            return null;
        }
    }
}

package org.granchi.hollywood;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.junit.MockitoJUnitRunner;

import static com.google.common.truth.Truth.assertThat;

@RunWith(MockitoJUnitRunner.class)
public class ModelTest {
    @Test
    public void testGetSubmodelsOfSameType() throws Exception {
        ParentModel model = new ParentModel();

        assertThat(model.getSubmodelsOfType(ParentModel.class)).containsExactly(model);
    }

    @Test
    public void testGetSubmodelsOfParentType() throws Exception {
        ChildModel model = new ChildModel();

        assertThat(model.getSubmodelsOfType(ParentModel.class)).containsExactly(model);
    }

    @Test
    public void testGetSubmodelsOfChildType() throws Exception {
        ParentModel model = new ParentModel();

        assertThat(model.getSubmodelsOfType(ChildModel.class)).isEmpty();
    }

    @Test
    public void testGetSubmodelsOfUnrelatedType() throws Exception {
        ParentModel model = new ParentModel();

        assertThat(model.getSubmodelsOfType(OtherParentModel.class)).isEmpty();
    }

    private static class ParentModel extends Model {
        @Override
        protected Model actUpon(Action action) {
            return null;
        }
    }

    private static class ChildModel extends ParentModel {
        @Override
        protected Model actUpon(Action action) {
            return null;
        }
    }

    public static class OtherParentModel extends Model {
        @Override
        protected Model actUpon(Action action) {
            return null;
        }
    }
}

Make test inner classes static

Make test inner classes static


/* TRUNK */
package bingo;
import java.util.ArrayList;

public class BingoCard {
    //private int[] cardNumbers = new int[24];
    //NumberCollection nc  =new NumberCollection();
    private ArrayList<Integer> cardNumbers = new ArrayList<Integer>();

    public BingoCard(){
        generateNumbers(24);
    }

    private void generateNumbers(int n){

    }

    public void stampNumber(int n){}

    public boolean containsNumber(int n){
        return false;
    }

    public int numbersStamped(){
        return 0;
    }

    public NumberCollection numberMissing(){
        NumberCollection nc  =new NumberCollection();
        return nc;
    }

}

Clear spaces - fix indent

Clear spaces - fix indent


package seedu.task.alerts;

import java.util.Optional;

import javafx.scene.control.Alert;
import javafx.scene.control.ButtonType;

//@@author A0142360U
public class TransferTaskAlert extends Alert {

    public static final String CHANGE_DIRECTORY_COMMAND_TITLE = "Change of Task Storage Directory";
    public static final String CHANGE_DIRECTORY_HEADER_TEXT = "Would you like your existing tasks to be transferred over to the new directory?";
    public static final ButtonType buttonTypeYes = new ButtonType("Yes");
    public static final ButtonType buttonTypeNo = new ButtonType("No");
    public static final ButtonType buttonTypeCancel = new ButtonType("Cancel");
    public static final String yes = "Yes";
    public static final String no = "No";
    public static final String noAction = "noAction";

    public TransferTaskAlert(AlertType alertType) {
        super(alertType);
    }

    public static String transferTaskOptionAlert() {

        try {
            Alert alert = new Alert(AlertType.CONFIRMATION);
            alert.setTitle(CHANGE_DIRECTORY_COMMAND_TITLE);
            alert.setHeaderText(CHANGE_DIRECTORY_HEADER_TEXT);
            alert.getButtonTypes().setAll(buttonTypeYes, buttonTypeNo, buttonTypeCancel);

            Optional<ButtonType> result = alert.showAndWait();
            if (result.get() == buttonTypeYes) {
                return yes;
            } else if (result.get() == buttonTypeNo) {
                return no;
            } else {
                return noAction;
            }

        } catch (ExceptionInInitializerError | IllegalStateException e) {
            return noAction;
        }

    }

}

package seedu.task.alerts;

import java.util.Optional;

import javafx.scene.control.Alert;
import javafx.scene.control.ButtonType;

//@@author A0142360U
public class TransferTaskAlert extends Alert {

    public static final String CHANGE_DIRECTORY_COMMAND_TITLE = "Change of Task Storage Directory";
    public static final String CHANGE_DIRECTORY_HEADER_TEXT = "Would you like your existing tasks to be transferred over to the new directory?\nNOTE: Never Forget will need to be relaunched.";
    public static final ButtonType buttonTypeYes = new ButtonType("Yes");
    public static final ButtonType buttonTypeNo = new ButtonType("No");
    public static final ButtonType buttonTypeCancel = new ButtonType("Cancel");
    public static final String yes = "Yes";
    public static final String no = "No";
    public static final String noAction = "noAction";

    public TransferTaskAlert(AlertType alertType) {
        super(alertType);
    }

    public static String transferTaskOptionAlert() {

        try {
            Alert alert = new Alert(AlertType.CONFIRMATION);
            alert.setTitle(CHANGE_DIRECTORY_COMMAND_TITLE);
            alert.setHeaderText(CHANGE_DIRECTORY_HEADER_TEXT);
            alert.getButtonTypes().setAll(buttonTypeYes, buttonTypeNo, buttonTypeCancel);

            Optional<ButtonType> result = alert.showAndWait();
            if (result.get() == buttonTypeYes) {
                return yes;
            } else if (result.get() == buttonTypeNo) {
                return no;
            } else {
                return noAction;
            }

        } catch (ExceptionInInitializerError | IllegalStateException e) {
            return noAction;
        }

    }

}

Change in warning message when user attempts to change task storage directory


package de.philipphager.disclosure;

import android.app.Application;
import com.jakewharton.threetenabp.AndroidThreeTen;

import static de.philipphager.disclosure.util.assertion.Assertions.ensureNotNull;

public class DisclosureApp extends Application {
  private ApplicationComponent applicationComponent;

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

  private void buildObjectGraphAndInject() {
    applicationComponent = DaggerApplicationComponent.builder()
        .applicationModule(new ApplicationModule(this))
        .build();

    AndroidThreeTen.init(this);
  }

  public ApplicationComponent getApplicationComponent() {
    return ensureNotNull(applicationComponent, "object graph not build");
  }
}

package de.philipphager.disclosure;

import android.app.Application;
import com.facebook.stetho.Stetho;
import com.jakewharton.threetenabp.AndroidThreeTen;
import timber.log.Timber;

import static de.philipphager.disclosure.util.assertion.Assertions.ensureNotNull;

public class DisclosureApp extends Application {
  private ApplicationComponent applicationComponent;

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

  private void buildObjectGraphAndInject() {
    applicationComponent = DaggerApplicationComponent.builder()
        .applicationModule(new ApplicationModule(this))
        .build();

    AndroidThreeTen.init(this);
    Stetho.initializeWithDefaults(this);
    Timber.plant(new Timber.DebugTree());
  }

  public ApplicationComponent getApplicationComponent() {
    return ensureNotNull(applicationComponent, "object graph not build");
  }
}

Initialize Stetho and Timber logging in Application


package SW9.model_canvas.arrow_heads;

import javafx.scene.paint.Color;
import javafx.scene.shape.LineTo;
import javafx.scene.shape.MoveTo;
import javafx.scene.shape.Path;

public class SimpleArrowHead extends ArrowHead {

    private static final double TRIANGLE_LENGTH = 20d;
    private static final double TRIANGLE_WIDTH = 15d;

    public SimpleArrowHead() {
        super();

        addChild(initializeTriangle());
    }

    private Path initializeTriangle() {
        final Path simpleArrow = new Path();

        MoveTo start = new MoveTo();
        LineTo l1 = new LineTo();
        MoveTo l2 = new MoveTo();
        LineTo l3 = new LineTo();

        start.xProperty().bind(xProperty);
        start.yProperty().bind(yProperty);

        l1.xProperty().bind(start.xProperty().subtract(TRIANGLE_WIDTH / 2));
        l1.yProperty().bind(start.yProperty().subtract(TRIANGLE_LENGTH));

        l2.xProperty().bind(start.xProperty().add(TRIANGLE_WIDTH / 2));
        l2.yProperty().bind(start.yProperty().subtract(TRIANGLE_LENGTH));

        l3.xProperty().bind(start.xProperty());
        l3.yProperty().bind(start.yProperty());

        simpleArrow.setStroke(Color.BLACK);
        simpleArrow.getElements().addAll(start, l1, l2, l3);

        return simpleArrow;
    }

    @Override
    public double getHeadHeight() {
        return TRIANGLE_LENGTH;
    }

    @Override
    public double getHeadWidth() {
        return TRIANGLE_WIDTH;
    }

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

}

package SW9.model_canvas.arrow_heads;

import javafx.scene.shape.Line;

public class SimpleArrowHead extends ArrowHead {

    private static final double TRIANGLE_LENGTH = 20d;
    private static final double TRIANGLE_WIDTH = 15d;

    public SimpleArrowHead() {
        super();

        addChildren(initializeLeftArrow(), initializeRightArrow());
    }

    private Line initializeLeftArrow() {
        final Line leftArrow = new Line();
        leftArrow.startXProperty().bind(xProperty);
        leftArrow.startYProperty().bind(yProperty);
        leftArrow.endXProperty().bind(xProperty.subtract(TRIANGLE_WIDTH / 2));
        leftArrow.endYProperty().bind(yProperty.subtract(TRIANGLE_LENGTH));

        return leftArrow;
    }

    private Line initializeRightArrow() {
        final Line rightArrow = new Line();
        rightArrow.startXProperty().bind(xProperty);
        rightArrow.startYProperty().bind(yProperty);
        rightArrow.endXProperty().bind(xProperty.add(TRIANGLE_WIDTH / 2));
        rightArrow.endYProperty().bind(yProperty.subtract(TRIANGLE_LENGTH));

        return rightArrow;
    }

    @Override
    public double getHeadHeight() {
        return TRIANGLE_LENGTH;
    }

    @Override
    public double getHeadWidth() {
        return TRIANGLE_WIDTH;
    }

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

}

Refactor simple arrow head to use two lines instead of path


package io.undertow.io;

import java.io.IOException;

import io.undertow.UndertowLogger;
import io.undertow.server.HttpServerExchange;
import org.xnio.IoUtils;

/**
 * A default callback implementation that simply ends the exchange
 *
 * @author Stuart Douglas
 * @see IoCallback#END_EXCHANGE
 */
public class DefaultIoCallback implements IoCallback {

    protected DefaultIoCallback() {

    }

    @Override
    public void onComplete(final HttpServerExchange exchange, final Sender sender) {
        sender.close(new IoCallback() {
            @Override
            public void onComplete(final HttpServerExchange exchange, final Sender sender) {
                try {
                    sender.close();
                } finally {
                    exchange.endExchange();
                }
            }

            @Override
            public void onException(final HttpServerExchange exchange, final Sender sender, final IOException exception) {
                UndertowLogger.REQUEST_IO_LOGGER.ioException(exception);
                try {
                    sender.close();
                } finally {
                    exchange.endExchange();
                }
            }
        });
    }

    @Override
    public void onException(final HttpServerExchange exchange, final Sender sender, final IOException exception) {
        try {
            exchange.endExchange();
        } finally {
            IoUtils.safeClose(exchange.getConnection());
        }
    }
}

package io.undertow.io;

import java.io.IOException;

import io.undertow.UndertowLogger;
import io.undertow.server.HttpServerExchange;
import org.xnio.IoUtils;

/**
 * A default callback implementation that simply ends the exchange
 *
 * @author Stuart Douglas
 * @see IoCallback#END_EXCHANGE
 */
public class DefaultIoCallback implements IoCallback {

    protected DefaultIoCallback() {

    }

    @Override
    public void onComplete(final HttpServerExchange exchange, final Sender sender) {
        sender.close(new IoCallback() {
            @Override
            public void onComplete(final HttpServerExchange exchange, final Sender sender) {
                exchange.endExchange();
            }

            @Override
            public void onException(final HttpServerExchange exchange, final Sender sender, final IOException exception) {
                UndertowLogger.REQUEST_IO_LOGGER.ioException(exception);
                exchange.endExchange();
            }
        });
    }

    @Override
    public void onException(final HttpServerExchange exchange, final Sender sender, final IOException exception) {
        try {
            exchange.endExchange();
        } finally {
            IoUtils.safeClose(exchange.getConnection());
        }
    }
}

Fix issue with the default IO callback

Fix issue with the default IO callback


package com.gh4a.loader;

import java.io.IOException;

import org.eclipse.egit.github.core.RepositoryId;
import org.eclipse.egit.github.core.client.RequestException;
import org.eclipse.egit.github.core.service.CollaboratorService;

import android.content.Context;

import com.gh4a.Gh4Application;

public class IsCollaboratorLoader extends BaseLoader<Boolean> {

    private String mRepoOwner;
    private String mRepoName;

    public IsCollaboratorLoader(Context context, String repoOwner, String repoName) {
        super(context);
        mRepoOwner = repoOwner;
        mRepoName = repoName;
    }

    @Override
    public Boolean doLoadInBackground() throws IOException {
        Gh4Application app = Gh4Application.get();
        CollaboratorService collabService =
                (CollaboratorService) app.getService(Gh4Application.COLLAB_SERVICE);
        try {
            RepositoryId repoId = new RepositoryId(mRepoOwner, mRepoName);
            return collabService.isCollaborator(repoId, app.getAuthLogin());
        } catch (RequestException e) {
            if (e.getStatus() == 403) {
                // the API returns 403 if the user doesn't have push access,
                // which in turn means he isn't a collaborator
                return false;
            }
            throw e;
        }
    }
}

package com.gh4a.loader;

import java.io.IOException;

import org.eclipse.egit.github.core.RepositoryId;
import org.eclipse.egit.github.core.client.RequestException;
import org.eclipse.egit.github.core.service.CollaboratorService;

import android.content.Context;

import com.gh4a.Gh4Application;

public class IsCollaboratorLoader extends BaseLoader<Boolean> {

    private String mRepoOwner;
    private String mRepoName;

    public IsCollaboratorLoader(Context context, String repoOwner, String repoName) {
        super(context);
        mRepoOwner = repoOwner;
        mRepoName = repoName;
    }

    @Override
    public Boolean doLoadInBackground() throws IOException {
        Gh4Application app = Gh4Application.get();
        String login = app.getAuthLogin();
        if (login == null) {
            return false;
        }

        CollaboratorService collabService =
                (CollaboratorService) app.getService(Gh4Application.COLLAB_SERVICE);
        try {
            RepositoryId repoId = new RepositoryId(mRepoOwner, mRepoName);
            return collabService.isCollaborator(repoId, login);
        } catch (RequestException e) {
            if (e.getStatus() == 403) {
                // the API returns 403 if the user doesn't have push access,
                // which in turn means he isn't a collaborator
                return false;
            }
            throw e;
        }
    }
}

Fix load failure if not logged in.

Fix load failure if not logged in.


package yanagishima.provider;

import me.geso.tinyorm.TinyORM;

import javax.inject.Inject;
import javax.inject.Provider;
import java.sql.Connection;

public class TinyORMProvider implements Provider<TinyORM> {

	@Inject
	private Connection connection;

	@Override
	public TinyORM get() {
		TinyORM tinyORM =  new TinyORM(connection);
		tinyORM.setQueryTimeout(3);
		return tinyORM;
	}
}

package yanagishima.provider;

import me.geso.tinyorm.TinyORM;

import javax.inject.Inject;
import javax.inject.Provider;
import java.sql.Connection;

public class TinyORMProvider implements Provider<TinyORM> {

	@Inject
	private Connection connection;

	@Override
	public TinyORM get() {
		TinyORM tinyORM =  new TinyORM(connection);
		tinyORM.setQueryTimeout(10);
		return tinyORM;
	}
}

Increase timeout to avoid SQLITE_BUSY

Increase timeout to avoid SQLITE_BUSY


package org.robockets.robotswitcher;

import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard;

/** Used to get and initialize a SmartDashboard field for a robot number
 *
 *
 * @author Jake Backer
 * @version
v.1.sleepy.1.0.ocean.1450230474.7

 *
 *
 *
 *
 */
public class Switcher {

	/** Holds the value of the SmartDashboard field*/
	public int currentRobot;

	/** Initializes the currentRobot field*/
	public Switcher() {
		try{
		currentRobot = getRobot();
		}catch(DoesNotExistException e){
			e.printStackTrace();
		}
	}

	/**
	 * Stores the value of the field in SmartDashboard in currentRobot
	 * @return The value of currentRobot
	 * @throws DoesNotExistException Thrown if field on SmartDashboard does not exist
	 */
	public int getRobot() throws DoesNotExistException{
		currentRobot = (int) SmartDashboard.getNumber("RobotNumber");
		return currentRobot;
	}

	/** Initializes the field on SmartDashboard TEMPORARY*/
	public void initRobotNumber() {
		SmartDashboard.putNumber("RobotNumber", 0); //TEMP
	}

}

package org.robockets.robotswitcher;

import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard;

/** Used to get and initialize a SmartDashboard field for a robot number
 *
 *
 * @author Jake Backer
 * @version
v.1.sleepy.1.0.ocean.1450230474.7

 *
 *
 *
 *
 */
public class Switcher {

	/** Holds the value of the SmartDashboard field*/
	public int currentRobot;

	/** Initializes the currentRobot field*/
	public Switcher() {
		try{
		currentRobot = getRobot();
		}catch(DoesNotExistException e){
			System.out.println("SmartDashboard field does not exist! Run initRobotNumber()");
		}
	}

	/**
	 * Stores the value of the field in SmartDashboard in currentRobot
	 * @return The value of currentRobot
	 * @throws DoesNotExistException Thrown if field on SmartDashboard does not exist
	 */
	public int getRobot() throws DoesNotExistException{
		currentRobot = (int) SmartDashboard.getNumber("RobotNumber");
		return currentRobot;
	}

	/** Initializes the field on SmartDashboard TEMPORARY*/
	public void initRobotNumber() {
		SmartDashboard.putNumber("RobotNumber", 0); //TEMP
	}

}

Change what happens when there is no field on SmartDashboard


/*
 *  JavaSMT is an API wrapper for a collection of SMT solvers.
 *  This file is part of JavaSMT.
 *
 *  Copyright (C) 2007-2015  Dirk Beyer
 *  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.sosy_lab.solver.z3java;

import org.junit.Test;
import org.sosy_lab.solver.SolverContextFactory.Solvers;
import org.sosy_lab.solver.test.SolverBasedTest0;

public class Z3JavaLoadingTest extends SolverBasedTest0 {

  @Override
  protected Solvers solverToUse() {
    return Solvers.Z3JAVA;
  }

  @Test(expected = Exception.class)
  @SuppressWarnings("CheckReturnValue")
  public void testErrorHandling() throws Exception {
    // Will exit(1) without an exception handler.
    rmgr.makeNumber("not-a-number");
  }
}

/*
 *  JavaSMT is an API wrapper for a collection of SMT solvers.
 *  This file is part of JavaSMT.
 *
 *  Copyright (C) 2007-2015  Dirk Beyer
 *  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.sosy_lab.solver.z3java;

import org.junit.Test;
import org.sosy_lab.solver.SolverContextFactory;
import org.sosy_lab.solver.SolverContextFactory.Solvers;

public class Z3JavaLoadingTest {

  @Test
  @SuppressWarnings("CheckReturnValue")
  public void testErrorHandling() throws Exception {

    // Test that Z3Java can be loaded correctly.
    SolverContextFactory.createSolverContext(Solvers.Z3JAVA);
  }
}

Test whether Z3Java can be loaded in a simpler way.


package me.nallar.patched;

import net.minecraft.world.ChunkCoordIntPair;

public abstract class PatchChunkCoordIntPair extends ChunkCoordIntPair {
	public PatchChunkCoordIntPair(int par1, int par2) {
		super(par1, par2);
	}

	@Override
	public boolean equals(Object o) {
		return o instanceof ChunkCoordIntPair && ((ChunkCoordIntPair) o).chunkZPos == this.chunkXPos && ((ChunkCoordIntPair) o).chunkZPos == this.chunkZPos;
	}

	@Override
	public int hashCode() {
		return (chunkXPos * 7907) + chunkXPos;
	}
}

package me.nallar.patched;

import net.minecraft.world.ChunkCoordIntPair;

public abstract class PatchChunkCoordIntPair extends ChunkCoordIntPair {
	public PatchChunkCoordIntPair(int par1, int par2) {
		super(par1, par2);
	}

	@Override
	public boolean equals(Object o) {
		return o instanceof ChunkCoordIntPair && ((ChunkCoordIntPair) o).chunkXPos == this.chunkXPos && ((ChunkCoordIntPair) o).chunkZPos == this.chunkZPos;
	}

	@Override
	public int hashCode() {
		return (chunkXPos * 7907) + chunkXPos;
	}
}

Fix everything being completely broken. Oops.

Signed-off-by: Ross Allan <ca2c77e14df1e7ee673215c1ef658354e220f471@gmail.com>


package controllers;

import play.*;
import play.mvc.*;
import play.db.jpa.*;

import views.html.*;

public class Application extends Controller {
    public Result index() {
        return ok(index.render("Hello World!"));
    }

}

package controllers;

import play.*;
import play.mvc.*;
import play.db.jpa.*;

import views.html.*;

public class Application extends Controller {
    public Result index() {
        return ok(index.render("System started"));
    }

}

Replace Hello World with something more professional


package nl.vpro.poel.service;

import nl.vpro.poel.domain.Group;
import nl.vpro.poel.dto.GroupForm;
import nl.vpro.poel.repository.GroupRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;

@Service
public class GroupServiceImpl implements GroupService {

    private static final Logger logger = LoggerFactory.getLogger(MessageServiceImpl.class);

    private final GroupRepository groupRepository;

    @Autowired
    public GroupServiceImpl(GroupRepository groupRepository) { this.groupRepository = groupRepository; }

    @Override
    public Optional<Group> findById(Long id) {
        return Optional.ofNullable(groupRepository.findOne(id));
    }

    @Override
    public Optional<Group> findByName(String name) {
        return Optional.ofNullable(groupRepository.findByName(name));
    }

    @Override
    public List<Group> findAll() { return groupRepository.findAll(); }

    @Override
    public void setGroups(GroupForm groupForm) {
       // TODO save posted groups
    }
}

package nl.vpro.poel.service;

import nl.vpro.poel.domain.Group;
import nl.vpro.poel.dto.GroupForm;
import nl.vpro.poel.repository.GroupRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

@Service
public class GroupServiceImpl implements GroupService {

    private final GroupRepository groupRepository;

    @Autowired
    public GroupServiceImpl(GroupRepository groupRepository) { this.groupRepository = groupRepository; }

    @Override
    public Optional<Group> findById(Long id) {
        return Optional.ofNullable(groupRepository.findOne(id));
    }

    @Override
    public Optional<Group> findByName(String name) {
        return Optional.ofNullable(groupRepository.findByName(name));
    }

    @Override
    public List<Group> findAll() { return groupRepository.findAll(); }

    @Override
    public void setGroups(GroupForm groupForm) {
       // TODO save posted groups
    }
}

Remove the unused logger (for the wrong class), Luke!


package udacity.storm.tools;

import java.util.Properties;

import edu.stanford.nlp.ling.CoreAnnotations;
import edu.stanford.nlp.neural.rnn.RNNCoreAnnotations;
import edu.stanford.nlp.pipeline.Annotation;
import edu.stanford.nlp.pipeline.StanfordCoreNLP;
import edu.stanford.nlp.sentiment.SentimentCoreAnnotations;
import edu.stanford.nlp.trees.Tree;
import edu.stanford.nlp.util.CoreMap;

public class SentimentAnalyzer {
    static StanfordCoreNLP pipeline;

    public static void init() {
    	Properties props = new Properties();
        props.setProperty("annotators", "tokenize,ssplit,parse,sentiment");
        pipeline = new StanfordCoreNLP(props);
    }

    public static int findSentiment(String tweet) {

        int mainSentiment = 0;
        if (tweet != null && tweet.length() > 0) {
            int longest = 0;
            Annotation annotation = pipeline.process(tweet);
            for (CoreMap sentence : annotation
                    .get(CoreAnnotations.SentencesAnnotation.class)) {
                Tree tree = sentence
                        .get(SentimentCoreAnnotations.AnnotatedTree.class);
                int sentiment = RNNCoreAnnotations.getPredictedClass(tree);
                String partText = sentence.toString();
                if (partText.length() > longest) {
                    mainSentiment = sentiment;
                    longest = partText.length();
                }

            }
        }
        return mainSentiment;
    }
}

package udacity.storm.tools;

import java.util.Properties;

import edu.stanford.nlp.ling.CoreAnnotations;
import edu.stanford.nlp.neural.rnn.RNNCoreAnnotations;
import edu.stanford.nlp.pipeline.Annotation;
import edu.stanford.nlp.pipeline.StanfordCoreNLP;
import edu.stanford.nlp.sentiment.SentimentCoreAnnotations;
import edu.stanford.nlp.trees.Tree;
import edu.stanford.nlp.util.CoreMap;

public class SentimentAnalyzer {
    static StanfordCoreNLP pipeline;

    public static void init() {
    	Properties props = new Properties();
        props.setProperty("annotators", "tokenize,ssplit,parse,sentiment");
        pipeline = new StanfordCoreNLP(props);
    }

    public static int getBinarySentiment(int sentiment){
        if(sentiment<=2)
            return 0;
        else
            return 1;
    }

    public static int findSentiment(String tweet) {

        int mainSentiment = 0;
        if (tweet != null && tweet.length() > 0) {
            int longest = 0;
            Annotation annotation = pipeline.process(tweet);
            for (CoreMap sentence : annotation
                    .get(CoreAnnotations.SentencesAnnotation.class)) {
                Tree tree = sentence
                            .get(SentimentCoreAnnotations.AnnotatedTree.class);
                int sentiment = RNNCoreAnnotations.getPredictedClass(tree);
                String partText = sentence.toString();
                if(partText.length() > longest){
                    mainSentiment = sentiment;
                    longest = partText.length();
                }
            }
        }
        return getBinarySentiment(mainSentiment);
    }
}

Use binary scores to represent sentiment in map


package ee.shy.core;

import ee.shy.io.Jsonable;
import ee.shy.io.Validated;

import java.net.URI;
import java.util.Objects;

/**
 * Class representing a remote repository's URI.
 */
public class Remote implements Jsonable, Validated {
    /**
     * Repository's URI.
     */
    private final URI remote;

    /**
     * Constructs a remote with given URI.
     * @param remote remote URI for repository
     */
    public Remote(URI remote) {
        this.remote = remote;
        assertValid();
    }

    public URI getURI() {
        return this.remote;
    }

    @Override
    public void assertValid() {
        Objects.requireNonNull(remote, "repository has no URI");
    }
}

package ee.shy.core;

import ee.shy.io.Jsonable;
import ee.shy.io.Validated;

import java.net.URI;
import java.util.Objects;

/**
 * Class representing a remote repository's URI.
 */
public class Remote implements Jsonable, Validated {
    /**
     * Repository's URI.
     */
    private final URI uri;

    /**
     * Constructs a remote with given URI.
     * @param uri remote URI for repository
     */
    public Remote(URI uri) {
        this.uri = uri;
        assertValid();
    }

    public URI getURI() {
        return this.uri;
    }

    @Override
    public void assertValid() {
        Objects.requireNonNull(uri, "repository has no URI");
    }
}

Rename remote field to uri.

Rename remote field to uri.


/*
 * Copyright (C) 2013 Square, 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.example.dagger.simple;

import android.app.Application;
import dagger.ObjectGraph;
import java.util.Arrays;
import java.util.List;

public class DemoApplication extends Application {
  private ObjectGraph graph;

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

    graph = ObjectGraph.create(getModules().toArray());
  }

  protected List<Object> getModules() {
    return Arrays.<Object>asList(
        new AndroidModule(this)
    );
  }

  public void inject(Object object) {
    graph.inject(object);
  }
}

/*
 * Copyright (C) 2013 Square, 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.example.dagger.simple;

import android.app.Application;
import dagger.ObjectGraph;
import java.util.Arrays;
import java.util.List;

public class DemoApplication extends Application {
  private ObjectGraph graph;

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

    graph = ObjectGraph.create(getModules().toArray());
  }

  protected List<Object> getModules() {
    return Arrays.asList(
        new AndroidModule(this),
        new DemoModule()
    );
  }

  public void inject(Object object) {
    graph.inject(object);
  }
}

Include DemoModule in module list for simple Android example.


package env;

import types.*;

public class Env {

  public Table<Type> tenv;
  public Table<Type> venv;

  public Env() {
    tenv = new Table<Type>();
    put(tenv, "unit", UNIT.T);
    put(tenv, "int",  INT.T);
    put(tenv, "real", REAL.T);
    put(tenv, "bool", BOOL.T);

    venv = new Table<Type>();
    put(venv, "print_int",  new FUNCTION(UNIT.T, INT.T));
    put(venv, "print_real", new FUNCTION(UNIT.T, REAL.T));
    put(venv, "print_unit", new FUNCTION(UNIT.T, UNIT.T));
    put(venv, "print_bool", new FUNCTION(UNIT.T, BOOL.T));
    put(venv, "round",      new FUNCTION(INT.T, REAL.T));
    put(venv, "ceil",       new FUNCTION(INT.T, REAL.T));
    put(venv, "floor",      new FUNCTION(INT.T, REAL.T));
    put(venv, "real",       new FUNCTION(REAL.T, INT.T));
  }

  @Override
  public String toString() {
    return "Env{" +
           "tenv=" + tenv +
           ", venv=" + venv +
           '}';
  }

  private static <E> void put(Table<E> table, String name, E value) {
    table.put(name.intern(), value);
  }

}

package env;

import types.*;

public class Env {

  public Table<Type> tenv;
  public Table<Type> venv;

  public Env() {
    tenv = new Table<Type>();
    put(tenv, "unit", UNIT.T);
    put(tenv, "int",  INT.T);
    put(tenv, "real", REAL.T);
    put(tenv, "bool", BOOL.T);

    venv = new Table<Type>();
    put(venv, "print_int",  new FUNCTION(UNIT.T, INT.T));
    put(venv, "print_real", new FUNCTION(UNIT.T, REAL.T));
    put(venv, "print_unit", new FUNCTION(UNIT.T, UNIT.T));
    put(venv, "print_bool", new FUNCTION(UNIT.T, BOOL.T));
    put(venv, "round",      new FUNCTION(INT.T, REAL.T));
    put(venv, "ceil",       new FUNCTION(INT.T, REAL.T));
    put(venv, "floor",      new FUNCTION(INT.T, REAL.T));
    put(venv, "real",       new FUNCTION(REAL.T, INT.T));
    put(venv, "not",        new FUNCTION(BOOL.T, BOOL.T));
  }

  @Override
  public String toString() {
    return "Env{" +
           "tenv=" + tenv +
           ", venv=" + venv +
           '}';
  }

  private static <E> void put(Table<E> table, String name, E value) {
    table.put(name.intern(), value);
  }

}

Add the 'not' function to the initial environment


/*
 * Copyright 2015 Open Networking Laboratory
 *
 * 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.onosproject.net;

/**
 * Represents type of wavelength grid.
 *
 * <p>
 * See Open Networking Foundation "Optical Transport Protocol Extensions Version 1.0".
 * </p>
 */
public enum GridType {
    RES,                // ??
    DWDM,               // Dense Wavelength Division Multiplexing
    CWDM,               // Coarse WDM
    FLEX                // Flex Grid
}

/*
 * Copyright 2015 Open Networking Laboratory
 *
 * 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.onosproject.net;

/**
 * Represents type of wavelength grid.
 *
 * <p>
 * See Open Networking Foundation "Optical Transport Protocol Extensions Version 1.0".
 * </p>
 */
public enum GridType {
    DWDM,               // Dense Wavelength Division Multiplexing
    CWDM,               // Coarse WDM
    FLEX                // Flex Grid
}

Remove RES definition as potential use case is unknow right now

Change-Id: I6d7d44598755632dbe5d069bc0de3e740e7ccc17


package com.codecrafters.server;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.time.Instant;
import java.util.List;
import java.util.Optional;

/**
 * @author Fabian Dietenberger
 */
@RestController()
@RequestMapping("todos")
public class TodoItemRestController {

    private final TodoItemRepository repository;

    @Autowired
    public TodoItemRestController(final TodoItemRepository repository) {
        this.repository = repository;
    }

    @RequestMapping(method = RequestMethod.GET)
    public ResponseEntity<List<TodoItem>> getTodoItems(@RequestParam(value = "text", required = false) String containingText) {
        final List<TodoItem> items = repository.findByTextContainingIgnoreCase(Optional.ofNullable(containingText).orElse(""));
        return ResponseEntity.ok()
                .lastModified(Instant.now().toEpochMilli()) // if we dont return this timestamp the browser could cache the request
                .body(items);
    }

    @RequestMapping(method = RequestMethod.PUT)
    public ResponseEntity<String> addTodoItem(@RequestBody final TodoItem item) {
        repository.save(item);
        return new ResponseEntity<>(HttpStatus.OK);
    }

    @RequestMapping(method = RequestMethod.DELETE)
    public ResponseEntity<String> removeTodoItem(@RequestBody final TodoItem item) {
        repository.delete(item);
        return new ResponseEntity<>(HttpStatus.OK);
    }
}

package com.codecrafters.server;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.CacheControl;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Optional;

/**
 * @author Fabian Dietenberger
 */
@RestController()
@RequestMapping("todos")
public class TodoItemRestController {

    private final TodoItemRepository repository;

    @Autowired
    public TodoItemRestController(final TodoItemRepository repository) {
        this.repository = repository;
    }

    @RequestMapping(method = RequestMethod.GET)
    public ResponseEntity<List<TodoItem>> getTodoItems(@RequestParam(value = "text", required = false) String containingText) {
        final List<TodoItem> items = repository.findByTextContainingIgnoreCase(Optional.ofNullable(containingText).orElse(""));
        return ResponseEntity.ok()
                .cacheControl(CacheControl.noCache()) // if we dont return this timestamp the browser could cache the request
                .body(items);
    }

    @RequestMapping(method = RequestMethod.PUT)
    public ResponseEntity<String> addTodoItem(@RequestBody final TodoItem item) {
        repository.save(item);
        return new ResponseEntity<>(HttpStatus.OK);
    }

    @RequestMapping(method = RequestMethod.DELETE)
    public ResponseEntity<String> removeTodoItem(@RequestBody final TodoItem item) {
        repository.delete(item);
        return new ResponseEntity<>(HttpStatus.OK);
    }
}

Return no-cache instead of last-modified for better performance


/*
 * Copyright 2015 Benedikt Ritter
 *
 * 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.github.britter.beanvalidators.strings;

import static java.lang.annotation.ElementType.ANNOTATION_TYPE;
import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.RetentionPolicy.RUNTIME;

import javax.validation.Constraint;
import javax.validation.Payload;
import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;

@Target({METHOD, FIELD, ANNOTATION_TYPE})
@Retention(RUNTIME)
@Constraint(validatedBy = ISBNConstraintValidator.class)
@Documented
public @interface ISBN {

    ISBNType type() default ISBNType.ALL;

    String message() default "{com.github.britter.beanvalidators.strings.ISBN.message}";

    Class<?>[] groups() default {};

    Class<? extends Payload>[] payload() default {};
}

Fix checkstyle issue: File does not end with a newline


package game;

import model.Grid;

/**
 * Created by kuro on 10/03/16.
 */
public class Game {

    private Grid grid;
    private boolean gameLooping;
    private long now, last;

    public Game()
    {
        //Setup game environement here
        grid = new Grid();

        gameLooping = true;
    }

    /**
     * Launch the main loop of the game
     */
    public void loop()
    {
        while(gameLooping)
        {
            now = System.nanoTime();
            System.out.println(now - last);
            update();
            last = now;
        }
    }

    private void update()
    {
    }

    public Grid getGrid() {
        return grid;
    }
}

package game;

import model.Grid;

/**
 * Created by kuro on 10/03/16.
 */
public class Game {

    private Grid grid;
    private Player player0;
    private boolean gameLooping;
    private long now, last;

    public Game()
    {
        //Setup game environement here
        grid = new Grid();
        gameLooping = true;
        player0 = new Player();
    }

    /**
     * Launch the main loop of the game
     */
    public void loop()
    {
        while(gameLooping)
        {
            now = System.nanoTime();
            System.out.println(now - last);
            update();
            last = now;
        }
    }

    private void update()
    {
    }

    public Grid getGrid() {
        return grid;
    }
}

Add player object to game

Add player object to game


package org.apache.maven.lifecycle.statemgmt;

import org.apache.maven.execution.MavenSession;
import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.apache.maven.project.MavenProject;

/**
 * Setup a new project instance for the forked executions to use.
 *
 * @author jdcasey
 *
 */
public class StartForkedExecutionMojo
    extends AbstractMojo
{

    private MavenProject project;

    private MavenSession session;

    private int forkId = -1;

    public void execute()
        throws MojoExecutionException, MojoFailureException
    {
        getLog().info( "Starting forked execution [fork id: " + forkId + "]" );

        if ( project != null )
        {
            session.addForkedProject( (MavenProject) project.clone() );
        }
    }

}

package org.apache.maven.lifecycle.statemgmt;

import org.apache.maven.execution.MavenSession;
import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.apache.maven.project.MavenProject;

/**
 * Setup a new project instance for the forked executions to use.
 *
 * @author jdcasey
 *
 */
public class StartForkedExecutionMojo
    extends AbstractMojo
{

    private MavenProject project;

    private MavenSession session;

    private int forkId = -1;

    public void execute()
        throws MojoExecutionException, MojoFailureException
    {
        getLog().info( "Starting forked execution [fork id: " + forkId + "]" );

        if ( project != null )
        {
            try
            {
                session.addForkedProject( (MavenProject) project.clone() );
            }
            catch ( CloneNotSupportedException e )
            {
                throw new IllegalStateException( "MavenProject instance of class " + project.getClass().getName() +
                    " does not support clone " );
            }
        }
    }

}

[MNG-3400] Implement clone properly following Effective Java' book considerations

git-svn-id: 2c527eb49caa05e19d6b2be874bf74fa9d7ea670@627935 13f79535-47bb-0310-9956-ffa450edef68


package io.mandrel.common.export;

import io.mandrel.common.content.FieldExtractor;
import io.mandrel.common.store.Document;

import java.io.IOException;
import java.io.Writer;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import lombok.Data;

import org.springframework.util.CollectionUtils;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;

@Data
public class JsonExporter implements Exporter {

	private static final long serialVersionUID = -410119107553820985L;

	@Override
	public void export(Stream<Document> documents, List<FieldExtractor> fields, Writer writer) throws IOException {
		ObjectMapper mapper = new ObjectMapper();

		ArrayNode arrayNode = mapper.createArrayNode();

		List<String> headers = fields.stream().map(field -> field.getName()).collect(Collectors.toList());

		documents.forEach(doc -> {
			ObjectNode rootNode = arrayNode.objectNode();
			for (String header : headers) {
				List<? extends Object> values = doc.get(header);
				if (!CollectionUtils.isEmpty(values)) {
					rootNode.putPOJO(header, values);
				}
			}
		});
	}

	@Override
	public String contentType() {
		return "application/json";
	}
}

package io.mandrel.common.export;

import io.mandrel.common.content.FieldExtractor;
import io.mandrel.common.store.Document;

import java.io.IOException;
import java.io.Writer;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import lombok.Data;

import org.springframework.util.CollectionUtils;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;

@Data
public class JsonExporter implements Exporter {

	private static final long serialVersionUID = -410119107553820985L;

	@Override
	public void export(Stream<Document> documents, List<FieldExtractor> fields, Writer writer) throws IOException {
		ObjectMapper mapper = new ObjectMapper();

		ArrayNode arrayNode = mapper.createArrayNode();

		List<String> headers = fields.stream().map(field -> field.getName()).collect(Collectors.toList());

		documents.forEach(doc -> {
			ObjectNode rootNode = arrayNode.objectNode();
			for (String header : headers) {
				List<? extends Object> values = doc.get(header);
				if (!CollectionUtils.isEmpty(values)) {
					rootNode.putPOJO(header, values);
				}
			}
		});

		mapper.writeValue(writer, arrayNode);
	}

	@Override
	public String contentType() {
		return "application/json";
	}
}

Write data in dedicated writer

Write data in dedicated writer


package org.sagebionetworks.bridge.crypto;

import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.jasypt.encryption.StringEncryptor;
import org.jasypt.encryption.pbe.StandardPBEStringEncryptor;
import org.jasypt.salt.RandomSaltGenerator;

public class BridgeEncryptor implements StringEncryptor {

    private final StringEncryptor encryptor;

    public BridgeEncryptor(String password) {
        StandardPBEStringEncryptor encryptor = new StandardPBEStringEncryptor();
        encryptor.setProvider(new BouncyCastleProvider());
        encryptor.setAlgorithm("PBEWITHSHAAND256BITAES-CBC-BC");
        encryptor.setPassword(password);
        encryptor.setSaltGenerator(new RandomSaltGenerator());
        this.encryptor = encryptor;
    }

    public String encrypt(String string) {
        return encryptor.encrypt(string);
    }

    public String decrypt(String string) {
        return encryptor.decrypt(string);
    }
}

package org.sagebionetworks.bridge.crypto;

import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.jasypt.encryption.StringEncryptor;
import org.jasypt.encryption.pbe.StandardPBEStringEncryptor;
import org.jasypt.salt.RandomSaltGenerator;

public class BridgeEncryptor implements StringEncryptor {

    private final StringEncryptor encryptor;

    public BridgeEncryptor(String password) {
        StandardPBEStringEncryptor encryptor = new StandardPBEStringEncryptor();
        encryptor.setProvider(new BouncyCastleProvider());
        encryptor.setAlgorithm("PBEWITHSHA256AND256BITAES-CBC-BC");
        encryptor.setPassword(password);
        encryptor.setSaltGenerator(new RandomSaltGenerator());
        this.encryptor = encryptor;
    }

    public String encrypt(String string) {
        return encryptor.encrypt(string);
    }

    public String decrypt(String string) {
        return encryptor.decrypt(string);
    }
}

Use SHA-256 for the encryption.

Use SHA-256 for the encryption.


package net.sf.jabref;

import static org.junit.Assert.assertEquals;

import java.io.File;

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

public class JabRefPreferencesTest {

    private JabRefPreferences prefs;

    private JabRefPreferences backup;

    @Before
    public void setUp() {
        prefs = JabRefPreferences.getInstance();
        backup = prefs;
    }

    @Test
    public void testPreferencesImport() throws JabRefException {
        // the primary sort field has been changed to "editor" in this case
        File importFile = new File("src/test/resources/net/sf/jabref/customPreferences.xml");

        prefs.importPreferences(importFile.getAbsolutePath());

        String expected = "editor";
        String actual = prefs.get(JabRefPreferences.SAVE_PRIMARY_SORT_FIELD);

        assertEquals(expected, actual);
    }

    @After
    public void tearDown() {
        //clean up preferences to default state
        prefs.overwritePreferences(backup);
    }

}

package net.sf.jabref;

import static org.junit.Assert.assertEquals;

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

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

public class JabRefPreferencesTest {

    private JabRefPreferences prefs;

    private JabRefPreferences backup;

    @Before
    public void setUp() {
        prefs = JabRefPreferences.getInstance();
        backup = prefs;
    }

    @Test
    public void testPreferencesImport() throws JabRefException {
        // the primary sort field has been changed to "editor" in this case
        File importFile = new File("src/test/resources/net/sf/jabref/customPreferences.xml");

        prefs.importPreferences(importFile.getAbsolutePath());

        String expected = "editor";
        String actual = prefs.get(JabRefPreferences.SAVE_PRIMARY_SORT_FIELD);

        assertEquals(expected, actual);
    }

    @Test
    public void getDefaultEncodingReturnsPreviouslyStoredEncoding() {
        prefs.setDefaultEncoding(StandardCharsets.UTF_16BE);
        assertEquals(StandardCharsets.UTF_16BE, prefs.getDefaultEncoding());
    }

    @After
    public void tearDown() {
        //clean up preferences to default state
        prefs.overwritePreferences(backup);
    }

}

Add test for getting/setting default encoding in preferences


package edu.deanza.calendar;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

import com.facebook.AccessToken;
import com.facebook.FacebookSdk;
import com.facebook.GraphRequest;
import com.facebook.GraphResponse;
import com.facebook.HttpMethod;
import com.facebook.appevents.AppEventsLogger;

import edu.deanza.R;

public class SearchActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_search);

        //track analytics using FB--can remove feature later
        FacebookSdk.sdkInitialize(getApplicationContext());
        AppEventsLogger.activateApp(this);

    }

    private void FacebookStalking()
    {
        long [] facebookGroups = {885940821502890L, //De Anza DECA Club
                219645201389350L, //VIDA: Vasconcellos Institute for Democracy In Action
                2236277819L, //De Anza College
        };
        long [] facebookPages = {265047173570399L, //ICC
                192472534143760L //DASB
        };
    }

    private void grabFacebookPage(int id)
    {
        /* make the API call */
        new GraphRequest(
                AccessToken.getCurrentAccessToken(),
                "/" + id + "/events",
                null,
                HttpMethod.GET,
                new GraphRequest.Callback() {
                    public void onCompleted(GraphResponse response) {
                        /* handle the result */
                    }
                }
        ).executeAsync();
    }
}

package edu.deanza.calendar;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

import edu.deanza.R;

public class SearchActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_search);

    }

}

Remove non-MVP Graph API calls

Remove non-MVP Graph API calls


package com.rejasupotaro.octodroid;

import com.google.gson.Gson;

public class GsonProvider {
    private static Gson gson = new Gson();

    public static void set(Gson gson) {
        GsonProvider.gson = gson;
    }

    public static Gson get() {
        return gson;
    }
}

package com.rejasupotaro.octodroid;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

public class GsonProvider {
    private static Gson gson = new GsonBuilder().setPrettyPrinting().create();

    public static void set(Gson gson) {
        GsonProvider.gson = gson;
    }

    public static Gson get() {
        return gson;
    }
}

Enable to print formatted json

Enable to print formatted json


package foam.lib.json;

import foam.lib.parse.*;

public class FObjectParser extends ProxyParser {
  public FObjectParser() {
    super(new Seq1(7,
                   new Whitespace(),
                   new Literal("{"),
                   new Whitespace(),
                   new KeyParser("class"),
                   new Whitespace(),
                   new Literal(":"),
                   new Whitespace(),
                   new Parser() {
        private Parser delegate = new StringParser();
        public PStream parse(PStream ps, ParserContext x) {
          ps = delegate.parse(ps, x);
          if ( ps == null ) return null;

          Class c;

          try {
            c = Class.forName(ps.value().toString());
          } catch(ClassNotFoundException e) {
            throw new RuntimeException(e);
          }

          ParserContext subx = x.sub();
          try {
            subx.set("obj", c.newInstance());
          } catch(InstantiationException e) {
            throw new RuntimeException(e);
          } catch(IllegalAccessException e) {
            throw new RuntimeException(e);
          }

          System.out.println("Parsing: " + c.getName());
          ps = ModelParserFactory.getInstance(c).parse(ps, subx);

          if ( ps != null ) {
            return ps.setValue(subx.get("obj"));
          }
          return null;
        }
      },
                   new Whitespace(),
                   new Literal("}")));
  }
}

package foam.lib.json;

import foam.lib.parse.*;

public class FObjectParser extends ProxyParser {
  public FObjectParser() {
    super(new Seq1(7,
                   new Whitespace(),
                   new Literal("{"),
                   new Whitespace(),
                   new KeyParser("class"),
                   new Whitespace(),
                   new Literal(":"),
                   new Whitespace(),
                   new Parser() {
        private Parser delegate = new StringParser();
        public PStream parse(PStream ps, ParserContext x) {
          ps = delegate.parse(ps, x);
          if ( ps == null ) return null;

          Class c;

          try {
            c = Class.forName(ps.value().toString());
          } catch(ClassNotFoundException e) {
            throw new RuntimeException(e);
          }

          ParserContext subx = x.sub();
          try {
            subx.set("obj", c.newInstance());
          } catch(InstantiationException e) {
            throw new RuntimeException(e);
          } catch(IllegalAccessException e) {
            throw new RuntimeException(e);
          }

          ps = ModelParserFactory.getInstance(c).parse(ps, subx);

          if ( ps != null ) {
            return ps.setValue(subx.get("obj"));
          }
          return null;
        }
      },
                   new Whitespace(),
                   new Literal("}")));
  }
}

Remove logging statment used for debugging.


package com.kryptnostic.api.v1.client;

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

import com.google.common.hash.HashFunction;
import com.google.common.hash.Hashing;
import com.google.common.io.Files;
import com.kryptnostic.kodex.v1.storage.DataStore;

/**
 * A simple implementation of the client datastore. The keys are used to generate filenames.
 *
 * @author Nick Hewitt <nick@kryptnostic.com>
 *
 */
public class FileStore implements DataStore {
    private final File rootDirectory;
    private static HashFunction hf = Hashing.murmur3_128();

    public FileStore(String name) {
        this.rootDirectory = new File(System.getProperty("user.home"), name);
        this.rootDirectory.mkdir();
    }

    @Override
    public byte[] get(byte[] key) throws IOException {
        File keyFile = keyToFile(key);
        if (keyFile.isFile()) {
            byte[] data = Files.toByteArray(keyFile);
            return data;
        }
        return null;
    }

    @Override
    public void put(byte[] key, byte[] value) throws IOException {
        File keyFile = keyToFile(key);
        Files.write(value, keyFile);
    }

    private File keyToFile(byte[] key) {
        Long longEncodedKey = hf.hashBytes(key).asLong();
        return new File(rootDirectory, longEncodedKey.toString());
    }

}

package com.kryptnostic.api.v1.client;

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

import org.apache.commons.codec.binary.Hex;

import com.google.common.hash.HashFunction;
import com.google.common.hash.Hashing;
import com.google.common.io.Files;
import com.kryptnostic.kodex.v1.storage.DataStore;

/**
 * A simple implementation of the client datastore. The keys are used to generate filenames.
 *
 * @author Nick Hewitt <nick@kryptnostic.com>
 *
 */
public class FileStore implements DataStore {
    private final File rootDirectory;

    public FileStore(String name) {
        this.rootDirectory = new File(".kryptnostic", name);
        this.rootDirectory.mkdir();
    }

    @Override
    public byte[] get(byte[] key) throws IOException {
        File keyFile = keyToFile(key);
        if (keyFile.isFile()) {
            byte[] data = Files.toByteArray(keyFile);
            return data;
        }
        return null;
    }

    @Override
    public void put(byte[] key, byte[] value) throws IOException {
        File keyFile = keyToFile(key);
        Files.write(value, keyFile);
    }

    private File keyToFile(byte[] key) {
        return new File(rootDirectory, Hex.encodeHexString( key ) );
    }
}

Switch to hex encoding for key values

Switch to hex encoding for key values


/*
 * Kurento Android Media: Android Media Library based on FFmpeg.
 * Copyright (C) 2011  Tikal Technologies
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License version 3
 * as published by the Free Software Foundation.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package com.kurento.kas.media.rx;

/**
 *
 * @author mparis
 *
 */
public interface AudioRx {

	public void putAudioSamplesRx(byte[] audio, int length);

}

/*
 * Kurento Android Media: Android Media Library based on FFmpeg.
 * Copyright (C) 2011  Tikal Technologies
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License version 3
 * as published by the Free Software Foundation.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package com.kurento.kas.media.rx;

/**
 *
 * @author mparis
 *
 */
public interface AudioRx {

	public void putAudioSamplesRx(byte[] audio, int length, int nFrame);

}

Add nFrame parameter in putAudioSamplesRx method.


/*
 * Copyright 2015, Yahoo Inc.
 * Copyrights licensed under the Apache 2.0 License.
 * See the accompanying LICENSE file for terms.
 */
package com.yahoo.squidb.processor.data;

import com.yahoo.aptutils.model.DeclaredTypeName;

/**
 * Tuple class to hold logged error info, to be written by the
 * {@link com.yahoo.squidb.processor.plugins.defaults.ErrorLoggingPlugin}.
 */
public final class ErrorInfo {

    /**
     * The class on which to log the error
     */
    public final DeclaredTypeName errorClass;

    /**
     * The specific element on which to log the error (or null/empty to log on the class)
     */
    public final String element;

    /**
     * The error message to log
     */
    public final String message;

    public ErrorInfo(DeclaredTypeName errorClass, String element, String message) {
        this.errorClass = errorClass;
        this.element = element;
        this.message = message;
    }
}

/*
 * Copyright 2015, Yahoo Inc.
 * Copyrights licensed under the Apache 2.0 License.
 * See the accompanying LICENSE file for terms.
 */
package com.yahoo.squidb.processor.data;

import com.yahoo.aptutils.model.DeclaredTypeName;

/**
 * Tuple class to hold logged error info, to be written by the
 * {@link com.yahoo.squidb.processor.plugins.defaults.ErrorLoggingPlugin}.
 */
public final class ErrorInfo {

    /**
     * The class on which to log the error
     */
    public final DeclaredTypeName errorClass;

    /**
     * The specific element on which to log the error (or null/empty to log on the class)
     */
    public final String element;

    /**
     * The error message to log
     */
    public final String message;

    ErrorInfo(DeclaredTypeName errorClass, String element, String message) {
        this.errorClass = errorClass;
        this.element = element;
        this.message = message;
    }
}

Make Error info constructor package private


/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package tw.edu.npu.mis;

/**
 * The model class of the calculator application.
 */
public class Calculator {

    /**
     * The available operators of the calculator.
     */
    public enum Operator {
        CLEAR,       // C
        CLEAR_ENTRY, // CE
        BACKSPACE,   // ⌫
        EQUAL,       // =
        PLUS,        // +
        MINUS,       // -
        TIMES,       // ×
        OVER,        // ⁄
        PLUS_MINUS,  // ±
        RECIPROCAL,  // 1/x
        PERCENT,     // %
        SQRT,        // √
        MEM_CLEAR,   // MC
        MEM_SET,     // MS
        MEM_PLUS,    // M+
        MEM_MINUS,   // M-
        MEM_RECALL   // MR
    }

    public void appendDigit(int digit) {
        // TODO code application logic here
    }

    public void appendDot() {
        // TODO code application logic here
    }

    public void performOperation(Operator operator) {
        // TODO code application logic here
    }

    public String getDisplay() {
        // TODO code application logic here
        return null;
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // TODO code application logic here
    }

}

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package tw.edu.npu.mis;

/**
 * The model class of the calculator application.
 */
public class Calculator {

    /**
     * The available operators of the calculator.
     */
    public enum Operator {
        EQUAL,       // =
        PLUS,        // +
        MINUS,       // -
        TIMES,       // ×
        OVER,        // ⁄
        PLUS_MINUS,  // ±
        RECIPROCAL,  // 1/x
        PERCENT,     // %
        SQRT,        // √
        BACKSPACE,   // ⌫
        CLEAR,       // C
        CLEAR_ENTRY, // CE
        MEM_SET,     // MS
        MEM_PLUS,    // M+
        MEM_MINUS,   // M-
        MEM_RECALL,  // MR
        MEM_CLEAR    // MC
    }

    public void appendDigit(int digit) {
        // TODO code application logic here
    }

    public void appendDot() {
        // TODO code application logic here
    }

    public void performOperation(Operator operator) {
        // TODO code application logic here
    }

    public String getDisplay() {
        // TODO code application logic here
        return null;
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // TODO code application logic here
    }

}

Revert "Revert "Revert "Reorder operator"""

This reverts commit 78a1b5e8391875e2b0e9e8272104e80ca10f3275.


package net.sf.taverna.t2.component;

import net.sf.taverna.t2.visit.VisitKind;
import net.sf.taverna.t2.visit.Visitor;

public class ComponentHealthCheck extends VisitKind {
	public static final int NO_PROBLEM = 0;
	public static final int OUT_OF_DATE = 10;
	public static final int NON_SHAREABLE = 20;
	public static final int FAILS_PROFILE = 30;

	@SuppressWarnings("rawtypes")
	@Override
	public Class<? extends Visitor> getVisitorClass() {
		return ComponentActivityUpgradeChecker.class;
	}

	private static class Singleton {
		private static ComponentHealthCheck instance = new ComponentHealthCheck();
	}

	public static ComponentHealthCheck getInstance() {
		return Singleton.instance;
	}
}

package net.sf.taverna.t2.component;

import net.sf.taverna.t2.visit.VisitKind;
import net.sf.taverna.t2.visit.Visitor;

public class ComponentHealthCheck extends VisitKind {
	public static final int NO_PROBLEM = 0;
	public static final int OUT_OF_DATE = 10;
	public static final int NON_SHAREABLE = 20;
	public static final int FAILS_PROFILE = 30;

	@Override
	public Class<? extends Visitor<?>> getVisitorClass() {
		return ComponentActivityUpgradeChecker.class;
	}

	private static class Singleton {
		private static ComponentHealthCheck instance = new ComponentHealthCheck();
	}

	public static ComponentHealthCheck getInstance() {
		return Singleton.instance;
	}
}

Reduce number/scope of warning suppressions.
Consolidate node-list manipulation into one place, which in turn is implemented correctly.

git-svn-id: e7a1cf118dbd81641b56f1cead84a0876efec607@16178 bf327186-88b3-11dd-a302-d386e5130c1c


package sfBugsNew;

import java.io.Serializable;

public class Bug1242 {

    public static class Child extends Parent<Something>
    {
        @Override
        public Something getDuplicateValue()
        {
            Something value = super.getDuplicateValue();

            System.err.println("getValue() called.");

            return value;
        }
    }
    public static interface Duplicatable<T extends Duplicatable<T>> extends Cloneable
    {
        T getDuplicate();
    }
    public static class Interim<T extends Interim<T>> implements Duplicatable<T>
    {
        @Override
        public T getDuplicate()
        {
            try
            {
                return (T) clone();
            }
            catch (CloneNotSupportedException cnse)
            {
                return null;
            }
        }
    }
    // Alternative that produces no bug warnings:
    //public class Parent<T extends Duplicatable<T>>
    public static class Parent<T extends Interim<T>>
    {
        private T value;

        public void setValue(T newValue)
        {
            value = newValue;
        }

        public T getDuplicateValue()
        {
            if (value == null)
            {
                return null;
            }
            T duplicate = value.getDuplicate();
            return duplicate;
        }
    }
    public static class Something extends Interim<Something>
    {
        public void doStuff()
        {
            System.err.println("Hello");
        }
    }

}

package sfBugsNew;

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

public class Bug1242 {

    public static class Child extends Parent<Something> {
        @Override
        @DesireNoWarning("BC_UNCONFIRMED_CAST_OF_RETURN_VALUE")
        @NoWarning(value="BC_UNCONFIRMED_CAST_OF_RETURN_VALUE", confidence=Confidence.MEDIUM)
        public Something getDuplicateValue() {
            Something value = super.getDuplicateValue();

            System.err.println("getValue() called.");

            return value;
        }
    }

    public static interface Duplicatable<T extends Duplicatable<T>> extends Cloneable {
        T getDuplicate();
    }

    public static class Interim<T extends Interim<T>> implements Duplicatable<T> {
        @Override
        public T getDuplicate() {
            try {
                return (T) clone();
            } catch (CloneNotSupportedException cnse) {
                return null;
            }
        }
    }

    // Alternative that produces no bug warnings:
    // public class Parent<T extends Duplicatable<T>>
    public static class Parent<T extends Interim<T>> {
        private T value;

        public void setValue(T newValue) {
            value = newValue;
        }

        public T getDuplicateValue() {
            if (value == null) {
                return null;
            }
            T duplicate = value.getDuplicate();
            return duplicate;
        }
    }

    public static class Something extends Interim<Something> {
        public void doStuff() {
            System.err.println("Hello");
        }
    }

}

Add annotations about expected outcomes

Add annotations about expected outcomes


package entityframe.test;

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

import com.darwinsys.entityframe.*;

public class DemoEntityList extends EntityList<Class1> {

	@PersistenceContext(unitName = "ds_demo")
	protected EntityManager entityManager;

	@Override
	public EntityManager getEntityManager() {
		return entityManager;
	}

	public void setEntityManager(EntityManager entityManager) {
		this.entityManager = entityManager;
	}

}

package entityframe.test;

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

import com.darwinsys.entityframe.*;

public class Class1List extends EntityList<Class1> {

	@PersistenceContext(unitName = "ds_demo")
	protected EntityManager entityManager;

	@Override
	public EntityManager getEntityManager() {
		return entityManager;
	}

	public void setEntityManager(EntityManager entityManager) {
		this.entityManager = entityManager;
	}

}

Make things compile again after some file renames.


/*
 * #%L
 * ImageJ server for RESTful access to ImageJ.
 * %%
 * Copyright (C) 2013 - 2016 Board of Regents of the University of
 * Wisconsin-Madison.
 * %%
 * 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.
 * #L%
 */

package net.imagej.server;

import net.imagej.ImageJ;

/**
 * Main class for imagej-server.
 *
 * @author Leon Yang
 */
public class Main {

	public static void main(String[] args) throws Exception {
		final ImageJ ij = new ImageJ();
		final String[] arguments = args == null || args.length == 0 ? new String[] {
			"server", "imagej-server.yml" } : args;
		final ImageJServerApplication app = new ImageJServerApplication(ij
			.context());
		app.run(arguments);
		app.join();
		ij.context().dispose();
	}

}

/*
 * #%L
 * ImageJ server for RESTful access to ImageJ.
 * %%
 * Copyright (C) 2013 - 2016 Board of Regents of the University of
 * Wisconsin-Madison.
 * %%
 * 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.
 * #L%
 */

package net.imagej.server;

import net.imagej.ImageJ;

/**
 * Main class for imagej-server.
 *
 * @author Leon Yang
 */
public class Main {

	public static void main(String[] args) throws Exception {
		final ImageJ ij = new ImageJ();
		ij.ui().setHeadless(true);
		final String[] arguments = args == null || args.length == 0 ? new String[] {
			"server", "imagej-server.yml" } : args;
		final ImageJServerApplication app = new ImageJServerApplication(ij
			.context());
		app.run(arguments);
		app.join();
		ij.context().dispose();
	}

}

Set ImageJ to headless in main method

Set ImageJ to headless in main method


package cellsociety_team05;

public class SegregationSimulation extends Simulation {
	private Grid myGrid;
	private double similar;

	public SegregationSimulation(Setup setup){
		super(setup);
		similar = 0;
	}

	//Need a way to set similarity percentage
	public void setSimilar(double x){
		similar = x;
	}

	@Override
	public void updateState(Cell cell) {
		int sim = 0;
		int tot = 0;
		for(Cell nCell: cell.getNeighbors()){
			++tot;
			if(nCell.myCurrentState == cell.myCurrentState){
				++sim;
			}
		}
		if((double)sim/tot < similar){
			//make cell empty and move it elsewhere
		}
	}

}

package cellsociety_team05;

public class SegregationSimulation extends Simulation {
	private Grid myGrid;
	private double similar;

	public SegregationSimulation(Setup setup){
		super(setup, null);
		similar = 0;
	}

	//Need a way to set similarity percentage
	public void setSimilar(double x){
		similar = x;
	}

	@Override
	public void updateState(Cell cell) {
		int sim = 0;
		int tot = 0;
		for(Cell nCell: cell.getNeighbors()){
			++tot;
			if(nCell.myCurrentState == cell.myCurrentState){
				++sim;
			}
		}
		if((double)sim/tot < similar){
			//make cell empty and move it elsewhere
		}
	}

}

Fix one last thing, good to run

Fix one last thing, good to run


package com.github.arteam.jdbi3;

import com.codahale.metrics.health.HealthCheck;
import io.dropwizard.db.TimeBoundHealthCheck;
import io.dropwizard.util.Duration;
import org.jdbi.v3.core.Handle;
import org.jdbi.v3.core.Jdbi;

import java.util.concurrent.ExecutorService;

/**
 * @author Artem Prigoda
 * @since 28.07.16
 */
public class JdbiHealthCheck extends HealthCheck {

    private final Jdbi jdbi;
    private final String validationQuery;
    private final TimeBoundHealthCheck timeBoundHealthCheck;

    public JdbiHealthCheck(ExecutorService executorService, Duration duration, Jdbi dbi, String validationQuery) {
        this.jdbi = dbi;
        this.validationQuery = validationQuery;
        this.timeBoundHealthCheck = new TimeBoundHealthCheck(executorService, duration);
    }

    @Override
    protected Result check() throws Exception {
        return timeBoundHealthCheck.check(() -> {
            try (Handle handle = jdbi.open()) {
                handle.execute(validationQuery);
                return Result.healthy();
            }
        });
    }
}

package com.github.arteam.jdbi3;

import com.codahale.metrics.health.HealthCheck;
import io.dropwizard.db.TimeBoundHealthCheck;
import io.dropwizard.util.Duration;
import org.jdbi.v3.core.Handle;
import org.jdbi.v3.core.Jdbi;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.ExecutorService;

/**
 * @author Artem Prigoda
 * @since 28.07.16
 */
public class JdbiHealthCheck extends HealthCheck {
    private static final Logger log = LoggerFactory.getLogger(JdbiHealthCheck.class);

    private final Jdbi jdbi;
    private final String validationQuery;
    private final TimeBoundHealthCheck timeBoundHealthCheck;

    public JdbiHealthCheck(ExecutorService executorService, Duration duration, Jdbi dbi, String validationQuery) {
        this.jdbi = dbi;
        this.validationQuery = validationQuery;
        this.timeBoundHealthCheck = new TimeBoundHealthCheck(executorService, duration);
    }

    @Override
    protected Result check() throws Exception {
        return timeBoundHealthCheck.check(() -> {
            try (Handle handle = jdbi.open()) {
                handle.execute(validationQuery);
                return Result.healthy();
            } catch (Exception e) {
                log.error("jDBI Healthcheck failed. validation-query={}", validationQuery, e);
                return Result.unhealthy("Validation query failed");
            }
        });
    }
}

Add error handling and logging to healthcheck


package com.ui;

import com.ui.TelemetryListener;

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

public class DataLabel extends JLabel implements TelemetryListener{
  private String label;
  private String suffix;
  private double data;
  private int maxWidth;
  private void updateText(){
    StringBuilder out = new StringBuilder();
    out.append(label);
    out.append((data >= 0)? " " : "-");
    out.append(String.format("%f", Math.abs(data)));
    out.append(suffix);

    int finalWidth = Math.min(out.length(), maxWidth);
    setText(disp);
  }
  public DataLabel(String prefix, double dat, String units){
    label    = prefix;
    data     = dat;
    suffix   = units;
    maxWidth = Integer.MAX_VALUE;
    updateText();
  }
  public DataLabel(String prefix, String units){
    this(prefix, 0.0, units);
  }
  public DataLabel(String prefix){
    this(prefix, 0.0, "");
  }
  public void setMaxLength(int ml){
    maxWidth = ml;
  }
  public void update(double data){
    this.data = data;
    updateText();
  }
  public void setLabel(String prefix){
    label = prefix;
    updateText();
  }
  public void setUnits(String units){
    suffix = units;
    updateText();
  }
  public double getData(){
    return data;
  }
}

package com.ui;

import com.ui.TelemetryListener;

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

public class DataLabel extends JLabel implements TelemetryListener{
  private String label;
  private String suffix;
  private double data;
  private int maxWidth;
  private void updateText(){
    StringBuilder out = new StringBuilder();
    out.append(label);
    out.append((data >= 0)? " " : "-");
    out.append(String.format("%f", Math.abs(data)));
    out.append(suffix);

    int finalWidth = Math.min(out.length(), maxWidth);
    setText(out.substring(0,finalWidth));
  }
  public DataLabel(String prefix, double dat, String units){
    label    = prefix;
    data     = dat;
    suffix   = units;
    maxWidth = Integer.MAX_VALUE;
    updateText();
  }
  public DataLabel(String prefix, String units){
    this(prefix, 0.0, units);
  }
  public DataLabel(String prefix){
    this(prefix, 0.0, "");
  }
  public void setMaxLength(int ml){
    maxWidth = ml;
  }
  public void update(double data){
    this.data = data;
    updateText();
  }
  public void setLabel(String prefix){
    label = prefix;
    updateText();
  }
  public void setUnits(String units){
    suffix = units;
    updateText();
  }
  public double getData(){
    return data;
  }
}

Fix error in previous commit

Fix error in previous commit


package net.shadowfacts.foodies.recipe;

import cpw.mods.fml.common.registry.GameRegistry;
import net.minecraft.init.Items;
import net.minecraft.item.ItemStack;
import net.shadowfacts.foodies.item.FItems;

/**
 * A helper class for registering recipes.
 * @author shadowfacts
 */
public class FRecipes {
	public static void preInit() {
		GameRegistry.addSmelting(Items.bread, new ItemStack(FItems.toast, 1), 0.2f);
	}

	public static void load() {

	}

	public static void postInit() {

	}
}

package net.shadowfacts.foodies.recipe;

import cpw.mods.fml.common.registry.GameRegistry;
import net.minecraft.init.Items;
import net.minecraft.item.ItemStack;
import net.shadowfacts.foodies.item.FItems;

/**
 * A helper class for registering recipes.
 * @author shadowfacts
 */
public class FRecipes {
	public static void preInit() {
		// Shapeless
		GameRegistry.addShapelessRecipe(new ItemStack(FItems.hamburger), new ItemStack(FItems.toast), new ItemStack(FItems.beefPattie), new ItemStack(FItems.toast));
		GameRegistry.addShapelessRecipe(new ItemStack(FItems.cheeseburger), new ItemStack(FItems.hamburger), new ItemStack(FItems.cheese));

		// Shaped

		registerSmelting();
	}

	private static void registerSmelting() {
		// Smelting
		GameRegistry.addSmelting(Items.bread, new ItemStack(FItems.toast), 0.2f);
		GameRegistry.addSmelting(Items.cooked_beef, new ItemStack(FItems.beefPattie), 0.3f);
	}

	public static void load() {

	}

	public static void postInit() {

	}
}

Add recipes for new things

Add recipes for new things