/*
 * Copyright (C) 2011 Archie L. Cobbs. All rights reserved.
 *
 * $Id$
 */

package org.dellroad.stuff.spring;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.StringWriter;

import org.springframework.beans.factory.config.AbstractFactoryBean;
import org.springframework.core.io.Resource;

/**
 * Spring factory bean that reads in a Spring {@link Resource} and converts it to a {@link String}.
 */
public class ResourceReaderFactoryBean extends AbstractFactoryBean<String> {

    private Resource resource;
    private String charset = "UTF-8";

    /**
     * Configure the resource containing the {@link String value}.
     */
    public void setResource(Resource resource) {
        this.resource = resource;
    }

    /**
     * Configure the character encoding for the resource. Default is {@code UTF-8}.
     */
    public void setCharacterEncoding(String charset) {
        this.charset = charset;
    }

    @Override
    public Class<String> getObjectType() {
        return String.class;
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        super.afterPropertiesSet();
        if (this.resource == null)
            throw new Exception("no resource configured");
    }

    @Override
    protected String createInstance() throws IOException {
        InputStream input = this.resource.getInputStream();
        try {
            InputStreamReader reader = new InputStreamReader(input, this.charset);
            StringWriter writer = new StringWriter();
            char[] buf = new char[4096];
            int r;
            while ((r = reader.read(buf)) != -1)
                writer.write(buf, 0, r);
            return writer.toString();
        } finally {
            try {
                input.close();
            } catch (IOException e) {
                // ignore
            }
        }
    }
}

Add utility class to read in a String from a Resource.


/*
 * Copyright (C) 2004 EBI, GRL
 *
 * This library is free software; you can redistribute it and/or modify it under the terms of the
 * GNU Lesser General Public License as published by the Free Software Foundation; either version
 * 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
 * even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License along with this library;
 * if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
 * 02111-1307 USA
 */

package org.ensembl.healthcheck.testcase.generic;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;

import org.ensembl.healthcheck.DatabaseRegistryEntry;
import org.ensembl.healthcheck.ReportManager;
import org.ensembl.healthcheck.testcase.Priority;
import org.ensembl.healthcheck.testcase.SingleDatabaseTestCase;

/**
 * Check if any tables are partitioned. None should be yet, until their definitions are updated in table.sql.
 */
public class PartitionedTables extends SingleDatabaseTestCase {

	/**
	 * Creates a new instance of PartitionedTables
	 */
	public PartitionedTables() {

		addToGroup("release");
		setDescription("Check whether tables have been partitioned.");
		setPriority(Priority.AMBER);
		setEffect("Tables should only be partitioned if the partitions are defined in table.sql.");
		setTeamResponsible("ReleaseCoordinator");

	}

	/**
	 * Run the test.
	 *
	 */
	public boolean run(DatabaseRegistryEntry dbre) {

		boolean result = true;

		Connection con = dbre.getConnection();

		try {

			Statement stmt = con.createStatement();
			ResultSet rs = stmt.executeQuery("SHOW TABLE STATUS WHERE create_options LIKE '%partitioned%'");

			while (rs.next()) {

				String table = rs.getString(1);
				ReportManager.problem(this, con, table + " is partitioned but shouldn't be.");
				result = false;

			}

			rs.close();

			stmt.close();

		} catch (Exception e) {

			e.printStackTrace();
			System.exit(1);

		}

		if (result == true) {

			ReportManager.correct(this, con, "No tables are partitioned");
		}

		return result;

	} // run

	// -----------------------------------------------------------------------

} // AnalyseTables


package com.salesforce.phoenix.end2end;

import java.sql.Connection;
import java.sql.DriverManager;
import java.util.Properties;

import org.junit.Test;

import com.salesforce.phoenix.util.PhoenixRuntime;

public class CreateTableTest  extends BaseClientMangedTimeTest {

    @Test
    public void testCreateTable() throws Exception {
        long ts = nextTimestamp();
        Properties props = new Properties();
        props.setProperty(PhoenixRuntime.CURRENT_SCN_ATTRIB, Long.toString(ts));
        Connection conn = DriverManager.getConnection(getUrl(), props);
        conn.createStatement().execute("CREATE TABLE m_interface_job(                data.addtime VARCHAR ,\n" +
        		"                data.dir VARCHAR ,\n" +
        		"                data.end_time VARCHAR ,\n" +
        		"                data.file VARCHAR ,\n" +
        		"                data.fk_log VARCHAR ,\n" +
        		"                data.host VARCHAR ,\n" +
        		"                data.row VARCHAR ,\n" +
        		"                data.size VARCHAR ,\n" +
        		"                data.start_time VARCHAR ,\n" +
        		"                data.stat_date DATE ,\n" +
        		"                data.stat_hour VARCHAR ,\n" +
        		"                data.stat_minute VARCHAR ,\n" +
        		"                data.state VARCHAR ,\n" +
        		"                data.title VARCHAR ,\n" +
        		"                data.user VARCHAR ,\n" +
        		"                data.inrow VARCHAR ,\n" +
        		"                data.jobid VARCHAR ,\n" +
        		"                data.jobtype VARCHAR ,\n" +
        		"                data.level VARCHAR ,\n" +
        		"                data.msg VARCHAR ,\n" +
        		"                data.outrow VARCHAR ,\n" +
        		"                data.pass_time VARCHAR ,\n" +
        		"                data.type VARCHAR ,\n" +
        		"                id INTEGER not null primary key desc\n" +
        		"                ) ");
        props.setProperty(PhoenixRuntime.CURRENT_SCN_ATTRIB, Long.toString(ts + 10));
        conn = DriverManager.getConnection(getUrl(), props);
        conn.createStatement().execute("DROP TABLE m_interface_job");
    }
}

Add new test for table creation

Add new test for table creation


package galileo.samples;

import java.util.ArrayList;

import java.util.List;
import java.util.Random;

import galileo.dataset.feature.Feature;
import galileo.query.Expression;
import galileo.query.Operation;
import galileo.query.Operator;
import galileo.query.Query;

public class RandomQuery {

    public static Random random = new Random();

    public static Operator randomOperator() {
        int i = random.nextInt(Operator.values().length - 2) + 1;
        return Operator.fromInt(i);
    }

    public static Feature randomFeature(String name, float min, float max) {
        float diff = max - min;
        float rand = random.nextFloat() * diff;
        float value = min + rand;
        return new Feature(name, value);
    }

    public static Query randomQuery() {
        Query q = new Query();

        List<Feature> features = new ArrayList<>();
        features.add(randomFeature("pressure", 1, 100));
        features.add(randomFeature("visibility", 1, 100));
        features.add(randomFeature("total_precipitation", 1, 100));
        features.add(randomFeature("temperature_surface", 1, 100));

        List<Expression> expressions = new ArrayList<>();
        for (Feature f : features) {
            expressions.add(new Expression(randomOperator(), f));
        }

        Operation op = new Operation(expressions.toArray(
                    new Expression[expressions.size()]));

        q.addOperation(op);

        return q;
    }

    public static void main(String[] args) {
        Query q = randomQuery();
        System.out.println(q);
    }
}

Add random query generator sample

Add random query generator sample


package rxbroadcast;

import org.junit.After;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.Timeout;
import rx.observers.TestSubscriber;

import java.io.Closeable;
import java.io.IOException;
import java.net.DatagramSocket;
import java.net.SocketException;
import java.util.LinkedList;
import java.util.List;
import java.util.function.Supplier;

@SuppressWarnings({"checkstyle:MagicNumber"})
public final class UdpBroadcastOnSubscribeTest {
    private final List<Closeable> resources = new LinkedList<>();

    private final Supplier<DatagramSocket> datagramSocketSupplier = () -> {
        try {
            final DatagramSocket socket = new DatagramSocket();
            resources.add(socket);
            return socket;
        } catch (final SocketException e) {
            throw new RuntimeException(e);
        }
    };

    @Rule
    public final Timeout timeout = Timeout.seconds(1);

    @After
    public final void tearDown() {
        resources.forEach(closeable -> {
            try {
                closeable.close();
            } catch (final IOException e) {
                // ???
            }
        });
    }

    @Test
    public final void unsubscribeDoesBreakCall() throws SocketException {
        final TestSubscriber<Object> subscriber = new TestSubscriber<>();
        final UdpBroadcastOnSubscribe<Object> onSubscribe = new UdpBroadcastOnSubscribe<>(
            datagramSocketSupplier.get(), new ObjectSerializer<>(), new NoOrder<>());

        subscriber.unsubscribe();
        onSubscribe.call(subscriber);

        subscriber.assertNoErrors();
        subscriber.assertNoValues();
        subscriber.assertNotCompleted();
    }

    @Test
    public final void closedReadSocketErrorDoesPropagateToSubscriber() throws SocketException {
        final TestSubscriber<Object> subscriber = new TestSubscriber<>();
        final DatagramSocket socket = new DatagramSocket();
        final UdpBroadcastOnSubscribe<Object> onSubscribe = new UdpBroadcastOnSubscribe<>(
            socket, new ObjectSerializer<>(), new NoOrder<>());

        socket.close();
        onSubscribe.call(subscriber);

        subscriber.assertError(IOException.class);
    }
}

Add test cases for UdpBroadcastOnSubscribe


package nz.mega.sdk;

public class MegaPushNotificationSettingsAndroid {

    /**
     * Creates a copy of MegaPushNotificationSetting.
     *
     * @param receivedPush The MegaPushNotificationsSetting received.
     * @return A copy of MegaPushNotificationSettings.
     */
    public static MegaPushNotificationSettings copy(MegaPushNotificationSettings receivedPush) {
        return receivedPush.copy();
    }
}

