/*
 * Copyright (c) 2014, Colorado State University All rights reserved.
 *
 * 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 holder 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.
 */

/**
 *
 *
 * @author ctolooee
 */
package mendel.data;

public class Metadata {
}

Add data package for representing datasets


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

import com.squareup.moshi.JsonAdapter;
import com.squareup.moshi.Moshi;
import com.squareup.moshi.Types;
import java.lang.reflect.Type;
import java.util.List;

public final class ReadJsonList {
  public void run() throws Exception {
    String json = "[\n"
        + "  {\n"
        + "    \"rank\": \"4\",\n"
        + "    \"suit\": \"CLUBS\"\n"
        + "  },\n"
        + "  {\n"
        + "    \"rank\": \"A\",\n"
        + "    \"suit\": \"HEARTS\"\n"
        + "  },\n"
        + "  {\n"
        + "    \"rank\": \"J\",\n"
        + "    \"suit\": \"SPADES\"\n"
        + "  }\n"
        + "]";

    Moshi moshi = new Moshi.Builder().build();

    Type listOfCardsType = Types.newParameterizedType(List.class, Card.class);
    JsonAdapter<List<Card>> jsonAdapter = moshi.adapter(listOfCardsType);

    List<Card> cards = jsonAdapter.fromJson(json);
    System.out.println(cards);
  }

  public static void main(String[] args) throws Exception {
    new ReadJsonList().run();
  }
}

Add read json array recipe

Add read json array recipe


package arez.integration;

import arez.Arez;
import arez.annotations.ArezComponent;
import arez.annotations.Injectible;
import arez.annotations.Observable;
import dagger.Component;
import javax.inject.Singleton;
import org.testng.annotations.Test;
import static org.testng.Assert.*;

public class DaggerComponentIntegrationTest
{
  @ArezComponent( dagger = Injectible.TRUE )
  static class TestComponent
  {
    private String _value = "";

    @Observable
    String getValue()
    {
      return _value;
    }

    void setValue( final String value )
    {
      _value = value;
    }
  }

  @Singleton
  @Component( modules = DaggerComponentIntegrationTest_TestComponentDaggerModule.class )
  interface TestDaggerComponent
  {
    TestComponent component();
  }

  @Test
  public void useDaggerComponentToGetAccessToComponent()
    throws Throwable
  {
    final TestDaggerComponent daggerComponent = DaggerDaggerComponentIntegrationTest_TestDaggerComponent.create();
    final TestComponent component = daggerComponent.component();

    Arez.context().action( false, () -> assertEquals( component.getValue(), "" ) );
    Arez.context().action( true, () -> component.setValue( "X" ) );
    Arez.context().action( false, () -> assertEquals( component.getValue(), "X" ) );
  }
}

Add test that bverifies dagger feature for single component


package arez.integration.action;

import arez.Arez;
import arez.ArezContext;
import arez.Environment;
import arez.Function;
import arez.SafeFunction;
import arez.annotations.Action;
import arez.annotations.ArezComponent;
import arez.integration.AbstractArezIntegrationTest;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.concurrent.atomic.AtomicInteger;
import javax.annotation.Nonnull;
import org.testng.annotations.Test;
import static org.testng.Assert.*;

@SuppressWarnings( { "UnusedReturnValue", "unused", "SameParameterValue" } )
public class RequiresEnvironmentTest
  extends AbstractArezIntegrationTest
{
  @ArezComponent
  static abstract class MyComponent
  {
    private final ArrayList<String> _steps;

    MyComponent( @Nonnull final ArrayList<String> steps )
    {
      _steps = steps;
    }

    @Action( requireEnvironment = true, verifyRequired = false )
    void myAction()
    {
      _steps.add( "myAction" );
    }

    @Action( requireEnvironment = false, verifyRequired = false )
    void myOtherAction()
    {
      _steps.add( "myOtherAction" );
    }
  }

  @Test
  public void scenario()
  {
    final ArezContext context = Arez.context();

    // Scheduler paused otherwise reactions will run in environment and upset our environment call count
    context.pauseScheduler();

    final ArrayList<String> steps = new ArrayList<>();
    final AtomicInteger inEnvironmentCallCount = new AtomicInteger();
    context.setEnvironment( new Environment()
    {
      @Override
      public <T> T run( @Nonnull final SafeFunction<T> function )
      {
        try
        {
          steps.add( "EnvironmentStart" );
          return function.call();
        }
        finally
        {
          steps.add( "EnvironmentEnd" );
        }
      }

      @Override
      public <T> T run( @Nonnull final Function<T> function )
        throws Throwable
      {
        try
        {
          steps.add( "EnvironmentStart" );
          return function.call();
        }
        finally
        {
          steps.add( "EnvironmentEnd" );
        }
      }
    } );

    final MyComponent component = new RequiresEnvironmentTest_Arez_MyComponent( steps );

    component.myAction();

    assertEquals( steps, Arrays.asList( "EnvironmentStart", "myAction", "EnvironmentEnd" ) );

    component.myOtherAction();

    assertEquals( steps, Arrays.asList( "EnvironmentStart", "myAction", "EnvironmentEnd", "myOtherAction" ) );
  }
}

Add integration test for actions that switch to environments


/*
 * Copyright 2006-2007 the original author or 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 org.openspaces.utest.remoting;

import java.lang.reflect.Method;
import java.util.Map;

import com.gigaspaces.internal.reflection.IMethod;
import junit.framework.TestCase;
import org.openspaces.remoting.RemotingUtils;
import org.openspaces.remoting.RemotingUtils.MethodHash;

/**
 * GS-8294: Methods of a Remoting Service interface are not included when it extends from another interface
 * @author moran
 */
public class RemotingUtilsTests extends TestCase {

    @Override
    protected void setUp() throws Exception {
    }

    public void testFastReflection() {
        fastReflection(true);
    }

    public void testStandardReflection() {
        fastReflection(false);
    }

    private void fastReflection(boolean fastReflection) {
        Map<MethodHash, IMethod> mapA = RemotingUtils.buildHashToMethodLookupForInterface(A.class, fastReflection);
        assertEquals(1, mapA.values().size());

        Map<MethodHash, IMethod> mapB = RemotingUtils.buildHashToMethodLookupForInterface(B.class, fastReflection);
        assertEquals(2, mapB.values().size());

        Map<MethodHash, IMethod> mapC = RemotingUtils.buildHashToMethodLookupForInterface(C.class, fastReflection);
        assertEquals(2, mapC.values().size());
    }

    public void testBuildMethodToHashLookupForInterface() {
        Map<Method, MethodHash> mapA = RemotingUtils.buildMethodToHashLookupForInterface(A.class, "asyncPrefix");
        assertEquals(1, mapA.values().size());

        Map<Method, MethodHash> mapB = RemotingUtils.buildMethodToHashLookupForInterface(B.class, "asyncPrefix");
        assertEquals(2, mapB.values().size());

        Map<Method, MethodHash> mapC = RemotingUtils.buildMethodToHashLookupForInterface(C.class, "asyncPrefix");
        assertEquals(2, mapC.values().size());
    }

    public interface A {
        String a(String s);
    }

    public interface B extends A {
        String b(String s);
    }

    public interface C extends B {
    }
}

GS-8294: Test RemotingUtils.buildMethodToHashLookupForInterface which calls RemotingUtils.getAllInterfacesForInterface with the relevant change in interface hierarchy.

svn path=/trunk/openspaces/; revision=76211

Former-commit-id: 61f23ca90143c422ae5a470a53961765f42aec9b


/**
* OpenCPS is the open source Core Public Services software
* Copyright (C) 2016-present OpenCPS community

* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* 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 Affero General Public License for more details.
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
*/

package org.opencps.hook.events;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.opencps.util.AccountUtil;

import com.liferay.portal.kernel.events.Action;
import com.liferay.portal.kernel.events.ActionException;

/**
 * @author trungnt
 *
 */
public class LogoutAction extends Action {

	@Override
	public void run(HttpServletRequest request, HttpServletResponse response)
	    throws ActionException {

		AccountUtil.destroy(request);
	}

}

Clean session taglib variable after logout


/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 * Given the root of a binary tree, then value v and depth d, you need to add a row of nodes with value v at the given depth d.
 * The root node is at depth 1.
 * The adding rule is:
 *   given a positive integer depth d, for each NOT null tree nodes N in depth d - 1, create two tree nodes with value v as N's left subtree root and right subtree root.
 *   And N's original left subtree should be the left subtree of the new left subtree root, its original right subtree should be the right subtree of the new right subtree root.
 *   If depth d is 1 that means there is no depth d-1 at all, then create a tree node with value v as the new root of the whole original tree, and the original tree is the new root's left subtree.
 */
public class Solution {
  public TreeNode addOneRow(TreeNode root, int v, int d) {
    Queue<TreeNode> queue = new LinkedList<TreeNode>();
    queue.add(root);

    // Edge case where we are adding a new root node.
    if (d == 1) {
      TreeNode temp = new TreeNode(v);
      temp.left = root;
      return temp;
    }

    int current = 1;
    int next = 0;
    int depth = 1;   // depth counter as we iterate

    while (!queue.isEmpty()) {
      TreeNode node = queue.poll();
      current --;

      if (d - 1 == depth) {
        // Store the left and right pointers to reattach.
        TreeNode left = node.left;
        TreeNode right = node.right;

        // Create the new row.
        node.left = new TreeNode(v);
        node.right = new TreeNode(v);

        // Reattach the old pointers to the new row.
        node.right.right = right;
        node.left.left = left;
      } else {
        if (node.left != null) {
          queue.add(node.left);
          next ++;
        }

        if (node.right != null) {
          queue.add(node.right);
          next ++;
        }
      }

      if (current == 0) {
        if (depth == d) return root;
        depth ++;
        current = next;
        next = 0;
      }
    }

    return root;
  }
}

