/*
 * Java Genetic Algorithm Library (@__identifier__@).
 * Copyright (c) @__year__@ Franz Wilhelmstötter
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * Author:
 *    Franz Wilhelmstötter (franz.wilhelmstoetter@gmx.at)
 */
package org.jenetics.util;

import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.TimeUnit;

import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.State;
import org.openjdk.jmh.runner.Runner;
import org.openjdk.jmh.runner.RunnerException;
import org.openjdk.jmh.runner.options.Options;
import org.openjdk.jmh.runner.options.OptionsBuilder;

/**
 * @author Franz Wilhelmstötter
 * @version 3.0 — $Date: 2014-07-14 $
 * @since 3.0
 */
@State(Scope.Benchmark)
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
public class SeqPerf {

	private final int index = ThreadLocalRandom.current().nextInt(1000);

	private final Integer[] array = new Integer[1000];
	{
		for (int i = 0; i < array.length; ++i) {
			array[i] = i;
		}
	}
	private final MSeq<Integer> seq = MSeq.ofLength(1000);
	{
		for (int i = 0; i < seq.length(); ++i) {
			seq.set(i, i);
		}
	}

	@Benchmark
	public Integer getFromArray() {
		return array[index];
	}

	@Benchmark
	public Integer getFromSeq() {
		return seq.get(index);
	}

	public static void main(String[] args) throws RunnerException {
		final Options opt = new OptionsBuilder()
			.include(".*" + SeqPerf.class.getSimpleName() + ".*")
			.warmupIterations(3)
			.measurementIterations(5)
			.threads(1)
			.forks(1)
			.build();

		new Runner(opt).run();
	}

}

Add performance test for Seq implementation.


//
// DebugTools.java
//

/*
LOCI Common package: utilities for I/O, reflection and miscellaneous tasks.
Copyright (C) 2005-@year@ Melissa Linkert, Curtis Rueden and Chris Allan.

This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.

This program 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 General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
*/

package loci.common;

import java.io.ByteArrayOutputStream;
import java.io.PrintStream;

/**
 * A utility class with convenience methods for debugging.
 *
 *

Source code:

 *
Trac,
 * SVN

 *
 * @author Curtis Rueden ctrueden at wisc.edu
 */
public final class DebugTools {

  // -- Constructor --

  private DebugTools() { }

  // -- DebugTools methods --

  /** Extracts the given exception's corresponding stack trace to a string. */
  public static String getStackTrace(Throwable t) {
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    t.printStackTrace(new PrintStream(out));
    return new String(out.toByteArray());
  }

}

Add utility method for extracting a stack trace string from an exception.


package com.namelessmc.java_api.logger;

import java.util.logging.Level;
import java.util.logging.Logger;

public class JavaLoggerLogger extends ApiLogger {

	private final Logger logger;
	private final Level level;
	private final String prefix;

	public JavaLoggerLogger(final Logger logger, final Level level, final String prefix) {
		this.logger = logger;
		this.level = level;
		this.prefix = prefix;
	}

	@Override
	public void log(final String string) {
		this.logger.log(this.level, this.prefix + string);
	}

}

Add apilogger implementation using java logger


package session;

import javax.annotation.PostConstruct;
import javax.ejb.Singleton;
import javax.ejb.TransactionManagement;
import javax.ejb.TransactionManagementType;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import domain.Customer;
import domain.Order;

/** Create one of each entity so the database
 * is "not null" - using /import.sql only works
 * in Hibernate.
 * @author ian
 */
@Singleton
@TransactionManagement(TransactionManagementType.CONTAINER)
public class PopulateDatabaseSingletonBean {

		@PersistenceContext(name="customer") EntityManager customerEntityManager;
		@PersistenceContext(name="orders") EntityManager orderEntityManager;

		@PostConstruct
		public void initDB() {
			System.out.println("PopulateDatabaseSingletonBean.initCustomerDB()");
			Customer cust = new Customer("Idon T'kare");
			customerEntityManager.persist(cust);

			System.out.println("PopulateDatabaseSingletonBean.initOrdersDB()");
			Order order = new Order();
			orderEntityManager.persist(order);
		}
}

Create an EE6 singleton bean to pre-load the database, since /import.sql is Hibernate-specific, ignored by most. Speaking of ignored, this bean's @PostConstruct annotated methods are ignored, at least by JBoss 6.0.0.20100911-M5.


package org.openmhealth.shim.common.mapper;

import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.fasterxml.jackson.datatype.jdk8.Jdk8Module;
import com.fasterxml.jackson.datatype.jsr310.JSR310Module;
import org.openmhealth.schema.serializer.Rfc3339OffsetDateTimeSerializer;
import org.testng.annotations.BeforeClass;

import java.time.OffsetDateTime;

/**
 * @author Emerson Farrugia
 */
public abstract class DataPointMapperUnitTests {

    protected static final ObjectMapper objectMapper = new ObjectMapper();

    @BeforeClass
    public static void initializeObjectMapper() {

        // we represent JSON numbers as Java BigDecimals
        objectMapper.enable(DeserializationFeature.USE_BIG_DECIMAL_FOR_FLOATS);

        // we serialize dates, date times, and times as strings, not numbers
        objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);

        // we default to the ISO8601 format for JSR-310 and support Optional
        objectMapper.registerModule(new JSR310Module());
        objectMapper.registerModule(new Jdk8Module());

        // but we have to explicitly support the RFC3339 format over ISO8601 to make JSON Schema happy, specifically to
        // prevent the truncation of zero second fields
        SimpleModule rfc3339Module = new SimpleModule("rfc3339Module");
        rfc3339Module.addSerializer(new Rfc3339OffsetDateTimeSerializer(OffsetDateTime.class));
        objectMapper.registerModule(rfc3339Module);
    }
}

Add base class for mapper unit tests

Add base class for mapper unit tests


package water.fvec;

import org.testng.AssertJUnit;
import org.testng.annotations.Test;
import water.TestUtil;

import java.util.Arrays;

public class C4SChunkTest extends TestUtil {
  @Test void test_inflate_impl() {
    for (int l=0; l<1; ++l) {
      NewChunk nc = new NewChunk(null, 0);

      // -2.147483647, 0, 0.0000215, 2.147583647, NA for l==0
      // NA, -2.147483647, 0, 0.0000215, 2.147583647, NA for l==1
      long[] man = new long[]{-2147483647, 0, 215, 188001238, 2147483647};
      int[] exp = new int[]{-9, 1, -6, -8, -9};
      if (l==1) nc.addNA(); //-2147483648
      for (int i = 0; i < man.length; ++i) nc.addNum(man[i], exp[i]);
      nc.addNA();

      Chunk cc = nc.compress();
      AssertJUnit.assertEquals(man.length + 1 + l, cc.len());
      AssertJUnit.assertTrue(cc instanceof C4SChunk);
      if (l==1) AssertJUnit.assertTrue(cc.isNA0(0));
      for (int i = 0; i < man.length; ++i)
        AssertJUnit.assertTrue("Expected: " + man[i] * Math.pow(10, exp[i]) + ", but is " + cc.at0(l+i), Math.abs((man[i] * Math.pow(10, exp[i])) - cc.at0(l+i)) < 1e-10);
      AssertJUnit.assertTrue(cc.isNA0(man.length + l));

      Chunk cc2 = cc.inflate_impl(new NewChunk(null, 0)).compress();
      AssertJUnit.assertEquals(man.length + 1 + l, cc.len());
      if (l==1) AssertJUnit.assertTrue(cc2.isNA0(0));
      for (int i = 0; i < man.length; ++i)
        AssertJUnit.assertTrue("Expected: " + man[i] * Math.pow(10, exp[i]) + ", but is " + cc2.at0(l+i), Math.abs((man[i] * Math.pow(10, exp[i])) - cc2.at0(l+i)) < 1e-10);
      AssertJUnit.assertTrue(cc2.isNA0(man.length + l));
      AssertJUnit.assertTrue(cc2 instanceof C4SChunk);

      AssertJUnit.assertTrue(Arrays.equals(cc._mem, cc2._mem));
    }
  }
}

Add inflate_impl test for C4SChunk.

PUBDEV-2: Add inflate_impl test for C4SChunk.


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

/*
 * Test class for BinaryTCPClientImpl utility methods.
 *
 */
package org.apache.jmeter.protocol.tcp.sampler;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;

import junit.framework.TestCase;

public class LengthPrefixedBinaryTCPClientImplTest extends TestCase {

    public void testError() throws Exception {
        ByteArrayOutputStream os = null;
        ByteArrayInputStream is = null;
        LengthPrefixedBinaryTCPClientImpl lp = new LengthPrefixedBinaryTCPClientImpl();
        try {
            lp.write(os, is);
            fail("Expected java.lang.UnsupportedOperationException");
        } catch (java.lang.UnsupportedOperationException expected) {
        }
    }

    public void testValid() throws Exception {
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        LengthPrefixedBinaryTCPClientImpl lp = new LengthPrefixedBinaryTCPClientImpl();
        final String DATA = "31323334353637";
        lp.write(os, DATA);
        os.close();
        final byte[] byteArray = os.toByteArray();
        assertEquals(2+(DATA.length()/2), byteArray.length);
        ByteArrayInputStream is = new ByteArrayInputStream(byteArray);
        assertEquals(DATA, lp.read(is));
    }

}

Add some tests for LengthPrefixedBinaryTCPClientImpl

git-svn-id: https://svn.apache.org/repos/asf/jakarta/jmeter/trunk@711667 13f79535-47bb-0310-9956-ffa450edef68

Former-commit-id: e77538aa069d9ee512bf443c995d231d19989c1b


package com.samovich.cop2800.chapter8;

/**
 * Filename ReturnArray.java
 * Created by Valery Samovich
 * Written on 6/21/2016
 */
public class ReturnArray {

    /**
     * main method
     * @param args
     */
    public static void main(String[] args) {
        System.out.print("Returned array: ");
        // loop over returned array
        for (int i = 0; i < ReturnArray.getArray().length; i++)
            System.out.print(ReturnArray.getArray()[i] + " ");
    }

