/*
 * Copyright © 2012 Sebastian Hoß <mail@shoss.de>
 * This work is free. You can redistribute it and/or modify it under the
 * terms of the Do What The Fuck You Want To Public License, Version 2,
 * as published by Sam Hocevar. See http://www.wtfpl.net/ for more details.
 */
package com.github.sebhoss.contract.configuration;

import com.github.sebhoss.contract.verifier.ParameterNamesLookupConfiguration;
import com.github.sebhoss.contract.verifier.SpringElConfiguration;
import com.github.sebhoss.contract.verifier.impl.ErrorMessageConfiguration;

import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.context.annotation.Import;

/**
 * Default configuration for Spring-based projects.
 */
@Configuration
@EnableAspectJAutoProxy
@Import({ ParameterNamesLookupConfiguration.class, SpringElConfiguration.class, ErrorMessageConfiguration.class })
public class DefaultSpringConfiguration {

    // Meta-configuration

}

/*
 * Copyright © 2012 Sebastian Hoß <mail@shoss.de>
 * This work is free. You can redistribute it and/or modify it under the
 * terms of the Do What The Fuck You Want To Public License, Version 2,
 * as published by Sam Hocevar. See http://www.wtfpl.net/ for more details.
 */
package com.github.sebhoss.contract.configuration;

import com.github.sebhoss.contract.verifier.ParameterNamesLookupConfiguration;
import com.github.sebhoss.contract.verifier.SpringElConfiguration;
import com.github.sebhoss.contract.verifier.impl.ErrorMessageConfiguration;

import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.context.annotation.Import;

/**
 * Default configuration for Spring-based projects.
 */
@Configuration
@EnableAspectJAutoProxy(proxyTargetClass = true)
@Import({ ParameterNamesLookupConfiguration.class, SpringElConfiguration.class, ErrorMessageConfiguration.class })
public class DefaultSpringConfiguration {

    // Meta-configuration

}

Enable proxy classes for parameter names


package hackerrank;

import java.util.Scanner;

/**
 * https://www.hackerrank.com/challenges/cut-the-sticks
 */
public class CutTheSticks {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
    }
}

package hackerrank;

import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.Scanner;

/**
 * https://www.hackerrank.com/challenges/cut-the-sticks
 */
public class CutTheSticks {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int n = in.nextInt();
        List<Integer> l = new ArrayList<>();
        for (int i = 0; i < n; i++) {
            l.add(in.nextInt());
        }
        Collections.sort(l);
        LinkedList<Integer> ll = new LinkedList<>(l);
        System.out.println(ll.size());
        while (ll.size() > 0) {
            int min = ll.getFirst();
            int size = ll.size();
            for (int i = 0; i < size; i++) {
                int e = ll.getFirst();
                int val = e - min;
                if (val == 0) {
                    ll.removeFirst();
                }
            }
            if (ll.size() > 0) {
                System.out.println(ll.size());
            }
        }
    }
}

Solve Cut the Sticks problem


// Copyright 2014, Kevin Ko <kevin@faveset.com>

package com.faveset.khttp;

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

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

import java.nio.ByteBuffer;

@RunWith(JUnit4.class)
public class RequestHeaderHandlerTest {
    @Test
    public void testSimple() throws InvalidRequestException {
        ByteBuffer buf = Helper.makeByteBuffer("hello: world\n");
        HandlerState state = new HandlerState();

        RequestHeaderHandler handler = new RequestHeaderHandler();
        assertFalse(handler.handleState(null, buf, state));

        assertEquals(1, state.getRequest().getHeader("hello").size());
        assertEquals("world", state.getRequest().getHeaderFirst("hello"));

        buf.clear();
        buf.put(Helper.makeByteBuffer("\n"));
        buf.flip();
        assertTrue(handler.handleState(null, buf, state));
    }
}

// Copyright 2014, Kevin Ko <kevin@faveset.com>

package com.faveset.khttp;

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

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

import java.nio.ByteBuffer;

@RunWith(JUnit4.class)
public class RequestHeaderHandlerTest {
    @Test
    public void testSimple() throws InvalidRequestException {
        ByteBuffer buf = Helper.makeByteBuffer("hello: world\n");
        HandlerState state = new HandlerState();

        RequestHeaderHandler handler = new RequestHeaderHandler();
        assertFalse(handler.handleState(null, buf, state));

        assertEquals(1, state.getRequest().getHeader("hello").size());
        assertEquals("world", state.getRequest().getHeaderFirst("hello"));

        buf.clear();
        buf.put(Helper.makeByteBuffer("foo: bar\r\n"));
        buf.flip();
        assertFalse(handler.handleState(null, buf, state));
        assertEquals(1, state.getRequest().getHeader("foo").size());
        assertEquals("bar", state.getRequest().getHeaderFirst("foo"));

        buf.clear();
        buf.put(Helper.makeByteBuffer("\n"));
        buf.flip();
        assertTrue(handler.handleState(null, buf, state));
    }
}

Expand simple test with another header.


/**
 * Copyright (C) 2015 MicroWorld (contact@microworld.org)
 *
 * 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.microworld.test.matchers;

import java.time.Instant;

import org.hamcrest.Description;
import org.hamcrest.TypeSafeDiagnosingMatcher;

public class IsAround extends TypeSafeDiagnosingMatcher<Instant> {
  private final Instant instant;

  public IsAround(final Instant instant) {
    this.instant = instant;
  }

  @Override
  public void describeTo(final Description description) {
    description.appendValue(instant);
  }

  @Override
  protected boolean matchesSafely(final Instant item, final Description mismatchDescription) {
    if (instant.minusSeconds(10).isAfter(item) || instant.plusSeconds(10).isBefore(item)) {
      mismatchDescription.appendText("was ").appendValue(item);
      return false;
    }
    return true;
  }
}

/**
 * Copyright (C) 2015 MicroWorld (contact@microworld.org)
 *
 * 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.microworld.test.matchers;

import java.time.Instant;

import org.hamcrest.Description;
import org.hamcrest.TypeSafeDiagnosingMatcher;

public class IsAround extends TypeSafeDiagnosingMatcher<Instant> {
  private static final int MARGIN = 15;
  private final Instant instant;

  public IsAround(final Instant instant) {
    this.instant = instant;
  }

  @Override
  public void describeTo(final Description description) {
    description.appendValue(instant);
  }

  @Override
  protected boolean matchesSafely(final Instant item, final Description mismatchDescription) {
    if (instant.minusSeconds(MARGIN).isAfter(item) || instant.plusSeconds(MARGIN).isBefore(item)) {
      mismatchDescription.appendText("was ").appendValue(item);
      return false;
    }
    return true;
  }
}

Increase "around" margin as tests are running quite slowly sometimes.


package com.grayben.riskExtractor.htmlScorer.partScorers.elementScorers;

import com.grayben.riskExtractor.htmlScorer.partScorers.Scorer;
import org.jsoup.nodes.Element;
import org.jsoup.parser.Tag;

/**
 * Score the segmentation of an {@link org.jsoup.nodes.Element} based upon the {@link org.jsoup.parser.Tag} it contains.
 */
public class SegmentationElementScorer extends Scorer<Element> {

	public final static String SCORE_LABEL = "element-segmentation";

	Scorer<Tag> tagScorer;

	public SegmentationElementScorer(Scorer<Tag> tagScorer){
		super(SCORE_LABEL);
		this.tagScorer = tagScorer;
	}

	@Override
	public int score(Element input) {
		validateScoreInput(input);
		int score = tagScorer.score(input.tag());
		return score;
	}

	private void validateScoreInput(Element input){
		if (input == null){
			throw new NullPointerException(
					"The input cannot be null"
			);
		}
		if(input.attributes() == null){
			throw new NullPointerException(
					"the input.attributes cannot be null"
			);
		}
	}

}

package com.grayben.riskExtractor.htmlScorer.partScorers.elementScorers;

import com.grayben.riskExtractor.htmlScorer.partScorers.Scorer;
import com.grayben.riskExtractor.htmlScorer.partScorers.tagScorers.TagSegmentationScorer;
import org.jsoup.nodes.Element;
import org.jsoup.parser.Tag;

/**
 * Score the segmentation of an {@link org.jsoup.nodes.Element} based upon the {@link org.jsoup.parser.Tag} it contains.
 */
public class SegmentationElementScorer extends Scorer<Element> {

	public final static String SCORE_LABEL = "element-segmentation";

	Scorer<Tag> tagScorer;

	public SegmentationElementScorer(TagSegmentationScorer tagScorer){
		super(SCORE_LABEL);
		this.tagScorer = tagScorer;
	}

	@Override
	public int score(Element input) {
		validateScoreInput(input);
		int score = tagScorer.score(input.tag());
		return score;
	}

	private void validateScoreInput(Element input){
		if (input == null){
			throw new NullPointerException(
					"The input cannot be null"
			);
		}
		if(input.attributes() == null){
			throw new NullPointerException(
					"the input.attributes cannot be null"
			);
		}
	}

}

Make constructor param more specific


package components;

import com.badlogic.ashley.core.Component;
import dataObjects.Profile;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Random;

/**
 * Created by Thagus on 19/10/16.
 */
public class ProfileComponent implements Component{
    public CityBlockComponent home, work;
    public Profile profile;

    public ProfileComponent(Profile profile, HashMap<CityBlockComponent.BlockType, ArrayList<CityBlockComponent>> cityBlocksIndex){
        this.profile = profile;
        Random random = new Random();

        //Select the home of the user
        home = cityBlocksIndex.get(CityBlockComponent.BlockType.RESIDENTIAL).get(random.nextInt(cityBlocksIndex.get(CityBlockComponent.BlockType.RESIDENTIAL).size()));

        //Define the work block
        if(profile.isHomeWorker()){ //If he/she works from home, the work block ant the home block are the same
            work = home;
        }
        else{
            switch(profile.getWorkArea()){  //We must select the work block according the profession
                case RESIDENTIAL:
                case BUSINESS:
                case SHOPPING:
                case PARK:
                    work = cityBlocksIndex.get(profile.getWorkArea()).get(random.nextInt(cityBlocksIndex.get(profile.getWorkArea()).size()));
                    break;
                case TRAFFIC:
                    work = null;
                    break;
            }
        }
    }
}