Add one row to tree 623

Add one row to tree 623


package alien4cloud.rest.deployment;

import alien4cloud.model.deployment.IDeploymentSource;
import lombok.AllArgsConstructor;
import lombok.Getter;

@Getter
@AllArgsConstructor
public class DeploymentSourceDTO implements IDeploymentSource {
    private String id;
    private String name;
}

Add the DeploymentSource object to provide when the source doesn't exits anymore.


package com.btk5h.skriptmirror.skript.custom;

import org.bukkit.event.Event;

import ch.njol.skript.ScriptLoader;
import ch.njol.skript.Skript;
import ch.njol.skript.lang.Expression;
import ch.njol.skript.lang.ExpressionType;
import ch.njol.skript.lang.SkriptParser;
import ch.njol.skript.lang.util.SimpleExpression;
import ch.njol.skript.log.ErrorQuality;
import ch.njol.util.Kleenean;

public class ExprParseMark extends SimpleExpression<Number> {
  static {
    Skript.registerExpression(ExprParseMark.class, Number.class, ExpressionType.SIMPLE,
        "[the] [parse[r]] mark");
  }

  @Override
  protected Number[] get(Event e) {
    return new Number[]{((CustomSyntaxEvent) e).getParseResult().mark};
  }

  @Override
  public boolean isSingle() {
    return true;
  }

  @Override
  public Class<? extends Number> getReturnType() {
    return Number.class;
  }

  @Override
  public String toString(Event e, boolean debug) {
    return "parser mark";
  }

  @SuppressWarnings("unchecked")
  @Override
  public boolean init(Expression<?>[] exprs, int matchedPattern, Kleenean isDelayed,
                      SkriptParser.ParseResult parseResult) {
    if (!ScriptLoader.isCurrentEvent(
        CustomEffect.EffectEvent.class,
        CustomExpression.ExpressionGetEvent.class,
        CustomExpression.ExpressionChangeEvent.class
    )) {
      Skript.error("The parser mark may only be used in custom syntax.",
          ErrorQuality.SEMANTIC_ERROR);
    }
    return true;
  }
}

Add missing parser mark expression

Add missing parser mark expression


/*
 * Copyright 2018 Daniel Gredler
 *
 * 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 uk.org.okapibarcode.backend;

/**
 * The text alignment of a bar code's human-readable text.
 */
public enum HumanReadableAlignment {

    /** Left-align the human-readable text. */
    LEFT,

    /** Right-align the human-readable text. */
    RIGHT,

    /** Center the human-readable text. */
    CENTER
}

Add support for custom alignment of human readable text (add missing file)


package com.yammer.stresstime.managers;

import com.yammer.stresstime.entities.Employee;
import com.yammer.stresstime.test.DatabaseTest;
import org.junit.Before;
import org.junit.Test;

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.core.IsEqual.equalTo;
import static org.junit.Assert.assertNotNull;

public class EmployeeManagerTest extends DatabaseTest {

    private EmployeeManager mEmployeeManager;

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

    @Test
    public void testFindByYammerIdRetrievesTheCorrectRecord() {
        Employee employee = new Employee();
        employee.setName("John Doe");
        employee.setYammerId("lorem");
        mEmployeeManager.save(employee);
        refresh(employee);
        Employee found = mEmployeeManager.findByYammerId("lorem");

        assertNotNull(found);
        assertThat(found, equalTo(employee));

        mEmployeeManager.delete(employee);
    }
}

Add test to EmployeeManager's findBy method


package com.tqdev.metrics.jvm;

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

import java.lang.management.ManagementFactory;

import org.junit.Test;

import com.sun.management.OperatingSystemMXBean;
import com.sun.management.UnixOperatingSystemMXBean;
import com.tqdev.metrics.core.MetricRegistry;

@SuppressWarnings("restriction")
public class SystemMonitorTest {

	protected final MetricRegistry registry = MetricRegistry.getInstance();

	protected final SystemMonitor systemMonitor = new SystemMonitor(registry);

	@Test
	public void shouldCreateGauges() {
		assertThat(registry.getKeys("jvm.Os.Cpu")).contains("load");
		try {
			@SuppressWarnings("unused")
			OperatingSystemMXBean sun = (OperatingSystemMXBean) ManagementFactory.getOperatingSystemMXBean();
			assertThat(registry.getKeys("jvm.Os.Cpu")).contains("process");
			assertThat(registry.getKeys("jvm.Os.Cpu")).contains("system");
			assertThat(registry.getKeys("jvm.Os.Memory")).contains("free");
			assertThat(registry.getKeys("jvm.Os.Memory")).contains("total");
			assertThat(registry.getKeys("jvm.Os.Swap")).contains("free");
			assertThat(registry.getKeys("jvm.Os.Swap")).contains("total");
		} catch (Exception e) {
			// ignore
		}
		try {
			@SuppressWarnings("unused")
			UnixOperatingSystemMXBean unix = (UnixOperatingSystemMXBean) ManagementFactory.getOperatingSystemMXBean();
			assertThat(registry.getKeys("jvm.Os.FileDescriptors")).contains("open");
			assertThat(registry.getKeys("jvm.Os.FileDescriptors")).contains("max");
		} catch (Exception e) {
			// ignore
		}
	}

	@Test
	public void shouldMeasureGauges() {
		assertThat(registry.get("jvm.Os.Cpu", "process")).isGreaterThanOrEqualTo(0);
		assertThat(registry.get("jvm.Os.Cpu", "system")).isGreaterThanOrEqualTo(0);
		assertThat(registry.get("jvm.Os.Memory", "free")).isGreaterThanOrEqualTo(0);
		assertThat(registry.get("jvm.Os.Memory", "total")).isGreaterThanOrEqualTo(0);
		assertThat(registry.get("jvm.Os.Swap", "free")).isGreaterThanOrEqualTo(0);
		assertThat(registry.get("jvm.Os.Swap", "total")).isGreaterThanOrEqualTo(0);
	}

}

Add test to jvm metrics module

Add test to jvm metrics module


/*
 * #%L
 * SciJava Common shared library for SciJava software.
 * %%
 * Copyright (C) 2009 - 2015 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 org.scijava.module.process;

import org.scijava.Priority;
import org.scijava.module.Module;
import org.scijava.module.ModuleItem;
import org.scijava.module.ModuleService;
import org.scijava.plugin.Parameter;
import org.scijava.plugin.Plugin;

/**
 * A preprocessor plugin that populates default parameter values.
 * <p>
 * Default values are determined using {@link ModuleService#getDefaultValue}.
 * </p>
 *
 * @author Curtis Rueden
 */
@Plugin(type = PreprocessorPlugin.class, priority = Priority.VERY_HIGH_PRIORITY)
public class DefaultValuePreprocessor extends AbstractPreprocessorPlugin {

	@Parameter
	private ModuleService moduleService;

	// -- ModuleProcessor methods --

	@Override
	public void process(final Module module) {
		for (final ModuleItem<?> input : module.getInfo().inputs()) {
			assignDefaultValue(module, input);
		}
		for (final ModuleItem<?> output : module.getInfo().outputs()) {
			assignDefaultValue(module, output);
		}
	}

	// -- Helper methods --

	private <T> void assignDefaultValue(final Module module,
		final ModuleItem<T> item)
	{
		if (module.isResolved(item.getName())) return;
		final T defaultValue = moduleService.getDefaultValue(item);
		if (defaultValue == null) return;
		item.setValue(module, defaultValue);
	}

}

Add preprocessor that assigns default values

Unresolved module items should be assigned their default value,
as given by the ModuleService#getDefaultValue() method, before
anything else (even module initialization!) happens.


package week_of_code_30;

import java.util.Scanner;

public class CandyReplenishingRobot {
  public static void main(String[] args) {
    Scanner in = new Scanner(System.in);
    int n = in.nextInt();
    int originalN = n;
    int t = in.nextInt();
    int count = 0;

    while (t-- > 1) {
      int b = in.nextInt();
      n -= b;
      if (n < 5) {
        count += (originalN - n);
        n = originalN;
      }
    }

    System.out.println(count);
    in.close();
  }
}

Add hackerrank week of code 30 solution

Add hackerrank week of code 30 solution


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

package tachyon.underfs.s3;

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

import tachyon.conf.TachyonConf;
import tachyon.underfs.UnderFileSystemFactory;
import tachyon.underfs.UnderFileSystemRegistry;

public class S3UnderFileSystemTest {
  @Test
  public void factoryTest() {
    TachyonConf conf = new TachyonConf();

    UnderFileSystemFactory factory =
        UnderFileSystemRegistry.find("s3n://localhost/test/path", conf);
    Assert.assertNotNull(
        "A UnderFileSystemFactory should exist for s3n paths when using this module", factory);
  }
}

Add test for S3UnderFileSystem Factory.

Add test for S3UnderFileSystem Factory.


package com.impossibl.stencil.api.impl;

import java.util.Map;

import com.impossibl.stencil.api.GlobalScope;

/**
 * GlobalScope backed by Map
 *
 * @author kdubb
 *
 */
public class MapGlobalScope implements GlobalScope {

  Map<String, Object> source;

  public MapGlobalScope(Map<String, Object> source) {
    this.source = source;
  }

  @Override
  public Object get(String name) {
    if (!source.containsKey(name))
      return GlobalScope.NOT_FOUND;
    return source.get(name);
  }

}

Add map based implementation of GlobalScope


package net.openhft.chronicle.queue;

import net.openhft.chronicle.core.OS;
import net.openhft.chronicle.wire.DocumentContext;
import net.openhft.chronicle.wire.Wire;
import org.junit.Test;