    /**
     * Retunr the array
     * @return
     */
    private static int[] getArray() {
        int[] scores = {90, 80, 70, 60};
        return scores;
    }
}

Add example for array a method

Add example for array a method


package net.spals.appbuilder.app.core.generic;

import com.google.inject.CreationException;
import com.google.inject.Injector;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;

import static com.googlecode.catchexception.CatchException.catchException;
import static com.googlecode.catchexception.CatchException.caughtException;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.instanceOf;
import static org.hamcrest.Matchers.is;

/**
 * A series of functional tests for {@link GenericWorkerApp}
 * which do not fit into the minimal or sample test classes.
 *
 * @author tkral
 */
public class GenericWorkerAppFTests {
    private final Logger LOGGER = LoggerFactory.getLogger(GenericWorkerAppFTests.class);

    @Test
    public void testModuleOverrideError() {
        // This doesn't really test anything in the AppBuilder code
        // but just proves out how Guice errors out on override bindings
        catchException(() -> new GenericWorkerApp.Builder("testModuleOverrideError", LOGGER)
            .addModule(binder -> binder.bind(MySingletonService.class)
                .toInstance(new MySingletonServiceA()))
            .addModule(binder -> binder.bind(MySingletonService.class)
                .toInstance(new MySingletonServiceB()))
            .build());

        assertThat(caughtException(), instanceOf(CreationException.class));
    }

    @DataProvider
    Object[][] enableBindingOverridesProvider() {
        final MySingletonService serviceA = new MySingletonServiceA();
        final MySingletonService serviceB = new MySingletonServiceB();

        return new Object[][] {
                // Ensure that binding order is honored. The last one in is chosen
                {serviceA, serviceB},
                {serviceB, serviceA},
        };
    }

    @Test(dataProvider = "enableBindingOverridesProvider")
    public void testEnableBindingOverrides(final MySingletonService firstService,
                                           final MySingletonService secondService) {
        final GenericWorkerApp app = new GenericWorkerApp.Builder(
                "testEnableBindingOverrides", LOGGER)
            .addModule(binder -> binder.bind(MySingletonService.class)
                .toInstance(firstService))
            .addModule(binder -> binder.bind(MySingletonService.class)
                .toInstance(secondService))
            .enableBindingOverrides()
            .build();

        final Injector serviceInjector = app.getServiceInjector();
        assertThat(serviceInjector.getInstance(MySingletonService.class), is(secondService));
    }

    private interface MySingletonService {  }

    private class MySingletonServiceA implements MySingletonService {  }

    private class MySingletonServiceB implements MySingletonService {  }
}

Add functional tests for enableBindingOverrides option


package net.greypanther.fastutil.tests;

import org.junit.Test;

import it.unimi.dsi.fastutil.ints.IntBigArrayBigList;

public final class IntBigList {
  @Test(expected=IndexOutOfBoundsException.class)
  public void testListIterator_tooLow() {
    new IntBigArrayBigList().listIterator(-1L);
  }

  @Test(expected=IndexOutOfBoundsException.class)
  public void testListIterator_tooHigh() {
    new IntBigArrayBigList().listIterator(1L);
  }
}

Add failing test for IntBigArrayBigList.listIterator


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

import static org.junit.Assert.assertEquals;

import org.junit.Test;

import nom.bdezonia.zorbage.algebras.G;
import nom.bdezonia.zorbage.type.data.float64.real.Float64Member;
import nom.bdezonia.zorbage.type.storage.array.ArrayStorage;
import nom.bdezonia.zorbage.type.storage.array.ArrayStorageBigDecimal;
import nom.bdezonia.zorbage.type.storage.datasource.IndexedDataSource;

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

	@Test
	public void test1() {

		Float64Member value = G.DBL.construct();
		IndexedDataSource<Float64Member> nums = ArrayStorage.allocateDoubles(
				new double[] {1.1, 1.1, 1.2, 3, 3, 3, 1.1, 4, 5, 5, 5});
		// Unique expects a sorted list as input
		Sort.compute(G.DBL, nums);
		IndexedDataSource<Float64Member> uniqueNums =
				Unique.compute(G.DBL, nums);

		assertEquals(5, uniqueNums.size());

		uniqueNums.get(0, value);
		assertEquals(1.1, value.v(), 0);

		uniqueNums.get(1, value);
		assertEquals(1.2, value.v(), 0);

		uniqueNums.get(2, value);
		assertEquals(3, value.v(), 0);

		uniqueNums.get(3, value);
		assertEquals(4, value.v(), 0);

		uniqueNums.get(4, value);
		assertEquals(5, value.v(), 0);
	}
}

Define a test for the Unique algorithm

Define a test for the Unique algorithm


package cgeo.geocaching.models;

import cgeo.geocaching.connector.trackable.TrackableBrand;
import cgeo.geocaching.enumerations.LogTypeTrackable;

import org.apache.commons.lang3.StringUtils;

public final class TrackableLog {
    public TrackableLog(final String geocode, final String trackCode, final String name, final int id, final int ctl, final TrackableBrand brand) {
        this.geocode = geocode;
        this.trackCode = trackCode;
        this.name = name;
        this.id = id;
        this.ctl = ctl;
        this.brand = brand;
    }

    public final int ctl;
    public final int id;
    public final String geocode;
    public final String trackCode;
    public final String name;
    public final TrackableBrand brand;
    public LogTypeTrackable action = LogTypeTrackable.DO_NOTHING; // base.logTrackablesAction - no action

    public void setAction(final LogTypeTrackable logTypeTrackable) {
        action = logTypeTrackable;
    }

    @Override
    public int hashCode() {
        return StringUtils.defaultString(trackCode).hashCode();
    }

    @Override
    public boolean equals(final Object obj) {
        if (!(obj instanceof TrackableLog)) {
            return false;
        }
        final TrackableLog tb = (TrackableLog) obj;
        return StringUtils.defaultString(tb.trackCode).equals(trackCode);
    }
}

package cgeo.geocaching.models;

import cgeo.geocaching.connector.trackable.TrackableBrand;
import cgeo.geocaching.enumerations.LogTypeTrackable;

import org.apache.commons.lang3.StringUtils;

public final class TrackableLog {
    public final int ctl;
    public final int id;
    public final String geocode;
    public final String trackCode;
    public final String name;
    public final TrackableBrand brand;
    public LogTypeTrackable action = LogTypeTrackable.DO_NOTHING; // base.logTrackablesAction - no action

    public TrackableLog(final String geocode, final String trackCode, final String name, final int id, final int ctl, final TrackableBrand brand) {
        this.geocode = geocode;
        this.trackCode = trackCode;
        this.name = name;
        this.id = id;
        this.ctl = ctl;
        this.brand = brand;
    }

    public void setAction(final LogTypeTrackable logTypeTrackable) {
        action = logTypeTrackable;
    }

    @Override
    public int hashCode() {
        return StringUtils.defaultString(trackCode).hashCode();
    }

    @Override
    public boolean equals(final Object obj) {
        if (!(obj instanceof TrackableLog)) {
            return false;
        }
        final TrackableLog tb = (TrackableLog) obj;
        return StringUtils.defaultString(tb.trackCode).equals(trackCode);
    }
}

Fix codacy: Fields should be declared at the top of the class


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

package permafrost.tundra.bytes;

import org.junit.Test;
import permafrost.tundra.string.StringHelper;

import static org.junit.Assert.*;

public class BytesHelperTest {
    @Test(expected = IllegalArgumentException.class)
    public void testNormalizeWithObject() throws Exception {
        BytesHelper.normalize(new Object());
    }

    @Test
    public void testNormalizeWithString() throws Exception {
        String message = "test";
        assertArrayEquals(message.getBytes(StringHelper.DEFAULT_CHARACTER_ENCODING), BytesHelper.normalize(message));
    }

    @Test
    public void testNormalizeWithStringAndEncoding() throws Exception {
        String message = "test";
        String encoding = "UTF-16";
        assertArrayEquals(message.getBytes(encoding), BytesHelper.normalize(message, encoding));
    }

    @Test
    public void testNormalizeWithInputStream() throws Exception {
        String message = "test";
        java.io.InputStream in = new java.io.ByteArrayInputStream(message.getBytes(StringHelper.DEFAULT_CHARACTER_ENCODING));
        assertArrayEquals(message.getBytes(StringHelper.DEFAULT_CHARACTER_ENCODING), BytesHelper.normalize(in));
    }

    @Test
    public void testNormalizeWithBytes() throws Exception {
        String message = "test";
        assertArrayEquals(message.getBytes(StringHelper.DEFAULT_CHARACTER_ENCODING), BytesHelper.normalize(message.getBytes(StringHelper.DEFAULT_CHARACTER_ENCODING)));
    }

    @Test
    public void testBase64Encode() throws Exception {
        assertEquals("test", new String(BytesHelper.base64Decode("dGVzdA=="), "UTF-8"));
    }

    @Test
    public void testBase64Decode() throws Exception {
        assertEquals("dGVzdA==", BytesHelper.base64Encode("test".getBytes("UTF-8")));
    }
}

Add unit tests for BytesHelper class

Add unit tests for BytesHelper class


package com.ushahidi.android.presentation.model.mapper;

import com.ushahidi.android.domain.entity.Form;
import com.ushahidi.android.presentation.model.FormModel;

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

import javax.inject.Inject;

/**
 * Transforms data between domain layer and presentation layer
 *
 * @author Ushahidi Team <team@ushahidi.com>
 */
public class FormModelDataMapper {

    /**
     * Default constructor
     */
    @Inject
    public FormModelDataMapper() {
        // Do nothing
    }

    /**
     * Maps {@link Form} to {@link FormModel}
     *
     * @param form The form  to be mapped
     * @return The mapped form model
     */
    public FormModel map(Form form) {
        FormModel formModel = null;
        if (form != null) {
            formModel = new FormModel();
            formModel._id = form._id;
            formModel.setCreated(form.getCreated());
            formModel.setUpdated(form.getUpdated());
            formModel.setDescription(form.getDescription());
            formModel.setName(form.getName());
            formModel.setDeploymentId(form.getDeploymentId());
            formModel.setDisabled(form.isDisabled());
        }
        return formModel;
    }

