/*
 * Copyright (c) 2015 Legend Zero LLC
 *
 * 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.legendzero.lzlib.util;

import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import org.bukkit.util.Vector;

@NoArgsConstructor(access = AccessLevel.PRIVATE)
public final class Vectors {

    public static Vector fromCSV(String string) {
        return fromCSV(string.split(","));
    }

    public static Vector fromCSV(String[] strings) {
        double x = 0;
        double y = 0;
        double z = 0;
        try {
            switch (strings.length) {
                case 3:
                    z = Double.valueOf(strings[2]);
                case 2:
                    y = Double.valueOf(strings[1]);
                case 1:
                    x = Double.valueOf(strings[0]);
                case 0:
                    break;
                default:

            }
        } catch (NumberFormatException e) {
            return null;
        }
        return new Vector(x, y, z);
    }

    public static String toCSV(Vector vector) {
        return vector.getX() + "," + vector.getY() + "," + vector.getZ();
    }
}

Add easy Vector String conversions


/**
 * Copyright 2015 Alessandro Daniele, Fabio Cesarato, Andrea Giraldin
 *
 * 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.salsaw.salsa.utils;

// http://www.mkyong.com/java/how-to-detect-os-in-java-systemgetpropertyosname/
public class OSChecker {

	private static String OS = System.getProperty("os.name").toLowerCase();

	public static boolean isWindows() {
		return (OS.indexOf("win") >= 0);
 	}

	public static boolean isMac() {
 		return (OS.indexOf("mac") >= 0);
	}

	public static boolean isUnix() {
		return (OS.indexOf("nix") >= 0 || OS.indexOf("nux") >= 0 || OS.indexOf("aix") > 0 );
 	}

	public static boolean isSolaris() {
		return (OS.indexOf("sunos") >= 0);
	}
}

Add class to get current opertive system


/*
 * This file is part of Sponge, licensed under the MIT License (MIT).
 *
 * Copyright (c) SpongePowered.org <http://www.spongepowered.org>
 * Copyright (c) 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 org.spongepowered.api.service.command;

import org.spongepowered.api.util.command.dispatcher.Dispatcher;

/**
 * A command dispatcher watches for commands (such as those said in chat)
 * and dispatches them to the correct command handler.
 */
public interface CommandDispatcher extends Dispatcher {

}

Add preliminary command dispatcher service.


package org.telegram.telegrambots.api.commands;

import org.telegram.telegrambots.BotLogger;
import org.telegram.telegrambots.TelegramApiException;
import org.telegram.telegrambots.api.methods.send.SendMessage;

/**
 * standard help command, which gets registered by default, to supply a list of all available commands
 *
 * @author tschulz
 */
public class HelpCommand extends Command {

    private static final String LOGTAG = "HELPCOMMAND";
    private final ICommandRegistery commandRegistry;

    public HelpCommand(ICommandRegistery commandRegistry, String botToken) {
        super("help", "Gives an overview over all Commands registered for this bot", botToken);
        this.commandRegistry = commandRegistry;
    }

    @Override
    void execute(String[] arguments, long chatId) {
        for (Command registeredCommand : commandRegistry.getRegisteredCommands()) {
            SendMessage sendMessage = new SendMessage();
            sendMessage.setChatId(chatId);
            sendMessage.enableHtml(true);
            sendMessage.setText("<b>" + registeredCommand.getCommandIdentifier() + "</b>\n" + registeredCommand.getDescription());

            try {
                sendMessage(sendMessage);
            } catch (TelegramApiException e) {
                BotLogger.error("Failed to send HelpMessage", LOGTAG, e);
            }
        }
    }
}

Implement basic help command, which provides an overview over all registered commands


package com.gmail.nossr50.listeners;

import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.entity.PlayerDeathEvent;

import com.gmail.nossr50.util.Hardcore;
import com.gmail.nossr50.util.Misc;
import com.gmail.nossr50.util.Permissions;

public class HardcoreListener implements Listener {

    /**
     * Monitor PlayerDeath events.
     *
     * @param event The event to monitor
     */
    @EventHandler(priority = EventPriority.MONITOR)
    public void onPlayerDeath(PlayerDeathEvent event) {
        Player player = event.getEntity();

        if (Misc.isNPCPlayer(player)) {
            return;
        }

        if (!Permissions.hardcoremodeBypass(player)) {
            Player killer = player.getKiller();

            if (killer != null && Hardcore.vampirismEnabled) {
                Hardcore.invokeVampirism(killer, player);
            }

            Hardcore.invokeStatPenalty(player);
        }
    }
}

package com.gmail.nossr50.listeners;

import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.entity.PlayerDeathEvent;

import com.gmail.nossr50.util.Hardcore;
import com.gmail.nossr50.util.Misc;
import com.gmail.nossr50.util.Permissions;

public class HardcoreListener implements Listener {

    /**
     * Monitor PlayerDeath events.
     *
     * @param event The event to watch
     */
    @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
    public void onPlayerDeath(PlayerDeathEvent event) {
        Player player = event.getEntity();

        if (Misc.isNPCPlayer(player)) {
            return;
        }

        if (!Permissions.hardcoremodeBypass(player)) {
            Player killer = player.getKiller();

            if (killer != null && Hardcore.vampirismEnabled) {
                Hardcore.invokeVampirism(killer, player);
            }

            Hardcore.invokeStatPenalty(player);
        }
    }
}

Make sure we ignore cancelled events.


package com.samczsun.helios.gui;

import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.events.MouseListener;

import java.util.function.BiConsumer;

/**
 * @author DarkSeraphim.
 */
public class GenericClickListener implements MouseListener, java.awt.event.MouseListener {

    enum ClickType {
        LEFT, MIDDLE, RIGHT;
        private static ClickType fromButton(int button) {
            return ClickType.values()[button - 1];
        }
    }

    private final BiConsumer<ClickType, Boolean> handler;

    private final byte buttons;

    private final boolean doubleClick;

    public GenericClickListener(BiConsumer<ClickType, Boolean> handler, ClickType type, ClickType...others) {
        this(handler, false, type, others);
    }

    public GenericClickListener(BiConsumer<ClickType, Boolean> handler, boolean doubleClick, ClickType type, ClickType...others) {
        this.handler = handler;
        this.doubleClick = doubleClick;
        int buttons = 1 << type.ordinal();
        for (ClickType otherType : others) {
            buttons |= 1 << otherType.ordinal();
        }
        this.buttons = (byte) buttons;
    }

    /* *
     * SWT events
     * */

    @Override
    public void mouseDoubleClick(MouseEvent event) {
        handle(ClickType.fromButton(event.button), true);
    }

    @Override
    public void mouseDown(MouseEvent event) {
    }

    private void handle(ClickType type, boolean doubleClick) {
        if (this.doubleClick == doubleClick && (this.buttons & (1 << (type.ordinal()))) != 0) {
            this.handler.accept(type, doubleClick);
        }
    }

    @Override
    public void mouseUp(MouseEvent event) {
        handle(ClickType.fromButton(event.button), false);
    }

    /* *
     * AWT events
     * */

    @Override
    public void mouseClicked(java.awt.event.MouseEvent e) {
        handle(ClickType.fromButton(e.getButton()), false);
    }

    @Override
    public void mousePressed(java.awt.event.MouseEvent e) {
    }

    @Override
    public void mouseReleased(java.awt.event.MouseEvent e) {
    }

    @Override
    public void mouseEntered(java.awt.event.MouseEvent e) {
    }

    @Override
    public void mouseExited(java.awt.event.MouseEvent e) {
    }
}

Add generic click listener for AWT and SWT


package com.suse.salt.netapi.calls.modules;

import com.google.gson.reflect.TypeToken;
import com.suse.salt.netapi.calls.LocalCall;

import java.util.LinkedHashMap;
import java.util.List;
import java.util.Optional;

/**
 * salt.modules.zypper
 *
 * https://docs.saltstack.com/en/latest/ref/modules/all/salt.modules.zypper.html
 */
public class Zypper {

    private Zypper() { }

    /**
     * The product information as returned by listProducts().
     */
    public static class ProductInfo {
        private final String name;
        private final String arch;
        private final String description;
        private final String eol;
        private final String epoch;
        private final String flavor;
        private final boolean installed;
        private final boolean isbase;
        private final String productline;
        private final String registerrelease;
        private final String release;
        private final String repo;
        private final String shortname;
        private final String summary;
        private final String vendor;
        private final String version;

        public ProductInfo(String name, String arch, String description, String eol,
                String epoch, String flavor, boolean installed, boolean isbase,
                String productline, String registerrelease, String release, String repo,
                String shortname, String summary, String vendor, String version) {
            this.name = name;
            this.arch = arch;
            this.description = description;
            this.eol = eol;
            this.epoch = epoch;
            this.flavor = flavor;
            this.installed = installed;
            this.isbase = isbase;
            this.productline = productline;
            this.registerrelease = registerrelease;
            this.release = release;
            this.repo = repo;
            this.shortname = shortname;
            this.summary = summary;
            this.vendor = vendor;
            this.version = version;
        }

        public String getName() {
            return name;
        }

        public String getVersion() {
            return version;
        }

        public String getArch() {
            return arch;
        }

        public String getDescription() {
            return description;
        }

        public String getEol() {
            return eol;
        }

        public String getEpoch() {
            return epoch;
        }

        public String getFlavor() {
            return flavor;
        }

        public boolean getInstalled() {
            return installed;
        }

        public boolean getIsbase() {
            return isbase;
        }

        public String getProductline() {
            return productline;
        }

        public String getRegisterrelease() {
            return registerrelease;
        }

        public String getRelease() {
            return release;
        }

        public String getRepo() {
            return repo;
        }

        public String getShortname() {
            return shortname;
        }