import java.nio.file.Files;
import java.nio.file.Paths;

public class Stackoveflow52274284Test {
    @Test
    public void fails() throws Exception {
        String basePath = OS.TMP;
        String path = Files.createTempDirectory(Paths.get(basePath), "chronicle-")
                .toAbsolutePath()
                .toString();
        System.out.printf("Using temp path '%s'%n", path);

        try (ChronicleQueue chronicleQueue = ChronicleQueue.single(path)) {

            // Create Appender
            ExcerptAppender appender = chronicleQueue.acquireAppender();

            // Create Tailer
            ExcerptTailer tailer = chronicleQueue.createTailer();
            tailer.toStart();

            int numberOfRecords = 10;

            // Write
            for (int i = 0; i <= numberOfRecords; i++) {
                System.out.println("Writing " + i);
                try (final DocumentContext dc = appender.writingDocument()) {
                    dc.wire().write(() -> "msg").text("Hello World!");
                    System.out.println("your data was store to index=" + dc.index());
                } catch (Exception e) {
                    System.err.println("Unable to store value to chronicle");
                    e.printStackTrace();
                }
            }
            // Read
            for (int i = 0; i <= numberOfRecords; i++) {
                System.out.println("Reading " + i);
                try (DocumentContext documentContext = tailer.readingDocument()) {
                    long currentOffset = documentContext.index();
                    System.out.println("Current offset: " + currentOffset);

                    Wire wire = documentContext.wire();

                    if (wire != null) {
                        String msg = wire
                                .read("msg")
                                .text();
                        System.out.println(msg);
                    }
                }
            }
        }
    }
}

Add queue based ring buffer

Add queue based ring buffer


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

/**
 * Given an array with elements from 1 to N where N is the size of the array operate with the
 * array to put every element in the position marked with the value of the element. You can't use
 * any other data structure and take into account the final result has to reflex the values of
 * the original one, not the already modified one.
 *
 * @author Pedro Vicente Gómez Sánchez.
 */
public class MoveElementsToPositions {
}

Add statement to problem 40

Add statement to problem 40


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

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

import org.osgi.framework.Bundle;
import org.osgi.framework.BundleException;
import org.osgi.service.composite.CompositeBundle;
import org.osgi.test.cases.composite.AbstractCompositeTestCase;

public class CompositePropertyTests extends AbstractCompositeTestCase {

	static final String TEST1 = "test1";
	static final String TEST2 = "test2";
	static final String VALUE1 = "value1";
	static final String VALUE2 = "value2";

	public void setUp() {
		super.setUp();
	}

	public void testProperties01() {
		// Test scoping of BundleContext properties for the composite system bundle
		Map configuration = new HashMap();
		configuration.put(TEST1, VALUE1);
		configuration.put(TEST2, VALUE2);
		CompositeBundle composite = createCompositeBundle(compAdmin, getName(), null, configuration);
		String value1 = composite.getSystemBundleContext().getProperty(TEST1);
		assertEquals("Wrong value1", VALUE1, value1);
		String value2 = composite.getSystemBundleContext().getProperty(TEST2);
		assertEquals("Wrong value2", VALUE2, value2);
	}

	public void testProperties02() {
		// Test scoping of BundleContext properties for a constituent bundle
		Map configuration = new HashMap();
		configuration.put(TEST1, VALUE1);
		configuration.put(TEST2, VALUE2);
		CompositeBundle composite = createCompositeBundle(compAdmin, getName(), null, configuration);
		Bundle tb1 = installConstituent(composite, "tb1", "tb1.jar");
		startCompositeBundle(composite);
		try {
			tb1.start();
		} catch (BundleException e) {
			fail("Failed to start tb1.", e);
		}
		String value1 = tb1.getBundleContext().getProperty(TEST1);
		assertEquals("Wrong value1", VALUE1, value1);
		String value2 = tb1.getBundleContext().getProperty(TEST2);
		assertEquals("Wrong value2", VALUE2, value2);
	}
}

Add tests for context property scoping.

Add tests for context property scoping.


package net.gouline.dagger2demo.activity;

import android.support.v7.widget.RecyclerView;
import android.test.ActivityInstrumentationTestCase2;
import android.widget.TextView;

import net.gouline.dagger2demo.R;
import net.gouline.dagger2demo.rest.ITunesService;

/**
 * Mostly following:
 *  http://developer.android.com/training/activity-testing/preparing-activity-testing.html
 *  http://developer.android.com/training/activity-testing/activity-basic-testing.html
 *
 * Created by clkim on 10/19/15
 */
public class AlbumSearchActivityTest extends ActivityInstrumentationTestCase2<AlbumSearchActivity> {
    private AlbumSearchActivity albumSearchActivity;
    private RecyclerView recyclerView;
    private TextView emptyView;
    private ITunesService mITunesService;

    public AlbumSearchActivityTest() {
        super(AlbumSearchActivity.class);
    }

    @Override
    protected void setUp() throws Exception {
        super.setUp();
        albumSearchActivity = getActivity();
        recyclerView = (RecyclerView) albumSearchActivity.findViewById(R.id.recycler_view);
        emptyView = (TextView) albumSearchActivity.findViewById(R.id.empty_view);

        // accessing a Kotlin var in Activity class by the property name
        //  IDE also offers getter getmITunesService()
        mITunesService = albumSearchActivity.mITunesService;
    }

    public void testPreConditions() {
        assertNotNull(albumSearchActivity);
        assertNotNull(recyclerView);
        assertNotNull(emptyView);
    }

    public void testITuneServiceIsInjected() {
        // test for successful Dagger 2 injection in the Activity class
        assertNotNull(mITunesService);
    }

    public void testEmptyTextView_labelText() {
        String expected = albumSearchActivity.getString(R.string.search_empty);
        String actual = emptyView.getText().toString();
        assertEquals(expected, actual);
    }
}

Add basic unit tests for Activity

Add basic unit tests for Activity

Easier to write tests in java since we mostly follow
 http://developer.android.com/training/activity-testing/preparing-activity-testing.html
 http://developer.android.com/training/activity-testing/activity-basic-testing.html

Able to access Kotlin code:
 (public) var -- using its property name, or a 'generated' getter


package prims;

/*
	This class defines vertex for Prims Minimum Spanning Tree algorithm.
*/

class Vertex{

	private int name = -1;					// Vertex name
	private int parent = -1;			// Parent in MST
	private int key = 99999999;			// Key //Distance to MST subset

	// Constructs vertex with specified name

	public Vertex(int name){

		this.name = name;
	}

	// Constructs Vertex with default values

	public Vertex(){
		// Do Nothing.
	}

	// Returns name

	public int getName(){
		return name;
	}

	// Sets parent

	public void setParent(int p){
		parent = p;
	}

	// Returns parent

	public int getParent(){
		return parent;
	}

	// Sets Key

	public void setKey(int k){
		key = k;
	}

	// Returns key

	public int getKey(){
		return key;
	}

}

Add vertex class for prims

Add vertex class for prims


package es.tid.cosmos.mobility.activityarea;

import java.io.IOException;

import com.twitter.elephantbird.mapreduce.io.ProtobufWritable;
import org.apache.hadoop.mapreduce.Reducer;

import es.tid.cosmos.mobility.data.MobProtocol.ActivityArea;
import es.tid.cosmos.mobility.data.MobProtocol.ActivityAreaKey;
import es.tid.cosmos.mobility.data.MobProtocol.Cell;

/**
 *
 * @author losa
 */
public class  FusionTotalVarsReducer extends Reducer<
        ProtobufWritable<ActivityAreaKey>, ProtobufWritable<ActivityArea>,
        ProtobufWritable<ActivityAreaKey>, ProtobufWritable<Cell>> {
    @Override
    protected void reduce(ProtobufWritable<ActivityAreaKey> key,
            Iterable<ProtobufWritable<ActivityArea>> values, Context context)
            throws IOException, InterruptedException {
    }
}

Add Reducer to fusion total vars

Add Reducer to fusion total vars

This Reducer implements MACRO_mobmx_MobVar_fusiontotalvars


package controllers;

import com.google.common.collect.ImmutableMap;
import org.junit.Before;
import org.junit.Test;
import play.mvc.Result;
import play.test.WithApplication;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static play.test.Helpers.callAction;
import static play.test.Helpers.fakeApplication;
import static play.test.Helpers.fakeRequest;
import static play.test.Helpers.session;
import static play.test.Helpers.status;

public class AuthTest extends WithApplication {

    @Before
    public void setUp() {
        start(fakeApplication());
    }

    @Test
    public void authenticateSuccess() {
        Result result = callAction(
            controllers.routes.ref.Application.authenticate(),
            fakeRequest().withFormUrlEncodedBody(ImmutableMap.of(
                "email", "foo@bar.com",
                "password", "password")));
        assertEquals(status(result), 303);
        assertEquals(session(result).get("email"), "foo@bar.com");
    }

    @Test
    public void authenticateFailure() {
        Result result = callAction(
            controllers.routes.ref.Application.authenticate(),
            fakeRequest().withFormUrlEncodedBody(ImmutableMap.of(
                "email", "",
                "password", "")));
        assertEquals(status(result), 400);
        assertNull(session(result).get("email"));
    }

}

Implement tests for authenticate action.


package us.myles.ViaVersion.api.rewriters;

import org.jetbrains.annotations.Nullable;
import us.myles.ViaVersion.api.PacketWrapper;
import us.myles.ViaVersion.api.protocol.ClientboundPacketType;
import us.myles.ViaVersion.api.protocol.Protocol;
import us.myles.ViaVersion.api.remapper.PacketRemapper;
import us.myles.ViaVersion.api.type.Type;

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