    /**
     * Maps {@link FormModel} to {@link Form}
     *
     * @param formModel The form to be mapped
     * @return The mapped form
     */
    public Form map(FormModel formModel) {
        Form form = null;
        if (formModel != null) {
            form = new Form();
            form._id = formModel._id;
            form.setCreated(formModel.getCreated());
            form.setUpdated(formModel.getUpdated());
            form.setDeploymentId(formModel.getDeploymentId());
            form.setName(formModel.getName());
            form.setDescription(formModel.getDescription());
            form.setDisabled(formModel.isDisabled());
        }
        return form;
    }

    /**
     * Maps a list of {@link Form} to a list of {@link FormModel}
     *
     * @param formList The form entity list
     * @return The mapped form entity list
     */
    public List<FormModel> map(List<Form> formList) {
        List<FormModel> formModelList = null;
        if (formList != null) {
            formModelList = new ArrayList<>();
            for (Form form : formList) {
                FormModel formModel = map(form);
                formModelList.add(formModel);
            }
        }
        return formModelList;
    }
}

Add form model data mapper

Add form model data mapper


package cs437.som.visualization;

import java.awt.Color;

/**
 * A color progression from green (#00FF00) to red (#FF0000).
 */
public class GreenToRedHeat implements ColorProgression {
    private static final float GREEN_HUE_SCALE = 1.2f;
    private static final float CIRCLE_DEG = 360.0f;

    @Override
    public Color getColor(int intensity) {
        if (intensity < 0)
            return Color.green;
        else if (intensity > 100)
            return Color.red;
        else {
            final float hue = ((100-intensity) * GREEN_HUE_SCALE) / CIRCLE_DEG;
            final int rgb = Color.HSBtoRGB(hue, 1.0f, 1.0f);
            return new Color(rgb);
        }
    }
}

Add a green to red color progression.

Add a green to red color progression.


package arrays.maximum_sub_array;
import arrays.maximum_sub_array.SubArray; 			// My implementation of class SubArray to hold result sub array
import arrays.maximum_sub_array.MaximumSubArray;	// My implementation of Kadane's algorithm to find maximum sub array

/*
	This class tests Kadane's Maximum sub array algorithm
*/

class TestMaximumSubArray{

	// Tests with valid as well as invalid input

	public static void testA(){

		// Define test arrays

		int a1[] = {-2,-3,4,-1,-2,1,5,-3};
		int a2[] = {-5,-4,-7,-6,-3,-2,-1,-9};
		int a3[] = {};
		int a4[] = {10,-15,5,-2,4,19,-30,20,4};
		int a5[] = {1,-1,1,-2,1,1,2,1,4,-4,5};
		int a6[] = null;
		int a7[] = {2,-1,-1,5,-4,9};

		// Find maximum sum sub arrays

		SubArray s1 = MaximumSubArray.find(a1);
		SubArray s2 = MaximumSubArray.find(a2);
		SubArray s3 = MaximumSubArray.find(a3);
		SubArray s4 = MaximumSubArray.find(a4);
		SubArray s5 = MaximumSubArray.find(a5);
		SubArray s6 = MaximumSubArray.find(a6);
		SubArray s7 = MaximumSubArray.find(a7);
		// Display results

		System.out.println(s1);
		System.out.println(s2);

		if(s3 == null)
			System.out.println("s3 null");

		System.out.println(s4);
		System.out.println(s5);

		if(s6 == null)
			System.out.println("s6 null");

		System.out.println(s7);

	}

	public static void main(String args[]){

		// Call testA
		testA();
	}

}

Add test class for Kadane's algorithm

Add test class for Kadane's algorithm


package no.cantara.jau;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

public class ProcessKiller {
    private static final Logger log = LoggerFactory.getLogger(ProcessKiller.class);
    private static final String RUNNING_PROCESS_FILENAME = "runningProcess.txt";

    public void killExistingProcessIfRunning() {
        Path file = Paths.get(RUNNING_PROCESS_FILENAME);
        if (Files.exists(file)) {
            String pid = null;
            try {
                pid = new String(Files.readAllBytes(Paths.get(RUNNING_PROCESS_FILENAME)));
            } catch (IOException e) {
                log.warn("Could not read file={}. Possible multiple processes!", RUNNING_PROCESS_FILENAME);
            }
            if (isValidPid(pid)) {
                killRunningProcess(pid);
            }
        } else {
            log.info("{} not found. Assuming no existing process is running.", RUNNING_PROCESS_FILENAME);
        }
    }

    public boolean isValidPid(String pid) {
        // TODO: How to check if valid pid?
        try {
            Integer.parseInt(pid);
            return true;
        } catch (NumberFormatException e) {
            log.warn("PID is not valid integer. Got: '{}'", pid, e);
            return false;
        }
    }

    public void killRunningProcess(String pid) {
        log.info("Killing existing managed process with pid={}", pid);
        Runtime rt = Runtime.getRuntime();
        ProcessBuilder processBuilder;

        if (System.getProperty("os.name").toLowerCase().contains("windows")) {
            processBuilder = new ProcessBuilder("taskkill", pid);
            killProcess(pid, processBuilder);
        } else { //unix
            processBuilder = new ProcessBuilder("kill", "-9", pid);
            killProcess(pid, processBuilder);
        }
    }

    public void killProcess(String pid, ProcessBuilder processBuilder) {
        try {
            Process p = processBuilder.start();
            try {
                p.waitFor();
                if (p.exitValue() == 0) {
                    log.info("Successfully killed existing managed process pid={}", pid);
                } else {
                    printErrorCommandFromProcess(p);
                    log.warn("Could not kill existing managed process pid={}, process exitValue={}", pid, p.exitValue());
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        } catch (IOException e) {
            log.warn("Could not kill existing managed process pid={}. Possible duplicate processes!", pid, e);
        }
    }

    public void printErrorCommandFromProcess(Process p) throws IOException {
        BufferedReader reader =
                new BufferedReader(new InputStreamReader(p.getErrorStream()));
        StringBuilder builder = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
            builder.append(line);
        }
        String result = builder.toString();
        log.error("Error output from kill command: '{}'", result);
    }
}

Add processkiller for checking for managed services already running when JAU starts


import java.io.*;
import java.util.*;

public class harshitmalik03_Word_Break {
        public static void main(String[] args)throws Exception{
            BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
            System.out.println("Enter the number of words in the dictionary");
            int n = Integer.parseInt(br.readLine());
//            ArrayList<String> arr = new ArrayList<>();
            String[] words ;
            System.out.println("Enter the words seperated by a space");
            words = br.readLine().split(" ");
            List B = Arrays.asList(words);
            System.out.println("Enter the sentence");
            String A = br.readLine();
            int val = wordBreak(A, B);
            System.out.print(val);
        }

        public static int wordBreak(String A, List B){
            int[] dp = new int[A.length()];

            for(int i = 0 ; i < dp.length ; i++){
                for(int j = 0 ; j <= i ; j++){
                    String toCheck = A.substring(j,i+1);
                    if(B.contains(toCheck)){
                        if(j > 0){
                            dp[i] += dp[j-1];
                        }else{
                            dp[i] += 1;
                        }
                    }
                }
            }
            if(dp[A.length()-1] > 0){
                return 1;
            }else{
                return 0;
            }

        }

}

Add Word Break Java Code

Add Word Break Java Code


//@@author A0141052Y
package guitests;

import static org.junit.Assert.assertTrue;

import org.junit.Test;

import seedu.task.testutil.TestTask;

public class SearchCommandTest extends TaskManagerGuiTest {
    @Test
    public void search() {
        TestTask[] currentList = td.getTypicalTasks();

        // test search full name
        assertSearchResult(td.daniel.getName().taskName, td.daniel);

        // test search partial name
        assertSearchResult("Have lunch", td.daniel);

        // test search no name
        assertSearchResult("", currentList);

        // test search no results
        assertSearchResult("this does not exist");
    }

    private void resetCommandBox() {
        commandBox.pressEnter();
    }

    private void assertSearchResult(String query, TestTask... expectedHits ) {
        commandBox.runCommand("searchbox");
        commandBox.enterCommand(query);
        assertListSize(expectedHits.length);
        assertTrue(taskListPanel.isListMatching(expectedHits));

        commandBox.runCommand(query);
        assertListSize(expectedHits.length);
        assertTrue(taskListPanel.isListMatching(expectedHits));

        resetCommandBox();
    }
}

Add basic test cases for searchbox

Add basic test cases for searchbox


package com.intellij.debugger.streams.trace.smart;

import com.sun.jdi.Value;
import org.jetbrains.annotations.NotNull;

/**
 * @author Vitaliy.Bibaev
 */
public class TraceElementImpl implements TraceElement {
  private final int myTime;
  private final Value myValue;

  public TraceElementImpl(int time, @NotNull Value value) {
    myTime = time;
    myValue = value;
  }

  @Override
  public int getTime() {
    return myTime;
  }

  @NotNull
  @Override
  public Value getValue() {
    return myValue;
  }
}

package com.intellij.debugger.streams.trace.smart;

import com.sun.jdi.Value;
import org.jetbrains.annotations.NotNull;

import java.util.Objects;

/**
 * @author Vitaliy.Bibaev
 */
public class TraceElementImpl implements TraceElement {
  private final int myTime;
  private final Value myValue;

  public TraceElementImpl(int time, @NotNull Value value) {
    myTime = time;
    myValue = value;
  }

  @Override
  public boolean equals(Object obj) {
    if (obj instanceof TraceElement) {
      final int time = ((TraceElement)obj).getTime();
      final Value value = ((TraceElement)obj).getValue();
      return time == myTime && myValue.equals(value);
    }

    return false;
  }

  @Override
  public int hashCode() {
    return Objects.hash(myTime, myValue);
  }

  @Override
  public int getTime() {
    return myTime;
  }

  @NotNull
  @Override
  public Value getValue() {
    return myValue;
  }
}

Add equals/hashCode into TraceElement implementation


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

// https://www.hackerrank.com/challenges/angry-professor/problem
public class AngryProfessor {

    private static final String SPACE = " ";

