package com.techhounds.commands.auton;

import com.techhounds.subsystems.DriveSubsystem;

import edu.wpi.first.wpilibj.PIDController;
import edu.wpi.first.wpilibj.PIDOutput;
import edu.wpi.first.wpilibj.PIDSource;
import edu.wpi.first.wpilibj.PIDSourceType;
import edu.wpi.first.wpilibj.command.Command;
import edu.wpi.first.wpilibj.networktables.NetworkTable;

/**
 *
 */
public class VisionAlignToTarget extends Command implements PIDSource, PIDOutput {

	private DriveSubsystem drive;
	private double offAngle = 0;
	private PIDController pid;
	private NetworkTable netTable;

    public VisionAlignToTarget() {
        drive = DriveSubsystem.getInstance();
        requires(drive);

        pid = new PIDController(0, 0, 0, this, this);
        pid.setOutputRange(-1, 1);
    }

    // Called just before this Command runs the first time
    protected void initialize() {
    	NetworkTable.setServerMode();
    	NetworkTable.initialize();
    	netTable = NetworkTable.getTable("SmartDashboard");

    	if(netTable != null) {
    		offAngle = netTable.getNumber("OffCenterDegreesX", 0);
    	}

    	pid.setSetpoint(offAngle);
    	pid.enable();
    }

    // Called repeatedly when this Command is scheduled to run
    protected void execute() {
    }

    // Make this return true when this Command no longer needs to run execute()
    protected boolean isFinished() {
        return pid.onTarget();
    }

    // Called once after isFinished returns true
    protected void end() {
    	pid.disable();
    }

    // Called when another command which requires one or more of the same
    // subsystems is scheduled to run
    protected void interrupted() {
    }

	@Override
	public void pidWrite(double output) {
		drive.setLeftPower(-output);
		drive.setRightPower(output);
	}

	@Override
	public void setPIDSourceType(PIDSourceType pidSource) {
		// TODO Auto-generated method stub

	}

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

	@Override
	public double pidGet() {
		return offAngle;
	}

	/*
	 * if angle is positive,
	 * we need to rotate to the left (counterclockwise)
	 * thus left power should be negative, right power should be positive
	 */
}

Add command to align robot based on camera angle


package com.gmail.nossr50.chat;

import org.bukkit.ChatColor;
import org.bukkit.entity.Player;
import org.bukkit.plugin.Plugin;

import com.gmail.nossr50.config.Config;
import com.gmail.nossr50.datatypes.party.Party;
import com.gmail.nossr50.events.chat.McMMOPartyChatEvent;
import com.gmail.nossr50.locale.LocaleLoader;

public class PartyChatManager extends ChatManager {
    private Party party;

    protected PartyChatManager(Plugin plugin) {
        super(plugin, Config.getInstance().getPartyDisplayNames(), "Commands.Party.Chat.Prefix");
    }

    public void setParty(Party party) {
        this.party = party;
    }

    @Override
    public void handleChat(String senderName, String displayName, String message, boolean isAsync) {
        handleChat(new McMMOPartyChatEvent(plugin, senderName, displayName, party.getName(), message, isAsync));
    }

    @Override
    protected void sendMessage() {
        for (Player member : party.getOnlineMembers()) {
            member.sendMessage(LocaleLoader.getString("Commands.Party.Chat.Prefix", displayName) + message);
        }

        plugin.getLogger().info("[P](" + party.getName() + ")" + "<" + ChatColor.stripColor(displayName) + "> " + message);
    }
}

package com.gmail.nossr50.chat;

import org.bukkit.entity.Player;
import org.bukkit.plugin.Plugin;

import com.gmail.nossr50.config.Config;
import com.gmail.nossr50.datatypes.party.Party;
import com.gmail.nossr50.events.chat.McMMOPartyChatEvent;

public class PartyChatManager extends ChatManager {
    private Party party;

    protected PartyChatManager(Plugin plugin) {
        super(plugin, Config.getInstance().getPartyDisplayNames(), "Commands.Party.Chat.Prefix");
    }

    public void setParty(Party party) {
        this.party = party;
    }

    @Override
    public void handleChat(String senderName, String displayName, String message, boolean isAsync) {
        handleChat(new McMMOPartyChatEvent(plugin, senderName, displayName, party.getName(), message, isAsync));
    }

    @Override
    protected void sendMessage() {
        for (Player member : party.getOnlineMembers()) {
            member.sendMessage(message);
        }

        plugin.getLogger().info("[P]<" + party.getName() + ">" + message);
    }
}

Fix duplicate prefix sending with party chat & logging.


package ie.omk.smpp.event;

import ie.omk.smpp.Connection;
import ie.omk.smpp.message.SMPPPacket;
import junit.framework.TestCase;

/**
 * @version $Id:$
 */
public class SimpleEventDispatcherTest extends TestCase {

    public void testGrowArray() {
        SimpleEventDispatcher dispatcher = new SimpleEventDispatcher();
        assertEquals(SimpleEventDispatcher.INCREMENT, dispatcher.capacity());
        assertEquals(0, dispatcher.size());
        for (int i = 0; i < SimpleEventDispatcher.INCREMENT + 1; i++) {
            dispatcher.addObserver(new TestConnectionObserver());
        }
        assertEquals(
                SimpleEventDispatcher.INCREMENT * 2, dispatcher.capacity());
        assertEquals(SimpleEventDispatcher.INCREMENT + 1, dispatcher.size());
    }

    public void testAddObserver() {
        SimpleEventDispatcher dispatcher = new SimpleEventDispatcher();
        TestConnectionObserver observer = new TestConnectionObserver();
        dispatcher.addObserver(observer);
        assertTrue(dispatcher.contains(observer));
        assertSame(observer, dispatcher.observerIterator().next());
    }

    public void testAddObserverDetectsDuplicates() {
        SimpleEventDispatcher dispatcher = new SimpleEventDispatcher();
        TestConnectionObserver observer = new TestConnectionObserver();
        dispatcher.addObserver(observer);
        assertEquals(1, dispatcher.size());
        dispatcher.addObserver(observer);
        assertEquals(1, dispatcher.size());
    }

    public void testRemove() {
        TestConnectionObserver ob1 = new TestConnectionObserver();
        TestConnectionObserver ob2 = new TestConnectionObserver();
        TestConnectionObserver ob3 = new TestConnectionObserver();
        TestConnectionObserver ob4 = new TestConnectionObserver();

        SimpleEventDispatcher dispatcher = new SimpleEventDispatcher();
        dispatcher.addObserver(ob1);
        dispatcher.addObserver(ob2);
        dispatcher.addObserver(ob3);
        dispatcher.addObserver(ob4);
        assertEquals(4, dispatcher.size());

        dispatcher.removeObserver(ob2);
        dispatcher.removeObserver(ob3);
        assertTrue(dispatcher.contains(ob1));
        assertFalse(dispatcher.contains(ob2));
        assertFalse(dispatcher.contains(ob3));
        assertTrue(dispatcher.contains(ob4));

        dispatcher.removeObserver(ob1);
        assertEquals(1, dispatcher.size());
        assertFalse(dispatcher.contains(ob1));
        assertFalse(dispatcher.contains(ob2));
        assertFalse(dispatcher.contains(ob3));
        assertTrue(dispatcher.contains(ob4));
    }

    private class TestConnectionObserver implements ConnectionObserver {
        public void packetReceived(Connection source, SMPPPacket packet) {
        }
        public void update(Connection source, SMPPEvent event) {
        }
    }
}

Add a unit test for SimpleEventDispatcher.


package io.sigpipe.sing.dataset;

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

import io.sigpipe.sing.dataset.feature.Feature;
import io.sigpipe.sing.stat.RunningStatistics;

public class TickEvaluator {

    private Quantizer quantizer;
    private Map<Feature, RunningStatistics> statMap = new HashMap<>();

    public TickEvaluator(Quantizer quantizer) {
        this.quantizer = quantizer;
    }

    public void train(List<Feature> features) {
        for (Feature feature : features) {
            Feature q = quantizer.quantize(feature);
            RunningStatistics rs = statMap.get(q);
            if (rs == null) {
                rs = new RunningStatistics();
                statMap.put(q, rs);
            }
            rs.put(feature.getDouble());
        }
    }

    public void evaluate(List<Feature> features) {

    }
}

Add class to evaluate tick mark errors


/*
 * 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 java.text;

import org.apache.harmony.luni.util.NotImplementedException;

/**
 * This class provider Unicode Normalization functions, which transform Unicode
 * text into an equivalent composed or decomposed form, allowing for easier
 * sorting and searching of text.
 *
 * @since 1.6
 */
public final class Normalizer {

    /**
     * This enum providers constants of normalization forms defined in Unicode
     * Standard Annex #15 Unicode Normalization Forms.
     *
     * @since 1.6
     */
    public static enum Form {
        /**
         * Canonical decomposition.
         */
        NFD,
        /**
         * Canonical decomposition followed by canonical composition.
         */
        NFC,
        /**
         * Compatibility decomposition.
         */
        NFKD,
        /**
         * Compatibility decomposition followed by canonical composition.
         */
        NFKC
    }

    /**
     * Normalize the given sequence of char src according to the
     * specified normalization form.
     *
     * @param src
     *            The sequence of char values.
     * @param form
     *            The specified normalization form.
     * @return The normalized String
     *
     * @exception NullPointerException
     *                If src or form is null.
     */
    public static String normalize(CharSequence src, Form form) {
        throw new NotImplementedException();
    }

    /**
     * Test wheather the given sequence of char src is normalized
     * according to the specified normalization form.
     *
     * @param src
     *            The sequence of char values.
     * @param form
     *            The specified normalization form.
     * @return true if src is normalized; false otherwise.
     *
     * @exception NullPointerException
     *                If src or form is null.
     */
    public static boolean isNormalized(CharSequence src, Form form) {
        throw new NotImplementedException();
    }
}

Apply for HARMONY-5740, Sorry for the inconvenience that caused.


package algorithms.dp;

/**
 * Created by sudharti on 5/26/17.
 */