        public String getSummary() {
            return summary;
        }

        public String getVendor() {
            return vendor;
        }
    }

    public static LocalCall<List<ProductInfo>> listProducts(boolean all) {
        LinkedHashMap<String, Object> args = new LinkedHashMap<>();
        args.put("all", all);
        return new LocalCall<>("pkg.list_products", Optional.empty(), Optional.of(args),
                new TypeToken<List<ProductInfo>>() { });
    }
}

Add zypper module support containing listProducts()


package flyway.pti;

import fi.nls.oskari.util.JSONHelper;
import org.flywaydb.core.api.migration.BaseJavaMigration;
import org.flywaydb.core.api.migration.Context;
import org.json.JSONObject;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * Removed layer.options.legends object (removing any override admin has given) for layers
 * returned by getLayersToModify().
 * This one removes overrides from layers with dataprovider 57 (Tilastokeskus)-
 */
public class V3_0_8__remove_legend_overrides extends BaseJavaMigration {

    class Result {
        int id;
        String options;
    }

    public void migrate(Context context) throws Exception {
        Connection connection = context.getConnection();
        List<Result> layers = getLayersToModify(connection);
        layers.forEach(r -> removeLegendOverrides(r));
        saveChanges(connection, layers);
    }

    private void removeLegendOverrides(Result result) {
        if (result.options == null) {
            return;
        }
        JSONObject options = JSONHelper.createJSONObject(result.options);
        if (options == null) {
            return;
        }
        options.remove("legends");
        result.options = options.toString();
    }

    public int getDataproviderToModify() {
        return 57;
    }

    public List<Result> getLayersToModify(Connection conn) throws Exception {
        List<Result> layers = new ArrayList<>();
        // remove legends override from layers by "Tilastokeskus"
        final String sql = "SELECT id, options FROM oskari_maplayer where dataprovider_id = " + getDataproviderToModify();
        try(PreparedStatement statement = conn.prepareStatement(sql)) {
            try (ResultSet rs = statement.executeQuery()) {
                while(rs.next()) {
                    Result result = new Result();
                    result.id = rs.getInt("id");
                    result.options = rs.getString("options");
                    layers.add(result);
                }
            }
        }
        return layers;
    }

    private void saveChanges(Connection conn, List<Result> layers) throws SQLException {
        String sql = "UPDATE oskari_maplayer SET options = ? WHERE id = ?";
        try (PreparedStatement ps = conn.prepareStatement(sql)) {
            for (Result layer : layers) {
                ps.setString(1, layer.options);
                ps.setInt(2, layer.id);
                ps.addBatch();
            }
            ps.executeBatch();
        }
    }
}

Remove legend overrides from layers from Tilastokeskus


/*
 * Copyright 2016 Vladimir Kizelbashev
 *
 * 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.haulmont.testtask.app;

import com.haulmont.testtask.entity.Group;

import com.vaadin.data.util.converter.Converter;
import java.util.Locale;

/**
 * The class {@code GroupConverter} is a class to String-Group and Group-String conversion,
 * to display group data in a table cell.
 *
 * @version 1.0
 * @author Vladimir
 */
class GroupConverter implements Converter<String, Group> {

    /**
     * Method to convert a String to a Group
     * @param s The string contains a newline-separated fields in the following form:
     *          id \n number \n faculty. Can be null.
     * @param aClass The type of the return value.
     * @param locale The locale to use for conversion. Can be null.
     * @throws ConversionException
     */
    @Override
    public Group convertToModel(String s, Class<? extends Group> aClass, Locale locale) throws ConversionException {
        if (s == null) {
            return null;
        }
        String[] parts = s.split("\n");
        if (parts.length != 3) {
            throw new ConversionException("Can not convert String to Group: " + s);
        }
        Group group = new Group();
        try {
            group.setId(Long.valueOf(parts[0]));
            group.setNumber(Integer.valueOf(parts[1]));
            group.setFaculty(parts[2]);
        } catch (Exception e) {
            throw new ConversionException(e.getMessage());
        }
        return group;
    }

    @Override
    public String convertToPresentation(Group group, Class<? extends String> aClass, Locale locale) throws ConversionException {
        if (group != null) {
            return String.valueOf(group.getNumber()) + ", " + group.getFaculty();
        } else {
            return null;
        }
    }

    @Override
    public Class<Group> getModelType() {
        return Group.class;
    }

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

Add class to group model-presentation conversion


package leetcode.remove_nth_node_from_end_of_list;

import java.util.ArrayList;

import common.ListNode;

public class Solution {
	public ListNode removeNthFromEnd(ListNode head, int n) {
		if(head == null || n == 0){
			return head;
		}
		if(n == 1 && head.next == null) return null;
		int size = 0;
		ListNode cur = head;
		while(cur != null){
			cur = cur.next;
			size += 1;
		}
		n = size - n;
		if(n == 0){
			head = head.next;
		}else{
			cur = head;
			ListNode prev = null;
			while(n > 0){
				prev = cur;
				n--;
				cur = cur.next;
			}
			prev.next = cur.next;
		}
		return head;
	}

//	public static class ListNode {
//		int val;
//		ListNode next;
//		ListNode(int x) {
//			val = x;
//			next = null;
//		}
//		public void dump(){
//			ListNode cur = this;
//			while(cur != null){
//				System.err.println("val = " + cur.val);
//				cur = cur.next;
//			}
//			System.err.println("");
//		}
//	}

	public static void main(String[] args){
		final int N = 10;
//		Solution sol = new Solution();
		for(int i = 0; i <= N; i++){
			ArrayList<ListNode> ary = new ArrayList<ListNode>();
			for(int j = 0; j < N; j++){
				ary.add(new ListNode(j));
				if(j > 0) ary.get(j - 1).next = ary.get(j);
			}
//			ListNode head = sol.removeNthFromEnd(ary.get(0), i);
//			head.dump();
		}
	}
}

Add java solution for 19. Remove Nth Node From End of List


package org.concord.otrunk.util;

import org.concord.framework.otrunk.OTObjectService;
import org.concord.framework.otrunk.view.OTLabbookManager;
import org.concord.framework.otrunk.view.OTLabbookManagerProvider;
import org.concord.otrunk.util.OTLabbookBundle.ResourceSchema;

public class OTLabbookManagerProviderImpl
    implements OTLabbookManagerProvider
{
	private ResourceSchema resources;

	public OTLabbookManagerProviderImpl(OTLabbookBundle.ResourceSchema resources)
    {
	    this.resources = resources;
    }

	public OTLabbookManager getLabbookManager(OTObjectService objectService)
	{
        try {
        	OTLabbookBundle bundle = (OTLabbookBundle) objectService.getOTObject(resources.getGlobalId());
        	this.resources = bundle.resources;
    		return new OTLabbookManagerImpl(resources);
        } catch (Exception e) {
	        e.printStackTrace();
        }
        System.err.println("Cannot create OTLabbookBundle from object service");
        return null;
	}

}

Add OTLabbookManagerProvider and implementation, which provides a service which passes back a OTLabbookManager using the OTObjectService


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

import com.github.pedrovgs.linkedlist.ListNode;
import org.junit.Before;
import org.junit.Test;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;

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

  private PartitionList partitionList;

  @Before public void setUp() {
    partitionList = new PartitionList();
  }

  @Test(expected = IllegalArgumentException.class) public void shouldNotAcceptNullLists() {
    partitionList.split(null, 1);
  }

  @Test public void shouldNotSplitListIfXIsMinorThanEveryNode() {
    ListNode<Integer> list = createList(new int[] { 1, 2, 3 });

    ListNode<Integer> result = partitionList.split(list, 0);

    assertListContainsElements(new Integer[] { 3, 2, 1 }, result);
  }

  @Test public void shouldNotSplitListIfXIsGreaterThanEveryNode() {
    ListNode<Integer> list = createList(new int[] { 1, 2, 3 });

    ListNode<Integer> result = partitionList.split(list, 4);

    assertListContainsElements(new Integer[] { 3, 2, 1 }, result);
  }

  @Test public void shouldSplitListUsingX() {
    ListNode<Integer> list = createList(new int[] { 3, 1, 2 });

    ListNode<Integer> result = partitionList.split(list, 2);

    assertListContainsElements(new Integer[] { 1, 2, 3 }, result);
  }

  private ListNode<Integer> createList(int[] integers) {
    ListNode<Integer> head = new ListNode<Integer>(integers[0]);
    if (integers.length > 1) {
      ListNode<Integer> prevNode = head;
      for (int i = 1; i < integers.length; i++) {
        ListNode<Integer> currentNode = new ListNode<Integer>(integers[i]);
        prevNode.setNext(currentNode);
        prevNode = currentNode;
      }
    }
    return head;
  }

  private void assertListContainsElements(Integer[] integers, ListNode<Integer> head) {
    int arrayLength = integers.length;
    ListNode<Integer> currentNode = head;

    int i = 0;
    while (i < arrayLength) {
      assertEquals(integers[i], currentNode.getData());
      currentNode = currentNode.getNext();
      i++;
    }
    assertNull(currentNode);
  }
}

Add some tests to problem 60


package org.jboss.cx.remoting.core.util;

import java.net.URI;
import java.net.URISyntaxException;
import java.util.regex.Pattern;
import java.util.regex.Matcher;

/**
 *
 */
public final class ServiceURI {
    public static final String SCHEME = "jrs";

    private static final String FIRST_CHAR = "[$_a-zA-Z]";
    private static final String SUBSEQUENT_CHAR = "[-+$_a-zA-Z0-9]*";
    private static final String ID = FIRST_CHAR + SUBSEQUENT_CHAR;
    private static final String SEPARATOR = "[./]";