    private class Case {
        private final int totalStudents;
        private final int minStudentsOnTime;
        private final int[] arrivals;

        public Case(int totalStudents, int minStudentsOnTime, int[] arrivals) {
            this.totalStudents = totalStudents;
            this.minStudentsOnTime = minStudentsOnTime;
            this.arrivals = arrivals;
        }

        private int getStudentsOnTime() {
            int studentsOnTime = 0;
            for (int arrival : arrivals) {
                studentsOnTime += (arrival <= 0) ? 1 : 0;
            }
            return studentsOnTime;
        }

        String classWillBeCancelled() {
            int studentsOnTime = getStudentsOnTime();
            return (studentsOnTime >= minStudentsOnTime) ? "NO" : "YES";
        }
    }

    private Case readCase(BufferedReader reader) throws IOException {
        String[] split = reader.readLine().split(SPACE);
        int totalStudents = Integer.parseInt(split[0]);
        int minStudentsOnTime = Integer.parseInt(split[1]);
        String[] arrivalsStr = reader.readLine().split(SPACE);
        int[] arrivals = Arrays.stream(arrivalsStr).mapToInt(Integer::parseInt).toArray();
        return new Case(totalStudents, minStudentsOnTime, arrivals);
    }

    private List<Case> readCases() throws IOException {
        List<Case> cases = new ArrayList<>();
        try (BufferedReader reader = new BufferedReader(new InputStreamReader(System.in))) {
            int totalCases = Integer.parseInt(reader.readLine());
            for (int i = 0; i < totalCases; i++) {
                Case inputCase = readCase(reader);
                cases.add(inputCase);
            }
        }
        return cases;
    }

    public static void main(String[] args) throws IOException {
        AngryProfessor angryProfessor = new AngryProfessor();
        List<Case> cases = angryProfessor.readCases();
        for (Case inputCase : cases) {
            System.out.println(inputCase.classWillBeCancelled());
        }
    }
}

Add solution for Angry Professor problem.


package org.modelmapper.bugs;

import static org.testng.Assert.assertEquals;

import org.modelmapper.AbstractTest;
import org.modelmapper.PropertyMap;
import org.testng.annotations.Test;

/**
 * https://github.com/jhalterman/modelmapper/pull/39
 */
@Test
public class GH39 extends AbstractTest {
  static class Source {
    String value;

    public Source() {
      getValue();
    }

    String getValue() {
      return value;
    }
  }

  static class Dest {
    String value;

    public Dest() {
      setValue(null);
    }

    void setValue(String value) {
      this.value = value;
    }
  }

  public void shouldIgnoreProxyInvocationsWhileInConstructor() {
    Source src = new Source();
    src.value = "5";

    modelMapper.addMappings(new PropertyMap<Source, Dest>() {
      @Override
      protected void configure() {
        map().setValue(source.getValue());
      }
    });

    Dest dest = modelMapper.map(src, Dest.class);

    assertEquals(dest.value, "5");
  }
}

Test for pull request 39

Test for pull request 39


package rabbit;

import org.junit.Test;

public class ReceiverTest {

    /**
     * Instantiate receiver many times.
     */
    @Test
    public void multipleInstantiation() {
        for (int i = 0; i < 10; i++) {
            Receiver receiver = new Receiver();
        }
    }

    /**
     * Close same connection multiple times.
     */
    @Test
    public void closeSameConnectionMultipleTimes() {
        Receiver receive = new Receiver();
        for (int i = 0; i < 10; i++) {
            receive.closeConnection();
        }
    }

}

Add unit tests for receiver.

Add unit tests for receiver.


package org.lapanen.stealth.si.subversion.convert;

import java.beans.PropertyEditor;

import org.springframework.context.support.SimpleThreadScope;
import org.springframework.core.convert.converter.Converter;
import org.tmatesoft.svn.core.SVNException;
import org.tmatesoft.svn.core.SVNURL;

public class StringToSubversionUrlConverter implements Converter<String, SVNURL> {

    @Override
    public SVNURL convert(final String source) {
        try {
            return SVNURL.parseURIEncoded(source);
        } catch (SVNException e) {
            throw new IllegalArgumentException(e);
        }
    }
}

Add String to SVN URL converter.

Add String to SVN URL converter.


#set( $symbol_pound = '#' )
#set( $symbol_dollar = '$' )
#set( $symbol_escape = '\' )
package ${package};

import org.junit.Test;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;

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

public class MessagesTest {

  @Test
  public void malformedKeyAndPairReturnsNull() {
    assertThat(Messages.parseKeyValuePair("blah"), nullValue());
  }

  @Test
  public void canParseFormattedKeyAndValuePair() {
    String key = "testKey";
    String value = "testValue";
    String formatted = Messages.formatKeyValuePair(key, value);
    Map.Entry<String, String> parsed = Messages.parseKeyValuePair(formatted);
    assertThat(parsed.getKey(), equalTo(key));
    assertThat(parsed.getValue(), equalTo(value));
  }

  @Test
  public void canParseFormattedKeyValueWithoutLeadingSpaces() {
    String key = "testKey";
    String value = "testValue";
    String formatted = Messages.formatKeyValuePair(key, value);
    String trimmed = formatted.trim();
    Map.Entry<String, String> parsed = Messages.parseKeyValuePair(trimmed);
    assertThat(parsed.getKey(), equalTo(key));
    assertThat(parsed.getValue(), equalTo(value));

  }

  @Test
  public void nullValueIsParsedAsNull() {
    String key = "testKey";
    String value = null;
    String formatted = Messages.formatKeyValuePair(key, value);
    Map.Entry<String, String> parsed = Messages.parseKeyValuePair(formatted);
    assertThat(parsed.getKey(), equalTo(key));
    assertThat(parsed.getValue(), equalTo(value));
  }

  @Test
  public void canParseFormattedKeyValueMap() {
    Map<String, String> map = new HashMap<>();

    for (int i = 0; i < 5; i++) {
      String key = String.valueOf(i);
      String value = "QQ" + key;
      map.put(key, value);
    }

    StringWriter sw = new StringWriter();
    Messages.formatKeyValueMap(new PrintWriter(sw, true), map);

    String formatted = sw.toString();

    Map<String, String> actual = Messages.parseKeyValueMap(formatted);
    assertThat(actual, equalTo(map));
  }
}

Add test for Messages class.

Add test for Messages class.


package am.extension.userfeedback.evaluation;

import am.extension.userfeedback.common.PrecisionRecallPlot;
import am.extension.userfeedback.experiments.UFLExperiment;

/**
 * A candidate selection evaluation that allows to run multiple candidate
 * selection evaluations as one.
 *
 * @author cosmin
 *
 */
public class MultiplexCandidateSelectionEvaluation extends CandidateSelectionEvaluation {

	private CandidateSelectionEvaluation[] evaluations;

	public MultiplexCandidateSelectionEvaluation() {
		super();

		// hardcoded for now
		evaluations = new CandidateSelectionEvaluation[2];
		evaluations[0] = new PrecisionRecallPlot();
		evaluations[1] = new RankingAccuracy();
	}

	@Override
	public void evaluate(UFLExperiment exp) {
		for( CandidateSelectionEvaluation eval : evaluations ) {
			eval.evaluate(exp);
		}
	}

}

Allow to use multiple candidate selection evaluations.


package leetcode.combination_sum_ii;

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

public class Solution {

	public static class MutableInt{
		private int val;
		public MutableInt(){
			val = 0;
		}
		public void increment(){
			val++;
		}
		public int get(){
			return val;
		}
	}

	public void dfs(ArrayList<ArrayList<Integer>> ans, ArrayList<Integer> cur, Map<Integer, MutableInt> counter, Integer[] intSet, int depth, int target, int sum){
		if(sum == target){
			ans.add(new ArrayList<Integer>(cur));
		}else if(depth < intSet.length){
			int cnt;
			dfs(ans, cur, counter, intSet, depth + 1, target, sum);
			int maxCnt = counter.get(intSet[depth]).get();
			for(cnt = 1; sum + intSet[depth] * cnt <= target && cnt <= maxCnt; cnt++){
				cur.add(intSet[depth]);
				dfs(ans, cur, counter, intSet, depth + 1, target, sum + intSet[depth] * cnt);
			}
			cur.subList(cur.size() - cnt + 1, cur.size()).clear();
		}
	}

    public ArrayList<ArrayList<Integer>> combinationSum2(int[] num, int target) {
    	ArrayList<ArrayList<Integer>> ans = new ArrayList<ArrayList<Integer>>();
    	if(num == null || num.length == 0) return ans;
    	Map<Integer, MutableInt> counter = new HashMap<Integer, MutableInt>();
    	for(int x : num){
    		MutableInt mi = counter.get(x);
    		if(mi == null){
    			mi = new MutableInt();
    			counter.put(x, mi);
    		}
    		mi.increment();
    	}
    	Integer[] intSet = counter.keySet().toArray(new Integer[0]);
    	Arrays.sort(intSet);
    	dfs(ans, new ArrayList<Integer>(), counter, intSet, 0, target, 0);
    	return ans;
    }

