package org.simpleframework.xml.core;

import java.io.StringWriter;

import junit.framework.TestCase;

import org.simpleframework.xml.Attribute;
import org.simpleframework.xml.Root;
import org.simpleframework.xml.Serializer;
import org.simpleframework.xml.Text;
import org.simpleframework.xml.transform.Matcher;
import org.simpleframework.xml.transform.Transform;

public class TextConstructorInjectionWithTransformTest extends TestCase {

   private static class DateTime {
      private String time;
      public DateTime(String time) {
         this.time = time;
      }
      public String getTime() {
         return time;
      }
      public String toString() {
         return time;
      }
   }

   private static class DateTimeTransform implements Transform<DateTime> {
      public DateTime read(String text) throws Exception {
          return new DateTime(text);
      }
      public String write(DateTime value) throws Exception {
          return value.getTime();
      }
   }

   public class DateTimeMatcher implements Matcher {
      public Transform match(Class type) throws Exception {
         if(type == DateTime.class) {
            return new DateTimeTransform();
         }
         return null;
      }
   }

   @Root
   public static class Embargo {
      @Attribute
      private String name;
      @Text
      private DateTime embargo_datetime;
      public Embargo(@Text DateTime embargo_datetime, @Attribute(name="name") String name) {
          this.embargo_datetime = embargo_datetime;
          this.name = name;
      }
      public DateTime getEmbargo() {
          return embargo_datetime;
      }
      public void setEmbargo(DateTime embargo_datetime) {
          this.embargo_datetime = embargo_datetime;
      }
  }

   public void testConstructor() throws Exception {
      Embargo embargo = new Embargo(new DateTime("2010-06-02T12:00:12"), "cuba");
      Serializer serializer = new Persister(new DateTimeMatcher());
      StringWriter writer = new StringWriter();

      serializer.write(embargo, writer);

      Embargo embargoout = serializer.read(Embargo.class, writer.toString());

      System.out.println(writer.toString());
   }

}

Add test for @Text injection

Add test for @Text injection

git-svn-id: 4741f78aa2d3279ddd0a34c053c42ca3ce19451b@1613 124fc276-1b20-0410-8d16-dc08e6bff5e9


package com.javarush.task.task05.task0510;

/*
Кошкоинициация
*/

/*
    — Имя,
    — Имя, вес, возраст
    — Имя, возраст (вес стандартный)
    — вес, цвет (имя, адрес и возраст неизвестны, это бездомный кот)
    — вес, цвет, адрес (чужой домашний кот)
*/

public class Cat {

    /*

    Валидатор поел говна.
    Закомментированый ниже код не принимается (WTF?).

    private String name = null;
    private int age;
    private int weight;
    private String address = null;
    private String color = null;

    public void initialize(String name) {
        this.name = name;
        this.age = 4;
        this.weight = 5;
        this.color = "white";
    }

    public void initialize(String name, int weight, int age) {
        this.name = name;
        this.weight = weight;
        this.age = age;
        this.color = "white";
    }

    private void initialize(String name, int age) {
        this.name = name;
        this.age = age;
        this.weight = 5;
        this.color = "white";
    }

    public void initialize(int weight, String color) {
        this.age = 4;
        this.weight = weight;
        this.color = color;
    }

    public void initialize(int weight, String color, String address) {
        this.age = 4;
        this.weight = weight;
        this.address = address;
        this.color = color;
    }
    */

    private String name = null;
    private int weight; //weight
    private int age;
    private String color = null;
    private String address = null;

    public void initialize (String name) {
        this.name = name;
        this.weight = 5;
        this.age = 5;
        this.color = "black";
    }

    public void initialize (String name, int weight, int age) {
        this.name = name;
        this.weight= weight;
        this.age = age;
        this.color = "black";
    }

    public void initialize (String name, int age) {
        this.name = name;
        this.weight= 5;
        this.age = age;

    }

    public void initialize (int weight, String color) {
        this.weight= weight;
        this.age = 5;
        this.color = color;
    }

    public void initialize (int weight, String color, String address) {
        this.weight= weight;
        this.age = 5;
        this.color = color;
        this.address = address;
    }

    public static void main(String[] args) {

    }
}

Complete 0510. Validator poel govna in this task IMHO


package com.jmb.springfactory.controller.api;

import org.springframework.beans.factory.annotation.Autowired;

import com.jmb.springfactory.controller.GenericController;
import com.jmb.springfactory.model.dto.RolDto;
import com.jmb.springfactory.service.GenericService;
import com.jmb.springfactory.service.rol.RolService;

public class RolController extends GenericController<RolDto, String>{

  @Autowired
  private RolService rolService;

  @Override
  public GenericService<RolDto, String> genericService() {
    return rolService;
  }

}

Create a controller to handle petition to rol resources


package org.nwapw.abacus.plugin;

import org.nwapw.abacus.number.NumberInterface;

import java.util.Map;
import java.util.function.Function;

public abstract class NumberImplementation {

    private Class<? extends NumberInterface> implementation;
    private Map<String, Function<NumberInterface, NumberInterface>> promotionPaths;
    private int priority;

    public abstract NumberInterface instanceForString(String string);
    public abstract NumberInterface instanceForPi();

}

Add a class that keeps track of the implementation information.


package org.bouncycastle.crypto.prng;

/**
 * Takes bytes generated by an underling RandomGenerator and reverses the order in
 * each small window (of configurable size).
 * <p>
 * Access to internals is synchronized so a single one of these can be shared.
 * </p>
 */
public class ReversedWindowGenerator
    implements RandomGenerator
{
    private final RandomGenerator generator;

    private byte[] window;
    private int windowCount;

    public ReversedWindowGenerator(
        RandomGenerator generator,
        int             windowSize)
    {
        if (generator == null)
            throw new IllegalArgumentException("generator cannot be null");
        if (windowSize < 2)
            throw new IllegalArgumentException("windowSize must be at least 2");

        this.generator = generator;
        this.window = new byte[windowSize];
    }

    /**
     * Add more seed material to the generator.
     *
     * @param seed a byte array to be mixed into the generator's state.
     */
    public void addSeedMaterial(
        byte[] seed)
    {
        synchronized (this)
        {
            windowCount = 0;
            generator.addSeedMaterial(seed);
        }
    }

    /**
     * Add more seed material to the generator.
     *
     * @param seed a long value to be mixed into the generator's state.
     */
    public void addSeedMaterial(
        long seed)
    {
        synchronized (this)
        {
            windowCount = 0;
            generator.addSeedMaterial(seed);
        }
    }

    /**
     * Fill bytes with random values.
     *
     * @param bytes byte array to be filled.
     */
    public void nextBytes(
        byte[] bytes)
    {
        doNextBytes(bytes, 0, bytes.length);
    }

    /**
     * Fill part of bytes with random values.
     *
     * @param bytes byte array to be filled.
     * @param start index to start filling at.
     * @param len length of segment to fill.
     */
    public void nextBytes(
        byte[]  bytes,
        int     start,
        int     len)
    {
        doNextBytes(bytes, start, len);
    }

    private void doNextBytes(
        byte[]  bytes,
        int     start,
        int     len)
    {
        synchronized (this)
        {
            int done = 0;
            while (done < len)
            {
                if (windowCount < 1)
                {
                    generator.nextBytes(window, 0, window.length);
                    windowCount = window.length;
                }

                bytes[start + done++] = window[--windowCount];
            }
        }
    }
}

Add a generator that reverses the output of another generator over each short window.


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

Add JUnit tests for InternalException.

Signed-off-by: Patrick Pelletier <4307fca26d0353058fbfb17dc5f40867e5e6b8e6@gmail.com>
Signed-off-by: Etienne M. Gagnon <bf06ec0eb40152cd863534753d026b021022c851@j-meg.com>


/*
 * FindBugs - Find Bugs in Java programs
 * Copyright (C) 2003-2007 University of Maryland
 *
 * 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 edu.umd.cs.findbugs;

import java.io.IOException;
import java.util.HashSet;
import java.util.Set;

import org.dom4j.DocumentException;

/**
 * @author pugh
 */
public class ExcludingHashesBugReporter extends DelegatingBugReporter {

	Set<String> excludedHashes = new HashSet<String>();
	/**
     * @param delegate
	 * @throws DocumentException
	 * @throws IOException
     */
    public ExcludingHashesBugReporter(BugReporter delegate, String baseline) throws IOException, DocumentException {
	    super(delegate);
		Project project = new Project();
		BugCollection origCollection;
		origCollection = new SortedBugCollection();
		origCollection.readXML(baseline, project);
		for(BugInstance b : origCollection.getCollection())
			excludedHashes.add(b.getInstanceHash());
    }
	@Override
	public void reportBug(BugInstance bugInstance) {
		if (!excludedHashes.contains(bugInstance.getInstanceHash()))
				getDelegate().reportBug(bugInstance);
	}
}

Add delegating bug reporter that filters out bugs that match a known instance hash

git-svn-id: e7d6bde23f017c9ff4efd468d79d66def666766b@8957 eae3c2d3-9b19-0410-a86e-396b6ccb6ab3


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

package org.opennms.smoketest;

import java.util.List;

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

import com.google.common.collect.Lists;

public class TopologyIT extends OpenNMSSeleniumTestCase {

    private static final String TOPOLOGY_UI_URL = BASE_URL + "opennms/topology";

    private final TopologyUiPage topologyUiPage = new TopologyUiPage();

    private final static List<String> availableLayouts = Lists.newArrayList(
            "Circle Layout",
            "D3 Layout",
            "FR Layout",
            "Hierarchy Layout",
            "ISOM Layout",
            "KK Layout",
            "Manual Layout",
            "Real Ultimate Layout",
            "Spring Layout"
            );

