/*++

NASM Assembly Language Plugin
Copyright (c) 2017-2018 Aidan Khoury. All rights reserved.

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

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.nasmlanguage;

import com.intellij.openapi.fileTypes.*;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.vfs.VirtualFile;
import org.jetbrains.annotations.NotNull;

public class NASMSyntaxHighlighterFactory extends SyntaxHighlighterFactory {
    @NotNull
    @Override
    public SyntaxHighlighter getSyntaxHighlighter(Project project, VirtualFile virtualFile) {
        return new NASMSyntaxHighlighter();
    }
}

/*++

NASM Assembly Language Plugin
Copyright (c) 2017-2018 Aidan Khoury

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

--*/

package com.nasmlanguage;

import com.intellij.openapi.fileTypes.*;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.vfs.VirtualFile;
import org.jetbrains.annotations.NotNull;

public class NASMSyntaxHighlighterFactory extends SyntaxHighlighterFactory {
    @NotNull
    @Override
    public SyntaxHighlighter getSyntaxHighlighter(Project project, VirtualFile virtualFile) {
        return new NASMSyntaxHighlighter();
    }
}

Update copyright notice with MIT license


package fi.helsinki.cs.tmc.cli.io;

import static org.junit.Assert.assertEquals;

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

public class ColorTest {

    private Boolean noColor;

    @Before
    public void setup() {
        this.noColor = EnvironmentUtil.isWindows();
    }

    @Test
    public void colorsWork() {
        String string = Color.colorString("foobar", Color.AnsiColor.ANSI_BLACK);
        if (!noColor) {
            assertEquals("\u001B[30mfoobar\u001B[0m", string);
        } else {
            assertEquals("foobar", string);
        }
    }

    @Test
    public void noColorWorks() {
        String string = Color.colorString("foobar", Color.AnsiColor.ANSI_NONE);
        assertEquals("foobar", string);
    }
}

package fi.helsinki.cs.tmc.cli.io;

import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.when;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;

@RunWith(PowerMockRunner.class)
@PrepareForTest(EnvironmentUtil.class)
public class ColorTest {

    @Before
    public void setup() {
        PowerMockito.mockStatic(EnvironmentUtil.class);
    }

    @Test
    public void colorsWorkInNonWindows() {
        when(EnvironmentUtil.isWindows()).thenReturn(false);
        String string = Color.colorString("foobar", Color.AnsiColor.ANSI_BLACK);
        assertEquals("\u001B[30mfoobar\u001B[0m", string);
    }

    @Test
    public void colorsWorkInWindows() {
        when(EnvironmentUtil.isWindows()).thenReturn(true);
        String string = Color.colorString("foobar", Color.AnsiColor.ANSI_BLACK);
        assertEquals("foobar", string);
    }

    @Test
    public void noColorWorks() {
        String string = Color.colorString("foobar", Color.AnsiColor.ANSI_NONE);
        assertEquals("foobar", string);
    }
}

Make the color tests OS agnostic.


Format code via `./gradlew spotlessApply`


package org.monospark.actioncontrol.category;

import java.io.File;
import java.io.IOException;
import java.nio.file.Path;
import java.util.Collections;
import java.util.Set;
import java.util.stream.Collectors;

import org.monospark.actioncontrol.config.ConfigParseException;
import org.monospark.actioncontrol.config.ConfigParser;
import org.spongepowered.api.entity.living.player.Player;

public final class CategoryRegistry {

	private static final String PERMISSION_BASE = "actioncontrol.category.";

	private Set<Category> allCategories;

	CategoryRegistry() {}

	public void loadCategories(Path path) throws ConfigParseException {
		Path groupsFile = path.resolve("categories.json");
		File file = groupsFile.toFile();
		try {
			if(!file.exists()) {
				path.toFile().mkdir();
				file.createNewFile();
				this.allCategories = Collections.emptySet();
			} else {
				this.allCategories = ConfigParser.parseConfig(groupsFile);
			}
		} catch (IOException e) {
			throw new ConfigParseException(e);
		}
	}

	public Set<Category> getCategories(Player p) {
		return allCategories.stream()
				.filter(c -> /* p.hasPermission(PERMISSION_BASE + c.getName()) */ true)
				.collect(Collectors.toSet());
	}
}

package org.monospark.actioncontrol.category;

import java.io.File;
import java.io.IOException;
import java.nio.file.Path;
import java.util.Collections;
import java.util.Set;
import java.util.stream.Collectors;

import org.monospark.actioncontrol.config.ConfigParseException;
import org.monospark.actioncontrol.config.ConfigParser;
import org.spongepowered.api.entity.living.player.Player;

public final class CategoryRegistry {

	private static final String PERMISSION_BASE = "actioncontrol.category.";

	private Set<Category> allCategories;

	CategoryRegistry() {}

	public void loadCategories(Path path) throws ConfigParseException {
		Path categoriesFile = path.resolve("categories.json");
		File file = categoriesFile.toFile();
		try {
			if(!file.exists()) {
				path.toFile().mkdir();
				file.createNewFile();
				this.allCategories = Collections.emptySet();
			} else {
				this.allCategories = ConfigParser.parseConfig(categoriesFile);
			}
		} catch (IOException e) {
			throw new ConfigParseException(e);
		}
	}

	public Set<Category> getCategories(Player p) {
		return allCategories.stream()
				.filter(c -> /* p.hasPermission(PERMISSION_BASE + c.getName()) */ true)
				.collect(Collectors.toSet());
	}
}

Replace more occurences of "group" with "category"


package info.u_team.u_team_core.intern.init;

import info.u_team.u_team_core.UCoreMod;
import info.u_team.u_team_core.intern.network.*;
import net.minecraft.util.ResourceLocation;
import net.minecraftforge.fml.network.NetworkRegistry;
import net.minecraftforge.fml.network.simple.SimpleChannel;

public class UCoreNetwork {

	public static final String PROTOCOL = "1.15.2-2";

	public static final SimpleChannel NETWORK = NetworkRegistry.newSimpleChannel(new ResourceLocation(UCoreMod.MODID, "network"), () -> PROTOCOL, PROTOCOL::equals, PROTOCOL::equals);

	public static void construct() {
		NETWORK.registerMessage(0, BufferPropertyContainerMessage.class, BufferPropertyContainerMessage::encode, BufferPropertyContainerMessage::decode, BufferPropertyContainerMessage.Handler::handle);
		NETWORK.registerMessage(1, FluidSetAllContainerMessage.class, FluidSetAllContainerMessage::encode, FluidSetAllContainerMessage::decode, FluidSetAllContainerMessage.Handler::handle);
		NETWORK.registerMessage(2, FluidSetSlotContainerMessage.class, FluidSetSlotContainerMessage::encode, FluidSetSlotContainerMessage::decode, FluidSetSlotContainerMessage.Handler::handle);
		NETWORK.registerMessage(3, FluidClickContainerMessage.class, FluidClickContainerMessage::encode, FluidClickContainerMessage::decode, FluidClickContainerMessage.Handler::handle);
	}

}

package info.u_team.u_team_core.intern.init;

import info.u_team.u_team_core.UCoreMod;
import info.u_team.u_team_core.intern.network.*;
import net.minecraft.util.ResourceLocation;
import net.minecraftforge.fml.event.lifecycle.FMLCommonSetupEvent;
import net.minecraftforge.fml.network.NetworkRegistry;
import net.minecraftforge.fml.network.simple.SimpleChannel;

public class UCoreNetwork {

	public static final String PROTOCOL = "1.15.2-2";

	public static final SimpleChannel NETWORK = NetworkRegistry.newSimpleChannel(new ResourceLocation(UCoreMod.MODID, "network"), () -> PROTOCOL, PROTOCOL::equals, PROTOCOL::equals);

	public static void setup(FMLCommonSetupEvent event) {
		NETWORK.registerMessage(0, BufferPropertyContainerMessage.class, BufferPropertyContainerMessage::encode, BufferPropertyContainerMessage::decode, BufferPropertyContainerMessage.Handler::handle);
		NETWORK.registerMessage(1, FluidSetAllContainerMessage.class, FluidSetAllContainerMessage::encode, FluidSetAllContainerMessage::decode, FluidSetAllContainerMessage.Handler::handle);
		NETWORK.registerMessage(2, FluidSetSlotContainerMessage.class, FluidSetSlotContainerMessage::encode, FluidSetSlotContainerMessage::decode, FluidSetSlotContainerMessage.Handler::handle);
		NETWORK.registerMessage(3, FluidClickContainerMessage.class, FluidClickContainerMessage::encode, FluidClickContainerMessage::decode, FluidClickContainerMessage.Handler::handle);
	}

}

Move network registry to common setup event. That is sufficient


package model;

import org.junit.Test;

import static org.junit.Assert.assertNotNull;

/**
 * Tests {@link FileLink FileLink} class.
 */
public class TestFileLink {
    private static final String API_KEY = "XXXXXXXXXXXXXXXXXXXXXXX";
    private static final String HANDLE = "XXXXXXXXXXXXXXXXXXXXX";

    @Test
    public void testInstantiation() {
        FileLink fileLink = new FileLink(API_KEY, HANDLE);
        assertNotNull("Unable to create FileLink", fileLink);
    }
}

package model;

import okhttp3.OkHttpClient;
import okhttp3.ResponseBody;
import org.junit.BeforeClass;
import org.junit.Test;
import util.Networking;
import util.MockInterceptor;

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

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

/**
 * Tests {@link FileLink FileLink} class.
 */
public class TestFileLink {
    private static final String API_KEY = "TEST_API_KEY";
    private static final String HANDLE = "TEST_FILE_HANDLE";

    private static final String DIRECTORY = "/tmp/";
    private static final String CUSTOM_FILENAME = "filestack_test_custom_filename.txt";

    /**
     * Set a custom httpClient for our testing.
     * This custom client has an added interceptor to create mock responses.
     */
    @BeforeClass
    public static void setup() {
        OkHttpClient httpClient = new OkHttpClient.Builder()
                .addInterceptor(new MockInterceptor())
                .build();
        Networking.setHttpClient(httpClient);
    }

    @Test
    public void testInstantiation() {
        FileLink fileLink = new FileLink(API_KEY, HANDLE);
        assertNotNull("Unable to create FileLink", fileLink);
    }