    public static void main(String[] args){
    	for(ArrayList<Integer> row : new Solution().combinationSum2(new int[]{10, 1, 2, 7, 6, 1, 5}, 8)){
    		for(int x : row){
    			System.err.print(x + ", ");
    		}
    		System.err.println("");
    	}
    }
}

Add java solution for 40. Combination Sum II

40. Combination Sum II: https://leetcode.com/problems/combination-sum-ii/


package hk.ust.comp4321.test;

import java.io.IOException;

import hk.ust.comp4321.engine.PageRank;

public class TestPageRank
{
  public static void main(String[] args) throws IOException
  {
    PageRank pageRank = new PageRank("Movie");
  }
}

Add test program for page rank

Add test program for page rank


package io.rodeo.chute;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Random;

public class MySqlBulkGenerator {
	public static void main(String[] args) throws InstantiationException, IllegalAccessException, ClassNotFoundException, SQLException {
		// TODO Auto-generated method stub
		Class.forName("com.mysql.jdbc.Driver").newInstance();
		Connection conn = DriverManager.getConnection("jdbc:mysql://localhost/chute_test", "root", "test");
		PreparedStatement insertStmt = conn.prepareStatement("INSERT INTO testb(id, comment, user_id) VALUES(?, ?, ?)");
		Random r = new Random();
		for (int i = 0; i < 1000000; i++) {
			insertStmt.setInt(1, r.nextInt());
			insertStmt.setString(2, "Hello " + i);
			insertStmt.setInt(3, r.nextInt());
			insertStmt.execute();
		}
	}
}

Add bulk loader for testing

Add bulk loader for testing


/**
 * This file is part of the Android DependencyManager project hosted at
 * http://code.google.com/p/android-dependencymanager/
 *
 * Copyright (C) 2009 Jens Finkhaeuser <jens@finkhaeuser.de>
 *
 * 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 de.finkhaeuser.dm.common;

/**
 * Constants related to XML namespace schemas
 **/
public class Schemas
{
  /**
   * String constants related to the data source schema for DependencyManager
   * http://schemas.finkhaeuser.de/android/dependency-manager/1.0/source
   **/
  public static class Source
  {
    // Not strictly speaking part of the schema, but the meta-data label used
    // for pointing to a resource file that follows this schema.
    public static String META_DATA_LABEL        = "de.finkhaeuser.dm.dependency-source";

    // Schema name
    public static String SCHEMA                 = "http://schemas.finkhaeuser.de/android/dependency-manager/1.0/source";

    // The schema defines a single element.
    public static String ELEM_DEPENDENCY_SOURCE = "dependency-source";

    // ELEM_DEPENDENCY_SOURCE defines a single attribute: the ContentProvider
    // authority to use when fetching dependency information from this data
    // source.
    public static String ATTR_AUTHORITY         = "authority";
  }

  /**
   * String constants related to the client schema for DependencyManager
   * http://schemas.finkhaeuser.de/android/dependency-manager/1.0/client
   **/
  public static class Client
  {
    // Not strictly speaking part of the schema, but the meta-data label used
    // for pointing to a resource file that follows this schema.
    public static String META_DATA_LABEL        = "de.finkhaeuser.dm.dependency-client";

    // Schema name
    public static String SCHEMA                 = "http://schemas.finkhaeuser.de/android/dependency-manager/1.0/client";

    // TODO
  }
}

Add Schema-related constants to common package; currently only for the (simpler) data source schema.


package seedu.doist.model.task;

import java.util.Date;

import seedu.doist.commons.exceptions.IllegalValueException;

public class TaskDate {

    private Date startDate;
    private Date endDate;

    public TaskDate() {
        this.startDate = null;
        this.endDate = null;
    }

    public TaskDate (Date startDate, Date endDate) {
        this.startDate = startDate;
        this.endDate = endDate;
    }
    public Date getStartDate() {
        return startDate;
    }

    public void setStartDate(Date startDate) {
        this.startDate = startDate;
    }

    public Date getEndDate() {
        return endDate;
    }

    public void setEndDate(Date endDate) {
        this.endDate = endDate;
    }

    public boolean isPast() {
        if (this.getStartDate() != null && this.getEndDate() != null) {
            Date currentDate = new Date();
            return (this.getEndDate().compareTo(currentDate) < 0);
        } else {
            return false;
        }
    }

    /**
     * Function to check whether the date input is valid i.e, the Start date is before or equal to the End Date.
     * Also checks if the parsing of dates has been successful
     * @param startDate
     * @param endDate
     * @return
     * @throws IllegalValueException
     */
    public static boolean validateDate (Date startDate, Date endDate) throws IllegalValueException {
        if (startDate == null || endDate == null) {
            throw new IllegalValueException("Incorrect Dates");
        } else {
            return (startDate.compareTo(endDate) <= 0) ? true : false;
        }
    }
}

Add new class to store times and date

Add new class to store times and date


package org.valid4j;

import org.junit.Ignore;
import org.junit.Test;

import static org.hamcrest.Matchers.containsString;
import static org.junit.Assert.assertThat;
import static org.valid4j.Assertive.require;
import static org.valid4j.Validation.validate;

@Ignore("Run manually for demonstration purposes")
public class DemoFailureBehavior {

  @Test
  public void shouldDescribeFailedVerification() {
    assertThat("This message is bad", containsString("good"));
  }

  @Test
  public void shouldDescribeContractViolation() {
    require("This message is bad", containsString("good"));
  }

  @Test
  public void shouldDescribeFailedInputValidation() {
    validate("This message is bad", containsString("good"), IllegalArgumentException.class);
  }
}

Add manually run test to demonstrate behavior


package leetcode.reverse_linked_list_ii;

import common.ListNode;

public class Solution {
    public ListNode reverseBetween(ListNode head, int m, int n) {
    	if(head == null) return null;
    	ListNode curRight = head;
    	for(int len = 0; len < n - m; len++){
    		curRight = curRight.next;
    	}
    	ListNode prevLeft = null;
    	ListNode curLeft = head;
    	for(int len = 0; len < m - 1; len++){
    		prevLeft = curLeft;
    		curLeft = curLeft.next;
    		curRight = curRight.next;
    	}
    	if(prevLeft == null){
    		head = curRight;
    	}else{
    		prevLeft.next = curRight;
    	}
    	for(int len = 0; len < n - m; len++){
    		ListNode next = curLeft.next;
    		curLeft.next = curRight.next;
    		curRight.next = curLeft;
    		curLeft = next;
    	}
    	return head;
    }

    public static void dump(ListNode node){
    	while(node != null){
    		System.err.print(node.val + "->");
    		node = node.next;
    	}
    	System.err.println("null");
    }

    public static void main(String[] args){
    	final int N = 10;
    	ListNode[] list = new ListNode[N];
    	for(int m = 1; m <= N; m++){
    		for(int n = m; n <= N; 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().reverseBetween(list[0], m, n));
    		}
    	}
    }
}

Add java solution for 92. Reverse Linked List II

92. Reverse Linked List II: https://leetcode.com/problems/reverse-linked-list-ii/


package nl.avansc1.facturatie;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.web.SpringBootServletInitializer;

/**
 * This class is used to run the Spring Boot application. It will start a tomcat server to load all the template files.

 * You can find the server on default: http://localhost:8080.
 * TODO: Still show a error in the webbrowser because we didn't add a template file yet.
 *
 * @author Bob van der Valk
 */
@SpringBootApplication
public class Server extends SpringBootServletInitializer {

    public static void main(String[] args) {
        SpringApplication.run(Server.class, args);
    }
}

Add main class to init the server

Add main class to init the server


/*-
 * Copyright (c) 2014 Mikolaj Izdebski
 *
 * 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.lbzip2.impl;

import static org.lbzip2.impl.Unsigned.umin;

/**
 * A simple BWT implementation based on LSD radix sort.
 *
 * @author Mikolaj Izdebski
 */
class RadixSortBWT
    implements BWT
{
    public int transform( int[] B, int n )
    {
        int[] U = new int[256];
        int[] C = new int[256];
        int[] P = new int[n];
        int[] R = new int[n];

        for ( int i = 0; i < n; i++ )
        {
            C[B[i]]++;
            P[i] = i;
        }

        int cum = 0;
        for ( int i = 0; i < 256; i++ )
            C[i] = ( cum += C[i] ) - C[i];
        assert cum == n;

        for ( int d = 1; d <= n; d++ )
        {
            System.arraycopy( C, 0, U, 0, 256 );

            for ( int i = 0; i < n; i++ )
            {
                int j = P[i];
                int t = umin( j - d, j - d + n );
                R[U[B[t]]++] = j;
            }

            int[] T = P;
            P = R;
            R = T;
        }

        System.arraycopy( B, 0, R, 0, n );
        int idx = n;
        for ( int i = 0; i < n; i++ )
        {
            int j = P[i];
            if ( j == 0 )
            {
                assert idx == n;
                idx = i;
                j = n;
            }

            B[i] = R[j - 1];
        }

        assert idx < n;
        return idx;
    }
}

Implement BWT based on LSD radix sort

Implement BWT based on LSD radix sort