/**
 * Abstract rewriter for the declare commands packet to handle argument type name and content changes.
 */
public abstract class CommandRewriter {
    protected final Protocol protocol;
    protected final Map<String, CommandArgumentConsumer> parserHandlers = new HashMap<>();

    protected CommandRewriter(Protocol protocol) {
        this.protocol = protocol;
    }

    public void handleArgument(PacketWrapper wrapper, String argumentType) throws Exception {
        CommandArgumentConsumer handler = parserHandlers.get(argumentType);
        if (handler != null) {
            handler.accept(wrapper);
        }
    }

    public void registerDeclareCommands(ClientboundPacketType packetType) {
        protocol.registerOutgoing(packetType, new PacketRemapper() {
            @Override
            public void registerMap() {
                handler(wrapper -> {
                    int size = wrapper.passthrough(Type.VAR_INT);
                    for (int i = 0; i < size; i++) {
                        byte flags = wrapper.passthrough(Type.BYTE);
                        wrapper.passthrough(Type.VAR_INT_ARRAY_PRIMITIVE); // Children indices
                        if ((flags & 0x08) != 0) {
                            wrapper.passthrough(Type.VAR_INT); // Redirect node index
                        }

                        byte nodeType = (byte) (flags & 0x03);
                        if (nodeType == 1 || nodeType == 2) { // Literal/argument node
                            wrapper.passthrough(Type.STRING); // Name
                        }

                        if (nodeType == 2) { // Argument node
                            String argumentType = handleArgumentType(wrapper.read(Type.STRING));
                            if (argumentType != null) {
                                wrapper.write(Type.STRING, argumentType);
                                handleArgument(wrapper, argumentType);
                            }
                        }

                        if ((flags & 0x10) != 0) {
                            wrapper.passthrough(Type.STRING); // Suggestion type
                        }
                    }

                    wrapper.passthrough(Type.VAR_INT); // Root node index
                });
            }
        });
    }

    /**
     * Can be overridden if needed.
     *
     * @param argumentType argument type
     * @return new argument type, or null if it should be removed
     */
    @Nullable
    protected String handleArgumentType(String argumentType) {
        return argumentType;
    }

    @FunctionalInterface
    public interface CommandArgumentConsumer {

        void accept(PacketWrapper wrapper) throws Exception;
    }
}

Add abstract declare commands handler

Add abstract declare commands handler


package io.github.omskscream.ioc;

import org.junit.Test;

import java.util.List;

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

/**
 * @author omskscream
 */
public class IOCKeyTest {
    private final IOCKey k1 = IOCKey.of(Typed.STRING);
    private final IOCKey k2 = IOCKey.of(Typed.STRING);
    private final IOCKey k3 = IOCKey.of("name", Typed.STRING);

    private final IOCKey k4 = IOCKey.of(Typed.INTEGER);
    private final IOCKey k5 = IOCKey.of("name", Typed.INTEGER);

    private final IOCKey k6 = IOCKey.of(new Typed<List<String>>(){});
    private final IOCKey k7 = IOCKey.of(new Typed<List<Integer>>(){});

    @Test
    public void equality() {
        assertEquals(k1, k2);       // keys with same Typed are equal
        assertEquals(k2, k1);       // symmetrically

        assertNotEquals(k1, k3);    // but with different names they are not
        assertNotEquals(k1, k4);    // or with different Typed
        assertNotEquals(k1, k5);
        assertNotEquals(k1, k6);
        assertNotEquals(k4, k5);
        assertNotEquals(k5, k6);
        assertNotEquals(k6, k7);
        assertNotEquals(k3, k4);
        assertNotEquals(k3, k6);
        assertNotEquals(k3, k5);    // or with same name and different Typed

    }

    @Test
    public void hashes() {
        assertEquals(k1.hashCode(), k2.hashCode());
        assertNotEquals(k6.hashCode(), k7.hashCode());

        assertNotEquals(k1.hashCode(), k3.hashCode());
        assertNotEquals(k1.hashCode(), k4.hashCode());

        assertNotEquals(k4.hashCode(), k5.hashCode());
        assertNotEquals(k5.hashCode(), k6.hashCode());
        assertNotEquals(k1.hashCode(), k6.hashCode());
        assertNotEquals(k3.hashCode(), k6.hashCode());
    }
}

Add test for IOCKey class

Add test for IOCKey class


/**
 * A linked list is given such that each node contains an additional random pointer
 * which could point to any node in the list or null.
 * Return a deep copy of the list.
 */
public class Solution {
  public RandomListNode copyRandomList(RandomListNode head) {
    if (head == null) return null;

    HashMap<RandomListNode, RandomListNode> map = new HashMap<RandomListNode, RandomListNode>();
    RandomListNode temp = head;

    // Populate the map and instantiate all new nodes.
    while (temp != null) {
      map.put(temp, new RandomListNode(temp.label));
      temp = temp.next;
    }

    temp = head;
    RandomListNode newHead = new RandomListNode(-1);
    RandomListNode anotherNode = newHead;
    while (temp != null) {
      RandomListNode clone = map.get(temp);
      newHead.next = clone;
      RandomListNode random = temp.random;

      // Assign the random pointer, if it exists.
      if (random != null) newHead.next.random = map.get(random);
      temp = temp.next;
      newHead = newHead.next;
    }

    return anotherNode.next;
  }
}

Add linked list deep copy problem

Add linked list deep copy problem


package com.twu.biblioteca.helpers;

import com.twu.biblioteca.IndexPage;
import com.twu.biblioteca.OutputWriter;

public class IndexPageTestHelper extends IndexPage {

    private boolean isPerformActionCalled;

    public IndexPageTestHelper(OutputWriter outputWriter) {
        super(outputWriter);
    }

    @Override
    public void performAction(int inputFromUser) {
        super.performAction(inputFromUser);
        isPerformActionCalled = true;
    }

    public boolean isPerformActionCalled() {
        return isPerformActionCalled;
    }
}

Create a helper class which helps to test IndexPage class


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

package org.apache.jmeter.util;

import junit.framework.TestCase;

public class PackageTest extends TestCase {

	public PackageTest() {
		super();
	}

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

	public void testServer() throws Exception {
		BeanShellServer bshs = new BeanShellServer(9876, "");
		assertNotNull(bshs);
		// Not sure we can test anything else here
	}
	public void testSub1() throws Exception {
		String input = "http://jakarta.apache.org/jmeter/index.html";
		String pattern = "jakarta.apache.org";
		String sub = "${server}";
		assertEquals("http://${server}/jmeter/index.html", StringUtilities.substitute(input, pattern, sub));
	}

	public void testSub2() throws Exception {
		String input = "arg1=param1;param1";
		String pattern = "param1";
		String sub = "${value}";
		assertEquals("arg1=${value};${value}", StringUtilities.substitute(input, pattern, sub));
	}

	public void testSub3() throws Exception {
		String input = "jakarta.apache.org";
		String pattern = "jakarta.apache.org";
		String sub = "${server}";
		assertEquals("${server}", StringUtilities.substitute(input, pattern, sub));
	}

}

Move more tests to test tree

Move more tests to test tree

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


package com.sbsk.web.configuration;

import org.springframework.boot.actuate.endpoint.Endpoint;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

@Configuration
@ComponentScan({"com.sbsk"})
public class ActuatorConfiguration {
    @Bean
    public static Endpoint<String> pingEndpoint() {
        return new Endpoint<String>() {
            @Override
            public String getId() {
                return "ping";
            }

            @Override
            public boolean isEnabled() {
                return true;
            }

            @Override
            public boolean isSensitive() {
                return false;
            }

            @Override
            public String invoke() {
                return "OK";
            }
        };
    }
}

Introduce new ping healthcheck endpoint

Introduce new ping healthcheck endpoint


package me.elrod.pureio;

import java.util.function.Function;

/**
 * Free (F => {@link ConsoleFileCoproduct}).
 */
public abstract class ConsoleFileFree {
    private ConsoleFileFree() {
    }

    // Functor
    public  ConsoleFileFree map(Function f) {
        return cata(
            a -> ConsoleFileFree.pure(f.apply(a)),
            a -> ConsoleFileFree.free(a.map(k -> k.map(f))));
    }

    // Free monad
    public  ConsoleFileFree flatMap(Function<A, ConsoleFileFree> f) {
        return cata(
            f,
            a -> ConsoleFileFree.free(a.map(k -> k.flatMap(f))));
    }

    public abstract  B cata(
        Function pure,
        Function<ConsoleFileCoproduct<ConsoleFileFree>, B> free);

    //----------------------------------------------------------------------

    final static class Pure extends ConsoleFileFree {
        private A a;

        public Pure(A a) {
            this.a = a;
        }

        public  B cata(
            Function pure,
            Function<ConsoleFileCoproduct<ConsoleFileFree>, B> free) {
            return pure.apply(a);
        }
    }

    public static  ConsoleFileFree pure(A a) {
        return new Pure(a);
    }

    //----------------------------------------------------------------------

    final static class Free extends ConsoleFileFree {
        private ConsoleFileCoproduct<ConsoleFileFree> a;

        public Free(ConsoleFileCoproduct<ConsoleFileFree> a) {
            this.a = a;
        }

        public  B cata(
            Function pure,
            Function<ConsoleFileCoproduct<ConsoleFileFree>, B> free) {
            return free.apply(a);
        }
    }

    public static  ConsoleFileFree free(ConsoleFileCoproduct<ConsoleFileFree> a) {
        return new Free(a);
    }
}

Add Free over ConsoleFileCoproduct - untested

Signed-off-by: Ricky Elrod <3de8762d49a778edd8b1aa9f381ea5a9ccb62944@elrod.me>


package com.haxademic.demo.system;