Add method to be able to copy MegaPushNotificationSettings (Android bindings)


package com.tom_e_white.set_game;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.text.ParseException;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * Use {@link CardPredictor} to play Set.
 */
public class PlaySet {

    public static void play(File testFile) throws IOException, ParseException {
        CardDetector cardDetector = new CardDetector();
        CardPredictor cardPredictor = new CardPredictor();
        List<BufferedImage> images = cardDetector.scan(testFile.getAbsolutePath(), false);

        List<Card> cards = images.stream().map(image -> {
            try {
                return cardPredictor.predict(image);
            } catch (IOException | ParseException e) {
                throw new RuntimeException(e);
            }
        }).collect(Collectors.toList());

        Set<Triple> sets = Cards.sets(cards);

        sets.forEach(System.out::println);
    }

    public static void main(String[] args) throws Exception {
        play(new File(args[0]));
    }
}

Add a program to play Set

Add a program to play Set


package eu.redray.trevie.utility;

import android.content.Context;
import android.graphics.Bitmap;
import android.net.Uri;
import android.util.Log;

import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;

/**
 * Created by frano on 23/01/2016.
 */
public class PosterHeper {
    private final static String FILE_EXTENSION = ".jpg";
    private final static String DIRECTORY = "Posters";

    /**
     * Saves poster image to internal storage
     * @param context Application's context
     * @param bitmap Movie poster to save
     * @param title Movie's title
     * @return Path to saved file
     */
    public static String savePoster(Context context, Bitmap bitmap, String title) {
        OutputStream fOut = null;
        Uri outputFileUri = null;
        try {
            File root = new File(context.getFilesDir()
                    + File.separator + DIRECTORY + File.separator);
            root.mkdirs();
            File sdImageMainDirectory = new File(root, title + FILE_EXTENSION);
            outputFileUri = Uri.fromFile(sdImageMainDirectory);
            fOut = new FileOutputStream(sdImageMainDirectory);
        } catch (Exception e) {
            Log.e(PosterHeper.class.getSimpleName(), e.getMessage(), e);
            e.printStackTrace();
        }

        try {
            bitmap.compress(Bitmap.CompressFormat.PNG, 100, fOut);
            fOut.flush();
            fOut.close();
        } catch (Exception e) {
            Log.e(PosterHeper.class.getSimpleName(), e.getMessage(), e);
            e.printStackTrace();
        }

        return outputFileUri.toString();
    }

    public static boolean deletePoster(Context context, String title) {
        File file = new File(context.getFilesDir() + File.separator + DIRECTORY + File.separator,
                title + FILE_EXTENSION);
        return file.delete();
    }
}

feat: Add helper class that will handle poster image storage


/*
 * Copyright (c) 2017 Farooq Khan
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to
 * deal in the Software without restriction, including without limitation the
 * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
 * sell copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */
package io.jsondb.tests;

import static org.junit.Assert.*;

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

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

import com.google.common.io.Files;

import io.jsondb.DefaultSchemaVersionComparator;
import io.jsondb.JsonDBConfig;
import io.jsondb.Util;
import io.jsondb.io.JsonReader;

/**
 * Unit tests for JsonReader IO utility class
 * @version 1.0 11-Dec-2017
 */
public class JsonReaderTests {

  private String dbFilesLocation = "src/test/resources/dbfiles/jsonReaderTests";
  private File dbFilesFolder = new File(dbFilesLocation);
  private File instancesJson = new File(dbFilesFolder, "instances.json");

  /**
   * @throws java.lang.Exception
   */
  @Before
  public void setUp() throws Exception {
    dbFilesFolder.mkdir();
    Files.copy(new File("src/test/resources/dbfiles/instances.json"), instancesJson);
  }

  @After
  public void tearDown() throws Exception {
    Util.delete(dbFilesFolder);
  }

  @Test
  public void testReadLine() throws IOException {
    JsonDBConfig dbConfig = new JsonDBConfig(dbFilesLocation, "io.jsondb.tests.model", null, false,
        new DefaultSchemaVersionComparator());

    JsonReader jr = new JsonReader(dbConfig, instancesJson);

    assertNotNull(jr);
    assertEquals("{\"schemaVersion\":\"1.0\"}", jr.readLine());
  }
}

Add unit tests for JsonReader class

Add unit tests for JsonReader class


package org.broadinstitute.sting.utils;

import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
import org.broadinstitute.sting.BaseTest;
import org.broadinstitute.sting.utils.MathUtils;

import java.io.File;

/**
 * Basic unit test for MathUtils
 */
public class MathUtilsTest extends BaseTest {
    @BeforeClass
    public static void init() { }

    /**
     * Tests that we get the right values from the binomial distribution
     */
    @Test
    public void testBinomialProbability() {
        logger.warn("Executing testBinomialProbability");

        Assert.assertTrue(MathUtils.compareDoubles(MathUtils.binomialProbability(2, 3, 0.5), 0.375, 0.001) == 0);
        Assert.assertTrue(MathUtils.compareDoubles(MathUtils.binomialProbability(10, 100, 0.5), 1.365543e-17, 1e-18) == 0);
        Assert.assertTrue(MathUtils.compareDoubles(MathUtils.binomialProbability(73, 217, 0.02), 4.521904e-67, 1e-68) == 0);
        Assert.assertTrue(MathUtils.compareDoubles(MathUtils.binomialProbability(100, 300, 0.02), 9.27097e-91, 1e-92) == 0);
        Assert.assertTrue(MathUtils.compareDoubles(MathUtils.binomialProbability(150, 300, 0.98), 6.462892e-168, 1e-169) == 0);
        Assert.assertTrue(MathUtils.compareDoubles(MathUtils.binomialProbability(120, 300, 0.98), 3.090054e-221, 1e-222) == 0);
        Assert.assertTrue(MathUtils.compareDoubles(MathUtils.binomialProbability(112, 300, 0.98), 2.34763e-236, 1e-237) == 0);
    }
}

Test class for MathUtils with a test for binomialProbability().

git-svn-id: 4561c0a8f080806b19201efb9525134c00b76d40@519 348d0f76-0448-11de-a6fe-93d51630548a


package de.fesere.tictactoe.players;

import de.fesere.tictactoe.Board;
import de.fesere.tictactoe.Marker;
import de.fesere.tictactoe.Move;
import de.fesere.tictactoe.board.ArrayBoard;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static de.fesere.tictactoe.Marker.NONE;

public class BoardBuilder {

    private Board board = new ArrayBoard();

    public BoardBuilder() {
    }

    public BoardBuilder row1(String row) {
        Marker [] markers = getMarkerFromString(row);
        return applyMarkersOnRow(0, markers);
    }

    private Marker[] getMarkerFromString(String row) {
        Pattern pattern = Pattern.compile("(\\[.?\\])");
        Matcher m = pattern.matcher(row);
        Marker [] marker = new Marker[3];
        for(int i = 0; i<3; i++) {
            m.find();
            marker[i] =convertToMarker(m.group());
        }
        return marker;

    }

    private Marker convertToMarker(String group) {
        if(group.contains("X")) {
            return Marker.X;
        }
        if(group.contains("O")) {
            return Marker.O;
        }
        return NONE;

    }

    private BoardBuilder applyMarkersOnRow(int row, Marker ... marker) {
        for(int i =0; i < 3; i++) {
            Move move = new Move(row, i);
            board = board.mark(move, marker[i]);
        }
        return this;
    }

    public BoardBuilder row2(String row) {
        Marker [] markers = getMarkerFromString(row);
        return applyMarkersOnRow(1, markers);
    }

    public BoardBuilder row3(String row) {
        Marker [] markers = getMarkerFromString(row);
        return applyMarkersOnRow(2, markers);
    }

    public Board build() {
        return board;
    }
}

Add infrastructure to write readable tests using a "graphical" board


/*
 * #%L
 * SciJava Common shared library for SciJava software.
 * %%
 * Copyright (C) 2009 - 2015 Board of Regents of the University of
 * Wisconsin-Madison, Broad Institute of MIT and Harvard, and Max Planck
 * Institute of Molecular Cell Biology and Genetics.
 * %%
 * 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.
 * #L%
 */

package org.scijava.console;

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

import java.util.LinkedList;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.scijava.Context;
import org.scijava.Priority;
import org.scijava.plugin.Plugin;

/**
 * Tests {@link ConsoleService}.
 *
 * @author Curtis Rueden
 */
public class ConsoleServiceTest {

	private ConsoleService consoleService;

	@Before
	public void setUp() {
		consoleService = new Context().service(ConsoleService.class);
	}

	@After
	public void tearDown() {
		consoleService.context().dispose();
	}

	/** Tests {@link ConsoleService#processArgs(String...)}. */
	@Test
	public void testProcessArgs() {
		consoleService.processArgs("--foo", "--bar");
		assertTrue(consoleService.getInstance(FooArgument.class).argsHandled);
	}

	// -- Helper classes --

	@Plugin(type = ConsoleArgument.class, priority = Priority.HIGH_PRIORITY)
	public static class FooArgument extends AbstractConsoleArgument {

		private boolean argsHandled;

		@Override
		public void handle(final LinkedList<String> args) {
			assertNotNull(args);
			assertEquals(2, args.size());
			assertEquals("--foo", args.get(0));
			assertEquals("--bar", args.get(1));
			args.clear();
			argsHandled = true;
		}

	}

}

Add a unit test for DefaultConsoleService


import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;

class Point
{
    private int m_x;
    private int m_y;

    public Point(int x, int y)
    {
        m_x = x;
        m_y = y;
    }