    @Test
    public void testGetContent() throws IOException {
        FileLink fileLink = new FileLink(API_KEY, HANDLE);

        ResponseBody body = fileLink.getContent();
        String text = body.string();
        assertTrue("Unexpected content in response", text.contains("Test content"));
    }

    @Test
    public void testDownload() throws IOException {
        FileLink fileLink = new FileLink(API_KEY, HANDLE);

        File file = fileLink.download(DIRECTORY);
        assertTrue(file.isFile());
    }

    @Test
    public void testDownloadCustomFilename() throws IOException {
        FileLink fileLink = new FileLink(API_KEY, HANDLE);
        File file = fileLink.download(DIRECTORY, CUSTOM_FILENAME);
        assertTrue(file.isFile());
    }

}

Add tests for download() and getContent() methods.


// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
// TODO: Remove this package on Vespa 7
@ExportPackage
package com.yahoo.vespaxmlparser;

import com.yahoo.osgi.annotation.ExportPackage;

// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
// TODO: Remove this package on Vespa 8
@ExportPackage
package com.yahoo.vespaxmlparser;

import com.yahoo.osgi.annotation.ExportPackage;

Move TODO to Vespa 8


package org.metaborg.core.tracing;

import javax.annotation.Nullable;

import org.metaborg.core.source.ISourceLocation;
import org.metaborg.core.source.ISourceRegion;

/**
 * Represents a resolution produced by reference resolution.
 */
public class Resolution {
    /**
     * Area in the source file to highlight as a hyperlink.
     */
    public final ISourceRegion highlight;

    /**
     * Resolution targets. Multiple targets indicate resolution to multiple valid locations.
     */
    public final Iterable<Resolution.Target> targets;

    public Resolution(ISourceRegion highlight, Iterable<Resolution.Target> targets) {
        this.highlight = highlight;
        this.targets = targets;
    }

    public static class Target {
        public final @Nullable String hyperlinkName;
        public final ISourceLocation location;

        public Target(ISourceLocation location) {
            this(null, location);
        }

        public Target(String hyperlinkName, ISourceLocation location) {
            this.hyperlinkName = hyperlinkName == null ? defaultHyperlinkName(location) : hyperlinkName;
            this.location = location;
        }

        private static String defaultHyperlinkName(ISourceLocation location) {
            String fileName = location.resource().getName().getBaseName();
            ISourceRegion region = location.region();
            int row = region.startRow();
            int col = region.startColumn();
            return fileName + ":" + row + ":" + col;
        }
    }
}

package org.metaborg.core.tracing;

import javax.annotation.Nullable;

import org.metaborg.core.source.ISourceLocation;
import org.metaborg.core.source.ISourceRegion;

/**
 * Represents a resolution produced by reference resolution.
 */
public class Resolution {
    /**
     * Area in the source file to highlight as a hyperlink.
     */
    public final ISourceRegion highlight;

    /**
     * Resolution targets. Multiple targets indicate resolution to multiple valid locations.
     */
    public final Iterable<Resolution.Target> targets;

    public Resolution(ISourceRegion highlight, Iterable<Resolution.Target> targets) {
        this.highlight = highlight;
        this.targets = targets;
    }

    public static class Target {
        public final @Nullable String hyperlinkName;
        public final ISourceLocation location;

        public Target(ISourceLocation location) {
            this(null, location);
        }

        public Target(String hyperlinkName, ISourceLocation location) {
            this.hyperlinkName = hyperlinkName == null ? defaultHyperlinkName(location) : hyperlinkName;
            this.location = location;
        }

        private static String defaultHyperlinkName(ISourceLocation location) {
            String fileName = location.resource().getName().getBaseName();
            ISourceRegion region = location.region();
            int row = region.startRow();
            int col = region.startColumn();
            return fileName + ":" + (row+1) + ":" + (col+1);
        }
    }
}

Add 1 to row and column, since the numbers are 0-based and the Eclipse editor shows 1-based


package controller;

import boundary.PlayerApplication;
import model.Move;
import model.PlayerModel;
import model.Point;
import model.Variation;

/**
 * @author Nick Chaput
 */
public class PlayerRemoveCtrl {
  PlayerApplication app;
  PlayerModel model;

  public PlayerRemoveCtrl(PlayerApplication app, PlayerModel model) {
    this.app = app;
    this.model = model;
  }

  public void mouseClicked(Point point) {
    // TODO: generic implementation
    PlayerVariationCtrl pVar = model.variation.createCtrl(app, model);
    if (model.variation != Variation.RELEASE &&
        model.level.currentBoard.grid[point.x][point.y].tile.number != 6) {
      // GO INTO PLAYERMODEL AND REPLACE PLAYERVARIATIONCTRL WITH VARIATION
      // TODO: This is suboptimal, decide whether to change PlayerVariationCtrl.
      // specialMove() to individual methods for each special move
      // TODO: resolve the move
      Move reMove = new Move();
      reMove.expand(model.level.currentBoard, point);
    }
    pVar.remove();
  }
}

package controller;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import boundary.PlayerApplication;
import model.Move;
import model.PlayerModel;
import model.PlayerState;
import model.Point;
import model.Variation;

/**
 * @author Nick Chaput
 */
public class PlayerRemoveCtrl implements ActionListener{
  PlayerApplication app;
  PlayerModel model;

  public PlayerRemoveCtrl(PlayerApplication app, PlayerModel model) {
    this.app = app;
    this.model = model;
  }

  public void startRemove(Point point) {
    // TODO: generic implementation
    PlayerVariationCtrl pVar = model.variation.createCtrl(app, model);
    if (model.variation != Variation.RELEASE &&
        model.level.currentBoard.grid[point.x][point.y].tile.number != 6) {
      // GO INTO PLAYERMODEL AND REPLACE PLAYERVARIATIONCTRL WITH VARIATION
      // TODO: This is suboptimal, decide whether to change PlayerVariationCtrl.
      // specialMove() to individual methods for each special move
      // TODO: resolve the move
      Move reMove = new Move();
      reMove.expand(model.level.currentBoard, point);
    }
    pVar.remove();
  }

  @Override
  public void actionPerformed(ActionEvent arg0) {
	model.playerState = PlayerState.REMOVE;
  }
}

Fix format error in RemoveCtrl


package zero.zd.zquestionnaire;

import java.util.ArrayList;

import zero.zd.zquestionnaire.model.QnA;

/**
 * Helper class for retrieving QnA for different topics.
 * for future feature: choosing diff topics instead of 1 topic
 * Note: temporary implementation
 */
class QnAHelper {

    // TODO: add more QnA, import & export file
    static ArrayList<QnA> getBasicQnA() {
        ArrayList<QnA> qnaList = new ArrayList<>();
        qnaList.add(new QnA("ABC", "ABC"));
        qnaList.add(new QnA("DEF", "DEF"));
        qnaList.add(new QnA("GHI", "GHI"));
        qnaList.add(new QnA("JKL", "JKL"));
        qnaList.add(new QnA("MNO", "MNO"));
        qnaList.add(new QnA("PQR", "PQR"));
        qnaList.add(new QnA("STU", "STU"));
        qnaList.add(new QnA("VWX", "VWX"));
        qnaList.add(new QnA("YZA", "YZA"));
        qnaList.add(new QnA("BCD", "BCD"));

        return qnaList;
    }

}

package zero.zd.zquestionnaire;

import java.util.ArrayList;

import zero.zd.zquestionnaire.model.QnA;

/**
 * Helper class for retrieving QnA for different topics.
 * for future feature: choosing diff topics instead of 1 topic
 * Note: temporary implementation
 */
class QnAHelper {
    private static QnAHelper sInstance;

    private ArrayList<ArrayList<QnA>> mSubjectList;

    public static QnAHelper getInstance() {
        if (sInstance == null)
            sInstance = new QnAHelper();
        return sInstance;
    }

    private QnAHelper() {}

    public ArrayList<ArrayList<QnA>> getSubjectList() {
        // populate subject list
        mSubjectList.add(getBasicQnA());

        return mSubjectList;
    }

    // TODO: add more QnA, import & export file
    private ArrayList<QnA> getBasicQnA() {
        ArrayList<QnA> qnaList = new ArrayList<>();
        qnaList.add(new QnA("ABC", "ABC"));
        qnaList.add(new QnA("DEF", "DEF"));
        qnaList.add(new QnA("GHI", "GHI"));
        qnaList.add(new QnA("JKL", "JKL"));
        qnaList.add(new QnA("MNO", "MNO"));
        qnaList.add(new QnA("PQR", "PQR"));
        qnaList.add(new QnA("STU", "STU"));
        qnaList.add(new QnA("VWX", "VWX"));
        qnaList.add(new QnA("YZA", "YZA"));
        qnaList.add(new QnA("BCD", "BCD"));

        return qnaList;
    }

}

Change Helper to Singleton Class


package com.bitbosh.dropwizardheroku.event.repository;

import java.util.Date;
import java.util.List;

import org.skife.jdbi.v2.sqlobject.Bind;
import org.skife.jdbi.v2.sqlobject.SqlQuery;
import org.skife.jdbi.v2.sqlobject.SqlUpdate;
import org.skife.jdbi.v2.sqlobject.customizers.Mapper;

import com.bitbosh.dropwizardheroku.event.api.Event;

public interface EventDao {
  @SqlUpdate("create table if not exists event (id serial primary key, name varchar(100), location varchar(100), description varchar(100), date date)")
  void createEventDatabaseTable();

  @SqlUpdate("insert into event (name, location, description, date) values (:name, :location, :description, :date)")
  void createEvent(@Bind("name") String name, @Bind("location") String location,
      @Bind("description") String description, @Bind("date") Date date);

  @Mapper(EventMapper.class)
  @SqlQuery("select * from event where name = :name")
  Event getEventByName(@Bind("name") String name);

  @Mapper(EventMapper.class)
  @SqlQuery("select * from event where date > now()")
  List<Event> getEvents();

  @SqlQuery("delete from event where id=:id")
  void deleteEventById(@Bind("id") int id);
}

package com.bitbosh.dropwizardheroku.event.repository;

import java.util.Date;
import java.util.List;