    private static final Pattern VALID_PATTERN = Pattern.compile("^(?:" + ID + "(?:" + SEPARATOR + ID + ")*)*$");

    private final URI uri;
    private final String serviceType;
    private final String groupName;
    private final String endpointName;

    public ServiceURI(final String str) throws URISyntaxException {
        this(new URI(str));
    }

    public ServiceURI(final URI uri) {
        this.uri = uri;
        if (! uri.getScheme().equals(SCHEME)) {
            throw new IllegalArgumentException("Invalid URI scheme for service");
        }
        final String ssp = uri.getSchemeSpecificPart();
        final int stcp = ssp.indexOf(':');
        if (stcp == -1) {
            serviceType = ssp;
            groupName = "";
            endpointName = "";
        } else {
            serviceType = ssp.substring(0, stcp).trim();
            final int gncp = ssp.indexOf(':', stcp + 1);
            if (gncp == -1) {
                groupName = ssp.substring(stcp + 1).trim();
                endpointName = "";
            } else {
                groupName = ssp.substring(stcp + 1, gncp).trim();
                // ignore everything after the last :
                final int encp = ssp.indexOf(':', gncp + 1);
                if (encp == -1) {
                    endpointName = ssp.substring(gncp + 1).trim();
                } else {
                    endpointName = ssp.substring(gncp + 1, encp).trim();
                }
            }
        }
        final Matcher matcher = VALID_PATTERN.matcher(serviceType);
        if (! matcher.matches()) {
            throw new IllegalArgumentException("Syntax error in service type URI part");
        }
        matcher.reset(groupName);
        if (! matcher.matches()) {
            throw new IllegalArgumentException("Syntax error in group name URI part");
        }
        matcher.reset(endpointName);
        if (! matcher.matches()) {
            throw new IllegalArgumentException("Syntax error in endpoint name URI part");
        }
    }

    public URI getUri() {
        return uri;
    }

    public String getServiceType() {
        return serviceType;
    }

    public String getGroupName() {
        return groupName;
    }

    public String getEndpointName() {
        return endpointName;
    }
}

Add service URI utility class


//        This file is part of the Yildiz-Online project, licenced under the MIT License
//        (MIT)
//
//        Copyright (c) 2016 Grégory Van den Borre
//
//        More infos available: http://yildiz.bitbucket.org
//
//        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 be.yildiz.module.graphic.ogre;

import be.yildiz.module.window.swt.SwtWindowEngine;

/**
 * @author Grégory Van den Borre
 */
public class OgreFactory {

    public static OgreGraphicEngine createOgreGraphic() {
        return new OgreGraphicEngine(new SwtWindowEngine());
    }
}

Add factory to build the engine.


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

/**
 * Given two integers passed as argument, can you write a function to determine the number of bits
 * required to convert integer A to integer B.
 *
 * @author Pedro Vicente Gómez Sánchez.
 */
public class BitsToTransform {

}

Add statement to problem 69


import java.util.*;
public class Solution {
    public List<List<Integer>> result = new ArrayList<List<Integer>>();
    public List<List<Integer>> subsets(int[] S) {
        Arrays.sort(S);
        List<Integer> valuelist = new ArrayList<Integer>();
        this.dfs(S, valuelist);
        return result;
    }

    public void dfs(int[] S, List<Integer> valuelist) {
        this.result.add(valuelist);
        if (S.length == 0) {
            return;
        }
        for (int i = 0; i < S.length; i++) {
            ArrayList<Integer> newList = new ArrayList<Integer>(valuelist);
            newList.add(S[i]);
            dfs(Arrays.copyOfRange(S, i+1, S.length), newList);
        }
    }
}

Revert "remove subsets for xu qian"


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

package com.pme.exe.res.vi;

import com.pme.exe.Bin;

public class StringTable extends VersionInfoBin {

  public StringTable(String name) {
    super(name, null, new VersionInfoFactory() {
      @Override
      public VersionInfoBin createChild(int index) {
        return new StringTableEntry();
      }
    });
  }

  public void setStringValue(String key, String value) {
    for (Bin bin : getMembers()) {
      if (bin.getName().equals(key)) {
        StringTableEntry entry = (StringTableEntry) bin;
        ((WChar) entry.getMember("Value")).setValue(value);
        ((Word) entry.getMember("wValueLength")).setValue(value.length());
        return;
      }
    }
    assert false: "Could not find string with key " + key;
  }
}

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

package com.pme.exe.res.vi;

import com.pme.exe.Bin;

public class StringTable extends VersionInfoBin {

  public StringTable(String name) {
    super(name, null, new VersionInfoFactory() {
      @Override
      public VersionInfoBin createChild(int index) {
        return new StringTableEntry();
      }
    });
  }

  public void setStringValue(String key, String value) {
    for (Bin bin : getMembers()) {
      if (bin.getName().equals(key)) {
        StringTableEntry entry = (StringTableEntry) bin;
        ((WChar) entry.getMember("Value")).setValue(value);
        ((Word) entry.getMember("wValueLength")).setValue(value.length() + 1);
        return;
      }
    }
    assert false: "Could not find string with key " + key;
  }
}

Correct length in exe resource string tables the change done by Matt Ellis (citizenmatt)


package com.coderevisited.arrays;

import java.io.BufferedWriter;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;

/**
 * 1. start from 0 to array.length -1;
 * 2. find first out of place element, i.e either positive at even index or negative at odd index
 * 3. find position of correct element, replace out of place element with correct element and shift array
 * 4. now out of place element will be 2 positions head
 */
public class RearrangePositivesAndNegative
{
    public static void main(String[] args)
    {

        PrintWriter pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
        int[] array = new int[]{-5, -2, 5, 2, 4, 7, 1, 8, 0, -8};
        rearrange(array);
        printArray(array, pw);
        pw.close();

    }

    private static void rearrange(int[] array)
    {
        int outOfPlace = -1;
        for (int i = 0; i < array.length; i++) {

            if (outOfPlace >= 0) {
                if (array[i] >= 0 && array[outOfPlace] < 0 || array[i] < 0 && array[outOfPlace] >= 0) {
                    rightRotate(array, outOfPlace, i);
                    if (i - outOfPlace > 2)
                        outOfPlace = outOfPlace + 2;
                    else
                        outOfPlace = -1;
                }
            }

            if (outOfPlace == -1) {
                if (array[i] >= 0 && ((i & 1) != 1) || array[i] < 0 && ((i & 1) == 1))
                    outOfPlace = i;
            }
        }

    }

    private static void rightRotate(int[] array, int i, int j)
    {
        int temp = array[j];
        System.arraycopy(array, i, array, i + 1, j - i);
        array[i] = temp;
    }

    private static void printArray(int[] array, PrintWriter pw)
    {
        for (int i : array) {
            pw.print(i + " ");
        }
        pw.println();
    }
}

Rearrange array in alternating positive & negative items with O(1) extra space


package org.jsmpp.util;

import static org.testng.Assert.*;
import org.jsmpp.bean.DeliveryReceipt;
import org.testng.annotations.Test;

/**
 * @author uudashr
 *
 */
public class DeliveryReceiptParserTest {
    private PDUDecomposer decomposer = new DefaultDecomposer();
    private static final String ORIGINAL_MESSAGE = "testing jsmpp bow";

    @Test
    public void parseTextWithLowerCase() {
        try {
            DeliveryReceipt delReceipt = decomposer.deliveryReceipt("id:0123456789 sub:001 dlvrd:001 submit date:200809011130 done date:200809011131 stat:DELIVRD err:000 text:" + ORIGINAL_MESSAGE);
            assertEquals(delReceipt.getText(), ORIGINAL_MESSAGE);
        } catch (InvalidDeliveryReceiptException e) {
            fail("Failed parsing delivery receipt:" + e.getMessage());
        }
    }

    @Test
    public void parsingTextWithUpperCase() {
        try {
            DeliveryReceipt delReceipt = decomposer.deliveryReceipt("id:0123456789 sub:001 dlvrd:001 submit date:200809011130 done date:200809011131 stat:DELIVRD err:000 Text:" + ORIGINAL_MESSAGE);
            assertEquals(delReceipt.getText(), ORIGINAL_MESSAGE);
        } catch (InvalidDeliveryReceiptException e) {
            fail("Failed parsing delivery receipt:" + e.getMessage());
        }
    }

    @Test
    public void parseWithNoTextAttribute() {
        try {
            DeliveryReceipt delReceipt = decomposer.deliveryReceipt("id:0123456789 sub:001 dlvrd:001 submit date:200809011130 done date:200809011131 stat:DELIVRD err:000 " + ORIGINAL_MESSAGE);
            assertEquals(delReceipt.getText(), null);
        } catch (InvalidDeliveryReceiptException e) {
            e.printStackTrace();
            fail("Failed parsing delivery receipt:" + e.getMessage());
        }
    }
}

Add delivery receipt test case


package pt.up.fe.sdis.proj1.utils;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.MulticastSocket;

import pt.up.fe.sdis.proj1.messages.Message;
import rx.Observable;
import rx.functions.Func1;
import rx.schedulers.Schedulers;
import rx.subjects.PublishSubject;

public class MulticastChannelMesssagePublisher extends Thread {
    private static final int MAX_UDP_SIZE = 65536;

    public MulticastChannelMesssagePublisher(String mCastAddr, int mCastPort) throws IOException {
        _mCastSocket = new MulticastSocket(mCastPort);
        _mCastSocket.joinGroup(InetAddress.getByName(mCastAddr));
    }

    public MulticastChannelMesssagePublisher(String mCastAddr, int mCastPort, int packetSize) throws IOException {
        _packetSize = packetSize;
        _mCastSocket = new MulticastSocket(mCastPort);
        _mCastSocket.joinGroup(InetAddress.getByName(mCastAddr));
    }