    int getX()
    {
        return m_x;
    }

    int getY()
    {
        return m_y;
    }
}

class Rectangle
{
    private Point m_upperLeft;
    private Point m_lowerRight;

    public Rectangle(Point upperLeft, Point lowerRight)
    {
        m_upperLeft = upperLeft;
        m_lowerRight = lowerRight;
    }

    private boolean containsPoint(Point p)
    {
        boolean fitsInX = m_upperLeft.getX() <= p.getX() && p.getX() <= m_lowerRight.getX();
        boolean fitsInY =  m_lowerRight.getY() <= p.getY() && p.getY() <= m_upperLeft.getY();

        return fitsInX && fitsInY;
    }

    boolean overlapsWith(Rectangle r)
    {
        // Left side
        for (int y = m_lowerRight.getY(); y <= m_upperLeft.getY(); y++) {
            if (r.containsPoint(new Point(m_upperLeft.getX(), y))) {
                return true;
            }
        }

        // Top side
        for (int x = m_upperLeft.getX(); x <= m_lowerRight.getX(); x++) {
            if (r.containsPoint(new Point(x, m_upperLeft.getY()))) {
                return true;
            }
        }

        // Right side
        for (int y = m_lowerRight.getY(); y <= m_upperLeft.getY(); y++) {
            if (r.containsPoint(new Point(m_lowerRight.getX(), y))) {
                return true;
            }
        }

        // Bottom side
        for (int x = m_upperLeft.getX(); x <= m_lowerRight.getX(); x++) {
            if (r.containsPoint(new Point(x, m_lowerRight.getY()))) {
                return true;
            }
        }

        return false;
    }
}

class OverlappingRectangles
{
    public static void main (String[] args)
            throws IOException
    {
        File file = new File(args[0]);
        BufferedReader in = new BufferedReader(new FileReader(file));
        String line;

        while ((line = in.readLine()) != null) {
            line = line.trim();

            if (line.length() == 0) {
                continue;
            }

            String[] stringArray = line.split(",");
            int[] intArray = new int[stringArray.length];

            for (int i = 0; i < intArray.length; i++) {
                intArray[i] = Integer.parseInt(stringArray[i].trim());
            }

            Rectangle r1 = new Rectangle(
                    new Point(intArray[0], intArray[1]),
                    new Point(intArray[2], intArray[3]));
            Rectangle r2 = new Rectangle(
                    new Point(intArray[4], intArray[5]),
                    new Point(intArray[6], intArray[7]));

            if (r1.overlapsWith(r2)) {
                System.out.println("True");
            } else {
                System.out.println("False");
            }

        }

        in.close();
    }
}

Add Java solution to the overlapping rectangles problem


package com.alma.pay2bid.gui;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

/**
 * Created by Folkvir(Grall Arnaud)) on 28/09/16.
 */
public class ClientGui {
    private JFrame mainFrame;
    private JLabel headerLabel;
    private JLabel statusLabel;
    private JPanel controlPanel;

    /**
     * Constructor
     */
    public ClientGui(){
        createGui();
    }

    private void createGui(){
        mainFrame = new JFrame("Pay2Bid - Auction");
        mainFrame.setSize(400,400);
        mainFrame.setLayout(new GridLayout(3, 1));

        headerLabel = new JLabel("",JLabel.CENTER );
        statusLabel = new JLabel("",JLabel.CENTER);

        statusLabel.setSize(350,100);
        mainFrame.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent windowEvent){
                System.exit(0);
            }
        });
        controlPanel = new JPanel();
        controlPanel.setLayout(new FlowLayout());

        mainFrame.add(headerLabel);
        mainFrame.add(controlPanel);
        mainFrame.add(statusLabel);
        mainFrame.setVisible(true);
    }

    private void prepareView(){
        headerLabel.setText("Control in action: Button");

        JButton okButton = new JButton("OK");
        JButton submitButton = new JButton("Submit");
        JButton cancelButton = new JButton("Cancel");

        okButton.setActionCommand("OK");
        submitButton.setActionCommand("Submit");
        cancelButton.setActionCommand("Cancel");

        okButton.addActionListener(new ButtonClickListener());
        submitButton.addActionListener(new ButtonClickListener());
        cancelButton.addActionListener(new ButtonClickListener());

        controlPanel.add(okButton);
        controlPanel.add(submitButton);
        controlPanel.add(cancelButton);

        mainFrame.setVisible(true);
    }

    private class ButtonClickListener implements ActionListener {
        public void actionPerformed(ActionEvent e) {
            String command = e.getActionCommand();
            if( command.equals( "OK" ))  {
                statusLabel.setText("Ok Button clicked.");
            }
            else if( command.equals( "Submit" ) )  {
                statusLabel.setText("Submit Button clicked.");
            }
            else  {
                statusLabel.setText("Cancel Button clicked.");
            }
        }
    }

    public static void main(String[] args){
        ClientGui c = new ClientGui();
        c.prepareView();
    }
}

Add gui package and a gui

Add gui package and a gui


/**
 * Copyright (c) 2015 deniskir@gmail.com. All rights reserved.
 *
 * @author Denis Kiriusin
 */

package com.dksoftware.combo;

import java.util.regex.Pattern;

import org.junit.Assert;
import org.junit.Test;

/**
 * Tests regular expressions used within the project.
 */
public class RegExTest {

	@Test
	public void testSectionContainsText() {
		final String text = "This is \t a\n \ta \n Combinatorius \n\n servlet \n";
		Pattern p = Pattern.compile("(?s)(?:.*Combinatorius.*)");
		Assert.assertTrue(p.matcher(text).find());
	}

	@Test
	public void testSectionContainsTextCaseSensitive() {
		final String text = "This is \t a\n \ta \n combinatorius \n\n servlet \n";
		Pattern p = Pattern.compile("(?s)(?:.*Combinatorius.*)");
		Assert.assertFalse(p.matcher(text).find());
	}

	@Test
	public void testSectionContainsTextCaseInsensitive() {
		final String text = "This is \t a\n \ta \n combinatorius \n\n servlet \n";
		Pattern p = Pattern.compile("(?s)(?i:.*Combinatorius.*)");
		Assert.assertTrue(p.matcher(text).find());
	}
}

Add unit tests for commonly used regular expressions.


/*
 * Created on 13-Jan-2006
 */
package uk.org.ponder.rsf.components;

import uk.org.ponder.beanutil.BeanUtil;

/** A special class to hold EL references so they may be detected in the
 * component tree. When held in this member, it is devoid of the packaging #{..}
 * characters - they are removed and replaced by the parser in transit from
 * XML form.
 * @author Antranig Basman (amb26@ponder.org.uk)
 *
 */
// TODO: in RSF 0.8 this class will be deprecated in favour of the version
// in PUC.
public class ELReference {
  public ELReference() {}
  public ELReference(String value) {
    String stripped = BeanUtil.stripEL(value);
    this.value = stripped == null? value : stripped;
  }
  public String value;
  public static ELReference make(String value) {
    return value == null? null : new ELReference(value);
  }
}

/*
 * Created on 13-Jan-2006
 */
package uk.org.ponder.rsf.components;

import uk.org.ponder.beanutil.BeanUtil;

/** A special class to hold EL references so they may be detected in the
 * component tree. When held in this member, it is devoid of the packaging #{..}
 * characters - they are removed and replaced by the parser in transit from
 * XML form.
 * @author Antranig Basman (amb26@ponder.org.uk)
 *
 */
// TODO: in RSF 0.8 this class will be deprecated in favour of the version
// in PUC.
public class ELReference {
  public ELReference() {}
  public ELReference(String value) {
    String stripped = BeanUtil.stripEL(value);
    this.value = stripped == null? value : stripped;
    if ("".equals(value)) {
      throw new IllegalArgumentException(
          "Cannot issue an EL reference to an empty path. For an empty binding please either supply null, or else provide a non-empty String as path");
    }
  }
  public String value;
  public static ELReference make(String value) {
    return value == null? null : new ELReference(value);
  }
}

Fix for RSF-42, binding to empty String

Fix for RSF-42, binding to empty String


/**
 * This source file is subject to the license that is bundled with this package in the file LICENSE.
 */
package com.codeup.movies.catalog;

import com.codeup.movies.Movies;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;

import static org.mockito.Mockito.verify;

@RunWith(MockitoJUnitRunner.class)
public class SearchMovieByTitleTest {
    @Test
    public void it_filters_movies_by_similar_titles() {
        String title = "on";
        searchMovieByTitle.withSimilarTitle(title);

        verify(movies).withTitleSimilarTo(title);
    }

    @Before
    public void configureCommand() {
        searchMovieByTitle = new SearchMovieByTitle(movies);
    }

    private SearchMovieByTitle searchMovieByTitle;

    @Mock
    Movies movies;
}

Add tests for SearchMovieByTitle class.

Add tests for SearchMovieByTitle class.


package nl.ap.hillclimbing;

public class Queens {

    public static boolean isConsistent(int[] q, int n) {
        for (int i = 0; i < n; i++) {
            if (q[i] == q[n]) {
                return false; // same column
            }

            if ((q[i] - q[n]) == (n - i)) {
                return false; // same major diagonal
            }

            if ((q[n] - q[i]) == (n - i)) {
                return false; // same minor diagonal
            }
        }

        return true;
    }

    public static void printQueens(int[] q) {
        int N = q.length;

        for (int i = 0; i < N; i++) {
            for (int j = 0; j < N; j++) {
                if (q[i] == j) {
                    System.out.print("Q  ");
                } else {
                    System.out.print("*  ");
                }
            }

            System.out.println();
        }

        System.out.println();
    }