import org.skife.jdbi.v2.sqlobject.Bind;
import org.skife.jdbi.v2.sqlobject.SqlQuery;
import org.skife.jdbi.v2.sqlobject.SqlUpdate;
import org.skife.jdbi.v2.sqlobject.customizers.Mapper;

import com.bitbosh.dropwizardheroku.event.api.Event;

public interface EventDao {
  @SqlUpdate("create table if not exists event (id serial primary key, name varchar(100), location varchar(100), description varchar(100), date date)")
  void createEventDatabaseTable();

  @SqlUpdate("insert into event (name, location, description, date) values (:name, :location, :description, :date)")
  void createEvent(@Bind("name") String name, @Bind("location") String location,
      @Bind("description") String description, @Bind("date") Date date);

  @Mapper(EventMapper.class)
  @SqlQuery("select * from event where name = :name")
  Event getEventByName(@Bind("name") String name);

  @Mapper(EventMapper.class)
  @SqlQuery("select * from event where date > now()")
  List<Event> getEvents();

  @SqlUpdate("delete from event where id=:id")
  void deleteEventById(@Bind("id") int id);
}

Annotate with update instead of query


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

/**
 * Classes that operate on the Gradle model.
 */
package org.gradle.api.model;

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

/**
 * Classes that operate on the Gradle model.
 */
@NonNullApi
package org.gradle.api.model;

import org.gradle.api.NonNullApi;

Add NonNullApi annotation on org.gradle.api.model


package seedu.jimi.logic.commands;

import seedu.jimi.model.task.FloatingTask;

/**
 *
 * @author zexuan
 *
 * Edits an existing task/event in Jimi.
 */
public class EditCommand extends Command{

    public static final String COMMAND_WORD = "add";

    public static final String MESSAGE_USAGE = COMMAND_WORD + ": Edits an existing task/event in Jimi. "
            + "Parameters: NAME p/PHONE e/EMAIL a/ADDRESS  [t/TAG]...\n"
            + "Example: " + COMMAND_WORD
            + " edit 2 by 10th july at 12 pm";

    public static final String MESSAGE_SUCCESS = "New task added: %1$s";
    public static final String MESSAGE_DUPLICATE_TASK = "This task already exists in Jimi";

    private final FloatingTask toAdd;

    @Override
    public CommandResult execute() {
        // TODO Auto-generated method stub
        return null;
    }

}

package seedu.jimi.logic.commands;

import seedu.jimi.model.task.FloatingTask;

/**
 *
 * @author zexuan
 *
 * Edits an existing task/event in Jimi.
 */
public class EditCommand extends Command{

    public static final String COMMAND_WORD = "edit";

    public static final String MESSAGE_USAGE = COMMAND_WORD + ": Edits an existing task/event in Jimi. "
            + "Example: " + COMMAND_WORD
            + "2 by 10th July at 12 pm";

    public static final String MESSAGE_SUCCESS = "New task added: %1$s";
    public static final String MESSAGE_DUPLICATE_TASK = "This task already exists in Jimi";

    private final FloatingTask toEdit;

    @Override
    public CommandResult execute() {
        // TODO Auto-generated method stub
        return null;
    }

}

Refactor minor details for editCommand


/*
 * Copyright (c) 2017 Stephan D. Cote' - All rights reserved.
 *
 * This program and the accompanying materials are made available under the
 * terms of the MIT License which accompanies this distribution, and is
 * available at http://creativecommons.org/licenses/MIT/
 *
 * Contributors:
 *   Stephan D. Cote
 *      - Initial concept and initial implementation
 */
package coyote.commons.network.http;

//import static org.junit.Assert.*;
import static org.junit.Assert.assertNotNull;

import java.io.IOException;

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

/**
 *
 */
public class TestHttpd {

  private static HTTPD server = null;

  /**
   * @throws java.lang.Exception
   */
  @BeforeClass
  public static void setUpBeforeClass() throws Exception {

    server = new TestingServer( 62300 );

    try {
      server.start( HTTPD.SOCKET_READ_TIMEOUT, true );
    } catch ( IOException ioe ) {
      System.err.println( "Couldn't start server:\n" + ioe );
      server.stop();
      server = null;
    }

  }

  /**
   * @throws java.lang.Exception
   */
  @AfterClass
  public static void tearDownAfterClass() throws Exception {
    server.stop();
  }

  @Test
  public void test() {
    assertNotNull( server );
  }

}

/*
 * Copyright (c) 2017 Stephan D. Cote' - All rights reserved.
 *
 * This program and the accompanying materials are made available under the
 * terms of the MIT License which accompanies this distribution, and is
 * available at http://creativecommons.org/licenses/MIT/
 *
 * Contributors:
 *   Stephan D. Cote
 *      - Initial concept and initial implementation
 */
package coyote.commons.network.http;

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

import java.io.IOException;

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

import coyote.commons.NetUtil;

/**
 *
 */
public class TestHttpd {

  private static HTTPD server = null;
  private static int port = 54321;

  /**
   * @throws java.lang.Exception
   */
  @BeforeClass
  public static void setUpBeforeClass() throws Exception {

    port = NetUtil.getNextAvailablePort( port );
    server = new TestingServer( port );

    try {
      server.start( HTTPD.SOCKET_READ_TIMEOUT, true );
    } catch ( IOException ioe ) {
      System.err.println( "Couldn't start server:\n" + ioe );
      server.stop();
      server = null;
    }

  }

  /**
   * @throws java.lang.Exception
   */
  @AfterClass
  public static void tearDownAfterClass() throws Exception {
    server.stop();
  }

  @Test
  public void test() {
    assertNotNull( server );
    assertTrue( port == server.getPort() );
  }

}

Use NetUtil.getNextAvailablePort to get a testing port


package com.beepscore.android.sunshine;

import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.TextView;

//import java.text.DateFormat;
import java.util.ArrayList;
//import java.util.Calendar;
//import java.util.Date;
import java.util.List;

/**
 * A placeholder fragment containing a simple view.
 */
public class MainActivityFragment extends Fragment {

    public MainActivityFragment() {
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View fragmentMainView = inflater.inflate(R.layout.fragment_main, container, false);
        configureList();
        return fragmentMainView;
    }

    private void configureList() {
        List<String> list = new ArrayList<String>;

        list.add("Today - Sunny - 88/63");
        list.add("Tomorrow - Foggy - 70/46");
        list.add("Weds - Cloudy - 72/63");
        list.add("Thurs - Rainy - 64/51");
        list.add("Fri - Foggy - 70/46");
        list.add("Sat - Sunny - 76/68");
    }

}

package com.beepscore.android.sunshine;

import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Adapter;
import android.widget.ArrayAdapter;

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

/**
 * A placeholder fragment containing a simple view.
 */
public class MainActivityFragment extends Fragment {

    public MainActivityFragment() {
    }

    List<String> weekForecast = new ArrayList<String>();

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View fragmentMainView = inflater.inflate(R.layout.fragment_main, container, false);
        configureList();

        // adapter creates views for each list item
        Adapter adapter = new ArrayAdapter<String>(getActivity(),
                R.layout.list_item_forecast,
                R.id.list_item_forecast_textview,
                weekForecast);

        View listView = fragmentMainView.findViewById(R.id.listview_forecast);

        return fragmentMainView;
    }

    private void configureList() {
        weekForecast.add("Today - Sunny - 88/63");
        weekForecast.add("Tomorrow - Foggy - 70/46");
        weekForecast.add("Weds - Cloudy - 72/63");
        weekForecast.add("Thurs - Rainy - 64/51");
        weekForecast.add("Fri - Foggy - 70/46");
        weekForecast.add("Sat - Sunny - 76/68");
    }

}

Add adapter, get listView. TODO: connect them


package us.myles.ViaVersion.api.type.types;

import com.google.common.base.Preconditions;
import io.netty.buffer.ByteBuf;
import us.myles.ViaVersion.api.type.Type;

public class ByteArrayType extends Type<byte[]> {
    public ByteArrayType() {
        super(byte[].class);
    }

    @Override
    public void write(ByteBuf buffer, byte[] object) throws Exception {
        Type.VAR_INT.write(buffer, object.length);
        buffer.writeBytes(object);
    }

    @Override
    public byte[] read(ByteBuf buffer) throws Exception {
        int length = Type.VAR_INT.read(buffer);
        Preconditions.checkArgument(!buffer.isReadable(length), "Length is fewer than readable bytes");
        byte[] array = new byte[length];
        buffer.readBytes(array);
        return array;
    }
}

package us.myles.ViaVersion.api.type.types;

import com.google.common.base.Preconditions;
import io.netty.buffer.ByteBuf;
import us.myles.ViaVersion.api.type.Type;

public class ByteArrayType extends Type<byte[]> {
    public ByteArrayType() {
        super(byte[].class);
    }

    @Override
    public void write(ByteBuf buffer, byte[] object) throws Exception {
        Type.VAR_INT.write(buffer, object.length);
        buffer.writeBytes(object);
    }

    @Override
    public byte[] read(ByteBuf buffer) throws Exception {
        int length = Type.VAR_INT.read(buffer);
        Preconditions.checkArgument(buffer.isReadable(length), "Length is fewer than readable bytes");
        byte[] array = new byte[length];
        buffer.readBytes(array);
        return array;
    }
}

Fix inverted array read check


package pl.grzeslowski.jsupla.server.ents;

import pl.grzeslowski.jsupla.server.SuplaChannel;

public abstract class SuplaConnection<T> {
    private final T t;
    private final SuplaChannel channel;

    public SuplaConnection(final T t, final SuplaChannel channel) {
        // TODO
//        this.request = requireNonNull(request);
//        this.channel = requireNonNull(channel);
        this.t = t;
        this.channel = channel;
    }

    public T value() {
        return t;
    }

    public SuplaChannel getChannel() {
        return channel;
    }

    @Override
    public boolean equals(final Object o) {
        if (this == o) {
            return true;
        }
        if (!(o instanceof SuplaConnection)) {
            return false;
        }

        final SuplaConnection<?> that = (SuplaConnection<?>) o;

        if (!t.equals(that.t)) return false;
        return getChannel().equals(that.getChannel());
    }

    @Override
    public int hashCode() {
        int result = t.hashCode();
        result = 31 * result + getChannel().hashCode();
        return result;
    }