public class EggDroppingProblem {
  public int minAttemptsRecursive(int floors, int eggs) {
    if (floors == 0 || floors == 1) {
      return floors;
    } else if (eggs == 1) {
      return floors;
    } else {
      int min = Integer.MAX_VALUE;
      for (int i = 1; i <= floors; i++) {
        min = Math.min(min, Math.max(1 + minAttemptsRecursive(i - 1, eggs - 1),
                1 + minAttemptsRecursive(floors - i, eggs)));
      }
      return min;
    }
  }

  public int minAttemptsDP(int floors, int eggs) {
    int[][] results = new int[eggs + 1][floors + 1];
    for (int i = 1; i < results[0].length; i++) {
      results[1][i] = i;
    }

    for (int i = 2; i < (eggs + 1); i++) {
      for (int j = 1; j < (floors + 1); j++) {
        if (i > j) {
          results[i][j] = j;
        } else {
          int min = Integer.MAX_VALUE;
          for (int k = 1; k <= j; k++) {
            min = Math.min(min, Math.max((1 + results[i - 1][k - 1]), (1 + results[i][j - k])));
          }
          results[i][j] = min;
        }
      }
    }

    return results[eggs][floors];
  }
}

Add solution for EggDropping problem


/*
 * Copyright (C) 2016 Michael Rozumyanskiy
 *
 * 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.michaelrocks.libphonenumber.android;

import android.content.res.AssetManager;

import java.io.IOException;
import java.io.InputStream;

public class AssetsMetadataLoader implements MetadataLoader {
  private final AssetManager assetManager;

  public AssetsMetadataLoader(final AssetManager assetManager) {
    this.assetManager = assetManager;
  }

  @Override
  public InputStream loadMetadata(final String metadataFileName) {
    String assetFileName = metadataFileName.substring(1);
    try {
      return assetManager.open(assetFileName);
    } catch (final IOException exception) {
      return null;
    }
  }
}

Add a metadata loader that loads data from assets


package leetcode.pascals_triangle_ii;

import java.util.ArrayList;

public class Solution {
    public ArrayList<Integer> getRow(int rowIndex) {
        ArrayList<Integer> ary = new ArrayList<Integer>();
        long C = 1;
        ary.add((int)C);
        for(int i = 1; i <= rowIndex; i++){
        	C *= rowIndex + 1 - i;
        	C /= i;
        	ary.add((int)C);
        }
        return ary;
    }

    public static void main(String[] args){
    	for(int x : new Solution().getRow(20)){
    		System.err.print(x + ", ");
    	}
    	System.err.println("");
    }
}

Add java solution for 119. Pascal's Triangle II


/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.msbaudiosteganography.text;

/**
 *
 * @author Afina, Meisyal, Irfan
 */

public class TextProcessor {
    public byte[] binaryStringToBytes(String binary) {
        byte[] buffer = new byte[binary.length()];

        for (int i = 0; i < binary.length(); i++) {
            if (binary.charAt(i) == '0') {
                buffer[i] = 0;
            } else {
                buffer[i] = 1;
            }
        }

        return buffer;
    }

    public String stringToBinaryString(String message) {
        String buffer = new String();

        for (int i = 0; i < message.length(); i++) {
            String bit = Integer.toBinaryString(message.charAt(i));

            if (bit.length() < 8) {
                bit = "00000000".substring(0, 8 - bit.length()).concat(bit);
            } else {
                bit = bit.substring(bit.length() - 8);
            }

            buffer = buffer.concat(bit);
        }

        return buffer;
    }

    public byte[] convertBinaryStringToBytes(String message) {
        return binaryStringToBytes(stringToBinaryString(message));
    }
}

Add binary string to byte converter


/*
 * JBoss, Home of Professional Open Source.
 * Copyright 2010, Red Hat Middleware LLC, and individual contributors
 * as indicated by the @author tags. See the copyright.txt file in the
 * distribution for a full listing of individual contributors.
 *
 * This 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 software 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 software; if not, write to the Free
 * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
 * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
 */

package org.jboss.msc.service;

import java.util.Arrays;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * A utility class for service actions.
 *
 * @author David M. Lloyd
 */
public final class ServiceUtils {

    private ServiceUtils() {
    }

    /**
     * Undeploy all the controllers and call the given runnable task when complete.
     *
     * @param completeTask the complete task
     * @param controllers the controllers to undeploy
     */
    public static void undeployAll(Runnable completeTask, ServiceController<?>... controllers) {
        undeployAll(completeTask, Arrays.asList(controllers));
    }

    /**
     * Undeploy all the controllers and call the given runnable task when complete.  The given controllers list
     * should not be modified while this method runs, or the results will be undefined.
     *
     * @param completeTask the complete task
     * @param controllers the controllers to undeploy
     */
    public static void undeployAll(final Runnable completeTask, final List<ServiceController<?>> controllers) {
        final AtomicInteger cnt = new AtomicInteger(controllers.size());
        final AbstractServiceListener<Object> listener = new AbstractServiceListener<Object>() {
            public void listenerAdded(final ServiceController<? extends Object> serviceController) {
                serviceController.setMode(ServiceController.Mode.NEVER);
            }

            public void serviceStopped(final ServiceController<? extends Object> serviceController) {
                serviceController.remove();
            }

            public void serviceRemoved(final ServiceController<? extends Object> serviceController) {
                if (cnt.decrementAndGet() == 0) {
                    completeTask.run();
                }
            }
        };
        for (ServiceController<?> controller : controllers) {
            controller.addListener(listener);
        }
    }
}

Add util class for services.


package model.transform;

/**
 * Base class for image transformation tasks.
 */
public class ImageTransformTask extends TransformTask {

    ImageTransformTask() {
    }

    ImageTransformTask(String name) {
        super(name);
    }
}

Add TransformTask subclass for image transforms


package org.jpos.iso;

import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;

import org.junit.jupiter.api.Test;

public final class ServiceCodeTest {

    @Test
    public void nullServiceCode() {
        assertThrows(NullPointerException.class, () -> {
            @SuppressWarnings("unused")
            ServiceCode sc = new ServiceCode(null);
        });
    }

    @Test
    public void invalidLengthServiceCode() {
        assertThrows(IllegalArgumentException.class, () -> {
            @SuppressWarnings("unused")
            ServiceCode sc = new ServiceCode("1234");
        });
    }

    @Test
    public void invalidServiceCode12E() {
        assertThrows(IllegalArgumentException.class, () -> {
            @SuppressWarnings("unused")
            ServiceCode sc = new ServiceCode("12E");
        });
    }

    @Test
    public void invalidServiceCodeSign22() {
        assertThrows(IllegalArgumentException.class, () -> {
            @SuppressWarnings("unused")
            ServiceCode sc = new ServiceCode("+22");
        });
    }

    @Test
    public void validLengthServiceCode() {
        @SuppressWarnings("unused")
        ServiceCode sc = new ServiceCode("201");
    }

    @Test
    public void testServiceCode201() {
        ServiceCode sc = new ServiceCode("201");
        assertTrue(sc.isICC(), "Service code should be ICC");
        assertTrue(sc.hasNoRestrictions(), "Service code should have no restrictions");
        assertTrue(sc.isInternational(), "Service code should be international");
        assertTrue(sc.isNormalAuthorization(), "Service code should be normal authorization");
        assertFalse(sc.isPINRequired(), "Service code should not require PIN");
        assertFalse(sc.isPrivate(), "Service code should not be private");
        assertFalse(sc.isNational(), "Service code should not be national");
        assertFalse(sc.isTest(), "Service code should not be test");
        assertFalse(sc.isGoodsAndServicesOnly(), "Service code should not be good and services only");
        assertFalse(sc.isATMOnly(), "Service code should not be ATM only");
        assertFalse(sc.isCashOnly(), "Service code should not be cash only");
    }
}

Add unit tests for 'ServiceCode'.


/**
 * The {@code network} package contains classes implementing self-organizing
 * maps.  These classes all implement
 * {@link cs437.som.TrainableSelfOrganizingMap} in {@link cs437.som}, either
 * directly or indirectly.
 */
package cs437.som.network;

Add a package annotation to network.


/*
 * Copyright (c) 2006-2014 DMDirc Developers
 *
 * 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.dmdirc.util.validators;

import java.util.function.Function;

/**
 * Validator that uses a function to validate an input.
 */
public class BaseValidator<T> implements Validator<T> {

    private final Function<T, ValidationResponse> function;

    public BaseValidator(final Function<T, ValidationResponse> function) {
        this.function = function;
    }

    @Override
    public ValidationResponse validate(final T object) {
        return function.apply(object);
    }
}

Add a function based validator.


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

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

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

/**
 * @author Pedro Vicente Gómez Sánchez.
 */
public class IsEvenTest {

  private IsEven isEven;

  @Before public void setUp() {
    isEven = new IsEven();
  }

  @Test public void shouldReturnTrueIfNumberIsZero() {
    assertTrue(isEven.check(0));
  }

  @Test public void shouldReturnTrueIfNumberIsEven() {
    assertTrue(isEven.check(68));
  }

  @Test public void shouldReturnFalseIfNumberIsOdd() {
    assertFalse(isEven.check(99));
  }
}

Add some tests to problem 68


package org.apache.jmeter.functions;

import java.util.Collection;
import java.util.LinkedList;

import org.apache.jmeter.engine.util.CompoundVariable;
import org.apache.jmeter.junit.JMeterTestCase;

public class TestXPathFunction extends JMeterTestCase {

    private XPath setupXPath(String file, String expr) throws Exception{
        Collection parms = new LinkedList();
        parms.add(new CompoundVariable(file));
        parms.add(new CompoundVariable(expr));
        XPath xp = new XPath();
        xp.setParameters(parms);
        return xp;
    }

    public void testEmpty() throws Exception{
        XPath xp = setupXPath("","");
        String val=xp.execute();
        assertEquals("",val);
        val=xp.execute();
        assertEquals("",val);
        val=xp.execute();
        assertEquals("",val);
    }

    public void testNoFile() throws Exception{
        XPath xp = setupXPath("no-such-file","");
        String val=xp.execute();
        assertEquals("",val); // TODO - should check that error has been logged...
    }