    public static void enumerate(int N) {
        int[] a = new int[N];

        enumerate(a, 0);
    }

    public static boolean enumerate(int[] q, int n) {
        int N = q.length;

        if (n == N) {
            printQueens(q);

            return true;
        } else {
            for (int i = 0; i < N; i++) {
                q[n] = i;

                if (isConsistent(q, n)) {
                    if (enumerate(q, n + 1)) {
                        return true;
                    }
                }
            }
        }

        return false;
    }

    public static void main(String[] args) {
        enumerate(new int[] {0, 0, 0, 0, 0, 0, 0, 0}, 0);

        enumerate(new int[] {5, 0, 0, 0, 0, 0, 0, 0}, 1);

        enumerate(new int[] {5, 3, 0, 0, 0, 0, 0, 0}, 2);

        enumerate(new int[] {5, 3, 0, 0, 0, 0, 0, 0, 5, 3, 0, 0, 0, 0, 0, 0}, 0);

        enumerate(new int[] {0, 0, 0, 0, 0, 0}, 0);

        enumerate(new int[] {0, 0}, 0);
    }

}

Add code for queens puzzle

Add code for queens puzzle


package leetcode.bitwise_and_of_numbers_range;

public class Solution {
    public int rangeBitwiseAnd(int m, int n) {
        int ans = 0;
        for(int i = 0; i < 31; i++){
            if((m & ~((1 << i) - 1)) == (n & ~((1 << i) - 1))){
                ans |= (1 << i) & m;
            }
        }
        return ans;
    }
}

Add java solution for 201. Bitwise AND of Numbers Range

201. Bitwise AND of Numbers Range: https://leetcode.com/problems/bitwise-and-of-numbers-range/


/*
 * Copyright 2014 TORCH GmbH
 *
 * 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.graylog2.gelfclient.encoder;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufInputStream;
import io.netty.buffer.Unpooled;
import io.netty.channel.embedded.EmbeddedChannel;
import org.testng.annotations.Test;

import java.nio.charset.StandardCharsets;
import java.util.zip.GZIPInputStream;

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

public class GelfCompressionEncoderTest {

    @Test
    public void testEncode() throws Exception {
        final EmbeddedChannel channel = new EmbeddedChannel(new GelfCompressionEncoder());
        final String message = "Test string";

        assertTrue(channel.writeOutbound(Unpooled.wrappedBuffer(message.getBytes(StandardCharsets.UTF_8))));
        assertTrue(channel.finish());

        final ByteBufInputStream byteBufInputStream = new ByteBufInputStream((ByteBuf) channel.readOutbound());
        final GZIPInputStream gzipInputStream = new GZIPInputStream(byteBufInputStream);

        byte[] bytes = new byte[message.length()];

        assertEquals(message.length(), gzipInputStream.read(bytes, 0, message.length()));
        assertEquals(message, new String(bytes, StandardCharsets.UTF_8));
    }
}

Add unit test for GelfCompressionEncoder


package com.abhi.fyberdemo;

import android.support.v4.app.Fragment;
import android.view.View;

import com.abhi.fyberdemo.fragments.FormFragment;
import com.abhi.fyberdemo.fragments.OffersFragment;
import com.abhi.fyberdemo.models.OfferResponse;

import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mockito;
import org.robolectric.Robolectric;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.annotation.Config;

/**
 * Created by abhi on 28/10/16.
 */
@RunWith(RobolectricTestRunner.class)
@Config(constants = BuildConfig.class, sdk = 23)
public class MainActivityTest {
    private MainActivity mMainActivity;

    @Before
    public void setUp() throws Exception {
        mMainActivity = Robolectric.setupActivity(MainActivity.class);
    }

    @Test
    public void showFormFragment() throws Exception {
        mMainActivity.showFormFragment();
        Fragment _fragment = mMainActivity.getSupportFragmentManager().findFragmentById(R.id.frag_container);
        Assert.assertTrue("FormFragment is not displayed",_fragment.getClass()== FormFragment.class);
    }

    @Test
    public void showOffersFragment() throws Exception {
        OfferResponse _offerResponse = Mockito.mock(OfferResponse.class);
        mMainActivity.showOffersFragment(_offerResponse);
        Fragment _fragment = mMainActivity.getSupportFragmentManager().findFragmentById(R.id.frag_container);
        Assert.assertTrue("FormFragment is not displayed",_fragment.getClass()== OffersFragment.class);
    }

    @Test
    public void onOfferReceived() throws Exception {
        OfferResponse _offerResponse = Mockito.mock(OfferResponse.class);
        mMainActivity.onOfferReceived(_offerResponse);
        Fragment _fragment = mMainActivity.getSupportFragmentManager().findFragmentById(R.id.frag_container);
        Assert.assertTrue("FormFragment is not displayed",_fragment.getClass()== OffersFragment.class);
    }

    @Test
    public void onShowProgress() throws Exception {
        mMainActivity.onShowProgress();
        Assert.assertTrue("ProgressBar is not displayed",mMainActivity.mProgressBar.getVisibility()== View.VISIBLE);
    }

    @Test
    public void onHideProgress() throws Exception {
        mMainActivity.onHideProgress();
        Assert.assertTrue("ProgressBar is not hidden",mMainActivity.mProgressBar.getVisibility()== View.GONE);
    }

}

Add Roboelectric Unit Test for MainActivity


package stopheracleum.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import stopheracleum.model.User;
import stopheracleum.security.SecurityService;
import stopheracleum.service.UserService;
import stopheracleum.validator.UserValidator;

/**
 * Controller for {@link stopheracleum.model.User}'s pages.
 */

@Controller
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private SecurityService securityService;

    @Autowired
    private UserValidator userValidator;

    @RequestMapping(value = "/registration", method = RequestMethod.GET)
    public String registration(Model model) {
        model.addAttribute("userForm", new User());

        return "registration";
    }

    @RequestMapping(value = "/registration", method = RequestMethod.POST)
    public String registration(@ModelAttribute("userForm") User userForm, BindingResult bindingResult, Model model) {
        userValidator.validate(userForm, bindingResult);

        if (bindingResult.hasErrors()) {
            return "registration";
        }

        userService.save(userForm);

        securityService.autoLogin(userForm.getUsername(), userForm.getConfirmPassword());

        return "redirect:/welcome";
    }

    @RequestMapping(value = "/login", method = RequestMethod.GET)
    public String login(Model model, String error, String logout) {
        if (error != null) {
            model.addAttribute("error", "Username or password is incorrect.");
        }

        if (logout != null) {
            model.addAttribute("message", "Logged out successfully.");
        }

        return "login";
    }

    @RequestMapping(value = {"/", "/welcome"}, method = RequestMethod.GET)
    public String welcome(Model model) {
        return "welcome";
    }

    @RequestMapping(value = "/admin", method = RequestMethod.GET)
    public String admin(Model model) {
        return "admin";
    }
}

Add controller for user's pages

Add controller for user's pages


package org.kuali.kd2013.dataobject;

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

import org.kuali.rice.core.api.util.ConcreteKeyValue;
import org.kuali.rice.core.api.util.KeyValue;
import org.kuali.rice.krad.keyvalues.KeyValuesBase;

public class AwardProgramValuesFinder extends KeyValuesBase {
	private static final long serialVersionUID = 1L;

	static List<KeyValue> VALUES = new ArrayList<KeyValue>(4);
	static {
		VALUES.add( new ConcreteKeyValue("", "") );
		VALUES.add( new ConcreteKeyValue("CRG 1", "CRG 1") );
		VALUES.add( new ConcreteKeyValue("CRG 2", "CRG 2") );
		VALUES.add( new ConcreteKeyValue("CRG 3", "CRG 3") );
		VALUES.add( new ConcreteKeyValue("CCF", "CCF") );
		VALUES.add( new ConcreteKeyValue("Sensors", "Sensors") );
	}

	@Override
	public List<KeyValue> getKeyValues() {
		return Collections.unmodifiableList(VALUES);
	}

}

Add key value finders for awards

Add key value finders for awards


package net.darkhax.bookshelf.api.util;

import net.minecraft.world.entity.Entity;
import net.minecraft.world.entity.LivingEntity;
import net.minecraft.world.entity.MobType;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.item.enchantment.EnchantmentHelper;

/**
 * This class contains static helper methods for working with ItemStacks.
 */
public final class ItemStackHelper {

    /**
     * Calculates the attack damage for an ItemStack when used to attack an unspecified mob. This will include bonus
     * damage sources such as modifiers and enchantments.
     *
     * @param stack The ItemStack to calculate the damage value of.
     * @return The attack damage for an ItemStack with bonus damage modifiers applied.
     */
    public static double getAttackDamage(ItemStack stack) {

        return getAttackDamage(stack, MobType.UNDEFINED);
    }

    /**
     * Calculates the attack damage for an ItemStack when used to attack a specific entity. This will include bonus
     * damage sources such as attribute modifiers and enchantments.
     *
     * @param stack  The ItemStack to calculate the damage value of.
     * @param target The target entity being attacked.
     * @return The attack damage for an ItemStack with bonus damage modifiers applied.
     */
    public static double getAttackDamage(ItemStack stack, Entity target) {

        return getAttackDamage(stack, (target instanceof LivingEntity living) ? living.getMobType() : MobType.UNDEFINED);
    }