/*
 * Copyright 2017, 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.type;

import com.google.common.testing.NullPointerTester;
import com.google.protobuf.BoolValue;
import com.google.protobuf.Int32Value;
import com.google.protobuf.StringValue;
import org.junit.Test;

import static org.junit.Assert.assertEquals;

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

    @Test
    public void create_set_on_varargs() {
        assertEquals(3,
                     FailureClass.setOf(BoolValue.class, Int32Value.class, StringValue.class)
                                 .size());
    }

    @Test
    public void pass_null_tolerance_check() throws Exception {
        new NullPointerTester()
                .testAllPublicStaticMethods(FailureClass.class);
    }
}

Add tests for the `FailureClass`.

Add tests for the `FailureClass`.


public class Solution {

    public int addDigits(int num) {

        int sum = 0;
        boolean isOneDigit = false;

        while (!isOneDigit) {

            while (num/10 != 0) {

                sum += num % 10;
                num /= 10;

            }

            sum += num;

            if (sum/10 == 0) {

                isOneDigit = true;

            } else {

                num = sum;
                sum = 0;

            }

        }

        return sum;

    }

}

Create : 258 Add Digits

Create : 258 Add Digits


package com.yammer.stresstime.entities;

import com.yammer.stresstime.managers.GroupManager;
import com.yammer.stresstime.test.DatabaseTest;
import org.junit.Before;
import org.junit.Test;

import static org.hamcrest.Matchers.*;
import static org.junit.Assert.*;

public class GroupTest extends DatabaseTest {

    private GroupManager mGroupManager;

    @Before
    @Override
    public void setUp() throws Exception {
        super.setUp();
        mGroupManager = new GroupManager(getSessionFactory());
    }

    @Test
    public void testNewGroupHasEmptyAssignableDays() {
        Group group = new Group();
        assertNotNull(group.getAssignableDays());
        assertThat(group.getAssignableDays(), empty());
    }
}

Add test for Group entity

Add test for Group entity

Add simple test to test if the assignable days association is working.


package no.javazone;

import io.dropwizard.testing.junit.ResourceTestRule;
import org.junit.ClassRule;
import org.junit.Test;
import javax.ws.rs.client.WebTarget;
import static org.assertj.core.api.Assertions.assertThat;

public class HelloWorldResourceTest {

    @ClassRule
    public static final ResourceTestRule resources = ResourceTestRule.builder()
            .addResource(new HelloWorldResource())
            .build();

    @Test
    public void hello_world_svarer_med_positivt_heltall() throws Exception {
        final WebTarget resource = resources.client().target("/hello-world");

        final Integer svar = resource.request().get(Integer.class);

        assertThat(svar).isGreaterThanOrEqualTo(1);
    }

    @Test
    public void hello_world_oeker_med_2_hver_gang() throws Exception {
        final WebTarget resource = resources.client().target("/hello-world");

        final Integer svar = resource.request().get(Integer.class);
        final Integer svar2 = resource.request().get(Integer.class);
        assertThat(svar2).isEqualTo(svar + 1);
    }
}

Add example test for testing a resource.


package com.algorithms.queue;

public class LinkedQueueOfStrings {

    private Node first, last;

    private class Node {
        String item;
        Node next;
    }

    public boolean isEmpty() { return first == null; }

    public void enqueue(String item) {
        Node oldlast = last;
        last = new Node();
        last.item = item;
        last.next = null;

        if (isEmpty()) first = last;
        else oldlast.next = last;
    }

    public String dequeue() {
        String item = first.item;
        first = first.next;
        if (isEmpty()) last = null;
        return item;
    }
}

Add linked-list implementation of queue of strings


package net.tridentsdk.base;

import lombok.Getter;

public enum BlockDirection {

    NORTH(0, 0, -1),
    NORTH_EAST(1, 0, -1),
    EAST(1, 0, 0),
    SOUTH_EAST(1, 0, 1),
    SOUTH(0, 0, 1),
    SOUTH_WEST(-1, 0, 1),
    WEST(-1, 0, 0),
    NORTH_WEST(-1, 0, -1),

    UP(0, 1, 0),
    DOWN(0, -1, 0);

    @Getter
    private int xDiff;
    @Getter
    private int yDiff;
    @Getter
    private int zDiff;

    BlockDirection(int xDiff, int yDiff, int zDiff) {
        this.xDiff = xDiff;
        this.yDiff = yDiff;
        this.zDiff = zDiff;
    }

    public BlockDirection left() {
        return left(false);
    }

    public BlockDirection left(boolean includeDiagonals) {
        int direction = ordinal() + (includeDiagonals ? 1 : 2);

        if(direction < 0){
            direction += 8;
        }

        return values()[direction];
    }

    public BlockDirection right() {
        return right(false);
    }

    public BlockDirection right(boolean includeDiagonals) {
        return values()[(ordinal() + (includeDiagonals ? 1 : 2)) % 8];
    }

}

Send chunks as the player is moving around


package de.retest.recheck.report;

import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;

import org.junit.jupiter.api.Test;

import de.retest.recheck.NoGoldenMasterActionReplayResult;

class TestReplayResultTest {

	@Test
	void hasNoGoldenMaster_should_return_false_if_no_specific_result_is_present() {
		final TestReplayResult cut = new TestReplayResult( "foo", 42 );
		cut.addAction( mock( ActionReplayResult.class ) );

		assertThat( cut.hasNoGoldenMaster() ).isFalse();
	}

	@Test
	void hasNoGoldenMaster_should_return_false_if_not_all_gm() {
		final TestReplayResult cut = new TestReplayResult( "foo", 42 );
		cut.addAction( mock( NoGoldenMasterActionReplayResult.class ) );
		cut.addAction( mock( ActionReplayResult.class ) );

		assertThat( cut.hasNoGoldenMaster() ).isFalse();
	}

	@Test
	void hasNoGoldenMaster_should_return_true_only_if_all_are_not_present() {
		final TestReplayResult cut = new TestReplayResult( "foo", 42 );
		cut.addAction( mock( NoGoldenMasterActionReplayResult.class ) );
		cut.addAction( mock( NoGoldenMasterActionReplayResult.class ) );

		assertThat( cut.hasNoGoldenMaster() ).isTrue();
	}
}

Add test for golden master results

Add test for golden master results


/*
 * #%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 imagej;

/**
 * Place-holder class for backwards-compatibility.
 *
 * @author Johannes Schindelin
 */
@Deprecated
public class ClassLauncher extends net.imagej.launcher.ClassLauncher { }

Add back another class, purely for backwards compatibility

When calling Fiji with an older Fiji launcher, we really want things
still to work. So let's add back a deprecated delegator in the old
location of the ClassLauncher.

Signed-off-by: Johannes Schindelin <53fb8db7833fca1e1746dd8592f61048d350f64c@gmx.de>


package com.google.sps;

import com.google.sps.data.TripLocation;

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

@RunWith(JUnit4.class)
public class TripLocationTest {
  @Test
  public void testDefaultUsage() {
    TripLocation location = TripLocation.create("xYz_A", "Googleplex", 4, "peter@google.com");
    Assert.assertEquals("xYz_A", location.placeID());
    Assert.assertEquals("Googleplex", location.placeName());
    Assert.assertEquals(4, location.weight());
    Assert.assertEquals("peter@google.com", location.owner());
  }
}

Add test for TripLocation value class

Add test for TripLocation value class


package net.imagej.convert;

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

import java.util.Arrays;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameter;
import org.junit.runners.Parameterized.Parameters;
import org.scijava.Context;
import org.scijava.convert.ConvertService;

import net.imglib2.type.numeric.NumericType;
import net.imglib2.type.numeric.integer.IntType;
import net.imglib2.type.numeric.integer.LongType;
import net.imglib2.type.numeric.integer.UnsignedByteType;
import net.imglib2.type.numeric.real.DoubleType;
import net.imglib2.type.numeric.real.FloatType;
import net.imglib2.type.operators.ValueEquals;

@RunWith(Parameterized.class)
public class NumberAndTypeConversionTest {

	@Parameters(name="Type conversion test {index}: {0} <=> {1}")
	public static Iterable<Object[]> data() {
		return Arrays.asList(new Object[][] {
				{new Double(Double.POSITIVE_INFINITY), new DoubleType(Double.POSITIVE_INFINITY)},
				{new Float(Float.NEGATIVE_INFINITY), new FloatType(Float.NEGATIVE_INFINITY)},
				{new Integer(Integer.MAX_VALUE), new IntType(Integer.MAX_VALUE)},
				{new Long(Long.MAX_VALUE), new LongType(Long.MAX_VALUE)},
				{new Integer(255), new UnsignedByteType(255)}
			});
	}

	@Parameter(0)
	public Object number;

	@Parameter(1)
	public Object numericType;

	private ConvertService convertService;

	@Before
	public void setUp() {
		final Context ctx = new Context();
		convertService = ctx.getService(ConvertService.class);
	}

	@After
	public void tearDown() {
		convertService.getContext().dispose();
		convertService = null;
	}

	/**
	 * Test conversion from {@link Number} to {@link NumericType}
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	@Test
	public void testNumberToNumericType() {
		assertTrue("Conversion support from number to numeric type", convertService.supports(number, numericType.getClass()));
		ValueEquals converted = (ValueEquals) convertService.convert(number, numericType.getClass());
		assertTrue("Converted type value equality", converted.valueEquals(numericType));
	}

	/**
	 * Test conversion from {@link Number} to {@link NumericType}
	 */
	@Test
	public void testNumericTypeToNumber() {
		assertTrue("Conversion support from numeric type to number", convertService.supports(numericType, number.getClass()));
		Number converted = (Number) convertService.convert(numericType, number.getClass());
		assertEquals("Converted value equality", number, converted);
	}
}

Add tests for various number/numeric type conversions


package com.aemreunal.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

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

/*
 * Via: https://spring.io/guides/tutorials/rest/5/
 */

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

//    @Override
//    protected void registerAuthentication(AuthenticationManagerBuilder auth) throws Exception {
//        auth.inMemoryAuthentication()
//            .withUser("letsnosh").password("noshing").roles("USER");
//    }
//
//    @Override
//    protected void configure(HttpSecurity http) throws Exception {
//        http.authorizeUrls()
//            .antMatchers("/aggregators/**").hasRole("USER")
//            .anyRequest().anonymous()
//            .and()
//            .httpBasic();
//    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
            .antMatchers("/**").hasRole("USER")
            .anyRequest().anonymous()
            .and()
            .httpBasic();
//            .and()
//            .formLogin()
        ;
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication()
            .withUser("user")
            .password("password")
            .roles("USER")
            .and()
            .withUser("adminr")
            .password("password")
            .roles("ADMIN", "USER");
//        auth.jdbcAuthentication().
    }
}

Add basic Spring Security configuration

Add basic Spring Security configuration

Not yet working to secure the system, as it isn’t attached at the
WebAppInitializer


/*
 * #%L
 * ImageJ software for multidimensional image processing and analysis.
 * %%
 * Copyright (C) 2009 - 2013 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.
 *
 * The views and conclusions contained in the software and documentation are
 * those of the authors and should not be interpreted as representing official
 * policies, either expressed or implied, of any organization.
 * #L%
 */

package imagej.legacy;

import java.lang.instrument.ClassFileTransformer;
import java.lang.instrument.IllegalClassFormatException;
import java.lang.instrument.Instrumentation;
import java.security.ProtectionDomain;

/**
 * A Java agent to help with legacy issues.
 *
 * @author Johannes Schindelin
 */
public class LegacyJavaAgent implements ClassFileTransformer {
	public static void premain(final String agentArgs, final Instrumentation instrumentation) {
		System.err.println("The legacy agent was started with the argument: " + agentArgs);
		instrumentation.addTransformer(new LegacyJavaAgent());
	}

	@Override
	public byte[] transform(ClassLoader loader, String className,
			Class<?> classBeingRedefined, ProtectionDomain protectionDomain,
			byte[] classfileBuffer) throws IllegalClassFormatException {
		if (className.startsWith("ij.") || className.startsWith("ij/")) {
			System.err.println("Loading " + className + " into " + loader + "!");
			Thread.dumpStack();
		}
		return null;
	}
}