    public void testFile1() throws Exception{
        XPath xp = setupXPath("testfiles/XPathTest.xml","//user/@username");
        assertEquals("u1",xp.execute());
        assertEquals("u2",xp.execute());
        assertEquals("u1",xp.execute());
    }

    public void testFile2() throws Exception{
        XPath xp1  = setupXPath("testfiles/XPathTest.xml","//user/@username");
        XPath xp1a = setupXPath("testfiles/XPathTest.xml","//user/@username");
        XPath xp2  = setupXPath("testfiles/XPathTest.xml","//user/@password");
        XPath xp2a = setupXPath("testfiles/XPathTest.xml","//user/@password");
        assertEquals("u1",xp1.execute());
        assertEquals("p1",xp2.execute());
        assertEquals("p2",xp2.execute());
        assertEquals("u2",xp1a.execute());
        assertEquals("u1",xp1.execute());
        assertEquals("u2",xp1.execute());
        assertEquals("p1",xp2a.execute());

    }
}

Add some tests for XPath function


import java.util.Arrays;

public class Solution {

    public int missingNumber(int[] nums) {

        int left = 0;
        int right = nums.length;

        Arrays.sort(nums);

        while (left < right) {

            int mid = (left + right) / 2;

            if (nums[mid] > mid) {
                right = mid;
            } else {
                left = mid + 1;
            }

        }

        return left;

    }

}

Create : 268 Missing Number


package de.retest.recheck.ui.diff;

import static de.retest.recheck.ui.diff.ElementBuilder.toAttributes;
import static org.mockito.Mockito.mock;

import java.util.TreeSet;

import org.assertj.core.api.Assertions;
import org.junit.Test;

import de.retest.recheck.ui.Path;
import de.retest.recheck.ui.PathElement;
import de.retest.recheck.ui.descriptors.Attributes;
import de.retest.recheck.ui.descriptors.Element;
import de.retest.recheck.ui.descriptors.IdentifyingAttributes;
import de.retest.recheck.ui.descriptors.MutableAttributes;

public class MatchTest {

	public static final double ONE_SIMILARITY = 1.0d / IdentifyingAttributes.PERFECT_SIMILARITY;

	@Test
	public void test_better_comp_always_comes_out_first() {
		final Element comp1 = getElement( comp1.class, 1 );
		final Match match1 = new Match( 0.9d + ONE_SIMILARITY, comp1 );

		final Element comp2 = getElement( comp2.class, 2 );
		final Match match2 = new Match( 0.9d, comp2 );

		final TreeSet<Match> bestMatches = new TreeSet<>();
		bestMatches.add( match1 );
		bestMatches.add( match2 );

		Assertions.assertThat( bestMatches.pollFirst().element ).isSameAs( comp1 );
		Assertions.assertThat( bestMatches.pollFirst().element ).isSameAs( comp2 );
	}

	@Test
	public void same_score_doesnt_overwrite() {
		final Element comp1 = getElement( comp2.class, 2 );
		final Match match1 = new Match( 0.9d, comp1 );

		final Element comp2 = getElement( comp2.class, 2 );
		final Match match2 = new Match( 0.9d, comp2 );

		final TreeSet<Match> bestMatches = new TreeSet<>();
		bestMatches.add( match1 );
		bestMatches.add( match2 );

		Assertions.assertThat( bestMatches.size() ).isEqualTo( 2 );
	}

	private Element getElement( final Class<?> clazz, final int cnt ) {
		return Element.create( "id", mock( Element.class ),
				IdentifyingAttributes.create( Path.path( new PathElement( clazz.getSimpleName(), 1 ) ), clazz ),
				toAttributes( "{color=green}" ) );
	}

	private class comp1 extends Element {
		private static final long serialVersionUID = 1L;
	};

	private class comp2 extends Element {
		private static final long serialVersionUID = 1L;
	};
}

Move tests for Match from review


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

/**
 * Package to test FileServer methods
 */

package org.apache.jmeter.config;

import java.io.IOException;

import org.apache.jmeter.junit.JMeterTestCase;
import org.apache.jmeter.threads.JMeterContext;
import org.apache.jmeter.threads.JMeterContextService;
import org.apache.jmeter.threads.JMeterVariables;

public class TestCVSDataSet extends JMeterTestCase {

    public TestCVSDataSet() {
        super();
    }

    public TestCVSDataSet(String arg0) {
        super(arg0);
    }

    public void tearDown() throws IOException{
    }

    public void testopen() throws Exception {
		JMeterContext jmcx = JMeterContextService.getContext();
		jmcx.setVariables(new JMeterVariables());
		JMeterVariables threadVars = jmcx.getVariables();
    	threadVars.put("b", "value");

    	CSVDataSet csv = new CSVDataSet();
    	csv.setFilename("No.such.filename");
    	csv.setVariableNames("a,b,c");
    	csv.setDelimiter(",");
    	csv.iterationStart(null);
		assertNull(threadVars.get("a"));
		assertEquals("value",threadVars.get("b"));
		assertNull(threadVars.get("c"));

		csv = new CSVDataSet();
    	csv.setFilename("testfiles/testempty.csv");
    	csv.setVariableNames("a,b,c");
    	csv.setDelimiter(",");

    	csv.iterationStart(null);
		assertEquals("",threadVars.get("a"));
		assertEquals("b1",threadVars.get("b"));
		assertEquals("c1",threadVars.get("c"));

    	csv.iterationStart(null);
		assertEquals("a2",threadVars.get("a"));
		assertEquals("",threadVars.get("b"));
		assertEquals("c2",threadVars.get("c"));

		csv.iterationStart(null);
		assertEquals("a3",threadVars.get("a"));
		assertEquals("b3",threadVars.get("b"));
		assertEquals("",threadVars.get("c"));

		csv.iterationStart(null);
		assertEquals("a4",threadVars.get("a"));
		assertEquals("b4",threadVars.get("b"));
		assertEquals("c4",threadVars.get("c"));

    	csv.iterationStart(null); // Restart file
		assertEquals("",threadVars.get("a"));
		assertEquals("b1",threadVars.get("b"));
		assertEquals("c1",threadVars.get("c"));
    }
}

Test for CSV Data Set


package tachyon.perf.basic;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.apache.log4j.Logger;

import tachyon.perf.conf.PerfConf;
import tachyon.perf.util.SAXConfiguration;

/**
 * Manage the configurations for each task.
 */
public class TaskConfiguration {
  public static final boolean DEFAULT_BOOLEAN = false;
  public static final int DEFAULT_INTEGER = 0;
  public static final long DEFAULT_LONG = 0;
  public static final String DEFAULT_STRING = "";
  private static final Logger LOG = Logger.getLogger("");

  private static TaskConfiguration sTaskConf = null;

  /**
   * Get the configuration.
   *
   * @param type the type of the benchmark task
   * @param fromFile if true, it will load the configuration file, otherwise it return an empty
   *        configuration.
   * @return the task configuration
   */
  public static synchronized TaskConfiguration get(String type, boolean fromFile) {
    if (sTaskConf == null) {
      if (fromFile) {
        try {
          sTaskConf =
              new TaskConfiguration(PerfConf.get().TACHYON_PERF_HOME + "/conf/testSuite/" + type
                  + ".xml");
        } catch (Exception e) {
          LOG.error("Error when parse conf/testSuite/" + type + ".xml", e);
          throw new RuntimeException("Failed to parse conf/testSuite/" + type + ".xml");
        }
      } else {
        sTaskConf = new TaskConfiguration();
      }
    }
    return sTaskConf;
  }

  private Map<String, String> mProperties;

  protected TaskConfiguration() {
    mProperties = new HashMap<String, String>();
  }

  protected TaskConfiguration(String xmlFileName) throws Exception {
    SAXParserFactory spf = SAXParserFactory.newInstance();
    SAXParser saxParser = spf.newSAXParser();
    File xmlFile = new File(xmlFileName);
    SAXConfiguration saxConfiguration = new SAXConfiguration();
    saxParser.parse(xmlFile, saxConfiguration);
    mProperties = saxConfiguration.getProperties();
  }

  public synchronized void addProperty(String name, String value) {
    mProperties.put(name, value);
  }

  public synchronized Map<String, String> getAllProperties() {
    Map<String, String> ret = new HashMap<String, String>(mProperties.size());
    ret.putAll(mProperties);
    return ret;
  }

  public synchronized boolean getBooleanProperty(String property) {
    if (mProperties.containsKey(property)) {
      return Boolean.valueOf(mProperties.get(property));
    }
    return DEFAULT_BOOLEAN;
  }

  public synchronized int getIntProperty(String property) {
    if (mProperties.containsKey(property)) {
      return Integer.valueOf(mProperties.get(property));
    }
    return DEFAULT_INTEGER;
  }

  public synchronized long getLongProperty(String property) {
    if (mProperties.containsKey(property)) {
      return Long.valueOf(mProperties.get(property));
    }
    return DEFAULT_LONG;
  }

  public synchronized String getProperty(String property) {
    if (mProperties.containsKey(property)) {
      return mProperties.get(property);
    }
    return DEFAULT_STRING;
  }
}

Manage the configurations for each task


package com.Acrobot.ChestShop.Tests;

import com.Acrobot.ChestShop.Events.PreShopCreationEvent;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;

import static com.Acrobot.ChestShop.Listeners.PreShopCreation.PriceChecker.onPreShopCreation;
import static junit.framework.Assert.assertFalse;
import static junit.framework.Assert.assertTrue;

/**
 * Created by Andrzej Pomirski (Acrobot)
 */
@RunWith(JUnit4.class)
public class PriceCheckerTest {

    String[] getPriceString(String prices) {
        return new String[]{null, null, prices, null};
    }

    @Test
    public void testPrice() {
        PreShopCreationEvent event = new PreShopCreationEvent(null, null, getPriceString("B 1"));
        onPreShopCreation(event);
        assertFalse(event.isCancelled());

        event = new PreShopCreationEvent(null, null, getPriceString("S 1"));
        onPreShopCreation(event);
        assertFalse(event.isCancelled());

        event = new PreShopCreationEvent(null, null, getPriceString("B 1:S 1"));
        onPreShopCreation(event);
        assertFalse(event.isCancelled());

        event = new PreShopCreationEvent(null, null, getPriceString("BS 1"));
        onPreShopCreation(event);
        assertTrue(event.isCancelled());

        event = new PreShopCreationEvent(null, null, getPriceString("B 1S0"));
        onPreShopCreation(event);
        assertTrue(event.isCancelled());
    }
}