    /**
     * Calculates the attack damage for an ItemStack after accounting for bonus damage modifiers such as attribute
     * modifiers and enchantments.
     *
     * @param stack      The ItemStack to calculate the damage value of.
     * @param targetType The type of mob being attacked. Used for some enchantment calculations.
     * @return The attack damage for an ItemStack with bonus damage modifiers applied.
     */
    public static double getAttackDamage(ItemStack stack, MobType targetType) {

        final double damage = AttributeHelper.getAttackDamage(stack);
        final double bonusEnchantmentDamage = EnchantmentHelper.getDamageBonus(stack, targetType);

        return damage + bonusEnchantmentDamage;
    }
}

Add helper for working with ItemStacks.

Add helper for working with ItemStacks.


package org.app.material.widget;

import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.helper.ItemTouchHelper;

public class ItemTouchHelperClass extends ItemTouchHelper.Callback {

    private ItemTouchHelperAdapter adapter;

    public interface ItemTouchHelperAdapter {

        void onItemMoved(int fromPosition, int toPosition);

        void onItemRemoved(int position);
    }

    public ItemTouchHelperClass(ItemTouchHelperAdapter ad){
        this.adapter = ad;
    }

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

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

    @Override
    public int getMovementFlags(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder) {
        int upFlags = ItemTouchHelper.UP | ItemTouchHelper.DOWN;
        int swipeFlags = ItemTouchHelper.START | ItemTouchHelper.END;

        return makeMovementFlags(upFlags, swipeFlags);
    }

    @Override
    public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, RecyclerView.ViewHolder target) {
        adapter.onItemMoved(viewHolder.getAdapterPosition(), target.getAdapterPosition());
        return true;
    }

    @Override
    public void onSwiped(RecyclerView.ViewHolder viewHolder, int direction) {
        adapter.onItemRemoved(viewHolder.getAdapterPosition());
    }
}

Update item helper recycler view class

Update item helper recycler view class


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

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import io.fabric8.kubernetes.client.KubernetesClient;
import static org.junit.Assert.assertNotNull;

@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = { KubernetesClient.class})
public class KubernetesClientTest {

    @Autowired
    private KubernetesClient client;

    @Test
    public void clientShouldNotBeNull() {
        assertNotNull(client);
    }

}

Add tiny little unit test to ensure that the client can be autowired.


package com.mpay24.payment;

import static org.junit.Assert.assertNotNull;

import java.text.ParseException;
import java.util.List;

import org.apache.log4j.Logger;
import org.junit.After;
import org.junit.Test;

import com.mpay24.payment.data.PaymentData;

public class TestCreateCustomer extends AbstractTestCase {
	public final static Logger log = Logger.getLogger(TestCreateCustomer.class);

	@After
	public void tearDown() throws Exception {
	}

	@Test
	public void testCreateCreditCardCustomer() throws ParseException, PaymentException {
		String customerId = "max.mustermann@gmail.com";
		deleteProfileForTest(customerId);
		mpay24.createCustomer(getCustomer(), getVisaTestData());
		List<PaymentData> storedPaymentDataList = mpay24.listCustomers(customerId, null, null, null);
		assertNotNull(storedPaymentDataList);
	}

	private void deleteProfileForTest(String customerId) {
		try {
			mpay24.deleteCustomer(customerId, null);
		} catch (PaymentException e) {
			// OK if Profile does not exist
		}
	}

}

Add new functionality to store a customer without a payment


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

/**
 * Given a matrix full of 1's and 0's can you write a method to fill part of the matrix using a
 * number?
 *
 * @author Pedro Vicente Gómez Sánchez.
 */
public class FloodFill {
}

Add statement to problem 42

Add statement to problem 42


/* This file is part of SableCC ( http://sablecc.org ).
 *
 * See the NOTICE file distributed with this work for copyright information.
 *
 * 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.sablecc.sablecc.automaton;

import static org.junit.Assert.fail;

import org.junit.Before;
import org.junit.Test;
import org.sablecc.sablecc.alphabet.Realms;
import org.sablecc.sablecc.exception.InternalException;

public class MinimalDfaTest {

    MinimalDfa<Integer> minimalDfa;

    Dfa<Integer> dfa;

    @Before
    public void setUp()
            throws Exception {

        this.dfa = new Dfa<Integer>(new Nfa<Integer>(Realms.getInteger()
                .createInterval(10)).oneOrMore());
        this.minimalDfa = new MinimalDfa<Integer>(this.dfa);
    }

    @Test
    public void testMinimalDfa() {

        // Case with null Dfa
        Dfa<Integer> nullDfa = null;
        try {
            this.minimalDfa = new MinimalDfa<Integer>(nullDfa);
            fail("dfa may not be null");
        }
        catch (InternalException e) {
            // Expected
        }
    }
}

Add JUnit tests. See ticket:44.

Add JUnit tests. See ticket:44.

Signed-off-by: Raymond Audet <281aa2b19aab01efe2941a7da076ec0616a9b992@gmail.com>
Signed-off-by: Etienne M. Gagnon <bf06ec0eb40152cd863534753d026b021022c851@j-meg.com>


package com.easternedgerobotics.rov.control;

import com.easternedgerobotics.rov.value.MotionValue;

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

import java.util.Arrays;

@RunWith(Parameterized.class)
@SuppressWarnings({"checkstyle:magicnumber"})
public class ExponentialMotionScaleTest {
    @Parameterized.Parameters(name = "Input {0} => Output {1}")
    public static Iterable<Float[]> data() {
        return Arrays.asList(new Float[][] {
            {0.00f,        0f},
            {0.05f, 0.029839f},
            {0.10f, 0.061207f},
            {0.15f, 0.094184f},
            {0.20f, 0.128851f},
            {0.25f, 0.165296f},
            {0.30f, 0.203610f},
            {0.35f, 0.243888f},
            {0.40f, 0.286231f},
            {0.45f, 0.330744f},
            {0.50f, 0.377541f},
            {0.55f, 0.426736f},
            {0.60f, 0.478454f},
            {0.65f, 0.532823f},
            {0.70f, 0.589980f},
            {0.75f, 0.650068f},
            {0.80f, 0.713236f},
            {0.85f, 0.779643f},
            {0.90f, 0.849455f},
            {0.95f, 0.922846f},
            {1.00f,        1f}
        });
    }

    private final float input;

    private final float expected;

    public ExponentialMotionScaleTest(final float input, final float expected) {
        this.input = input;
        this.expected = expected;
    }

    @Test
    public final void exponentialScaling() {
        final ExponentialMotionScale scale = new ExponentialMotionScale();
        final MotionValue inputMotion = MotionValue.create(input, 0, 0, 0, 0, 0);
        final MotionValue expectedMotion = MotionValue.create(expected, 0, 0, 0, 0, 0);
        Assert.assertEquals(expectedMotion, scale.apply(inputMotion));
    }
}

Add test cases for joystick input scaling


package co.omise.resources;

import co.omise.models.OmiseException;
import co.omise.models.Source;
import org.junit.Test;

import java.io.IOException;

public class SourceResourceTest extends ResourceTest {

    @Test
    public void testCreateAliPaySource() throws IOException, OmiseException {
        Source source = resource().create(new Source.Create()
                .amount(100000)
                .currency("thb")
                .type("alipay")
                .barcode("xyz")
                .invoiceId("abc"));

        assertRequested("POST", "/sources", 200);
        assertEquals(100000L, source.getAmount());
        assertEquals("thb", source.getCurrency());
        assertEquals("alipay", source.getType());
        assertEquals("xyz", source.getBarcode());
        assertEquals("abc", source.getInvoiceId());
    }

    private SourceResource resource() {
        return new SourceResource(testClient());
    }
}

Create unit test to source.

Create unit test to source.


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

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

/**
 * This annotation is used to create an 'empty' instance of the
 * current component type.
 * @author Felix Project Team
 */
@Target(ElementType.TYPE)
public @interface Instantiate {

    /**
     * Optional attribute to set the instance name.
     * Default: no name
     */
    String name() default "";
}

Add the instantiate annotation (FELIX-1940)

git-svn-id: e057f57e93a604d3b43d277ae69bde5ebf332112@892614 13f79535-47bb-0310-9956-ffa450edef68


package com.alibaba.rocketmq.example.smoking;

import com.alibaba.rocketmq.client.store.DefaultLocalMessageStore;
import com.alibaba.rocketmq.client.store.LocalMessageStore;
import com.alibaba.rocketmq.common.message.Message;

import java.io.IOException;
import java.util.Arrays;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

public class LocalStore {
    private static volatile int prev;

    public static void main(String[] args) throws IOException {
        final LocalMessageStore localMessageStore = new DefaultLocalMessageStore("Test");
        localMessageStore.start();
        int parallelism = 10;
        final AtomicInteger count = new AtomicInteger();

        final byte[] data = new byte[1024];
        Arrays.fill(data, (byte)'x');
        final Message message = new Message("TestTopic", data);
        final AtomicInteger round = new AtomicInteger(5);

        ScheduledExecutorService executorService = Executors.newScheduledThreadPool(parallelism);
        for (int i = 0; i < parallelism - 1; i++) {
            executorService.submit(new Runnable() {
                @Override
                public void run() {
                    while (round.get() > 0) {
                        try {
                            localMessageStore.stash(message);
                            count.incrementAndGet();
                        } catch (Exception ignore) {
                        }
                    }
                }
            });
        }

        executorService.schedule(new Runnable() {
            @Override
            public void run() {
                int stopWatch = count.get();
                System.out.println("QPS: " + (stopWatch - prev) / 30);
                prev = stopWatch;
                if (round.decrementAndGet() < 0) {
                    localMessageStore.close();
                }
            }
        }, 30, TimeUnit.SECONDS);
    }
}

Add benchmarking of local message store.