    /**
     * Class to control the inputs and workflow of the "Topology UI" Page
     */
    private class TopologyUiPage {
        public TopologyUiPage open() {
            m_driver.get(TOPOLOGY_UI_URL);
            return this;
        }

        public TopologyUiPage selectLayout(String layoutName) {
            clickItemInMenuBar("View");
            clickItemInMenuBar(layoutName);
            showEntireMap();
            return this;
        }

        private void clickItemInMenuBar(String itemName) {
            findElementByXpath("//span[@class='v-menubar-menuitem-caption' and text()='" + itemName + "']").click();
        }

        private void showEntireMap() {
            findElementByXpath("//i[@class='icon-globe']").click();
        }
    }

    @Before
    public void setUp() {
        topologyUiPage.open();
    }

    @Test
    public void canSelectLayouts() throws InterruptedException {
        for (String layout : availableLayouts) {
            topologyUiPage.selectLayout(layout);
        }
    }
}

HZN-732: Add a simple Topology UI tests that cycles through known layouts.


package org.robockets.stronghold.robot.commands;

import org.robockets.stronghold.robot.highgoalshooter.MoveHood;
import org.robockets.stronghold.robot.highgoalshooter.MoveTurnTable;
import org.robockets.stronghold.robot.intake.IntakesUp;

import edu.wpi.first.wpilibj.command.CommandGroup;

/**
 *
 */
public class DrivePosition extends CommandGroup {

    public  DrivePosition() {
        addSequential(new MoveHood(-70));
        addSequential(new IntakesUp());
        addSequential(new MoveTurnTable(0));
    }
}

Add command to move robot to its driving position


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

/**
 * Given a BinaryTree and two nodes, can you write a method to find the lowest common ancestor of
 * this nodes?
 *
 * @author Pedro Vicente Gómez Sánchez.
 */
public class LowestCommonAncestor {
}

Add statement to problem 21

Add statement to problem 21


package com.sunny.grokkingalgorithms.ctc.c2;

import com.sunny.grokkingalgorithms.ctc.c2.util.LinkedListUtil;
import com.sunny.grokkingalgorithms.ctc.c2.util.Node;

/**
 * Created by sundas on 3/14/2018.
 */
public class DeleteMiddleOfLinkedListGivenReference {

  /*
  Given reference to a node , delete it from the linked list.If it is last element you
  will not be delete it.

  a->b->c->d
  delete c
  after deletion
  a->b->d
   */

  /**
   *
   * @param middle
   */
  public static void deleteNodeFromMiddle(Node middle){
    if(middle != null
        && middle.next != null){
      /*
      Copy next node's value into middle which is essentailly line overwriting existing middle's value and then
      delete next
       */
      middle.data = middle.next.data;
      middle.next = middle.next.next;
    }
  }

  /**
   *
   * @param root
   * @return
   */
  public static Node findMiddleOfLinkedList(Node root){
    /*
    Once again we use the fast runner apporach. The fast runner covers twice as much noes as slow
     runner so when fast runner will be at the end, slow runner will be in the middle
     */
    Node slowRunner = root;
    Node fastRunner = root;
    while(fastRunner != null && slowRunner != null){
      slowRunner = slowRunner.next;
      fastRunner = fastRunner.next;
      if(fastRunner != null){
        fastRunner = fastRunner.next;
      }
    }
    //Now slow runner is at the middle
    return slowRunner;
  }

  /**
   *
   * @param args
   */
  public static void main(String[] args) {
    int[] input = new int[]{1,2,3,4,5,6,7,8};
    Node root = LinkedListUtil.createLinkedList(input);
    LinkedListUtil.printLinkedList(root);
    Node middle = findMiddleOfLinkedList(root);
    System.out.println(middle.data);
    deleteNodeFromMiddle(middle);
    LinkedListUtil.printLinkedList(root);
  }
}

Delete node from middle of linked list.

Delete node from middle of linked list.


// ======================================================================
// Filename: Card.java
// Description: Define and implement a basic playing card.
// Created: Fri Mar 24 21:37:59 2017 (-0500)
// Last-Updated: Fri Mar 24 23:02:27 2017 (-0500)
// Author: Ivan Guerra <Ivan.E.Guerra-1@ou.edu>
// ======================================================================
package com.mouthofrandom.cardshark.game.blackjack;

public class Card {
    private String suit;
    private String cardType;
    private int value;

    public Card(final String suit, final String cardType, final int value) {
	this.suit = suit;
	this.cardType = cardType;
	this.value = value;
    }

    /* Return the card suit. */
    public String getSuit() {
	return suit;
    }

    /* Return the card type. */
    public String getCardType() {
	return cardType;
    }

    /* Return the card value. */
    public int getValue() {
	return value;
    }

    /* Return the string representation of a Card. */
    public String toString() {
	return ("(" + this.suit + ", " + this.cardType + ", " + this.value + ")");
    }
}

Add a class for representing playing cards.


package com.suse.saltstack.netapi.event;

import java.io.IOException;

import javax.websocket.CloseReason;
import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;

import com.suse.saltstack.netapi.utils.ClientUtils;

/**
 * This class is intended to emulate the Server WebSocket
 * EndPoint where EventStream is connected to, and where events came from.
 */
@ServerEndpoint(value = "/token")
public class WebSocketServerSalt {

    /**
     * Note: The event stream message is a String delimited by "\n\n". The resource file
     * events_stream.txt contains some events separated by "\n\n".
     */
    static final String[] TEXT_EVENT_STREAM_MESSAGES =
            ClientUtils.streamToString(WebSocketServerSalt.class
                    .getResourceAsStream("/events_stream.txt")).split("\n\n");

    @OnOpen
    public void onOpen(Session session) {
    }