Add a test for price checking


/*
 * Copyright 2019 Google LLC
 *
 * 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
 *
 *     https://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.android.gnd.rx;

import androidx.annotation.NonNull;
import io.reactivex.Single;
import io.reactivex.functions.Consumer;
import javax.annotation.Nullable;

public class Result<T> {
  public enum State {
    SUCCESS,
    ERROR
  }

  private final State state;

  @Nullable private final T value;
  @Nullable private final Throwable error;

  private Result(State state, @Nullable T value, @Nullable Throwable error) {
    this.state = state;
    this.value = value;
    this.error = error;
  }

  public static <T> Result<T> success(@NonNull T result) {
    return new Result<>(State.SUCCESS, result, null);
  }

  public static <T> Result<T> error(@NonNull Throwable t) {
    return new Result<>(State.ERROR, null, t);
  }

  @Nullable
  public State getState() {
    return state;
  }

  @Nullable
  public T get() {
    return value;
  }

  @Nullable
  public Throwable getError() {
    return error;
  }

  public static <T> Single<Result<T>> wrap(Single<T> single) {
    return single.map(Result::success).onErrorReturn(Result::error);
  }

  public static <T> Consumer<? super Result<T>> unwrap(
      Consumer<T> onSuccess, Consumer<Throwable> onError) {
    return result -> {
      switch (result.getState()) {
        case SUCCESS:
          onSuccess.accept(result.get());
          break;
        case ERROR:
          onError.accept(result.getError());
          break;
      }
    };
  }
}

Add simple wrapper for streaming results


package dae.io.readers;

import dae.components.ComponentType;
import dae.components.PrefabComponent;
import dae.io.XMLUtils;
import dae.prefabs.PropertyReflector;
import dae.prefabs.ReflectionManager;
import dae.prefabs.parameters.ChoiceParameter;
import dae.prefabs.parameters.FileParameter;
import dae.prefabs.parameters.Float3Parameter;
import dae.prefabs.parameters.FloatParameter;
import dae.prefabs.parameters.IntParameter;
import dae.prefabs.parameters.Parameter;
import dae.prefabs.parameters.RangeParameter;
import dae.prefabs.parameters.TextParameter;
import java.util.HashMap;

/**
 * @author Koen Samyn
 */
public class DefaultPrefabImporter implements PrefabTextImporter {

    private HashMap<Class, ParameterParser> parameterMap =
            new HashMap<Class, ParameterParser>();

    /**
     * Creates a new DefaultPrefabImporter object.
     */
    public DefaultPrefabImporter() {
        parameterMap.put(FloatParameter.class, new ParameterParser() {
            public Object parseParameter(String value) {
                return Float.parseFloat(value);
            }
        });
        parameterMap.put(RangeParameter.class, new ParameterParser() {
            public Object parseParameter(String value) {
                return Float.parseFloat(value);
            }
        });
        parameterMap.put(IntParameter.class, new ParameterParser() {
            public Object parseParameter(String value) {
                return Float.parseFloat(value);
            }
        });
        parameterMap.put(TextParameter.class, new ParameterParser() {
            public Object parseParameter(String value) {
                return value;
            }
        });
        parameterMap.put(Float3Parameter.class, new ParameterParser() {
            public Object parseParameter(String value) {
                return XMLUtils.parseFloat3(value);
            }
        });
        parameterMap.put(FileParameter.class, new ParameterParser() {
            public Object parseParameter(String value) {
                return value;
            }
        });
        parameterMap.put(ChoiceParameter.class, new ParameterParser() {
            public Object parseParameter(String value) {
                return value;
            }
        });
    }

    /**
     * Parses a parameter and sets the value on the correct property of the
     * component.
     *
     * @param p the prefab component to set the property on.
     * @param ct the component type of the PrefabComponent.
     * @param id the id of the parameter.
     * @param value the value of the parameter.
     */
    public void parseAndSetParameter(PrefabComponent p, ComponentType ct, String id, String value) {
        Parameter parameter = ct.findParameter(id);
        ParameterParser pp = parameterMap.get(parameter.getClass());
        if ( pp != null ){
            Object oValue = pp.parseParameter(value);
            if ( oValue != null){
                PropertyReflector pr = ReflectionManager.getInstance().getPropertyReflector(p.getClass());
                pr.invokeSetMethod(p, id, parameter.convertToObject(oValue));
            }
        }
    }
}

Support for reading parameters in a structured way.


package reactmann;

import io.vertx.core.Vertx;

/**
 * @author blake
 */
public class RiemannRun {
    public static void main(String... args) {
        Vertx.vertx().deployVerticle("java:" + TestVerticle.class.getName());
    }
}

Add a main class, which is useful for development in an IDE.


/*
 * Copyright 2012 SFB 632.
 *
 * 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 annis.sqlgen;

import annis.ql.parser.QueryData;
import java.net.URI;
import java.util.ArrayList;

/**
 * This class is only a wrapper to transport the salt ids with the
 * {@link QueryData} class as extension.
 *
 * @author Benjamin Weißenfels <b.pixeldrama@gmail.com>
 */
public class SaltURI extends ArrayList<URI>
{
}

Add wrapper class for slat ids.


package com.taxonic.rml.vocab;

import org.eclipse.rdf4j.model.IRI;
import org.eclipse.rdf4j.model.ValueFactory;
import org.eclipse.rdf4j.model.impl.SimpleValueFactory;

public class Rdf {

	private static final ValueFactory f = SimpleValueFactory.getInstance();

	public static class Rml {

		static IRI iri(String suffix) {
			return f.createIRI(prefix + suffix);
		}

		public static final String prefix = "http://semweb.mmlab.be/ns/rml#";

		public static final IRI logicalSource = iri("logicalSource");

	}

	public static class Ql {

		public static IRI iri(String suffix) {
			return f.createIRI(prefix + suffix);
		}

		public static final String prefix = "http://semweb.mmlab.be/ns/ql#";

		public static final IRI JsonPath = iri("JSONPath");

	}
}

Add vocabulary classes using RDF4J model (in addition to the vocabularies in Strings)


public class Solution {

    public int findMaxConsecutiveOnes(int[] nums) {

        int max = 0;
        int current = 0;

        for (int i = 0; i < nums.length; i++) {

            if (nums[i] == 1) {
                current++;
                max = Math.max(max, current);
            } else if (nums[i] == 0){
                current = 0;
            }

        }

        return max;

    }

}

Create : 485 Max Consecutive Ones


package leetcode.reverse_words_in_a_string;

import java.util.Stack;

public class Solution {
	public String reverseWords(String s) {
		Stack<String> ans = new Stack<String>();
        for(String word : s.split(" ")){
        	if(!word.isEmpty()){
        		ans.push(word);
        	}
        }
        String prefix = "";
        StringBuilder sb = new StringBuilder();
        while(!ans.isEmpty()){
        	sb.append(prefix);
        	sb.append(ans.pop());
        	prefix = " ";
        }
        return sb.toString();
    }

	public static void main(String[] args){
		System.err.println(new Solution().reverseWords(" the sky is blue   "));
	}
}

Add java solution for 151. Reverse Words in a String


public class Solution {

    public boolean checkPerfectNumber(int num) {

        if (num < 2) {
            return false;
        }

        int sum = 1;

        for (int i = 2; i <= Math.sqrt(num); i++) {

            if (num % i == 0) {

                sum += i;
                sum += num / i;

            }

        }

        return sum == num;

    }

}

Create : 507 Perfect Number


package checkpoint.andela.readersClub;

import checkpoint.andela.main.Member;
import checkpoint.andela.members.*;

import java.util.Comparator;

/**
 * Created by Semiu on 26/11/2015.
 */
public class ComparatorInterface implements Comparator<Member> {

  @Override
  public int compare(Member member1, Member member2) {
    if (member1.getClass() == member2.getClass()) {
      return member1.getRegistrationDate().compareTo(member2.getRegistrationDate());
    }
    if(member1 instanceof Staff && member2 instanceof Student) {
      return -1;
    }
    return 1;
  }
}

Implement The Comparator Interface To Sort Who Get Book First


/*
 * This file is part of Bisq.
 *
 * Bisq is free software: you can redistribute it and/or modify it
 * under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or (at
 * your option) any later version.
 *
 * Bisq is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public
 * License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with Bisq. If not, see <http://www.gnu.org/licenses/>.
 */

// This package is not used atm but might be used in future when we need to lookup non-wallet transactions

package bisq.core.btc.blockchain;

Add package info and comment


package org.mcphoton.impl.server;

import com.electronwill.nightconfig.core.UnmodifiableCommentedConfig;
import com.electronwill.nightconfig.core.conversion.ObjectConverter;
import com.electronwill.nightconfig.toml.TomlConfig;
import com.electronwill.nightconfig.toml.TomlParser;
import java.awt.image.BufferedImage;
import java.io.File;
import java.util.Map;
import org.mcphoton.Photon;
import org.mcphoton.server.ServerConfiguration;
import org.mcphoton.utils.Location;

/**
 * The server configuration, loaded from the file server-config.toml with the Night-Config library.
 *
 * @author TheElectronWill
 */
public final class ServerConfigImpl implements ServerConfiguration {
	private static final File configFile = new File(Photon.getMainDirectory(), "server-config.toml");

	private volatile String motd;
	private volatile int maxPlayers, port;
	private volatile Location spawnLocation;
	private volatile boolean onlineMode;
	private volatile transient BufferedImage icon;// not saved in the config but loaded from icon.jpg or .png
	private volatile transient Map<String, UnmodifiableCommentedConfig.CommentNode> savedComments;

	@Override
	public String getMOTD() {
		return motd;
	}

	@Override
	public void setMOTD(String motd) {
		this.motd = motd;
	}

	@Override
	public int getMaxPlayers() {
		return maxPlayers;
	}

	@Override
	public void setMaxPlayers(int maxPlayers) {
		this.maxPlayers = maxPlayers;
	}

	@Override
	public int getPort() {
		return port;
	}

