package leetcode.longest_consecutive_sequence;

import java.util.HashMap;

public class Solution {
	public static class Interval {
		public int start;
		public int end;
		public Interval() { start = 0; end = 0; }
		public Interval(int s, int e) { start = s; end = e; }
	}

	public int longestConsecutive(int[] num) {
    	HashMap<Integer, Interval> leftMap = new HashMap<Integer, Interval>();
    	HashMap<Integer, Interval> rightMap = new HashMap<Integer, Interval>();
    	for(int x : num){
    		Interval asLeft = leftMap.get(x);
    		Interval asRight = rightMap.get(x);
    		if(asLeft != null || asRight != null){
    			continue;
    		}
    		Interval leftIvl = rightMap.get(x - 1);
    		Interval rightIvl = leftMap.get(x + 1);
    		if(leftIvl == null && rightIvl == null){
    			Interval ivl = new Interval(x, x);
    			leftMap.put(x, ivl);
    			rightMap.put(x, ivl);
    		}else if(leftIvl != null && rightIvl == null){
    			leftIvl.end = x;
    			rightMap.remove(x - 1);
    			rightMap.put(x, leftIvl);
    		}else if(leftIvl == null && rightIvl != null){
    			rightIvl.start = x;
    			leftMap.remove(x + 1);
    			leftMap.put(x, rightIvl);
    		}else{
    			Interval ivl = leftIvl;
    			leftMap.remove(x + 1);
    			rightMap.remove(x - 1);
    			ivl.end = rightIvl.end;
    			leftMap.put(ivl.start, ivl);
    			rightMap.put(ivl.end, ivl);
    		}
    	}
    	int maxlength = 0;
    	for(Interval ivl : leftMap.values()){
    		int length = ivl.end - ivl.start + 1;
    		if(length > maxlength){
    			maxlength = length;
    		}
    	}
    	return maxlength;
    }

	public static void main(String[] args){
		System.err.println(new Solution().longestConsecutive(new int[]{2147483646,-2147483647,0,2,2147483644,-2147483645,2147483645}));
	}
}

Add java solution for 128. Longest Consecutive Sequence

128. Longest Consecutive Sequence: https://leetcode.com/problems/longest-consecutive-sequence/


package com.gmail.nossr50.events.experience;

import org.bukkit.entity.Player;

import com.gmail.nossr50.skills.utilities.SkillType;

/**
 * Called when a user levels up in a skill
 */
public class McMMOPlayerLevelUpEvent extends McMMOPlayerExperienceEvent {
    private int levelsGained;

    public McMMOPlayerLevelUpEvent(Player player, SkillType skill) {
        super(player, skill);
        this.levelsGained = 1;    // Always 1 for now as we call in the loop where the levelups are calculated, could change later!
    }

    /**
     * @return The number of levels gained in this event
     */
    public int getLevelsGained() {
        return levelsGained;
    }
}

package com.gmail.nossr50.events.experience;

import org.bukkit.entity.Player;

import com.gmail.nossr50.skills.utilities.SkillType;

/**
 * Called when a user levels up in a skill
 */
public class McMMOPlayerLevelUpEvent extends McMMOPlayerExperienceEvent {
    private int levelsGained;

    public McMMOPlayerLevelUpEvent(Player player, SkillType skill) {
        super(player, skill);
        this.levelsGained = 1;
    }

    public McMMOPlayerLevelUpEvent(Player player, SkillType skill, int levelsGained) {
        super(player, skill);
        this.levelsGained = levelsGained;
    }

    /**
     * @return The number of levels gained in this event
     */
    public int getLevelsGained() {
        return levelsGained;
    }

    /**
     * @param levelsGained int number of levels gained in this event
     */
    public void setLevelsGained(int levelsGained) {
        this.levelsGained = levelsGained;
    }
}

Add constructor for adding multiple levels at once. Need to work out how to handle level-ups in order for this to be properly cancelled, however.


package com.algolia.search.saas;

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

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

import static org.junit.Assert.assertTrue;

public class NetworkTest {

  private APIClient client;

  @Before
  public void init() {
    String applicationID = System.getenv("ALGOLIA_APPLICATION_ID");
    String apiKey = System.getenv("ALGOLIA_API_KEY");
    Assume.assumeFalse("You must set environement variables ALGOLIA_APPLICATION_ID and ALGOLIA_API_KEY to run the tests.", applicationID == null || apiKey == null);

    List<String> hosts = new ArrayList<String>();
    hosts.add("java-dsn.algolia.biz");
    hosts.add(applicationID + "-1.algolianet.com");

    client = new APIClient(applicationID, apiKey, hosts, hosts);
  }

  @Test
  public void shouldHandleTimeoutsInDns() throws AlgoliaException {
    Long start = System.currentTimeMillis();
    client.listIndexes();
    assertTrue((System.currentTimeMillis() - start) < 3 * 1000);
  }

}

Add test for DNS timeout

Add test for DNS timeout


package io.github.saidie.plantuml_api;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.security.core.userdetails.*;

@Service
public class UserService implements UserDetailsService {
    @Autowired
    private AccountRepository accountRepository;

    public UserDetails loadUserByUsername(String username) {
        Account account = accountRepository.findByUsername(username);

        return new User(username, account.getPassword(), null);
    }
}

Add user service for Spring Security

Add user service for Spring Security


package io.quarkus.jdbc.postgresql.runtime.graal;

import java.lang.reflect.Method;
import java.util.concurrent.atomic.AtomicBoolean;

import javax.xml.transform.dom.DOMResult;

import org.graalvm.nativeimage.hosted.Feature;
import org.graalvm.nativeimage.hosted.RuntimeReflection;
import org.postgresql.core.BaseConnection;

import com.oracle.svm.core.annotate.AutomaticFeature;

@AutomaticFeature
public final class SQLXLMFeature implements Feature {

    private final AtomicBoolean triggered = new AtomicBoolean(false);

    /**
     * To set this, add `-J-Dio.quarkus.jdbc.postgresql.graalvm.diagnostics=true` to the native-image parameters
     */
    private static final boolean log = Boolean.getBoolean("io.quarkus.jdbc.postgresql.graalvm.diagnostics");