    @OnMessage
    public void onMessage(String message, Session session) {
        try {
            for (String s : TEXT_EVENT_STREAM_MESSAGES) {
                session.getBasicRemote().sendText(s);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @OnClose
    public void onClose(Session session, CloseReason closeReason) {
    }
}

Add an emulation of a websocket server endpoint


Create a text "template" file for class instantiation. Will find a better solution in the future.

Essentially it's a text file to reference (read: copy/paste) when building a new class to faster developing.


package at.ac.univie.isc.asio.junit;

import com.hp.hpl.jena.rdf.model.Model;
import org.hamcrest.Description;
import org.hamcrest.TypeSafeMatcher;

public final class IsSuperSetOf extends TypeSafeMatcher<Model> {
  /**
   * Create a matcher for {@link com.hp.hpl.jena.rdf.model.Model jena rdf models}, matching when the
   * examined model contains all statements in the given reference model.
   *
   * @param expected expected RDF statements
   */
  public static IsSuperSetOf superSetOf(final Model expected) {
    return new IsSuperSetOf(expected);
  }

  private final Model expected;

  private IsSuperSetOf(final Model expected) {
    this.expected = expected;
  }

  @Override
  protected boolean matchesSafely(final Model item) {
    return item.containsAll(expected);
  }

  @Override
  public void describeTo(final Description description) {
    description.appendText("model containing all statements from ").appendValue(expected);
  }
}

Add contains matcher for jena models

[DEV] Add contains matcher for jena models

Matches if actual model has at least all expected statements. More may be
present.


/*
 * $Id: IOPScienceUrlNormalizer.java,v 1.1 2013-10-10 00:06:43 etenbrink Exp $
 */

/*

Copyright (c) 2000-2013 Board of Trustees of Leland Stanford Jr. University,
all rights reserved.

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
STANFORD UNIVERSITY 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.

Except as contained in this notice, the name of Stanford University shall not
be used in advertising or otherwise to promote the sale, use or other dealings
in this Software without prior written authorization from Stanford University.

*/

package org.lockss.plugin.iop;

import org.apache.commons.lang.StringUtils;
import org.lockss.daemon.PluginException;
import org.lockss.plugin.*;
import org.lockss.util.*;

/**
 *
This URL normalizer is only for org.lockss.plugin.iop.(Clockss)IOPSciencePlugin

 */
public class IOPScienceUrlNormalizer implements UrlNormalizer {

  private static final String host = "http://iopscience.iop.org/";

  protected static final String[] endings = new String[] {
    "?rel=ref",
    "?rel=sem",
  };

  protected static Logger log =
      Logger.getLogger(IOPScienceUrlNormalizer.class);

  @Override
  public String normalizeUrl(String url, ArchivalUnit au) throws PluginException {
    if (url == null) {
      return null;
    }
    if (StringUtil.startsWithIgnoreCase(url, host)) {
      if (url.indexOf("?") > 0) {
        // Normalize ending
        for (String ending : endings) {
          url = StringUtils.substringBefore(url, ending);
        }
      }
    }
    return url;
  }

}

Add to remove ?rel=(ref|sem), links to articles in the same AU

git-svn-id: 293778eaa97c8c94097d610b1bd5133a8f478f36@30348 4f837ed2-42f5-46e7-a7a5-fa17313484d4


package refdiff.core.diff;

import refdiff.core.rast.RastNode;

public class PotentialMatch implements Comparable<PotentialMatch> {

	private final RastNode nodeBefore;
	private final RastNode nodeAfter;
	private final int maxDepth;
	private final double score;

	public PotentialMatch(RastNode nodeBefore, RastNode nodeAfter, int maxDepth, double score) {
		this.nodeBefore = nodeBefore;
		this.nodeAfter = nodeAfter;
		this.maxDepth = maxDepth;
		this.score = score;
	}

	public RastNode getNodeBefore() {
		return nodeBefore;
	}

	public RastNode getNodeAfter() {
		return nodeAfter;
	}

	public double getScore() {
		return score;
	}

	public double getMaxDepth() {
		return score;
	}

	@Override
	public String toString() {
		return String.format("(%s, %s)", this.nodeBefore, this.nodeAfter);
	}

	@Override
	public int compareTo(PotentialMatch o) {
		int c1 = Integer.compare(maxDepth, o.maxDepth);
		int c2 = -Double.compare(score, o.score);
		return c1 != 0 ? c1 : c2;
	}
}

Use node depth to sort candidates

Use node depth to sort candidates


package uk.ac.ebi.atlas.bioentity.properties;

import org.junit.Test;
import uk.ac.ebi.atlas.model.experiment.baseline.BioentityPropertyName;

import java.util.Map.Entry;

import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
import static uk.ac.ebi.atlas.model.experiment.baseline.BioentityPropertyName.GENE_BIOTYPE;

public class BioEntityCardPropertiesTest {

    @Test
    public void linkTemplatesExceptGeneBiotypeHaveFormatElements() throws Exception {
        for (Entry<BioentityPropertyName, String> linkTemplate : BioEntityCardProperties.linkTemplates.entrySet()) {
            if (linkTemplate.getKey() != GENE_BIOTYPE) {
                assertThat(linkTemplate.getValue().matches(".+\\{\\d\\}.*"), is(true));
            }
        }
    }

}

Add new test for BioEntityCardProperties


package net.restlesscoder.sandbox.imagej;

import java.util.Set;

import net.imagej.ImageJ;
import net.imglib2.FinalDimensions;
import net.imglib2.algorithm.labeling.ConnectedComponents.StructuringElement;
import net.imglib2.img.Img;
import net.imglib2.roi.labeling.ImgLabeling;
import net.imglib2.roi.labeling.LabelingType;
import net.imglib2.type.numeric.IntegerType;
import net.imglib2.type.numeric.integer.UnsignedByteType;

/**
 * The generics of {@link ImgLabeling} always strike me as potentially unsafe.
 * But in practice they are OK. This code explores it.
 */
public class WhyImgLabelingIsOK {

	private static <T, I extends IntegerType<I>> void checkIt(String name,
		ImgLabeling<T, I> imgLabeling, T valueToAdd)
	{
		imgLabeling.firstElement().add(valueToAdd);

		boolean first = true;
		int count = 0;
		for (final LabelingType<T> item : imgLabeling) {
			count++;
			final Set<T> labels = item.getMapping().getLabels(); // A COPY; mutating it will not persist
			//System.out.println(name + ": got item labels: " + labels + " of size " + labels.size());
			for (final T value : labels) {
				if (first) first = false;
				else break;
				System.out.println(name + ": first value = " + value.getClass());
			}
		}
		System.out.println(name + ": item count = " + count + " compared to size = " + imgLabeling.size());
	}

	public static <T> void main(final String... args) throws Exception {
		final ImageJ ij = new ImageJ();

		@SuppressWarnings({ "unchecked", "rawtypes" })
		final Img<UnsignedByteType> img = (Img) ij.scifio().datasetIO().open("/Users/curtis/data/blobs.tif");
		final ImgLabeling<Integer, UnsignedByteType> imgLabelingCCA = ij.op().labeling().cca(img, StructuringElement.EIGHT_CONNECTED);

		final ImgLabeling<String, UnsignedByteType> imgLabelingEmpty = ij.op().create().imgLabeling(new FinalDimensions(3, 4), new UnsignedByteType());

		checkIt("CCA", imgLabelingCCA, 37);
		checkIt("Empty", imgLabelingEmpty, "hello");

		ij.context().dispose();
	}

}

Add an exploration of ImgLabeling usage

Add an exploration of ImgLabeling usage


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

package com.google.sps.servlets;

import com.google.common.collect.ListMultimap;
import com.google.common.collect.ArrayListMultimap;
import com.google.sps.utilities.CommonUtils;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/** Servlet that handles comments data. */
@WebServlet("/searchData")
public class SearchDataServlet extends HttpServlet {
  private ListMultimap<String, String> keywordToEventIds = ArrayListMultimap.create();
  private static final String KEYWORD = "keyword";
  private static final String EVENT_ID = "event-id";
  private static final String DESCRIPTION = "description";

  @Override
  public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
    String keyword = request.getParameter(KEYWORD);

    if (keyword == null) {

    }

    response.setContentType("application/json;");
    response.getWriter().println(CommonUtils.convertToJson(keywordToEventIds.get(keyword)));
  }

  @Override
  public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
    String eventId = request.getParameter(EVENT_ID);
    String description = CommonUtils.getParameter(request, DESCRIPTION, "");

    String[] keywordsInDescription = description.split("[^a-zA-Z0-9']+");
    addWordsToIndex(eventId, keywordsInDescription);

    response.sendRedirect("/events-feed.html");
  }

  private void addWordsToIndex(String eventId, String[] keywords) {
    for (String keyword : keywords) {
      keywordToEventIds.put(keyword, eventId);
    }
  }
}

Add servlet with naive search algorithm.


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

package org.apache.usergrid.persistence.qakka;

import com.google.inject.Injector;
import org.apache.usergrid.persistence.core.migration.schema.MigrationException;
import org.apache.usergrid.persistence.core.migration.schema.MigrationManager;
import org.junit.BeforeClass;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;

public abstract class AbstractAkkaTest {
    private static final Logger logger = LoggerFactory.getLogger( AbstractAkkaTest.class );

    static AtomicInteger nextPort = new AtomicInteger(3551);

//    protected static Injector sharedInjector;

    static AtomicBoolean migrated = new AtomicBoolean( false );

    static { new KeyspaceDropper(); }

    public AbstractAkkaTest() {
        if ( !migrated.getAndSet( true ) ) {
            //setInjector( Guice.createInjector( new TestModule() ) );
            MigrationManager migrationManager = getInjector().getInstance( MigrationManager.class );
            try {
                migrationManager.migrate();
            } catch (MigrationException e) {
                logger.error("Error in migration", e);
            }
        }
    }

    protected abstract Injector getInjector();

//    protected Injector getInjector() {
//        return sharedInjector;
//    }
//
//    protected static void setInjector(Injector injector) {
//        AbstractTest.sharedInjector = injector;
//    }

    protected static int getNextAkkaPort() {
        int ret = nextPort.getAndIncrement();
        logger.info("Returning port {}", ret);
        return ret;
    }

    @BeforeClass
    public static void startCassandra() throws Exception {
        //EmbeddedCassandraServerHelper.startEmbeddedCassandra("/cassandra.yaml");
    }

}

Use one injector in tests and, at most, one Akka cluster per test class.


package leetcode.binary_tree_inorder_traversal;

import java.util.ArrayList;
import java.util.Stack;

import common.TreeNode;

public class Solution {

	public static class MyNode{
		TreeNode node;
		boolean isVisit;
		public MyNode(TreeNode node){
			this.node = node;
		}
	}

    public ArrayList<Integer> inorderTraversal(TreeNode root) {
    	ArrayList<Integer> ans = new ArrayList<Integer>();
    	if(root == null) return ans;
    	Stack<MyNode> stack = new Stack<MyNode>();
    	stack.push(new MyNode(root));
    	while(!stack.isEmpty()){
    		MyNode cur = stack.pop();
    		if(cur.isVisit){
    			ans.add(cur.node.val);
    		}else{
    			cur.isVisit = true;
    			if(cur.node.right != null){
    				stack.push(new MyNode(cur.node.right));
    			}
    			stack.push(cur);
    			if(cur.node.left != null){
    				stack.push(new MyNode(cur.node.left));
    			}
    		}
    	}
    	return ans;
    }

    public static void main(String[] args){
    	TreeNode t1 = new TreeNode(1);
    	TreeNode t2 = new TreeNode(2);
    	TreeNode t3 = new TreeNode(3);
    	TreeNode t4 = new TreeNode(4);
    	t1.left = t2;
    	t2.left = t3;
    	t2.right = t4;
    	for(int x : new Solution().inorderTraversal(t1)){
    		System.err.print(x + "->");
    	}
    	System.err.println("");
    }
}

Add java solution for 94. Binary Tree Inorder Traversal

94. Binary Tree Inorder Traversal: https://leetcode.com/problems/binary-tree-inorder-traversal/


package org.apache.ddlutils.platform;

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

import java.util.Map;

import org.apache.commons.beanutils.DynaBean;
import org.apache.ddlutils.TestPlatformBase;
import org.apache.ddlutils.dynabean.SqlDynaBean;
import org.apache.ddlutils.dynabean.SqlDynaClass;
import org.apache.ddlutils.model.Database;
import org.apache.ddlutils.model.Table;

/**
 * Tests the {@link org.apache.ddlutils.PlatformImplBase} (abstract) class.
 *
 * @author Martin van den Bemt
 * @version $Revision: 279421 $
 */
public class TestPlatformImplBase extends TestPlatformBase
{

    String xml = "<?xml version='1.0' encoding='ISO-8859-1'?>\n"+
                 "<database name='ddlutils'>\n"+
                 "  <table name='TestTable'>\n"+
                 "    <column name='id' autoIncrement='true' type='INTEGER' primaryKey='true'/>\n"+
                 "    <column name='name' type='VARCHAR' size='15'/>\n"+
                 "  </table>\n"+
                 "</database>";

    public void setUp()
    {
    }

    /**
     * Test the toColumnValues method
     */
    public void testToColumnValues()
    {
        Database database = parseDatabaseFromString(xml);
        PlatformImplBase platform = new PlatformBase();
        Table table = database.getTable(0);
        SqlDynaClass clz = SqlDynaClass.newInstance(table);
        DynaBean db = new SqlDynaBean(SqlDynaClass.newInstance(table));
        db.set("name", "name");
        Map map = platform.toColumnValues(clz.getSqlDynaProperties(), db);

        assertEquals("name", map.get("name"));
        assertEquals(true, map.containsKey("id"));
    }