    @Override
    public String toString() {
        return "SuplaConnection{" +
                       "t=" + t +
                       ", channel=" + channel +
                       '}';
    }
}

Comment has incorrect indentation level 8, expected is 0, indentation should be the same level as line 11.


// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.curator.api;

import com.yahoo.path.Path;

import java.time.Duration;

/**
 * A client for a ZooKeeper cluster running inside Vespa. Applications that want to use ZooKeeper can inject this in
 * their code.
 *
 * @author mpolden
 */
public interface VespaCurator {

    /** Create and acquire a re-entrant lock in given path. This blocks until the lock is acquired or timeout elapses. */
    AutoCloseable lock(Path path, Duration timeout);

}

// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.curator.api;

import com.yahoo.concurrent.UncheckedTimeoutException;
import com.yahoo.path.Path;

import java.time.Duration;

/**
 * A client for a ZooKeeper cluster running inside Vespa. Applications that want to use ZooKeeper can inject this in
 * their code.
 *
 * @author mpolden
 */
public interface VespaCurator {

    /** Create and acquire a re-entrant lock in given path. This blocks until the lock is acquired or timeout elapses. */
    AutoCloseable lock(Path path, Duration timeout) throws UncheckedTimeoutException;

}

Document timeout exception may be thrown


package br.com.six2six.fixturefactory.function;

import static junit.framework.Assert.assertNotNull;
import static junit.framework.Assert.assertTrue;

import org.junit.Test;

import br.com.six2six.fixturefactory.function.impl.RegexFunction;

public class RegexFunctionTest {

	@Test
	public void regexString() {
		String pattern = "\\w{8}";
		String value = new RegexFunction(pattern).generateValue();
		assertNotNull("Generated string can not be null", value);
		assertTrue(String.format("Generated string no match with %s", pattern), value.matches(pattern));
	}

	@Test
	public void regexNumber() {
		String pattern = "\\d{3,8}";
		String value = new RegexFunction(pattern).generateValue();
		assertNotNull("Generated number can not be null", value);
		assertTrue(String.format("Generated number no match with %s", pattern), value.matches(pattern));
	}

	@Test
	public void regexPhoneNumber() {
		String pattern = "(\\d{2})-(\\d{4})-(\\d{4})";
		String value = new RegexFunction(pattern).generateValue();
		assertNotNull("Generated phone number can not be null", value);
		assertTrue(String.format("Generated phone number no match with %s", pattern), value.matches(pattern));
	}

}

package br.com.six2six.fixturefactory.function;

import static junit.framework.Assert.assertNotNull;
import static junit.framework.Assert.assertTrue;

import org.junit.Test;

import br.com.six2six.fixturefactory.function.impl.RegexFunction;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;

import java.util.Arrays;

@RunWith(Parameterized.class)
public class RegexFunctionTest {

	@Parameters(name= "{index}: regex {0}={1}")
	public static Iterable<String[]> data() {
		return Arrays.asList(new String[][]{
				{"String", "\\w{8}"},
				{"Number", "\\d{3,8}"},
				{"Phone number", "(\\d{2})-(\\d{4})-(\\d{4})"},
				{"MD5", "[0-9a-f]{32}"}
		});
	}

	private String regexName;
	private String pattern;

	public RegexFunctionTest(String regexName, String pattern) {
		this.regexName = regexName;
		this.pattern = pattern;
	}

	@Test
	public void testAgainstRegex() {
		String value = new RegexFunction(pattern).generateValue();
		assertNotNull(String.format("Generated %s can not be null", regexName), regexName);
		assertTrue(String.format("Generated %s (%s) no match with %s", regexName, value, pattern), value.matches(pattern));
	}

}

Test for character range regex introduced in bfgex 1.1.1


/*
       Licensed to the Apache Software Foundation (ASF) under one
       or more contributor license agreements.  See the NOTICE file
       distributed with this work for additional information
       regarding copyright ownership.  The ASF licenses this file
       to you under the Apache License, Version 2.0 (the
       "License"); you may not use this file except in compliance
       with the License.  You may obtain a copy of the License at

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

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

package __ID__;

import android.app.Activity;
import android.os.Bundle;
import org.apache.cordova.*;

public class __ACTIVITY__ extends DroidGap
{
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        super.loadUrl("file:///android_asset/www/index.html");
    }
}

/*
       Licensed to the Apache Software Foundation (ASF) under one
       or more contributor license agreements.  See the NOTICE file
       distributed with this work for additional information
       regarding copyright ownership.  The ASF licenses this file
       to you under the Apache License, Version 2.0 (the
       "License"); you may not use this file except in compliance
       with the License.  You may obtain a copy of the License at

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

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

package __ID__;

import android.os.Bundle;
import org.apache.cordova.*;

public class __ACTIVITY__ extends DroidGap
{
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        Config.init(this);
        super.loadUrl("file:///android_asset/www/index.html");
    }
}

Move config.xml parsing into its own Config class


package io.github.lexware.bukkit.enderbow;

import org.bukkit.entity.Entity;
import org.bukkit.entity.Projectile;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.entity.EntityShootBowEvent;
import org.bukkit.event.entity.ProjectileHitEvent;
import org.bukkit.metadata.FixedMetadataValue;
import org.bukkit.metadata.MetadataValue;

/**
 * Created by jamie on 09/01/15.
 */
public class EnderBowListener implements Listener {
    private final EnderBowPlugin plugin;

    public EnderBowListener(EnderBowPlugin plugin) {
        this.plugin = plugin;
    }

    @EventHandler
    public void onEntityShootBowEvent(EntityShootBowEvent event) {
        if(event.getBow().getItemMeta().getDisplayName().equals("Ender bow")) {
            event.getProjectile().setMetadata("enderBowData", new FixedMetadataValue(plugin, "enderArrow"));
        }
    }

    @EventHandler
    public void onProjectileHit(ProjectileHitEvent event) {
        if(event.getEntity().hasMetadata("enderBowData")) {
            for(MetadataValue value : event.getEntity().getMetadata("enderBowData")) {
                if(value.asString().equals("enderArrow")) {
                    ((Entity)event.getEntity().getShooter()).teleport(event.getEntity().getLocation());
                }
            }
        }
    }
}

package io.github.lexware.bukkit.enderbow;

import org.bukkit.entity.Entity;
import org.bukkit.entity.Projectile;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.entity.EntityShootBowEvent;
import org.bukkit.event.entity.ProjectileHitEvent;
import org.bukkit.metadata.FixedMetadataValue;
import org.bukkit.metadata.MetadataValue;

/**
 * Created by jamie on 09/01/15.
 */
public class EnderBowListener implements Listener {
    private final EnderBowPlugin plugin;

    public EnderBowListener(EnderBowPlugin plugin) {
        this.plugin = plugin;
    }

    @EventHandler
    public void onEntityShootBowEvent(EntityShootBowEvent event) {
        if(event.getBow().hasItemMeta() && event.getBow().getItemMeta().getDisplayName().equals("Ender bow")) {
            event.getProjectile().setMetadata("enderBowData", new FixedMetadataValue(plugin, "enderArrow"));
        }
    }

    @EventHandler
    public void onProjectileHit(ProjectileHitEvent event) {
        if(event.getEntity().hasMetadata("enderBowData")) {
            for(MetadataValue value : event.getEntity().getMetadata("enderBowData")) {
                if(value.asString().equals("enderArrow")) {
                    ((Entity)event.getEntity().getShooter()).teleport(event.getEntity().getLocation());
                }
            }
        }
    }
}

Fix NPE with normal bows.


package com.xdd;

import org.junit.runners.BlockJUnit4ClassRunner;
import org.junit.runners.model.InitializationError;

public class SpecRunner extends BlockJUnit4ClassRunner {

    public SpecRunner(Class<?> klass) throws InitializationError {
        super(klass);
    }
}

package com.xdd;

import org.junit.runner.Description;
import org.junit.runner.Runner;
import org.junit.runner.notification.RunNotifier;

public class SpecRunner extends Runner {

    private Class testClass;

    public SpecRunner(Class testClass) {
        this.testClass = testClass;
    }

    @Override
    public Description getDescription() {
        return Description.createSuiteDescription(testClass);
    }

    @Override
    public void run(RunNotifier notifier) {

    }
}

Move SpecRunnner to extend Runner


package org.edx.mobile.view;

import android.os.Bundle;
import android.webkit.WebView;

import org.edx.mobile.R;
import org.edx.mobile.base.FindCoursesBaseActivity;
import org.edx.mobile.util.Config;

public class FindCoursesActivity extends FindCoursesBaseActivity {

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

        // configure slider layout. This should be called only once and
        // hence is shifted to onCreate() function
        configureDrawer();

        try{
            segIO.screenViewsTracking(getString(R.string.find_courses_title));
        }catch(Exception e){
            logger.error(e);
        }
    }

    @Override
    protected void onStart() {
        super.onStart();

        String url = Config.getInstance().getEnrollmentConfig().getCourseSearchUrl();
        WebView webview = (WebView) findViewById(R.id.webview);
        webview.loadUrl(url);
    }
}

package org.edx.mobile.view;

import android.os.Bundle;
import android.webkit.WebView;

import org.edx.mobile.R;
import org.edx.mobile.base.FindCoursesBaseActivity;
import org.edx.mobile.util.Config;

public class FindCoursesActivity extends FindCoursesBaseActivity {

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

        // configure slider layout. This should be called only once and
        // hence is shifted to onCreate() function
        configureDrawer();

        try{
            segIO.screenViewsTracking(getString(R.string.find_courses_title));
        }catch(Exception e){
            logger.error(e);
        }
        String url = Config.getInstance().getEnrollmentConfig().getCourseSearchUrl();
        WebView webview = (WebView) findViewById(R.id.webview);
        webview.loadUrl(url);
    }

}

Stop webview reloading in Find Courses


package com.frc2013.rmr662.main;

import com.frc2013.rmr662.eastereggs.DanceMode;
import com.frc2013.rmr662.system.generic.Robot;
import com.frc2013.rmr662.system.generic.RobotMode;

public class MainRobot extends Robot {

	protected RobotMode getAutoMode() {
		return null;// new DanceMode(); // No autonomous mode this season :(
	}