package components;

import com.badlogic.ashley.core.Component;
import dataObjects.Profile;
import javafx.scene.shape.Circle;
import utils.Constants;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Random;

/**
 * Created by Thagus on 19/10/16.
 */
public class ProfileComponent implements Component{
    public CityBlockComponent home, work;
    public Profile profile;

    public ProfileComponent(Profile profile, HashMap<CityBlockComponent.BlockType, ArrayList<CityBlockComponent>> cityBlocksIndex, Circle circleToReposition){
        this.profile = profile;
        Random random = new Random();

        //Select the home of the user
        home = cityBlocksIndex.get(CityBlockComponent.BlockType.RESIDENTIAL).get(random.nextInt(cityBlocksIndex.get(CityBlockComponent.BlockType.RESIDENTIAL).size()));
        circleToReposition.setCenterX(home.block.getX() + Constants.BLOCK_SIZE/2);
        circleToReposition.setCenterY(home.block.getY() + Constants.BLOCK_SIZE/2);

        //Define the work block
        if(profile.isHomeWorker()){ //If he/she works from home, the work block ant the home block are the same
            work = home;
        }
        else{
            switch(profile.getWorkArea()){  //We must select the work block according the profession
                case RESIDENTIAL:
                case BUSINESS:
                case SHOPPING:
                case PARK:
                    work = cityBlocksIndex.get(profile.getWorkArea()).get(random.nextInt(cityBlocksIndex.get(profile.getWorkArea()).size()));
                    break;
                case TRAFFIC:
                    work = null;
                    break;
            }
        }
    }
}

Set user circle at home


package de.espend.idea.php.annotation.doctrine.action;

import com.intellij.openapi.editor.Editor;
import com.intellij.psi.PsiDocumentManager;
import com.intellij.psi.PsiFile;
import com.jetbrains.php.codeInsight.PhpCodeInsightUtil;
import com.jetbrains.php.lang.psi.elements.PhpClass;
import com.jetbrains.php.lang.psi.elements.PhpPsiElement;
import de.espend.idea.php.annotation.doctrine.util.DoctrineUtil;
import de.espend.idea.php.annotation.util.PhpDocUtil;
import de.espend.idea.php.annotation.util.PhpElementsUtil;
import org.jetbrains.annotations.NotNull;

/**
 * @author Daniel Espendiller <daniel@espendiller.net>
 */
public class DoctrineEmbeddedClassAnnotationGenerateAction extends DoctrineClassGeneratorAction {
    @NotNull
    @Override
    protected String supportedClass() {
        return "Doctrine\\ORM\\Mapping\\Embedded";
    }

    protected void execute(@NotNull Editor editor, @NotNull PhpClass phpClass, @NotNull PsiFile psiFile) {
        // insert ORM alias
        PhpPsiElement scopeForUseOperator = PhpCodeInsightUtil.findScopeForUseOperator(phpClass.getFirstChild());
        if(scopeForUseOperator != null) {
            PhpElementsUtil.insertUseIfNecessary(scopeForUseOperator, DoctrineUtil.DOCTRINE_ORM_MAPPING, "Embedded");
            PsiDocumentManager.getInstance(psiFile.getProject()).doPostponedOperationsAndUnblockDocument(editor.getDocument());
        }

        PhpDocUtil.addClassEmbeddedDocs(phpClass, editor.getDocument(), psiFile);
    }
}

package de.espend.idea.php.annotation.doctrine.action;

import com.intellij.openapi.editor.Editor;
import com.intellij.psi.PsiDocumentManager;
import com.intellij.psi.PsiFile;
import com.jetbrains.php.codeInsight.PhpCodeInsightUtil;
import com.jetbrains.php.lang.psi.elements.PhpClass;
import com.jetbrains.php.lang.psi.elements.PhpPsiElement;
import de.espend.idea.php.annotation.doctrine.util.DoctrineUtil;
import de.espend.idea.php.annotation.util.PhpDocUtil;
import de.espend.idea.php.annotation.util.PhpElementsUtil;
import org.jetbrains.annotations.NotNull;

/**
 * @author Daniel Espendiller <daniel@espendiller.net>
 */
public class DoctrineEmbeddedClassAnnotationGenerateAction extends DoctrineClassGeneratorAction {
    @NotNull
    @Override
    protected String supportedClass() {
        return "Doctrine\\ORM\\Mapping\\Embedded";
    }

    protected void execute(@NotNull Editor editor, @NotNull PhpClass phpClass, @NotNull PsiFile psiFile) {
        // insert ORM alias
        PhpPsiElement scopeForUseOperator = PhpCodeInsightUtil.findScopeForUseOperator(phpClass.getFirstChild());
        if(scopeForUseOperator != null) {
            PhpElementsUtil.insertUseIfNecessary(scopeForUseOperator, DoctrineUtil.DOCTRINE_ORM_MAPPING, "ORM");
            PsiDocumentManager.getInstance(psiFile.getProject()).doPostponedOperationsAndUnblockDocument(editor.getDocument());
        }

        PhpDocUtil.addClassEmbeddedDocs(phpClass, editor.getDocument(), psiFile);
    }
}

Use ORM alias for embedded classes


package com.openxc.measurements;

import com.openxc.units.Degree;
import com.openxc.util.Range;

public class SteeringWheelAngle extends Measurement<Degree>
        implements VehicleMeasurement {
    private final static Range<Degree> RANGE =
        new Range<Degree>(new Degree(-400), new Degree(400));
    public final static String ID = "SteeringWheelAngle";

    public SteeringWheelAngle(double value) {
        super(new Degree(value), RANGE);
    }
    public SteeringWheelAngle(Degree value) {
        super(value, RANGE);
    }
}

package com.openxc.measurements;

import com.openxc.units.Degree;
import com.openxc.util.Range;

public class SteeringWheelAngle extends Measurement<Degree>
        implements VehicleMeasurement {
    private final static Range<Degree> RANGE =
        new Range<Degree>(new Degree(-400), new Degree(400));
    public final static String ID = "SteeringWheelAngle";

    public SteeringWheelAngle(Double value) {
        super(new Degree(value), RANGE);
    }
    public SteeringWheelAngle(Degree value) {
        super(value, RANGE);
    }
}

Use proper Double type in numeric measurement constructor.


/**
 * Created by Siclait on 18/7/16.
 */
import JSONTools.ResponseError;

import static JSONTools.JSONUtil.json;
import static spark.Spark.after;
import static spark.Spark.get;

public class JSONServiceController {

    public JSONServiceController() {
        // Fetch All Urls
        get("/json/allurls", (req, res) -> DatabaseManager.FetchAllURL(), json());

        // Fetch Specific Short Url
        get("/json/original/:short",  (req, res) -> {
            String shortURL = req.params(":short");

            String url = DatabaseManager.FetchOriginalURL(shortURL);

            if(url != null)
                return url;

            res.status(400);
            return new ResponseError("No url with id %s found", shortURL);

        }, json());

        after("/json/*",(req, res) -> {res.type("application/json");});
    }
}

/**
 * Created by Siclait on 18/7/16.
 */
import Entity.User;
import JSONTools.ResponseError;
import org.h2.engine.Database;

import static JSONTools.JSONUtil.json;
import static spark.Spark.after;
import static spark.Spark.get;

public class JSONServiceController {

    public JSONServiceController() {
        // Fetch All Urls
        get("/json/allurls", (req, res) -> DatabaseManager.FetchAllURL(), json());

        // Fetch Specific Short Url
        get("/json/original/:short",  (req, res) -> {
            String shortURL = req.params(":short");

            String url = DatabaseManager.FetchOriginalURL(shortURL);

            if(url != null)
                return url;

            res.status(400);
            return new ResponseError("No url with id %s found", shortURL);

        }, json());

        // Fetch All Users
        get("/json/allusers", (req, res) -> DatabaseManager.FetchAllUsers(), json());

        // Fetch Specific User
        get("/json/user/:username", (req, res) -> {
            String username = req.params(":username");

            User user = DatabaseManager.FetchUser(username);

            if(user != null)
                return user;

            res.status(400);
            return new ResponseError("No user with id %s found", username);

        }, json());

        after("/json/*",(req, res) -> {res.type("application/json");});
    }
}

Add find User json function


package org.jbake.util;

import org.jbake.app.ContentStore;
import org.jbake.app.DocumentList;

import java.util.Map;

public class DataFileUtil {
    private ContentStore db;
    private String defaultDocType;

    public DataFileUtil(ContentStore db, String defaultDocType) {
        this.db = db;
        this.defaultDocType = defaultDocType;
    }

    public Map<String, Object> get(String ref) {
        DocumentList docs = db.getDocumentByUri(defaultDocType, ref);
        if (docs.size() == 1) {
            return docs.get(0);
        }
        return null;
    }
}

package org.jbake.util;

import org.jbake.app.ContentStore;
import org.jbake.app.DocumentList;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

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

public class DataFileUtil {

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

    private ContentStore db;
    private String defaultDocType;

    public DataFileUtil(ContentStore db, String defaultDocType) {
        this.db = db;
        this.defaultDocType = defaultDocType;
    }

    public Map<String, Object> get(String ref) {
        Map<String, Object> result = new HashMap<>();
        DocumentList docs = db.getDocumentByUri(defaultDocType, ref);
        if (docs.isEmpty()) {
            LOGGER.warn("Unable to locate content for ref: {}", ref);
        } else {
            if (docs.size() == 1) {
                result = docs.get(0);
            } else {
                LOGGER.warn("Located multiple hits for ref: {}", ref);
            }
        }
        return result;
    }
}

Return empty Map instead of null. Added logging.


package team498.robot.commands;

import edu.wpi.first.wpilibj.command.Command;
import team498.robot.Helpers;
import team498.robot.Operator;
import team498.robot.subsystems.Drivetrain;
import team498.robot.subsystems.Gyro;

public class Drive extends Command {

    private static final double CORRECTION_GAIN = 0.03;

    private Operator operator = Operator.getOperator();

    private Drivetrain drivetrain;
    private Gyro gyro;

    public Drive() {
        super("Drive");

        // Acquire control of subsystems
        requires(this.drivetrain = Drivetrain.getDrivetrain());
        requires(this.gyro = Gyro.getGyro());

    }