	@Override
	public void setPort(int port) {
		this.port = port;
	}

	@Override
	public BufferedImage getIcon() {
		return icon;
	}

	@Override
	public void setIcon(BufferedImage icon) {
		this.icon = icon;
	}

	@Override
	public Location getSpawnLocation() {
		return spawnLocation;
	}

	@Override
	public void setSpawnLocation(Location location) {
		this.spawnLocation = location;
	}

	@Override
	public boolean isOnlineMode() {
		return onlineMode;
	}

	@Override
	public void setOnlineMode(boolean online) {
		this.onlineMode = online;
	}

	static ServerConfiguration load() {
		TomlConfig config = new TomlParser().parse(configFile);
		ServerConfigImpl impl = new ObjectConverter().toObject(config, ServerConfigImpl::new);
		impl.savedComments = config.getComments();// Remembers the comments
		return impl;
	}

	void save() {
		TomlConfig config = new ObjectConverter().toConfig(this, TomlConfig::new);
		config.setComments(savedComments);// Restores the comments
		config.write(configFile);
	}
}

Implement ServerConfiguration with the NightConfig library


/*
 * The MIT License
 *
 * Copyright (c) 2004-, Kohsuke Kawaguchi, Sun Microsystems, Inc., and a number of other of contributors
 *
 * 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 hudson.plugins.ec2;

import org.jvnet.hudson.test.HudsonTestCase;

import com.amazonaws.services.ec2.model.InstanceType;

public class EC2InstanceTypesTest extends HudsonTestCase {
    public void testListTypes() throws Exception {
	System.out.println("EC2 Instance Types available:");
	for (InstanceType t : InstanceType.values()) {
	    System.out.println(t.toString());
	}
    }
}

Add a 'test' that lists the available EC2 instance types.


package com.sinyuk.yuk.utils;

import android.support.v4.view.animation.FastOutSlowInInterpolator;
import android.view.ViewPropertyAnimator;

import fr.castorflex.android.smoothprogressbar.SmoothProgressBar;

/**
 * Created by Sinyuk on 16/8/15.
 */
public class BlackMagics {
    /*
     * 进度条上移
     * @param v
     * @param withLayer
     */
    public static ViewPropertyAnimator scrollUp(SmoothProgressBar progressBar) {
        final int offset = progressBar.getHeight();
        progressBar.setTranslationY(offset);
        progressBar.setAlpha(0.01f);
        return progressBar.animate()
                .translationY(0)
                .alpha(1)
                .setDuration(600)
                .setInterpolator(new FastOutSlowInInterpolator())
                .withLayer();
    }

    /*
    * 进度条下移
    * @param v
    * @param withLayer
    */
    public static ViewPropertyAnimator scrollDown(SmoothProgressBar progressBar) {
        final int offset = progressBar.getHeight();
        return progressBar.animate()
                .translationY(offset)
                .alpha(0.01f)
                .setDuration(600)
                .setInterpolator(new FastOutSlowInInterpolator())
                .withLayer();
    }
}

Move some code on animations outside


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

import java.util.Collection;
import java.util.LinkedList;

public class BugMerge {

    @SuppressWarnings("unused")
    public static void main(
            String[] args) {

        Collection<Interval<Integer>> intervalsInt = new LinkedList<Interval<Integer>>();
        Symbol<Integer> firstSymbol;

        Symbol<Integer> secondSymbol;

        Alphabet<Integer> completeAlphabet;
        Alphabet<Integer> firstPartAlphabet;
        Alphabet<Integer> secondPartAlphabet;
        AlphabetMergeResult<Integer> mergeResult;

        intervalsInt.add(new Interval<Integer>(0, 5, Realms.getInteger()));
        intervalsInt.add(new Interval<Integer>(10, 15, Realms.getInteger()));
        intervalsInt.add(new Interval<Integer>(20, 25, Realms.getInteger()));
        firstPartAlphabet = new Alphabet<Integer>(new Symbol<Integer>(
                intervalsInt));

        intervalsInt.clear();
        intervalsInt.add(new Interval<Integer>(30, 35, Realms.getInteger()));
        intervalsInt.add(new Interval<Integer>(40, 45, Realms.getInteger()));
        intervalsInt.add(new Interval<Integer>(50, 55, Realms.getInteger()));
        secondPartAlphabet = new Alphabet<Integer>(new Symbol<Integer>(
                intervalsInt));

        System.out.println(firstPartAlphabet + "\n" + secondPartAlphabet);

        // Line that cause the bug.
        mergeResult = firstPartAlphabet.mergeWith(secondPartAlphabet);
        System.out.print(mergeResult);

    }

}

Add regression test. See ticket:20.


/*
 * Copyright 2013 MovingBlocks
 *
 * 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.terasology.asset;

/**
 *
 */
public interface AssetFactory<DATA_TYPE extends AssetData, ASSET_TYPE extends Asset<DATA_TYPE>> {

    ASSET_TYPE buildAsset(AssetUri uri, DATA_TYPE data);
}

/*
 * Copyright 2013 MovingBlocks
 *
 * 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.terasology.asset;

/**
 *
 */
public interface AssetFactory<DATA extends AssetData, ASSET extends Asset<DATA>> {

    ASSET buildAsset(AssetUri uri, DATA data);
}

Fix checkstyle type name warning


package com.ttaylorr.ctci.answers.trees;

import com.ttaylorr.ctci.answers.trees.util.TreeNode;
import com.ttaylorr.ctci.meta.Solution;

@Solution(chapter = 4, problem = 6)
public class CommonAncestor {
    // Example usage: CommonAncestorFinder.of(foo, bar).in(baz);
    public static CommonAncestor.Builder of(TreeNode a, TreeNode b) {
        return new CommonAncestor.Builder(a, b);
    }

    private static class Builder {
        private TreeNode a, b;
        public Builder(TreeNode a, TreeNode b) {
            this.a = a;
            this.b = b;
        }

        public TreeNode in(TreeNode root) {
            return new CommonAncestor(a, b).findCommonAncestor(root);
        }
    }

    protected final TreeNode a, b;
    public CommonAncestor(TreeNode a, TreeNode b) {
        this.a = a;
        this.b = b;
    }

    public TreeNode findCommonAncestor(TreeNode root) {
        if (this.covers(root.left, this.a) && this.covers(root.left, this.b)) {
            return this.findCommonAncestor(root.left);
        } else if (this.covers(root.right, this.a) && this.covers(root.right, this.b)) {
            return this.findCommonAncestor(root.right);
        } else {
            return root;
        }
    }

    /**
     * Determine whether the other node is contained within the root.
     */
    private boolean covers(TreeNode root, TreeNode other) {
        if (root == null) return false;
        if (root == other) return true;
        else return this.covers(root.left, other) || this.covers(root.right, other);
    }
}

Add finding the common ancestor problem


package no.dusken.momus.controller;

import no.dusken.momus.model.Person;
import no.dusken.momus.service.repository.PersonRepository;
import org.springframework.context.event.EventListener;
import org.springframework.data.util.Pair;
import org.springframework.messaging.simp.user.SimpUserRegistry;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.socket.messaging.SessionDisconnectEvent;

import java.security.Principal;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

@RestController
public class WebSocketController {

    private final SimpUserRegistry userRegistry;

    private final Map<String, Pair<Person, String>> sessionStates;

    private final PersonRepository personRepository;

    public WebSocketController(SimpUserRegistry userRegistry, PersonRepository personRepository) {
        this.personRepository = personRepository;
        this.userRegistry = userRegistry;
        sessionStates = new HashMap<>();
    }

    @GetMapping("/users")
    public @ResponseBody Set<Person> getLoggedInUsers(@RequestParam String state) {
        return userRegistry.findSubscriptions(sub -> true)
                .stream()
                .filter(s -> sessionStates.get(s.getSession().getId()).getSecond().equals(state))
                .map(s -> sessionStates.get(s.getSession().getId()).getFirst())
                .collect(Collectors.toSet());
    }

    @PutMapping("/users/{sessid}")
    public void setMyState(@PathVariable("sessid") String sessid, @RequestParam String state, Principal principal) {
        if(sessionStates.containsKey(sessid)) {
            sessionStates.put(sessid, Pair.of(sessionStates.get(sessid).getFirst(), state));
        }else {
            sessionStates.put(sessid, Pair.of(personRepository.findByUsername(principal.getName()), state));
        }
    }

    @EventListener
    public void handleSessionEnd(SessionDisconnectEvent disconnectEvent) {
        sessionStates.remove(disconnectEvent.getSessionId());
    }
}

Add websocket controller with user state


package hex.tree.drf;

import org.junit.BeforeClass;
import org.junit.Test;
import water.*;
import water.fvec.Frame;
import water.util.Log;

import static org.junit.Assert.*;

public class DRFConcurrentTest extends TestUtil  {

  @BeforeClass
  public static void setup() { stall_till_cloudsize(1); }

  @Test
  public void testBuildSingle() {
    Scope.enter();
    try {
      Frame fr = parse_test_file(Key.make("prostate_single.hex"), "smalldata/logreg/prostate.csv");
      Scope.track(fr);
      fr.remove("ID").remove();
      buildXValDRF(fr, "AGE");
    } finally {
      Scope.exit();
    }
  }

  @Test
  public void testBuildConcurrent() {
    Scope.enter();
    try {
      Frame fr = parse_test_file(Key.make("prostate_concurrent.hex"), "smalldata/logreg/prostate.csv");
      Scope.track(fr);
      fr.remove("ID").remove();
      TrainSingleFun fun = new TrainSingleFun(fr);
      H2O.submitTask(new LocalMR(fun, 100)).join();
    } finally {
      Scope.exit();
    }
  }

  private static class TrainSingleFun extends MrFun<TrainSingleFun> {
    private final Frame _train;
    private TrainSingleFun(Frame train) { _train = train; }
    public TrainSingleFun() { _train = null; }
    @Override
    protected void map(int id) {
      assert _train != null;
      buildXValDRF(_train, "AGE");
    }
  }