import com.haxademic.core.app.P;
import com.haxademic.core.app.PAppletHax;
import com.haxademic.core.file.FileUtil;
import com.haxademic.core.math.Millis;
import com.haxademic.core.system.AppRestart;

public class Demo_AppRestart_afterUptime
extends PAppletHax {
	public static void main(String args[]) { PAppletHax.main(Thread.currentThread().getStackTrace()[1].getClassName()); }

	public void drawApp() {
		p.background(0);
		p.text(uptimeHours() + FileUtil.NEWLINE + P.hour() + ":" + P.minute() + ":" + P.second(), 20, 30);

		// restart if running for x hours and the local time is between 7-8pm
		if(uptimeHours() > 0.01f && P.hour() >= 19 && P.hour() < 20) {
			AppRestart.restart( p );
		}
	}

	protected float uptimeHours() {
		return Millis.msToHours(p.millis());
	}
}

Add demo to restart within certain hours after a certain uptime


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

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

/**
 * Holds a list of fields names used for TSV. Specified as it's own class as it is used in more than one client.
 * @author Tony Wardell
 * Date: 28/06/2017
 * Time: 11:22
 * Created with IntelliJ IDEA.
 */
public class TSVDownload {

    public static final String GENE_PRODUCT_ID_FIELD_NAME = "geneproductid";
    public static final String SYMBOL_FIELD_NAME = "symbol";
    public static final String QUALIFIER_FIELD_NAME = "qualifier";
    public static final String GO_TERM_FIELD_NAME = "goid";
    public static final String GO_NAME_FIELD_NAME = "goname";
    public static final String ECO_ID_FIELD_NAME = "evidencecode";
    public static final String GO_EVIDENCE_CODE_FIELD_NAME = "goevidence";
    public static final String REFERENCE_FIELD_NAME = "reference";
    public static final String WITH_FROM_FIELD_NAME = "withfrom";
    public static final String TAXON_ID_FIELD_NAME = "taxonid";
    public static final String ASSIGNED_BY_FIELD_NAME = "assignedby";
    public static final String ANNOTATION_EXTENSION_FIELD_NAME = "extensions";
    public static final String DATE_FIELD_NAME = "date";
    public static final String TAXON_NAME_FIELD_NAME = "taxonname";
    public static final String GENE_PRODUCT_NAME_FIELD_NAME = "name";
    public static final String GENE_PRODUCT_SYNONYMS_FIELD_NAME = "synonyms";
    public static final String GENE_PRODUCT_TYPE_FIELD_NAME = "geneProductType";

    private static final List<String> FULL_FIELD_LIST = Arrays.asList(GENE_PRODUCT_ID_FIELD_NAME, SYMBOL_FIELD_NAME,
                                                                      QUALIFIER_FIELD_NAME, GO_TERM_FIELD_NAME,
                                                                      GO_NAME_FIELD_NAME, ECO_ID_FIELD_NAME,
                                                                      GO_EVIDENCE_CODE_FIELD_NAME,
                                                                      REFERENCE_FIELD_NAME, WITH_FROM_FIELD_NAME,
                                                                      TAXON_ID_FIELD_NAME, ASSIGNED_BY_FIELD_NAME,
                                                                      ANNOTATION_EXTENSION_FIELD_NAME, DATE_FIELD_NAME,
                                                                      TAXON_NAME_FIELD_NAME,
                                                                      GENE_PRODUCT_NAME_FIELD_NAME,
                                                                      GENE_PRODUCT_SYNONYMS_FIELD_NAME,
                                                                      GENE_PRODUCT_TYPE_FIELD_NAME);

    public static List<String> whichColumnsWillWeShow(List<String> selectedFields) {
        return selectedFields.isEmpty() ? FULL_FIELD_LIST : selectedFields;
    }
}

Change the field names for gene product name and synonyms so that match the ones used in the Annotation model.


// Use synchronize to control access.

class SumArray {
	private int sum;

	synchronized int sumArray(int nums[]) {
		sum = 0; // reset sum

		for(int i=0; i<nums.length; i++) {
			sum += nums[i];
			System.out.println("Running total for " + Thread.currentThread().getName() + " is " + sum);
			try {
				Thread.sleep(10); // allow task-switch
			}
			catch(InterruptedException exc) {
				System.out.println("Main thread interrupted.");
			}
		}
		return sum;
	}
}

class MyThread implements Runnable {
	Thread thrd;
	static SumArray sa = new SumArray();
	int a[];
	int answer;

	// Construct a new thread.
	MyThread(String name, int nums[]) {
		thrd = new Thread(this, name);
		a = nums;
		thrd.start(); // start the thread
	}

	// Begin execution of new thread.
	public void run() {
		int sum;

		System.out.println(thrd.getName() + " starting.");

		answer = sa.sumArray(a);
		System.out.println("Sum for " + thrd.getName() + " is " + answer);

		System.out.println(thrd.getName() + " terminating.");
	}
}

class Sync {
	public static void main(String args[]) {
		int a[] = {1, 2, 3, 4, 5};

		MyThread mt1 = new MyThread("Child #1", a);
		MyThread mt2 = new MyThread("Child #2", a);
	}
}

Use synchronize to control access

Use synchronize to control access

http://ideone.com/ezMWzK


/*
 * This file is part of ELKI:
 * Environment for Developing KDD-Applications Supported by Index-Structures
 *
 * Copyright (C) 2020
 * ELKI Development Team
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * 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 Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 */
package elki.evaluation.clustering;

import elki.utilities.datastructures.KuhnMunkresStern;
import elki.utilities.documentation.Reference;

/**
 * Calculates the accuracy of a clustering based on the maximum set matching
 * found by the Hungarian algorithm. The resulting runtime is O(k³) for k
 * clusters due to the matching algorithm.
 *

 * Reference:
 *

 * M. J. Zaki and W. Meira Jr.

 * Data Mining and Analysis: Fundamental Concepts and Algorithms

 *
 * @author Robert Gehde
 */
@Reference(authors = "M. J. Zaki and W. Meira Jr.", //
    title = "Data Mining and Analysis: Fundamental Concepts and Algorithms", //
    booktitle = "", //
    url = "http://www.dataminingbook.info/", //
    bibkey = "DBLP:books/cu/ZM2014")
public class MaximumMatchingAccuracy {
  /**
   * Accuracy calculated with maximum matching
   */
  protected double accuracy;

  /**
   * Calculate the maximum matching accuracy.
   *
   * @param table cluster contingency table
   */
  public MaximumMatchingAccuracy(ClusterContingencyTable table) {
    int[][] cont = table.contingency;
    final int rowlen = table.size1, collen = table.size2;
    final int maxlen = Math.max(rowlen, collen);
    // convert to costs for minimum matching:
    double[][] costs = new double[maxlen][maxlen];
    for(int i = 0; i < rowlen; i++) {
      for(int j = 0; j < collen; j++) {
        costs[i][j] = -cont[i][j];
      }
    }
    int[] chosen = new KuhnMunkresStern().run(costs);
    // read off maximum matching
    double correctAssociations = 0;
    for(int i = 0; i < maxlen; i++) {
      correctAssociations += chosen[i] < collen ? cont[i][chosen[i]] : 0;
    }
    accuracy = correctAssociations / cont[rowlen][collen];
  }

  /**
   * Get the maximum matching cluster accuracy.
   *
   * @return accuracy
   */
  public double getAccuracy() {
    return accuracy;
  }
}

Add maximum matching cluster accuracy

Add maximum matching cluster accuracy


package com.vrachieru.cnp4j;

import com.vrachieru.cnp4j.exception.Cnp4jException;

import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;

public class CnpValidatorTest {

    @Rule
    public final ExpectedException exception = ExpectedException.none();

    @Test
    public void validate_success_1800_male() {
        CnpValidator.validate("3350717113978");
        CnpValidator.validate("3290202368859");
        CnpValidator.validate("3070709233667");
    }

    @Test
    public void validate_success_1800_female() {
        CnpValidator.validate("4490805241431");
        CnpValidator.validate("4860708316111");
        CnpValidator.validate("4440510283854");
    }

    @Test
    public void validate_success_1900_male() {
        CnpValidator.validate("1210419290352");
        CnpValidator.validate("1780310350607");
        CnpValidator.validate("1930313207799");
    }

    @Test
    public void validate_success_1900_female() {
        CnpValidator.validate("2750705226687");
        CnpValidator.validate("2151224322302");
        CnpValidator.validate("2190616042297");
    }

    @Test
    public void validate_success_2000_male() {
        CnpValidator.validate("5140129079734");
        CnpValidator.validate("5001116287452");
        CnpValidator.validate("5031107050671");
    }

    @Test
    public void validate_success_2000_female() {
        CnpValidator.validate("6140514337371");
        CnpValidator.validate("6130520171631");
        CnpValidator.validate("6101025222967");
    }

    @Test
    public void validate_failure_invalidCheckDigit() {
        exception.expect(Cnp4jException.class);
        CnpValidator.validate("1910209405800");
    }
}

Add JUnits for CNP validator

Add JUnits for CNP validator


package jp.gr.java_conf.hhayakawa_jp.beehive_client;

import java.io.IOException;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;

class ZonedDateTimeSerializer extends JsonSerializer<ZonedDateTime> {

    @Override
    public void serialize(ZonedDateTime datetime, JsonGenerator generator,
            SerializerProvider serializerProvider)
            throws IOException, JsonProcessingException {
        generator.writeString(
                DateTimeFormatter.ISO_OFFSET_DATE_TIME.format(datetime));
    }

}

Change to use ZonedDateTime object directory for datetime in message payload .


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

import org.fife.ui.rsyntaxtextarea.TokenMaker;
import org.scijava.plugin.SciJavaPlugin;