    protected void initialize() {
        gyro.resetAngle();
    }

    protected void execute() {

        // Get move and rotate input values from the controller
        double move = operator.getRightTriggerAxis();
        double rotate = operator.getLeftXAxis();

        // Apply drift correction when going straight
        if(rotate == 0) {
           // Calculate how much correction is need to move straight
            rotate = Helpers.rotateToTarget(gyro.getAngle(), 0, 0, CORRECTION_GAIN);
        }

        // Drive robot
        drivetrain.drive(move, rotate);

    }

    protected void interrupted() {
        end();
    }

    @Override
    protected boolean isFinished() {
        return false;
    }

    protected void end() {
        drivetrain.stop();
    }

}

package team498.robot.commands;

import edu.wpi.first.wpilibj.command.Command;
import team498.robot.Helpers;
import team498.robot.Operator;
import team498.robot.subsystems.Drivetrain;
import team498.robot.subsystems.Gyro;

public class Drive extends Command {

    private static final double CORRECTION_GAIN = 0.03;

    private Operator operator = Operator.getOperator();

    private Drivetrain drivetrain;
    private Gyro gyro;

    public Drive() {
        super("Drive");

        // Acquire control of subsystems
        requires(this.drivetrain = Drivetrain.getDrivetrain());
        requires(this.gyro = Gyro.getGyro());

    }

    protected void initialize() {
        gyro.resetAngle();
    }

    protected void execute() {

        // Get move and rotate input values from the controller
        double move = operator.getRightTriggerAxis();
        double rotate = operator.getLeftXAxis();

        // Apply drift correction when going straight
        if(rotate == 0) {
           // Calculate how much correction is need to move straight
            rotate = Helpers.rotateToTarget(gyro.getAngle(), 0, 0, CORRECTION_GAIN);
        }
        else {
            gyro.resetAngle();
        }

        // Drive robot
        drivetrain.drive(move, rotate);

    }

    protected void interrupted() {
        end();
    }

    @Override
    protected boolean isFinished() {
        return false;
    }

    protected void end() {
        drivetrain.stop();
    }

}

Add gyro reset for drift correction


package forager.ui;

import com.beust.jcommander.Parameter;
import com.beust.jcommander.Parameters;

import forager.server.Overlord;

@Parameters(separators = "=",
        commandDescription = "Starts a forager master server")
public class Server implements CommandLauncher {

    public static final int DEFAULT_PORT = 53380;
    @Parameter(names = { "-p", "--port" }, description = "Server port")
    private int port = DEFAULT_PORT;

    @Override
    public void launch() throws Exception {
        Overlord server = new Overlord(port);
        server.start();
    }
}

package forager.ui;

import com.beust.jcommander.Parameter;
import com.beust.jcommander.Parameters;

import forager.server.Overlord;

@Parameters(separators = "=",
        commandDescription = "Starts a forager master server")
public class Server implements CommandLauncher {

    public static final int DEFAULT_PORT = 53380;
    public static final String DEFAULT_TASKLIST = "tasklist";

    @Parameter(names = { "-p", "--port" }, description = "Server port")
    private int port = DEFAULT_PORT;

    @Parameter(names = { "-t", "--task-list" },
            description = "Task list location")
    private String taskList = DEFAULT_TASKLIST;

    @Override
    public void launch() throws Exception {
        Overlord server = new Overlord(port, taskList);
        server.start();
    }
}

Add task list parameter and default


package org.jetbrains.yaml;

import com.intellij.lang.Language;
import org.jetbrains.annotations.NotNull;

/**
 * @author oleg
 */
public class YAMLLanguage extends Language {
  public static final YAMLLanguage INSTANCE = new YAMLLanguage();

  private YAMLLanguage() {
    super("yaml");
  }

  @NotNull
  @Override
  public String getDisplayName() {
    return "Yaml";
  }
}

package org.jetbrains.yaml;

import com.intellij.lang.Language;
import org.jetbrains.annotations.NotNull;

/**
 * @author oleg
 */
public class YAMLLanguage extends Language {
  public static final YAMLLanguage INSTANCE = new YAMLLanguage();

  private YAMLLanguage() {
    super("yaml");
  }

  @NotNull
  @Override
  public String getDisplayName() {
    return "YAML";
  }
}

Fix YAML Language display name


package com.ippon.jug.slip;

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.net.InetAddress;
import java.net.UnknownHostException;

@RestController
public class SlipController {

    @RequestMapping(value = "/request")
    public String getRequest() throws InterruptedException, UnknownHostException {
        this.doSlip();
        return "Hello I'm " + InetAddress.getLocalHost().getHostName();
    }

    private static final int SLEEP_MILLIS = 50;

    private synchronized void doSlip() throws InterruptedException {
        Thread.sleep(SLEEP_MILLIS);
    }

    @RequestMapping(value = "/dockerHealth")
    public ResponseEntity<Void> getHealth() {
        return new ResponseEntity<Void>(HttpStatus.INTERNAL_SERVER_ERROR);
    }
}

package com.ippon.jug.slip;

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.nio.file.Files;
import java.nio.file.Paths;

@RestController
public class SlipController {

    @RequestMapping(value = "/request")
    public String getRequest() throws InterruptedException, UnknownHostException {
        this.doSlip();

        StringBuilder builder = new StringBuilder()
                .append("Hello I'm ")
                .append(InetAddress.getLocalHost().getHostName())
                .append(". My little secret is ... ");
        try {
            Files.readAllLines(Paths.get("/run/secrets/bdx"))
                    .forEach(builder::append);
        } catch (IOException e) {
            // No secret here
            builder.append(" UNKNOWN !");
        }
        return builder.toString();
    }

    private static final int SLEEP_MILLIS = 50;

    private synchronized void doSlip() throws InterruptedException {
        Thread.sleep(SLEEP_MILLIS);
    }

    @RequestMapping(value = "/dockerHealth")
    public ResponseEntity<Void> getHealth() {
        return new ResponseEntity<Void>(HttpStatus.INTERNAL_SERVER_ERROR);
    }
}

Add secrets read to the slip application


package city;

import utils.Helper;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class Intersection {
    public Date nextTime;
    public int calls = 0;
    public int index;
    final static int MAX_CALLS = 4;

    public List<Integer> connections = new ArrayList<Integer>();

    public Intersection(int index, List<Integer> connections) {
        this.index = index;
        this.connections = connections;
    }

    public Intersection() {
    }

//    public void nextTime(Date currentTime){
//        if(calls < MAX_CALLS)
//            this.nextTime = Helper.nextCall(currentTime);
//        else
//            this.nextTime = null;
//    }

    public void receiveCall() {
        this.calls++;
    }

    @Override
    public String toString() {
        return "Intersection{" +
                "nextTime=" + nextTime +
                ", calls=" + calls +
                ", index=" + index +
                ", connections=" + connections +
                '}';
    }

}

package city;

import utils.Helper;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class Intersection {
    public int calls = 0;
    public int index;

    public List<Integer> connections = new ArrayList<Integer>();

    public Intersection(int index, List<Integer> connections) {
        this.index = index;
        this.connections = connections;
    }

    public Intersection() {
    }

    public void receiveCall() {
        this.calls++;
    }

    @Override
    public String toString() {
        return "Intersection{" +
                "nextTime=" + nextTime +
                ", calls=" + calls +
                ", index=" + index +
                ", connections=" + connections +
                '}';
    }

}

Clean intersection class. Moved method to Main class and not intersection


package com.alexfu.sqlitequerybuilder.utils;

public class StringUtils {
  public static String join(CharSequence delimiter, String... array) {
    return join(delimiter, (Object[]) array);
  }

  public static String join(CharSequence delimiter, Object... array) {
    StringBuilder sb = new StringBuilder();
    boolean firstTime = true;
    for (Object object : array) {
      if (firstTime) {
        firstTime = false;
      } else {
        sb.append(delimiter);
      }
      sb.append(object);
    }
    return sb.toString();
  }
}

package com.alexfu.sqlitequerybuilder.utils;

public class StringUtils {
  public static String join(CharSequence delimiter, String... array) {
    return join(delimiter, (Object[]) array);
  }

  public static String join(CharSequence delimiter, Object... array) {
    StringBuilder sb = new StringBuilder();

    for (int i = 0, size = array.length; i < size; i++) {
      if (i > 0) {
        sb.append(delimiter);
      }
      sb.append(array[i]);
    }
    return sb.toString();
  }
}

Change back to classical for loop.


package logUtils;

import java.time.LocalDateTime;
import java.util.concurrent.LinkedBlockingQueue;

public class Logger
{
    private static boolean shouldLog = false,
        threadStarted = false;

    private static LinkedBlockingQueue<String> messages = new LinkedBlockingQueue<>();

    private Logger() {}

    public static synchronized void log(String message)
    {
        if (! threadStarted && shouldLog)
        {
            new Thread(() ->
            {
                while (true)
                {
                    if (messages.size() > 0)
                    {
                        try
                        {
                            System.out.println(getTime() + " " + messages.take());
                        }
                        catch (InterruptedException e)
                        {
                            log(e.getMessage());
                        }
                    }
                }
            }).start();
            threadStarted = true;
        }
        messages.add(message);
    }

    public static void setShouldLog(boolean log) { shouldLog = log; }

    private static String getTime()
    {
        return "[" + LocalDateTime.now().getHour() + ":" +
            LocalDateTime.now().getMinute() + ":" +
            LocalDateTime.now().getSecond() + "]";
    }
}

package logUtils;

import java.time.LocalDateTime;
import java.util.concurrent.LinkedBlockingQueue;

public class Logger
{
    private static boolean shouldLog = false;

    private Logger() {}

    public static synchronized void log(String message)
    {
        if (shouldLog)
            System.out.println(getTime() + " " + message);
    }

    public static void setShouldLog(boolean log) { shouldLog = log; }

    private static String getTime()
    {
        return "[" + LocalDateTime.now().getHour() + ":" +
            LocalDateTime.now().getMinute() + ":" +
            LocalDateTime.now().getSecond() + "]";
    }
}

Reset the logging stuff. - Logging would full use a thread instead of using it when necessary