    public class PlatformBase extends PlatformImplBase
    {
        public String getName()
        {
            return null;
        }
    }

    protected String getDatabaseName() {
        return null;
    }

}

Add test for abstract PlatformImplBase.

Add test for abstract PlatformImplBase.

git-svn-id: b9063b25153de5216c397e252c209c32bc9c47ff@331926 13f79535-47bb-0310-9956-ffa450edef68


package com.example.playground.monadic.parser.combinators;

import com.example.playground.result.Result;

import java.util.stream.BaseStream;

@FunctionalInterface
public interface Parser<T, E, I, S extends BaseStream<I, S>> {
    Result<ParserResult<T, I, S>, E> parse(S input);
}

Add functional interface for parsers

Add functional interface for parsers


package com.philliphsu.bottomsheetpickers.view.numberpad;

interface INumberPadTimePicker {
    interface View {
        void setNumberKeysEnabled(int start, int end);
        void setBackspaceEnabled(boolean enabled);
        void updateTimeDisplay(CharSequence time);
        void updateAmPmDisplay(CharSequence ampm);
        void setOkButtonEnabled(boolean enabled);
    }
    interface Presenter {
        void onNumberKeyClick(CharSequence numberKeyText);
        void onBackspaceClick();
    }
}

Create contract between view implementations of NumberPadTimePicker and presenters.


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

public class ClustalFileMapper {
	// FIELDS
	private final String inputFilePath;
	private String guideTreeFilePath;
	private String guidePhylogeneticTreeFile;

	// CONSTRUCTOR
	public ClustalFileMapper(String inputFilePath){
		this.inputFilePath = inputFilePath;
	}

	// GET/ SET
	public String getInputFilePath(){
		return this.inputFilePath;
	}

	public String getGuideTreeFilePath(){
		return this.guideTreeFilePath;
	}

	public String getGuidePhylogeneticTreeFile(){
		return this.guidePhylogeneticTreeFile;
	}

	public void setGuideTreeFilePath(String guideTreeFilePath){
		this.guideTreeFilePath = guideTreeFilePath;
	}

	public void setGuidePhylogeneticTreeFile(String guidePhylogeneticTreeFile){
		this.guidePhylogeneticTreeFile = guidePhylogeneticTreeFile;
	}

	// METHODS
	public String getTreeFilePath(){
		// Return guide tree if phylogenetic tree isn't set
		if (this.guidePhylogeneticTreeFile == null)
		{
			return this.guideTreeFilePath;
		}
		return this.guidePhylogeneticTreeFile;
	}
}

[ADD] Add class to easy manage clustal parameters


/*
 * Copyright 2019, TeamDev. All rights reserved.
 *
 * Redistribution and use in source and/or binary forms, with or without
 * modification, must retain the above copyright notice and the following
 * disclaimer.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

package io.spine.validate.rule;

import com.google.common.truth.OptionalSubject;
import com.google.protobuf.Descriptors;
import io.spine.code.proto.FieldContext;
import io.spine.option.OptionsProto;
import io.spine.test.validate.rule.AField;
import io.spine.test.validate.rule.AMessage;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;

import static com.google.common.truth.Truth8.assertThat;

@DisplayName("ValidationRuleOptions should")
final class ValidationRuleOptionsTest {

    @DisplayName("retrieve option value from context")
    @Test
    void retrieveOptionValue() {
        FieldContext targetContext = FieldContext.create(AMessage.getDescriptor()
                                                                 .getFields()
                                                                 .get(0));
        Descriptors.FieldDescriptor nameField = AField.getDescriptor()
                                                      .getFields()
                                                      .get(0);
        FieldContext context = targetContext.forChild(nameField);
        OptionalSubject subject =
                assertThat(ValidationRuleOptions.getOptionValue(context, OptionsProto.required));
        subject.isPresent();
        subject.hasValue(true);
    }

    @DisplayName("return empty for field without options")
    @Test
    void returnEmptyForNonExistingRuleOptions() {

        FieldContext targetContext = FieldContext.create(AMessage.getDescriptor()
                                                                 .getFields()
                                                                 .get(0));
        Descriptors.FieldDescriptor addressField = AField.getDescriptor()
                                                         .getFields()
                                                         .get(3);
        FieldContext context = targetContext.forChild(addressField);
        assertThat(ValidationRuleOptions.getOptionValue(context, OptionsProto.required)).isEmpty();
    }
}

Add validation rule options test

Add validation rule options test


/*******************************************************************************
 * Copyright (c) 1998, 2013 Oracle and/or its affiliates. All rights reserved.
 * This program and the accompanying materials are made available under the
 * terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0
 * which accompanies this distribution.
 * The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html
 * and the Eclipse Distribution License is available at
 * http://www.eclipse.org/org/documents/edl-v10.php.
 *
 * Contributors:
 *     Matt MacIvor - 2.5.1 - Initial Implementation
 ******************************************************************************/
package org.eclipse.persistence.testing.jaxb.annotations.xmlinlinebinarydata;

import java.util.List;

import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlSchemaType;

@XmlRootElement
public class HexRoot {

    @XmlSchemaType(name="hexBinary")
    public byte[] bytes;

    public boolean equals(Object obj) {
        HexRoot r = (HexRoot)obj;

        return new String(this.bytes).equals(new String(r.bytes));
    }

}

Check in for missing file

Check in for missing file


/*
 * Copyright (C) 2015 Brett Wooldridge
 *
 * 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.codacy.play.tomcatcp.metrics;

import com.codacy.play.tomcatcp.utils.ClockSource;

import java.util.concurrent.atomic.AtomicLong;

/**
 * @author Brett Wooldridge
 */
public abstract class PoolStats {
    private final ClockSource clock;
    private final AtomicLong reloadAt;
    private final long timeoutMs;

    protected volatile int totalConnections;
    protected volatile int idleConnections;
    protected volatile int activeConnections;
    protected volatile int pendingThreads;

    public PoolStats(final long timeoutMs) {
        this.timeoutMs = timeoutMs;
        this.reloadAt = new AtomicLong();
        this.clock = ClockSource.INSTANCE;
    }

    public int getTotalConnections() {
        if (shouldLoad()) {
            update();
        }

        return totalConnections;
    }

    public int getIdleConnections() {
        if (shouldLoad()) {
            update();
        }

        return idleConnections;
    }

    public int getActiveConnections() {
        if (shouldLoad()) {
            update();
        }

        return activeConnections;
    }

    public int getPendingThreads() {
        if (shouldLoad()) {
            update();
        }

        return pendingThreads;
    }

    protected abstract void update();

    private boolean shouldLoad() {
        for (; ; ) {
            final long now = clock.currentTime();
            final long reloadTime = reloadAt.get();
            if (reloadTime > now) {
                return false;
            } else if (reloadAt.compareAndSet(reloadTime, clock.plusMillis(now, timeoutMs))) {
                return true;
            }
        }
    }
}

Add a class that provides updated stats of a pool


package net.kuujo.copycat.test;

/**
 * @author Jordan Halterman
 */
public class ResourceTest {
}

Refactor member info in order to ensure that members are properly marked DEAD once the failure limit is reached.


/*
 * Copyright (C) 2015 Karumi.
 *
 * 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.karumi.katagenda.ui;

import com.karumi.katagenda.domain.Contact;
import java.util.List;

public class SysOutContactsListView implements ContactsListPresenter.View {

  @Override public void showWelcomeMessage() {

  }

  @Override public void showGoodbyeMessage() {

  }

  @Override public void showContacts(List<Contact> contactList) {

  }

  @Override public String getNewContactFirstName() {
    return null;
  }

  @Override public String getNewContactLastName() {
    return null;
  }

  @Override public String getNewContactPhoneNumber() {
    return null;
  }

  @Override public void showDefaultError() {

  }
}

Add an empty ContactsList.View implementation


package net.jgp.labs.spark.l300_reduce.l000;

import java.io.Serializable;
import java.util.Arrays;
import java.util.List;

import org.apache.spark.api.java.function.ReduceFunction;
import org.apache.spark.sql.Dataset;
import org.apache.spark.sql.Encoders;
import org.apache.spark.sql.SparkSession;

public class ReducerApp implements Serializable {
	private static final long serialVersionUID = -8951059218545451099L;

	private final class SumByReduce implements ReduceFunction<Integer> {
		private static final long serialVersionUID = -7580381094052442862L;

		@Override
		public Integer call(Integer v1, Integer v2) throws Exception {
			return v1 + v2;
		}
	}

	public static void main(String[] args) {
		ReducerApp ra = new ReducerApp();
		ra.start();
	}

	private void start() {
		SparkSession spark = SparkSession.builder().master("local").getOrCreate();

		List<Integer> data = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
		Dataset<Integer> df = spark.createDataset(data, Encoders.INT());
		df.show();
		df.printSchema();
		Integer sumByReduce = df.reduce(new SumByReduce());
		System.out.println("Sum should be 55 and it is... " + sumByReduce);
	}

}

Work on simple reducer for Dataframe

Work on simple reducer for Dataframe


package org.pilgrim.leetcode.y2022;

import java.util.Arrays;

public class SumTwoInSorterArray {

	public static void main(String[] args) {
		// TODO Auto-generated method stub

		int[] indexes = twoSum(new int[] {1,2,3,4,4,9,56,90}, 8);
		System.out.println(Arrays.toString(indexes));
	}

	public static int[] twoSum(int[] arr, int k) {
        // Validate input values
        if(arr == null || arr.length <= 1 || arr.length > 3 * 10000 || k< -1000 || k > 1000){
            return null;
        }

        // Traverse array from both sides
        int[] res = new int[] {-1, -1};
        int i = 0;
        int j = arr.length - 1;
        while(i < j){
            int s = arr[i] + arr[j];
            if(k == s){
                res[0] = i+1;
                res[1] = j+1;
                break;
            }
            else if(k > s){
                i++;
                while(i < j && arr[i] == arr[i+1] && arr[i]*2 != k){
                    i++;
                }
            }
            else if(k < s){
                j--;
                while(i < j && arr[j] == arr[j - 1] && arr[j]*2 != k){
                    j--;
                }
            }
        }

        return res;
    }

	public static int[] twoSum2(int[] numbers, int target) {
        int left = 0, right = numbers.length - 1;
        while (left < right) {
            int sum = numbers[left] + numbers[right];
            int mid = left + (right - left) / 2;
            if (sum > target)
                if (numbers[left] + numbers[mid] > target)
                    right = mid - 1;
                else
                    right--;
            else if (sum < target)
                if (numbers[mid] + numbers[right] < target)
                    left = mid + 1;
                else
                    left++;
            else
                return new int[] {left +1, right + 1};
        }
        return null;
    }

}

Add sum two in sorted array

Add sum two in sorted array


package de.philipphager.disclosure.util.text;

import android.os.Build;
import android.text.Html;
import android.text.Spanned;

public final class HtmlCompat {
  public static Spanned fromHtml(String source) {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
      return Html.fromHtml(source, Html.FROM_HTML_MODE_LEGACY);
    } else {
      return Html.fromHtml(source);
    }
  }

  private HtmlCompat() {
    // no instances
  }
}

Add helper class for HTML text formatting

Is used to transform HTML in string resources into formatted text
(spannable text) to include bold, italic text etc.


package com.fsck.k9.account;

import com.fsck.k9.Account.DeletePolicy;
import com.fsck.k9.mail.ConnectionSecurity;
import com.fsck.k9.mail.ServerSettings.Type;

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

/**
 * Deals with logic surrounding account creation.
 * <p/>
 * TODO Move much of the code from com.fsck.k9.activity.setup.* into here
 */
public class AccountCreator {