  private static void buildXValDRF(Frame train, String response) {
    DRFModel model = null;
    try {
      Scope.enter();
      // Configure DRF
      DRFModel.DRFParameters drf = new DRFModel.DRFParameters();
      drf._train = train._key;
      drf._response_column = response;
      drf._seed = (1L<<32)|2;
      drf._nfolds = 5;
      drf._ntrees = 7;

      model = new DRF(drf).trainModel().get();

      assertNotNull(model);
      Log.info(model._output);

      assertEquals(5, model._output._cross_validation_models.length);
    } finally {
      if (model != null) {
        model.delete();
        model.deleteCrossValidationModels();
        model.deleteCrossValidationPreds();
      }
      Scope.exit();
    }
  }

}

Test concurrent building of DRF models


/*
 Copyright (C) 2003 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 org.ensembl.healthcheck.DatabaseRegistryEntry;
import org.ensembl.healthcheck.ReportManager;
import org.ensembl.healthcheck.Team;
import org.ensembl.healthcheck.testcase.Priority;
import org.ensembl.healthcheck.testcase.SingleDatabaseTestCase;

/**
 * Check for Uniprot xrefs that have "Unreviewed" as the primary DB accession.
 */

public class UnreviewedXrefs extends SingleDatabaseTestCase {

	/**
	 * Create a new UnreviewedXrefs testcase.
	 */
	public UnreviewedXrefs() {

		addToGroup("release");
		addToGroup("core_xrefs");
		addToGroup("post-compara-handover");

		setDescription("Check for Uniprot xrefs that have 'Unreviewed' as the primary DB accession.");
		setPriority(Priority.AMBER);
		setEffect("Affected xrefs will have broken hyperlinks, also problems for downstream pipelines.");
		setFix("Re-run xref system or manually fix affected xrefs.");
		setTeamResponsible(Team.CORE);
		setSecondTeamResponsible(Team.GENEBUILD);

	}

	/**
	 * Run the test.
	 *
	 * @param dbre
	 *          The database to use.
	 * @return true if the test passed.
	 *
	 */
	public boolean run(DatabaseRegistryEntry dbre) {

		boolean result = true;

		Connection con = dbre.getConnection();

		// --------------------------------
		// MGI - dbprimary_acc should have MGI: prefix
		int rows = getRowCount(con, "SELECT COUNT(*) FROM xref x, external_db e WHERE e.external_db_id=x.external_db_id AND e.db_name LIKE 'UniProt%' AND x.dbprimary_acc='Unreviewed';");

		if (rows > 0) {
			ReportManager.problem(this, con, rows + " UniProt xrefs have \'Unreviewed\' as the primary accession.");
			result = false;
		} else {
			ReportManager.correct(this, con, "No Uniprot xrefs have \'Unreviewed\' as the accession.");
		}

		return result;

	} // run

} // UnreviewedXrefs


package leetcode.valid_sudoku;

public class Solution {
	public static final int N = 9;

    public boolean isValidSudoku(char[][] board) {
    	boolean[][] appearX = new boolean[N][N];
    	boolean[][] appearY = new boolean[N][N];
    	boolean[][] appearG = new boolean[N][N];
    	for(int x = 0; x < N; x++){
    		for(int y = 0; y < N; y++){
    			if(board[x][y] != '.'){
    				int d = board[x][y] - '1';
    				int g = (x / 3) * 3 + (y / 3);
    				if(appearX[x][d] || appearY[y][d] || appearG[g][d]) return false;
    				appearX[x][d] = appearY[y][d] = appearG[g][d] = true;
    			}
    		}
    	}
    	return true;
    }

    public static void main(String[] args){
    	String[] s = new String[]{"....4.9..","..21..3..",".........","........3","...2.....",".....7...","...61....","..9......",".......9."};
    	char[][] board = new char[N][N];
    	for(int i = 0; i < N; i++){
    		board[i] = s[i].toCharArray();
    	}
    	System.err.println(new Solution().isValidSudoku(board) + "");
    }
}

Add java solution for 36. Valid Sudoku


import java.util.Scanner;

/**
 * This program computes the factorial of an input integer >=0 and <=12
 **/
public class Factorial {
    public static void main(String[] args) {
        // Multiple assignment
        // "number" will have no value, while
        // "factorial" is set to 1
        int number, factorial = 1;

        System.out.println("Input a number >=0 and <= 12");

        // Create a new Scanner object using System.in
        // This object allows us to get keyboard input
        Scanner scan = new Scanner(System.in);
        // Give us the next Integer value inputted via the keyboard.
        // Using nextInt() will ensure the value is an Integer.
        number = scan.nextInt();

        // Calculate the factorial using the standard algorithm
        for (int i = 1; i <= number; i++) {
            factorial = factorial * i;
        }

        // String concatanation
        // println() will parse Integers into Strings (turns numbers into strings)
        // then stick everything together into one long string.
        System.out.println("Factorial of " + number + " = " + factorial);
    }
}

Add problem 2 for unit 1


package org.realityforge.arez.api2;

import org.realityforge.guiceyloops.shared.ValueUtil;
import org.testng.annotations.Test;
import static org.testng.Assert.*;

public class TransactionTest
  extends AbstractArezTest
{
  @Test
  public void construction()
  {
    final ArezContext context = new ArezContext();
    final String name1 = ValueUtil.randomString();
    final int nextNodeId = context.currentNextNodeId();

    final Transaction transaction = new Transaction( context, null, name1, null );

    assertEquals( transaction.getName(), name1 );
    assertEquals( transaction.getContext(), context );
    assertEquals( transaction.getId(), nextNodeId );
    assertEquals( transaction.getPrevious(), null );
    assertEquals( transaction.getTracker(), null );
    assertEquals( transaction.getObservables(), null );
    assertEquals( transaction.getPendingPassivations(), null );

    assertEquals( context.currentNextNodeId(), nextNodeId + 1 );
  }

  @Test
  public void trackingCycleWithNoTracker()
  {
    final ArezContext context = new ArezContext();
    final Transaction transaction = new Transaction( context, null, ValueUtil.randomString(), null );

    final TestObservable observable = new TestObservable( context, ValueUtil.randomString() );

    assertEquals( observable.getObservers().size(), 0 );
    assertEquals( transaction.getObservables(), null );

    //Transaction should perform no action during tracking if there is no associated tracker
    transaction.beginTracking();
    transaction.observe( observable );
    transaction.completeTracking();

    assertEquals( observable.getObservers().size(), 0 );
    assertEquals( transaction.getObservables(), null );
  }
}

Add some basic unit tests for transaction


package ca.corefacility.bioinformatics.irida.web.controller.test.integration.security;

import static com.jayway.restassured.RestAssured.expect;
import static org.hamcrest.CoreMatchers.containsString;
import static org.hamcrest.CoreMatchers.is;

import org.apache.http.HttpStatus;
import org.junit.Test;

/**
 * General tests relating to security for the REST API.
 *
 */
public class SecurityIT {

	/**
	 * Test that we get the right type of response when we don't have valid
	 * credentials.
	 */
	@Test
	public void testAccessWithoutAuthentication() {
		expect().body("error", is("invalid_request")).and()
				.body("error_description", containsString("No client credentials were provided"))
				.statusCode(HttpStatus.SC_UNAUTHORIZED).when().get("/api");
	}
}

Add a test to verify that we're getting the customized error message when accessing the rest api without credentials.


package de.asw.java.training2016.basics;

import java.util.concurrent.TimeUnit;

public class ThreadSleepExamples {

	public static void main(String[] args) {

		System.out.println("Warte!");

		try {
			// Alternative 1 (Sprechende API)
			TimeUnit.SECONDS.sleep(2);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}

		// Alternative 2: (Java Standard)
		// try {
		// Thread.sleep(2000);
		// } catch (InterruptedException e) {
		// e.printStackTrace();
		// }

		// Alternative 3 (Advanced Java)
		// LockSupport.parkNanos(TimeUnit.SECONDS.toNanos(2));

		System.out.println("Fertig!");
	}
}

Add example for letting a Thread sleep for some time


package com.stanfy.gsonxml.issues;

import com.stanfy.gsonxml.GsonXml;
import com.stanfy.gsonxml.GsonXmlBuilder;
import com.stanfy.gsonxml.XmlParserCreator;

import org.junit.Before;
import org.junit.Test;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserFactory;

import java.math.BigDecimal;
import java.util.List;

import static org.junit.Assert.assertEquals;

/**
 * Issue EmptyList.
 */
public class IssueEmptyList {

  private GsonXml gsonXml;

  static class A {
    List B;
    List C;
  }

  static class I {
    BigDecimal v;
  }

  @Before
  public void init() {
    XmlParserCreator parserCreator = new XmlParserCreator() {
      public XmlPullParser createParser() {
        try {
          return XmlPullParserFactory.newInstance().newPullParser();
        } catch (Exception e) {
          throw new RuntimeException(e);
        }
      }
    };

    gsonXml = new GsonXmlBuilder()
        .setXmlParserCreator(parserCreator)
        .create();
  }

  @Test
  public void reproduce() {
    A a = gsonXml.fromXml("<C></C>", A.class);
    assertEquals("{\"B\":[],\"C\":[]}", gsonXml.getGson().toJson(a));
  }

}

Add test with two empty lists in xml.


package com.github.onsdigital.babbage.template.handlebars.helpers.markdown.util;

import com.github.onsdigital.babbage.template.TemplateService;

import java.io.IOException;
import java.util.LinkedHashMap;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class PulloutBoxTagReplacer extends TagReplacementStrategy {

    private static final Pattern pattern = Pattern.compile("<ons-box align=\"([a-zA-Z]*)\">(.*?)</ons-box>");
    private final String template;

    /**
     * Create an instance of a tag replacement strategy with the given page path.
     * <p>
     * The page path is the path of the page having tags replaced. It is used to resolve links that are relative to the page.
     *
     * @param path
     */
    public PulloutBoxTagReplacer(String path, String template) {
        super(path);
        this.template = template;
    }

    @Override
    Pattern getPattern() {
        return pattern;
    }

    @Override
    String replace(Matcher matcher) throws IOException {

        String alignment = matcher.group(1);
        String content = matcher.group(2);
        LinkedHashMap<String, Object> additionalData = new LinkedHashMap<>();
        additionalData.put("id", UUID.randomUUID().toString().substring(10));
        additionalData.put("content", content);
        additionalData.put("alignment", alignment);
        return TemplateService.getInstance().renderTemplate(template, null, additionalData);
    }
}