package com.github._1element;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.orm.jpa.EntityScan;
import org.springframework.context.annotation.Bean;
import org.springframework.data.jpa.convert.threeten.Jsr310JpaConverters;
import org.thymeleaf.extras.java8time.dialect.Java8TimeDialect;

@EntityScan(basePackageClasses = {SurveillanceCenterApplication.class, Jsr310JpaConverters.class})
@SpringBootApplication
public class SurveillanceCenterApplication {

  @Bean
  public Java8TimeDialect java8TimeDialect() {
    return new Java8TimeDialect();
  }

  public static void main(String[] args) {
    SpringApplication.run(SurveillanceCenterApplication.class, args);
  }

}

package com.github._1element;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.orm.jpa.EntityScan;
import org.springframework.context.annotation.Bean;
import org.springframework.data.jpa.convert.threeten.Jsr310JpaConverters;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.thymeleaf.extras.java8time.dialect.Java8TimeDialect;

@EntityScan(basePackageClasses = {SurveillanceCenterApplication.class, Jsr310JpaConverters.class})
@SpringBootApplication
@EnableScheduling
public class SurveillanceCenterApplication {

  @Bean
  public Java8TimeDialect java8TimeDialect() {
    return new Java8TimeDialect();
  }

  public static void main(String[] args) {
    SpringApplication.run(SurveillanceCenterApplication.class, args);
  }

}

Add missing enable scheduling annotation


package com.github.lunatrius.core.world.chunk;

import net.minecraft.util.math.BlockPos;

import java.util.Random;

public class ChunkHelper {
    private static final Random RANDOM = new Random();

    public static boolean isSlimeChunk(final long seed, final BlockPos pos) {
        final int x = pos.getX() >> 4;
        final int z = pos.getZ() >> 4;
        RANDOM.setSeed(seed + (x * x * 4987142) + (x * 5947611) + (z * z * 4392871) + (z * 389711) ^ 987234911);
        return RANDOM.nextInt(10) == 0;
    }
}

package com.github.lunatrius.core.world.chunk;

import net.minecraft.util.math.BlockPos;

import java.util.Random;

public class ChunkHelper {
    private static final Random RANDOM = new Random();

    public static boolean isSlimeChunk(final long seed, final BlockPos pos) {
        final long x = pos.getX() >> 4;
        final long z = pos.getZ() >> 4;
        RANDOM.setSeed(seed + (x * x * 4987142L) + (x * 5947611L) + (z * z * 4392871L) + (z * 389711L) ^ 987234911L);
        return RANDOM.nextInt(10) == 0;
    }
}

Use long for x/z instead of int to prevent a MAX_INT overflow. Fixes gh-40


package cfvbaibai.cardfantasy.engine;

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

import cfvbaibai.cardfantasy.CardFantasyRuntimeException;
import cfvbaibai.cardfantasy.Randomizer;
import cfvbaibai.cardfantasy.data.Race;

public class Deck extends CardPile {

    public Deck(Collection <CardInfo> cards) {
        List <CardInfo> cloned = new ArrayList<CardInfo>(cards);
        this.getCards().addAll(cloned);
    }

    public boolean isEmpty() {
        return this.getCards().isEmpty();
    }

    public CardInfo draw() {
        if (this.getCards().isEmpty()) {
            return null;
        }
        return this.getCards().remove(0);
    }

    public void removeCard(CardInfo card) {
        if (!this.getCards().remove(card)) {
            throw new CardFantasyRuntimeException("Cannot find card in deck: " + card.getShortDesc());
        }
    }

    public void shuffle() {
        Randomizer.getRandomizer().shuffle(this.getCards());
        List<CardInfo> bosses = new ArrayList<CardInfo>();
        for (CardInfo card : this.getCards()) {
            if (card.getRace() == Race.BOSS) {
                bosses.add(card);
            }
        }
        for (CardInfo boss : bosses) {
            this.getCards().remove(boss);
            this.getCards().add(0, boss);
        }
    }
}

package cfvbaibai.cardfantasy.engine;

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

import cfvbaibai.cardfantasy.CardFantasyRuntimeException;
import cfvbaibai.cardfantasy.Randomizer;

public class Deck extends CardPile {

    public Deck(Collection <CardInfo> cards) {
        List <CardInfo> cloned = new ArrayList<CardInfo>(cards);
        this.getCards().addAll(cloned);
    }

    public boolean isEmpty() {
        return this.getCards().isEmpty();
    }

    public CardInfo draw() {
        if (this.getCards().isEmpty()) {
            return null;
        }
        return this.getCards().remove(0);
    }

    public void removeCard(CardInfo card) {
        if (!this.getCards().remove(card)) {
            throw new CardFantasyRuntimeException("Cannot find card in deck: " + card.getShortDesc());
        }
    }

    public void shuffle() {
        Randomizer.getRandomizer().shuffle(this.getCards());
    }
}

Fix deck sorting issue in boss battle


package org.apache.lucene.index;

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

import java.io.IOException;

import org.apache.lucene.store.GCJDirectory;

class GCJSegmentReader extends SegmentReader {

  public final TermDocs termDocs() throws IOException {
    if (directory() instanceof GCJDirectory) {
      return new GCJTermDocs(this);
    } else {
      return super.termDocs();
    }
  }
}

package org.apache.lucene.index;

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

import java.io.IOException;

import org.apache.lucene.store.GCJDirectory;

class GCJSegmentReader extends SegmentReader {

  /** Try to use an optimized native implementation of TermDocs.  The optimized
   * implementation can only be used when the segment's directory is a
   * GCJDirectory and it is not in compound format.  */
  public final TermDocs termDocs() throws IOException {
    if (directory() instanceof GCJDirectory       // it's a GCJ directory
        && this.cfsReader == null) {              // & not in compound format
      return new GCJTermDocs(this);               // so can use GCJTermDocs
    } else {
      return super.termDocs();
    }
  }
}

Disable optimized implementation with compound format.


/**
 * Copyright (c) 2014-present, Facebook, Inc.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */

package com.facebook.react.fabric;

public interface FabricBinder {

  void setBinding(FabricBinding binding);

}

/**
 * Copyright (c) 2014-present, Facebook, Inc.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */

package com.facebook.react.fabric;

public interface FabricBinder<T extends FabricBinding> {

  void setBinding(T binding);

}

Initialize FabricXX C++ code and register rootview


package io.github.plastix.forage.util;

public class RxUtilsTest {
}

package io.github.plastix.forage.util;

import org.junit.Test;

import rx.Subscription;

import static com.google.common.truth.Truth.assert_;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;

public class RxUtilsTest {

    @Test
    public void safeUnsubscribe_handleNullSubscription() {
        try {
            RxUtils.safeUnsubscribe(null);
        } catch (Exception e) {
            assert_().fail("RxUtils safeUnsubscribe threw an unexpected error!", e);
        }
    }

    @Test
    public void safeUnsubscribe_unsubscribeSubscriptionCorrectly() {
        Subscription subscription = mock(Subscription.class);

        RxUtils.safeUnsubscribe(subscription);

        verify(subscription, times(1)).unsubscribe();
    }

    @Test
    public void safeUnsubscribe_onlyUnsubscribeActiveSubscriptions() {
        Subscription subscription = mock(Subscription.class);
        when(subscription.isUnsubscribed()).thenReturn(true);

        RxUtils.safeUnsubscribe(subscription);

        verify(subscription, never()).unsubscribe();
    }
}

Add unit tests for RxUtils.safeUnsubscribe


package com.aesthetikx.hubski.model;

import java.net.URL;
import java.util.List;

public class Comment {

    private String username;
    private URL userLink;
    private URL link;
    private String body;
    private String age;
    private int score;
    private Comment parent;
    private List<Comment> children;

    public Comment(String username, URL userLink, URL link, String body, String age, int score,
                   Comment parent, List<Comment> children) {
        this.username = username;
        this.userLink = userLink;
        this.link = link;
        this.body = body;
        this.age = age;
        this.score = score;
        this.parent = parent;
        this.children = children;
    }

    public String getUsername() {
        return username;
    }

    public URL getUserLink() {
        return userLink;
    }

    public URL getLink() {
        return link;
    }

    public String getBody() {
        return body;
    }

    public String getAge() {
        return age;
    }

    public int getScore() {
        return score;
    }

    public Comment getParent() {
        return parent;
    }

    public List<Comment> getChildren() {
        return children;
    }

}

package com.aesthetikx.hubski.model;

import com.aesthetikx.hubski.adapter.BaseTreeListItem;
import com.aesthetikx.hubski.adapter.TreeListItem;

import java.net.URL;
import java.util.List;

public class Comment extends BaseTreeListItem implements TreeListItem {

    private String username;
    private URL userLink;
    private URL link;
    private String body;
    private String age;
    private int score;
    private List<Comment> children;

    public Comment(String username, URL userLink, URL link, String body, String age, int score, List<Comment> children, int depth) {
        super(children, true, true, depth);
        this.username = username;
        this.userLink = userLink;
        this.link = link;
        this.body = body;
        this.age = age;
        this.score = score;
        this.children = children;
    }

    public String getUsername() {
        return username;
    }

    public URL getUserLink() {
        return userLink;
    }

    public URL getLink() {
        return link;
    }

    public String getBody() {
        return body;
    }

    public String getAge() {
        return age;
    }

    public int getScore() {
        return score;
    }

    public List<Comment> getChildren() {
        return children;
    }

    public void print(int depth) {
        String tab = "";
        for (int i = 0; i < depth; ++i) tab += "\t";
        System.out.println(tab + getUsername());
        for (Comment child: getChildren()) {
            child.print(depth + 1);
        }
    }

}

Add depth to comment, implement tree list item


package GameNationBackEnd.Documents;

import com.sun.org.apache.xpath.internal.operations.Bool;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.DBRef;
import org.springframework.data.mongodb.core.mapping.Document;

/**
 * Created by tijs on 30/11/2016.
 */
@Document
public class Friend {
    @Id
    private String id;

    @DBRef
    private User sender;

    @DBRef
    private User receiver;

    private Boolean accepted;
    private Boolean sended;

    public Friend(){
        sender = new User();
        receiver = new User();
    }

    public Friend(User sender, User receiver){
        this.sender = sender;
        this.receiver = receiver;
        this.sended = true;
    }