Add a simple Java agent to identify when ImageJ 1.x classes are loaded

When ImageJ 1.x' classes are loaded before the ij-legacy patching had
a chance, we have a problem. The biggest problem is that we only have
a chance to detect that situation when the ij-legacy patching takes
place, so there is no way to know which code path loaded the unpatched
ImageJ 1.x classes.

To help with that, this commit adds a Java agent that reports whenever
classes in the "ij" package (or any of its nested packages) is loaded.

We will refine this agent in subsequent commits.

Signed-off-by: Johannes Schindelin <53fb8db7833fca1e1746dd8592f61048d350f64c@gmx.de>


package com.dhemery.slicer.test.unit;

import static org.hamcrest.Matchers.*;
import static org.junit.Assert.*;

import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Arrays;

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

import com.dhemery.slicer.Grid;
import com.dhemery.slicer.GridReader;
import com.dhemery.slicer.test.util.CsvTmpFileCreator;

public class AGridReader {
	String[][] cells = {
			{ "a", "b", "c", "d", },
			{ "1", "3", "5", "42", "42 again", },
			{ "-", "$", "*", },
			{ "the", "quick", "brown", "fox", },
	};
	private String csvFileName;

	@Before
	public void writeCellsToCsvFile() throws IOException {
		csvFileName = CsvTmpFileCreator.create(cells);
	}

	@Test
	public void createsAGridWithTheValuesFromTheCsvFile() throws FileNotFoundException, IOException  {
		GridReader gridReader = new GridReader(new FileReader(csvFileName));
		Grid grid = gridReader.grid();
		for(int i = 0 ; i < cells.length ; i++) {
			assertThat(grid.row(i), is(Arrays.asList(cells[i])));
		}
	}
}

Test that the reader reads the same values as were written


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

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

/**
 * Command group for autonomous operation.
 *
 * @author RAmato
 */
public class DriveAndShootCommandGroup extends CommandGroup {

    public DriveAndShootCommandGroup() {
        addSequential(new AutoDriveToShotRangeCommand());
        //TODO: Position forklift for shooting;
        addSequential(new FireLauncherCommand());

    }
}

Add command group for autonomous operation.


import java.util.*;
import java.io.*;
import java.lang.*;
import java.text.*;

public class ListDirectory{

    private static void sortName(String path){
        File file = new File(path);

        File[] fileList = file.listFiles();

        Arrays.sort(fileList);

        System.out.println("Files in\t" + path + "\tlisted according to Name :\n");

        print(fileList);

    }

    private static void sortModified(String path){
        File file = new File(path);

        File[] fileList = file.listFiles();

        Arrays.sort(fileList, new Comparator<File>(){

            public int compare(File object1, File object2){
                int result = ((Long)object1.lastModified()).compareTo( (Long)object2.lastModified() );
                return -result;
            }
        });

        System.out.println("Files in\t" + path + "\tlisted according to Date Modified (most recent to least) :\n");

        print(fileList);
    }

    private static void sortSize(String path){
        File file = new File(path);

        File[] fileList = file.listFiles();

        Arrays.sort(fileList, new Comparator<File>(){

            public int compare(File object1, File object2){
                int result = ((Long)object1.length()).compareTo( (Long)object2.length() );
                return -result;
            }
        });

        System.out.println("Files in\t" + path + "\tlisted in decreasing order of size :\n");

        print(fileList);

    }

    private static void print (File[] fileList){

        SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-YYYY, HH:mm");

        System.out.println(String.format("%-100s\t%-10s\t%-10s", "Name", "Size", "Last Modified" ));

        for(File fileName : fileList){
            long size = fileName.length();
            int sizeUnit = 0;
            while(size / 1024 != 0){
                size /= 1024;
                sizeUnit ++;
            }
            String fileSize = "";
            if(sizeUnit == 0){
                fileSize = size + " B";
            }
            else if(sizeUnit == 1){
                fileSize = size + " KB";
            }
            else if(sizeUnit == 2){
                fileSize = size + " MB";
            }
            else if(sizeUnit == 3){
                fileSize = size + " GB";
            }
            else if(sizeUnit == 4){
                fileSize = size + " TB";
            }

            System.out.println(String.format("%-100s\t%-10s\t%-10s", fileName.getName(), fileSize, dateFormat.format(fileName.lastModified()) ) );
        }

        System.out.println("\n");

    }

    public static void main(String args[]){

        String path = args[0];
        if(args.length > 2){
            System.out.println("ERROR : Cant have more than one modifier!");
        }
        else if (args.length == 2){

            if( (args[1].equals("-s") ) ){
                sortSize(path);
            }
            else if( (args[1].equals("-d") ) ){
                sortModified(path);
            }
        }
        else{
            sortName(path);
        }
    }

}

Add prog. to list items in a dir(sorted)

A program that lists all of the files and subdirectories in a specified
directory, along with their sizes and modification dates. By default,
the output is by name.
If invoked with the -s option, however, output is sorted by size, from
largest to smallest.
If invoked with the -d option, output is sorted by date, from most
recent to least.


package net.restlesscoder.sandbox.imagej;

import net.imagej.ImageJ;
import net.imagej.ops.OpService;
import net.imglib2.Dimensions;
import net.imglib2.FinalDimensions;
import net.imglib2.RandomAccess;
import net.imglib2.img.Img;
import net.imglib2.img.display.imagej.ImageJFunctions;
import net.imglib2.type.logic.BitType;
import net.imglib2.view.IntervalView;
import net.imglib2.view.Views;

import org.scijava.command.Command;
import org.scijava.display.DisplayService;
import org.scijava.plugin.Parameter;
import org.scijava.plugin.Plugin;

/**
 * From Discrepancy between different
 * ways of displaying Views.
 *
 * @author Curtis Rueden
 */
@Plugin(type = Command.class)
public class ImgViewDisplay implements Command {

	@Parameter
	private OpService opService;

	@Parameter
	private DisplayService displayService;

	@Override
	public void run() {

		final int[] center = new int[] { 15, 10 };
		final Dimensions dims = new FinalDimensions(31, 21);

		final Img<BitType> img = opService.create().img(dims, new BitType());

		final RandomAccess<BitType> ra = img.randomAccess();
		ra.setPosition(center);
		ra.get().set(true);

		displayService.createDisplay("original", img);

		final IntervalView<BitType> view = Views.interval(img, new long[] { 5, 5 },
			new long[] { 25, 15 });
		ImageJFunctions.show(view, "view - ImageJFunctions.show()");

		displayService.createDisplay("view - DisplayService.createDisplay()", view);
	}

	public static void main(final String[] args) throws Exception {
		final ImageJ ij = net.imagej.Main.launch(args);
		ij.command().run(ImgViewDisplay.class, false);
	}
}

Add MCVE for SciJava display creation discrepancy


package rxbroadcast;

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

@SuppressWarnings({"checkstyle:MagicNumber"})
public final class ObjectSerializerTest {
    @Test
    public final void testEncodeDecodeDoesResultInSameObject() {
        final Serializer<TestValue> serializer = new ObjectSerializer<>();
        final byte[] bytes = serializer.encode(new TestValue(42));
        Assert.assertEquals(new TestValue(42), serializer.decode(bytes));
    }
}

Add test case for ObjectSerializer

Add test case for ObjectSerializer


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

package com.greplin.lucene.query;

import org.apache.lucene.index.IndexReader;
import org.apache.lucene.search.Query;

import java.io.IOException;

/**
 * A Query that just wraps a sub query and adds a name to it in toString()
 */
public class NamedQuery extends Query {

  /**
   * The query to match.
   */
  private final Query query;

  /**
   * The name of the query, for toString.
   */
  private final String name;

  /**
   * Constructs a query that adds a name to a sub query.
   * @param query the sub query
   * @param name the name of the query
   */
  public NamedQuery(final Query query, final String name) {
    this.query = query;
    this.name = name;
  }

  @Override
  public final String toString(final String field) {
    return this.name + '=' + this.query.toString(field);
  }

  @Override
  public final int hashCode() {
    // Only check for query equality.
    return this.query.hashCode();
  }

  @Override
  public final boolean equals(final Object obj) {
    if (this == obj) {
      return true;
    }
    if (!super.equals(obj)) {
      return false;
    }
    if (getClass() != obj.getClass()) {
      return false;
    }
    NamedQuery other = (NamedQuery) obj;
    // Only check for query equality.
    return this.query.equals(other.query);
  }

  @Override
  public final Query rewrite(final IndexReader reader) throws IOException {
    return this.query.rewrite(reader);
  }

}

Add named query object for debugging

Add named query object for debugging


package net.bytebuddy.test.c;

import net.bytebuddy.agent.ByteBuddyAgent;
import org.objectweb.asm.*;

import java.lang.instrument.ClassFileTransformer;
import java.lang.instrument.Instrumentation;
import java.security.ProtectionDomain;

public class Sample {

    public static void main(String[] args) throws Exception {
        ClassReader reader = new ClassReader("net.bytebuddy.test.c.NativeSample");
        ClassWriter writer = new ClassWriter(0);
        reader.accept(new ClassVisitor(Opcodes.ASM8, writer) {

            @Override
            public MethodVisitor visitMethod(int access, String name, String descriptor, String signature, String[] exceptions) {
                if (name.equals("foo")) {
                    super.visitMethod(Opcodes.ACC_PRIVATE | Opcodes.ACC_NATIVE, "$$renamed$$foo", descriptor, signature, exceptions).visitEnd();
                    MethodVisitor visitor = super.visitMethod(Opcodes.ACC_PUBLIC, name, descriptor, signature, exceptions);
                    visitor.visitCode();
                    visitor.visitVarInsn(Opcodes.ALOAD, 0);
                    visitor.visitVarInsn(Opcodes.ILOAD, 1);
                    visitor.visitInsn(Opcodes.ICONST_2);
                    visitor.visitMethodInsn(Opcodes.INVOKESPECIAL, "net/bytebuddy/test/c/NativeSample", "$$renamed$$foo", descriptor, false);
                    visitor.visitInsn(Opcodes.IRETURN);
                    visitor.visitMaxs(3, 3);
                    visitor.visitEnd();
                    return null;
                } else {
                    return super.visitMethod(access, name, descriptor, signature, exceptions);
                }
            }
        }, 0);

        ClassFileTransformer transformer = new ClassFileTransformer() {
            @Override
            public byte[] transform(ClassLoader loader,
                                    String className,
                                    Class<?> classBeingRedefined,
                                    ProtectionDomain protectionDomain,
                                    byte[] classfileBuffer) {
                if ("net/bytebuddy/test/c/NativeSample".equals(className)) {
                    return writer.toByteArray();
                } else {
                    return null;
                }
            }
        };

        Class.forName("net.bytebuddy.test.c.NativeSample");

        Instrumentation instrumentation = ByteBuddyAgent.install();
        instrumentation.addTransformer(transformer, true);
        instrumentation.setNativeMethodPrefix(transformer, "$$renamed$$");

        instrumentation.retransformClasses(NativeSample.class);

        int result = new NativeSample().foo(42, 1);
        System.out.println(result);
    }

}