    private static Map<Type, DeletePolicy> defaults = new HashMap<Type, DeletePolicy>();

    static {
        defaults.put(Type.IMAP, DeletePolicy.ON_DELETE);
        defaults.put(Type.POP3, DeletePolicy.NEVER);
        defaults.put(Type.WebDAV, DeletePolicy.ON_DELETE);
    }

    public static DeletePolicy calculateDefaultDeletePolicy(Type type) {
        return defaults.get(type);
    }

    public static int getDefaultPort(ConnectionSecurity securityType, Type storeType) {
        switch (securityType) {
            case NONE:
            case STARTTLS_REQUIRED: {
                return storeType.defaultPort;
            }
            case SSL_TLS_REQUIRED: {
                return storeType.defaultTlsPort;
            }
        }

        throw new AssertionError("Unhandled ConnectionSecurity type encountered: " + securityType);
    }
}

package com.fsck.k9.account;

import com.fsck.k9.Account.DeletePolicy;
import com.fsck.k9.mail.ConnectionSecurity;
import com.fsck.k9.mail.ServerSettings.Type;

/**
 * Deals with logic surrounding account creation.
 * <p/>
 * TODO Move much of the code from com.fsck.k9.activity.setup.* into here
 */
public class AccountCreator {

    public static DeletePolicy calculateDefaultDeletePolicy(Type type) {
        switch (type) {
            case IMAP: {
                return DeletePolicy.ON_DELETE;
            }
            case POP3: {
                return DeletePolicy.NEVER;
            }
            case WebDAV: {
                return DeletePolicy.ON_DELETE;
            }
            case SMTP: {
                throw new IllegalStateException("Delete policy doesn't apply to SMTP");
            }
        }

        throw new AssertionError("Unhandled case: " + type);
    }

    public static int getDefaultPort(ConnectionSecurity securityType, Type storeType) {
        switch (securityType) {
            case NONE:
            case STARTTLS_REQUIRED: {
                return storeType.defaultPort;
            }
            case SSL_TLS_REQUIRED: {
                return storeType.defaultTlsPort;
            }
        }

        throw new AssertionError("Unhandled ConnectionSecurity type encountered: " + securityType);
    }
}

Use switch statement inside calculateDefaultDeletePolicy()

With this - at least in theory  - the JIT compiler can produce better code
than is possible with the static HashMap.


package org.slc.sli.modeling.rest;

import static org.junit.Assert.*;

import java.util.ArrayList;

import org.junit.Before;
import org.junit.Test;
import org.junit.internal.builders.NullBuilder;

public class LinkTest {
    private Link link; // class under test

    private static final String RESOURCE_TYPE = "resourceType";
    private static final String REL = "rel";
    private static final String REV = "rev";
    private static final ArrayList<Documentation> DOC = new ArrayList<Documentation>(0);

    @Before
    public void setup() throws Exception {
        link = new Link(RESOURCE_TYPE, REL, REV, DOC);
    }

    @Test (expected = NullPointerException.class)
    public void testNullResourceType() {
        new Link(null, REL, REV, DOC);
    }

    @Test (expected = NullPointerException.class)
    public void testNullRel() {
        new Link(RESOURCE_TYPE, null, REV, DOC);
    }

    @Test (expected = NullPointerException.class)
    public void testNullRev() {
        new Link(RESOURCE_TYPE, REL, null, DOC);
    }

    @Test (expected = NullPointerException.class)
    public void testNullDoc() {
        new Link(RESOURCE_TYPE, REL, REV, null);
    }

    @Test
    public void testGetResourceType() {
        assertEquals(RESOURCE_TYPE, link.getResourceType());
    }

    @Test
    public void testGetRelType() {
        assertEquals(REL, link.getRel());
    }

    @Test
    public void testGetRev() {
        assertEquals(REV, link.getRev());
    }

}

Add JUnit test for Link class in rest modeling module.


/*
 * Copyright 2016-2019 Talsma ICT
 *
 * 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 for common utilities not otherwise related to the core UML doclet.
 *
 * <ul>
 * <li>{@linkplain nl.talsmasoftware.umldoclet.util.FileUtils} for various non-standard
 * {@linkplain java.io.File} related functionality such as determining the relative path between
 * two files, etc.
 * <li>{@linkplain nl.talsmasoftware.umldoclet.util.UriUtils} for various non-standard
 * {@linkplain java.net.URI} related functionality such as adding path components or parameters
 * to an existing {@code URI}.
 * </ul>
 */
package nl.talsmasoftware.umldoclet.util;

Add package documentation to generic 'util' package

Signed-off-by: Sjoerd Talsma <1dafb4c4a7acdc6e1eca32ff35fda03e0e9cd976@talsma-ict.nl>


class ContinueForAll {
    public static void main(String[] args) {
	for (int i = 1; i <= 5; i = i + 1) {
	    System.out.println(0);
	    continue;
	    System.out.println(i);
	}
    }
}

Add continue for all example

Add continue for all example


package de.lmu.ifi.dbs.elki.datasource.filter;

import de.lmu.ifi.dbs.elki.data.SparseFloatVector;
import de.lmu.ifi.dbs.elki.data.type.SimpleTypeInformation;
import de.lmu.ifi.dbs.elki.data.type.TypeUtil;
import de.lmu.ifi.dbs.elki.data.type.VectorFieldTypeInformation;

/**
 * Class that turns sparse float vectors into a proper vector field, by setting
 * the maximum dimensionality for each vector.
 *
 * @author Erich Schubert
 */
public class SparseVectorFieldFilter extends AbstractConversionFilter<SparseFloatVector, SparseFloatVector> {
  /**
   * Maximum dimension
   */
  int maxdim = -1;

  /**
   * Constructor.
   */
  public SparseVectorFieldFilter() {
    super();
  }

  @Override
  protected boolean prepareStart(SimpleTypeInformation<SparseFloatVector> in) {
    return true;
  }

  @Override
  protected void prepareProcessInstance(SparseFloatVector obj) {
    maxdim = Math.max(maxdim, obj.getDimensionality());
  }

  @Override
  protected SparseFloatVector filterSingleObject(SparseFloatVector obj) {
    assert(maxdim > 0);
    obj.setDimensionality(maxdim);
    return obj;
  }

  @Override
  protected SimpleTypeInformation<? super SparseFloatVector> getInputTypeRestriction() {
    return TypeUtil.SPARSE_FLOAT_FIELD;
  }

  @Override
  protected SimpleTypeInformation<? super SparseFloatVector> convertedType(SimpleTypeInformation<SparseFloatVector> in) {
    return new VectorFieldTypeInformation<SparseFloatVector>(SparseFloatVector.class, maxdim);
  }
}

Add filter to turn sparse vectors into a vector field (of the same dimensionality!)


package org.t246osslab.easybuggy;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.t246osslab.easybuggy.utils.HTTPResponseCreator;

@SuppressWarnings("serial")
@WebServlet(urlPatterns = { "/test" })
public class TestServlet extends HttpServlet {

    protected void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {

        HTTPResponseCreator.createSimpleResponse(res, "Test", "Test!!");
    }
}

Add a servlet as template.

Add a servlet as template.


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

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

import org.jsmpp.PDUStringException;
import org.testng.annotations.Test;

/**
 * @author uudashr
 *
 */
public class OctetStringValidationTest {
    private static final String FULL_LENGTH_TEXT = "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor";
    private static final int MAX_SHORT_MESSAGE_LENGTH = 254;

    @Test
    public void zeroLength() throws Exception {
        String shortMessage = "";
        assertEquals(shortMessage.length(), 0);
        StringValidator.validateString(shortMessage.getBytes(), StringParameter.SHORT_MESSAGE);
    }

    @Test
    public void nonZeroBelow255Length() throws Exception {
        String shortMessage = "This is a simple message";
        assertTrue(shortMessage.length() > 0);
        assertTrue(shortMessage.length() <= MAX_SHORT_MESSAGE_LENGTH);
        StringValidator.validateString(shortMessage.getBytes(), StringParameter.SHORT_MESSAGE);
    }