    public User getSender() {
        return sender;
    }
    public User getReceiver() {
        return receiver;
    }
    public String getId() {
        return id;
    }
    public Boolean isAccepted(){ return accepted; }
    public Boolean getSended(){ return sended; }

    public void setAccepted(Boolean a){ this.accepted = a; }
    public void setSended(Boolean s){ this.sended = s; }

}

package GameNationBackEnd.Documents;

import com.sun.org.apache.xpath.internal.operations.Bool;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.DBRef;
import org.springframework.data.mongodb.core.mapping.Document;

/**
 * Created by tijs on 30/11/2016.
 */
@Document
public class Friend {
    @Id
    private String id;

    @DBRef
    private User sender;

    @DBRef
    private User receiver;

    private Boolean accepted;
    private Boolean sended;

    public Friend(){
        sender = new User();
        receiver = new User();
    }

    public Friend(User sender, User receiver) {
        this(sender, receiver, false);
    }

    public Friend(User sender, User receiver, boolean accepted){
        this.sender = sender;
        this.receiver = receiver;
        this.sended = true;

        this.accepted = accepted;
    }

    public User getSender() {
        return sender;
    }
    public User getReceiver() {
        return receiver;
    }
    public String getId() {
        return id;
    }
    public Boolean isAccepted(){ return accepted; }
    public Boolean getSended(){ return sended; }

    public void setAccepted(Boolean a){ this.accepted = a; }
    public void setSended(Boolean s){ this.sended = s; }

}

Add overload method for easier immediate friend accepting in dev


package flow.netbeans.markdown.highlighter;

import java.util.Collection;
import java.util.EnumSet;
import org.netbeans.spi.lexer.LanguageHierarchy;
import org.netbeans.spi.lexer.Lexer;
import org.netbeans.spi.lexer.LexerRestartInfo;

public class MarkdownLanguageHierarchy extends LanguageHierarchy<MarkdownTokenId> {

    @Override
    protected synchronized Collection<MarkdownTokenId> createTokenIds () {
        return EnumSet.allOf (MarkdownTokenId.class);
    }

    @Override
    protected Lexer<MarkdownTokenId> createLexer (LexerRestartInfo<MarkdownTokenId> info) {
        return new MarkdownLexer(info);
    }

    @Override
    protected String mimeType () {
        return "text/x-markdown";
    }

}

package flow.netbeans.markdown.highlighter;

import flow.netbeans.markdown.csl.MarkdownLanguageConfig;
import java.util.Collection;
import java.util.EnumSet;
import org.netbeans.spi.lexer.LanguageHierarchy;
import org.netbeans.spi.lexer.Lexer;
import org.netbeans.spi.lexer.LexerRestartInfo;

public class MarkdownLanguageHierarchy extends LanguageHierarchy<MarkdownTokenId> {

    @Override
    protected synchronized Collection<MarkdownTokenId> createTokenIds () {
        return EnumSet.allOf (MarkdownTokenId.class);
    }

    @Override
    protected Lexer<MarkdownTokenId> createLexer (LexerRestartInfo<MarkdownTokenId> info) {
        return new MarkdownLexer(info);
    }

    @Override
    protected String mimeType () {
        return MarkdownLanguageConfig.MIME_TYPE;
    }

}

Make use of MarkdownLanguageConfig constants


package org.freedesktop;

import java.io.IOException;
import java.io.Writer;

public class DesktopEntryWriter {

    private IniStyleFileWriter delgate;

    /**
     * @param writer the writer must be using a utf-8 encoding
     */
    public DesktopEntryWriter(Writer writer) {
        this.delgate = new IniStyleFileWriter(writer);
    }

    public void write(DesktopEntry file) throws IOException {
        delgate.write(file);
    }
}

package org.freedesktop;

import java.io.IOException;
import java.io.Writer;

public class DesktopEntryWriter {

    private IniStyleFileWriter delegate;

    /**
     * @param writer the writer must be using a utf-8 encoding
     */
    public DesktopEntryWriter(Writer writer) {
        this.delegate = new IniStyleFileWriter(writer);
    }

    public void write(DesktopEntry file) throws IOException {
        delegate.write(file);
    }
}

Fix typo in variable name


package com.elmakers.mine.bukkit.api.effect;

import org.bukkit.Color;
import org.bukkit.Effect;
import org.bukkit.Location;
import org.bukkit.Sound;
import org.bukkit.block.Block;

import com.elmakers.mine.bukkit.api.block.MaterialAndData;
import org.bukkit.entity.Entity;

import java.util.Collection;
import java.util.Map;

public interface EffectPlayer {
    public void setEffectPlayList(Collection<EffectPlay> plays);
    public void setEffect(Effect effect);
    public void setEffectData(int data);
    public void setScale(float scale);

    public void setSound(Sound sound);
    public void setSound(Sound sound, float volume, float pitch);
    public void setParameterMap(Map<String, String> parameters);

    public void setDelayTicks(int ticks);

    public void setParticleOverride(String particleType);
    public void setMaterial(MaterialAndData material);
    public void setMaterial(Block block);
    public void setColor(Color color);
    public boolean shouldUseHitLocation();
    public boolean shouldUseWandLocation();
    public boolean shouldUseEyeLocation();

    public void start(Location origin, Location target);
    public void start(Entity origin, Entity target);
    public void start(Location origin, Entity originEntity, Location target, Entity targetEntity);
    public void start(Location origin, Entity originEntity, Location target, Entity targetEntity, Collection<Entity> targets);
}

package com.elmakers.mine.bukkit.api.effect;

import org.bukkit.Color;
import org.bukkit.Effect;
import org.bukkit.Location;
import org.bukkit.Sound;
import org.bukkit.block.Block;

import com.elmakers.mine.bukkit.api.block.MaterialAndData;
import org.bukkit.entity.Entity;

import java.util.Collection;
import java.util.Map;

public interface EffectPlayer {
    public void setEffectPlayList(Collection<EffectPlay> plays);
    public void setEffect(Effect effect);
    public void setEffectData(int data);
    public void setScale(float scale);

    public void setSound(Sound sound);
    public void setSound(Sound sound, float volume, float pitch);
    public void setParameterMap(Map<String, String> parameters);

    public void setDelayTicks(int ticks);

    public void setParticleOverride(String particleType);
    public void setMaterial(MaterialAndData material);
    public void setMaterial(Block block);
    public void setColor(Color color);
    public boolean shouldUseHitLocation();
    public boolean shouldUseWandLocation();
    public boolean shouldUseEyeLocation();
    public boolean shouldUseBlockLocation();

    public void start(Location origin, Location target);
    public void start(Entity origin, Entity target);
    public void start(Location origin, Entity originEntity, Location target, Entity targetEntity);
    public void start(Location origin, Entity originEntity, Location target, Entity targetEntity, Collection<Entity> targets);
}

Add block-based effect target flag


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

/**
 * Implementation of service for interacting with interfaces.
 */
package org.onosproject.net.impl;

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

/**
 * Implementation of service for interacting with interfaces.
 */
package org.onosproject.net.intf.impl;

Fix Javadoc warning due to incorrect package.


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

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

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

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

BREAK BUILD

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

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

Break the build to test Hudson


package liquibase.change.ext;

import liquibase.change.ChangeMetaData;
import liquibase.change.DatabaseChange;
import liquibase.change.core.DropNotNullConstraintChange;
import liquibase.database.Database;
import liquibase.database.ext.HanaDBDatabase;
import liquibase.statement.SqlStatement;
import liquibase.statement.core.SetNullableStatement;

@DatabaseChange(name="dropNotNullConstraint", description = "Makes a column nullable", priority = ChangeMetaData.PRIORITY_DATABASE, appliesTo = "column", since = "3.0")
public class DropNotNullConstraintChangeHana extends
		DropNotNullConstraintChange {

	@Override
	public boolean supports(Database database) {
		return database instanceof HanaDBDatabase;
	}

	@Override
	public SqlStatement[] generateStatements(Database database) {
    	if (getSchemaName() == null) {
    		setSchemaName(database.getDefaultSchemaName());
    	}
    	String columnDataTypeName = getColumnDataType();
    	if (columnDataTypeName == null && getSchemaName() != null && database instanceof HanaDBDatabase) {
    		columnDataTypeName = ((HanaDBDatabase) database).getColumnDataTypeName(getCatalogName(), getSchemaName(), getTableName(), getColumnName());
		}

    	return new SqlStatement[] { new SetNullableStatement(
                getCatalogName(),
    			getSchemaName(),
    			getTableName(), getColumnName(), columnDataTypeName, true)
    	};

	}

}

package liquibase.change.ext;

import liquibase.change.ChangeMetaData;
import liquibase.change.DatabaseChange;
import liquibase.change.core.DropNotNullConstraintChange;
import liquibase.database.Database;
import liquibase.database.ext.HanaDBDatabase;
import liquibase.statement.SqlStatement;
import liquibase.statement.core.SetNullableStatement;

@DatabaseChange(name="dropNotNullConstraint", description = "Makes a column nullable", priority = ChangeMetaData.PRIORITY_DATABASE, appliesTo = "column", since = "3.0")
public class DropNotNullConstraintChangeHana extends
		DropNotNullConstraintChange {

	@Override
	public boolean supports(Database database) {
		return database instanceof HanaDBDatabase;
	}

	@Override
	public SqlStatement[] generateStatements(Database database) {
		// local variable introduced as superclass's schemaName is used for checksum calculation
		// TODO: is this logic also needed for the inverse?
		String schemaToUse = getSchemaName();
    	if (schemaToUse == null) {
    		schemaToUse = database.getDefaultSchemaName();
    	}
    	String columnDataTypeName = getColumnDataType();
    	if (columnDataTypeName == null && schemaToUse != null && database instanceof HanaDBDatabase) {
    		columnDataTypeName = ((HanaDBDatabase) database).getColumnDataTypeName(getCatalogName(), schemaToUse, getTableName(), getColumnName());
		}

    	return new SqlStatement[] { new SetNullableStatement(
                getCatalogName(),
    			schemaToUse,
    			getTableName(), getColumnName(), columnDataTypeName, true)
    	};

	}

}

Fix checksum failure when reexecuting changesets with dropNotNullConstraint