/**
 * Placeholder interface for syntax highlighters.
 * <p>
 * Third-party libraries can provide syntax highlighter plugins for the script
 * editor by implementing this interface, extending the {@link TokenMaker} and
 * providing the lower-cased language name as {@code label}.
 * </p>
 *
 * @author Johannes Schindelin
 */
public interface SyntaxHighlighter extends SciJavaPlugin, TokenMaker { }

Add a place-holder interface for syntax highlighter plugins

This will allow third-party components to provide their own syntax
highlighting plugins for additional languages.

The next commit will actually convert all of our custom syntax
highlighters into such plugins so that we 'eat our own dog food'.

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


package org.cyclops.cyclopscore.datastructure;

import lombok.Data;
import net.minecraft.util.BlockPos;
import net.minecraft.world.World;

/**
 * A simple data class for a block position inside a world.
 * @author rubensworks
 */
@Data
public class DimPos {

    private final World world;
    private final BlockPos blockPos;

}

Add DImPos data class for storing World and BlockPos.


package year2011;

import java.util.Scanner;

/**
 *
Binary Adder

 *
Create an application that accepts a binary number and a decimal number as input.
 * Add these numbers. Display the sum as a binary number.

 *
 * @author John Cameron
 * @see Problem Descrption and Requirements
 */
public class BinaryAdder {

    public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);

        System.out.println("Enter binary number: ");

        int binaryNumberBase10 = Integer.parseInt(scanner.nextLine(), 2);

        System.out.println("Enter decimal number: ");

        int decimalNumber = scanner.nextInt();

        scanner.close();

        int result = (binaryNumberBase10 + decimalNumber);

        System.out.println("Binary sum is: " + Integer.toString(result, 2));

    }

}

Add Binary Adder (2011) solution

Add Binary Adder (2011) solution


package com.ggcoke.oj.leetcode;

import java.util.Hashtable;
import java.util.Iterator;

/**
 * @author Wang Huisong <ggcoke@foxmail.com>
 */
public class SingleNumber {

    public static void main(String[] args) {
        SingleNumber sn = new SingleNumber();

        int[] nums = {0, 0, 1, 1, 2, 2, 3, 3, 5, 4, 5};

        System.out.println(sn.singleNumber(nums));
    }

    public int singleNumber(int[] nums) {
        Hashtable<Integer, Integer> table = new Hashtable<Integer, Integer>();
        for (int num : nums) {
            if (table.containsKey(num)) {
                table.remove(num);
            } else {
                table.put(num, num);
            }
        }

        int result = 0;
        Iterator it = table.keySet().iterator();
        while (it.hasNext()) {
            result = (Integer) it.next();
        }

        return result;
    }
}

Add solution of 'Single Number'

Add solution of 'Single Number'


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

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

import java.io.File;
import java.net.URL;

import org.junit.Test;

/**
 * Tests the {@link DllFile} class.
 *
 * @author Johannes Schindelin
 */
public class DllFileTest {
	@Test
	public void testRecompiledDll() {
		final URL emptyDllURL = getClass().getResource("/empty.dll");
		assertEquals("file", emptyDllURL.getProtocol());
		final File emptyDll = new File(emptyDllURL.getPath());
		assertTrue(emptyDll.exists());

		final URL recompiledDllURL = getClass().getResource("/recompiled.dll");
		assertEquals("file", recompiledjustedDllURL.getProtocol());
		final File recompiledDll = new File(recompiledDllURL.getPath());
		assertTrue(recompiledDll.exists());

		assertTrue(DllFile.equals(emptyDll, recompiledDll));
	}
}

Verify that the DllFile class correctly compares real .dll files

When recompiling an empty .c file into a .dll, it is a pretty surprising
thing for the unsuspecting developer that the result is not byte-wise
identical. The reason is that several time date stamps are part of the
.dll file format, and that there is a checksum, too, that changes with
the time date stamps, too.

To handle such cases, we just added a class to compare .dll files and
report whether they are functionally identical.

This commit adds a unit test.

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


package com.ziffit.autoconfigure.spring.web;

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

public class CommonDTO {

    private List<String> eventMessages;
    private List<String> errorMessages;

    public CommonDTO() {
        eventMessages = new ArrayList<>();
        errorMessages = new ArrayList<>();
    }

    public void addEventMessage(String message) {
        eventMessages.add(message);
    }

    public void addErrorMessage(String errorMessage) {
        errorMessages.add(errorMessage);
    }

    public List<String> getEventMessages() {
        return eventMessages;
    }

    public void setEventMessages(List<String> eventMessages) {
        this.eventMessages = eventMessages;
    }

    public List<String> getErrorMessages() {
        return errorMessages;
    }

    public void setErrorMessages(List<String> errorMessages) {
        this.errorMessages = errorMessages;
    }
}

Add a base data transfer object.

Add a base data transfer object.


package leetcode.word_pattern;

import java.util.HashMap;

public class Solution {
    public boolean wordPattern(String pattern, String str) {
        String[] char2Str = new String[26];
        HashMap<String, Integer> str2Char = new HashMap<String, Integer>();
        String[] splits = str.split(" +");
        if(splits.length != pattern.length()) return false;
        int length = splits.length;
        for(int i = 0; i < length; i++){
            String word = splits[i];
            char c = pattern.charAt(i);
            if(word.equals(char2Str[c - 'a'])) continue;
            if(str2Char.containsKey(word) || char2Str[c - 'a'] != null)
                return false;
            str2Char.put(word, (int)(c - 'a'));
            char2Str[c - 'a'] = word;
        }
        return true;
    }
}

Add solution for Word Pattern

Add solution for Word Pattern

Word Pattern: https://leetcode.com/problems/word-pattern/


package ea.tool.checker;

import ea.tool.api.EAUtil;
import org.junit.Test;

import java.util.List;

public class EAUtilTest {
    @Test
    public void testGetElementList() {
//        System.out.println("Start...");
//
//        String file = "C:\\Work\\dbtools\\dbtools\\sample\\sample.EAP";
//        List<String[]> elements = EAUtil.getElementList(file);
//        System.out.printf("%s, elements: %d, %s\r\n", file, elements.size(), elements);
    }
}

Support to read eap file

Support to read eap file


package org.jboss.shamrock.runtime.graal;

import javax.management.JMX;
import javax.management.MBeanServerConnection;
import javax.management.ObjectName;

import com.oracle.svm.core.annotate.Substitute;
import com.oracle.svm.core.annotate.TargetClass;

@TargetClass(JMX.class)
final class Target_javax_management_JMX {

    @Substitute
    private static <T> T createProxy(MBeanServerConnection connection,
                                     ObjectName objectName,
                                     Class<T> interfaceClass,
                                     boolean notificationEmitter,
                                     boolean isMXBean) {
        throw new IllegalStateException("Not Implemented in Substrate");
    }

}

Add substitution for problematic JMX method


/*
 * Copyright 2016 Palantir Technologies
 *
 * Licensed under the BSD-3 License (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://opensource.org/licenses/BSD-3-Clause
 *
 * 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.palantir.example.profile;

import static com.palantir.example.profile.schema.generated.UserProfileTable.CookiesIdxTable.CookiesIdxColumn;

import java.util.UUID;

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

public class CookiesIdxColumnTest {
    @Test
    public void testHashCode() {
        UUID uuid = new UUID(3, 4);
        CookiesIdxColumn a = CookiesIdxColumn.of(new byte[]{1}, new byte[]{2}, uuid);
        CookiesIdxColumn b = CookiesIdxColumn.of(new byte[]{1}, new byte[]{2}, uuid);
        Assert.assertEquals(a.hashCode(), b.hashCode());
    }
}

Test that our generated hashCode is deep enough

This could be made obsolete by using EqualsVerifier


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

/**
 * Given a sorted array full of integers, can you write a method to return a BST?
 *
 * A binary search tree (BST), sometimes also called an ordered or sorted binary tree, is a
 * node-based binary tree data structure where each node has a comparable key (and an associated
 * value) and satisfies the restriction that the key in any node is larger than the keys in all
 * nodes in that node's left sub-tree are smaller than the keys in all nodes in that node's right
 * sub-tree. Each node has no more than two child nodes.
 *
 * @author Pedro Vicente Gómez Sánchez.
 */
public class SortedArrayToBST {
}

Add statement to problem 24

Add statement to problem 24


package com.skcraft.plume.module;

import com.sk89q.worldedit.forge.ForgePermissionsProvider;
import com.sk89q.worldedit.forge.ForgeWorldEdit;
import com.sk89q.worldedit.util.eventbus.Subscribe;
import com.skcraft.plume.common.UserId;
import com.skcraft.plume.common.service.auth.Authorizer;
import com.skcraft.plume.common.service.auth.Context;
import com.skcraft.plume.common.service.auth.Context.Builder;
import com.skcraft.plume.common.util.module.Module;
import com.skcraft.plume.common.util.service.InjectService;
import com.skcraft.plume.common.util.service.Service;
import com.skcraft.plume.util.Contexts;
import com.skcraft.plume.util.profile.Profiles;
import cpw.mods.fml.common.event.FMLServerStartingEvent;
import net.minecraft.command.ICommand;
import net.minecraft.entity.player.EntityPlayerMP;

@Module(name = "worldedit-perm-provider", hidden = true)
public class WorldEditPermProvider implements ForgePermissionsProvider {

    @InjectService
    private Service<Authorizer> authorizer;

    @Subscribe
    public void onFMLServerStartingEvent(FMLServerStartingEvent event) {
        ForgeWorldEdit.inst.setPermissionsProvider(this);
    }

    @Override
    public boolean hasPermission(EntityPlayerMP player, String permission) {
        UserId userId = Profiles.fromPlayer(player);
        Context.Builder builder = new Builder();
        Contexts.update(builder, player);
        return authorizer.provide().getSubject(userId).hasPermission(permission, builder.build());
    }