	protected RobotMode getTeleopMode() {
		return new TeleopMode();
	}

}

package com.frc2013.rmr662.main;

import com.frc2013.rmr662.system.generic.Robot;
import com.frc2013.rmr662.system.generic.RobotMode;

public class MainRobot extends Robot {

	protected RobotMode getAutoMode() {
		return null;// new DanceMode(); // No autonomous mode this season :(
	}

	protected RobotMode getTeleopMode() {
		return new TeleopMode();
	}

}

Fix import issue from removing eastereggs


/*
 * Copyright (C) 2004 - 2014 Brian McCallister
 *
 * 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.skife.jdbi.v2.sqlobject;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.PARAMETER})
@BindingAnnotation(BindBeanFactory.class)
public @interface BindBean
{
    static final String BARE_BINDING = "___jdbi_bare___";
    String value() default BARE_BINDING;
}

/*
 * Copyright (C) 2004 - 2014 Brian McCallister
 *
 * 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.skife.jdbi.v2.sqlobject;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.PARAMETER})
@BindingAnnotation(BindBeanFactory.class)
public @interface BindBean
{
    final String BARE_BINDING = "___jdbi_bare___";
    String value() default BARE_BINDING;
}

Fix 'redundant static modifier' warning


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

/**
 * The eventing thread pool is a special thread pool used for the eventing.
 * The eventing uses a service registered as this interface.
 * The default implementation is a configurable pool registered with
 * commons threads.
 *
 * @version $Id$
 */
public interface ThreadPool extends org.apache.sling.commons.threads.ThreadPool {

    // this is just a marker interface
}

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

/**
 * The eventing thread pool is a special thread pool used for the eventing.
 * The eventing uses a service registered as this interface.
 * The default implementation is a configurable pool registered with
 * commons threads.
 */
public interface ThreadPool extends org.apache.sling.commons.threads.ThreadPool {

    // this is just a marker interface
}

Remove version info from comment.


package tw.kewang.hbase;

public class UserDao {

}

package tw.kewang.hbase;

import java.io.IOException;

import org.apache.hadoop.hbase.client.Get;
import org.apache.hadoop.hbase.client.HConnection;
import org.apache.hadoop.hbase.client.HTableInterface;
import org.apache.hadoop.hbase.client.Result;
import org.apache.hadoop.hbase.util.Bytes;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import tw.kewang.hbase.annotations.Table;
import tw.kewang.hbase.dao.Constants;
import tw.kewang.hbase.dao.HConnectionHolder;

@Table(name = "User")
public class UserDao {
	private static final Table TABLE = getTableAnnotation();
	private static final Logger LOG = LoggerFactory.getLogger(UserDao.class);
	private static final HConnection CONNECTION = HConnectionHolder
			.getInstance().getHConnection();

	public User1 getByRowkey(String rowkey) {
		HTableInterface hTableInterface = null;

		try {
			hTableInterface = CONNECTION.getTable(TABLE.name());

			Result results = hTableInterface.get(buildGet(rowkey));

			if (!results.isEmpty()) {

			}
		} catch (Exception e) {
			LOG.error(Constants.EXCEPTION_PREFIX, e);
		} catch (Error e) {
			LOG.error(Constants.EXCEPTION_PREFIX, e);
		} finally {
			closeHTable(hTableInterface);
		}

		return null;
	}

	private static Table getTableAnnotation() {
		Class<?> clazz = UserDao.class;

		Table table = clazz.getAnnotation(Table.class);

		if (table == null) {
			throw new RuntimeException("No table annotation");
		}

		return table;
	}

	private Get buildGet(String rowkey) {
		Get get = new Get(Bytes.toBytes(rowkey));

		try {
			get.setMaxVersions(TABLE.maxVersions());
		} catch (IOException e) {
			LOG.error(Constants.EXCEPTION_PREFIX, e);
		}

		return get;
	}

	private void closeHTable(HTableInterface hTableInterface) {
		if (hTableInterface != null) {
			try {
				hTableInterface.close();
			} catch (Exception e) {
				LOG.error(Constants.EXCEPTION_PREFIX, e);
			} catch (Error e) {
				LOG.error(Constants.EXCEPTION_PREFIX, e);
			}
		}
	}
}

Add getByRowkey @ Dao (uncomplete)


/*
 * Copyright (C) 2013 salesforce.com, 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 org.auraframework.docs;

import javax.inject.Inject;

import org.auraframework.annotations.Annotations.ServiceComponentModelFactory;
import org.auraframework.ds.servicecomponent.ModelFactory;
import org.auraframework.ds.servicecomponent.ModelInitializationException;
import org.auraframework.service.ContextService;

@ServiceComponentModelFactory
public class ApiTopicModelFactory implements ModelFactory<ApiTopicModel> {

    @Inject
    private ContextService contextService;

    @Override
    public ApiTopicModel modelInstance() throws ModelInitializationException {
        try {
            return new ApiTopicModel(contextService);
        } catch (Exception x) {
            throw new ModelInitializationException("Error creating model instance", x);
        }
    }
}

/*
 * Copyright (C) 2013 salesforce.com, 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 org.auraframework.docs;

import javax.annotation.PostConstruct;
import javax.inject.Inject;

import org.auraframework.adapter.ConfigAdapter;
import org.auraframework.annotations.Annotations.ServiceComponentModelFactory;
import org.auraframework.ds.servicecomponent.ModelFactory;
import org.auraframework.ds.servicecomponent.ModelInitializationException;
import org.auraframework.service.ContextService;

@ServiceComponentModelFactory
public class ApiTopicModelFactory implements ModelFactory<ApiTopicModel> {

    @Inject
    private ContextService contextService;

    @Inject
    private ConfigAdapter configAdapter;

    @PostConstruct
    public void init() {
        // This is messy, we should clean this up, but just converting it for the moment.
        ApiContentsModel.refreshSymbols(configAdapter.getResourceLoader());
    }

    @Override
    public ApiTopicModel modelInstance() throws ModelInitializationException {
        try {
            return new ApiTopicModel(contextService);
        } catch (Exception x) {
            throw new ModelInitializationException("Error creating model instance", x);
        }
    }
}

Fix a race condition with topic model usage of symbols


package com.google.sps;

import com.google.sps.data.Trip;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;

import com.google.sps.data.Location;

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

@RunWith(JUnit4.class)
public class TripTest {
  @Test
  public void testDefaultBuilderValuesWithRequiredData() {
    Location loc1 = Location.create("aBc123", 4);
    Location loc2 = Location.create("xY4z65", 2);
    Trip defaultTrip = Trip.builder()
                        .setTitle("Trip 1")
                        .setLocations(new ArrayList<Location>(Arrays.asList(loc1, loc2)))
                        .setOwner("test@gmail.com")
                        .setTimestamp(1594160425000L)
                        .build();
    Assert.assertEquals("Trip 1", defaultTrip.title());
    Assert.assertEquals(Arrays.asList(loc1, loc2), defaultTrip.locations());
    Assert.assertEquals(Collections.emptyList(), defaultTrip.hotels());
    Assert.assertEquals(-1, defaultTrip.rating(), 0.01);
    Assert.assertEquals("", defaultTrip.description());
    Assert.assertEquals("test@gmail.com", defaultTrip.owner());
    Assert.assertEquals(false, defaultTrip.isPublic());
    Assert.assertEquals(1594160425000L, defaultTrip.timestamp());
  }
}

package com.google.sps;

import com.google.sps.data.Trip;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;

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

@RunWith(JUnit4.class)
public class TripTest {
  @Test
  public void testDefaultBuilderValuesWithRequiredData() {
    Trip defaultTrip = Trip.builder()
                        .setTitle("Trip 1")
                        .setOwner("test@gmail.com")
                        .setTimestamp(1594160425000L)
                        .build();
    Assert.assertEquals("Trip 1", defaultTrip.title());
    Assert.assertEquals("", defaultTrip.hotel());
    Assert.assertEquals(-1, defaultTrip.rating(), 0.01);
    Assert.assertEquals("", defaultTrip.description());
    Assert.assertEquals("test@gmail.com", defaultTrip.owner());
    Assert.assertEquals(false, defaultTrip.isPublic());
    Assert.assertEquals(1594160425000L, defaultTrip.timestamp());
  }
}

Fix failing tests for Trip value class


package org.opennms.netmgt.vulnscand;

import junit.framework.TestCase;

import org.opennms.core.queue.FifoQueue;
import org.opennms.core.queue.FifoQueueImpl;
import org.opennms.netmgt.config.VulnscandConfigFactory;

public class SchedulerTest extends TestCase {

	protected void setUp() throws Exception {

		System.setProperty("opennms.home", "src/test/test-configurations/vulnscand");

		VulnscandConfigFactory.init();

		super.setUp();

	}

	protected void tearDown() throws Exception {
		super.tearDown();
	}

	public void FIXMEtestCreate() throws Exception {
		FifoQueue q = new FifoQueueImpl();
		Scheduler scheduler = new Scheduler(q);
		Vulnscand vulnscand = null;
		vulnscand.initialize();

	}

}

package org.opennms.netmgt.vulnscand;

import junit.framework.TestCase;

import org.opennms.core.queue.FifoQueue;
import org.opennms.core.queue.FifoQueueImpl;
import org.opennms.netmgt.config.VulnscandConfigFactory;

public class SchedulerTest extends TestCase {

	protected void setUp() throws Exception {

		System.setProperty("opennms.home", "src/test/test-configurations/vulnscand");

		VulnscandConfigFactory.init();

		super.setUp();

	}

	protected void tearDown() throws Exception {
		super.tearDown();
	}

    // FIXME
	public void FIXMEtestCreate() throws Exception {
		FifoQueue q = new FifoQueueImpl();
		Scheduler scheduler = new Scheduler(q);
		Vulnscand vulnscand = null;
		vulnscand.initialize();

	}

}

Add a "FIXME" comment for the disabled test so it shows up as a note in Eclipse (this idea was suggested awhile ago by brozow).


package info.u_team.u_team_test.init;

import java.awt.Color;

import info.u_team.u_team_test.TestMod;
import net.minecraftforge.api.distmarker.Dist;
import net.minecraftforge.client.event.ColorHandlerEvent;
import net.minecraftforge.eventbus.api.SubscribeEvent;
import net.minecraftforge.fml.common.Mod.EventBusSubscriber;
import net.minecraftforge.fml.common.Mod.EventBusSubscriber.Bus;

@EventBusSubscriber(modid = TestMod.MODID, bus = Bus.MOD, value = Dist.CLIENT)
public class TestColors {

	@SubscribeEvent
	public static void register(ColorHandlerEvent.Item event) {
		// This use the awt color class. Might not work but was too lazy to write an own color class.
		event.getItemColors().register((stack, index) -> Color.getHSBColor((float) stack.getDamage() / (float) stack.getMaxDamage(), 0.8F, 0.5F).getRGB(), TestItems.BASIC.get());
	}
}

package info.u_team.u_team_test.init;

import java.awt.Color;

import net.minecraftforge.client.event.ColorHandlerEvent;
import net.minecraftforge.eventbus.api.IEventBus;

public class TestColors {

	private static void colorItem(ColorHandlerEvent.Item event) {
		// This use the awt color class. Might not work but was too lazy to write an own color class.
		event.getItemColors().register((stack, index) -> Color.getHSBColor((float) stack.getDamage() / (float) stack.getMaxDamage(), 0.8F, 0.5F).getRGB(), TestItems.BASIC.get());
	}

	public static void registerMod(IEventBus bus) {
		bus.addListener(TestColors::colorItem);
	}
}

Update test colors to the new system


package org.wmaop.bdd.jbehave;

import org.junit.runner.RunWith;

import de.codecentric.jbehave.junit.monitoring.JUnitReportingRunner;

@RunWith(JUnitReportingRunner.class)
public class JBehaveTestRunner extends JBehaveRunner {
	public JBehaveTestRunner() {
		super();
	}

}

package org.wmaop.bdd.jbehave;

import org.junit.runner.RunWith;

import de.codecentric.jbehave.junit.monitoring.JUnitReportingRunner;

@RunWith(JUnitReportingRunner.class)
public class JBehaveTestRunner extends JBehaveRunner {
}

Tidy runner to make consistent


package org.realityforge.arez.api2;

import javax.annotation.Nonnull;
import javax.annotation.Nullable;

public class Reaction
  extends Observer
{
  /**
   * Flag indicating whether this reaction has been scheduled. i.e. has a pending reaction.
   */
  private boolean _scheduled;

  Reaction( @Nonnull final ArezContext context, @Nullable final String name )
  {
    super( context, name );
    setOnStale( this::schedule );
  }

  final boolean isScheduled()
  {
    return _scheduled;
  }

  final void schedule()
  {
    Guards.invariant( this::isActive,
                      () -> String.format(
                        "Observer named '%s' is not active but an attempt has been made to schedule observer.",
                        getName() ) );
    if ( !_scheduled )
    {
      _scheduled = true;
      getContext().scheduleReaction( this );
    }
  }
}