// 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 com.cloud.agent;

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

import junit.framework.TestCase;

import org.apache.log4j.Logger;

public class TestAgentShell extends TestCase {
    protected final static Logger s_logger = Logger.getLogger(TestAgentShell.class);

    public void testWget() {
        File file = null;
        try {
            file = File.createTempFile("wget", ".html");
            AgentShell.wget("http://www.google.com/", file);

            if (s_logger.isDebugEnabled()) {
                s_logger.debug("file saved to " + file.getAbsolutePath());
            }

        } catch (final IOException e) {
            s_logger.warn("Exception while downloading agent update package, ", e);
        }
    }
}

// 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 com.cloud.agent;

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

import junit.framework.TestCase;

import org.apache.log4j.Logger;

public class TestAgentShell extends TestCase {
    protected final static Logger s_logger = Logger.getLogger(TestAgentShell.class);

    public void testWget() {
        File file = null;
        try {
            file = File.createTempFile("wget", ".html");
            AgentShell.wget("http://www.apache.org/", file);

            if (s_logger.isDebugEnabled()) {
                s_logger.debug("file saved to " + file.getAbsolutePath());
            }

        } catch (final IOException e) {
            s_logger.warn("Exception while downloading agent update package, ", e);
        }
    }
}

Change URL from google as 503 returns from that site cause test to erroneously fail.


package com.pennapps.labs.pennmobile.api;

import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;

public class DiningAPI {
    protected OkHttpClient client;
    protected String BASE_URL = "http://api.pennlabs.org/dining/";

    public DiningAPI(OkHttpClient client) {
        this.client = client;
    }

    public JSONObject getAPIData(String urlPath) {
        Request request = new Request.Builder()
                .url(BASE_URL + urlPath)
                .header("Content-Type", "application/json")
                .build();
        try {
            Response response = client.newCall(request).execute();
            return new JSONObject(response.body().string());
        } catch (JSONException | IOException ignored) {
            return null;
        }
    }

    public JSONObject getVenues() {
        return getAPIData("venues");
    }

    public JSONObject getDailyMenu(int hallID) {
        return getAPIData("daily_menu/" + hallID);
    }
}

package com.pennapps.labs.pennmobile.api;

import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;

public class DiningAPI {
    protected OkHttpClient client;
    protected String BASE_URL = "http://api.pennlabs.org/dining/";

    public DiningAPI(OkHttpClient client) {
        this.client = client;
    }

    public JSONObject getAPIData(String urlPath) {
        Request request = new Request.Builder()
                .url(BASE_URL + urlPath)
                .header("Content-Type", "application/json")
                .build();
        try {
            Response response = client.newCall(request).execute();
            return new JSONObject(response.body().string());
        } catch (JSONException | IOException ignored) {
            return null;
        }
    }

    public JSONObject getDailyMenu(int hallID) {
        return getAPIData("daily_menu/" + hallID);
    }
}

Remove unused dining API method


package org.sejda.impl.sambox.util;

import org.sejda.impl.sambox.component.DefaultPdfSourceOpener;
import org.sejda.model.exception.TaskIOException;
import org.sejda.model.input.PdfStreamSource;
import org.sejda.sambox.pdmodel.PDDocument;

import static org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric;

public class TestUtils {

    public static PDDocument getTestDoc(String name) throws TaskIOException {
        PdfStreamSource source = PdfStreamSource.newInstanceNoPassword(
                TestUtils.class.getClassLoader().getResourceAsStream(name), randomAlphanumeric(16) + ".pdf");

        return new DefaultPdfSourceOpener().open(source).getUnderlyingPDDocument();
    }
}

package org.sejda.impl.sambox.util;

import org.sejda.impl.sambox.component.DefaultPdfSourceOpener;
import org.sejda.model.exception.TaskIOException;
import org.sejda.model.input.PdfFileSource;
import org.sejda.model.input.PdfStreamSource;
import org.sejda.sambox.pdmodel.PDDocument;

import java.io.File;

import static org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric;

public class TestUtils {

    public static PDDocument getTestDoc(String name) throws TaskIOException {
        File file = new File(name);
        if(file.exists()) {
            PdfFileSource source = PdfFileSource.newInstanceNoPassword(file);
            return new DefaultPdfSourceOpener().open(source).getUnderlyingPDDocument();
        }

        PdfStreamSource source = PdfStreamSource.newInstanceNoPassword(
                TestUtils.class.getClassLoader().getResourceAsStream(name), randomAlphanumeric(16) + ".pdf");

        return new DefaultPdfSourceOpener().open(source).getUnderlyingPDDocument();
    }
}

Test doc: support paths to disk file


package net.bloople.stories;

import java.io.IOException;
import java.io.Reader;
import java.util.Scanner;

/**
 * Created by i on 27/05/2016.
 */
public class StoryParser {
    private Scanner scanner;

    public StoryParser(Reader reader) {
        scanner = new Scanner(reader);
        scanner.useDelimiter("(?:\r?\n){2,}+");
    }

    public boolean hasNext() throws IOException {
        return scanner.hasNext();
    }

    public Node next() throws IOException {
        String content = scanner.next();

        if(content.startsWith("#")) {
            return NodeFactory.heading(content);
        }
        else {
            return NodeFactory.paragraph(content);
        }
    }
}

package net.bloople.stories;

import java.io.IOException;
import java.io.Reader;
import java.util.Scanner;

/**
 * Created by i on 27/05/2016.
 */
public class StoryParser {
    private Scanner scanner;

    public StoryParser(Reader reader) {
        scanner = new Scanner(reader);
        scanner.useDelimiter("(?:\r?\n[\u200B\uFEFF]*){2,}+");
    }

    public boolean hasNext() throws IOException {
        return scanner.hasNext();
    }

    public Node next() throws IOException {
        String content = scanner.next();

        if(content.startsWith("#")) {
            return NodeFactory.heading(content);
        }
        else {
            return NodeFactory.paragraph(content);
        }
    }
}

Fix story parsing regexp to ignore ZWSP and ZWNBSP characters between newlines


package org.monospark.spongematchers.type;

import static org.hamcrest.CoreMatchers.not;
import static org.junit.Assert.assertThat;
import static org.monospark.spongematchers.testutil.HamcrestSpongeMatchers.matches;

import org.junit.Test;
import org.monospark.spongematchers.matcher.SpongeMatcher;
import org.monospark.spongematchers.parser.SpongeMatcherParseException;
import org.monospark.spongematchers.parser.element.StringElementParser;
import org.monospark.spongematchers.type.MatcherType;

public class MatcherTypeTest {

    @Test
    public void parseMatcher_MatcherWithConjunctions_ReturnsCorrectMatcher() throws SpongeMatcherParseException {
        String input = "(('test1'|'test2')&!('test2'))";

        SpongeMatcher<String> matcher = MatcherType.STRING.parseMatcher(StringElementParser.parseStringElement(input));

        assertThat(matcher, matches("test1"));
        assertThat(matcher, not(matches("test2")));
    }
}

package org.monospark.spongematchers.type;

import static org.hamcrest.CoreMatchers.not;
import static org.junit.Assert.assertThat;
import static org.monospark.spongematchers.testutil.HamcrestSpongeMatchers.matches;

import org.junit.Test;
import org.monospark.spongematchers.matcher.SpongeMatcher;
import org.monospark.spongematchers.parser.SpongeMatcherParseException;
import org.monospark.spongematchers.parser.element.StringElementParser;
import org.monospark.spongematchers.type.MatcherType;

public class MatcherTypeTest {

    @Test
    public void parseMatcher_MatcherWithConjunctions_ReturnsCorrectMatcher() throws SpongeMatcherParseException {
        String input = "(('test1'|'test2')&!('test2'))";

        SpongeMatcher<String> matcher = MatcherType.STRING.parseMatcher(StringElementParser.parseStringElement(input));

        assertThat(matcher, matches("test1"));
        assertThat(matcher, not(matches("test2")));
    }

    @Test
    public void parseMatcher_WildcardMatcher_ReturnsCorrectMatcher() throws SpongeMatcherParseException {
        String input = "*";

        SpongeMatcher<String> matcher = MatcherType.STRING.parseMatcher(StringElementParser.parseStringElement(input));

        assertThat(matcher, matches("test1"));
        assertThat(matcher, matches("test2"));
    }
}

Add a test method to test wildcard matcher parsing


package Hotel.database;

import Hotel.database.tables.Booking;

import java.sql.*;

public class Connection {
    private final java.sql.Connection connection;
    private static Table customer;
    private static Table booking;
    private static Table room;

    public Connection() throws ClassNotFoundException, SQLException {
        Class.forName("com.mysql.jdbc.Driver");  // Load JDBC driver

        this.connection = DriverManager.getConnection(
                "jdbc:mysql://localhost:3306/Hotel", "root", "fastralee"
        );

        Connection.booking = new Booking(this.connection);
        Connection.booking.setup();
    }
}

package Hotel.database;

import Hotel.database.tables.Booking;

import java.sql.*;

public class Connection {
    private final java.sql.Connection connection;
    private static Table customer;
    private static Table booking;
    private static Table room;

    public Connection() throws ClassNotFoundException, SQLException {
        Class.forName("com.mysql.jdbc.Driver");  // Load JDBC driver

        this.connection = DriverManager.getConnection(
                "jdbc:mysql://localhost:3306/", "root", "fastralee"
        );

        Statement statement = this.connection.createStatement();
        statement.execute("CREATE DATABASE IF NOT EXISTS hotel");
        statement.execute("USE hotel");

        Connection.booking = new Booking(this.connection);
        Connection.booking.setup();
    }
}

Create database if it doesn't exist


package org.jboss.pnc.core.builder;

import org.jboss.pnc.model.ProjectBuildResult;
import org.jboss.pnc.spi.builddriver.BuildJobConfiguration;
import org.jboss.pnc.spi.builddriver.BuildJobDetails;
import org.jboss.pnc.spi.datastore.Datastore;

import javax.inject.Inject;

/**
 * Created by Matej Lazar on 2014-12-15.
 */
public class DatastoreAdapter {

    private Datastore datastore;

    @Inject
    public DatastoreAdapter(Datastore datastore) {
        this.datastore = datastore;
    }