    @Override
    public void run() {
        byte[] buffer = new byte[_packetSize];
        DatagramPacket dp = new DatagramPacket(buffer, _packetSize);

        while (true) {
            try {
                _mCastSocket.receive(dp);
                _subject.onNext(dp.getData());
            } catch (IOException e) {
            }
        }
    }

    public Observable<Message> getObservable() {
        return _observable;
    }

    private PublishSubject<byte[]> _subject = PublishSubject.create();
    private Observable<Message> _observable = _subject
            .observeOn(Schedulers.io())
            .map(new Func1<byte[], Message>() {
                @Override
                public Message call(byte[] arg0) {
                    try {
                        return Message.fromByteArray(arg0);
                    } catch (IOException e) {
                        return null;
                    }
                }
            }).filter(new Func1<Message, Boolean>() {
                @Override
                public Boolean call(Message arg0) {
                    return arg0 != null;
                }
            });

    private MulticastSocket _mCastSocket;
    private int _packetSize = MAX_UDP_SIZE;
}

Implement MulticastChannelMessagePublisher class to handle Messages received via a multicast socket.


package org.opennms.core.test;

import java.util.Arrays;
import java.util.List;

import org.junit.Assert;

public abstract class OnmsAssert {

    public static void assertArrayEqualsIgnoreOrder(final Object[] a, final Object[] b) {
        final List<?> aList = Arrays.asList(a);
        final List<?> bList = Arrays.asList(b);
        Assert.assertTrue(aList.containsAll(bList) && bList.containsAll(aList));
    }

}

Add a utility method for asserting array equality regardless of order


package com.fuzz.indicator;

import android.database.DataSetObserver;
import android.view.ViewTreeObserver;

import com.fuzz.indicator.proxy.StateProxy;
import com.fuzz.indicator.proxy.UnavailableProxy;

import org.junit.Test;

import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.doCallRealMethod;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;

/**
 * Test of whether calls to {@link StateProxy#associateWith} are always mirrored by
 * calls to {@link StateProxy#disassociateFrom}.
 *
 * @author Philip Cohn-Cort (Fuzz)
 */
public class StateProxyBalancingTest {

    @Test
    public void associateThenDisassociateWithNoChanges() throws Exception {
        CutoutViewIndicator indicator = mock(CutoutViewIndicator.class);

        // Setup

        indicator.dataSetObserver = mock(DataSetObserver.class);
        indicator.stateProxy = new UnavailableProxy();
        ViewTreeObserver vtoMock = mock(ViewTreeObserver.class);

        when(indicator.getViewTreeObserver()).thenReturn(vtoMock);
        doCallRealMethod().when(indicator).setStateProxy(any(StateProxy.class));

        StateProxy proxyA = mock(StateProxy.class);
        when(proxyA.canObserve(any(DataSetObserver.class))).thenReturn(false);

        StateProxy proxyB = mock(StateProxy.class);
        when(proxyB.canObserve(any(DataSetObserver.class))).thenReturn(true);

        // The test

        indicator.setStateProxy(proxyA);

        verify(proxyA).canObserve(any(DataSetObserver.class));
        verify(proxyA, never()).associateWith(any(DataSetObserver.class));

        indicator.setStateProxy(proxyB);

        verify(proxyA, never()).disassociateFrom(any(DataSetObserver.class));

        verify(proxyB).canObserve(any(DataSetObserver.class));
        verify(proxyB).associateWith(any(DataSetObserver.class));
    }
}

Test whether StateProxies are associated and disassociated correctly


package com.eqot.xray;

import android.content.Intent;
import android.test.ServiceTestCase;

import org.junit.Test;

public class SampleAndroidServiceTest extends ServiceTestCase<SampleAndroidService> {
    public SampleAndroidServiceTest() {
        super(SampleAndroidService.class);
    }

    @Test
    public void testStartService() throws Exception {
        final Intent startIntent = new Intent();
        startIntent.setClass(getContext(), SampleAndroidService.class);
        startService(startIntent);

        final SampleAndroidService service = getService();
        assertNotNull(service);
    }
}

Add test for Android service


package info.u_team.u_team_core.container;

import info.u_team.u_team_core.inventory.UItemStackHandler;
import net.minecraftforge.items.*;

public class ItemSlot extends SlotItemHandler {

	private final IItemHandler itemHandler;
	private final int index;

	public ItemSlot(IItemHandler itemHandler, int index, int x, int y) {
		super(itemHandler, index, x, y);
		this.itemHandler = itemHandler;
		this.index = index;
	}

	@Override
	public void onSlotChanged() {
		if (itemHandler instanceof UItemStackHandler) {
			((UItemStackHandler) itemHandler).onContentsChanged(index);
		}
	}

}

Add item slot with the IItemHandler that calls the onSlotChanged method


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

package com.solsticesquared.schelling.task;

import com.solsticesquared.schelling.SchellingExplorer;
import sim.engine.SimState;
import sim.engine.Steppable;

/**
 * Represents a task, implemented as a {@link Steppable}, that determines
 * whether or not a simulation has been allowed to execute for more than an
 * arbitrary number of steps and, if so, forces it to stop.
 *
 *

 *     In addition, this task can also stop a simulation if the number of
 *     "unhappy" agents is zero.  Please note that this is disabled by
 *     default but can be activated via the user-interface options.
 *

 */
public class StopConditionTask implements Steppable {

    /**
     * The current number of executed steps.
     *
     *

     *     This is intentionally kept separate from MASON's internal schedule
     *     counter to avoid potential conflicts.
     *

     */
    private int internalCounter;

    @Override
    public void step(SimState simState) {
        final SchellingExplorer model = (SchellingExplorer)simState;

        // Increment the number of steps we've taken.
        this.internalCounter++;

        // Determine the status of both stopping conditions.
        final boolean mustStop =
                this.internalCounter >= model.getParameters().getMaximumSteps();
        final boolean shouldStop =
                model.getParameters().getStopOnEquilibrium()
                  && model.getMovementList().isEmpty();

        // Compare to the maximum number of steps allowed.
        if(mustStop || shouldStop) {
            // Force the simulation to stop.
            model.finish();
        }
    }
}

Add task that stops the simulation if conditions are met to do so.


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

import com.codeup.application.CategoriesConsole;
import com.codeup.movies.catalog.AddCategory;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;

import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;

@RunWith(MockitoJUnitRunner.class)
public class AddCategoryActionTest {
    @Test
    public void it_adds_a_new_category() {
        String newCategory = "action";
        when(console.askForCategoryName()).thenReturn(newCategory);

        action.execute();

        verify(addCategory).withName(newCategory);
    }

    @Before
    public void configureAction() {
        action = new AddCategoryAction(addCategory, console);
    }

    private AddCategoryAction action;

    @Mock
    private AddCategory addCategory;

    @Mock
    private CategoriesConsole console;
}

Add tests for rAddCategoryAction class.


/**
 *
 */
package mathsquared.resultswizard2;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;

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

import org.junit.Test;

/**
 * @author MathSquared
 *
 */
public class AdditiveMapUtilsTest {

    /**
     * Test method for {@link mathsquared.resultswizard2.AdditiveMapUtils#addNumber(java.util.Map, java.lang.Object, int)}.
     */
    @Test
    public void testAddNumberMapOfQsuperKIntegerKInt () {
        Map<String, Integer> one = new HashMap<String, Integer>();
        one.put("a", 1);
        one.put("b", 2);

        Map<String, Integer> first = new HashMap<String, Integer>();
        first.put("a", 1);
        first.put("b", 4);

        Map<String, Integer> second = new HashMap<String, Integer>();
        second.put("a", 1);
        second.put("b", 4);
        second.put("c", 3);

        AdditiveMapUtils.addNumber(one, "b", 2);
        assertEquals("Simple addition", one, first);

        AdditiveMapUtils.addNumber(one, "c", 3);
        assertEquals("Pre-existing null", one, second);
    }

    /**
     * Test method for {@link mathsquared.resultswizard2.AdditiveMapUtils#addNumber(java.util.Map, java.lang.Object, mathsquared.resultswizard2.Fraction)}.
     */
    @Test
    public void testAddNumberMapOfQsuperKFractionKFraction () {
        Map<String, Fraction> one = new HashMap<String, Fraction>();
        one.put("a", new Fraction(1, 2));
        one.put("b", new Fraction(5, 3));

        Map<String, Fraction> first = new HashMap<String, Fraction>();
        first.put("a", new Fraction(1, 2));
        first.put("b", new Fraction(10, 3));

        Map<String, Fraction> second = new HashMap<String, Fraction>();
        second.put("a", new Fraction(1, 2));
        second.put("b", new Fraction(10, 3));
        second.put("c", new Fraction(4, 7));

        AdditiveMapUtils.addNumber(one, "b", new Fraction(5, 3));
        assertEquals("Simple addition", one, first);

        AdditiveMapUtils.addNumber(one, "c", new Fraction(4, 7));
        assertEquals("Pre-existing null", one, second);
    }

    /**
     * Test method for {@link mathsquared.resultswizard2.AdditiveMapUtils#addAllNumbers(java.util.Map, java.util.Map)}.
     */
    @Test
    public void testAddAllNumbersMapOfQsuperKIntegerMapOfKInteger () {
        fail("Not yet implemented");
    }

    /**
     * Test method for {@link mathsquared.resultswizard2.AdditiveMapUtils#addAllNumbers(java.util.Map, java.util.Map, boolean)}.
     */
    @Test
    public void testAddAllNumbersMapOfQsuperKFractionMapOfKFractionBoolean () {
        fail("Not yet implemented");
    }

}

Add AdditiveMapUtils and tests: addNumber(...)


package com.tngtech.jgiven.impl;

public class Timer {
  private long startNanoseconds;
  private long elapsedTime = -1L;