    @Override
    public void registerPermission(ICommand command, String permission) {
    }

}

Add module to hook the authorizer into WE.


package nakadi;

import com.google.common.collect.ImmutableMap;
import java.io.EOFException;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.util.Map;
import org.junit.Test;

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

public class ExceptionSupportTest {

  private static final ImmutableMap<Throwable, Boolean> CODES_TO_EXCEPTIONS =
      ImmutableMap.<Throwable, Boolean>builder()
          // ok
          .put(new ServerException(Problem.localProblem("", "")), true)
          .put(new NetworkException(Problem.localProblem("", "")), true)
          .put(new RateLimitException(Problem.localProblem("", "")), true)
          .put(new EOFException(), true)
          .put(new UncheckedIOException(new java.net.SocketTimeoutException()), true)
          .put(new UncheckedIOException(new IOException("")), true)
          .put(new java.util.concurrent.TimeoutException(), true)
          // nope
          .put(new Throwable(""), false)
          .put(new Exception(), false)
          .put(new InterruptedException(), false)
          .put(new IOException(), false)
          .put(new NakadiException(Problem.localProblem("", "")), false)
          .put(new ClientException(Problem.localProblem("", "")), false)
          .put(new ContractException(Problem.localProblem("", "")), false)
          .put(new NotFoundException(Problem.localProblem("", "")), false)
          .put(new PreconditionFailedException(Problem.localProblem("", "")), false)
          .build();

  @Test
  public void isEventStreamRetryable() {
    for (Map.Entry<Throwable, Boolean> entry : CODES_TO_EXCEPTIONS.entrySet()) {
      assertTrue(entry.getValue() == ExceptionSupport.isEventStreamRetryable(entry.getKey()));
      assertFalse(ExceptionSupport.isEventStreamRetryable(
          new ConflictException(Problem.localProblem("", ""))));
    }
  }

  @Test
  public void isSubscriptionStreamRetryable() {
    for (Map.Entry<Throwable, Boolean> e : CODES_TO_EXCEPTIONS.entrySet()) {
      assertTrue(e.getValue() == ExceptionSupport.isSubscriptionStreamRetryable(e.getKey()));
      assertTrue(ExceptionSupport.isSubscriptionStreamRetryable(
          new ConflictException(Problem.localProblem("", ""))));
    }
  }
}

Add tests for retryable exceptions

Add tests for retryable exceptions


/*
 * This file is released under terms of BSD license
 * See LICENSE file for more information
 */
package claw.tatsu.xcodeml.xnode.fortran;

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

/**
 * Intrinsic function name as enumeration.
 *
 * @author clementval
 */
public enum Xintrinsic {
  PRESENT;

  private static final Map<String, Xintrinsic> _stringToEnum = new HashMap<>();

  static {
    for(Xintrinsic value : values()) {
      _stringToEnum.put(value.toString().toLowerCase(), value);
    }
  }

  public static Xintrinsic fromString(String value) {
    return (value == null || !_stringToEnum.containsKey(value.toLowerCase())) ?
        null : _stringToEnum.get(value.toLowerCase());
  }
}

Add enum holding intrinsic function name (need to be populated)


package top.quantic.sentry.health;

import com.google.common.cache.Cache;
import com.google.common.cache.CacheStats;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.actuate.health.Health;
import org.springframework.boot.actuate.health.HealthIndicator;
import org.springframework.cache.CacheManager;
import org.springframework.cache.guava.GuavaCache;
import org.springframework.stereotype.Component;

import java.util.LinkedHashMap;
import java.util.Map;
import java.util.stream.Collectors;

@Component
public class CacheHealthIndicator implements HealthIndicator {

    private final CacheManager cacheManager;

    @Autowired
    public CacheHealthIndicator(CacheManager cacheManager) {
        this.cacheManager = cacheManager;
    }

    @Override
    public Health health() {
        Map<String, Map<String, Object>> caches = cacheManager.getCacheNames().stream()
            .map(name -> (GuavaCache) cacheManager.getCache(name))
            .map(cache -> buildStats(cache.getName(), cache.getNativeCache()))
            .collect(Collectors.toMap(stats -> (String) stats.get("name"), stats -> stats));
        Health.Builder builder = Health.up()
            .withDetail("count", caches.size());
        caches.forEach(builder::withDetail);
        return builder.build();
    }

    private Map<String, Object> buildStats(String name, Cache<Object, Object> cache) {
        Map<String, Object> map = new LinkedHashMap<>();
        map.put("name", name);
        map.put("status", "UP");
        map.put("size", cache.size());
        CacheStats stats = cache.stats();
        map.put("hitRate", stats.hitRate());
        map.put("hitCount", stats.hitCount());
        map.put("missCount", stats.missRate());
        map.put("loadSuccessCount", stats.loadSuccessCount());
        map.put("loadExceptionCount", stats.loadExceptionCount());
        map.put("totalLoadTime", stats.totalLoadTime());
        map.put("evictionCount", stats.evictionCount());
        return map;
    }
}

Add a health indicator for caches

Add a health indicator for caches


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

package no.ntnu.okse.core.messaging;

import no.ntnu.okse.Application;
import no.ntnu.okse.core.topic.Topic;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;

import java.util.HashSet;
import java.util.List;

import static org.testng.Assert.*;

public class MessageServiceTest {

    MessageService m;

    @BeforeMethod
    public void setUp() throws Exception {
        m = MessageService.getInstance();
    }

    @AfterMethod
    public void tearDown() throws Exception {
        m = null;
    }

    @Test
    public void testIsCachingMessages() throws Exception {
        assertEquals(Application.CACHE_MESSAGES, m.isCachingMessages());
    }

    @Test
    public void testGenerateMessageForAGivenTopicSet() throws Exception {
        HashSet<Topic> topics = new HashSet<>();
        topics.add(new Topic("test", "TEST"));
        topics.add(new Topic("test2", "TEST"));
        Message msg = new Message("message", "origTopic", null, "Test");
        List<Message> generated = m.generateMessageForAGivenTopicSet(msg, topics);

        generated.forEach(genMsg -> {
            assertFalse(genMsg.getTopic().equals("origTopic"));
            assertNotSame(genMsg, msg);
            assertTrue(genMsg.getTopic().equals("test") || genMsg.getTopic().equals("test2"));
        });
        assertEquals(generated.size(), 2);
    }
}

Add some tests for MessageService

Add some tests for MessageService


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

package org.opendaylight.ovsdb.openstack.netvirt;

import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;

import java.net.HttpURLConnection;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import org.opendaylight.neutron.spi.NeutronSubnet;
import org.opendaylight.ovsdb.openstack.netvirt.api.Action;
import org.opendaylight.ovsdb.openstack.netvirt.impl.NeutronL3Adapter;

/**
 * Unit test fort {@link SubnetHandler}
 */
@RunWith(MockitoJUnitRunner.class)
public class SubnetHandlerTest {

    @InjectMocks private SubnetHandler subnetHandler;

    @Mock NeutronL3Adapter neutronl3Adapter;

    @Test
    public void testCanCreateSubnet() {
        assertEquals("Error, canCreateSubnet() did not return the correct HTTP flag", HttpURLConnection.HTTP_CREATED, subnetHandler.canCreateSubnet(mock(NeutronSubnet.class)));
    }

    @Test
    public void testCanUpdateSubnet() {
        assertEquals("Error, canUpdateSubnet() did not return the correct HTTP flag", HttpURLConnection.HTTP_CREATED, subnetHandler.canUpdateSubnet(mock(NeutronSubnet.class), mock(NeutronSubnet.class)));
    }

    @Test
    public void testCanDeleteSubnet() {
        assertEquals("Error, canDeleteSubnet() did not return the correct HTTP flag", HttpURLConnection.HTTP_CREATED, subnetHandler.canDeleteSubnet(mock(NeutronSubnet.class)));
    }

    @Test
    public void testProcessEvent() {
        NorthboundEvent ev = mock(NorthboundEvent.class);
        when(ev.getSubnet()).thenReturn(mock(NeutronSubnet.class));

        when(ev.getAction()).thenReturn(Action.ADD);
        subnetHandler.processEvent(ev);
        verify(neutronl3Adapter, times(1)).handleNeutronSubnetEvent(ev.getSubnet(), ev.getAction());;

        when(ev.getAction()).thenReturn(Action.DELETE);
        subnetHandler.processEvent(ev);
        verify(neutronl3Adapter, times(1)).handleNeutronSubnetEvent(ev.getSubnet(), ev.getAction());;

        when(ev.getAction()).thenReturn(Action.UPDATE);
        subnetHandler.processEvent(ev);
        verify(neutronl3Adapter, times(1)).handleNeutronSubnetEvent(ev.getSubnet(), ev.getAction());;
    }
}

Add JUnit testing for SubnetHandler class.

Change-Id: I164fbf62f1a119ec8582740c84b77a1775e149b0
Signed-off-by: Alexis de Talhouët <3f85d13b1d0fb141169e8f22f55d7ee87dcd5f00@inocybe.com>


package org.cyclops.cyclopscore.init;

import org.cyclops.cyclopscore.tracking.IModVersion;

/**
 * A {@link ModBase} which is also a {@link org.cyclops.cyclopscore.tracking.IModVersion}.
 * @author rubensworks
 */
public abstract class ModBaseVersionable extends ModBase implements IModVersion {

    private boolean versionInfo = false;
    private String version;
    private String info;
    private String updateUrl;

    public ModBaseVersionable(String modId, String modName, String modVersion) {
        super(modId, modName);
        putGenericReference(REFKEY_MOD_VERSION, modVersion);
    }