    public void storeResult(BuildJobDetails buildDetails, BuildJobConfiguration buildJobConfiguration) {
        ProjectBuildResult buildResult = new ProjectBuildResult();
        buildResult.setBuildLog(buildDetails.getBuildLog());
        buildResult.setStatus(buildDetails.getBuildStatus());
        buildResult.setProjectBuildConfiguration(buildJobConfiguration.getProjectBuildConfiguration());
        datastore.storeCompletedBuild(buildResult);
    }

}

package org.jboss.pnc.core.builder;

import org.jboss.logging.Logger;
import org.jboss.pnc.model.ProjectBuildResult;
import org.jboss.pnc.spi.builddriver.BuildJobConfiguration;
import org.jboss.pnc.spi.builddriver.BuildJobDetails;
import org.jboss.pnc.spi.datastore.Datastore;

import javax.inject.Inject;

/**
 * Created by Matej Lazar on 2014-12-15.
 */
public class DatastoreAdapter {

    private Datastore datastore;

    private static final Logger log = Logger.getLogger(DatastoreAdapter.class);

    @Inject
    public DatastoreAdapter(Datastore datastore) {
        this.datastore = datastore;
    }

    public void storeResult(BuildJobDetails buildDetails, BuildJobConfiguration buildJobConfiguration) {
        ProjectBuildResult buildResult = new ProjectBuildResult();
        buildResult.setBuildLog(buildDetails.getBuildLog());
        buildResult.setStatus(buildDetails.getBuildStatus());
        buildResult.setProjectBuildConfiguration(buildJobConfiguration.getProjectBuildConfiguration());
        log.tracef("Storing results of %s to datastore.", buildDetails.getJobName());
        datastore.storeCompletedBuild(buildResult);
    }

}

Add logging before storing to datastore.


/*
 * Copyright 2009 Paul Austin
 *
 * 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.oauth.client.httpclient4;

import net.oauth.OAuthAccessor;
import org.apache.http.auth.UsernamePasswordCredentials;

/**
 * @author John Kristian
 */
public class OAuthCredentials extends UsernamePasswordCredentials {

    private final OAuthAccessor accessor;

    public OAuthCredentials(OAuthAccessor accessor) {
        super(accessor.consumer.consumerKey, accessor.consumer.consumerSecret);
        this.accessor = accessor;
    }

    public OAuthAccessor getAccessor() {
        return accessor;
    }

}

/*
 * Copyright 2009 Paul Austin
 *
 * 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.oauth.client.httpclient4;

import net.oauth.OAuthAccessor;
import org.apache.http.auth.UsernamePasswordCredentials;

/**
 * An OAuthAccessor, to be used as credentials for an AuthScheme based on OAuth.
 * The OAuthAccessor is contained by reference, so you can change it to contain
 * the OAuth tokens and secrets that you receive from a service provider.
 *
 * @author John Kristian
 */
public class OAuthCredentials extends UsernamePasswordCredentials {

    private final OAuthAccessor accessor;

    public OAuthCredentials(OAuthAccessor accessor) {
        super(accessor.consumer.consumerKey, accessor.consumer.consumerSecret);
        this.accessor = accessor;
    }

    public OAuthAccessor getAccessor() {
        return accessor;
    }

    /** Get the current consumer secret, to be used as a password. */
    @Override
    public String getPassword() {
        return getAccessor().consumer.consumerSecret;
    }

    /** Get the current consumer key, to be used as a password. */
    @Override
    public String getUserName() {
        return getAccessor().consumer.consumerKey;
    }

}

Enable changing the userName or password.


package com.arinerron.forux.core;

public class Logger {
    public static int PRINT_TO_CONSOLE = 0;
    public static int PRINT_TO_FILE = 1;
    public static int PRINT_TO_CONSOLE_AND_FILE = 2;

    private Game game = null;
    private int type = Logger.PRINT_TO_CONSOLE_AND_FILE;

    public Logger(Game game) {
        this.game = game;
    }

    private void log(Object o) {
        if(this.getLoggerType() % 2 == 0)
            System.out.println(o);
        if(this.getLoggerType() > 0)
            ;// make write to file later
    }

    public void log(String type, Object o) {
        log("[" + type.toUpperCase() + "] " + o);
    }

    public void info(Object o) {
        log("INFO", o);
    }

    public void warn(Object o) {
        log("WARN", o);
    }

    public void error(Object o) {
        log("ERROR", o);
    }

    public void error(Exception e) {
        log("ERROR", e.getMessage());
        e.printStackTrace();
    }

    public void setLoggerType(int type) {
        this.type = type;
    }

    public Game getGame() {
        return this.game;
    }

    public int getLoggerType() {
        return this.type;
    }
}

package com.arinerron.forux.core;

import java.text.SimpleDateFormat;
import java.util.Calendar;

public class Logger {
    public static int PRINT_TO_CONSOLE = 0;
    public static int PRINT_TO_FILE = 1;
    public static int PRINT_TO_CONSOLE_AND_FILE = 2;

    private Game game = null;
    private int type = Logger.PRINT_TO_CONSOLE_AND_FILE;

    public Logger(Game game) {
        this.game = game;
    }

    private void log(Object o) {
        if(this.getLoggerType() % 2 == 0)
            System.out.println(o);
        if(this.getLoggerType() > 0)
            ;// make write to file later
    }

    public void log(String type, Object o) {
        log("[" + new SimpleDateFormat("yyyyMMdd_HHmmss").format(Calendar.getInstance().getTime()) + type.toUpperCase() + "] " + o);
    }

    public void info(Object o) {
        log("INFO", o);
    }

    public void warn(Object o) {
        log("WARN", o);
    }

    public void error(Object o) {
        log("ERROR", o);
    }

    public void error(Exception e) {
        log("ERROR", e.getMessage());
        e.printStackTrace();
    }

    public void setLoggerType(int type) {
        this.type = type;
    }

    public Game getGame() {
        return this.game;
    }

    public int getLoggerType() {
        return this.type;
    }
}

Add date and time info


package com.miguelgaeta.android_message_parser;

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

public class AppActivity extends AppCompatActivity {

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

        setContentView(R.layout.app_activity);
    }
}

package com.miguelgaeta.android_message_parser;

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

import com.miguelgaeta.message_parser.MessageParser;
import com.miguelgaeta.message_parser.MessageParserImplFastJson;

import java.io.IOException;
import java.io.StringReader;

public class AppActivity extends AppCompatActivity {

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

        setContentView(R.layout.app_activity);

        final TestModel testModel = new TestModel();

        try {

            final MessageParser reader = new MessageParserImplFastJson(new StringReader("{\"test\":\"Bob\", \"test_again\":13}"));

            reader.beginObject();

            while (reader.hasNext()) {

                switch (reader.nextName()) {

                    case "test":
                        testModel.test = reader.nextString();
                        break;
                    case "test_again":
                        testModel.test_again = reader.nextInt();
                        break;
                }
            }

            reader.endObject();
            reader.close();

            Log.e("MessageParser", "Parsed: " + testModel);

        } catch (IOException e) {

            Log.e("MessageParser", "Error", e);
        }
    }

    public static class TestModel {

        private String test;

        private int test_again;

        @Override
        public String toString() {

            return "test: " +  test + ", test_again: " + test_again;
        }
    }
}

Add some basic example code.


//
// Triple Play - utilities for use in PlayN-based games
// Copyright (c) 2011-2014, Three Rings Design, Inc. - All rights reserved.
// http://github.com/threerings/tripleplay/blob/master/LICENSE

package tripleplay.demo;

import playn.core.Game;
import playn.core.PlayN;
import playn.core.util.Clock;

import tripleplay.game.ScreenStack;

public class TripleDemo extends Game.Default
{
    /** Args from the Java bootstrap class. */
    public static String[] mainArgs = {};

    public static final int UPDATE_RATE = 25;

    public TripleDemo () {
        super(UPDATE_RATE);
    }

    @Override public void init () {
        _screens.push(new DemoMenuScreen(_screens));
    }

    @Override public void update (int delta) {
        _clock.update(delta);
        _screens.update(delta);
    }

    @Override public void paint (float alpha) {
        _clock.paint(alpha);
        _screens.paint(_clock);
    }

    protected final Clock.Source _clock = new Clock.Source(UPDATE_RATE);

    protected final ScreenStack _screens = new ScreenStack() {
        @Override protected void handleError (RuntimeException error) {
            PlayN.log().warn("Screen failure", error);
        }
        @Override protected Transition defaultPushTransition () {
            return slide();
        }
        @Override protected Transition defaultPopTransition () {
            return slide().right();
        }
    };
}

//
// Triple Play - utilities for use in PlayN-based games
// Copyright (c) 2011-2014, Three Rings Design, Inc. - All rights reserved.
// http://github.com/threerings/tripleplay/blob/master/LICENSE

package tripleplay.demo;

import java.util.Arrays;

import playn.core.Game;
import playn.core.PlayN;
import playn.core.util.Clock;
import tripleplay.game.ScreenStack;

public class TripleDemo extends Game.Default
{
    /** Args from the Java bootstrap class. */
    public static String[] mainArgs = {};

    public static final int UPDATE_RATE = 25;

    public TripleDemo () {
        super(UPDATE_RATE);
    }

    @Override public void init () {
        _screens.push(new DemoMenuScreen(_screens));

        // propagate events so that things like buttons inside a scroller work
        if (!Arrays.asList(mainArgs).contains("--no-propagate")) {
            PlayN.setPropagateEvents(true);
        }
    }

    @Override public void update (int delta) {
        _clock.update(delta);
        _screens.update(delta);
    }

    @Override public void paint (float alpha) {
        _clock.paint(alpha);
        _screens.paint(_clock);
    }

    protected final Clock.Source _clock = new Clock.Source(UPDATE_RATE);

    protected final ScreenStack _screens = new ScreenStack() {
        @Override protected void handleError (RuntimeException error) {
            PlayN.log().warn("Screen failure", error);
        }
        @Override protected Transition defaultPushTransition () {
            return slide();
        }
        @Override protected Transition defaultPopTransition () {
            return slide().right();
        }
    };
}

Make fancy things like scrolling menus work in the demo.


// Copyright Verizon Media. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.config.model.api;

import java.time.Instant;
import java.util.Map;

