package org.apache.maven.siteindexer.mojo;

import java.io.IOException;

import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.apache.maven.siteindexer.Indexer;

/**
 * This goal will build the index.
 *
 * @goal index
 * @aggregator
 *
 */
public class IndexerMojo extends AbstractMojo {

	@Override
	public void execute() throws MojoExecutionException, MojoFailureException {
		Indexer indexer = new Indexer(getLog());
		try {
			getLog().info("Maven Site Index");
			getLog().info("------------------------------");
			getLog().info("building index.js...");
			indexer.buildIndex(
					"target\\site\\",
					"target\\site\\js\\index.js");
			getLog().info("done.");
		} catch (IOException e) {
			getLog().error(e);
		}
	}
}

package org.apache.maven.siteindexer.mojo;

import java.io.IOException;

import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.apache.maven.siteindexer.Indexer;

/**
 * This goal will build the index.
 *
 * @goal index
 * @aggregator
 *
 */
public class IndexerMojo extends AbstractMojo {

	@Override
	public void execute() throws MojoExecutionException, MojoFailureException {
		Indexer indexer = new Indexer(getLog());
		try {
			getLog().info("Maven Site Index");
			getLog().info("------------------------------");
			getLog().info("building index.js...");
			indexer.buildIndex(
					"target"+ File.separator +"site"+ File.separator,
					"target" + File.separator + "site" + File.separator + "js" + File.separator + "index.js");
			getLog().info("done.");
		} catch (IOException e) {
			getLog().error(e);
		}
	}
}

Add support for linux with File.separator


package pipeTesting;

import core.Artifact;
import core.ArtifactID;
import util.Os;

/**
 * Created by nwilson on 2/23/15.
 */
public class CmdTest extends Test {

    private static final String BASELINE_ARG = "\\$BASELINE";
    private static final String ACTUAL_ARG   = "\\$ACTUAL";

    private final String cmd;

    public CmdTest(String cmd, ArtifactID aid, String name) {
        super(aid, name);
        this.cmd = cmd;
    }

    @Override
    void Verify(Artifact base, Artifact actual) {
        String cmdParsed = this.cmd;
        cmdParsed = cmdParsed.replaceAll(BASELINE_ARG, base.file.getAbsolutePath());
        cmdParsed = cmdParsed.replaceAll(ACTUAL_ARG, base.file.getAbsolutePath());
        assert Os.current.Exec(cmdParsed) == 0;
    }
}

package pipeTesting;

import core.Artifact;
import core.ArtifactID;
import util.Os;

/**
 * Created by nwilson on 2/23/15.
 */
public class CmdTest extends Test {

    private static final String BASELINE_ARG = "\\$BASELINE";
    private static final String ACTUAL_ARG   = "\\$ACTUAL";

    private final String cmd;

    public CmdTest(String cmd, ArtifactID aid, String name) {
        super(aid, name);
        this.cmd = cmd;
    }

    @Override
    void Verify(Artifact base, Artifact actual) {
        String cmdParsed = this.cmd;
        cmdParsed = cmdParsed.replaceAll(BASELINE_ARG, base.file.getAbsolutePath());
        cmdParsed = cmdParsed.replaceAll(ACTUAL_ARG, actual.file.getAbsolutePath());
        assert Os.current.Exec(cmdParsed) == 0;
    }
}

Fix typo: compare baseline with baseline


package com.asana.models;

import com.google.gson.annotations.SerializedName;

import java.util.Collection;
import com.google.api.client.util.DateTime;

public class Project {
    public String id;
    public String name;

    public String notes;
    public String color;
    @SerializedName("archived")
    public boolean isArchived;
    @SerializedName("public")
    public boolean isPublic;

    public Collection<User> followers;
    public Collection<User> members;

    public Team team;
    public Workspace workspace;

    @SerializedName("created_at")
    public DateTime createdAt;
    @SerializedName("modified_at")
    public DateTime modifiedAt;

    public Project() {
        //no-arg constructor
    }

    // constructor with id arg provided for convenience
    public Project(String id) {
        this.id = id;
    }
}

package com.asana.models;

import com.google.gson.annotations.SerializedName;

import java.util.Collection;
import com.google.api.client.util.DateTime;

public class Project {
    public String id;
    public String name;

    public String notes;
    public String color;
    @SerializedName("archived")
    public boolean isArchived;
    @SerializedName("public")
    public boolean isPublic;

    public Collection<User> followers;
    public Collection<User> members;

    public Team team;
    public Workspace workspace;

    @SerializedName("created_at")
    public DateTime createdAt;
    @SerializedName("modified_at")
    public DateTime modifiedAt;

    public User owner;

    public Project() {
        //no-arg constructor
    }

    // constructor with id arg provided for convenience
    public Project(String id) {
        this.id = id;
    }
}

Add owner to projects model.

Add owner to projects model.


package org.ethereum.core;

import static org.junit.Assert.*;

import java.math.BigInteger;

import org.junit.Test;
import org.spongycastle.util.encoders.Hex;

public class AccountStateTest {

	@Test
	public void testGetEncoded() {
		String expected = "f83e809a010000000000000000000000000000000000000000000000000080a0c5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470";
		AccountState acct = new AccountState(BigInteger.ZERO, BigInteger.valueOf(2).pow(200));
		assertEquals(expected, Hex.toHexString(acct.getEncoded()));
	}

}

package org.ethereum.core;

import static org.junit.Assert.*;

import java.math.BigInteger;

import org.junit.Test;
import org.spongycastle.util.encoders.Hex;

public class AccountStateTest {