  public Timer() {
    startNanoseconds = System.nanoTime();
  }

  public void reset() {
    elapsedTime = -1L;
    startNanoseconds = System.nanoTime();
  }

  public long stop() {
    if (elapsedTime != -1L)
      return elapsedTime;
    elapsedTime = System.nanoTime() - startNanoseconds;
    return elapsedTime;
  }
}

Add timer class for tests


/*
 * Copyright 2017 haeun kim
 *
 * 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 algorithm.boj;

import java.io.*;

/**
 * Created by haeun on 2017-10-06
 * Site       : https://www.acmicpc.net/problem/10828
 */

public class Boj10828 {
    String[] items = new String[10000];

    int top = -1;

    public void push(String item) {
        items[++top] = item;
    }

    public String pop() {
        if (empty()==1){
            return ""+ -1;
        }
        return items[top--];
    }

    public String peek() {
        if(empty()==1){
            return ""+ -1;
        }
        return items[top];
    }

    public int size() {
        return top+1;
    }

    public int empty() {
        if(top == -1){
            return  1;
        }else{
            return  0;
        }
    }
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        int n = Integer.parseInt(br.readLine());
        Boj10828 obj = new Boj10828();
        for(int i=0; i<n; i++){
            String[] comm = br.readLine().split(" ");
            if(comm[0].equals("push")){
                obj.push(comm[1]);
            }else if(comm[0].equals("pop")){
                System.out.println(obj.pop());
            }else if(comm[0].equals("size")){
                System.out.println(obj.size());
            }else if(comm[0].equals("empty")){
                System.out.println(obj.empty());
            }else{
                System.out.println(obj.peek());
            }
        }
    }

}

Solve No.10828 from Baekjoon Online Judge


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

/**
 * Check for any retrotransposed transcripts that have translations (shouldn't be any).
 */

public class Retrotransposed extends SingleDatabaseTestCase {

	/**
	 * Constructor.
	 */
	public Retrotransposed() {

		addToGroup("post_genebuild");
		addToGroup("release");
		setDescription("Check for any retrotransposed transcripts that have translations (shouldn't be any).");

	}

	/**
	 * 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();
		int rows = getRowCount(con, "SELECT COUNT(*) FROM transcript t, translation tln WHERE t.transcript_id=tln.transcript_id AND t.biotype = 'retrotransposed'");

		if (rows > 0) {

			ReportManager.problem(this, con, rows + " transcripts with biotype 'retrotransposed' have translations.");
			result = false;

		} else {

			ReportManager.correct(this, con, "No retrotransposed transcripts have translations.");

		}

		return result;

	} // run

} // Retrotransposed


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

package com.solsticesquared.schelling;

import sim.util.IntBag;

/**
 * Represents a collection of reusable objects that are intended to be shared
 * across a single simulation thread.
 */
public class ComputeCache {

    /**
     * A collection of default values for a {@code ComputeCache}.
     */
    public static final class Defaults {

        /**
         * The default initial capacity to use.
         *
         * <p>
         *     This corresponds to a typical "nearest neighbor" grid search with
         *     a Moore distance of one without including the search origin.
         * </p>
         */
        public static final int InitialCapacity = 8;

        /**
         * Constructor (private).
         */
        private Defaults() {
        }
    }

    /**
     * The x-axis values that correspond - in order - to the grid cells returned
     * from a nearest-neighbor search query.
     */
    public final IntBag xLocations;

    /**
     * The x-axis values that correspond - in order - to the grid cells returned
     * from a nearest-neighbor search query.
     */
    public final IntBag yLocations;

    /**
     * Constructor.
     */
    public ComputeCache() {
        this(Defaults.InitialCapacity);
    }

    /**
     * Constructor.
     *
     * @param initialCapacity
     *        The number of elements to reserve.
     * @throws IllegalArgumentException
     *         If {@code initialCapacity} is less than zero.
     */
    public ComputeCache(final int initialCapacity) {
        if(initialCapacity < 0) {
            throw new IllegalArgumentException("initial capacity must be " +
                                               "positive!");
        }

        this.xLocations = new IntBag(initialCapacity);
        this.yLocations = new IntBag(initialCapacity);
    }
}

Add object to represent a cache of reusable, thread-local data.


/*
* I don't know what to do with this.
*/

package org.app.material.annotation;

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

@Retention(RetentionPolicy.CLASS)
@Target({
        ElementType.ANNOTATION_TYPE,
        ElementType.CONSTRUCTOR,
        ElementType.FIELD,
        ElementType.METHOD,
        ElementType.TYPE
})
@Documented
@Experimental
public @interface Experimental {

    String task() default "";

    @Priority String priority() default "";
}

Create new annotation for experimental classes and methods


package com.epam.ta.reportportal.ws.model;

import com.fasterxml.jackson.annotation.JsonProperty;

import javax.validation.constraints.NotNull;
import java.util.List;

/**
 * @author Ivan Budayeu
 */
public class DeleteBulkRQ {

	@NotNull
	@JsonProperty(value = "ids")
	private List<Long> ids;

	public DeleteBulkRQ() {
	}

	public List<Long> getIds() {
		return ids;
	}

	public void setIds(List<Long> ids) {
		this.ids = ids;
	}

	@Override
	public String toString() {
		return "DeleteBulkRQ{" + "ids=" + ids + '}';
	}
}

Delete bulk request entity impl


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

import nom.bdezonia.zorbage.sampling.IntegerIndex;
import nom.bdezonia.zorbage.type.algebra.Group;
import nom.bdezonia.zorbage.type.data.universal.PrimitiveConversion;
import nom.bdezonia.zorbage.type.data.universal.PrimitiveConverter;
import nom.bdezonia.zorbage.type.storage.linear.LinearStorage;

/**
 *
 * @author Barry DeZonia
 *
 */
public class DataConvert {

	// do not instantiate

	private DataConvert() {}

	/**
	 * DataConvert.compute()
	 *
	 * @param group1
	 * @param group2
	 * @param input
	 * @param output
	 */
	public static <T extends Group<T,V>, U extends Group<U,W>, V extends PrimitiveConversion, W extends PrimitiveConversion>
		void compute(T group1, U group2, LinearStorage<?,V> input, LinearStorage<?,W> output)
	{
		// assumptions: output size is >= input size

		V from = group1.construct();
		W to = group2.construct();
		int numD = Math.max(from.numDimensions(), to.numDimensions());
		IntegerIndex tmp1 = new IntegerIndex(numD);
		IntegerIndex tmp2 = new IntegerIndex(numD);
		IntegerIndex tmp3 = new IntegerIndex(numD);
		for (long i = 0; i < input.size(); i++) {
			input.get(i, from);
			PrimitiveConverter.convert(tmp1, tmp2, tmp3, from, to);
			output.set(i, to);
		}
	}
}

Add data conversion algorithm that transmutes lists of class data


/*
 Copyright 2006 Paul Zepernick

 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at

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

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

import net.sf.pzfilereader.util.ParserUtils;
import junit.framework.TestCase;

/**
 * Tests the functionality of the left trim in the ParserUtils
 *
 * @author paul zepernick
 */
public class LTrimTest extends TestCase{

    /**
     * Make sure all spaces are properly removed from the front of the String
     *
     */
    public void testTrimLeadingSpaces(){
        final String testS = "     RemoveAllSpacesFromMe";
        assertEquals(true , ParserUtils.lTrim(testS).indexOf(" ") == -1);
    }

    /**
     * Make sure all spaces are properly removed from the front of the String
     * leaving the trailing spaces at the end
     *
     */
    public void testTrimLeadingSpacesWithTrailingSpaces(){
        final String testS = "     RemoveAllSpacesFromMe     ";
        final String tResult = ParserUtils.lTrim(testS);
        assertEquals(true , !tResult.startsWith(" ") && tResult.endsWith(" "));
    }

    /**
     * Make sure all TAB chars are properly removed from the front of the String
     * leaving the trailing spaces at the end
     *
     */
    public void testTrimLeadingTabs(){
        final String testS = "\t\t\tRemoveAllSpacesFromMe     ";
        final String tResult = ParserUtils.lTrim(testS);
        assertEquals(true , !tResult.startsWith("\t") && tResult.endsWith(" "));
    }

    /**
     * Make sure all TAB chars are properly removed from the front of the String
     * leaving the trailing spaces at the end
     *
     */
    public void testKeepLeadingTabs(){
        final String testS = "     \t\t\tRemoveAllSpacesFromMe     ";
        final String tResult = ParserUtils.lTrimKeepTabs(testS);
        assertEquals(true , !tResult.startsWith("\t") && tResult.endsWith(" "));
    }

    public static void main(final String[] args) {
        junit.textui.TestRunner.run(LTrimTest.class);
    }
}

Test cases for lTrim and lTrimKeepTabs


package com.daviancorp.android.data.database;

public class QueryHelper {
	public boolean Distinct;
	public String Table;
	public String[] Columns;
	public String Selection;
	public String[] SelectionArgs;
	public String GroupBy;
	public String Having;
	public String OrderBy;
	public String Limit;

	public QueryHelper()
	{
		Distinct = false;
		Table = null;
		Columns = null;
		Selection = null;
		SelectionArgs = null;
		GroupBy = null;
		Having = null;
		OrderBy = null;
		Limit = null;
	}

	public QueryHelper(boolean distinct, String table, String[] columns,
			String selection, String[] selectionArgs, String groupBy,
			String having, String orderBy, String limit) {
		Distinct = distinct;
		Table = table;
		Columns = columns;
		Selection = selection;
		SelectionArgs = selectionArgs;
		GroupBy = groupBy;
		Having = having;
		OrderBy = orderBy;
		Limit = limit;
	}
}

Fix race conditions in the database helper. Fixes G Rank Tab crash.


package main.algorithm.leetcode;

import org.junit.Test;

/**
 * Title : main.algorithm.leetcode

 * Company : 北京华宇元典信息服务有限公司

 * Description :
 *
 *
 * @author chile
 * @version 1.0
 * @date 2019/4/29 9:49
 */
public class RemoveDuplicatesfromSortedArray {