package org.realityforge.arez.api2;

import java.util.Objects;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;

public class Reaction
  extends Observer
{
  /**
   * Flag indicating whether this reaction has been scheduled. i.e. has a pending reaction.
   */
  private boolean _scheduled;
  /**
   * The transaction mode in which the action executes.
   */
  @Nonnull
  private final TransactionMode _mode;

  Reaction( @Nonnull final ArezContext context, @Nullable final String name, @Nonnull final TransactionMode mode )
  {
    super( context, name );
    setOnStale( this::schedule );
    _mode = Objects.requireNonNull( mode );
  }

  /**
   * Return the transaction mode in which the action executes.
   *
   * @return the transaction mode in which the action executes.
   */
  @Nonnull
  final TransactionMode getMode()
  {
    return _mode;
  }

  final boolean isScheduled()
  {
    return _scheduled;
  }

  final void schedule()
  {
    Guards.invariant( this::isActive,
                      () -> String.format(
                        "Observer named '%s' is not active but an attempt has been made to schedule observer.",
                        getName() ) );
    if ( !_scheduled )
    {
      _scheduled = true;
      getContext().scheduleReaction( this );
    }
  }
}

Add the transaction mode to the reaction


/*
 * CollabNet Subversion Edge
 * Copyright (C) 2011, CollabNet Inc. All rights reserved.
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * 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 Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package com.collabnet.svnedge.schema;

import org.apache.log4j.Logger;

import java.sql.SQLException;

public class MS009EnableCloudService implements MigrationScript {
    private Logger log = Logger.getLogger(getClass());

    public boolean migrate(SqlUtil db) throws SQLException {

        db.executeUpdateSql("update CLOUD_SERVICES_CONFIGURATION " +
                "set ENABLED = true");
        return false;
    }

    public int[] getVersion() {
        return new int[] {2,4,1};
    }
}

/*
 * CollabNet Subversion Edge
 * Copyright (C) 2011, CollabNet Inc. All rights reserved.
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * 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 Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package com.collabnet.svnedge.schema;

import org.apache.log4j.Logger;

import java.sql.SQLException;

public class MS009EnableCloudService implements MigrationScript {
    private Logger log = Logger.getLogger(getClass());

    public boolean migrate(SqlUtil db) throws SQLException {
        // insert row, if it does not exist
        db.executeUpdateSql("insert into CLOUD_SERVICES_CONFIGURATION " +
                "(select 1 as ID, 0 as VERSION, '' as DOMAIN, '' as USERNAME," +
                " '' as PASSWORD, true as ENABLED from " +
                "(select 1 as ID, count(*) from CLOUD_SERVICES_CONFIGURATION)" +
                " where ID not in " +
                "(select ID from CLOUD_SERVICES_CONFIGURATION))");
        // for installations where a row already existed
        db.executeUpdateSql("update CLOUD_SERVICES_CONFIGURATION " +
                "set ENABLED = true");
        return false;
    }

    public int[] getVersion() {
        return new int[] {3,0,0};
    }
}

Enable cloud services by default


package org.icij.extract.cli.factory;

import org.apache.commons.cli.CommandLine;

import org.redisson.Config;

/**
 * Factory methods for creating Redis configuration.
 *
 * @author Matthew Caruana Galizia <mcaruana@icij.org>
 * @since 1.0.0-beta
 */
public class RedisConfigFactory {

	/**
	 * Create a new Redis configuration object from commandline parameters.
	 *
	 * @param cmd the commandline object containing supplied parameters
	 * @return the generated configuration object
	 */
	public static Object createConfig(final CommandLine cmd) {
		final Config config = new Config();
		final Object serverConfig;

		// TODO: support all the other types supported by the ConnectionManagerFactory.
		serverConfig = config.useSingleServer()
				.setAddress(cmd.getOptionValue("redis-address", "127.0.0.1:6379"))
				.setTimeout(5000);

		return serverConfig;
	}
}

package org.icij.extract.cli.factory;

import org.apache.commons.cli.CommandLine;

import org.redisson.Config;

/**
 * Factory methods for creating Redis configuration.
 *
 * @author Matthew Caruana Galizia <mcaruana@icij.org>
 * @since 1.0.0-beta
 */
public class RedisConfigFactory {

	/**
	 * Create a new Redis configuration object from commandline parameters.
	 *
	 * @param cmd the commandline object containing supplied parameters
	 * @return the generated configuration object
	 */
	public static Object createConfig(final CommandLine cmd) {
		final Config config = new Config();
		final Object serverConfig;

		// TODO: support all the other types supported by the ConnectionManagerFactory.
		serverConfig = config.useSingleServer()
				.setAddress(cmd.getOptionValue("redis-address", "127.0.0.1:6379"))
				.setTimeout(60000);

		return serverConfig;
	}
}

Increase the timeout for Redis connections


package com.oxapps.tradenotifications;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.preference.PreferenceManager;

public class NotificationDeleteReceiver extends BroadcastReceiver {
    private static final String TRADE_OFFERS_URL = "https://steamcommunity.com/id/id/tradeoffers/";

    @Override
    public void onReceive(Context context, Intent intent) {
        long newRequestTime = System.currentTimeMillis() / 1000;
        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
        SharedPreferences.Editor editor = prefs.edit();
        editor.putLong(BackgroundIntentService.LAST_DELETE_KEY, newRequestTime);
        editor.apply();

        if(intent.hasExtra(BackgroundIntentService.NOTIFICATION_CLICKED)) {
            Intent browserIntent = new Intent(Intent.ACTION_VIEW);
            browserIntent.setData(Uri.parse(TRADE_OFFERS_URL));
            context.getApplicationContext().startActivity(browserIntent);
        }
    }
}

package com.oxapps.tradenotifications;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.preference.PreferenceManager;

public class NotificationDeleteReceiver extends BroadcastReceiver {
    private static final String TRADE_OFFERS_URL = "https://steamcommunity.com/id/id/tradeoffers/";

    @Override
    public void onReceive(Context context, Intent intent) {
        long newRequestTime = System.currentTimeMillis() / 1000;
        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
        SharedPreferences.Editor editor = prefs.edit();
        editor.putLong(BackgroundIntentService.LAST_DELETE_KEY, newRequestTime);
        editor.apply();

        if(intent.hasExtra(BackgroundIntentService.NOTIFICATION_CLICKED)) {
            Intent browserIntent = new Intent(Intent.ACTION_VIEW);
            browserIntent.setData(Uri.parse(TRADE_OFFERS_URL));
            browserIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            context.getApplicationContext().startActivity(browserIntent);
        }
    }
}

Fix bug causing app to crash on clicking notification


// Copyright (c) 2015, Wojciech Adam Koszek <wojciech@koszek.com>
// All rights reserved.

package com.barvoy.sensorama;

public class SRCfg {
    public static final String addDirName = "sensorama";
    public static final int interval = 250;
    public static final String timeFormat = "HHmmss";
    public static final String dateFormat = "yyyyMMdd_" + timeFormat;
    public static final int buttonColorStopped = 0xffff0000;    // red
    public static final int buttonColorStart = 0xff00ff00;      // green
    public static final int buttonColorInitial = buttonColorStart;
    public static final boolean doParseBootstrap = false;
}

// Copyright (c) 2015, Wojciech Adam Koszek <wojciech@koszek.com>
// All rights reserved.

package com.barvoy.sensorama;