/*
 * 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.commonwl.viewer;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.mongodb.MongoDbFactory;
import org.springframework.data.mongodb.core.convert.DbRefResolver;
import org.springframework.data.mongodb.core.convert.DefaultDbRefResolver;
import org.springframework.data.mongodb.core.convert.MappingMongoConverter;
import org.springframework.data.mongodb.core.mapping.MongoMappingContext;

@Configuration
public class MongoConfig {

    @Autowired
    private MongoDbFactory mongoFactory;

    @Autowired
    private MongoMappingContext mongoMappingContext;

    /**
     * Override the default converter which just throws an error with special chars
     */
    @Bean
    public MappingMongoConverter mongoConverter() throws Exception {
        DbRefResolver dbRefResolver = new DefaultDbRefResolver(mongoFactory);
        MappingMongoConverter mongoConverter = new MappingMongoConverter(dbRefResolver, mongoMappingContext);

        // Replace dot with the unicode replacement character
        mongoConverter.setMapKeyDotReplacement("\uFFFD");

        return mongoConverter;
    }
}

Allow the use of the dot character in workflow IDs

Closes #90


package com.github.shredder121.gh_event_api.testutil;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.deser.DeserializationProblemHandler;
import com.fasterxml.jackson.databind.module.SimpleModule;

/**
 * An additional module that configures printing a warning about properties that exist in JSON form, but not in the source.
 *
 * @author Shredder121
 */
@Component
@SuppressWarnings("serial") // Interoperability is not required
class GHEventApiTestModule extends SimpleModule {

    public GHEventApiTestModule() {
        super("GHEventApiServerTest");
    }

    @Override
    public void setupModule(SetupContext context) {
        context.addDeserializationProblemHandler(new WarningDeserializationProblemHandler());
    }

    static class WarningDeserializationProblemHandler extends DeserializationProblemHandler {

        static Logger logger = LoggerFactory.getLogger(WarningDeserializationProblemHandler.class);

        @Override
        public boolean handleUnknownProperty(DeserializationContext ctxt, JsonParser jp, JsonDeserializer<?> deserializer, Object beanOrClass, String propertyName) {
            logger.debug("Unhandled field {}.{}", beanOrClass.getClass(), propertyName);
            return false;
        }
    }
}

Print debug level warnings about unknown properties in the tests


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

import org.junit.Test;

public class TestWithTimeout {

    @Test(timeout = 1000)
    public void test() throws InterruptedException {
        Thread.sleep(2000);
    }

}

Include a JUnit 4 with timeout example

Include a JUnit 4 with timeout example


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

import org.junit.Test;

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

/**
 * Raft session event test.
 */
public class RaftSessionEventTest {
  @Test
  public void testRaftSessionEvent() throws Exception {
    RaftSession session = mock(RaftSession.class);
    long timestamp = System.currentTimeMillis();
    RaftSessionEvent event = new RaftSessionEvent(RaftSessionEvent.Type.OPEN, session, timestamp);
    assertEquals(RaftSessionEvent.Type.OPEN, event.type());
    assertEquals(session, event.subject());
    assertEquals(timestamp, event.time());
  }
}

Add Raft session event test.

Add Raft session event test.


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

import static org.mockito.Mockito.*;

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

import javax.swing.AbstractButton;

import org.junit.Test;
import org.mockito.Matchers;

import rx.subscriptions.Subscriptions;
import rx.util.functions.Action0;
import rx.util.functions.Action1;
import rx.util.functions.Func1;

public enum SwingObservable { ; // no instances

    public static Observable<ActionEvent> fromButtonAction(final AbstractButton button) {
        return Observable.create(new Func1<Observer<ActionEvent>, Subscription>() {
            @Override
            public Subscription call(final Observer<ActionEvent> observer) {
                final ActionListener listener = new ActionListener() {
                    @Override
                    public void actionPerformed(ActionEvent e) {
                        observer.onNext(e);
                    }
                };
                button.addActionListener(listener);

                return Subscriptions.create(new Action0() {
                    @Override
                    public void call() {
                        button.removeActionListener(listener);
                    }
                });
            }
        });
    }

    public static class UnitTest {
        @Test
        public void testObservingActionEvents() {
            @SuppressWarnings("unchecked")
            Action1<ActionEvent> action = mock(Action1.class);
            @SuppressWarnings("unchecked")
            Action1<Exception> error = mock(Action1.class);
            Action0 complete = mock(Action0.class);

            final ActionEvent event = new ActionEvent(this, 1, "command");

            class TestButton extends AbstractButton {
                void testAction() {
                    fireActionPerformed(event);
                }
            }

            TestButton button = new TestButton();
            Subscription sub = fromButtonAction(button).subscribe(action, error, complete);

            verify(action, never()).call(Matchers.<ActionEvent>any());
            verify(error, never()).call(Matchers.<Exception>any());
            verify(complete, never()).call();

            button.testAction();
            verify(action, times(1)).call(Matchers.<ActionEvent>any());

            button.testAction();
            verify(action, times(2)).call(Matchers.<ActionEvent>any());

            sub.unsubscribe();
            button.testAction();
            verify(action, times(2)).call(Matchers.<ActionEvent>any());
            verify(error, never()).call(Matchers.<Exception>any());
            verify(complete, never()).call();
        }
    }
}

Allow creating observables from `AbstractButton`s.


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

package org.pentaho.di.trans.steps.splitfieldtorows;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.junit.BeforeClass;
import org.junit.Test;
import org.pentaho.di.core.KettleEnvironment;
import org.pentaho.di.core.exception.KettleException;
import org.pentaho.di.trans.steps.loadsave.LoadSaveTester;
import org.pentaho.di.trans.steps.loadsave.validator.FieldLoadSaveValidator;

public class SplitFieldToRowsMetaTest {

  @BeforeClass
  public static void setUpBeforeClass() throws KettleException {
    KettleEnvironment.init( false );
  }

  @Test
  public void loadSaveTest() throws KettleException {
    List<String> attributes = Arrays.asList( "splitField", "delimiter", "newFieldname", "includeRowNumber",
      "rowNumberField", "resetRowNumber", "delimiterRegex" );

    Map<String, String> getterMap = new HashMap<String, String>();
    getterMap.put( "includeRowNumber", "includeRowNumber" );
    getterMap.put( "resetRowNumber", "resetRowNumber" );

    Map<String, String> setterMap = new HashMap<String, String>();

    LoadSaveTester loadSaveTester = new LoadSaveTester(
      SplitFieldToRowsMeta.class, attributes, getterMap, setterMap,
      new HashMap<String, FieldLoadSaveValidator<?>>(), new HashMap<String, FieldLoadSaveValidator<?>>() );
    loadSaveTester.testRepoRoundTrip();
    loadSaveTester.testXmlRoundTrip();
  }
}

Split Field to Rows LoadSaveTest

[TEST] Split Field to Rows LoadSaveTest


/*
 * SubIterator.java
 *
 * Author: Ming Tsang
 * Copyright (c) 2015 Ming Tsang
 * Refer to LICENSE for details
 */

package com.nkming.utils.type;

import java.util.Iterator;
import java.util.NoSuchElementException;

/**
 * An Iterator that iterates a subset of another Iterator. For List, consider
 * List#subList instead
 *
 * @param <T>
 */
public class SubIterator<T> implements Iterator<T>
{
	/**
	 * Create an Iterator that iterate between [start, end) in @a it
	 *
	 * @param it
	 * @param start
	 * @param end
	 */
	public SubIterator(Iterator<T> it, int start, int end)
	{
		mIt = it;
		for (int i = 0; i < start && mIt.hasNext(); ++i)
		{
			mIt.next();
		}
		mLeft = end - start;
	}

	@Override
	public boolean hasNext()
	{
		return (mIt.hasNext() && mLeft > 0);
	}

	@Override
	public T next()
	{
		if (!hasNext())
		{
			throw new NoSuchElementException();
		}
		else
		{
			--mLeft;
			return mIt.next();
		}
	}

	@Override
	public void remove()
	{
		mIt.remove();
	}

	private Iterator<T> mIt;
	private int mLeft;
}

Add iterator that is a subpart of another iterator


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

/**
 * Given an array of available money and a value as input, can you write a method to return all
 * that change using the less money as possible.
 *
 * @author Pedro Vicente Gómez Sánchez.
 */
public class ReturnChange {
}

Add statement to problem 47

Add statement to problem 47


package com.oreilly.learningsparkexamples.java;
import java.io.Serializable;

class HappyPerson implements Serializable {
  private String name;
  private String favouriteBeverage;
  public HappyPerson() {}
  public HappyPerson(String n, String b) {
    name = n; favouriteBeverage = b;
  }
  public String getName() { return name; }
  public void setName(String n) { name = n; }
  public String getFavouriteBeverage() { return favouriteBeverage; }
  public void setFavouriteBeverage(String b) { favouriteBeverage = b; }
};

Add a JavaBean based Spark SQL example

Add a JavaBean based Spark SQL example


package com.squareup.protoparser;

import java.io.File;
import java.util.ArrayDeque;
import java.util.Collections;
import java.util.Deque;

/** Recursively traverse a directory and attempt to parse all of its proto files. */
public class ParsingTester {
  /** Directory under which to search for protos. Change as needed. */
  private static final File ROOT = new File("/path/to/protos");

  public static void main(String... args) {
    int total = 0;
    int failed = 0;

    Deque<File> fileQueue = new ArrayDeque<File>();
    fileQueue.add(ROOT);
    while (!fileQueue.isEmpty()) {
      File file = fileQueue.removeFirst();
      if (file.isDirectory()) {
        Collections.addAll(fileQueue, file.listFiles());
      } else if (file.getName().endsWith(".proto")) {
        System.out.println("Parsing " + file.getPath());
        total += 1;

        try {
          ProtoSchemaParser.parse(file);
        } catch (Exception e) {
          e.printStackTrace();
          failed += 1;
        }
      }
    }

    System.out.println("\nTotal: " + total + "  Failed: " + failed);
  }
}