    class Solution {
        public int removeDuplicates(int[] nums) {
            if (nums.length == 0) {
                return 0;
            }

            int i = 0;
            for (int j = 1; j < nums.length; j++) {
                if (nums[j] > nums[i]) {
                    nums[++i] = nums[j];
                }
            }

            return i + 1;
        }
    }

    @Test
    public void test1() {
        int[] nums = {1, 2};
        assert new Solution().removeDuplicates(nums) == 2;
        for (int i : nums) {
            System.out.print(i);
        }
    }

    @Test
    public void test2() {
        int[] nums = {1, 1, 2, 2, 4, 5, 6, 6};
        assert new Solution().removeDuplicates(nums) == 5;
        for (int i : nums) {
            System.out.print(i);
        }
    }

}

Remove Duplicates from Sorted Array


package org.realityforge.arez.annotations;

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

/**
 * Marks classes that contain Observable properties.
 *
 *
The annotation controls the way that contained observables are named. If names are
 * not enabled in the system, this annotation has no effect.

 *
 *
The {@link #name()} value indicates the type name for all instances of this object.
 * If not specified it will default to the SimpleName of the class. i.e. The class
 * <tt>com.biz.models.MyModel</tt> will default to a name of "MyModel".

 *
 *
The {@link #singleton()} indicates whether there are expected to be multiple
 * instances of this type. If the method returns true then the debug name of
 * contained observables will not include the "id" of the instance.

 *
 *
The name of any observables contained within the container follows the pattern
 * "[Container.name].[Container.id].[Observable.name]" for non singletons and
 * "[Container.name].[Observable.name]" for singletons.

 */
@Retention( RetentionPolicy.RUNTIME )
@Target( ElementType.TYPE )
public @interface Container
{
  /**
   * Return the name of the type.
   *
   * @return the name of the type.
   */
  String name() default "";

  /**
   * Return true if the container can only have a single instance, false otherwise.
   *
   * @return true if the container can only have a single instance, false otherwise.
   */
  boolean singleton() default false;
}

Add annotation controlling debug naming of nexted observables and actions


package no.ssb.vtl.script.operations;

import com.google.common.collect.ImmutableMap;
import no.ssb.vtl.model.Component;
import no.ssb.vtl.model.DataPoint;
import no.ssb.vtl.model.DataStructure;
import no.ssb.vtl.model.Dataset;
import no.ssb.vtl.model.VTLBoolean;
import org.junit.Before;
import org.junit.Test;

import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Stream;

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

public class FilterOperationTest {

    private Dataset dataset;

    @Before
    public void setUp() throws Exception {
        DataStructure structure = DataStructure.builder()
                .put("id", Component.Role.IDENTIFIER, String.class)
                .build();

        DataPoint dataPoint = structure.wrap(ImmutableMap.of("id", "idValue"));
        List<DataPoint> dataPoints = Collections.singletonList(dataPoint);

        dataset = new TestableDataset(structure, dataPoints);
    }

    @Test
    public void testPredicateReturnsNull() throws Exception {

        FilterOperation resultBooleanNull = new FilterOperation(dataset, dp -> VTLBoolean.of(null));
        assertThat(resultBooleanNull.getData()).isEmpty();

        FilterOperation resultNull = new FilterOperation(dataset, dp -> null);
        assertThat(resultNull.getData()).isEmpty();
    }

    @Test
    public void testPredicateReturnsFalse() throws Exception {

        FilterOperation result = new FilterOperation(dataset, dp -> VTLBoolean.of(Boolean.FALSE));
        assertThat(result.getData()).isEmpty();
    }

    @Test
    public void testPredicateReturnsTrue() throws Exception {

        FilterOperation result = new FilterOperation(dataset, dp -> VTLBoolean.of(Boolean.TRUE));
        assertThat(result.getData()).isNotEmpty();
    }

    private static class TestableDataset implements Dataset {

        private final List<DataPoint> dataPoints;
        private final DataStructure structure;

        private TestableDataset(DataStructure structure, List<DataPoint> dataPoints) {
            this.dataPoints = dataPoints;
            this.structure = structure;
        }

        @Override
        public Stream<DataPoint> getData() {
            return dataPoints.stream();
        }

        @Override
        public Optional<Map<String, Integer>> getDistinctValuesCount() {
            return Optional.empty();
        }

        @Override
        public Optional<Long> getSize() {
            return Optional.of((long) dataPoints.size());
        }

        @Override
        public DataStructure getDataStructure() {
            return structure;
        }
    }
}

Add a simple test for the FilterOperation that check that null values are handled as false


package com.github.ansell.csvmap;

import static org.junit.Assert.*;

import java.util.List;

import javax.script.Bindings;
import javax.script.Compilable;
import javax.script.CompiledScript;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineFactory;
import javax.script.ScriptEngineManager;

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

public class ScriptEngineTest {

	private static final ScriptEngineManager SCRIPT_MANAGER = new ScriptEngineManager();

	// Uncomment the following to debug which script engines are available on
	// the classpath
	static {
		List<ScriptEngineFactory> factories = SCRIPT_MANAGER.getEngineFactories();

		System.out.println("Installed script engines:");

		for (ScriptEngineFactory nextFactory : factories) {
			System.out.println(nextFactory.getEngineName());
		}
	}

	private ScriptEngine scriptEngine;

	@Before
	public void setUp() throws Exception {
		scriptEngine = SCRIPT_MANAGER.getEngineByName("lua");
	}

	@After
	public void tearDown() throws Exception {
	}

	@Test
	public final void test() throws Exception {
		String csvMapperScript = "mapFunction = function(inputHeaders, inputField, inputValue, outputField, line) return inputValue end";
		String simpleScript = "return inputValue";
		CompiledScript compiledScript = (CompiledScript) ((Compilable) scriptEngine).compile(simpleScript);
		Bindings bindings = scriptEngine.createBindings();
		// inputHeaders, inputField, inputValue, outputField, line
		bindings.put("inputHeaders", "");
		bindings.put("inputField", "");
		bindings.put("inputValue", "testreturnvalue");
		bindings.put("outputField", "");
		bindings.put("line", "");
		String result = (String) compiledScript.eval(bindings);
		System.out.println(result);
		assertEquals("testreturnvalue", result);
	}

}

Add test for the way the Lua functionality should work


package info.u_team.u_team_core.intern.loot;

import com.google.gson.*;

import info.u_team.u_team_core.UCoreMain;
import info.u_team.u_team_core.tileentity.UTileEntity;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.CompoundNBT;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.ResourceLocation;
import net.minecraft.world.storage.loot.*;
import net.minecraft.world.storage.loot.conditions.ILootCondition;

public class SetTileEntityNBTLootFunction extends LootFunction {

	private SetTileEntityNBTLootFunction(ILootCondition[] conditions) {
		super(conditions);
	}

	public ItemStack doApply(ItemStack stack, LootContext context) {
		if (context.has(LootParameters.BLOCK_ENTITY)) {
			final CompoundNBT compound = new CompoundNBT();
			final TileEntity tileEntity = context.get(LootParameters.BLOCK_ENTITY);
			if (tileEntity instanceof UTileEntity) {
				((UTileEntity) tileEntity).writeNBT(compound);
			} else {
				tileEntity.write(compound);
			}
			if (!compound.isEmpty()) {
				stack.setTagInfo("BlockEntityTag", compound);
			}
		}
		return stack;
	}

	public static LootFunction.Builder<?> builder() {
		return builder((conditions) -> new SetTileEntityNBTLootFunction(conditions));
	}

	public static class Serializer extends LootFunction.Serializer<SetTileEntityNBTLootFunction> {

		public Serializer() {
			super(new ResourceLocation(UCoreMain.MODID, "set_tileentity_nbt"), SetTileEntityNBTLootFunction.class);
		}

		@Override
		public SetTileEntityNBTLootFunction deserialize(JsonObject object, JsonDeserializationContext deserializationContext, ILootCondition[] conditions) {
			return new SetTileEntityNBTLootFunction(conditions);
		}
	}
}

Add set tile entity nbt loot function


package com.siirush.localwiki.search.annotation;

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

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

@Target({ METHOD }) @Retention(RUNTIME)
public @interface IndexAfter {}

Add method annotation to allow on demand indexing.


package uk.ac.ebi.quickgo.annotation.model;

/**
 * @author Tony Wardell
 * Date: 24/05/2016
 * Time: 17:19
 * Created with IntelliJ IDEA.
 */
public interface FilterModifier {

    String[] modify(String[] original);
}

Define how filter arguments will be modified.


/*
 * Copyright 2022 Jim Voris.
 *
 * 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.qvcsos.server;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * A simple test to backup the database using the pg_dump tool.
 *
 * @author Jim Voris.
 */
public class BackupDatabaseTest {
    private static final Logger LOGGER = LoggerFactory.getLogger(BackupDatabaseTest.class);