/**
 * Status of reindexing for the documents of an application.
 *
 * @author jonmv
 */
public interface Reindexing {

    /** Reindexing status for a given application, cluster and document type. */
    default Status status(String cluster, String documentType) { return () -> Instant.MAX; }

    /** Reindexing status of a given document type in a given cluster in a given application. */
    interface Status {

        /** The instant at which reindexing may begin. */
        Instant ready();

    }

}

// Copyright Verizon Media. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.config.model.api;

import java.time.Instant;
import java.util.Map;

/**
 * Status of reindexing for the documents of an application.
 *
 * @author jonmv
 */
public interface Reindexing {

    /** No reindexing should be done for this document type and cluster. */
    Status NO_REINDEXING = () -> Instant.MAX;

    /** Reindexing status for a given application, cluster and document type. */
    default Status status(String cluster, String documentType) { return NO_REINDEXING; }

    /** Reindexing status of a given document type in a given cluster in a given application. */
    interface Status {

        /** The instant at which reindexing may begin. */
        Instant ready();

    }

}

Use more explicit value when reindexing should not be done


package nuclibook.server;

import com.j256.ormlite.jdbc.JdbcConnectionSource;
import com.j256.ormlite.support.ConnectionSource;
import com.j256.ormlite.table.TableUtils;
import nuclibook.constants.C;
import nuclibook.models.Radiographer;
import nuclibook.models.RadiographerAvailability;
import nuclibook.models.User;

import java.sql.SQLException;

public class SqlServerConnection {

	/* singleton pattern */

	private SqlServerConnection() {
	}

	private static ConnectionSource connection = null;

	public static ConnectionSource acquireConnection() {
		if (connection == null) {
			try {
				connection = new JdbcConnectionSource(C.MYSQL_URI);
				((JdbcConnectionSource) connection).setUsername(C.MYSQL_USERNAME);
				((JdbcConnectionSource) connection).setPassword(C.MYSQL_PASSWORD);
			} catch (Exception e) {
				e.printStackTrace(); // TODO deal with exception
			}

			initDB(connection);
		}

		return connection;
	}

    public static void initDB(ConnectionSource connection) {
		try {
			TableUtils.createTableIfNotExists(connection, User.class);
			TableUtils.createTableIfNotExists(connection, Radiographer.class);
			TableUtils.createTableIfNotExists(connection, RadiographerAvailability.class);
		} catch (SQLException e) {
			e.printStackTrace(); // TODO deal with exception
		}
	}
}

package nuclibook.server;

import com.j256.ormlite.jdbc.JdbcConnectionSource;
import com.j256.ormlite.support.ConnectionSource;
import com.j256.ormlite.table.TableUtils;
import nuclibook.constants.C;
import nuclibook.models.Radiographer;
import nuclibook.models.RadiographerAvailability;
import nuclibook.models.User;

import java.sql.SQLException;

public class SqlServerConnection {

	/* singleton pattern */

	private SqlServerConnection() {
	}

	private static ConnectionSource connection = null;

	public static ConnectionSource acquireConnection() {
		if (connection == null) {
			try {
				connection = new JdbcConnectionSource(C.MYSQL_URI);
				((JdbcConnectionSource) connection).setUsername(C.MYSQL_USERNAME);
				((JdbcConnectionSource) connection).setPassword(C.MYSQL_PASSWORD);

				initDB(connection);
			} catch (Exception e) {
				e.printStackTrace(); // TODO deal with exception
			}
		}

		return connection;
	}

    public static void initDB(ConnectionSource connection) {
		try {
			TableUtils.createTableIfNotExists(connection, User.class);
			TableUtils.createTableIfNotExists(connection, Radiographer.class);
			TableUtils.createTableIfNotExists(connection, RadiographerAvailability.class);
		} catch (SQLException e) {
			e.printStackTrace(); // TODO deal with exception
		}
	}
}

Move init DB in try block


package semantic;

import error.CompilerError;

import parse.Loc;
import types.Type;

public interface SemanticHelper {

   static CompilerError typeMismatch(Loc loc, Type found, Type... expected) {
      final StringBuilder builder = new StringBuilder();
      final int n = expected.length;
      if (n > 0) {
         builder.append(expected[0]);
         if (n > 1) {
            for (int i = 1; i < n - 2; i++)
               builder.append(", ").append(expected[i]);
            builder.append(" or ").append(expected[n - 1]);
         }
      }
      return new CompilerError(loc, "type mismatch: found %s but expected %s", found, builder);
   }

   static CompilerError undefined(Loc loc, String category, String name) {
      return new CompilerError(loc, "undefined %s '%s'", category, name);
   }

   static CompilerError notAFunction(Loc loc, String name) {
      return new CompilerError(loc, "'%s' is not a function", name);
   }

   static CompilerError tooFewArguments(Loc loc, String name) {
      return new CompilerError(loc, "too few arguments in call to '%s'", name);
   }

   static CompilerError tooMuchArguments(Loc loc, String name) {
      return new CompilerError(loc, "too much arguments in call to '%s'", name);
   }

}

package semantic;

import error.CompilerError;

import parse.Loc;
import types.Type;

public interface SemanticHelper {

   static CompilerError error(String message) {
      return new CompilerError(message);
   }

   static CompilerError error(String format, Object... args) {
      return new CompilerError(format, args);
   }

   static CompilerError error(Loc loc, String format, Object... args) {
      return new CompilerError(loc, format, args);
   }

   static CompilerError typeMismatch(Loc loc, Type found, Type... expected) {
      final StringBuilder builder = new StringBuilder();
      final int n = expected.length;
      if (n > 0) {
         builder.append(expected[0]);
         if (n > 1) {
            for (int i = 1; i < n - 2; i++)
               builder.append(", ").append(expected[i]);
            builder.append(" or ").append(expected[n - 1]);
         }
      }
      return error(loc, "type mismatch: found %s but expected %s", found, builder);
   }

   static CompilerError undefined(Loc loc, String category, String name) {
      return new CompilerError(loc, "undefined %s '%s'", category, name);
   }

   static CompilerError notAFunction(Loc loc, String name) {
      return error(loc, "'%s' is not a function", name);
   }

   static CompilerError tooFewArguments(Loc loc, String name) {
      return error(loc, "too few arguments in call to '%s'", name);
   }

   static CompilerError tooMuchArguments(Loc loc, String name) {
      return error(loc, "too much arguments in call to '%s'", name);
   }

}

Add more helper methods for reporting errors


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

import static io.github.bonigarcia.wdm.WebDriverManager.chromedriver;
import static org.junit.Assert.assertTrue;

import java.io.File;

import org.junit.Test;

import io.github.bonigarcia.wdm.WebDriverManager;

/**
 * Test for preferences.
 *
 * @author Boni Garcia (boni.gg@gmail.com)
 * @since 3.0.0
 */
public class ResolutionCacheTest {

    @Test
    public void testEmptyTtl() {
        WebDriverManager.main(new String[] { "clear-resolution-cache" });
        chromedriver().ttl(0).ttlBrowsers(0).setup();
        File driver = new File(chromedriver().getDownloadedDriverPath());
        assertTrue(driver.exists());
    }

}

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

import static io.github.bonigarcia.wdm.WebDriverManager.chromedriver;
import static org.junit.Assert.assertTrue;

import java.io.File;

import org.junit.Test;

import io.github.bonigarcia.wdm.WebDriverManager;

/**
 * Test for resolution cache.
 *
 * @author Boni Garcia (boni.gg@gmail.com)
 * @since 3.0.0
 */
public class ResolutionCacheTest {

    @Test
    public void testEmptyTtl() {
        WebDriverManager.main(new String[] { "clear-resolution-cache" });
        chromedriver().ttl(0).ttlBrowsers(0).setup();
        File driver = new File(chromedriver().getDownloadedDriverPath());
        assertTrue(driver.exists());
    }

}

Change header in resolution cache test


package org.deidentifier.arx.gui.view.impl.analyze;

import java.awt.Panel;

import org.deidentifier.arx.DataHandle;
import org.deidentifier.arx.gui.model.Model;
import org.deidentifier.arx.gui.model.ModelEvent.ModelPart;

public abstract class ViewStatistics extends Panel{

    private static final long serialVersionUID = 5170104283288654748L;

    protected ModelPart target;
    protected Model model;

    /**
     * Returns the data handle
     * @return
     */
    protected DataHandle getHandle() {
        if (model != null){
            if (target == ModelPart.INPUT){
                DataHandle handle = model.getInputConfig().getInput().getHandle();
                if (model.getViewConfig().isSubset() &&
                    model.getOutputConfig() != null &&
                    model.getOutputConfig().getConfig() != null) {
                    handle = handle.getView();
                }
                return handle;
            } else {
                DataHandle handle = model.getOutput();
                if (model.getViewConfig().isSubset() &&
                    model.getOutputConfig() != null &&
                    model.getOutputConfig().getConfig() != null) {
                    handle = handle.getView();
                }
                return handle;
            }
        } else {
            return null;
        }
    }
}

package org.deidentifier.arx.gui.view.impl.analyze;

import java.awt.Panel;

import org.deidentifier.arx.DataHandle;
import org.deidentifier.arx.gui.model.Model;
import org.deidentifier.arx.gui.model.ModelEvent.ModelPart;

public abstract class ViewStatistics extends Panel{

    private static final long serialVersionUID = 5170104283288654748L;

    protected ModelPart target;
    protected Model model;

    /**
     * Returns the data handle
     * @return
     */
    protected DataHandle getHandle() {
        if (model != null){
            if (target == ModelPart.INPUT){
                DataHandle handle = model.getInputConfig().getInput().getHandle();
                if (model.getViewConfig().isSubset() &&
                    model.getOutputConfig() != null &&
                    model.getOutputConfig().getConfig() != null &&
                    handle != null) {
                    handle = handle.getView();
                }
                return handle;
            } else {
                DataHandle handle = model.getOutput();
                if (model.getViewConfig().isSubset() &&
                    model.getOutputConfig() != null &&
                    model.getOutputConfig().getConfig() != null &&
                    handle != null) {
                    handle = handle.getView();
                }
                return handle;
            }
        } else {
            return null;
        }
    }
}

Fix bug when loading projects