Add sample for same issue.

Add sample for same issue.


package org.robockets.stronghold.robot.intake;

import org.robockets.stronghold.robot.Robot;

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

/**
 * A Command to spin the intake motor forward or backward
 */
public class ManualVerticalIntake extends Command {

	/**
	 * Object for the Direction enum
	 * */
	public Direction direction;

	/**
	 * Used to set timeout
	 * */
	int time;

	/**
	 * Initalizes some variables
	 *
	 * @param direction  Used to initalize Direction enum
	 * @param time  Takes input for time
	 * */
    public ManualVerticalIntake(Direction direction, int time) {
        // Use requires() here to declare subsystem dependencies
        // eg. requires(chassis);
    	requires(Robot.intake);
    	this.direction = direction;
    	this.time = time;
    }

    // Called just before this Command runs the first time
    protected void initialize() {
    	setTimeout(time);
    }

    // Called repeatedly when this Command is scheduled to run
    protected void execute() {
    	if(direction == Direction.UP) {
    		Robot.intake.moveUp();
    	} else if(direction == Direction.DOWN){
    		Robot.intake.moveDown();
    	} else {
    		Robot.intake.stopVertical();
    	}
    }

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

    // Called once after isFinished returns true
    protected void end() {
    	Robot.intake.stopVertical();
    }

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

Add manual vertical intake command

Add manual vertical intake command


package cl.fatman.capital.fund;

import org.apache.log4j.Logger;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

public class FundProperties {

	private String propertyFile;
	private String userAgent;
	private String fundLink;
	private String fundQuery;
	private String ufLink;
	static final Logger logger = Logger.getLogger(FundProperties.class);

	public FundProperties(String propertyFile) {
		super();
		this.propertyFile = propertyFile;
	}

	public String getUserAgent() {
		return userAgent;
	}

	public String getFundLink() {
		return fundLink;
	}

	public String getFundQuery() {
		return fundQuery;
	}

	public String getUfLink() {
		return ufLink;
	}

	public String getPropertyFile() {
		return propertyFile;
	}

	public void setPropertyFile(String propertyFile) {
		this.propertyFile = propertyFile;
	}

	/*
	 * Method that read the property file and store the property values.
	 */
	public void readProperties() {
		logger.debug("readProperties()");
		InputStream input = null;
		try {
			logger.debug("Start reading " + propertyFile + " file.");
			input = new FileInputStream("fund.properties");
			logger.debug("Loading properties.");
			Properties prop = new Properties();
			prop.load(input);
			userAgent = (String) prop.getProperty("connection.common.UserAgent");
			logger.debug("User agent: " + userAgent);
			fundLink = (String) prop.getProperty("connection.fund.Link");
			logger.debug("Fund link: " + fundLink);
			fundQuery = (String) prop.getProperty("connection.fund.Query");
			logger.debug("Raw fund query: " + fundQuery);
			ufLink = (String) prop.getProperty("connection.uf.Link");
			logger.debug("UF link: " + ufLink);
			logger.debug("Finish reading fund.properties file.");
		} catch (IOException e) {
			logger.error("Problem reading the property file.", e);
		} finally {
			if (input != null) {
				try {
					input.close();
				} catch (IOException e) {
					logger.error("Problem closing the property file.", e);
				}
			}
		}
	}

}

Create a property class to read the configuration file, this will reduce the coupling in the project.


import java.util.Collection;

import javafx.geometry.Point2D;
import javafx.scene.shape.Shape;

/**
 * This is the class in which the Cell object is defined.
 *
 * @author Jeremy, Team 12
 */
public class Cell {
	private int myID;
	private int myCurrentState;
	private int myFutureState;
	private Shape myShape;
	private Collection<Cell> myNeighbors;
	private Collection<Point2D> myVertices;

	public Cell(int id, int currentState, int futureState, Shape shape,
			Collection<Cell> neighbors, Collection<Point2D> vertices) {
		myID = id;
		myCurrentState = currentState;
		myFutureState = futureState;
		myShape = shape;
		myNeighbors = neighbors;
		myVertices = vertices;
	}

	public int getID() {
		return myID;
	}

	public void setID(int id) {
		myID = id;
	}

	public int getCurrentState() {
		return myCurrentState;
	}

	public void setCurrentState(int currentState) {
		myCurrentState = currentState;
	}

	public int getFutureState() {
		return myFutureState;
	}

	public void setFutureState(int futureState) {
		myFutureState = futureState;
	}

	public Shape getShape() {
		return myShape;
	}

	public void setShape(Shape shape) {
		myShape = shape;
	}

	public void addNeighbor(Cell neighbor) {
		myNeighbors.add(neighbor);
	}

	public void removeNeighbor(Cell neighbor) {
		if (myNeighbors.contains(neighbor))
			myNeighbors.remove(neighbor);
	}

	public Collection<Cell> getNeighbors() {
		return myNeighbors;
	}

	public Collection<Point2D> getVertices() {
		return myVertices;
	}

}

Create cell class with basic get and set method


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

import javax.inject.Provider;

public class LazyAdapter<T> implements Lazy<T> {
    private final Provider<T> provider;
    private volatile T instance;
    private final Object instanceLock = new Object();

    public LazyAdapter(final Provider<T> provider) {
        this.provider = provider;
    }

    @Override
    public T get() {
        if (instance == null) {
            synchronized (instanceLock) {
                if (instance == null) {
                    instance = provider.get();
                }
            }
        }
        return instance;
    }
}

Implement a lazy adapter for a provider

Implement a lazy adapter for a provider


package boilerplate.common.compathandler;

import net.minecraft.block.Block;
import net.minecraft.item.ItemStack;
import cpw.mods.fml.common.event.FMLInterModComms;

/**
 * @author tterrag1098
 *
 */
public class FMPCompatHandler
{
	public static void registerFMP(Block block)
	{
		registerFMP(block, 0, 15);
	}

	public static void registerFMP(Block block, int minMeta, int maxMeta)
	{
		for (int c = minMeta; c <= maxMeta; c++)
		{
			registerFMP(block, c);
		}
	}

	public static void registerFMP(Block block, int meta)
	{
		FMLInterModComms.sendMessage("ForgeMicroblock", "microMaterial", new ItemStack(block, 1, meta));
	}
}

Add a copy of tterrag's FMP handler to Boilerplate


package net.restlesscoder.sandbox.interview;

public class ResampleImage {

	/** "Nearest" neighbor resampling. */
	public static void resampleNN(final double[][] in, final double[][] out) {
		final int iw = in[0].length, ih = in.length;
		final int ow = out[0].length, oh = out.length;

		for (int oy = 0; oy < oh; oy++) {
			final int iy = ih * oy / oh;
			for (int ox = 0; ox < ow; ox++) {
				final int ix = iw * ox / ow;
				out[oy][ox] = in[iy][ix];
			}
		}
	}

	public static void show(final String title, final double[][] matrix,
		final double scale)
	{
		final int w = matrix[0].length, h = matrix.length;
		final int ow = (int) (w * scale), oh = (int) (h * scale);
		final double[][] scaled = new double[oh][ow];
		resampleNN(matrix, scaled);
		Images.display(title, Images.makeBufferedImage(scaled));
	}

	public static void main(final String... args) {
		final int w = 300, h = 200;
		final double[][] matrix = Images.gradient(w, h);

		show("3.5x", matrix, 3.5);
		show("1.5x", matrix, 1.5);
		show("0.333x", matrix, 0.333);
	}
}

Add simple solution for resampling an image


/**
 *
 */
package content;

/**
 * @author john
 *
 */
public class DocumentRecord {
	public int id, size;
	public String file_type, digest;
	public boolean folder;
	public String created, created_at, updated_at;

	/**
	 *
	 */
	public DocumentRecord() {
		// TODO Auto-generated constructor stub
	}

}

Add record to reflect searches

Add record to reflect searches


package com.google.sps.servlets;

import com.google.gson.Gson;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Scanner;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/** Returns map data as a JSON array, e.g. [{"lat": 38.4404675, "lng": -122.7144313}] */
@WebServlet("/map-data")
public class MapServlet extends HttpServlet {

    private class elementMap {
        double lat, lng;
        String name, description;

        public elementMap(double lat, double lng, String name, String description) {
            this.lat = lat;
            this.lng = lng;
            this.name = name;
            this.description = description;
        }
    }

    private ArrayList<elementMap> markers;

    @Override
    public void init() {
        markers = new ArrayList<elementMap>();

        Scanner scanner = new Scanner(getServletContext().getResourceAsStream("/WEB-INF/cities.csv"));
        while (scanner.hasNextLine()) {
            String line = scanner.nextLine();
            String[] cells = line.split(",");

            double lat = Double.parseDouble(cells[0]);
            double lng = Double.parseDouble(cells[1]);

            markers.add(new elementMap(lat, lng, cells[2], cells[3]));
        }
        scanner.close();
    }

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

Add the servlet that returns the map markers as JSON.


package org.opennms.core.test;

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

import org.junit.Assert;

public abstract class OnmsAssert {

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

}

Add a utility method for asserting array equality regardless of order