Add simple directory-traversing parser for quickly testing the parser.


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

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

import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;

import io.github.bonigarcia.wdm.WebDriverManager;

/**
 * Test with Internet Explorer browser.
 *
 * @author Boni Garcia
 * @since 1.0.0
 */
@Disabled
class IETest {

    WebDriver driver;

    @BeforeAll
    static void setupClass() {
        WebDriverManager.iedriver().setup();
    }

    @BeforeEach
    void setupTest() {
        driver = new InternetExplorerDriver();
    }

    @AfterEach
    void teardown() {
        driver.quit();
    }

    @Test
    void test() {
        // Exercise
        driver.get("https://bonigarcia.dev/selenium-webdriver-java/");
        String title = driver.getTitle();

        // Verify
        assertThat(title).contains("Selenium WebDriver");
    }

}

Include IExplorer browser test (disabled by default)


/*
 * Copyright 2000-2011 JetBrains s.r.o.
 *
 * 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.
 */

/*
 * @author max
 */
package com.intellij.psi.search;

import com.intellij.openapi.util.io.FileUtil;

public abstract class SpecificNameItemProcessor implements PsiFileSystemItemProcessor {
  private final String myName;

  public String getName() {
    return myName;
  }

  protected SpecificNameItemProcessor(String name) {
    myName = name;
  }

  @Override
  public boolean acceptItem(String name, boolean isDirectory) {
    return FileUtil.pathsEqual(myName, name);
  }
}

Optimize imports resolving by processing a name -> file maps instead of linear lists.


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

import org.junit.Test;

import static org.apache.cassandra.utils.ByteBufferUtil.bytes;
import static org.apache.cassandra.utils.ByteBufferUtil.EMPTY_BYTE_BUFFER;

public class ReversedTypeTest
{
    @Test
    public void testReverseComparison()
    {
        ReversedType<Long> t = ReversedType.getInstance(LongType.instance);

        assert t.compare(bytes(2L), bytes(4L)) == 1;
        assert t.compare(bytes(4L), bytes(2L)) == -1;

        // the empty byte buffer is always the smaller
        assert t.compare(EMPTY_BYTE_BUFFER, bytes(2L)) == -1;
        assert t.compare(bytes(2L), EMPTY_BYTE_BUFFER) == 1;
    }
}

Add file missing from previous commit

Add file missing from previous commit

git-svn-id: 5b9f2d9930f7dfb79b2654297310ec296e5fde68@1164069 13f79535-47bb-0310-9956-ffa450edef68


package net.md_5.bungee.module.reconnect.yaml;

import net.md_5.bungee.api.plugin.Plugin;

public class PluginYaml extends Plugin
{

    @Override
    public void onEnable()
    {
        getProxy().setReconnectHandler( new YamlReconnectHandler() );
    }
}

package net.md_5.bungee.module.reconnect.yaml;

import net.md_5.bungee.api.config.ListenerInfo;
import net.md_5.bungee.api.plugin.Plugin;

public class PluginYaml extends Plugin
{

    @Override
    public void onEnable()
    {
        // TODO: Abstract this for other reconnect modules
        for ( ListenerInfo info : getProxy().getConfig().getListeners() )
        {
            if ( !info.isForceDefault() && getProxy().getReconnectHandler() == null )
            {
                getProxy().setReconnectHandler( new YamlReconnectHandler() );
                break;
            }
        }
    }
}

Bring reconnect yaml handler setting in line with what we had before (only create if needed)


package org.interledger.everledger.common.util;

//REF: http://stackoverflow.com/questions/9755057/converting-strings-to-encryption-keys-and-vice-versa-java

// TODO:(0) Move to java-ilp-core/... utils/... ?
import java.security.*;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Arrays;
import java.util.Base64;
public class DSAPrivPubKeySupport {
 public static PrivateKey loadPrivateKey(String key64) throws GeneralSecurityException {
     byte[] clear = Base64.getDecoder().decode(key64);
     PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(clear);
     KeyFactory fact = KeyFactory.getInstance("DSA");
     PrivateKey priv = fact.generatePrivate(keySpec);
     Arrays.fill(clear, (byte) 0);
     return priv;
 }

 public static PublicKey loadPublicKey(String stored) throws GeneralSecurityException {
     byte[] data = Base64.getDecoder().decode(stored);
     X509EncodedKeySpec spec = new X509EncodedKeySpec(data);
     KeyFactory fact = KeyFactory.getInstance("DSA");
     return fact.generatePublic(spec);
 }

 public static String savePrivateKey(PrivateKey priv) throws GeneralSecurityException {
     KeyFactory fact = KeyFactory.getInstance("DSA");
     PKCS8EncodedKeySpec spec = fact.getKeySpec(priv,
             PKCS8EncodedKeySpec.class);
     byte[] packed = spec.getEncoded();
     String key64 = new String(Base64.getEncoder().encode(packed));
     Arrays.fill(packed, (byte) 0);
     return key64;
 }

 public static String savePublicKey(PublicKey publ) throws GeneralSecurityException {
     KeyFactory fact = KeyFactory.getInstance("DSA");
     X509EncodedKeySpec spec = fact.getKeySpec(publ,
             X509EncodedKeySpec.class);
     return new String(Base64.getEncoder().encode(spec.getEncoded()));
 }

 public static void main(String[] args) throws Exception {
     KeyPairGenerator gen = KeyPairGenerator.getInstance("DSA");
     KeyPair pair = gen.generateKeyPair();
     String pubKey = savePublicKey(pair.getPublic());
     String privKey = savePrivateKey(pair.getPrivate());
     System.out.println("privKey:"+privKey);
     System.out.println("pubKey :"+pubKey );
     // PublicKey pubSaved = loadPublicKey(pubKey);
     // System.out.println(pair.getPublic()+"\n"+pubSaved);
     // PrivateKey privSaved = loadPrivateKey(privKey);
     // System.out.println(pair.getPrivate()+"\n"+privSaved);
 }
}

Add Support to generate DSA-Ed25519 Pub/Priv Keys


package interfaces;

/**
 * Chat interface for Servers
 */
public interface ChatServer {
    /**
     * Configures and start a chat server
     */
    void setupServer();

    /**
     * Loop and wait for Socket client connections
     */
    void waitForClients();

}

Add an interface for chat servers

Add an interface for chat servers


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

package org.springframework.security.oauth2;

import org.junit.Ignore;
import org.junit.runner.RunWith;
import org.junit.runners.Suite;
import org.junit.runners.Suite.SuiteClasses;
import org.springframework.security.oauth2.config.annotation.AuthorizationServerConfigurationTests;
import org.springframework.security.oauth2.config.annotation.ResourceServerConfigurationTests;

/**
 * A test suite for probing weird ordering problems in the tests.
 *
 * @author Dave Syer
 */
@RunWith(Suite.class)
@SuiteClasses({ AuthorizationServerConfigurationTests.class,  ResourceServerConfigurationTests.class })
@Ignore
public class AdhocTestSuite {

}

Add test suite for ordering tests

Add test suite for ordering tests


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

package com.google.template.soy.shared.restricted;

import static java.lang.annotation.ElementType.TYPE;
import static java.lang.annotation.RetentionPolicy.RUNTIME;

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

/**
 * Optional annotation for SoySourceFunction indicating that uses can be migrated to an equivalent
 * extern.
 */
@Target(TYPE)
@Retention(RUNTIME)
public @interface ExternMigration {
  String file();
}

Create a linter to migrate functions to externs

PiperOrigin-RevId: 385612555


/**
 * Copyright (c) 2016, German Neuroinformatics Node (G-Node)
 *
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted under the terms of the BSD License. See
 * LICENSE file in the root of the Project.
 */

package org.g_node.reporter.LKTLogbook;

import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.Option;
import org.apache.commons.cli.Options;
import org.g_node.micro.commons.CliToolController;

/**
 * Class handling how to fetch reports from an RDF file specific to the LKT Logbook use case of Kay Thurley.
   *
 * @author Michael Sonntag (sonntag@bio.lmu.de)
 */
public class CliLKTController implements CliToolController {
    /**
     * Method returning the commandline options of the LKT reporter tool.
     *
     * @return Available {@link CommandLine} {@link Options}.
     */
    public final Options options() {

        final Options options = new Options();

        final Option opHelp = new Option("h", "help", false, "Print this message.");

        final String inDesc = String.join("",
                "RDF file containing the main database. ",
                "Data for the required report will be fetched from this file.");

        final Option opInRdfFile = Option.builder("i")
                .longOpt("input-rdf")
                .desc(inDesc)
                .required()
                .hasArg()
                .valueSeparator()
                .build();

        // TODO implement available reports
        final String reportDesc = String.join("",
                "Reports available to the selected tool.");

        final Option opReport = Option.builder("r")
                .longOpt("report")
                .desc(reportDesc)
                .required()
                .hasArg()
                .valueSeparator()
                .build();

        final String outDesc = String.join("",
                "Optional: Path and name of the output file. ",
                "Files with the same name will be overwritten. ");

        final Option opOut = Option.builder("o")
                .longOpt("out-file")
                .desc(outDesc)
                .hasArg()
                .valueSeparator()
                .build();

        final String formatDesc = String.join("",
                "Optional: format of the report file that will be written.\n",
                "\nDefault setting is the CSV format.");

        final Option opFormat = Option.builder("f")
                .longOpt("out-format")
                .desc(formatDesc)
                .hasArg()
                .valueSeparator()
                .build();

        options.addOption(opHelp);
        options.addOption(opInRdfFile);
        options.addOption(opReport);
        options.addOption(opOut);
        options.addOption(opFormat);

        return options;
    }