public class SRCfg {
    public static final String addDirName = "sensorama";
    public static final int interval = 250;
    public static final String timeFormat = "HHmmss";
    public static final String dateFormat = "yyyyMMdd_" + timeFormat;
    public static final int buttonColorStopped = 0xffff0000;    // red
    public static final int buttonColorStart = 0xff00ff00;      // green
    public static final int buttonColorInitial = buttonColorStart;
    public static final boolean doParseBootstrap = true;
}

Enable bootstrap for Parse testing.


package org.javarosa.xpath.expr;

import org.javarosa.core.model.condition.EvaluationContext;
import org.javarosa.core.model.instance.DataInstance;
import org.javarosa.xpath.XPathNodeset;
import org.javarosa.xpath.XPathTypeMismatchException;
import org.javarosa.xpath.parser.XPathSyntaxException;

public class XPathCountFunc extends XPathFuncExpr {
    public static final String NAME = "count";
    private static final int EXPECTED_ARG_COUNT = 1;

    public XPathCountFunc() {
        name = NAME;
        expectedArgCount = EXPECTED_ARG_COUNT;
    }

    public XPathCountFunc(XPathExpression[] args) throws XPathSyntaxException {
        super(NAME, args, EXPECTED_ARG_COUNT, true);
    }

    @Override
    public Object evalBody(DataInstance model, EvaluationContext evalContext, Object[] evaluatedArgs) {
        if (evaluatedArgs[0] instanceof XPathNodeset) {
            return new Double(((XPathNodeset)evaluatedArgs[0]).size());
        } else {
            throw new XPathTypeMismatchException("not a nodeset");
        }
    }

}

package org.javarosa.xpath.expr;

import org.javarosa.core.model.condition.EvaluationContext;
import org.javarosa.core.model.instance.DataInstance;
import org.javarosa.xpath.XPathNodeset;
import org.javarosa.xpath.XPathTypeMismatchException;
import org.javarosa.xpath.parser.XPathSyntaxException;

public class XPathCountFunc extends XPathFuncExpr {
    public static final String NAME = "count";
    private static final int EXPECTED_ARG_COUNT = 1;

    public XPathCountFunc() {
        name = NAME;
        expectedArgCount = EXPECTED_ARG_COUNT;
    }

    public XPathCountFunc(XPathExpression[] args) throws XPathSyntaxException {
        super(NAME, args, EXPECTED_ARG_COUNT, true);
    }

    @Override
    public Object evalBody(DataInstance model, EvaluationContext evalContext, Object[] evaluatedArgs) {
        if (evaluatedArgs[0] instanceof XPathNodeset) {
            return new Double(((XPathNodeset)evaluatedArgs[0]).size());
        } else {
            throw new XPathTypeMismatchException("uses an invalid reference inside a count function");
        }
    }

}

Update error text to be more descriptive


package co.paystack.android.api.request;

import com.google.gson.annotations.SerializedName;

import java.io.Serializable;
import java.util.HashMap;

/**
 * Created by i on 24/08/2016.
 */
public class ValidateRequestBody extends BaseRequestBody implements Serializable {

    public static final String FIELD_TRANS = "trans";
    public static final String FIELD_TOKEN = "token";

    @SerializedName(FIELD_TRANS)
    public String trans;

    @SerializedName(FIELD_TOKEN)
    public String token;

    public ValidateRequestBody() {
    }

    public ValidateRequestBody(String trans, String token) {
        this.trans = trans;
        this.token = token;
    }

    @Override
    public HashMap<String, String> getParamsHashMap() {
        HashMap<String, String> params = new HashMap<>();
        params.put(FIELD_TRANS, trans);
        params.put(FIELD_TOKEN, token);
        return params;
    }
}

package co.paystack.android.api.request;

import com.google.gson.annotations.SerializedName;

import java.io.Serializable;
import java.util.HashMap;

/**
 * Created by i on 24/08/2016.
 */
public class ValidateRequestBody extends BaseRequestBody implements Serializable {

    public static final String FIELD_TRANS = "trans";
    public static final String FIELD_TOKEN = "token";

    @SerializedName(FIELD_TRANS)
    public String trans;

    @SerializedName(FIELD_TOKEN)
    public String token;

    public ValidateRequestBody() {
    }

    public String getTrans() {
        return trans;
    }

    public ValidateRequestBody setTrans(String trans) {
        this.trans = trans;
        return this;
    }

    public String getToken() {
        return token;
    }

    public ValidateRequestBody setToken(String token) {
        this.token = token;
        return this;
    }

    @Override
    public HashMap<String, String> getParamsHashMap() {
        HashMap<String, String> params = new HashMap<>();
        params.put(FIELD_TRANS, getTrans());
        params.put(FIELD_TOKEN, getToken());
        return params;
    }
}

Validate request body get and set fields


package info.u_team.u_team_core.util.registry;

import java.util.function.Supplier;

import net.minecraft.client.KeyMapping;
import net.minecraft.client.gui.screens.MenuScreens;
import net.minecraft.client.gui.screens.Screen;
import net.minecraft.client.gui.screens.inventory.MenuAccess;
import net.minecraft.client.renderer.blockentity.BlockEntityRendererProvider;
import net.minecraft.client.renderer.blockentity.BlockEntityRenderers;
import net.minecraft.client.renderer.entity.EntityRendererProvider;
import net.minecraft.world.entity.Entity;
import net.minecraft.world.entity.EntityType;
import net.minecraft.world.inventory.AbstractContainerMenu;
import net.minecraft.world.inventory.MenuType;
import net.minecraft.world.level.block.entity.BlockEntity;
import net.minecraft.world.level.block.entity.BlockEntityType;
import net.minecraftforge.fmlclient.registry.RenderingRegistry;

public class ClientRegistry {

	public static <M extends AbstractContainerMenu, U extends Screen & MenuAccess<M>> void registerScreen(Supplier<? extends MenuType<? extends M>> supplier, MenuScreens.ScreenConstructor<M, U> factory) {
		MenuScreens.register(supplier.get(), factory);
	}

	public static <T extends Entity> void registerEntityRenderer(Supplier<? extends EntityType<? extends T>> supplier, EntityRendererProvider<T> provider) {
		RenderingRegistry.registerEntityRenderingHandler(supplier.get(), provider);
	}

	public static <T extends BlockEntity> void registerSpecialTileEntityRenderer(Supplier<? extends BlockEntityType<T>> supplier, BlockEntityRendererProvider<T> provider) {
		BlockEntityRenderers.register(supplier.get(), provider);
	}

	public static void registerKeybinding(KeyMapping key) {
		net.minecraftforge.fmlclient.registry.ClientRegistry.registerKeyBinding(key);
	}

}

package info.u_team.u_team_core.util.registry;

import java.util.function.Supplier;

import net.minecraft.client.KeyMapping;
import net.minecraft.client.gui.screens.MenuScreens;
import net.minecraft.client.gui.screens.Screen;
import net.minecraft.client.gui.screens.inventory.MenuAccess;
import net.minecraft.world.inventory.AbstractContainerMenu;
import net.minecraft.world.inventory.MenuType;

public class ClientRegistry {

	@Deprecated // TODO remove
	public static <M extends AbstractContainerMenu, U extends Screen & MenuAccess<M>> void registerScreen(Supplier<? extends MenuType<? extends M>> supplier, MenuScreens.ScreenConstructor<M, U> factory) {
		MenuScreens.register(supplier.get(), factory);
	}

	public static void registerKeybinding(KeyMapping key) {
		net.minecraftforge.fmlclient.registry.ClientRegistry.registerKeyBinding(key);
	}

}

Remove oudated methods due to new forge update


package org.jvirtanen.philadelphia.perf;

import static java.nio.charset.StandardCharsets.*;

import java.nio.ByteBuffer;
import java.util.concurrent.TimeUnit;
import org.jvirtanen.philadelphia.FIXTags;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Level;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.Setup;
import org.openjdk.jmh.annotations.State;
import org.openjdk.jmh.annotations.TearDown;

@State(Scope.Thread)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
public class FIXTagsBenchmark {

    private ByteBuffer buffer;

    @Setup(Level.Iteration)
    public void prepare() {
        buffer = ByteBuffer.wrap("123=".getBytes(US_ASCII));
    }

    @TearDown(Level.Invocation)
    public void tearDown() {
        buffer.flip();
    }

    @Benchmark
    @BenchmarkMode(Mode.SampleTime)
    public long get() {
        return FIXTags.get(buffer);
    }

    @Benchmark
    @BenchmarkMode(Mode.SampleTime)
    public void put() {
        FIXTags.put(buffer, 123);
    }

}

package org.jvirtanen.philadelphia.perf;

import static java.nio.charset.StandardCharsets.*;

import java.nio.ByteBuffer;
import java.util.concurrent.TimeUnit;
import org.jvirtanen.philadelphia.FIXTags;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Level;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.Setup;
import org.openjdk.jmh.annotations.State;
import org.openjdk.jmh.annotations.TearDown;

@State(Scope.Thread)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
public class FIXTagsBenchmark {

    private ByteBuffer buffer;

    @Setup(Level.Iteration)
    public void prepare() {
        buffer = ByteBuffer.wrap("123=".getBytes(US_ASCII));
    }

    @Benchmark
    @BenchmarkMode(Mode.SampleTime)
    public long get() {
        long tag = FIXTags.get(buffer);

        buffer.flip();

        return tag;
    }

    @Benchmark
    @BenchmarkMode(Mode.SampleTime)
    public void put() {
        FIXTags.put(buffer, 123);

        buffer.flip();
    }

}

Remove invocation level teardown from FIX tags benchmark


package se.kth.csc.controller;

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

import se.kth.csc.model.Account;
import se.kth.csc.persist.AccountStore;

import java.security.Principal;

import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.atLeastOnce;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;

public class HomeControllerTest {

  // System under test (SUT):
  private HomeController homeController;

  // Dependencies of this unit
  private AccountStore accountStore;

  @Before
  public void setUp() throws Exception {
    // Mock dependencies
    accountStore = mock(AccountStore.class);

    // Create SUT
    homeController = new HomeController(accountStore);
  }