    @Test
    public void fullLegth() throws Exception {
        assertEquals(FULL_LENGTH_TEXT.length(), MAX_SHORT_MESSAGE_LENGTH);
        StringValidator.validateString(FULL_LENGTH_TEXT.getBytes(), StringParameter.SHORT_MESSAGE);
    }

    @Test(expectedExceptions = PDUStringException.class)
    public void overLengthText() throws Exception {
        String shortMessage = FULL_LENGTH_TEXT + " ";
        assertTrue(shortMessage.length() > MAX_SHORT_MESSAGE_LENGTH);
        StringValidator.validateString(shortMessage.getBytes(), StringParameter.SHORT_MESSAGE);
    }
}

Add new test case for OctetString validation

git-svn-id: 8aef34885c21801cc977f98956a081c938212632@193 1678c8a9-8d33-0410-b0a4-d546c816ed44


package net.engin33r.luaspigot.lua.type;

import net.engin33r.luaspigot.lua.LinkedField;
import net.engin33r.luaspigot.lua.WeakType;
import org.bukkit.util.Vector;
import org.luaj.vm2.LuaValue;

/**
 * Utility type describing a vector.
 */
public class LuaVector extends WeakType {
    private Vector vec;
    private static LuaValue typeMetatable = LuaValue.tableOf();

    public LuaVector(Vector vec) {
        this.vec = vec;

        registerLinkedField("x", new LuaVector.XField(this));
        registerLinkedField("y", new LuaVector.YField(this));
        registerLinkedField("z", new LuaVector.ZField(this));
    }

    public LuaVector(double x, double y, double z) {
        this(new Vector(x, y, z));
    }

    @Override
    protected LuaValue getMetatable() {
        return typeMetatable;
    }

    @Override
    public String getName() {
        return "vector";
    }

    private class XField extends LinkedField<LuaVector> {
        public XField(LuaVector self) { super(self); }

        @Override
        public void update(LuaValue val) {
            vec.setX(val.checkdouble());
        }

        @Override
        public LuaValue query() {
            return LuaValue.valueOf(LuaVector.this.vec.getX());
        }
    }

    private class YField extends LinkedField<LuaVector> {
        public YField(LuaVector self) { super(self); }

        @Override
        public void update(LuaValue val) {
            vec.setY(val.checkdouble());
        }

        @Override
        public LuaValue query() {
            return LuaValue.valueOf(LuaVector.this.vec.getY());
        }
    }

    private class ZField extends LinkedField<LuaVector> {
        public ZField(LuaVector self) { super(self); }

        @Override
        public void update(LuaValue val) {
            vec.setZ(val.checkdouble());
        }

        @Override
        public LuaValue query() {
            return LuaValue.valueOf(LuaVector.this.vec.getZ());
        }
    }
}

Add utility class for vectors

Add utility class for vectors


/*
 * Zorbage: an algebraic data hierarchy for use in numeric processing.
 *
 * Copyright (C) 2016-2018 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.type.data;

import static org.junit.Assert.assertEquals;

import org.junit.Test;

import nom.bdezonia.zorbage.groups.G;
import nom.bdezonia.zorbage.sampling.IntegerIndex;
import nom.bdezonia.zorbage.type.algebra.Addition;
import nom.bdezonia.zorbage.type.algebra.Group;
import nom.bdezonia.zorbage.type.data.float64.real.Float64Member;
import nom.bdezonia.zorbage.type.data.universal.PrimitiveConversion;
import nom.bdezonia.zorbage.type.data.universal.PrimitiveConverter;

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

	private <T extends Group<T,U> & Addition<U>, U extends PrimitiveConversion>
		void test(T group)
	{
		Float64Member dbl = G.DBL.construct();
		U val1 = group.construct("1.4");
		U val2 = group.construct("5.3");
		U val3 = group.construct();
		group.add().call(val1, val2, val3);
		PrimitiveConverter.convert(new IntegerIndex(0), new IntegerIndex(0), new IntegerIndex(0), val3, dbl);
		assertEquals(6.7, dbl.v(), 0.01);
	}

	@Test
	public void testF16() {
		test(G.HLF);
	}

	@Test
	public void testF32() {
		test(G.FLT);
	}

	@Test
	public void testF64() {
		test(G.DBL);
	}
}

Define a simple test that exercises the 3 floating types


package de.cinovo.cloudconductor.api.interfaces;

import java.util.Map;

import javax.annotation.security.RolesAllowed;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;

import de.cinovo.cloudconductor.api.MediaType;

/**
 *
 * Copyright 2018 Cinovo AG

 *

 *
 * @author mweise
 *
 */
@Path("/serviceusages")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public interface IServiceUsage {

	/**
	 * @return map service -> serviceUsage (template -> package)
	 */
	@GET
	@Path("/")
	@RolesAllowed({"VIEW_CONFIGURATIONS", "EDIT_CONFIGURATIONS"})
	Map<String, Map<String, String>> getServiceUsages();

}

Add an interface for getting usage maps of all services.


package com.fasterxml.jackson.failing;

import com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.*;
import com.fasterxml.jackson.databind.introspect.AnnotatedMember;
import com.fasterxml.jackson.databind.introspect.AnnotatedParameter;
import com.fasterxml.jackson.databind.introspect.JacksonAnnotationIntrospector;

public class MultiArgConstructorTest extends BaseMapTest
{
    static class MultiArgCtorBean
    {
        protected int a, b;

        public MultiArgCtorBean(int a, int b) {
            this.a = a;
            this.b = b;
        }
    }

    /* Before JDK8, we won't have parameter names available, so let's
     * fake it before that...
     */
    @SuppressWarnings("serial")
    static class MyParamIntrospector extends JacksonAnnotationIntrospector
    {
        @Override
        public String findImplicitPropertyName(AnnotatedMember param) {
            if (param instanceof AnnotatedParameter) {
                AnnotatedParameter ap = (AnnotatedParameter) param;
                switch (ap.getIndex()) {
                case 0: return "a";
                case 1: return "b";
                default:
                    return "param"+ap.getIndex();
                }
            }
            return super.findImplicitPropertyName(param);
        }
    }

    /*
    /**********************************************************************
    /* Test methods
    /**********************************************************************
     */

    public void testMultiArgVisible() throws Exception
    {
        final ObjectMapper mapper = new ObjectMapper();
        mapper.setAnnotationIntrospector(new MyParamIntrospector());
        MultiArgCtorBean bean = mapper.readValue(aposToQuotes("{'b':13,  'a':-99}"),
                MultiArgCtorBean.class);
        assertNotNull(bean);
        assertEquals(13, bean.b);
        assertEquals(-99, bean.a);
    }

    // but let's also ensure that it is possible to prevent use of that constructor
    // with different visibility
    public void testMultiArgNotVisible() throws Exception
    {
        final ObjectMapper mapper = new ObjectMapper();
        mapper.setAnnotationIntrospector(new MyParamIntrospector());
        mapper.setVisibility(PropertyAccessor.CREATOR, Visibility.NONE);
        try {
            /*MultiArgCtorBean bean =*/ mapper.readValue(aposToQuotes("{'b':13,  'a':-99}"),
                MultiArgCtorBean.class);
            fail("Should not have passed");
        } catch (JsonMappingException e) {
            verifyException(e, "No suitable constructor");
        }
    }
}

Add a (failing) test for implicit multi-arg-creator test, support to be added in 2.6


package com.yahoo.abicheck;

import static org.junit.Assert.assertEquals;

import com.yahoo.abicheck.collector.Util;
import java.util.Arrays;
import org.junit.Test;
import org.objectweb.asm.Opcodes;

public class AccessConversionTest {

  @Test
  public void testClassFlags() {
    // ACC_SUPER should be ignored
    assertEquals(
        Arrays.asList("public", "abstract"),
        Util.convertAccess(
            Opcodes.ACC_PUBLIC | Opcodes.ACC_SUPER | Opcodes.ACC_ABSTRACT,
            Util.classFlags));
  }

  @Test
  public void testMethodFlags() {
    // ACC_DEPRECATED should be ignored
    assertEquals(
        Arrays.asList("protected", "varargs"),
        Util.convertAccess(
            Opcodes.ACC_PROTECTED | Opcodes.ACC_VARARGS | Opcodes.ACC_DEPRECATED,
            Util.methodFlags));
  }

  @Test
  public void testFieldFlags() {
    assertEquals(
        Arrays.asList("private", "volatile"),
        Util.convertAccess(
            Opcodes.ACC_PRIVATE | Opcodes.ACC_VOLATILE,
            Util.fieldFlags));
  }

  @Test(expected = IllegalArgumentException.class)
  public void testUnsupportedFlags() {
    // ACC_MODULE is not a valid flag for fields
    Util.convertAccess(Opcodes.ACC_MODULE, Util.fieldFlags);
  }
}

Add some initial unit tests.

Add some initial unit tests.


package com.custardsource.parfait;

import java.util.Collection;

import com.google.common.collect.Lists;

public class CompositeCounter implements Counter {
    private final Collection<Counter> counters;

    public CompositeCounter(Collection<Counter> counters) {
        this.counters = Lists.newArrayList(counters);
    }

    @Override
    public void inc() {
        for(Counter counter : counters) {
            counter.inc();
        }
    }

    @Override
    public void inc(long increment) {
        for(Counter counter : counters) {
            counter.inc(increment);
        }
    }
}

Add composite counter to enable easier updates. Getting there!


package io.sommers.packmode.compat.crafttweaker;

import crafttweaker.annotations.ZenRegister;
import io.sommers.packmode.api.PackModeAPI;
import stanhebben.zenscript.annotations.ZenClass;
import stanhebben.zenscript.annotations.ZenMethod;

@ZenRegister
@ZenClass("mods.packmode.PackModeInfo")
public class PackModeInfo {
    @ZenMethod
    public String getPackMode() {
        return PackModeAPI.getInstance().getCurrentPackMode();
    }