    /**
     * Method to check input file, available report, output file format and to facilitate the
     * delegation of creating the report and saving it an output file.
     *
     * @param cmd User provided {@link CommandLine} input.
     */
    public final void run(final CommandLine cmd) {
        System.out.println("Implement checks and actual call of reports.");
    }

}

Add controller for LKTLog use case

LKTLog: Add controller for LKTLog use case


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

import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
import junit.textui.TestRunner;

/**
 * Issue-specific test suite for Commons SCXML.
 *
 */
public class IssuesTestSuite extends TestCase {

    /**
     * Construct a new instance.
     */
    public IssuesTestSuite(String name) {
        super(name);
    }

    /**
     * Command-line interface.
     */
    public static void main(String[] args) {
        TestRunner.run(suite());
    }

    /**
     * Get the suite of tests
     */
    public static Test suite() {
        TestSuite suite = new TestSuite();
        suite.setName("Commons SCXML Issues Tests");
        return suite;
    }
}

Add the oacs.issues test package for adding tests specific to an issue (and its fix, if any).


package me.deftware.client.framework.wrappers.render;

import me.deftware.client.framework.utils.TexUtil;
import me.deftware.client.framework.wrappers.IResourceLocation;
import me.deftware.client.framework.wrappers.entity.IEntityPlayer;
import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.GlStateManager;
import net.minecraft.client.renderer.tileentity.TileEntityBeaconRenderer;
import net.minecraft.item.EnumDyeColor;

public class IBeaconRenderer {

    public static final IResourceLocation TEXTURE_BEACON_BEAM = new IResourceLocation("textures/entity/beacon_beam.png");

    public static void renderBeamAt(double x, double y, double z, float r, float g, float b, int height, float partialTicks) {
        if (height < 1) {
            throw new IllegalArgumentException("Height cannot be less than 1");
        }
        GlStateManager.alphaFunc(516, 0.1F);
        TexUtil.bindTexture(TEXTURE_BEACON_BEAM);
        GlStateManager.disableFog();
        x -= (IEntityPlayer.getPrevPosX() + (IEntityPlayer.getPosX() - IEntityPlayer.getPrevPosX()) * (double)partialTicks);
        y -= (IEntityPlayer.getPrevPosY() + (IEntityPlayer.getPosY() - IEntityPlayer.getPrevPosY()) * (double)partialTicks);
        z -= (IEntityPlayer.getPrevPosZ() + (IEntityPlayer.getPosZ() - IEntityPlayer.getPrevPosZ()) * (double)partialTicks);
        TileEntityBeaconRenderer.renderBeamSegment(x, y, z, partialTicks, 1.0, Minecraft.getMinecraft().world.getWorldTime(), 0, height, new float[]{r, g, b});
    }

    public static void renderBeamAt(double x, double y, double z, int height, float partialTicks) {
        float[] white = EnumDyeColor.WHITE.getColorComponentValues();
        renderBeamAt(x, y, z, white[0], white[1], white[2], height, partialTicks);
    }

}

Add methods to render beacon beams

Add methods to render beacon beams


package ch.heigvd.res.lab00;

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

/**
 * @author Abass MAHDAVI
 */

public class ClavierTest {
  @Test
  public void thereShouldBeAClavierClass() {
    IInstrument clavier = new Clavier();
    assertNotNull(clavier);
  }

  @Test
  public void itShouldBePossibleToPlayAClavier() {
    IInstrument clavier = new Clavier();
    String sound = clavier.play();
    assertNotNull(sound);
  }

  @Test
  public void aClavierShouldMakeDayyyn() {
    IInstrument clavier = new Clavier();
    String sound = clavier.play();
    Assert.assertEquals("dayyyn", sound);
  }

  @Test
  public void aClavierShouldNotBeMute() {
    IInstrument clavier = new Clavier();
    int clavierVolume = clavier.getSoundVolume();
    Assert.assertTrue(clavierVolume > 0);
  }

  @Test
  public void aClavierShouldBeIvory() {
    IInstrument clavier = new Clavier();
    String color = clavier.getColor();
    Assert.assertEquals("ivory", color);
  }
}

Add specs for Clavier 2d attempt

Add specs for Clavier 2d attempt


/*
 * Copyright 2018, TeamDev. All rights reserved.
 *
 * Redistribution and use in source and/or binary forms, with or without
 * modification, must retain the above copyright notice and the following
 * disclaimer.
 *
 * 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
 * OWNER 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 io.spine.system.server;

import io.spine.annotation.Internal;
import io.spine.client.EntityId;
import io.spine.server.aggregate.Aggregate;

/**
 * @author Dmytro Dashenkov
 */
@Internal
public final class EntityHistoryAggregate
        extends Aggregate<EntityId, EntityHistory, EntityHistoryVBuilder> {

    private EntityHistoryAggregate(EntityId id) {
        super(id);
    }

}

Create class for EntityHistory aggregate.


/**
 * Copyright 2017 University of Victoria
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to
 * deal in the Software without restriction, including without limitation the
 * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
 * sell copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
 * IN THE SOFTWARE.
 */
package com.rigiresearch.quizgen;

import java.util.List;
import java.util.stream.Collectors;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.experimental.Accessors;

/**
 * A question composed of several sub-questions.
 * @author Miguel Jimenez (miguel@uvic.ca)
 * @date 2017-08-19
 * @version $Id$
 * @since 0.0.1
 */
@Accessors(fluent = true)
@AllArgsConstructor
@Getter
public final class CompoundQuestion implements Question {

    /**
     * This question's segment.
     */
    private final TextSegment statement;

    /**
     * This question's sub-questions.
     */
    private final List<Question> children;

    /* (non-Javadoc)
     * @see com.rigiresearch.quizgen.Question#header()
     */
    @Override
    public TextSegment header() {
        return this.statement;
    }

    /* (non-Javadoc)
     * @see com.rigiresearch.quizgen.Question#body()
     */
    @Override
    public List<TextSegment> body() {
        return this.children.stream()
            .flatMap(child -> child.body().stream())
            .collect(Collectors.toList());
    }

    /* (non-Javadoc)
     * @see com.rigiresearch.quizgen.Question#children()
     */
    @Override
    public List<Question> children() {
        return this.children;
    }

}

Add new type of question

Add new type of question


package io.sigpipe.sing.adapters;

import io.sigpipe.sing.graph.Vertex;
import io.sigpipe.sing.serialization.Serializer;

public class ReadVertexBundle {

    public static void main(String[] args) throws Exception {

        Vertex root = Serializer.restoreCompressed(Vertex.class, args[0]);
        System.out.println(root.numLeaves());
        System.out.println(root.numDescendants());
        System.out.println(root.numDescendantEdges());

    }
}

Add small utility for reading vertex bundles


package top.quantic.sentry.job;

import com.codahale.metrics.Gauge;
import com.codahale.metrics.MetricRegistry;
import com.ibasco.agql.protocols.valve.steam.webapi.pojos.SteamPlayerProfile;
import org.quartz.Job;
import org.quartz.JobDataMap;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import top.quantic.sentry.service.GameQueryService;

import java.util.LinkedHashSet;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

public class SteamProfilePoller implements Job {

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

    @Autowired
    private GameQueryService gameQueryService;

    @Autowired
    private MetricRegistry metricRegistry;

    private final Map<Long, SteamPlayerProfile> profileMap = new ConcurrentHashMap<>();

    @Override
    public void execute(JobExecutionContext context) throws JobExecutionException {
        JobDataMap dataMap = context.getMergedJobDataMap();
        String keys = dataMap.getString("keys");
        if (keys == null) {
            throw new JobExecutionException("Data map key 'keys' is missing");
        }

        Set<Long> checked = new LinkedHashSet<>();

        for (String key : keys.split(";")) {
            Long id = gameQueryService.getSteamId64(key).exceptionally(t -> {
                log.warn("Could not get profile ID from key {}", key, t);
                return null;
            }).join();
            if (id != null) {
                profileMap.remove(id);
                registerGauges(id);
                checked.add(id);
            }
        }

        // clean up removed ids
        metricRegistry.removeMatching((name, metric) -> name.startsWith("steam.profile") && !checked.contains(extractId(name)));
    }

    private Long extractId(String name) {
        return Long.valueOf(name.replaceAll("^steam\\.profile\\..+\\[steamId:([0-9]+)]$", "$1"));
    }

    private void registerGauges(Long id) {
        if (metricRegistry.getGauges((name, metric) -> name.contains("steamId:" + id)).isEmpty()) {
            metricRegistry.register("steam.profile.status[steamId:" + id + "]", (Gauge<Integer>) () -> profileMap.computeIfAbsent(id, this::getPlayerProfile).getPersonaState());
            metricRegistry.register("steam.profile.lastLogOff[steamId:" + id + "]", (Gauge<Long>) () -> profileMap.computeIfAbsent(id, this::getPlayerProfile).getLastLogOff());
        }
    }

    private SteamPlayerProfile getPlayerProfile(Long id) {
        return gameQueryService.getPlayerProfile(id).exceptionally(t -> {
            log.warn("Could not retrieve profile info for {}", id, t);
            SteamPlayerProfile dummy = new SteamPlayerProfile();
            dummy.setPersonaState(0);
            dummy.setLastLogOff(0);
            return dummy;
        }).join();
    }
}

Add a job to report status of Steam profiles