  @Test
  public void testMakeMeAdmin() {
    // Set up expected behavior of mocks
    Principal principal = mock(Principal.class);
    when(principal.getName()).thenReturn("testuser");

    Account account = mock(Account.class);
    when(accountStore.fetchAccountWithPrincipalName("testuser")).thenReturn(account);

    // Run the system under test
    String result = homeController.makeMeAdmin(principal);

    // Verify that interactions with mocks happened
    verify(account, atLeastOnce()).setAdmin(true);

    // Verify actual returned results
    assertEquals("redirect:/debug", result);
  }
}

package se.kth.csc.controller;

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

import se.kth.csc.model.Account;
import se.kth.csc.persist.AccountStore;

import java.security.Principal;

import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.atLeastOnce;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;

public class HomeControllerTest {

  // System under test (SUT):
  private HomeController homeController;

  // Dependencies of this unit
  private AccountStore accountStore;

  @Before
  public void setUp() throws Exception {
    // Mock dependencies
    accountStore = mock(AccountStore.class);

    // Create SUT
    homeController = new HomeController(accountStore);
  }

  @Test
  public void testMakeMeAdmin() {
    // Set up expected behavior of mocks
    Principal principal = mock(Principal.class);
    when(principal.getName()).thenReturn("testuser");

    Account account = mock(Account.class);
    when(accountStore.fetchAccountWithPrincipalName("testuser")).thenReturn(account);

    // Run the system under test
    String result = null;
      try {
        result = homeController.makeMeAdmin(principal);
      } catch (ForbiddenException e) {
        // Do nothing
      }

    // Verify that interactions with mocks happened
    verify(account, atLeastOnce()).setAdmin(true);

    // Verify actual returned results
    assertEquals("redirect:/debug", result);
  }
}

Add try catch to test


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

import java.io.IOException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLStreamHandler;

public class Handler extends URLStreamHandler {

    @Override
    protected URLConnection openConnection(URL u) throws IOException {
        return new WarURLConnection(u);
    }
}

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

import java.io.IOException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLStreamHandler;

public class Handler extends URLStreamHandler {

    @Override
    protected URLConnection openConnection(URL u) throws IOException {
        return new WarURLConnection(u);
    }

    @Override
    protected void setURL(URL u, String protocol, String host, int port, String authority, String userInfo, String path,
            String query, String ref) {
        if (path.startsWith("file:") && !path.startsWith("file:/")) {
            // Work around a problem with the URLs in the security policy file.
            // On Windows, the use of ${catalina.[home|base]} in the policy file
            // results in codebase URLs of the form file:C:/... when they should
            // be file:/C:/...
            // For file: and jar: URLs, the JRE compensates for this. It does not
            // compensate for this for war:file:... URLs. Therefore, we do that
            // here
            path = "file:/" + path.substring(5);
        }
        super.setURL(u, protocol, host, port, authority, userInfo, path, query, ref);
    }
}

Add a work-around for poorly constructed "war:..." URLs obtained from the security policy file.


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

package net.openhft.chronicle.wire;

import org.jetbrains.annotations.NotNull;

import java.lang.reflect.Method;

/*
 * Created by Peter Lawrey on 25/03/16.
 */
public class BinaryMethodWriterInvocationHandler extends AbstractMethodWriterInvocationHandler {
    @NotNull
    private final MarshallableOut appender;

    BinaryMethodWriterInvocationHandler(@NotNull MarshallableOut appender) {
        this.appender = appender;
        recordHistory = appender.recordHistory();
    }

    @Override
    protected void handleInvoke(Method method, Object[] args) {
        try (@NotNull DocumentContext context = appender.writingDocument()) {
            Wire wire = context.wire();

            handleInvoke(method, args, wire);
            wire.padToCacheAlign();
        }
    }
}

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

package net.openhft.chronicle.wire;

import org.jetbrains.annotations.NotNull;

import java.lang.reflect.Method;
import java.util.function.Supplier;

/*
 * Created by Peter Lawrey on 25/03/16.
 */
public class BinaryMethodWriterInvocationHandler extends AbstractMethodWriterInvocationHandler {
    @NotNull
    private final Supplier<MarshallableOut> marshallableOutSupplier;

    BinaryMethodWriterInvocationHandler(@NotNull MarshallableOut marshallableOut) {
        this(() -> marshallableOut);
    }

    public BinaryMethodWriterInvocationHandler(Supplier<MarshallableOut> marshallableOutSupplier) {
        this.marshallableOutSupplier = marshallableOutSupplier;
        recordHistory = marshallableOutSupplier.get().recordHistory();
    }

    @Override
    protected void handleInvoke(Method method, Object[] args) {
        MarshallableOut marshallableOut = this.marshallableOutSupplier.get();
        try (@NotNull DocumentContext context = marshallableOut.writingDocument()) {
            Wire wire = context.wire();

            handleInvoke(method, args, wire);
            wire.padToCacheAlign();
        }
    }
}

Make a MethodWriter for a queue obtain a thread safe appender each time.


package game;

import com.badlogic.gdx.Game;
import com.badlogic.gdx.Screen;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import game.MenuScreens.MainMenu;

/**
 * Created by eriks on 26/10/2016.
 */

/**
 * Games entry point.
 */
public class BlueSky extends Game {

    // Game world size in arbitrary scale, these are not pixels
    public static final int GAME_WIDTH = 640;
    public static final int GAME_HEIGHT = 640;

    // Game version for global use
    public static final double VERSION = 0.2;

    SpriteBatch batch;

    private static SimpleLogger myLog = SimpleLogger.getLogger();

    /**
     * Analogue to instantiation. Loads all the assets to the memory. Creates a {@link SimpleLogger} and {@link SpriteBatch}.
     */
    public void create(){
        batch = new SpriteBatch();

        // Pre-loading all the assets for the game
        Assets.load();

        myLog.setLogFile("BlueSky");
        myLog.setLogLevel(SimpleLogger.DEBUG);
        myLog.info("Starting...");
        this.setScreen(new MainMenu(this));
    }

    /**
     * Renders a {@link Screen}
     */
    public void render(){
        super.render();
    }

    /**
     * Disposes of all teh assets that are not collected by garbage collector. This method runs automatically.
     */
    public void dispose(){
        batch.dispose();
        Assets.dispose();
    }
}

package game;

import com.badlogic.gdx.Game;
import com.badlogic.gdx.Screen;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import game.MenuScreens.MainMenu;

/**
 * Created by eriks on 26/10/2016.
 */

/**
 * Games entry point.
 */
public class BlueSky extends Game {

    // Game world size in arbitrary scale, these are not pixels
    public static final int GAME_WIDTH = 640;
    public static final int GAME_HEIGHT = 640;

    // Game version for global use
    public static final double VERSION = 0.2;

    SpriteBatch batch;

    private static SimpleLogger myLog = SimpleLogger.getLogger();

    /**
     * Analogue to instantiation. Loads all the assets to the memory. Creates a {@link SimpleLogger} and {@link SpriteBatch}.
     */
    public void create(){
        batch = new SpriteBatch();

        // Pre-loading all the assets for the game
        Assets.load();

        myLog.setLogFile("BlueSky");
        myLog.setLogLevel(SimpleLogger.INFO);
        myLog.info("Starting...");
        this.setScreen(new MainMenu(this));
    }

    /**
     * Renders a {@link Screen}
     */
    public void render(){
        super.render();
    }

    /**
     * Disposes of all teh assets that are not collected by garbage collector. This method runs automatically.
     */
    public void dispose(){
        batch.dispose();
        Assets.dispose();
    }
}

Set log level to info


package com.molina.cvmfs.directoryentry;

import com.molina.cvmfs.directoryentry.exception.ChunkFileDoesNotMatch;

/**
 * @author Jose Molina Colmenero
 *         <p/>
 *         Wrapper around file chunks in the CVMFS catalogs
 */
public class Chunk {

    protected int offset;
    protected int size;
    protected String contentHash;
    protected int contentHashType;

    public Chunk(Object[] chunkData, int contentHashType) throws ChunkFileDoesNotMatch {
        if (chunkData.length != 5)
            throw new ChunkFileDoesNotMatch();
        this.offset = (Integer) chunkData[2];
        this.size = (Integer) chunkData[3];
        this.contentHash = new String((byte[]) chunkData[4]);
        this.contentHashType = contentHashType;
    }

    public static String catalogDatabaseFields() {
        return "md5path_1, md5path_2, offset, size, hash";
    }

    public String contentHashString() {
        String suffix = ContentHashTypes.toSuffix(contentHashType);
        StringBuilder sb = new StringBuilder();
        for (byte b : contentHash.getBytes())
            sb.append(String.format("%02X ", b));
        return sb.toString().toLowerCase() + suffix;
    }
}

package com.molina.cvmfs.directoryentry;

import com.molina.cvmfs.directoryentry.exception.ChunkFileDoesNotMatch;

import org.sqldroid.SQLDroidBlob;

import java.sql.SQLException;

/**
 * @author Jose Molina Colmenero
 *         <p/>
 *         Wrapper around file chunks in the CVMFS catalogs
 */
public class Chunk {

    protected int offset;
    protected int size;
    protected String contentHash;
    protected int contentHashType;

    public Chunk(Object[] chunkData, int contentHashType) throws ChunkFileDoesNotMatch {
        if (chunkData.length != 5)
            throw new ChunkFileDoesNotMatch();
        this.offset = (Integer) chunkData[2];
        this.size = (Integer) chunkData[3];
        this.contentHashType = contentHashType;
        if (chunkData[4] instanceof byte[]) {
            this.contentHash = new String((byte[]) chunkData[4]);
        } else if (chunkData[4] instanceof SQLDroidBlob){
            SQLDroidBlob blob = (SQLDroidBlob) chunkData[4];
            try {
                this.contentHash = new String(blob.getBytes(0, (int) blob.length()));
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

    public static String catalogDatabaseFields() {
        return "md5path_1, md5path_2, offset, size, hash";
    }

    public String contentHashString() {
        String suffix = ContentHashTypes.toSuffix(contentHashType);
        StringBuilder sb = new StringBuilder();
        for (byte b : contentHash.getBytes())
            sb.append(String.format("%02X ", b));
        return sb.toString().toLowerCase() + suffix;
    }
}

Fix chunks when using the SQLDroid library