Add handler for <ons-box> tags in markdown


package org.intermine.webservice.server;

import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

public enum Format {

    /** The format for when no value is given **/
    EMPTY(null),
    /** The Unknown format **/
    UNKNOWN(null),
    /** The HTML format **/
    HTML("text/html"),
    /** Plain Text **/
    TEXT("text/plain"),
    /** XML **/
    XML("application/xml"),
    /** Comma-separated-values **/
    CSV("text/comma-separated-values"),
    /** Tab-separated-values **/
    TSV("text/tab-separated-values"),
    /** Vanilla-JSON **/
    JSON("application/json"),
    /** JSON Object format constant **/
    OBJECTS("application/json;format=objects"),
    /** JSON Table format constant **/
    TABLE("application/json;format=table"),
    /** JSON Row format constant **/
    ROWS("application/json;format=rows");

    public static final Set<Format> BASIC_FORMATS = new HashSet<Format>(Arrays.asList(
        HTML, TEXT, XML, JSON
    ));

    public static final Set<Format> JSON_FORMATS = new HashSet<Format>(Arrays.asList(
        JSON, OBJECTS, TABLE, ROWS
    ));

    public static final Set<Format> FLAT_FILES = new HashSet<Format>(Arrays.asList(
        TSV, CSV
    ));

    private final String contentType;

    private Format(String contentType) {
        this.contentType = contentType;
    }

    public String getContentType() {
        return contentType;
    }

    @Override
    public String toString() {
        return super.toString() + ((contentType == null) ? "" : (" (" + contentType + ") "));
    }

}

Move to a much cleaner format implementation


package com.samuel.cachelocator;

/**
 * Created by Samuel on 7/22/2015.
 */
public class Constants {
    //Class

    //Fields
    public static final float METERS_PER_FEET = 0.3048f;
    public static final int METERS_PER_KILOMETER = 1000;
}

Add global variables to be used throughout the application


package io.undertow.util;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

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

/**
 * Tests that the headers in the Headers class have the correct order. The headers
 * are assigned an explicit ordering integer to allow for super fast comparisons.
 *
 * @author Stuart Douglas
 */
public class HeaderOrderTestCase {

    @Test
    public void testHeadersOrder() throws Exception {

        final Field orderIntField = HttpString.class.getDeclaredField("orderInt");
        orderIntField.setAccessible(true);

        Field[] fields = Headers.class.getDeclaredFields();
        final List<HttpString> headers = new ArrayList<>();
        for(final Field field : fields) {
            Object value = field.get(null);
            if(!(value instanceof HttpString)) {
                continue;
            }
            HttpString header = (HttpString) value;
            if((int)orderIntField.get(header) != 0) {
                headers.add(header);
            }
        }

        Collections.sort(headers, new Comparator<HttpString>() {
            @Override
            public int compare(final HttpString o1, final HttpString o2) {
                return o1.toString().toLowerCase().compareTo(o2.toString().toLowerCase());
            }
        });
        int val = 1;
        for(final HttpString header : headers) {
            Assert.assertEquals(val++, orderIntField.get(header));
        }

    }

}

Add test for header ordering


package com.zenika.cudf.adapter;

import com.zenika.cudf.model.CUDFDescriptor;

/**
 * @author Antoine Rouaze <antoine.rouaze@zenika.com>
 */
public interface Adapter<T> {

    T fromCUDF(CUDFDescriptor descriptor);

    CUDFDescriptor toCUDF(T descriptors);
}

Add adapter in core project.


class Stack {
	int top1, top2;
	private int[] arr;
	public Stack(int capacity) {
		arr = new int[capacity];
		top1= -1;
		top2= arr.length;
	}
	public void push1(int data) {
		if (top1 < top2 -1) {
			top1++;
			arr[top1] = data;

		} else {
			System.out.println("filled up");
		}

	}
	public void push2(int data) {
		if (top1 < top2-1) {
			top2--;
			arr[top2] = data;

		} else {
			System.out.println("filled up");
		}

	}
	public int pop1() {
		if (top1 == -1) {
			System.out.println("Underflow ");
			return -1;
		}
		else {
			int temp = arr[top1];
			top1--;
			return temp;
		}
	}
	public int pop2() {
		if (top2 == arr.length) {
			System.out.println("Underflow ");
			return -1;
		}
		else {
			int temp = arr[top2];
			top2++;
			return temp;
		}
	}
	public void print1() {
		for( int i=0; i <= top1; i++) {
			System.out.print(arr[i] + " : ");
		}
	}
	public void print2() {
		for( int i=arr.length-1; i >= top2; i--) {
			System.out.print(arr[i] + " : ");
		}

	}
	public void emptyStack1() {
		System.out.println("top1 :" + top1);
		int nTemp ;
		while(true) {
			nTemp = pop1();
			if (nTemp == -1)
				break;
			System.out.print(nTemp + " : ");
		}
		System.out.println("---------------");
	}
	public void emptyStack2() {
		for(int i= top2; i <= arr.length-1; i++) {
			System.out.print(pop2() + " : ");
		}
	}
}
class TwoStacksInOneArray {
	public static void main(String[] args) {
		Stack stack = new Stack(5);
		stack.push1(5);
		stack.push2(10);
		stack.push2(15);
		stack.push2(7);
		stack.push1(11);

		stack.print1();
		System.out.println("***");
		stack.print2();
		System.out.println("***1.1***");

		stack.emptyStack1();
		stack.emptyStack2();
		System.out.println("***1.2***");

		stack.push1(25);
		stack.push2(30);
		System.out.println("***1.3***");

		stack.print1();
		stack.print2();
	}

}

Use of one array to implement 2 stacks


package hudson.plugins.git;

import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import static org.hamcrest.CoreMatchers.is;

public class GitExceptionTest {

    @Rule
    public ExpectedException thrown = ExpectedException.none();

    @Test
    public void throwsGitException() {
        String message = null;
        thrown.expect(GitException.class);
        thrown.expectMessage(is(message));
        throw new GitException();
    }

}

Add test of GitException with no message string


/*
 * Copyright 2018 B2i Healthcare Pte Ltd, http://b2i.sg
 *
 * 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.b2international.snowowl.datastore.server.history;

import java.util.Objects;

import org.eclipse.emf.ecore.EClass;

import com.b2international.snowowl.datastore.cdo.LocalDbUtils;

/**
 * Minimal implementation of {@link PreparedStatementKey} that is identified by the EClass
 * it is queried against.
 */
public final class OtherComponentStatementKey implements PreparedStatementKey {

	private static final String QUERY_TEMPLATE = "SELECT "
			+ "component.CDO_ID, " // Redundant, only returned to be compatible with all other "other component" queries
			+ "component.CDO_CREATED, "
			+ "component.CDO_REVISED "
			// -------------------------------
			+ "FROM %s component "
			// -------------------------------
			+ "WHERE component.CDO_ID = ? "
			+ "AND component.CDO_BRANCH = ? "
			+ "AND component.CDO_CREATED <= ? "
			+ "ORDER BY component.CDO_CREATED DESC ";

	private final EClass eClass;

	public OtherComponentStatementKey(final EClass eClass) {
		this.eClass = eClass;
	}

	public String getQuery() {
		final String tableName = LocalDbUtils.tableNameFor(eClass);
		return String.format(QUERY_TEMPLATE, tableName);
	}

	@Override
	public int hashCode() {
		return Objects.hash(eClass);
	}

	@Override
	public boolean equals(final Object obj) {
		if (this == obj) { return true; }
		if (obj == null) { return false; }
		if (getClass() != obj.getClass()) { return false; }

		final OtherComponentStatementKey other = (OtherComponentStatementKey) obj;
		return Objects.equals(eClass, other.eClass);
	}
}

Introduce prepared statement key for determining minor...


/*
 * The MIT License (MIT)
 *
 * Copyright (c) 2015 Norwegian Defence Research Establishment / NTNU
 *
 * 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 no.ntnu.okse;

import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;

import java.time.Duration;
import java.util.Properties;

import static org.testng.Assert.*;

@Test(singleThreaded = true)
public class ApplicationTest {

    @BeforeMethod
    public void setUp() throws Exception {

    }

    @AfterMethod
    public void tearDown() throws Exception {

    }

    @Test
    public void testGetRunningTime() throws Exception {
        assertTrue(Application.getRunningTime() instanceof Duration);
        assertTrue(Application.getRunningTime().compareTo(Duration.ofMillis(0)) >= 0);
    }

    @Test
    public void testResetStartTime() throws Exception {
        Thread.sleep(10);
        long d = Application.getRunningTime().toMillis();
        Application.resetStartTime();
        long s = Application.getRunningTime().toMillis();
        assertTrue(s < d);

    }

    @Test
    public void testReadConfigurationFiles() throws Exception {
        Properties p = Application.readConfigurationFiles();
        assertNotNull(p);
    }
}

Add a couple of tests for Application methods


package net.hexid.hexbot;

import java.util.Arrays;
import net.hexid.hexbot.bot.Bots;
import net.hexid.hexbot.bot.cmd.BotCMD;

public class HexBotFallback extends HexBot {
	public HexBotFallback() {
		super();
	}

	protected void init(String[] args) {
		Bots.removeInvalidBots();

		if(args.length > 0 && args[0].equalsIgnoreCase("gui")) {
			args = Arrays.copyOfRange(args, 1, args.length);
		}

		BotCMD.init(args);
	}

	public static void main(String[] args) {
		HexBotFallback hexbotFallback = new HexBotFallback();
		hexbotFallback.init(args);
	}
}

Add a fallback that gets run when JavaFX is not present


/*
 * (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.BeforeClass;
import org.junit.ClassRule;
import org.junit.Test;
import org.junit.rules.ExternalResource;

public class TestClassRule {

    private static Resource resource;

    @ClassRule
    public static ExternalResource rule = new ExternalResource() {
        @Override
        protected void before() throws Throwable {
            resource = new Resource();
            resource.open();
        }

        @Override
        protected void after() {
            resource.close();
            System.out.println();
        }
    };

    @BeforeClass
    public static void before() {
        System.out.println("before class");
    }

    @Test
    public void someTest() throws Exception {
        System.out.println(resource.get());
    }

    @Test
    public void someTest2() throws Exception {
        System.out.println(resource.get());
    }

}

Add @ClassRule example in JUnit 4 project


package net.imagej.ops.viewOp;

import org.scijava.plugin.Plugin;

import net.imagej.ops.view.ViewOps;
import net.imagej.ops.view.ViewOps.ExtendBorder;
import net.imglib2.RandomAccessibleInterval;
import net.imglib2.view.ExtendedRandomAccessibleInterval;
import net.imglib2.view.Views;

@Plugin(type = ViewOps.ExtendBorder.class, name = ViewOps.ExtendBorder.NAME)
public class DefaultExtendBorder<T, F extends RandomAccessibleInterval<T>>
		extends AbstractView<F, ExtendedRandomAccessibleInterval<T, F>>
		implements ExtendBorder<F, ExtendedRandomAccessibleInterval<T, F>> {

	@Override
	public ExtendedRandomAccessibleInterval<T, F> compute(F input) {
		return Views.extendBorder(input);
	}

}

Add default implementation of ExtendBorder interface.


package com.jmb.springfactory.model.entity;

public class Rol extends BaseEntity{

  private String name;

  public String getName() {
    return name;
  }

  public void setName(String name) {
    this.name = name;
  }
}

Implement a class to represent roles for a user


package seedu.ezdo.logic.parser;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static seedu.ezdo.logic.parser.DateParser.USER_DATE_OUTPUT_FORMAT;

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

import org.junit.Test;

/**
 * Tests the behaviour of the date parser
 */