    @ZenMethod
    public boolean matchPackMode(String packmode) {
        return PackModeAPI.getInstance().getCurrentPackMode().equals(packmode);
    }

    @ZenMethod
    public String[] getAcceptablePackModes() {
        return PackModeAPI.getInstance().getPackModes().toArray(new String[0]);
    }
}

Add ZenClass for getting info on current pack mode


/*
 * Copyright 2017 Red Hat, Inc. and/or its affiliates.
 *
 * 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.jboss.perspicuus.storage;

import org.apache.avro.Schema;
import org.apache.lucene.analysis.TokenStream;
import org.apache.lucene.analysis.Tokenizer;
import org.apache.lucene.analysis.core.LowerCaseFilter;
import org.apache.lucene.analysis.core.StopFilter;
import org.apache.lucene.analysis.standard.StandardFilter;
import org.apache.lucene.analysis.standard.StandardTokenizer;
import org.apache.lucene.analysis.util.StopwordAnalyzerBase;

import java.io.IOException;
import java.io.Reader;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.List;

/**
 * Custom Analyzer to help make Avro's Schema structure indexable by Hibernate Search i.e. lucene.
 *
 * Currently unused, but may be a more flexible approach than the exiting AvroSchemaStringBridge.
 *
 * @since 2017-03
 * @author Jonathan Halliday (jonathan.halliday@redhat.com)
 */
public class AvroSchemaAnalyzer extends StopwordAnalyzerBase {

    // should probably be a subclass of StandardAnalyzer, but that's final :-(

    @Override
    protected TokenStreamComponents createComponents(final String fieldName) {

        final Tokenizer src = new StandardTokenizer();

        TokenStream tok = new StandardFilter(src);
        tok = new LowerCaseFilter(tok);
        tok = new StopFilter(tok, stopwords);

        return new TokenStreamComponents(src, tok) {
            @Override
            protected void setReader(final Reader reader) throws IOException {

                char[] array = new char[4 * 1024];
                StringBuilder buffer = new StringBuilder();
                int count;
                while ((count = reader.read(array, 0, array.length)) != -1) {
                    buffer.append(array, 0, count);
                }

                String data = buffer.toString();

                if(data.startsWith("{")) {

                    Schema avroSchema = new Schema.Parser().parse(data);
                    List<String> tokens = new ArrayList<>();

                    tokens.add(avroSchema.getName());

                    for (Schema.Field field : avroSchema.getFields()) {
                        tokens.add(field.name());
                    }

                    String result = String.join(" ", tokens);
                    data = result;
                }

                super.setReader( new StringReader(data) );
            }
        };
    }
}

Add custom Analyzer for indexing schema objects.


package de.philipphager.disclosure.util.device;

import android.os.Build;

public final class DeviceFeatures {
  public static boolean supportsRuntimePermissions() {
    return Build.VERSION.SDK_INT >= Build.VERSION_CODES.M;
  }

  private DeviceFeatures() {
    // Not instances.
  }
}

Add helper class for Android version features


package fr.insee.pogues.jersey;

import fr.insee.pogues.webservice.rest.PoguesException;
import fr.insee.pogues.webservice.rest.PoguesExceptionMapper;
import fr.insee.pogues.webservice.rest.RestMessage;
import org.junit.Before;
import org.junit.Test;

import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

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

public class TetsPoguesExceptionMapper {

    PoguesExceptionMapper mapper;

    @Before
    public void setUp(){
        mapper = spy(new PoguesExceptionMapper());
    }

    @Test
    public void toResponse(){
        PoguesException e = new PoguesException(418, "I'm a teapot", "Strange things happen");
        RestMessage m = e.toRestMessage();
        Response resp = mapper.toResponse(e);
        assertEquals(MediaType.APPLICATION_JSON_TYPE, resp.getMediaType());
        assertEquals(m.getMessage(), ((RestMessage)resp.getEntity()).getMessage());
        assertEquals(m.getDetails(), ((RestMessage)resp.getEntity()).getDetails());
        assertEquals(418, resp.getStatus());
    }
}

Add Jersey Exception Mapper test

Add Jersey Exception Mapper test


package com.yuzhouwan.hacker.netty;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import org.junit.Assert;
import org.junit.Test;

import java.nio.charset.StandardCharsets;

/**
 * Copyright @ 2020 yuzhouwan.com
 * All right reserved.
 * Function：Netty Test
 *
 * @author Benedict Jin
 * @see Netty：从入门到实践
 * @since 2020/5/7
 */
public class NettyTest {

    @Test
    public void string2ByteBuf() {
        String s = "yuzhouwan.com";
        final ByteBuf buf = Unpooled.wrappedBuffer(s.getBytes(StandardCharsets.UTF_8));
        byte[] bytes = new byte[buf.readableBytes()];
        buf.readBytes(bytes);
        Assert.assertEquals(s, new String(bytes, StandardCharsets.UTF_8));
    }
}

Add a test case about netty

Add a test case about netty


package edu.cmu.sv.ws.ssnoc.test;

import static org.junit.Assert.*;

import java.sql.Timestamp;

import javax.ws.rs.core.Response;

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

import edu.cmu.sv.ws.ssnoc.dto.Message;
import edu.cmu.sv.ws.ssnoc.dto.User;
import edu.cmu.sv.ws.ssnoc.rest.MessageService;
import edu.cmu.sv.ws.ssnoc.rest.UserGroupsService;
import edu.cmu.sv.ws.ssnoc.rest.UserService;

public class SocialNetworkAnalysisTest {

	@Before
	public void tearDown() throws Exception {
	}

	@Test
	public void test01_checkUserCount() {
		// Add multiple users
		for (int i = 0; i < 5; i++) {
			User user = new User();
			user.setUserName("user" + i);
			user.setPassword("1234");

			UserService userService = new UserService();
			userService.addUser(user);
		}

		assertEquals(5, userClusters.size());
	}

	@Test
	public void test02_checkCloseUser(){
		Time time = new Time();

		// send messages from user1 to user3 and user5

		// send messages from user5 to user3

		// check user1 is close to user2 and user4
		// Check user3 is close to user2 and user4 as well
		// Check user5 is close to user2 and user4 as well
		// Check user2 is close to user4

		// check user1 is NOT close to user3 and user5
		// check user5 is NOT close to user3

		// Response response = UserGroupsService.add("foo", msg);
		// assertEquals(1, userClusters.size());
		//
		// MessageService msgService = new MessageService();
		// Response response = msgService.addWallMessage("foo", msg);
		// assertEquals(((Message)response.getEntity()).getContent(),
		// "test test lloyd owes a me a beer");
	}

}

Add test case for Social Network Analysis


package de.retest.recheck;

import java.io.File;

import de.retest.recheck.persistence.FileNamer;

public class GradleConformFileNamerStrategy implements FileNamerStrategy {

    public static final String DEFAULT_RETEST_WORKSPACE_PATH = "src/test/resources/retest/";
    public static final String DEFAULT_RETEST_TESTREPORTS_PATH = "build/test-results/test";

    @Override
    public FileNamer createFileNamer( final String... baseNames ) {
        return new FileNamer() {

            @Override
            public File getFile( final String extension ) {
                final String baseName = String.join( "/", baseNames );
                return new File( DEFAULT_RETEST_WORKSPACE_PATH + File.separator
                        + baseName + extension );
            }

            @Override
            public File getResultFile( final String extension ) {
                final String baseName = String.join( "/", baseNames );
                return new File( DEFAULT_RETEST_TESTREPORTS_PATH + File.separator
                        + baseName + extension );
            }
        };
    }

    @Override
    public String getTestClassName() {
        final StackTraceElement testMethodStack = TestCaseFinder.findTestCaseMethodInStack();
        if ( testMethodStack != null ) {
            return testMethodStack.getClassName();
        }
        throw new RuntimeException( "Couldn't identify test method in call stack. Use explicit namer!" );
    }

    @Override
    public String getTestMethodName() {
        final StackTraceElement testMethodStack = TestCaseFinder.findTestCaseMethodInStack();
        if ( testMethodStack != null ) {
            return testMethodStack.getMethodName();
        }
        throw new RuntimeException( "Couldn't identify test method in call stack. Use explicit namer!" );
    }
}

Add a gradle compatible file namer

Add a gradle compatible file namer


package br.com.alura.agenda.retrofit;

import retrofit2.Retrofit;
import retrofit2.converter.jackson.JacksonConverterFactory;

public class RetrofitInicializador {
    private final Retrofit retrofit;

    public RetrofitInicializador() {
        retrofit = new Retrofit.Builder()
                .baseUrl("http://192.168.25.8:8080/api/")
                .addConverterFactory(JacksonConverterFactory.create())
                .build();
    }
}

Add Retrofit with Jackson converter to handle http requests


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

import java.util.Set;

import org.apache.commons.pool2.impl.TestGenericObjectPool.SimpleFactory;
import org.junit.Assert;
import org.junit.Test;

public class TestDefaultPooledObjectInfo {