	@Test
	public void testGetEncoded() {
		String expected = "de809a01000000000000000000000000000000000000000000000000008080";
		AccountState acct = new AccountState(BigInteger.ZERO, BigInteger.valueOf(2).pow(200));
		assertEquals(expected, Hex.toHexString(acct.getEncoded()));
	}

}

Fix account state rlp encoding test

Fix account state rlp encoding test


/*
 * Zorbage: an algebraic data hierarchy for use in numeric processing.
 *
 * Copyright (C) 2016-2020 Barry DeZonia
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * 1. Redistributions of source code must retain the above copyright notice,
 *    this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright notice,
 *    this list of conditions and the following disclaimer in the documentation
 *    and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */
package nom.bdezonia.zorbage.algebra;

/**
 *
 * @author Barry DeZonia
 *
 */
public interface Ring<T extends Ring<T,U>,U>
  extends
    AdditiveGroup<T,U>,
    Multiplication<U>
{
}

Fix spacing in one more file

Fix spacing in one more file


package forklift.concurrent;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * Forklift core thread pool.
 * @author zdavep
 */
public final class Executors {

    // Base value for determining thread pool size.
    private static final int cpus = Runtime.getRuntime().availableProcessors();

    /**
     * Disable instance creation.
     */
    private Executors() {}

    /**
     * Allows us to create daemon threads with meaningful names.
     */
    private static ThreadFactory daemonThreadFactory(final String name) {
        return new ThreadFactory() {
            private final AtomicInteger counter = new AtomicInteger();
            @Override public Thread newThread(Runnable r) {
                final Thread thread = new Thread(r);
                thread.setName(name + "-" + counter.incrementAndGet());
                thread.setDaemon(true);
                return thread;
            }
        };
    }

    /**
     * A core thread pool factory method that returns a "better" alternative to a cached thread pool.
     */
    public static ExecutorService newCoreThreadPool(final String name) {
        final ThreadPoolExecutor pool = new ThreadPoolExecutor(
            (2 * cpus),  (6 * cpus), 60, TimeUnit.SECONDS, new SynchronousQueue<Runnable>(), daemonThreadFactory(name)
        );
        pool.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        return pool;
    }

}

package forklift.concurrent;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * Forklift core thread pool.
 * @author zdavep
 */
public final class Executors {

    // Base value for determining thread pool size.
    private static final int cpus = Runtime.getRuntime().availableProcessors();

    /**
     * Disable instance creation.
     */
    private Executors() {}

    /**
     * Allows us to create daemon threads with meaningful names.
     */
    private static ThreadFactory daemonThreadFactory(final String name) {
        return new ThreadFactory() {
            private final AtomicInteger counter = new AtomicInteger();
            @Override public Thread newThread(Runnable r) {
                final Thread thread = new Thread(r);
                thread.setName(name + "-" + counter.incrementAndGet());
                thread.setDaemon(true);
                return thread;
            }
        };
    }

    /**
     * A core thread pool factory method that returns a cached thread pool.
     */
    public static ExecutorService newCoreThreadPool(final String name) {
        final ThreadPoolExecutor pool = new ThreadPoolExecutor(
            (2 * cpus),  Integer.MAX_VALUE, 60, TimeUnit.SECONDS, new SynchronousQueue<Runnable>(), daemonThreadFactory(name)
        );
        pool.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        return pool;
    }

}

Make core thread pool size unbounded

Make core thread pool size unbounded


package systems.speedy.lmf.time;

public class Constants {
	public static final int NUM_OF_TIMESTAMPS = 300_000;
	public static final int NUM_OF_WARMUPS    = 5;
	public static final int REPETITIONS       = 10;
}

package systems.speedy.lmf.time;

public class Constants {
	public static final int NUM_OF_TIMESTAMPS = 200_000;
	public static final int NUM_OF_WARMUPS    = 10;
	public static final int REPETITIONS       = 10;
}

Increase number of warmup runs and decrease number of timestamps to avoid GC.


/*
 * 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

Signed-off-by: Sebastian Hoß <1d6e1cf70ec6f9ab28d3ea4b27a49a77654d370e@shoss.de>


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

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.

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

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

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

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

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

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

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

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.

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

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.

git-svn-id: 4c5078813df38efa56971a28e09a55254294f104@150562 13f79535-47bb-0310-9956-ffa450edef68


/**
 * 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

Summary: This diff initializes Fabric C++ UIManager code from java, it also registers android RootViews inside C++.

Reviewed By: shergin

Differential Revision: D8878148

fbshipit-source-id: 8b7924f715b135eda37bb2683206d3e321a2b7b2


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

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

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.

Change-Id: I626c8b81b20cdbbe1b8f292db9c21b32aacc24e8


/*
 * 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

Break the build to test Hudson

git-svn-id: ec6ef1d57ec0831ce4cbff3b75527511e63bfbe3@736933 13f79535-47bb-0310-9956-ffa450edef68


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

The checksum validation failed when a changeset containing a
<dropNotNullConstraint> change was processed for the second time.
The reason is that the statement generation (which only occurs when the
change
is really executed, i.e. the first time only) changes the value of the
schemaName field. The schemaName, however, is used for checksum
calculation.


// 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);
        }
    }
}

CLOUDSTACK-1148: Change URL from google as 503 returns from that site cause test to erroneously fail.

Signed-off-by: Simon Waterhouse <d0c6b5888fa60b3b8207dfa2bef2890dd742fceb@citrix.com>
Signed-off-by: Rohit Yadav <0fa72ca37c4b5fa62675187ce32ea6c9f842fd52@apache.org>


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

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

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

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

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.

Add some basic example code.