public class DateParserTest {

    DateParser dateParser;

    /**
     * Checks if dates in natural language are parsed correctly
     * @throws Exception
     */
    @Test
    public void checkNaturalParsing() throws Exception {
        DateFormat expectedFormat = new SimpleDateFormat(USER_DATE_OUTPUT_FORMAT);
        Date dt = new Date();
        Calendar c = Calendar.getInstance();
        c.setTime(dt);

        dateParser = new DateParser("today");
        String expectedValue = expectedFormat.format(dt);
        assertTrue(expectedValue.equals(dateParser.value));

        dateParser = new DateParser("tomorrow");
        c.add(Calendar.DATE, 1); // add 1 day to get tomorrow's date
        dt = c.getTime();
        expectedValue = expectedFormat.format(dt);
        assertTrue(expectedValue.equals(dateParser.value));
    }

    /**
     * Checks if dates formatted in DD/MM/YYYY are parsed correctly
     */
    @Test
    public void checkFormatParsing() throws Exception {
        dateParser = new DateParser("31/12/2017 11:00");
        assertEquals(dateParser.value, "31/12/2017 11:00");

        dateParser = new DateParser("1/1/2016 12:00");
        assertEquals(dateParser.value, "01/01/2016 12:00");

        dateParser = new DateParser("15/01/2016 00:00");
        assertEquals(dateParser.value, "15/01/2016 00:00");
    }
}

Add tests for date parser


package prototypev.PermissiveFov;

import java.security.SecureRandom;

public class Randomizer extends SecureRandom {
    private static Randomizer instance;

    private Randomizer() {
    }

    public static Randomizer getInstance() {
        if (instance == null) {
            instance = new Randomizer();
        }

        return instance;
    }

    /**
     * @param clazz   The class of the enum.
     * @param <TEnum> The type of the enum.
     * @return A pseudo-random uniformly distributed enum value of the specified type.
     */
    public <TEnum extends Enum<?>> TEnum getRandomEnum(Class<TEnum> clazz) {
        int x = nextInt(clazz.getEnumConstants().length);
        return clazz.getEnumConstants()[x];
    }

    /**
     * @param minimum The lower bounds of the range.
     * @param maximum The upper bounds of the range.
     * @return A pseudo-random uniformly distributed {@code int} in the closed range [minimum, maximum].
     */
    public int nextInt(int minimum, int maximum) {
        int range = maximum - minimum + 1;
        return nextInt(range) + minimum;
    }
}

Create utility class for generating random values


public class Solution {

    public int findComplement(int num) {

        int exponent = 0;

        int i = 0;

        while (i < num) {

            i += Math.pow(2, exponent);
            exponent++;

        }

        int complement = i - num;

        return complement;

    }

}

Create : 476 Number Complement


package com.scylladb.jmx.utils;

import java.time.Instant;
import java.util.Date;

import javax.xml.bind.annotation.adapters.XmlAdapter;

public class DateXmlAdapter extends XmlAdapter<String, Date> {
    @Override
    public String marshal(Date v) throws Exception {
        return Instant.ofEpochMilli(v.getTime()).toString();
    }

    @Override
    public Date unmarshal(String v) throws Exception {
        return new Date(Instant.parse(v).toEpochMilli());
    }

}

Add Date json serializer helper


/*
 *  Copyright (c) 2005-2014, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
 *
 *  WSO2 Inc. 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.wso2.msf4j.spring;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * Server configuration for Spring.
 */
@Configuration
public class ServerConfig {

    /*
     This will override "SpringMicroservicesRunner" bean configured in default MSF4JSpringConfiguration class, this
     enables to start Netty transport on 9090 port.
     NOTE - Due to Spring framework limitations this feature only work with Spring versions starting from 4.2.0
     */
    @Bean
    public SpringMicroservicesRunner springMicroservicesRunner() {
        return new SpringMicroservicesRunner(9291);
    }
}

Use a non standard port for Spring tests to avoid clashes


package com.example.drinkingapp;

import android.widget.CheckBox;

public class CheckValue {
	public String value;
	public CheckBox view;

	public CheckValue(String str_value, CheckBox chk_view){
		value = str_value;
		view = chk_view;
	}
}

Add class to assist in handling many checkboxes


package nl.fifth.postulate.tools;

import nom.tam.fits.Fits;
import nom.tam.fits.FitsException;
import nom.tam.fits.ImageData;
import nom.tam.fits.ImageHDU;
import org.junit.Test;

import java.io.IOException;

import static org.hamcrest.core.Is.is;
import static org.hamcrest.core.IsNot.not;
import static org.hamcrest.core.IsNull.nullValue;
import static org.junit.Assert.assertThat;

public class FitsTest {
    @Test
    public void shouldReadFitsFile() throws FitsException, IOException {
        Fits f = new Fits("../k2-trappist1-unofficial-tpf-long-cadence.fits");
        ImageHDU hdu = (ImageHDU) f.getHDU(2);
        ImageData imageData = (ImageData) hdu.getData();
        int[][] image = (int[][]) imageData.getData();

        assertThat(hdu, is(not(nullValue())));
        assertThat(imageData, is(not(nullValue())));
        assertThat(image, is(not(nullValue())));
        assertThat(image.length, is(11));
        assertThat(image[0].length, is(11));
    }
}

Read an image from fits file


package leetcode.binary_tree_right_side_view;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

import common.TreeNode;

public class Solution {
    public static class TreeNodeWithDepth{
        TreeNode node;
        int depth;
        public TreeNodeWithDepth(TreeNode node, int depth){
            this.node = node;
            this.depth = depth;
        }
    }
    public List<Integer> rightSideView(TreeNode root) {
        List<Integer> solution = new ArrayList<Integer>();
        Queue<TreeNodeWithDepth> queue = new LinkedList<TreeNodeWithDepth>();
        if(root != null){
            int curDepth = -1;
            queue.offer(new TreeNodeWithDepth(root, 0));
            while(!queue.isEmpty()){
                TreeNodeWithDepth twd = queue.remove();
                if(twd.node != null){
                    if(curDepth < twd.depth){
                        solution.add(twd.node.val);
                        curDepth = twd.depth;
                    }
                    queue.offer(new TreeNodeWithDepth(twd.node.right, twd.depth + 1));
                    queue.offer(new TreeNodeWithDepth(twd.node.left, twd.depth + 1));
                }
            }
        }
        return solution;
    }
}

Add java solution for 199. Binary Tree Right Side View


package com.google.sps.servlets;

import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;
import com.google.gson.Gson;
import com.google.sps.data.AuthInfo;
import java.io.IOException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/login")
public class AuthServlet extends HttpServlet {

  @Override
  public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
    response.setContentType("application/json");
    Gson gson = new Gson();

    UserService userService = UserServiceFactory.getUserService();
    if (userService.isUserLoggedIn()) {
      String redirectAfterLogout = "/";
      String logoutURL = userService.createLogoutURL(redirectAfterLogout);

      AuthInfo userLoginStatus = AuthInfo.createLoggedInInfo(logoutURL);
      response.getWriter().println(gson.toJson(userLoginStatus));
    } else {
      String redirectAfterLogin = "/";
      String loginURL = userService.createLoginURL(redirectAfterLogin);

      AuthInfo userLoginStatus = AuthInfo.createLoggedOutInfo(loginURL);
      response.getWriter().println(gson.toJson(userLoginStatus));
    }
  }
}

Add servlet to handle user authentication


package de.fau.osr.core.vcs.base;

import org.junit.Test;

import static org.junit.Assert.*;

/**
 * Created by Rajab Kaoneka on 18.05.2015.
 */
public class CommitTest {

    @Test
    public void CommitConstructor_idField_Test(){
        Commit commitToTest = new Commit("new_id", null, null, null);
        assertEquals("commit id should be equal the initialization id", "new_id", commitToTest.id);
    }
}

Test for Commit, testing ID initialization


package info.u_team.u_team_core.gui;

import net.minecraft.client.gui.screen.inventory.ContainerScreen;
import net.minecraft.entity.player.PlayerInventory;
import net.minecraft.inventory.container.Container;
import net.minecraft.util.text.ITextComponent;

public abstract class FluidContainerScreen<T extends Container> extends ContainerScreen<T> {

	public FluidContainerScreen(T screenContainer, PlayerInventory inv, ITextComponent titleIn) {
		super(screenContainer, inv, titleIn);
	}

	@Override
	protected void drawGuiContainerForegroundLayer(int mouseX, int mouseY) {
	}

}

Add basic fluid container screen class