    @Test
    public void testTiming() throws Exception {
        GenericObjectPool<String> pool =
                new GenericObjectPool<String>(new SimpleFactory());

        long t1 = System.currentTimeMillis();

        Thread.sleep(50);
        String s1 = pool.borrowObject();
        Thread.sleep(50);

        long t2 = System.currentTimeMillis();

        Thread.sleep(50);
        pool.returnObject(s1);
        Thread.sleep(50);

        long t3 = System.currentTimeMillis();

        Thread.sleep(50);
        s1 = pool.borrowObject();
        Thread.sleep(50);

        long t4 = System.currentTimeMillis();

        Set<DefaultPooledObjectInfo> strings = pool.listAllObjects();

        Assert.assertEquals(1, strings.size());

        DefaultPooledObjectInfo s1Info = strings.iterator().next();

        Assert.assertTrue(s1Info.getCreateTime() > t1);
        Assert.assertTrue(s1Info.getCreateTime() < t2);

        Assert.assertTrue(s1Info.getLastReturnTime() > t2);
        Assert.assertTrue(s1Info.getLastReturnTime() < t3);

        Assert.assertTrue(s1Info.getLastBorrowTime() > t3);
        Assert.assertTrue(s1Info.getLastBorrowTime() < t4);
    }

    @Test
    public void testGetPooledObjectType() throws Exception {
        GenericObjectPool<String> pool =
                new GenericObjectPool<String>(new SimpleFactory());

        pool.borrowObject();

        Set<DefaultPooledObjectInfo> strings = pool.listAllObjects();

        Assert.assertEquals(1, strings.size());

        DefaultPooledObjectInfo s1Info = strings.iterator().next();

        Assert.assertEquals(String.class.getName(),
                s1Info.getPooledObjectType());
    }

    @Test
    public void testGetPooledObjectToString() throws Exception {
        GenericObjectPool<String> pool =
                new GenericObjectPool<String>(new SimpleFactory());

        String s1 = pool.borrowObject();

        Set<DefaultPooledObjectInfo> strings = pool.listAllObjects();

        Assert.assertEquals(1, strings.size());

        DefaultPooledObjectInfo s1Info = strings.iterator().next();

        Assert.assertEquals(s1, s1Info.getPooledObjectToString());
    }
}

Add some tests for DefaultPooledObjectInfo that currently has zero coverage.

git-svn-id: a66ef3f0e6c00b14098e182847b4bd646263fa09@1538412 13f79535-47bb-0310-9956-ffa450edef68


package com.couchbase.devguide;

import com.couchbase.client.java.Bucket;
import com.couchbase.client.java.Cluster;
import com.couchbase.client.java.CouchbaseCluster;
import com.couchbase.client.java.env.CouchbaseEnvironment;
import com.couchbase.client.java.env.DefaultCouchbaseEnvironment;

/**
 * This example shows how to connect to a couchbase server EE cluster using
 * client certificate authentication.
 *
 * Please make sure to follow the proper server side documentation on how to
 * import the certifactes into the server and set up the Java keystore.
 *
 * https://developer.couchbase.com/documentation/server/current/security/security-x509certsintro.html
 */
public class ConnectingCertAuth {

    public static void main(String... args) {
        CouchbaseEnvironment environment = DefaultCouchbaseEnvironment.builder()
            .sslEnabled(true)
            .certAuthEnabled(true)
            .sslKeystoreFile("/path/to/keystore")
            .sslKeystorePassword("password")
            .sslTruststoreFile("/path/to/truststore") // you can also pack it all in just the keystore
            .sslTruststorePassword("password")
            .build();

        Cluster cluster = CouchbaseCluster.create(environment, "127.0.0.1");
        // IMPORTANT: do NOT call cluster.authenticate() since this is part of the cert auth
        Bucket bucket = cluster.openBucket("travel-sample");

        // perform operations here...
        bucket.get("mydoc");
    }

}

Add example for client cert auth java

Add example for client cert auth java


package com.dylanvann.fastimage;

import android.graphics.drawable.Drawable;

import com.bumptech.glide.load.DataSource;
import com.bumptech.glide.load.engine.GlideException;
import com.bumptech.glide.request.RequestListener;
import com.bumptech.glide.request.target.ImageViewTarget;
import com.bumptech.glide.request.target.Target;
import com.facebook.react.bridge.WritableNativeMap;
import com.facebook.react.uimanager.ThemedReactContext;
import com.facebook.react.uimanager.events.RCTEventEmitter;

public class FastImageRequestListener implements RequestListener<Drawable> {
    public static final String REACT_ON_ERROR_EVENT = "onFastImageError";
    public static final String REACT_ON_LOAD_EVENT = "onFastImageLoad";
    public static final String REACT_ON_LOAD_END_EVENT = "onFastImageLoadEnd";
    private static String key = null;

    public FastImageRequestListener(String key) {
        this.key = key;
    }

    @Override
    public boolean onLoadFailed(@android.support.annotation.Nullable GlideException e, Object model, Target<Drawable> target, boolean isFirstResource) {
        OkHttpProgressGlideModule.forget(key);
        if (!(target instanceof ImageViewTarget)) {
            return false;
        }
        ImageViewWithUrl view = (ImageViewWithUrl) ((ImageViewTarget) target).getView();
        ThemedReactContext context = (ThemedReactContext) view.getContext();
        RCTEventEmitter eventEmitter = context.getJSModule(RCTEventEmitter.class);
        int viewId = view.getId();
        eventEmitter.receiveEvent(viewId, REACT_ON_ERROR_EVENT, new WritableNativeMap());
        eventEmitter.receiveEvent(viewId, REACT_ON_LOAD_END_EVENT, new WritableNativeMap());
        return false;
    }

    @Override
    public boolean onResourceReady(Drawable resource, Object model, Target<Drawable> target, DataSource dataSource, boolean isFirstResource) {
        if (!(target instanceof ImageViewTarget)) {
            return false;
        }
        ImageViewWithUrl view = (ImageViewWithUrl) ((ImageViewTarget) target).getView();
        ThemedReactContext context = (ThemedReactContext) view.getContext();
        RCTEventEmitter eventEmitter = context.getJSModule(RCTEventEmitter.class);
        int viewId = view.getId();
        eventEmitter.receiveEvent(viewId, REACT_ON_LOAD_EVENT, new WritableNativeMap());
        eventEmitter.receiveEvent(viewId, REACT_ON_LOAD_END_EVENT, new WritableNativeMap());
        return false;
    }
}

Add a custom request listener class

Add a custom request listener class


/*
 * FindBugs - Find bugs in Java programs
 * Copyright (C) 2003, University of Maryland
 *
 * 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 edu.umd.cs.findbugs.detect;
import edu.umd.cs.findbugs.*;
import java.util.*;
import java.io.PrintStream;
import org.apache.bcel.classfile.*;
import java.util.zip.*;
import java.io.*;

import edu.umd.cs.pugh.visitclass.DismantleBytecode;
import edu.umd.cs.pugh.visitclass.Constants2;

public class FindFieldSelfAssignment extends BytecodeScanningDetector implements   Constants2 {
    private BugReporter bugReporter;
    int state;

  public FindFieldSelfAssignment(BugReporter bugReporter) {
	this.bugReporter = bugReporter;
  }

   JavaClass jClass;
   public void visit(JavaClass obj) {
	jClass = obj;
	}
   public void visit(Code obj) {
	state = 0;
	super.visit(obj);
	}

    String f;
    public void sawOpcode(int seen) {

	switch (state) {
	case 0:
		if (seen == ALOAD_0)
			state = 1;
		break;
	case 1:
		if (seen == ALOAD_0)
			state = 2;
		else
			state = 0;
		break;
	case 2:
		if (seen == GETFIELD) {
			state = 3;
			f = refConstant;
			}
		else
			state = 0;
		break;
	case 3:
		if (seen == PUTFIELD && refConstant.equals(f)) {

                                bugReporter.reportBug(new BugInstance("SA_FIELD_SELF_ASSIGNMENT", NORMAL_PRIORITY)
                                        .addClass(className)
                                        .addMethod(className, methodName, methodSig)
                                        .addField(betterClassConstant, nameConstant,
						betterSigConstant, false)
                                        .addSourceLine(this)

					);
			}
		state = 0;
		}
	}

}

Check for self assignment of fields

Check for self assignment of fields

git-svn-id: e7d6bde23f017c9ff4efd468d79d66def666766b@1765 eae3c2d3-9b19-0410-a86e-396b6ccb6ab3


/*
Copyright 2012 Selenium committers
Copyright 2012 Software Freedom Conservancy

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.thoughtworks.selenium.thirdparty;

import com.thoughtworks.selenium.InternalSelenseTestBase;

import org.testng.annotations.Test;

public class YahooHttpsTest extends InternalSelenseTestBase {

  @Test(dataProvider = "system-properties")
  public void testYahoo() throws Exception {
    // this site has **two** HTTPS hosts (akamai and yahoo), so it's a good test of the new
    // multi-domain keystore support we just added
    selenium
        .open("https://login11.marketingsolutions.yahoo.com/adui/signin/loadSignin.do?d=U2FsdGVkX1_evOPYuoCCKbeDENMTzoQ6O.oTzifl7TwsO8IqXh6duToE2tI2&p=11&s=21");
  }

}

/*
Copyright 2012 Selenium committers
Copyright 2012 Software Freedom Conservancy

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.thoughtworks.selenium.thirdparty;

import com.thoughtworks.selenium.InternalSelenseTestBase;

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

public class YahooHttpsTest extends InternalSelenseTestBase {

  @After
  public void resetTimeout() {
    selenium.setTimeout("30000");
  }

  @Test
  public void testYahoo() throws Exception {
    selenium.setTimeout("120000");

    // this site has **two** HTTPS hosts (akamai and yahoo), so it's a good test of the new
    // multi-domain keystore support we just added
    selenium
        .open(
            "https://login11.marketingsolutions.yahoo.com/adui/signin/loadSignin.do?d=U2FsdGVkX1_evOPYuoCCKbeDENMTzoQ6O.oTzifl7TwsO8IqXh6duToE2tI2&p=11&s=21");
  }

}

SimonStewart: Convert the https test that we never run to use junit.

r17194