    /**
     * Backup the database.
     */
    @Test
    public void testBackupDatabase() {
        SimpleDateFormat dateFormatter = new SimpleDateFormat("yyyy.MM.dd-HH.mm.ss");
        Date now = new Date();
        String dateString = dateFormatter.format(now);
        String host = "10.0.1.3";
        String port = "5432";
        String userDir = System.getProperty("user.home");
        try {
            String execString = String.format("pg_dump --file %s/tmp/qvcsos_db_backup-%s --host %s --port %s --username postgres --no-password --verbose --role qvcsos410prod --format=p --encoding UTF8 qvcsos410prod",
                    userDir, dateString, host, port);
            Process p = Runtime.getRuntime().exec(execString);

            try ( BufferedReader in = new BufferedReader(new InputStreamReader(p.getErrorStream()))) {
                String line;
                while ((line = in.readLine()) != null) {
                    System.out.println(line);
                }
            }
            p.waitFor();
            LOGGER.info("Backup database process exit value: [{}]", p.exitValue());
        } catch (IOException | InterruptedException ex) {
            LOGGER.warn(ex.getLocalizedMessage(), ex);
        }
    }

}

Add unit test to backup qvcsos postgres database.


package ru.stqa.training.selenium;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.WebDriverWait;

import java.util.concurrent.TimeUnit;

import static org.openqa.selenium.support.ui.ExpectedConditions.titleIs;

public class LoginTest {

  public WebDriver driver;
  public WebDriverWait wait;

  @Before
  public void start() {
    driver = new ChromeDriver();
    driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
    wait = new WebDriverWait(driver, 10);
  }

  @Test
  public void loginTest() {
    driver.navigate().to("http://localhost/litecart/admin/");
    driver.findElement(By.name("username")).sendKeys("admin");
    driver.findElement(By.name("password")).sendKeys("admin");
    driver.findElement(By.name("login")).click();
    wait.until(titleIs("My Store"));
  }

  @After
  public void stop() {
    driver.quit();
    driver = null;
  }
}

Test for admin login for lifecart app is created


package io.tonny.regitry;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer;

@SpringBootApplication
@EnableEurekaServer
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

Change pom to use log4j2 and add registry project.


package leetcode.binary_tree_level_order_traversal;

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

import common.TreeNode;

public class Solution {
	public ArrayList<ArrayList<Integer>> levelOrder(TreeNode root) {
		Queue<MyNode> queue = new LinkedList<MyNode>();
		ArrayList<ArrayList<Integer>> ans = new ArrayList<ArrayList<Integer>>();
		if(root == null) return ans;
		queue.offer(new MyNode(root, 0));
		while(!queue.isEmpty()){
			MyNode myNode = queue.remove();
			TreeNode tn = myNode.node;
			ArrayList<Integer> lvl = null;
			if(ans.size() <= myNode.level){
				lvl = new ArrayList<Integer>();
				ans.add(lvl);
			}else{
				lvl = ans.get(myNode.level);
			}
			lvl.add(tn.val);
			if(tn.left != null) queue.offer(new MyNode(tn.left, myNode.level + 1));
			if(tn.right != null) queue.offer(new MyNode(tn.right, myNode.level + 1));
		}
		return ans;
	}
	public static class MyNode{
		TreeNode node;
		int level;
		public MyNode(TreeNode node, int level){
			this.node = node;
			this.level = level;
		}
	}

	public static void main(String[] args){
		final int N = 15;
		final int R = 5;
		ArrayList<TreeNode> nodes = new ArrayList<TreeNode>();
		for(int i = 0; i < N; i++){
			nodes.add(new TreeNode(i));
		}
		Random r = new Random();
		for(int i = 0; i < N; i++){
			if(i * 2 + 1 < N){
				nodes.get(i).left = nodes.get(i * 2 + 1);
			}
			if(i * 2 + 2 < N){
				nodes.get(i).right = nodes.get(i * 2 + 2);
			}
		}
		for(int i = 0; i < R; i++){
			int ran = r.nextInt(N);
			System.err.println("ran:" + ran);
			nodes.get(ran).left = null;
		}

		for(ArrayList<Integer> row : new Solution().levelOrder(nodes.get(0))){
			for(int x : row){
				System.err.print(x + ", ");
			}
			System.err.println("");
		}
	}
}

Add java solution for 102. Binary Tree Level Order Traversal


/*
 * Copyright (c) 2015-present, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 */

package com.facebook.common.media;

import android.webkit.MimeTypeMap;

import com.facebook.testing.robolectric.v2.WithTestDefaultsRunner;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.Robolectric;
import org.robolectric.shadows.ShadowMimeTypeMap;

import static org.fest.assertions.api.Assertions.assertThat;

@RunWith(WithTestDefaultsRunner.class)
public class MediaUtilsTest {

  @Test
  public void testIsPhotoMimeTypeNull() {
    assertThat(MediaUtils.isPhoto(null)).isFalse();
  }

  @Test
  public void testIsPhotoMimeTypeImage() {
    assertThat(MediaUtils.isPhoto("image/jpg")).isTrue();
  }

  @Test
  public void testIsPhotoMimeTypeVideo() {
    assertThat(MediaUtils.isPhoto("video/mp4")).isFalse();
  }

  @Test
  public void testIsVideoMimeTypeNull() {
    assertThat(MediaUtils.isVideo(null)).isFalse();
  }

  @Test
  public void testIsVideoMimeTypeImage() {
    assertThat(MediaUtils.isVideo("image/jpg")).isFalse();
  }

  @Test
  public void testIsVideoMimeTypeVideo() {
    assertThat(MediaUtils.isVideo("video/mp4")).isTrue();
  }

  @Test
  public void testExtractMimeNoFileExtension() {
    String path = "file/with/no/extension";
    assertThat(MediaUtils.extractMime(path)).isNull();
  }

  @Test
  public void testExtractMimeNativelySupportedFileExtension() {
    ShadowMimeTypeMap mimeTypeMap = Robolectric.shadowOf(MimeTypeMap.getSingleton());
    mimeTypeMap.addExtensionMimeTypMapping("jpg", "image/jpg");

    String path = "file/with/natively/supported/extension.jpg";
    assertThat(MediaUtils.extractMime(path)).isEqualTo("image/jpg");
  }

  @Test
  public void testExtractMimeNonNativelySupportedFileExtension() {
    String path = "file/with/non/natively/supported/extension.mkv";
    assertThat(MediaUtils.extractMime(path)).isEqualTo("video/x-matroska");
  }

  @Test
  public void testExtractMimeUnsupportedFileExtension() {
    String path = "file/with/unsupported/extension.zip";
    assertThat(MediaUtils.extractMime(path)).isNull();
  }

  @Test
   public void testIsNonNativeSupportedMimeTypeNative() {
    assertThat(MediaUtils.isNonNativeSupportedMimeType("image/jpg")).isFalse();
  }

  @Test
  public void testIsNonNativeSupportedMimeTypeNonNative() {
    assertThat(MediaUtils.isNonNativeSupportedMimeType("video/x-matroska")).isTrue();
  }
}

Add unit tests for MediaUtils


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

package ticwear.design.app;

import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnDismissListener;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;

/**
 * Create some common ticwear dialogs.
 *
 * Created by tankery on 08/03/2017.
 */

public class TicwearDialogs {

    @NonNull
    public static AlertDialog permissionRequestDialog(@NonNull Context context,
                                                      @Nullable String message,
                                                      @Nullable final Runnable positiveAction) {
        return permissionRequestDialog(context, message, positiveAction, null);
    }

    @NonNull
    public static AlertDialog permissionRequestDialog(@NonNull Context context,
                                                      @Nullable String message,
                                                      @Nullable final Runnable positiveAction,
                                                      @Nullable final Runnable negativeAction) {
        return permissionRequestDialog(context, message, positiveAction, negativeAction, null);
    }

    @NonNull
    public static AlertDialog permissionRequestDialog(@NonNull Context context,
                                                      @Nullable String message,
                                                      @Nullable final Runnable positiveAction,
                                                      @Nullable final Runnable negativeAction,
                                                      @Nullable final Runnable cancelAction) {
        class ActionStatus {
            boolean hasAction = false;
        }

        final ActionStatus actionStatus = new ActionStatus();

        return new AlertDialog.Builder(context)
                .setMessage(message)
                .setPositiveButtonIcon(ticwear.design.R.drawable.tic_ic_btn_ok,
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                actionStatus.hasAction = true;
                                dialog.dismiss();
                                if (positiveAction != null) {
                                    positiveAction.run();
                                }
                            }
                        })
                .setNegativeButtonIcon(ticwear.design.R.drawable.tic_ic_btn_cancel,
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                actionStatus.hasAction = true;
                                dialog.dismiss();
                                if (negativeAction != null) {
                                    negativeAction.run();
                                }
                            }
                        })
                .setOnDismissListener(new OnDismissListener() {
                    @Override
                    public void onDismiss(DialogInterface dialogInterface) {
                        // If dismiss with no user action, we know the user has cancel the dialog.
                        if (!actionStatus.hasAction && cancelAction != null) {
                            cancelAction.run();
                        }
                    }
                })
                .setDelayConfirmAction(DialogInterface.BUTTON_POSITIVE, 5000)
                .create();
    }

}

Unify Permission request rationale dialog.


package jenkins.plugins.git.traits;

import hudson.model.TaskListener;
import jenkins.plugins.git.GitSCMSourceContext;
import jenkins.scm.api.SCMHeadObserver;
import jenkins.scm.api.SCMSource;
import jenkins.scm.api.SCMSourceCriteria;
import jenkins.scm.api.trait.SCMSourceContext;
import jenkins.scm.api.trait.SCMSourceRequest;

import static org.junit.Assert.*;
import static org.hamcrest.Matchers.*;
import org.junit.Test;
import org.jvnet.hudson.test.Issue;

/**
 * Test for JENKINS-57683 - Class cast exception when an SCMSource or
 * SCMSourceContext was passed that was not a GitSCMSource.
 *
 * @author Mark Waite
 */
public class PruneStaleBranchTraitTest {

    public PruneStaleBranchTraitTest() {
    }