    @Override
    public void beforeAnalysis(BeforeAnalysisAccess access) {
        Class<?> pgSQLXMLClass = access.findClassByName("io.quarkus.jdbc.postgresql.runtime.graal.PgSQLXML");
        try {
            //Only if this method is ever invoked, then it's possible that field {@link PgSQLXML#domResult }
            //is ever non-null, and only in that case the XML parsing facilities pulled in by the driver
            //end up being necessary.
            final Method triggerMethod = pgSQLXMLClass.getMethod("setResult", Class.class);
            access.registerReachabilityHandler(this::identifiedXMLProcessingInDriver, triggerMethod);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    private void identifiedXMLProcessingInDriver(DuringAnalysisAccess duringAnalysisAccess) {
        final boolean needsEnablingYet = triggered.compareAndSet(false, true);
        if (needsEnablingYet) {
            if (log) {
                System.out.println(
                        "Quarkus's automatic feature for GraalVM native images: enabling support for XML processing in the PosgreSQL JDBC driver");
            }
            enableDomXMLProcessingInDriver(duringAnalysisAccess);
        }
    }

    private void enableDomXMLProcessingInDriver(DuringAnalysisAccess duringAnalysisAccess) {
        final Class<?> classByName = duringAnalysisAccess.findClassByName("io.quarkus.jdbc.postgresql.runtime.graal.DomHelper");
        try {
            final Method method = classByName.getMethod("reallyProcessDomResult", DOMResult.class, BaseConnection.class);
            RuntimeReflection.register(method);
        } catch (NoSuchMethodException e) {
            throw new RuntimeException(e);
        }
    }

}

Introduce an AutomaticFeature for jdbc-postgresql enabling XML processing capabilities only when required


package algorithms.dp;

/**
 * Question: http://www.geeksforgeeks.org/count-ways-reach-nth-stair/
 *
 * @author Sudharsanan Muralidharan
 */
public class CountWaysToReachNStairs {
  public int countWays(int n, int m) {
    return countWays(n, m, new int[n + 1]);
  }

  private int countWays(int n, int m, int[] results) {
    if (n < 0) {
      return 0;
    } else if (n == 0) {
      return 1;
    } else if (results[n] == 0) {
      for (int i = 1; i <= m; i++) {
        results[n] += countWays((n - i), m, results);
      }
    }
    return results[n];
  }
}

Add memoized solution for count ways to reach nth stair


package dr.evomodelxml.tree;

import dr.evolution.tree.Tree;
import dr.evomodel.tree.TreeHeightStatistic;
import dr.evomodel.tree.TreeModel;
import dr.inference.model.Statistic;
import dr.xml.*;

/**
 * Joseph Heled
 */
public class TreeHeightStatisticParser extends AbstractXMLObjectParser {

    public static final String TREE_HEIGHT_STATISTIC = "treeHeightStatistic";

        public String getParserName() {
            return TREE_HEIGHT_STATISTIC;
        }

        public Object parseXMLObject(XMLObject xo) throws XMLParseException {

            final String name = xo.getAttribute(Statistic.NAME, xo.getId());
            final Tree tree = (Tree) xo.getChild(Tree.class);

            return new TreeHeightStatistic(name, tree);
        }

        //************************************************************************
        // AbstractXMLObjectParser implementation
        //************************************************************************

        public String getParserDescription() {
            return "A statistic that returns the height of the tree";
        }

        public Class getReturnType() {
            return TreeHeightStatistic.class;
        }

        public XMLSyntaxRule[] getSyntaxRules() {
            return rules;
        }

        private final XMLSyntaxRule[] rules = {
                AttributeRule.newStringRule(Statistic.NAME, true),
                new ElementRule(TreeModel.class),
        };
}

Make tree height statistic available

Make tree height statistic available


package com.architecting.ch11;

import java.util.List;
import java.util.concurrent.atomic.AtomicLong;

import org.apache.flume.Context;
import org.apache.flume.Event;
import org.apache.flume.interceptor.Interceptor;

public class FlumeInterceptor implements Interceptor {
  private final String headerKey;
  private static final String CONF_HEADER_KEY = "header";
  private static final String DEFAULT_HEADER = "count";
  private final AtomicLong currentCount;

  private FlumeInterceptor(Context ctx) {
    headerKey = ctx.getString(CONF_HEADER_KEY, DEFAULT_HEADER);
    currentCount = new AtomicLong(0);
  }

  @Override
  public void initialize() {
    // No op
  }

  @Override
  public Event intercept(final Event event) {
    long count = currentCount.incrementAndGet();
    event.getHeaders().put(headerKey, String.valueOf(count));
    return event;
  }

  @Override
  public List<Event> intercept(final List<Event> events) {
    for (Event e : events) {
      intercept(e); // Ignore the return value; the event is modified in place
    }
    return events;
  }

  @Override
  public void close() {
    // No op
  }

  public static class FlumeInterceptorBuilder implements Interceptor.Builder {
    private Context ctx;

    @Override
    public Interceptor build() {
      return new FlumeInterceptor(ctx);
    }

    @Override
    public void configure(Context context) {
      this.ctx = context;
    }
  }
}

Ch11: Change class name, add imports, re-format.


package org.bitreserve.bitreserve_android_sdk.test.integration.model.card;

import junit.framework.Assert;

import org.bitreserve.bitreserve_android_sdk.model.card.CardRequest;
import org.junit.Test;
import org.junit.runner.RunWith;

import android.support.test.runner.AndroidJUnit4;
import android.test.suitebuilder.annotation.SmallTest;

/**
 * CardRequest integration tests.
 */

@RunWith(AndroidJUnit4.class)
@SmallTest
public class CardRequestTest {

    @Test
    public void getLabelShouldReturnTheLabel() {
        CardRequest cardRequest = new CardRequest("foo", "bar");

        Assert.assertEquals(cardRequest.getLabel(), "foo");
    }

    @Test
    public void getCurrencyShouldReturnTheCurrency() {
        CardRequest cardRequest = new CardRequest("foo", "bar");

        Assert.assertEquals(cardRequest.getCurrency(), "bar");
    }

}

Add tests to the card request model

Add tests to the card request model


/*
 * #%L
 * ImageJ software for multidimensional image processing and analysis.
 * %%
 * Copyright (C) 2009 - 2014 Board of Regents of the University of
 * Wisconsin-Madison, Broad Institute of MIT and Harvard, and Max Planck
 * Institute of Molecular Cell Biology and Genetics.
 * %%
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * 1. Redistributions of source code must retain the above copyright notice,
 *    this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright notice,
 *    this list of conditions and the following disclaimer in the documentation
 *    and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 * #L%
 */

package net.imagej.legacy;

import org.scijava.app.AbstractApp;
import org.scijava.app.App;
import org.scijava.plugin.Plugin;

/**
 * Application metadata about ImageJ 1.x.
 *
 * @author Curtis Rueden
 * @see org.scijava.app.AppService
 */
@Plugin(type = App.class, name = LegacyImageJApp.NAME)
public class LegacyImageJApp extends AbstractApp {

	public static final String NAME = "ImageJ1";

	@Override
	public String getGroupId() {
		return "net.imagej";
	}

	@Override
	public String getArtifactId() {
		return "ij";
	}

}

Add an App plugin for ImageJ 1.x

Add an App plugin for ImageJ 1.x

This is nice to have, and will come in handy soon...


// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

package com.microsoft.aad.msal4j;

import org.testng.Assert;
import org.testng.annotations.Test;

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

@Test(groups = { "checkin" })
public class HttpUtilsTest {

    private final String COOKIE_HEADER_NAME = "Set-Cookie";
    private final String COOKIE_HEADER_VALUE_1 = "298zf09hf012fh2";
    private final String COOKIE_HEADER_VALUE_2 = "u32t4o3tb3gg43";

    @Test
    public void testHttpUtils_singleValueHeader(){

        Map<String, List<String>> singleValuedHeader = new HashMap<String, List<String>>(){{
            put(COOKIE_HEADER_NAME, Collections.singletonList(COOKIE_HEADER_VALUE_1));
        }};

        String headerValue = HttpUtils.headerValue(singleValuedHeader, COOKIE_HEADER_NAME);
        Assert.assertEquals(headerValue, COOKIE_HEADER_VALUE_1);
    }

    @Test
    public void testHttpUtils_multiValueHeader(){

        Map<String, List<String>> multiValuedHeader = new HashMap<String, List<String>>(){{
            put(COOKIE_HEADER_NAME, Arrays.asList(COOKIE_HEADER_VALUE_1, COOKIE_HEADER_VALUE_2));
        }};

        String headerValue = HttpUtils.headerValue(multiValuedHeader, COOKIE_HEADER_NAME);
        String expectedValue = COOKIE_HEADER_VALUE_1 + "," + COOKIE_HEADER_VALUE_2;
        Assert.assertEquals(headerValue, expectedValue);
    }

    @Test
    public void testHttpUtils_HeaderValueNull(){

        Map<String, List<String>> nullValuedHeader = new HashMap<String, List<String>>(){{
            put(COOKIE_HEADER_NAME, null);
        }};

        String headerValue = HttpUtils.headerValue(nullValuedHeader, COOKIE_HEADER_NAME);
        Assert.assertNull(headerValue);
    }
}

Add unit test for HttpUtils

Add unit test for HttpUtils


package cucumber.demo.bank;

import static org.junit.Assert.*;

import org.junit.Test;
import org.junit.runner.RunWith;

import cucumber.api.junit.Cucumber;

@RunWith(Cucumber.class)
public class AccountTransferTest {

	@Test
	public void test() {
	}

}

Add Cucumber runner in test cases

Add Cucumber runner in test cases


package com.openxc;

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;

import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.assertFalse;

import com.openxc.units.Meter;
import com.openxc.measurements.Measurement;
import com.openxc.measurements.NoValueException;
import com.openxc.measurements.NoRangeException;

public class NoRangeMeasurementTest {
    Measurement<Meter> measurement;

    @Before
    public void setUp() {
        measurement = new Measurement<Meter>(new Meter(10.0));
    }

    @Test
    public void testHasValue() {
        assertThat(measurement.hasValue(), equalTo(true));
    }

    @Test
    public void testHasNoRange() {
        assertFalse(measurement.hasRange());
    }

    @Test(expected=NoRangeException.class)
    public void testEmptyRange() throws NoRangeException {
        measurement.getRange();
    }

    @Test
    public void testGet() throws NoValueException {
        assertThat(measurement.getValue().doubleValue(), equalTo(10.0));
    }
}

Test measurements with a value but no range.


/*
 * ******************************************************************************
 *   Copyright 2014-2015 Spectra Logic Corporation. All Rights Reserved.
 *   Licensed under the Apache License, Version 2.0 (the "License"). You may not use
 *   this file except in compliance with the License. A copy of the License is located at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 *   or in the "license" file accompanying this file.
 *   This file 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.spectralogic.ds3autogen.c;

import com.google.common.collect.ImmutableList;
import com.spectralogic.ds3autogen.c.converters.HeaderConverter;
import com.spectralogic.ds3autogen.c.converters.RequestConverter;
import com.spectralogic.ds3autogen.c.models.Enum;
import com.spectralogic.ds3autogen.c.models.*;
import com.spectralogic.ds3autogen.testutil.Ds3ModelFixtures;
import org.junit.Test;

import java.text.ParseException;

import static org.junit.Assert.assertEquals;

public class HeaderConverter_Test {
    @Test
    public void testToHeader() throws ParseException {
        final ImmutableList<Request> allRequests = ImmutableList.of(
                RequestConverter.toRequest(Ds3ModelFixtures.createBucketRequest()),
                RequestConverter.toRequest(Ds3ModelFixtures.deleteBucketRequest()),
                RequestConverter.toRequest(Ds3ModelFixtures.getBucketsRequest()));

        final ImmutableList<Enum> allEnums = ImmutableList.of(
                new Enum("TestEnum", ImmutableList.of(
                        "TestEnumValue1",
                        "TestEnumValue2")),
                new Enum("TestEnum2", ImmutableList.of(
                        "TestEnumValue3",
                        "TestEnumValue4")));

        final ImmutableList<Struct> allStructs = ImmutableList.of(
                new Struct("testStruct1", null, ImmutableList.of(
                        new StructMember(new PrimitiveType("int", false), "structMember1"),
                        new StructMember(new PrimitiveType("ds3_str", true), "structMember2")),
                        true,
                        false),
                new Struct("testStruct2", "marshallStruct2", ImmutableList.of(
                        new StructMember(new PrimitiveType("int", false), "structMember3")),
                        false,
                        true));

        final Header testHeader = HeaderConverter.toHeader(allEnums, allStructs, allRequests);
        assertEquals(testHeader.getEnums(), allEnums);
        assertEquals(testHeader.getRequests(), allRequests);
        assertEquals(testHeader.getStructs(), allStructs);
    }
}

Add unit test coverage for the HeaderConverter


/*
 * Copyright 2010, Red Hat, Inc. and individual contributors as indicated by the
 * @author tags. See the copyright.txt file in the distribution for a full
 * listing of individual contributors.
 *
 * This is free software; you can redistribute it and/or modify it under the
 * terms of the GNU Lesser General Public License as published by the Free
 * Software Foundation; either version 2.1 of the License, or (at your option)
 * any later version.
 *
 * This software is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
 * details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this software; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA, or see the FSF
 * site: http://www.fsf.org.
 */
package org.zanata.rest.service;

import java.io.InputStream;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;

public interface TranslationFileResource
{

   public static final String FILE_NAME_TEMPLATE = "/{docId:[a-zA-Z0-9]+([a-zA-Z0-9_\\-,{.}]*[a-zA-Z0-9]+)?}";

   @GET
   @Path(FILE_NAME_TEMPLATE)
   // /file/{docId}
   public InputStream downloadTranslationFile( @PathParam("docId") String docId );

}

Add File Resource and Service to manage file downloads.


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

import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;

/**
 * This listener can help programatically prevent scroll when desired.  For example, it may be undesirable to allow scrolling when animating a ListView.
 *
 * If used with a ListView, it is useful to also disable OnItemClickListener when scroll is disabled, as an attempt to scroll could be registered as
 * a click.
 *
 * @author Kevin Quan (kevin.quan@gmail.com)
 *
 */
public class DisableScrollOnTouchListener implements OnTouchListener {

    @SuppressWarnings("unused")
    private static final String TAG = DisableScrollOnTouchListener.class.getSimpleName();

    protected boolean mIsDisableScroll;
    protected OnTouchListener mOnTouchListener;

    public DisableScrollOnTouchListener() {
        mIsDisableScroll = true;
    }

    public DisableScrollOnTouchListener(OnTouchListener actualOnTouchListener) {
        mIsDisableScroll = true;
        mOnTouchListener = actualOnTouchListener;
    }

    @Override
    public boolean onTouch(View v, MotionEvent event) {
        if (!mIsDisableScroll && mOnTouchListener != null) {
            return mOnTouchListener.onTouch(v, event);
        } else if (mIsDisableScroll && event.getAction() == MotionEvent.ACTION_MOVE) {
            // Consume scroll event
            return true;
        }
        return false;
    }

    public DisableScrollOnTouchListener setConsumeScroll(boolean consumeScroll) {
        mIsDisableScroll = consumeScroll;
        return this;
    }

    public DisableScrollOnTouchListener setOnTouchListener(OnTouchListener onTouchListener) {
        mOnTouchListener = onTouchListener;
        return this;
    }

    public boolean isDisablingScroll() {
        return mIsDisableScroll;
    }

}

Add helper to disable scrolling

Add helper to disable scrolling


package org.monospark.spongematchers.parser.element;

import static org.hamcrest.CoreMatchers.equalTo;
import static org.junit.Assert.assertThat;

import org.junit.Test;
import org.monospark.spongematchers.parser.SpongeMatcherParseException;

public class MapElementParserTest {

    @Test
    public void parseElements_MapElementWithSingleEntry_ReturnsCorrectStringElement()
            throws SpongeMatcherParseException {
        String input = "{test:'test'}";

        StringElement element = StringElementParser.parseStringElement(input);

        MapElement map = (MapElement) element;
        BaseElement<?> base = (BaseElement<?>) map.getElement("test").get();
        assertThat(base.getString(), equalTo("'test'"));
    }

    @Test
    public void parseElements_MapElementWithSingleEntryWithSpaces_ReturnsCorrectStringElement()
            throws SpongeMatcherParseException {
        String input = " { test  :  'test' }  ";

        StringElement element = StringElementParser.parseStringElement(input);

        MapElement map = (MapElement) element;
        BaseElement<?> base = (BaseElement<?>) map.getElement("test").get();
        assertThat(base.getString(), equalTo("'test'"));
    }

    @Test
    public void parseElements_MapElement_ReturnsCorrectStringElement() throws SpongeMatcherParseException {
        String input = "{firsttest:'test1',secondtest:'test2',thirdtest:'test3'}";

        StringElement element = StringElementParser.parseStringElement(input);

        MapElement map = (MapElement) element;
        BaseElement<?> base1 = (BaseElement<?>) map.getElement("firsttest").get();
        assertThat(base1.getString(), equalTo("'test1'"));
        BaseElement<?> base2 = (BaseElement<?>) map.getElement("secondtest").get();
        assertThat(base2.getString(), equalTo("'test2'"));
        BaseElement<?> base3 = (BaseElement<?>) map.getElement("thirdtest").get();
        assertThat(base3.getString(), equalTo("'test3'"));
    }
}

Add unit tests for parsing map matchers

Add unit tests for parsing map matchers


package org.corpus_tools.annis.gui.query_references;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;

import java.net.URI;
import java.util.Date;
import java.util.UUID;
import org.junit.jupiter.api.Test;

class UrlShortenerEntryTest {

  @Test
  void testEquals() {
    UrlShortenerEntry e1 = new UrlShortenerEntry();

    assertEquals(e1, e1);
    assertFalse(e1.equals(null));
    assertFalse(e1.equals("Someobject"));

    UrlShortenerEntry e2 = new UrlShortenerEntry();

    assertEquals(e1, e2);

    e1.setCreated(new Date());
    assertFalse(e1.equals(e2));
    e2.setCreated(e1.getCreated());
    assertEquals(e1, e2);

    e1.setId(UUID.randomUUID());
    assertFalse(e1.equals(e2));
    e2.setId(e1.getId());
    assertEquals(e1, e2);

    e1.setOwner("someone");
    assertFalse(e1.equals(e2));
    e2.setOwner(e1.getOwner());
    assertEquals(e1, e2);

    e1.setTemporaryUrl(URI.create("/"));
    assertFalse(e1.equals(e2));
    e2.setTemporaryUrl(e1.getTemporaryUrl());
    assertEquals(e1, e2);

    e1.setUrl(URI.create("/target"));
    assertFalse(e1.equals(e2));
    e2.setUrl(e1.getUrl());
    assertEquals(e1, e2);

  }

}

Test equals function of UrlShortenerEntry


package org.kairosdb.security.auth.core.exception;

public class LoadingModuleException extends Exception
{
    private final String moduleName;

    public LoadingModuleException(String moduleName, String message)
    {
        super(message);
        this.moduleName = moduleName;
    }

    public String getModuleName()
    {
        return moduleName;
    }
}

Add exception class for module loader

Add exception class for module loader


package io.mobeacon.sdk;

import android.content.Context;
import android.location.Location;
import android.os.Bundle;
import android.util.Log;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.GoogleApiClient.ConnectionCallbacks;
import com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;

/**
 * Created by maxulan on 22.07.15.
 */
public class LocationManager implements ConnectionCallbacks, OnConnectionFailedListener, LocationListener {
    private static final String TAG = "MobeaconLocationManager";

    private Context ctx;
    private GoogleApiClient mGoogleApiClient;
    private LocationRequest mLocationRequest;

    public LocationManager(Context ctx) {
        this.ctx = ctx;
        buildGoogleApiClient();
        createLocationRequest();
        mGoogleApiClient.connect();
    }

    protected synchronized void buildGoogleApiClient() {
        mGoogleApiClient = new GoogleApiClient.Builder(ctx)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .addApi(LocationServices.API)
                .build();
    }
    @Override
    public void onConnected(Bundle connectionHint) {
        Location mLastLocation = LocationServices.FusedLocationApi.getLastLocation(
                mGoogleApiClient);
        if (mLastLocation != null) {
            Log.i(TAG, String.format("Current location. Latitude=%d Longitude=%d", mLastLocation.getLatitude(), mLastLocation.getLongitude()));
        }
        else  {
            Log.e(TAG, "Connected but failed to receive last location");
        }
        startLocationUpdates();
    }

    @Override
    public void onConnectionSuspended(int var1) {
        Log.e(TAG, "Google play services connection suspended");
    }

    public void onConnectionFailed(ConnectionResult var1){
        Log.e(TAG, "Google play services connection failed: " + var1.toString());
    }

    private void createLocationRequest() {
        mLocationRequest = new LocationRequest();
        mLocationRequest.setInterval(10000);
        mLocationRequest.setFastestInterval(5000);
        mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
    }
    /**
     * Requests location updates from the FusedLocationApi.
     */
    private void startLocationUpdates() {
        // The final argument to {@code requestLocationUpdates()} is a LocationListener
        // (http://developer.android.com/reference/com/google/android/gms/location/LocationListener.html).
        LocationServices.FusedLocationApi.requestLocationUpdates(
                mGoogleApiClient, mLocationRequest, this);
    }
    public void onLocationChanged(Location loc) {
        if (loc != null) {
            Log.i(TAG, String.format("location update: Latitude=%d Longitude=%d", loc.getLatitude(), loc.getLongitude()));
        }
        else  {
            Log.e(TAG, "Failed to update location");
        }
    }

}

Work started on device location discovery


/*
 * Copyright 2014-2015 Red Hat, Inc. and/or its affiliates
 * and other contributors as indicated by the @author tags.
 *
 * 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.hawkular.metrics.api.jaxrs;

import java.io.IOException;

import javax.ws.rs.container.ContainerRequestContext;
import javax.ws.rs.container.ContainerRequestFilter;
import javax.ws.rs.core.Response;
import javax.ws.rs.ext.Provider;

/**
 * @author Stefan Negrea
 *
 */
@Provider
public class TenantIdFilter implements ContainerRequestFilter {

    @Override
    public void filter(ContainerRequestContext requestContext) throws IOException {
        if (!requestContext.getUriInfo().getAbsolutePath().toString().contains("tenants")) {
            String tenantIdHeaderParam = requestContext.getHeaderString("tenantId");
            if (tenantIdHeaderParam == null || tenantIdHeaderParam.isEmpty()) {
                String tenandIdQueryParam = requestContext.getUriInfo().getQueryParameters().getFirst("tenantId");
                if (tenandIdQueryParam == null || tenandIdQueryParam.isEmpty()) {
                    requestContext.abortWith(Response.status(Response.Status.BAD_REQUEST)
                            .entity(new ApiError("Tenant id not specified")).build());
                }

                requestContext.getHeaders().add("tenantId", tenandIdQueryParam);
            }
        }
    }
}

Add a filter to transform requests that have tenantId as a query param when header information is missing. The fallback mechanism gracefully attempts to recreate the tenantId header if the param with an identical name is present. This will allow an easy transition and backwards compatibility for clients that cannot set headers on requests.


package uk.ac.ebi.quickgo.ontology.common.coterm;

/**
 * @author Tony Wardell
 * Date: 29/09/2016
 * Time: 15:49
 * Created with IntelliJ IDEA.
 */
public enum CoTermType {

    ALL,
    MANUAL
}

Define the types of co-occurring by source - manual (not electronic) or all (every source).


package flyway.oskari;

import fi.nls.oskari.db.BundleHelper;
import fi.nls.oskari.domain.map.view.Bundle;
import org.flywaydb.core.api.migration.jdbc.JdbcMigration;

import java.sql.Connection;
import java.sql.SQLException;

public class V1_36_0__register_contenteditor_bundle implements JdbcMigration {

    private static final String NAMESPACE = "tampere";
    private static final String BUNDLE_ID = "content-editor";
    private static final String BUNDLE_TITLE = "content-editor";

    public void migrate(Connection connection) throws SQLException {
        // BundleHelper checks if these bundles are already registered
        Bundle bundle = new Bundle();
        bundle.setName(BUNDLE_ID);
        bundle.setStartup(BundleHelper.getDefaultBundleStartup(NAMESPACE, BUNDLE_ID, BUNDLE_TITLE));
        BundleHelper.registerBundle(bundle, connection);
    }
}

Add flyway class to add bundle

Add flyway class to add bundle


/*
 * Copyright (c) 2012 Mateusz Parzonka, Eric Bodden
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 * Mateusz Parzonka - initial API and implementation
 */
package prm4j.logic;

import java.util.Set;

import prm4j.api.Parameter;
import prm4j.indexing.BaseEvent;

public interface FiniteSpec {

    public Set<Parameter<?>> getParameter();

    public Set<? extends BaseEvent> getBaseEvents();

    public Set<MonitorState> getStates();

    public MonitorState getInitialState();

}

Add interface for finite state specifications


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

package org.apache.jorphan.math;

/**
 * Class to calculate various items that don't require all previous results to be saved:
 * - mean = average
 * - standard deviation
 * - minimum
 * - maximum
 */
public class Calculator {

	private double sum = 0;

	private double sumOfSquares = 0;

	private double mean = 0;

	private double deviation = 0;

	private int count = 0;

	private long bytes = 0;

	private long maximum = Long.MIN_VALUE;

	private long minimum = Long.MAX_VALUE;

	public void clear() {
		maximum = Long.MIN_VALUE;
		minimum = Long.MAX_VALUE;
		sum = 0;
		sumOfSquares = 0;
		mean = 0;
		deviation = 0;
		count = 0;
	}

	public void addValue(long newValue) {
		count++;
		minimum=Math.min(newValue, minimum);
		maximum=Math.max(newValue, maximum);
		double currentVal = newValue;
		sum += currentVal;
		sumOfSquares += currentVal * currentVal;
		// Calculate each time, as likely to be called for each add
		mean = sum / count;
		deviation = Math.sqrt((sumOfSquares / count) - (mean * mean));
	}

	public void addBytes(long newValue) {
		bytes += newValue;
	}

	public long getTotalBytes() {
		return bytes;
	}

	public double getMean() {
		return mean;
	}

	public double getStandardDeviation() {
		return deviation;
	}

	public long getMin() {
		return minimum;
	}

	public long getMax() {
		return maximum;
	}

	public int getCount() {
		return count;
	}
}

Add cheaper calculator (no need to save results)

git-svn-id: 52ad764cdf1b64a6e804f4e5ad13917d3c4b2253@405491 13f79535-47bb-0310-9956-ffa450edef68


package replicant;

import java.util.HashMap;
import javax.annotation.Nonnull;

public class TestEntityChangeData
  implements EntityChangeData
{
  private final HashMap<String, Object> _data = new HashMap<>();

  public HashMap<String, Object> getData()
  {
    return _data;
  }

  @Override
  public boolean containsKey( @Nonnull final String key )
  {
    return _data.containsKey( key );
  }

  @Override
  public boolean isNull( @Nonnull final String key )
  {
    assert _data.containsKey( key );
    return null == _data.get( key );
  }

  @Override
  public int getIntegerValue( @Nonnull final String key )
  {
    assert _data.containsKey( key );
    return (int) _data.get( key );
  }

  @Nonnull
  @Override
  public String getStringValue( @Nonnull final String key )
  {
    assert _data.containsKey( key );
    return (String) _data.get( key );
  }

  @Override
  public boolean getBooleanValue( @Nonnull final String key )
  {
    assert _data.containsKey( key );
    return (Boolean) _data.get( key );
  }
}

Add EntityChangeData implementation used for testing


package com.aemreunal.controller;

/*
 ***************************
 * Copyright (c) 2014      *
 *                         *
 * This code belongs to:   *
 *                         *
 * @author Ahmet Emre Ünal *
 * S001974                 *
 *                         *
 * aemreunal@gmail.com     *
 * emre.unal@ozu.edu.tr    *
 *                         *
 * aemreunal.com           *
 ***************************
 */

import org.junit.Test;
import org.springframework.security.crypto.codec.Base64;

public class GenAuth {
    @Test
    public void generateAuth() {
        String auth = "adminr:password";
        byte[] encodedAuthorisation = Base64.encode(auth.getBytes());
        System.out.println("Basic " + new String(encodedAuthorisation));
    }
}

Add OAuth token generating test

Add OAuth token generating test


/*
 * Java core library component.
 *
 * Copyright (c) 1999
 *	Archie L. Cobbs.  All rights reserved.
 * Copyright (c) 1999
 *	Transvirtual Technologies, Inc.  All rights reserved.
 *
 * See the file "license.terms" for information on usage and redistribution
 * of this file.
 *
 * Author: Archie L. Cobbs <archie@whistle.com>
 */

package java.net;

import java.io.IOException;
import java.security.CodeSource;
import java.security.PermissionCollection;
import java.security.SecureClassLoader;
import java.util.Enumeration;
import java.util.Vector;
import java.util.jar.Manifest;

// XXX this class is not complete!

public class URLClassLoader extends SecureClassLoader {
	final Vector urls;
	final ClassLoader parent;

	public URLClassLoader(URL[] urls, ClassLoader parent) {
		this(urls, parent, null);
	}

	public URLClassLoader(URL[] urls) {
		this(urls, URLClassLoader.class.getClassLoader(), null);
	}

	public URLClassLoader(URL[] urls, ClassLoader parent,
			URLStreamHandlerFactory factory) {
		this.urls = new Vector();
		for (int i = 0; i < urls.length; i++) {
			this.urls.addElement(urls[i]);
		}
		this.parent = parent;
	}

	protected void addURL(URL url) {
		urls.addElement(url);
	}

	public URL[] getURLs() {
		return (URL[])urls.toArray(new URL[urls.size()]);
	}

	//protected Class findClass(String name) throws ClassNotFoundException {
	//}

	protected Package definePackage(String name, Manifest man, URL url)
			throws IllegalArgumentException {
		return super.definePackage(name, "", "", "", "", "", "", url);
	}

	//public URL findResource(String name) {
	//}

	//public Enumeration findResources(String name) throws IOException {
	//}

	protected PermissionCollection getPermissions(CodeSource codesource) {
		return null;
	}

	public static URLClassLoader newInstance(URL[] urls,
			ClassLoader parent) {
		return new URLClassLoader(urls, parent);
	}

	public static URLClassLoader newInstance(URL[] urls) {
		return new URLClassLoader(urls);
	}
}

Add missing class (mostly unimplemented).


package org.krugler.yalder;

import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.io.FileUtils;
import org.krugler.yalder.hash.HashLanguageModel;
import org.krugler.yalder.text.TextLanguageModel;

public class ModelLoader {

    public static Collection<BaseLanguageModel> loadModelsFromResources() {
        // TODO use language-detector code to find/load resources
        return null;
    }

    public static Collection<BaseLanguageModel> loadModelsFromDirectory(File dirFile, boolean isBinary) throws IOException {
        Set<BaseLanguageModel> result = new HashSet<>();

        String modelSuffix = isBinary ? "bin" : "txt";
        for (File file : FileUtils.listFiles(dirFile, new String[]{modelSuffix}, true)) {
            String filename = file.getName();
            Pattern p = Pattern.compile(String.format("yalder_model_(.+).%s", modelSuffix));
            Matcher m = p.matcher(filename);
            if (!m.matches()) {
                continue;
            }

            // Verify that language is valid
            LanguageLocale.fromString(m.group(1));

            if (isBinary) {
                try (DataInputStream dis = new DataInputStream(new FileInputStream(file))) {
                    HashLanguageModel binaryModel = new HashLanguageModel();
                    binaryModel.readAsBinary(dis);
                    result.add(binaryModel);
                }
            } else {
                try (InputStreamReader isr = new InputStreamReader(new FileInputStream(file), "UTF-8")) {
                    TextLanguageModel textModel = new TextLanguageModel();
                    textModel.readAsText(isr);
                    result.add(textModel);
                }
            }
        }

        return result;
    }
}

Add first cut at model loader

Add first cut at model loader


package leetcode.palindrome_partitioning_ii;

public class Solution {

	public void buildTable(char[] charAry, int[] table){
		int L = 0, R = -1, C = 0;
		int len = charAry.length;
		for(int i = 0; i < len * 2 - 1; i++){
			int ref = 2 * C - i;
			if(i > R || ref - table[ref] + 1 <= L){
				int rad;
				int minrad = i > R ? 1 : R - i + 1;
				if(minrad > len * 2 - i) minrad = len * 2 - i;
				C = i;
				for(rad = minrad; i - rad + 1 >= 0 && i + rad - 1 < len * 2 - 1; rad++){
					int l = i - rad + 1, r = i + rad - 1;
					if(l % 2 == 1 || charAry[l / 2] == charAry[r / 2]){
						table[i] = rad;
						R = i + rad - 1;
						L = i - rad + 1;
					}else{
						break;
					}
				}
			}else{
				table[i] = table[ref];
			}
		}
		for(int i = 0; i < len * 2 - 1; i++){
			if(i % 2 == 0){
				table[i] = (table[i] - 1) / 2 * 2 + 1;
			}else{
				table[i] = table[i] / 2 * 2;
			}
		}
	}

    public int minCut(String s) {
    	if(s.length() == 0) return 0;
    	int[] maxPalinTable = new int[s.length() * 2 - 1];
    	buildTable(s.toCharArray(), maxPalinTable);
    	int[] cut = new int[s.length() + 1];
    	for(int i = 0; i < s.length() * 2 - 1; i++){
    		int palinLength = maxPalinTable[i];
    		int jumpStart = i / 2 - (palinLength + 1) / 2 + 1;
    		int jumpEnd = i / 2;
    		for(int j = jumpStart; j <= jumpEnd; j++){
    			int jumpLength = palinLength + jumpStart * 2 - j * 2;
    			if(cut[j + jumpLength] == 0 || cut[j + jumpLength] > cut[j] + 1){
    				cut[j + jumpLength] = cut[j] + 1;
    			}
    		}
    	}
    	return cut[s.length()] - 1;
    }

	public static void main(String[] args){
		System.err.println(new Solution().minCut("a"));
	}
}

Add java solution for 132. Palindrome Partitioning II

132. Palindrome Partitioning II: https://leetcode.com/problems/palindrome-partitioning-ii/


package com.pturpin.quickcheck.generator;

import java.math.BigDecimal;
import java.math.BigInteger;

import static com.google.common.base.Preconditions.checkArgument;

public class Numbers {

    public static Generator<Integer> integerGen() {
        return integerGen(Integer.MIN_VALUE, Integer.MAX_VALUE);
    }

    public static Generator<Integer> integerGen(int min, int max) {
        checkArgument(max > min);
        return re -> re.nextInt() % (max - min) + min;
    }

    public static Generator<Long> longGen() {
        return longGen(Long.MIN_VALUE, Long.MAX_VALUE);
    }

    public static Generator<Long> longGen(long min, long max) {
        checkArgument(max > min);
        return re -> re.nextLong() % (max - min) + min;
    }

    public static Generator<Float> floatGen() {
        return floatGen(-Float.MAX_VALUE, Float.MAX_VALUE);
    }

    public static Generator<Float> floatGen(float min, float max) {
        checkArgument(max > min);
        return re -> re.nextFloat() * (max - min) + min; // FIXME handle overflow
    }

    public static Generator<Double> doubleGen() {
        return doubleGen(-Double.MAX_VALUE, Double.MAX_VALUE);
    }

    public static Generator<Double> doubleGen(double min, double max) {
        checkArgument(max > min);
        return re -> re.nextDouble() * (max - min) + min;  // FIXME handle overflow
    }

    public static Generator<Double> specialDouble() {
        return Generators.oneOf(Double.MIN_VALUE, Double.MAX_VALUE,
                Double.MIN_NORMAL, Double.NaN, 0.d, -0.d,
                Double.POSITIVE_INFINITY, Double.NEGATIVE_INFINITY);
    }

    public static Generator<BigInteger> bigIntegerGen(BigInteger min, BigInteger max) {
        checkArgument(max.compareTo(min) > 0);
        BigInteger delta = max.subtract(min);

        int deltaNumBits = delta.bitCount();
        Generator<Integer> numBitsGen = integerGen(0, deltaNumBits);

        return re -> {
            BigInteger generated = new BigInteger(numBitsGen.get(re), re);
            return generated.remainder(delta).add(min);
        };
    }

    public static Generator<BigDecimal> bigDecimalGen(BigDecimal min, BigDecimal max) {
        checkArgument(max.compareTo(min) > 0);

        BigInteger minInt = min.unscaledValue();
        BigInteger maxInt = max.unscaledValue();
        Generator<BigInteger> bigIntGen = bigIntegerGen(minInt, maxInt);

        int minScale = min.scale();
        int maxScale = max.scale();
        Generator<Integer> scaleGen = integerGen(minScale, maxScale);

        BigDecimal delta = max.subtract(min);

        return re -> {
            BigDecimal generated = new BigDecimal(bigIntGen.get(re), scaleGen.get(re));
            return generated.remainder(delta).add(min);
        };
    }
}

Create basic implementations (lambda) of numbers generators


package com.darwinsys.todo.test;

import static org.junit.Assert.assertTrue;

import org.junit.Test;

import com.pobox.cbarham.testhelpers.EqualsHashCodeTestCase;

public class TaskEqualsHashcodeTest extends EqualsHashCodeTestCase {

	@Override
	protected App createInstance() throws Exception {
		return new Task("Get Stuff Done");
	}

	@Override
	protected App createNotEqualInstance() throws Exception {
		return new App("Get MORE stuff done!");
	}

	@Test
	public void testAssertTrue() {
		assertTrue(true);
	}
}

Test our Equals method a bit

Test our Equals method a bit


package de.gurkenlabs.litiengine.entities;

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

import org.junit.jupiter.api.Test;

import de.gurkenlabs.litiengine.annotation.Action;

public class EntityTests {

  @Test
  public void testEntityAction() {
    TestEntity entity = new TestEntity();

    assertTrue(entity.actions().exists("doSomething"));

    EntityAction action = entity.actions().get("doSomething");

    assertNotNull(action);

    action.perform();

    assertTrue(entity.didSomething);
  }

  @Test
  public void testNamedAction() {
    TestEntity entity = new TestEntity();

    assertTrue(entity.actions().exists("myName"));

    EntityAction action = entity.actions().get("myName");

    assertNotNull(action);

    action.perform();

    assertTrue(entity.didNamedAction);
  }

  @Test
  public void testCustomAction() {
    Entity entity = new TestEntity();
    entity.register("customAction", () -> {
      return;
    });

    assertTrue(entity.actions().exists("customAction"));

    entity.actions().unregister("customAction");

    assertFalse(entity.actions().exists("customAction"));
  }

  private class TestEntity extends Entity {
    private boolean didSomething;
    private boolean didNamedAction;

    @Action(description = "does something")
    public void doSomething() {
      didSomething = true;
    }

    @Action(name = "myName")
    public void namedAction() {
      didNamedAction = true;
    }
  }
}

Add some test cases for entity actions.

Add some test cases for entity actions.


package net.imagej.ops.views;

import org.scijava.plugin.Plugin;

import net.imagej.ops.view.ViewOps;
import net.imagej.ops.view.ViewOps.ZeroMin;
import net.imglib2.RandomAccessibleInterval;
import net.imglib2.view.IntervalView;
import net.imglib2.view.Views;

@Plugin(type = ViewOps.ZeroMin.class, name = ViewOps.ZeroMin.NAME)
public class DefaultZeroMin<T> extends
		AbstractView<RandomAccessibleInterval<T>, IntervalView<T>> implements
		ZeroMin<RandomAccessibleInterval<T>, IntervalView<T>> {

	@Override
	public IntervalView<T> compute(RandomAccessibleInterval<T> input) {
		return Views.zeroMin(input);
	}

}

Add default implementation of ZeroMin interface.


package leetcode.reverse_nodes_in_k_group;

import common.ListNode;

public class Solution {
    public ListNode reverseKGroup(ListNode head, int k) {
        if(head == null || k <= 1) return head;

        ListNode prev = null;
        while(true){
        	ListNode groupHead;
        	if(prev == null){
        		groupHead = head;
        	}else{
        		groupHead = prev.next;
        	}
        	if(groupHead == null) return head;
        	ListNode groupTail = groupHead;
        	int steps;
        	for(steps = 0; steps < k - 1 && groupTail.next != null; steps++){
        		groupTail = groupTail.next;
        	}
        	if(steps < k - 1) return head;
        	else{
        		ListNode groupNext = groupHead.next;
        		ListNode groupPrev = groupHead;
        		for(int i = 0; i < k - 1; i++){
        			ListNode groupTmp = groupNext.next;
        			groupNext.next = groupHead;
        			groupPrev.next = groupTmp;
        			groupHead = groupNext;
        			groupTail = groupPrev;
        			groupNext = groupTmp;
        		}
        		if(prev == null){
        			head = groupHead;
        		}else{
        			prev.next = groupHead;
        		}
        		prev = groupTail;
        	}
        }
    }

    public static void dump(ListNode head){
    	while(head != null){
    		System.err.print(head.val + "->");
    		head = head.next;
    	}
    }
    public static void main(String[] args){
    	final int N = 3;
    	ListNode[] list = new ListNode[N];
    	for(int i = 0; i < N; i++){
    		list[i] = new ListNode(i);
    		if(i > 0) list[i - 1].next = list[i];
    	}
    	dump(new Solution().reverseKGroup(list[0], 4));
    }
}

Add java solution for 25. Reverse Nodes in k-Group

25. Reverse Nodes in k-Group: https://leetcode.com/problems/reverse-nodes-in-k-group/


import android.support.test.filters.SmallTest;
import android.support.test.runner.AndroidJUnit4;

import com.hewgill.android.nzsldict.Dictionary;

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

import java.util.List;

import static android.support.test.InstrumentationRegistry.getInstrumentation;
import static junit.framework.Assert.assertEquals;
import static org.junit.Assert.assertNotEquals;

@RunWith(AndroidJUnit4.class)
@SmallTest
public class DictionaryAndroidUnitTest {
    private Dictionary mDictionary;
    private List<Dictionary.DictItem> mResults;

    @Before
    public void createDictionary() {
        mDictionary = new Dictionary(getInstrumentation().getTargetContext());
    }

    @After
    public void clearResults() {
        mResults = null;
    }

    @Test
    public void dictionary_getWordsContainsWords() {
        assertNotEquals(mDictionary.getWords().size(), 0);
    }

    @Test
    public void dictionary_getWordsExactMatchMainGloss() {
        mResults = mDictionary.getWords("Book");
        assertEquals(mResults.get(0).gloss, "book");
    }

    @Test
    public void dictionary_getWordsContainsMatchMainGlass() {
        mResults = mDictionary.getWords("las");
        assertEquals(mResults.get(0).gloss, "sunglasses");
    }

    @Test
    public void dictionary_getWordsExactMatchMaoriGloss() {
        mResults = mDictionary.getWords("ora");
        assertEquals(mResults.get(0).gloss, "alive, live, survive");
    }

    @Test
    public void dictionary_getWordsContainsMatchMaoriGloss() {
        mResults = mDictionary.getWords("orang");
        assertEquals(mResults.get(0).gloss, "politics");
    }

    @Test
    public void dictionary_getWordsExactSecondaryGloss() {
        mResults = mDictionary.getWords("nought");
        assertEquals(mResults.get(0).gloss, "zero");
    }

    @Test
    public void dictionary_getWordsContainsSecondaryGloss() {
        mResults = mDictionary.getWords("keep ou");
        assertEquals(mResults.get(0).gloss, "want nothing to do with");
    }
}

Add tests asserting that search matching is working as per spec


package core.util;

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

import core.Database;
import net.dv8tion.jda.core.entities.User;

public class MatchMaker {

	String guildId;
	List<Ranking> rankings = new ArrayList<Ranking>();

	public MatchMaker(String guildId, List<User> players){
		this.guildId = guildId;
		for(User p : players){
			rankings.add(new Ranking(p));
		}
		calcRank();
	}

	private void calcRank(){
		for(Ranking ranking : rankings){
			double score = 0.0;
			for(Ranking r : rankings){
				if(r != ranking){
					Double pickDiff = Database.queryGetPickOrderDiff(Long.valueOf(guildId), ranking.player.getIdLong(), r.player.getIdLong());

					if(pickDiff > 0){
						score += pickDiff;
					}
				}
			}

			ranking.score = (int)(score * 100);
		}
	}

	public User getMatch(User captain){
		Ranking captainRanking = getRanking(captain);
		Ranking closestMatch = null;

		for(Ranking r : rankings){
			if(r != captainRanking){
				if(closestMatch != null){
					if(captainRanking.getDifference(r) > r.score){
						closestMatch = r;
					}
				}else{
					closestMatch = r;
				}
			}
		}
		return closestMatch.player;
	}

	private Ranking getRanking(User player){
		for(Ranking ranking : rankings){
			if(ranking.player == player){
				return ranking;
			}
		}
		return null;
	}

	private class Ranking{
		private User player;
		private Integer score;

		public Ranking(User player){
			this.player = player;
			this.score = 0;
		}

		private Integer getDifference(Ranking r){
			return Math.abs(score - r.score);
		}
	}
}

Create first matchmaking implementation for captains


/*
 * DomUI Java User Interface - shared code
 * Copyright (c) 2010 by Frits Jalvingh, Itris B.V.
 *
 * 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., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 *
 * See the "sponsors" file for a list of supporters.
 *
 * The latest version of DomUI and related code, support and documentation
 * can be found at http://www.domui.org/
 * The contact for the project is Frits Jalvingh <jal@etc.to>.
 */
package javax.annotation;

import java.lang.annotation.*;

import javax.annotation.meta.*;

@Documented
@TypeQualifier
@Retention(RetentionPolicy.RUNTIME)
public @interface DefaultNonNull {
}

Add DefaultNonnull annotation to jst305 crap


/*
 *
 * Copyright 2016, TeamDev Ltd. 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 org.spine3.base;

import org.junit.Test;

import static org.junit.Assert.assertTrue;
import static org.spine3.test.Tests.hasPrivateUtilityConstructor;

/**
 * @author Alex Tymchenko
 */
public class QueriesShould {

    @Test
    public void have_private_constructor() {
        assertTrue(hasPrivateUtilityConstructor(Queries.class));
    }

}

Create a test for `Queries` utility class.


/*
 * This file is released under terms of BSD license
 * See LICENSE file for more information
 */
package cx2x.translator.transformation;

import cx2x.translator.language.base.ClawLanguage;
import cx2x.translator.transformation.ClawTransformation;
import cx2x.xcodeml.transformation.Transformation;
import cx2x.xcodeml.transformation.Transformer;
import cx2x.xcodeml.xnode.XcodeProgram;

/**
 * Simple transformation for documentation example
 */
public class MyFirstTransformation extends ClawTransformation {

  // Constructor that received the analyzed pragma as argument
  public MyFirstTransformation(ClawLanguage directive) {
    super(directive);
  }

  // The analyzis step
  public boolean analyze(XcodeProgram xcodeml, Transformer transformer) {
    return true;
  }

  // The transformation step
  public void transform(XcodeProgram xcodeml, Transformer transformer,
                        Transformation other) throws Exception
  {
    _claw.delete();
  }

  // Only used by dependent transformation
  public boolean canBeTransformedWith(Transformation other) {
    return false; // Independent transformation
  }
}

Add simple example of transformation class


package org.jsmpp.util;

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

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

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

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

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

Add delivery receipt test case

Add delivery receipt test case


package jme3test.scene;

import com.jme3.app.SimpleApplication;
import com.jme3.material.Material;
import com.jme3.scene.Geometry;
import com.jme3.scene.Node;
import com.jme3.scene.shape.Box;

public class TestRefreshFlagBug extends SimpleApplication {

    private float time = 0;
    private boolean attached = false;
    private Node inBetweenNode;

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

    @Override
    public void simpleUpdate(float tpf) {
        time += tpf;
        if (time > 5 && !attached) {
            attached = true;

            Box b = new Box(1, 1, 1);
            Geometry geom = new Geometry("Box", b);
            Material mat = new Material(assetManager, "Common/MatDefs/Misc/Unshaded.j3md");
            geom.setMaterial(mat);

            inBetweenNode.attachChild(geom);

            // the refresh flags become corrupted here ...
            inBetweenNode.getWorldBound();
        }
    }

    @Override
    public void simpleInitApp() {
        inBetweenNode = new Node("In Between Node");
        rootNode.attachChild(inBetweenNode);

        flyCam.setDragToRotate(true);
    }
}

Add simple test case for the "scene not updated" crash in the SDK


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

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

import com.google.common.collect.ImmutableList;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;

/** Test for {@link ProjectViewStorageManager}. */
@RunWith(JUnit4.class)
public class ProjectViewStorageManagerTest {

  private static final com.google.common.collect.ImmutableList<String>
      VALID_PROJECT_VIEW_FILENAMES =
          ImmutableList.of(
              ".blazeproject",
              ".asproject",
              ".bazelproject",
              "foo.blazeproject",
              "bar.baz.bazelproject");

  private static final com.google.common.collect.ImmutableList<String>
      INVALID_PROJECT_VIEW_FILENAMES =
          ImmutableList.of(
              ".buckproject",
              ".bazel",
              "blazeproject",
              "bazelproject",
              "blazeproject.foo",
              "bar.bazelproject.baz",
              ".",
              "");

  @Test
  public void testIsProjectViewFile() {
    VALID_PROJECT_VIEW_FILENAMES.forEach(
        filename -> assertThat(ProjectViewStorageManager.isProjectViewFile(filename)).isTrue());

    INVALID_PROJECT_VIEW_FILENAMES.forEach(
        filename -> assertThat(ProjectViewStorageManager.isProjectViewFile(filename)).isFalse());
  }
}

Add a test for detecting the blazeproject filetype.

PiperOrigin-RevId: 369601112


/*******************************************************************************
 * Copyright (c) 2016 Red Hat Inc. and others.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies range distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *     Red Hat Inc. - initial API and implementation
 *******************************************************************************/
package org.jboss.tools.vscode.java.internal;

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

import org.eclipse.lsp4j.Position;
import org.eclipse.lsp4j.Range;

/**
 * A set of assertion methods about LSP4J entities
 *
 * @author Fred Bricon
 *
 */
public class Lsp4jAssertions {

	public static void assertRange(int expectedLine, int expectedStart, int expectedEnd, Range range) {
		assertNotNull("Range is null", range);
		assertPosition(expectedLine, expectedStart, range.getStart());
		assertPosition(expectedLine, expectedEnd, range.getEnd());
	}

	public static void assertPosition(int expectedLine, int expectedChar, Position position) {
		assertNotNull("Position is null", position);
		assertEquals("Unexpected line position from "+position, expectedLine, position.getLine());
		assertEquals("Unexpected character position from "+position, expectedChar, position.getCharacter());
	}
}

Add test assertion helper class

Add test assertion helper class

Signed-off-by: Fred Bricon <3278c038c93c729ae96f0d035919e3fb69e9cff7@gmail.com>


package org.csstudio.utility.ldap.engine;

public class Engine extends Thread {

	private static Engine thisEngine = null;
	/**
	 * @param args
	 */
	public void run () {

	}

	private Engine() {
    	// absicherung
    }

    public static Engine getInstance() {
		//
		// get an instance of our sigleton
		//
		if ( thisEngine == null) {
			synchronized (Engine.class) {
				if (thisEngine == null) {
					thisEngine = new Engine();
				}
			}
		}
		return thisEngine;
	}

}

Add engine for common use of asynch LDAP requests


package org.cyclops.cyclopscore.helper;

import net.minecraft.client.gui.Gui;
import net.minecraft.client.renderer.GlStateManager;
import net.minecraft.client.renderer.texture.TextureAtlasSprite;
import net.minecraft.client.renderer.texture.TextureMap;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.ResourceLocation;
import net.minecraftforge.fluids.FluidStack;

import javax.annotation.Nullable;

/**
 * Helpers related to guis.
 */
public class GuiHelpers {

    /**
     * Render a fluid tank in a gui.
     *
     * @param gui The gui to render in.
     * @param fluidStack The fluid to render.
     * @param capacity The tank capacity.
     * @param x The gui x position, including gui left.
     * @param y The gui y position, including gui top.
     * @param width The tank width.
     * @param height The tank height.
     */
    public static void renderFluidTank(Gui gui, @Nullable FluidStack fluidStack, int capacity,
                                       int x, int y, int width, int height) {
        if (fluidStack != null && capacity > 0) {
            int level = height * fluidStack.amount / capacity;
            TextureAtlasSprite icon = RenderHelpers.getFluidIcon(fluidStack, EnumFacing.UP);
            int verticalOffset = 0;
            while(level > 0) {
                int textureHeight;
                if(level > 16) {
                    textureHeight = 16;
                    level -= 16;
                } else {
                    textureHeight = level;
                    level = 0;
                }

                RenderHelpers.bindTexture(TextureMap.LOCATION_BLOCKS_TEXTURE);
                gui.drawTexturedModalRect(x, y - textureHeight - verticalOffset + height, icon, width, textureHeight);
                verticalOffset = verticalOffset + 16;
            }
        }
    }

    /**
     * Render a fluid tank in a gui with a tank overlay.
     * This assumes that the tank overlay has the provided width and height.
     *
     * @param gui The gui to render in.
     * @param fluidStack The fluid to render.
     * @param capacity The tank capacity.
     * @param x The gui x position, including gui left.
     * @param y The gui y position, including gui top.
     * @param width The tank width.
     * @param height The tank height.
     * @param textureOverlay The texture of the tank overlay.
     * @param overlayTextureX The overlay x texture position.
     * @param overlayTextureY The overlay y texture position.
     */
    public static void renderOverlayedFluidTank(Gui gui, @Nullable FluidStack fluidStack, int capacity,
                                                int x, int y, int width, int height,
                                                ResourceLocation textureOverlay, int overlayTextureX, int overlayTextureY) {
        renderFluidTank(gui, fluidStack, capacity, x, y, width, height);
        if (fluidStack != null && capacity > 0) {
            GlStateManager.enableBlend();
            RenderHelpers.bindTexture(textureOverlay);
            gui.drawTexturedModalRect(x, y, overlayTextureX, overlayTextureY, width, height);
        }
    }

}

Add helpers for rendering fluid tanks in guis


package ca.antonious.viewcelladapter.utilstests;

import org.junit.Test;

import ca.antonious.viewcelladapter.TestViewCell;
import ca.antonious.viewcelladapter.utils.ViewCellUtils;
import ca.antonious.viewcelladapter.viewcells.AbstractViewCell;

import static org.junit.Assert.*;

/**
 * Created by George on 2017-05-14.
 */

public class GetSpanSizeTests {
    @Test
    public void test_totalPerLineOf1_spanCountOf3_shouldReturnSpanSizeOf3() {
        AbstractViewCell viewCell = new TestViewCell("id", 1);

        int expectedSpanSize = 3;
        int actualSpanSize = ViewCellUtils.getSpanSizeFor(viewCell, 3);

        assertEquals(expectedSpanSize, actualSpanSize);
    }

    @Test
    public void test_totalPerLineOf3_spanCountOf3_shouldReturnSpanSizeOf1() {
        AbstractViewCell viewCell = new TestViewCell("id", 3);

        int expectedSpanSize = 1;
        int actualSpanSize = ViewCellUtils.getSpanSizeFor(viewCell, 3);

        assertEquals(expectedSpanSize, actualSpanSize);
    }
}

Add basic tests for calculating span count


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

package com.michaelrocks.lightsaber.processor.descriptors;

import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import org.objectweb.asm.Type;

public class ParameterizedType {
    private final Type rawType;
    private final Type parameterType;

    public ParameterizedType(final Type rawType) {
        this(rawType, null);
    }

    public ParameterizedType(final Type rawType, final Type parameterType) {
        this.rawType = rawType;
        this.parameterType = parameterType;
    }

    public static ParameterizedType fromType(final Type type) {
        return new ParameterizedType(type, null);
    }

    public Type getRawType() {
        return rawType;
    }

    public Type getParameterType() {
        return parameterType;
    }

    @Override
    public boolean equals(final Object object) {
        if (this == object) {
            return true;
        }

        if (object == null || getClass() != object.getClass()) {
            return false;
        }

        final ParameterizedType that = (ParameterizedType) object;
        return new EqualsBuilder()
                .append(rawType, that.rawType)
                .append(parameterType, that.parameterType)
                .isEquals();
    }

    @Override
    public int hashCode() {
        return new HashCodeBuilder(17, 37)
                .append(rawType)
                .append(parameterType)
                .toHashCode();
    }

    @Override
    public String toString() {
        if (parameterType == null) {
            return rawType.toString();
        } else {
            return rawType + "<" + parameterType + ">";
        }
    }
}

Add a descriptor for parameterized types


package rsc.processor;

import java.util.concurrent.ConcurrentLinkedQueue;

import org.junit.Test;

import rsc.test.TestSubscriber;

public class UnicastProcessorTest {

    @Test
    public void secondSubscriberRejectedProperly() {

        UnicastProcessor<Integer> up = new UnicastProcessor<>(new ConcurrentLinkedQueue<>());

        up.subscribe();

        TestSubscriber<Integer> ts = new TestSubscriber<>();

        up.subscribe(ts);

        ts.assertNoValues()
        .assertError(IllegalStateException.class)
        .assertNotComplete();

    }
}

Add test fro UnicastProcessor rejecting second Subscriber properly


package fm.last.commons.kyoto;

import static org.junit.Assert.assertEquals;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

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

@RunWith(Parameterized.class)
public class FixedPointTest {
  private static final double ERROR_MARGIN = 0.000000000000001d;

  private static final byte[] _10_0001 = new byte[] { 0, 0, 0, 0, 0, 0, 0, 10, 0, 0, 0, 23, 72, 118, -25, -1 };
  private static final byte[] __1 = new byte[] { -1, -1, -1, -1, -1, -1, -1, -1, 0, 0, 0, 0, 0, 0, 0, 0 };
  private static final byte[] __1_1 = new byte[] { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -91, 12, -17, -123, -64, 0 };
  private static final byte[] _1_1 = new byte[] { 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 90, -13, 16, 122, 64, 0 };

  private byte[] bytes;
  private double expected;

  @Parameters
  public static Collection<Object[]> data() {
    List<Object[]> data = new ArrayList<Object[]>();
    data.add(new Object[] { 10.0001d, _10_0001 });
    data.add(new Object[] { -1.0d, __1 });
    data.add(new Object[] { -1.1d, __1_1 });
    data.add(new Object[] { 1.1d, _1_1 });
    return data;
  }

  public FixedPointTest(double expected, byte[] bytes) {
    this.expected = expected;
    this.bytes = bytes;
  }

  @Test
  public void testFixedPointToDouble() {
    double decodedValue = FixedPoint.toDouble(bytes);
    assertEquals("Expected to get " + expected, expected, decodedValue, ERROR_MARGIN);
  }
}

Add unit test for FixedPoint

Add unit test for FixedPoint


package leetcode;

/**
 * https://leetcode.com/problems/search-in-rotated-sorted-array-ii/
 */
public class Problem81 {
    public boolean search(int[] nums, int target) {
        return false;
    }

    public static void main(String[] args) {
        Problem81 prob = new Problem81();
//        System.out.println(prob.search(nums, target));
    }
}

Create a skeleton for problem 81

Create a skeleton for problem 81


/*
 * Copyright (c) 2016 Instituto Atlântico Development Company, L.P. and others. All rights reserved.
 *
 * This program and the accompanying materials are made available under the
 * terms of the Eclipse Public License v1.0 which accompanies this distribution,
 * and is available at http://www.eclipse.org/legal/epl-v10.html
 */

package org.opendaylight.nic.of.renderer.strategy;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.opendaylight.nic.of.renderer.impl.RedirectFlowManager;
import org.opendaylight.nic.utils.FlowAction;
import org.opendaylight.yang.gen.v1.urn.opendaylight.intent.rev150122.intents.Intent;
import org.powermock.modules.junit4.PowerMockRunner;

/**
 * @author victor. Created on 17/11/16.
 */
@RunWith(PowerMockRunner.class)
public class RedirectExecutorTest {

    @InjectMocks
    private RedirectExecutor redirectExecutor;

    @Mock
    private RedirectFlowManager redirectFlowManager;

    @Mock
    private Intent intentMock;

    @Before
    public void setUp() throws Exception {
        redirectExecutor = new RedirectExecutor(redirectFlowManager);
    }

    @Test
    public void testExecuteIntentAddFlow() throws Exception {
        redirectExecutor.execute(intentMock, FlowAction.ADD_FLOW);
    }
}

Increase of-renderer coverage on RedirectExecutor.

    RedirectExecutor.java

Change-Id: Icdedc03106f5a1f31d22d968ac6aa53de1ffe296
Signed-off-by: Victor Mota <a399842758ce81a1b2704ada69a36369cee4aa4d@atlantico.com.br>


package arez.integration.observed;

import arez.Arez;
import arez.Observer;
import arez.annotations.ArezComponent;
import arez.annotations.Observable;
import arez.annotations.Observed;
import arez.annotations.ObserverRef;
import arez.integration.AbstractArezIntegrationTest;
import org.realityforge.guiceyloops.shared.ValueUtil;
import org.testng.annotations.Test;
import static org.testng.Assert.*;

public class ObservedNonArezDependenciesTest
  extends AbstractArezIntegrationTest
{
  @ArezComponent
  public static abstract class TestComponent1
  {
    int _renderCallCount;

    @Observed( arezOnlyDependencies = false )
    void render()
    {
      getValue();
      _renderCallCount++;
    }

    @ObserverRef
    abstract Observer getRenderObserver();

    @SuppressWarnings( "UnusedReturnValue" )
    @Observable
    abstract long getValue();

    abstract void setValue( long value );
  }

  @Test
  public void scenario()
    throws Exception
  {
    final TestComponent1 component = new ObservedNonArezDependenciesTest_Arez_TestComponent1();

    assertEquals( component._renderCallCount, 1 );

    // reportStale should result in re-render invocation
    Arez.context().safeAction( null, true, false, () -> component.getRenderObserver().reportStale() );

    assertEquals( component._renderCallCount, 2 );

    // Trigger a dependency change, mark observer as dirty
    safeAction( () -> component.setValue( ValueUtil.randomLong() ) );

    assertEquals( component._renderCallCount, 3 );

    // reportStale and dependency change should result in single re-render invocation
    Arez.context().safeAction( () -> {
      component.setValue( ValueUtil.randomLong() );
      component.getRenderObserver().reportStale();
    } );

    assertEquals( component._renderCallCount, 4 );
  }
}

Add integration tests for non-arez dependencies


/**
 * An implementation of the HTTP Digest authentication scheme for Android.
 *
 * With a small effort you can use it to get HTTP digest working with HttpURLConnection or any
 * other HTTP stack.
 *

 * Here is an example of how to make a request and respond to a Digest challenge:
 *
 *

{@code
 * // Step 1. Create the connection
 * URL url = new URL("http://httpbin.org/digest-auth/auth/user/passwd");
 * HttpURLConnection connection = (HttpURLConnection) url.openConnection();
 *
 * // Step 2. Make the request and check to see if the response contains an authorization challenge
 * if (connection.getResponseCode() == HttpURLConnection.HTTP_UNAUTHORIZED) {
 *     // Step 3. Create a authentication object from the challenge...
 *     DigestAuthentication auth = DigestAuthentication.fromResponse(connection);
 *     // ...with correct credentials
 *     auth.username("user").password("passwd");
 *
 *     // Step 4 (Optional). Check if the challenge was a digest challenge of a supported type
 *     if (!auth.canRespond()) {
 *         // No digest challenge or a challenge of an unsupported type - do something else or fail
 *         return;
 *     }
 *
 *     // Step 5. Create a new connection, identical to the original one...
 *     connection = (HttpURLConnection) url.openConnection();
 *     // ...and set the Authorization header on the request, with the challenge response
 *     connection.setRequestProperty(DigestChallengeResponse.HTTP_HEADER_AUTHORIZATION,
 *     auth.getAuthorizationForRequest("GET", connection.getURL().getPath()));
 * }
 * }

 *
 * {@link com.albroco.barebonesdigest.DigestAuthentication} is the main entry point of the API,
 * read the documentation for more examples. Some other useful classes include:
 *

 *
{@link com.albroco.barebonesdigest.WwwAuthenticateHeader} which can be used to parse
 * challenges from WWW-Authenticate headers, including challenges of other types than Digest.

 *
{@link com.albroco.barebonesdigest.DigestChallenge} which provides functionality for
 * parsing digest challenges.

 *
{@link com.albroco.barebonesdigest.DigestChallengeResponse} which provides functionality
 * for generating responses to digest challenges.

 *

 */
package com.albroco.barebonesdigest;

Add top-level package info to javadoc

Add top-level package info to javadoc


package fi.nls.oskari.control.view.modifier.param;

import fi.nls.oskari.annotation.OskariViewModifier;
import fi.nls.oskari.util.JSONHelper;
import fi.nls.oskari.view.modifier.ModifierException;
import fi.nls.oskari.view.modifier.ModifierParams;
import fi.nls.oskari.view.modifier.ParamHandler;
import org.json.JSONArray;
import org.json.JSONObject;

@OskariViewModifier("timeseries")
public class TimeseriesParamHandler extends ParamHandler {
    private static final String KEY_TIME = "time";

    public boolean handleParam(final ModifierParams params) throws ModifierException {
        String paramValue = params.getParamValue();
        if (paramValue == null) {
            return false;
        }
        final JSONObject bundleState = getBundleState(params.getConfig(), BUNDLE_TIMESERIES);
        final String[] timeProps = paramValue.split("/");
        if (timeProps.length != 2) {
            JSONHelper.putValue(bundleState, KEY_TIME, paramValue);
            return false;
        }
        JSONArray time = new JSONArray();
        time.put(timeProps[0]);
        time.put(timeProps[1]);
        JSONHelper.putValue(bundleState, KEY_TIME, time);
        return false;
    }
}

Add handler for timeseries parameter

Add handler for timeseries parameter


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

package org.jboss.shamrock.jaxrs.runtime.graal;

import com.oracle.svm.core.annotate.Substitute;
import com.oracle.svm.core.annotate.TargetClass;
import org.w3c.dom.Document;

import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.MultivaluedMap;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;

@TargetClass(className = "org.jboss.resteasy.plugins.providers.DocumentProvider")
final class DeleteDocumentProvider {

    @Substitute
    public boolean isReadable(Class<?> clazz, Type type, Annotation[] annotation, MediaType mediaType) {
        return false;
    }

    @Substitute
    public Document readFrom(Class<Document> clazz, Type type, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, String> headers, InputStream input) throws IOException, WebApplicationException {
        return null;
    }

    @Substitute
    public boolean isWriteable(Class<?> clazz, Type type, Annotation[] annotation, MediaType mediaType) {
        return false;
    }

    @Substitute
    public void writeTo(Document document, Class<?> clazz, Type type, Annotation[] annotation, MediaType mediaType, MultivaluedMap<String, Object> headers, OutputStream output) throws IOException, WebApplicationException {

    }
}

Remove DocumentProvider from native image

This is done since the Provider is very unlikely to be needed and it
contributes a non trivial amount of code to the image.
A future implementation might be more sophisticated about the cases
under which the DocumentProvider is removed

Fixes: #708


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

import zorbage.type.algebra.Group;

/**
 *
 * @author Barry DeZonia
 *
 * @param <U>
 */
public class ArrayStorageGeneric<T extends Group<T,U>,U>
	implements Storage<U>
{

	private final Object[] data;
	private final T g;

	public ArrayStorageGeneric(long size, T g) {
		if (size < 0)
			throw new IllegalArgumentException("ArrayStorage cannot handle a negative request");
		if (size > Integer.MAX_VALUE)
			throw new IllegalArgumentException("ArrayStorage cannot handle such a large request");
		this.data = new Object[(int)size];
		for (int i = 0; i < size; i++) {
			this.data[i] = g.construct();
		}
		this.g = g;
	}

	@Override
	public void put(long index, U value) {
		g.assign(value, (U)data[(int)index]);
	}

	@Override
	public void get(long index, U value) {
		g.assign((U)data[(int)index], value);
	}

	@Override
	public long size() {
		return data.length;
	}

}

Define generic storage based upon a group


package com.codenvy.ide.ext.datasource.client.common;

import com.codenvy.ide.api.mvp.View;
import com.codenvy.ide.api.parts.PartStackUIResources;
import com.google.gwt.dom.client.Style;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.DockLayoutPanel;
import com.google.gwt.user.client.ui.LayoutPanel;

public abstract class ViewWithToolbar<T> extends Composite implements View<T> {

    private final LayoutPanel     toolBar;
    private final DockLayoutPanel container;
    private T                     delegate;

    public ViewWithToolbar(final PartStackUIResources resources) {
        container = new DockLayoutPanel(Style.Unit.PX);
        initWidget(container);
        container.setSize("100%", "100%");
        toolBar = new LayoutPanel();
        toolBar.addStyleName(resources.partStackCss().ideBasePartToolbar());
        container.addNorth(toolBar, 20);

        // this hack used for adding box shadow effect to toolbar
        toolBar.getElement().getParentElement().getStyle().setOverflow(Style.Overflow.VISIBLE);
    }

    /** {@inheritDoc} */
    @Override
    public void setDelegate(T delegate) {
        this.delegate = delegate;
    }

    public T getDelegate() {
        return delegate;
    }

    public DockLayoutPanel getContainer() {
        return container;
    }

    public LayoutPanel getToolBar() {
        return toolBar;
    }
}

Add view with a toolbar (but without minimize button as in BaseView)


package io.quarkus.hibernate.reactive;

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

import javax.enterprise.context.control.ActivateRequestContext;
import javax.inject.Inject;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

import org.hibernate.SessionFactory;
import org.hibernate.engine.spi.SessionFactoryImplementor;
import org.hibernate.engine.transaction.jta.platform.spi.JtaPlatform;
import org.hibernate.reactive.mutiny.Mutiny;
import org.hibernate.resource.transaction.spi.TransactionCoordinatorBuilder;
import org.hibernate.service.spi.ServiceRegistryImplementor;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.spec.JavaArchive;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;

import io.quarkus.test.QuarkusUnitTest;

public class NoJtaTest {

    @RegisterExtension
    static QuarkusUnitTest runner = new QuarkusUnitTest()
            .setArchiveProducer(() -> ShrinkWrap.create(JavaArchive.class)
                    .addClass(MyEntity.class)
                    .addAsResource("application.properties"));

    @Inject
    SessionFactory sessionFactory; // This is an ORM SessionFactory, but it's backing Hibernate Reactive.

    @Inject
    Mutiny.Session session;

    @Test
    @ActivateRequestContext
    public void test() {
        ServiceRegistryImplementor serviceRegistry = sessionFactory.unwrap(SessionFactoryImplementor.class)
                .getServiceRegistry();

        // Two assertions are necessary, because these values are influenced by separate configuration
        assertThat(serviceRegistry.getService(JtaPlatform.class).retrieveTransactionManager()).isNull();
        assertThat(serviceRegistry.getService(TransactionCoordinatorBuilder.class).isJta()).isFalse();

        // Quick test to make sure HRX works
        MyEntity entity = new MyEntity("default");
        MyEntity retrievedEntity = session.withTransaction(tx -> session.persist(entity))
                .chain(() -> session.withTransaction(tx -> session.clear().find(MyEntity.class, entity.getId())))
                .await().indefinitely();
        assertThat(retrievedEntity)
                .isNotSameAs(entity)
                .returns(entity.getName(), MyEntity::getName);
    }

    @Entity
    public static class MyEntity {

        private long id;

        private String name;

        public MyEntity() {
        }

        public MyEntity(String name) {
            this.name = name;
        }

        @Override
        public String toString() {
            return getClass().getSimpleName() + ":" + name;
        }

        @Id
        @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "defaultSeq")
        public long getId() {
            return id;
        }

        public void setId(long id) {
            this.id = id;
        }

        public String getName() {
            return name;
        }

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

Test that JTA is disabled for Hibernate Reactive persistence units

Signed-off-by: Yoann Rodière <be2a24d2f52a7ba2aca48263378b2614d5b68cd6@hibernate.org>


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

package com.google.gerrit.pgm.util;

import java.util.logging.Formatter;
import java.util.logging.Handler;
import java.util.logging.Level;
import java.util.logging.LogRecord;
import java.util.logging.Logger;
import java.util.logging.StreamHandler;

public class GuiceLogger {
  private static final Handler HANDLER;
  static {
    HANDLER = new StreamHandler(System.out, new Formatter() {
      public String format(LogRecord record) {
        return String.format("[Guice %s] %s%n", record.getLevel().getName(),
            record.getMessage());
      }
    });
    HANDLER.setLevel(Level.ALL);
  }

  private GuiceLogger() {
  }

  public static Logger getLogger() {
    return Logger.getLogger("com.google.inject");
  }

  public static void enable() {
    Logger guiceLogger = getLogger();
    guiceLogger.addHandler(GuiceLogger.HANDLER);
    guiceLogger.setLevel(Level.ALL);
  }

  public static void disable() {
    Logger guiceLogger = getLogger();
    guiceLogger.setLevel(Level.OFF);
    guiceLogger.removeHandler(GuiceLogger.HANDLER);
  }
}

Add utility class to inspect Guice wiring

It is known that it is not so easy to troubleshoot Guice wiring problems.
Thankfully the Guice authors added java util logging facility. This change
introduces the Guice logger activator to easily enable/disable Guice logging.

To activate Guice logging add this line to your run() method:

  @Override
  public int run() throws Exception {
    GuiceLogger.enable();
    [...]
  }

Sample output from reindex pgm:
  http://paste.openstack.org/show/54356

Change-Id: Idd0d71e3660d098b593dc9fc7d9147fde49b8a16


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

package io.michaelrocks.lightsaber.processor.descriptors;

import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.objectweb.asm.Type;

public class EnumValueDescriptor {
    private final Type type;
    private final String value;

    public EnumValueDescriptor(final Type type, final String value) {
        this.type = type;
        this.value = value;
    }

    public static EnumValueDescriptor from(final String desc, final String value) {
        return new EnumValueDescriptor(Type.getType(desc), value);
    }

    public Type getType() {
        return type;
    }

    public String getValue() {
        return value;
    }

    @Override
    public boolean equals(final Object object) {
        if (this == object) {
            return true;
        }

        if (object == null || getClass() != object.getClass()) {
            return false;
        }

        final EnumValueDescriptor that = (EnumValueDescriptor) object;
        return new EqualsBuilder()
                .append(type, that.type)
                .append(value, that.value)
                .isEquals();
    }

    @Override
    public int hashCode() {
        return new HashCodeBuilder(17, 37)
                .append(type)
                .append(value)
                .toHashCode();
    }

    @Override
    public String toString() {
        return new ToStringBuilder(this)
                .append("type", type)
                .append("value", value)
                .toString();
    }
}

Implement a descriptor for enum values

Implement a descriptor for enum values


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

import javax.annotation.Generated;

Add @Generated to protobuf package file.