    @Override
    public void setVersionInfo(String version, String info, String updateUrl) {
        versionInfo = true;
        this.version = version;
        this.info = info;
        this.updateUrl = updateUrl;
    }

    @Override
    public boolean isVersionInfo() {
        return versionInfo;
    }

    @Override
    public String getVersion() {
        return version;
    }

    @Override
    public String getInfo() {
        return info;
    }

    @Override
    public String getUpdateUrl() {
        return updateUrl;
    }

    @Override
    public boolean needsUpdate() {
        return getVersion() != null && !getReferenceValue(REFKEY_MOD_VERSION).equals(getVersion());
    }

}

Add base class for mods which are versionable


/*
 Copyright (C) 2003 EBI, GRL

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

 This library is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 Lesser General Public License for more details.

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

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import org.ensembl.healthcheck.DatabaseRegistryEntry;
import org.ensembl.healthcheck.ReportManager;
import org.ensembl.healthcheck.Team;
import org.ensembl.healthcheck.testcase.Priority;
import org.ensembl.healthcheck.testcase.SingleDatabaseTestCase;

/**
 * Check for sequence that does not match GTACN.
 */

public class NonGTACNSequence extends SingleDatabaseTestCase {

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

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

		setDescription("Check for sequence that does not match GTACN.");
		setPriority(Priority.AMBER);
		setEffect("May indicate the presence of ambiguity codes.");
		setFix("Change affected bases to Ns");
		setTeamResponsible(Team.GENEBUILD);

	}

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

		boolean result = true;

		Connection con = dbre.getConnection();

		try {

			Statement stmt = con.createStatement();

			// if this query returns anything then something is wrong
			ResultSet rs = stmt.executeQuery("SELECT sr.seq_region_id, sr.name FROM seq_region sr, dna d WHERE sr.seq_region_id=d.seq_region_id AND d.sequence REGEXP '[^ATGCN]'");

			while (rs != null && rs.next()) {

				result = false;

				ReportManager.problem(this, con, String.format("%s (seq_region_id %s) has non GTACN sequence", rs.getString(2), rs.getLong(1)));

			} // while rs

			stmt.close();

		} catch (SQLException e) {
			e.printStackTrace();
		}

		if (result == true) {

			ReportManager.correct(this, con, "No entries in dna table have non-GTACN bases.");

		}

		return result;

	} // run

} // NonGTACNSequence


package arez.integration.observed;

import arez.Observer;
import arez.annotations.ArezComponent;
import arez.annotations.Observable;
import arez.annotations.Observed;
import arez.annotations.ObserverRef;
import arez.integration.AbstractArezIntegrationTest;
import org.testng.annotations.Test;
import static org.testng.Assert.*;

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

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

    @ObserverRef
    abstract Observer getRenderObserver();

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

    abstract void setValue( long value );
  }

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

    assertEquals( component._renderCallCount, 1 );

    // Manual schedule should generate error
    final IllegalStateException exception =
      expectThrows( IllegalStateException.class, () -> safeAction( () -> component.getRenderObserver().schedule() ) );

    assertEquals( component._renderCallCount, 1 );
    assertEquals( exception.getMessage(),
                  "Arez-0202: Observer.schedule() invoked on observer named 'TestComponent1.0.render' but supportsManualSchedule() returns false." );
  }
}

Add integration test to verify that manual scheduling does not work if not OnDepsChanged


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

import javax.annotation.concurrent.Immutable;

/**
 * Plain object for number of characters with support for half character.
 *
 * @version 0.2.0 2019/02/01
 * @author ExBin Project (https://exbin.org)
 */
@Immutable
public class CharactersNumAndHalf {

    private final int characters;
    private final boolean half;

    public CharactersNumAndHalf(int characters, boolean half) {
        this.characters = characters;
        this.half = half;
    }

    public int getCharacters() {
        return characters;
    }

    public boolean isHalf() {
        return half;
    }
}

Handle group sizes in layout profile - 13


// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.hosted.controller.api.integration.stubs;

import com.yahoo.component.AbstractComponent;
import com.yahoo.vespa.hosted.controller.api.integration.BuildService;

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

/**
 * @author jvenstad
 */
public class MockBuildService extends AbstractComponent implements BuildService {

    private final List<BuildJob> jobs = Collections.synchronizedList(new ArrayList<>());

    @Override
    public void trigger(BuildJob buildJob) {
        jobs.add(buildJob);
    }

    @Override
    public boolean isRunning(BuildJob buildJob) {
        return jobs.contains(buildJob);
    }

    /** List all running jobs. */
    public List<BuildJob> jobs() {
        return new ArrayList<>(jobs);
    }

    /** Clears all running jobs. */
    public void clear() {
        jobs.clear();
    }

    /** Removes the given job for the given project and returns whether it was found. */
    public boolean removeJob(long projectId, String jobType) {
        return jobs.remove(new BuildJob(projectId, jobType));
    }

}

Add file that was lost by IntelliJ

Add file that was lost by IntelliJ


/*
 * Copyright 2015 Datalogics, Inc.
 */

package com.datalogics.pdf.samples.printing;

import com.datalogics.pdf.samples.SampleTest;

import org.junit.Test;

/**
 * Tests the PrintPdf sample.
 */
public class PrintPdfTest extends SampleTest {
    @Test
    public void testMain() throws Exception {
        final String[] args = new String[0];
        PrintPdf.main(args);
    }
}

Add first version of unit test

Add first version of unit test

The test currently calls main() and does nothing else, not even
asserting results (there's nothing to assert, really).

It also passes an empty argument list, letting the sample print the
default document.


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

import com.speedment.common.codegen.Meta;
import com.speedment.common.codegen.model.File;
import com.speedment.runtime.annotation.Api;
import com.speedment.runtime.config.Project;
import com.speedment.runtime.event.Event;
import com.speedment.runtime.event.trait.ProjectEvent;
import static java.util.Objects.requireNonNull;

/**
 *
 * @author  Emil Forslund
 * @since   2.4.0
 */
@Api(version="2.4")
public final class FileGenerated implements ProjectEvent, Event {

    private final Project project;
    private final Meta<File, String> meta;

    public FileGenerated(Project project, Meta<File, String> meta) {
        this.project = requireNonNull(project);
        this.meta    = requireNonNull(meta);
    }

    public Meta<File, String> meta() {
        return meta;
    }

    @Override
    public Project project() {
        return project;
    }
}

Add event for every file generated

Generator: Add event for every file generated


package com.javier.util;

import android.os.Handler;

/**
 * Extends handler post and postDelayed functions. Remembers last called runnable and allows to
 * cancel it.
 *
 * Created by javier on 11.12.15.
 */
public class Timer {

    private Handler mHandler = new Handler();
    private Runnable mLastRunnable;

    /**
     * Executes runnable in the current thread
     * @param runnable
     */
    public void execute(Runnable runnable) {
        mLastRunnable = runnable;
        mHandler.post(runnable);
    }

    /**
     * Executes runnable in the current thread with a delay
     * @param runnable
     * @param delayInMs
     */
    public void executeDelayed(Runnable runnable, long delayInMs) {
        mLastRunnable = runnable;
        mHandler.postDelayed(runnable, delayInMs);
    }

    /**
     * Cancels previously set runnable
     */
    public void clear() {
        if (mLastRunnable != null) {
            mHandler.removeCallbacks(mLastRunnable);
        }
        mLastRunnable = null;
    }

}

Add FileUtils and NetworkUtils with a few functions


package com.github.aureliano.edocs.app;

import java.awt.BorderLayout;
import java.awt.Dimension;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;

public class EdocsApp {

	private static void createAndShowGui() {
		JFrame frame = new JFrame("e-Docs");
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

		JPanel panel = new JPanel(new BorderLayout());
		panel.setOpaque(true);
		frame.setContentPane(panel);

		frame.pack();
		frame.setVisible(true);

		frame.setSize(new Dimension(500, 500));
	}

	public static void main(String[] args) {
		SwingUtilities.invokeLater(new Runnable() {

			@Override
			public void run() {
				createAndShowGui();
			}
		});
	}
}

Create main class to launch a frame.

Create main class to launch a frame.


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

import io.prestosql.connector.CatalogName;
import org.testng.annotations.Test;

import java.util.Map;

import static io.prestosql.testing.TestingSession.testSessionBuilder;
import static org.assertj.core.api.Assertions.assertThat;

public class TestSession
{
    @Test
    public void testSetCatalogProperty()
    {
        Session session = Session.builder(testSessionBuilder().build())
                .setCatalogSessionProperty("some_catalog", "first_property", "some_value")
                .build();

        assertThat(session.getUnprocessedCatalogProperties())
                .isEqualTo(Map.of("some_catalog", Map.of("first_property", "some_value")));

        // empty, will be populated at transaction start
        assertThat(session.getConnectorProperties())
                .isEqualTo(Map.of());

        // empty, will be populated at transaction start
        assertThat(session.getConnectorProperties(new CatalogName("some_catalog")))
                .isEqualTo(Map.of());
    }

    @Test
    public void testBuildWithCatalogProperty()
    {
        Session session = Session.builder(testSessionBuilder().build())
                .setCatalogSessionProperty("some_catalog", "first_property", "some_value")
                .build();
        session = Session.builder(session)
                .build();

        assertThat(session.getUnprocessedCatalogProperties())
                .isEqualTo(Map.of("some_catalog", Map.of("first_property", "some_value")));

        // empty, will be populated at transaction start
        assertThat(session.getConnectorProperties())
                .isEqualTo(Map.of());

        // empty, will be populated at transaction start
        assertThat(session.getConnectorProperties(new CatalogName("some_catalog")))
                .isEqualTo(Map.of());
    }
}

Add unit test for Session

Add unit test for Session