    @Test
    public void testDecorateContextWithGitSCMSourceContent() {
        GitSCMSourceContext context = new GitSCMSourceContext(null, null);
        assertThat(context.pruneRefs(), is(false));
        PruneStaleBranchTrait pruneStaleBranchTrait = new PruneStaleBranchTrait();
        pruneStaleBranchTrait.decorateContext(context);
        assertThat(context.pruneRefs(), is(true));
    }

    @Test
    @Issue("JENKINS-57683")
    public void testDecorateContextWithNonGitSCMSourceContent() {
        SCMSourceContext context = new FakeSCMSourceContext(null, null);
        PruneStaleBranchTrait pruneStaleBranchTrait = new PruneStaleBranchTrait();
        pruneStaleBranchTrait.decorateContext(context);
        /* JENKINS-57683 would cause this test to throw an exception */
    }

    private static class FakeSCMSourceContext extends SCMSourceContext {

        public FakeSCMSourceContext(SCMSourceCriteria scmsc, SCMHeadObserver scmho) {
            super(scmsc, scmho);
        }

        @Override
        public SCMSourceRequest newRequest(SCMSource scms, TaskListener tl) {
            throw new UnsupportedOperationException("Not supported yet.");
        }
    }
}

Test for PruneStaleBranchTrait class cast exception


/* 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 static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;

import org.junit.Test;
import org.sablecc.sablecc.exception.InternalException;

public class InternalExceptionTest {

    @Test
    @SuppressWarnings("unused")
    public void testInternalExceptionString() {

        // Initializing a good internal exception.
        InternalException goodInternalException = new InternalException(
                "Not null");

        // Testing no thrown exception when the message is not null.
        try {
            goodInternalException = new InternalException("Valid message");
        }
        catch (InternalException e) {
            fail("InternalException not expected here.");
        }

        // Testing thrown exception when the message is null.
        try {
            InternalException nullMessageInternalException = new InternalException(
                    null);
            fail("An InternalException should be thrown.");
        }
        catch (InternalException e) {
            // Expected
        }

        // Verifying validity provided message is taken correctly.
        assertEquals("Invalid exception message", "Valid message",
                goodInternalException.getMessage());
    }

    @Test
    @SuppressWarnings("unused")
    public void testInternalExceptionStringThrowable() {

        Throwable cause = new Throwable();

        // Initializing a good internal exception.
        InternalException goodInternalException = new InternalException(
                "Not null", cause);

        // Testing no thrown exception when message and cause not null.
        try {
            goodInternalException = new InternalException("Valid message",
                    cause);
        }
        catch (InternalException e) {
            fail("InternalException not expected here.");
        }

        // Testing thrown exception when message is null, cause is good.
        try {
            InternalException nullMessageInternalException = new InternalException(
                    null, cause);
            fail("An InternalException should be thrown.");
        }
        catch (InternalException e) {
            // Expected
        }

        // Testing thrown exception when cause is null, message is good.
        try {
            InternalException nullCauseInternalException = new InternalException(
                    "Message", null);
            fail("An InternalException should be thrown.");
        }
        catch (InternalException e) {
            // Expected
        }

        // Testing thrown exception when message and cause are null.
        try {
            InternalException nullMessageAndCauseInternalException = new InternalException(
                    null, null);
            fail("An InternalException should be thrown.");
        }
        catch (InternalException e) {
            // Expected
        }

        // Verifying validity provided message is taken correctly.
        assertEquals("Invalid exception message", "Valid message",
                goodInternalException.getMessage());

        // Verifying validity provided message is taken correctly.
        assertEquals("Invalid exception cause", cause, goodInternalException
                .getCause());

    }

}

Add JUnit tests for InternalException. See ticket:9.


package xyz.benw.plugins.fouriermc.Violations;

/**
 *  Super basic violation handling
 *  //TODO Something useful
 */
public class Violation {

    // Fields for the cumulative violation values
    private double cps = 0;  // Clicks per second
    private double pd = 0;   // Pattern detection

    public double getCPS() {
        return cps;
    }

    public double getPD() {
        return pd;
    }

    public void incrementCPS(double val) {
        cps = cps + val;
    }

    public void incrementPD(double val) {
        pd = pd + val;
    }

    public void setCPS(double cps) {
        this.cps = cps;
    }

    public void setPD(double pd) {
        this.pd = pd;
    }

}

Add basic violation class for now


package org.realityforge.arez.api2;

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

public class ObserverTest
  extends AbstractArezTest
{
  @Test
  public void initialState()
    throws Exception
  {
    final ArezContext context = new ArezContext();
    final String name = ValueUtil.randomString();
    final int nextNodeId = context.currentNextNodeId();
    final Observer observer = new Observer( context, name );

    // Verify all "Node" behaviour
    assertEquals( observer.getContext(), context );
    assertEquals( observer.getName(), name );
    assertEquals( observer.getId(), nextNodeId );
    assertEquals( observer.toString(), name );

    // Starts out inactive and inactive means no dependencies
    assertEquals( observer.getState(), ObserverState.INACTIVE );
    assertEquals( observer.isActive(), false );
    assertEquals( observer.isInactive(), true );
    assertEquals( observer.getDependencies().size(), 0 );

    // All the hooks start out null
    assertEquals( observer.getOnActivate(), null );
    assertEquals( observer.getOnDeactivate(), null );
    assertEquals( observer.getOnStale(), null );

    final Action onActivate = () -> {
    };
    final Action onDeactivate = () -> {
    };
    final Action onStale = () -> {
    };

    // Ensure hooks can be modified
    observer.setOnActivate( onActivate );
    observer.setOnDeactivate( onDeactivate );
    observer.setOnStale( onStale );

    assertEquals( observer.getOnActivate(), onActivate );
    assertEquals( observer.getOnDeactivate(), onDeactivate );
    assertEquals( observer.getOnStale(), onStale );

    observer.invariantState();
  }
}

Add start of tests for Observer


package com.japlj.healthydiet.food.playerstats;

import com.japlj.healthydiet.ModConfig;
import com.japlj.healthydiet.food.FoodParameter;

import net.minecraft.entity.Entity;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.world.World;
import net.minecraftforge.common.IExtendedEntityProperties;

public class PlayerNutritionalConditions implements IExtendedEntityProperties {
	public final static String EXT_PROP_NAME = "playerNutritionalConditions";

	private FoodParameter param = new FoodParameter(50.0F, 50.0F, 50.0F, 50.0F);
	private final static String PROTEIN_VALUE_NAME = "proteinValue";
	private final static String CARBOHYDRATE_VALUE_NAME = "carbohydrateValue";
	private final static String VITA_MINE_VALUE_NAME = "vitaMineValue";
	private final static String FOOD_SATURATION_NAME = "foodSaturation";

	public static void register(EntityPlayer player) {
		player.registerExtendedProperties(EXT_PROP_NAME, new PlayerNutritionalConditions());
	}

	public static PlayerNutritionalConditions get(EntityPlayer player) {
		return (PlayerNutritionalConditions)player.getExtendedProperties(EXT_PROP_NAME);
	}

	@Override
	public void saveNBTData(NBTTagCompound nbtOut) {
		NBTTagCompound nbt = new NBTTagCompound();

		nbt.setFloat(PROTEIN_VALUE_NAME, param.proteinValue);
		nbt.setFloat(CARBOHYDRATE_VALUE_NAME, param.carbohydrateValue);
		nbt.setFloat(VITA_MINE_VALUE_NAME, param.vitaMineValue);
		nbt.setFloat(FOOD_SATURATION_NAME, param.saturation);

		nbtOut.setTag(EXT_PROP_NAME, nbt);
	}

	@Override
	public void loadNBTData(NBTTagCompound nbtIn) {
		NBTTagCompound nbt = (NBTTagCompound)nbtIn.getTag(EXT_PROP_NAME);

		this.param.proteinValue = nbt.getFloat(PROTEIN_VALUE_NAME);
		this.param.carbohydrateValue = nbt.getFloat(CARBOHYDRATE_VALUE_NAME);
		this.param.vitaMineValue = nbt.getFloat(VITA_MINE_VALUE_NAME);
		this.param.saturation = nbt.getFloat(FOOD_SATURATION_NAME);
	}

	@Override
	public void init(Entity entitiy, World world) { }

	public FoodParameter getFoodParameter() {
		return param;
	}

	public boolean isEdible(FoodParameter foodParam) {
		return param.saturation + foodParam.saturation <= ModConfig.MAX_NUTRITION_VALUE;
	}
}

Implement extended player properties representing nutritional conditions


package com.practice.tree;
import java.util.Arrays;

/**
 * Print Right View of a Binary Tree  - http://www.geeksforgeeks.org/print-right-view-binary-tree-2/
 *
 * @author tsohil
 *
 */
public class PrintRightView {
	public static int[] rightView;
	public static int count = 0;

	public static void printRightView(Node root) {
		if(root == null) {
			System.out.println("NULL");
		}

		if(root.right != null) {
			printRightView(root.right);
		}

		rightView[count++] = root.data;
	}

	public static int depth(Node root) {
		if(root == null) {
			return 0;
		} else {
			return 1+depth(root.right);
		}
	}

	public static void main(String[] args) {
		Node root = new Node(1);
		root.left = new Node(2);
		root.left.left = new Node(4);
		root.left.right = new Node(5);

		root.right = new Node(3);
		root.right.left = new Node(6);
		root.right.right = new Node(7);
		root.right.right.right = new Node(8);

		rightView = new int[depth(root)];
		printRightView(root);

		//reverse array
		for(int i=0; i<rightView.length/2; i++) {
			int temp = rightView[i];
			rightView[i] = rightView[rightView.length - i - 1];
			rightView[rightView.length - i - 1] = temp;
		}

		System.out.println(Arrays.toString(rightView));
	}
}

Print right view of Binary Tree