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

import org.apache.beam.sdk.transforms.ParDo;

/**
 * Category tag for validation tests which utilize stateful {@link ParDo}.
 */
public interface UsesStatefulParDo {}

Add JUnit category for stateful ParDo tests


package org.realityforge.replicant.client;

import arez.Arez;
import arez.ArezTestUtil;
import arez.Observer;
import arez.ObserverError;
import java.util.ArrayList;
import java.util.stream.Collectors;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import org.realityforge.braincheck.BrainCheckTestUtil;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import static org.testng.Assert.*;

public abstract class AbstractReplicantTest
{
  private final ArrayList<String> _observerErrors = new ArrayList<>();
  private boolean _ignoreObserverErrors;
  private boolean _printObserverErrors;

  @BeforeMethod
  protected void beforeTest()
    throws Exception
  {
    BrainCheckTestUtil.resetConfig( false );
    ArezTestUtil.resetConfig( false );
    _ignoreObserverErrors = false;
    _printObserverErrors = true;
    _observerErrors.clear();
    Arez.context().addObserverErrorHandler( this::onObserverError );
  }

  @AfterMethod
  protected void afterTest()
    throws Exception
  {
    BrainCheckTestUtil.resetConfig( true );
    ArezTestUtil.resetConfig( true );
    if ( !_ignoreObserverErrors && !_observerErrors.isEmpty() )
    {
      fail( "Unexpected Observer Errors: " + _observerErrors.stream().collect( Collectors.joining( "\n" ) ) );
    }
  }

  protected final void setIgnoreObserverErrors( final boolean ignoreObserverErrors )
  {
    _ignoreObserverErrors = ignoreObserverErrors;
  }

  protected final void setPrintObserverErrors( final boolean printObserverErrors )
  {
    _printObserverErrors = printObserverErrors;
  }

  private void onObserverError( @Nonnull final Observer observer,
                                @Nonnull final ObserverError error,
                                @Nullable final Throwable throwable )
  {
    final String message = "Observer: " + observer.getName() + " Error: " + error + " " + throwable;
    _observerErrors.add( message );
    if ( _printObserverErrors )
    {
      System.out.println( message );
    }
  }

  @Nonnull
  final ArrayList<String> getObserverErrors()
  {
    return _observerErrors;
  }
}

Add base class useful for writing tests with Arez components


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

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;

import java.io.Serializable;
import java.util.Map;

/**
 * @author Ivan Budayeu
 */
@JsonInclude(JsonInclude.Include.NON_NULL)
public class CreateIntegrationTypeRQ implements Serializable {

	@JsonProperty("name")
	private String name;

	@JsonProperty("auth_flow")
	private String authFlow;

	@JsonProperty("group_type")
	private String groupType;

	@JsonProperty("details")
	private Map<String, Object> details;

	public String getName() {
		return name;
	}

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

	public String getAuthFlow() {
		return authFlow;
	}

	public void setAuthFlow(String authFlow) {
		this.authFlow = authFlow;
	}

	public String getGroupType() {
		return groupType;
	}

	public void setGroupType(String groupType) {
		this.groupType = groupType;
	}

	public Map<String, Object> getDetails() {
		return details;
	}

	public void setDetails(Map<String, Object> details) {
		this.details = details;
	}
}

Create integration type rq entity was added


/*
 * Copyright 2015 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 net.kuujo.copycat.raft;

import net.kuujo.copycat.cluster.MemberInfo;
import net.kuujo.copycat.cluster.Session;
import org.testng.annotations.Test;

import static org.testng.Assert.assertEquals;

/**
 * State machine test.
 *
 * @author Jordan Halterman
 */
@Test
public class StateMachineTest {

  /**
   * Tests a state machine.
   */
  public void testStateMachine() {
    StateMachine stateMachine = new TestStateMachine();
    assertEquals(stateMachine.apply(new Commit<>(1, new Session(2, new MemberInfo(3) {}), System.currentTimeMillis(), new TestCommand())), "write");
    assertEquals(stateMachine.apply(new Commit<>(1, new Session(2, new MemberInfo(3) {}), System.currentTimeMillis(), new TestQuery())), "read");
  }

  /**
   * Test command.
   */
  public static class TestCommand implements Command<String> {
  }

  /**
   * Test query.
   */
  public static class TestQuery implements Query<String> {
    @Override
    public Consistency consistency() {
      return Consistency.LINEARIZABLE_STRICT;
    }
  }

  /**
   * Test state machine.
   */
  public static class TestStateMachine extends StateMachine {
    @Apply(TestCommand.class)
    public String applyCommand(Commit<TestCommand> commit) {
      return "write";
    }

    @Filter(TestCommand.class)
    public boolean filterCommand(Commit<TestCommand> commit) {
      return true;
    }

    @Apply(TestQuery.class)
    public String applyQuery(Commit<TestQuery> commit) {
      return "read";
    }
  }

}

Add simple state machine test.

Add simple state machine test.


/*
 * Copyright 2012-2014 Institut National des Sciences Appliquées de Lyon (INSA-Lyon)
 *
 * 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 gololang.concurrent.async;

import org.testng.annotations.Test;

import java.util.HashSet;

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

public class AssignedFutureTest {

  @Test
  public void check_set_future() throws InterruptedException {
    Future future = AssignedFuture.setFuture(666);
    assertThat(future.isResolved(), is(true));
    assertThat(future.isFailed(), is(false));
    assertThat(future.get(), is((Object) 666));
    assertThat(future.blockingGet(), is((Object) 666));
    final HashSet<Object> set = new HashSet<>();
    future.onSet(new Functions.Observer() {
      @Override
      public void apply(Object value) {
        set.add("Ok");
      }
    });
    assertThat(set.size(), is(1));
  }

  @Test
  public void check_failed_future() throws InterruptedException {
    final RuntimeException omg = new RuntimeException("OMG");
    Future future = AssignedFuture.failedFuture(omg);
    assertThat(future.isResolved(), is(true));
    assertThat(future.isFailed(), is(true));
    assertThat(future.get(), is((Object) omg));
    assertThat(future.blockingGet(), is((Object) omg));
    final HashSet<Object> set = new HashSet<>();
    future.onFail(new Functions.Observer() {
      @Override
      public void apply(Object value) {
        set.add("Ok");
      }
    });
    assertThat(set.size(), is(1));
  }
}

Test coverage direct for set / failed futures


package com.elmakers.mine.bukkit.api.magic;

/**
 * Specifies different types of property holders.
 *
 * Properties in Magic can be configured to save in one of these locations.
 *
 * Generally this is an inheritance chain, going like
 *
 * Mage->Class->(SubClass...)->SubClass->Wand
 *
 * But for most purposes properties are all merged together along this chain,
 * and generally speaking a property may not appear in more than one place.
 *
 * The exception to this rule is subclasses, since there maybe many of those, the
 * ones further down the chain will take precedent.
 */
public enum MagicPropertyType {
    WAND, SUBCLASS, CLASS, MAGE
}

Add an enum to represent different storage options for magic properties


/*
 * Copyright 2015 Ryan Gilera.
 *
 * 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.daytron.revworks.event;

import com.github.daytron.revworks.MainUI;
import com.google.common.eventbus.EventBus;
import com.google.common.eventbus.SubscriberExceptionContext;
import com.google.common.eventbus.SubscriberExceptionHandler;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * Wrapper for Guava's EventBus. Defines static methods for EventBus actions.
 * Handles all subscriber exceptions.
 *
 * @author Ryan Gilera
 */
public class AppEventBus implements SubscriberExceptionHandler {

    private final EventBus eventBus = new EventBus(this);

    public static void post(final Object event) {
        MainUI.getAppEventbus().eventBus.post(event);
    }

    public static void register(final Object object) {
        MainUI.getAppEventbus().eventBus.register(object);
    }

    public static void unregister(final Object object) {
        MainUI.getAppEventbus().eventBus.unregister(object);
    }

    @Override
    public void handleException(Throwable exception, SubscriberExceptionContext context) {
        Logger.getLogger(AppEventBus.class.getName())
                .log(Level.SEVERE, null, exception);
    }

}

Create a wrapper class for EventBus for handling subscriber exceptions


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

package org.eclipse.birt.core.script;

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

import org.mozilla.javascript.Scriptable;
import org.mozilla.javascript.ScriptableObject;

/**
 * Represents the scriptable object for Java object, LinkedHashMap.
 * This class supports to access hash map with index.
 *
 * @version $Revision$ $Date$
 */

public class NativeJavaLinkedHashMap extends NativeJavaMap
{

	public NativeJavaLinkedHashMap( )
	{
	}

	public NativeJavaLinkedHashMap( Scriptable scope, Object javaObject,
			Class staticType )
	{
		super( scope, javaObject, staticType );
	}

	/*
	 * (non-Javadoc)
	 *
	 * @see org.mozilla.javascript.Scriptable#get(int,
	 *      org.mozilla.javascript.Scriptable)
	 */

	public Object get( int index, Scriptable start )
	{
		List list = new ArrayList( ( (Map) javaObject ).values( ) );
		if ( list.size( ) > index )
			return list.get( index );

		return Scriptable.NOT_FOUND;
	}
}

Add native object for the hash map which can be accessed by index.


// Copyright Verizon Media. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.security.tls;

import javax.net.ssl.SSLEngine;
import javax.net.ssl.X509ExtendedTrustManager;
import java.net.Socket;
import java.security.cert.X509Certificate;

/**
 * A {@link X509ExtendedTrustManager} that accepts all server certificates.
 *
 * @author bjorncs
 */
public class TrustAllX509TrustManager extends X509ExtendedTrustManager {
    @Override public void checkClientTrusted(X509Certificate[] chain, String authType, Socket socket) { failWhenUsedOnServer(); }
    @Override public void checkClientTrusted(X509Certificate[] chain, String authType, SSLEngine engine) { failWhenUsedOnServer(); }
    @Override public void checkClientTrusted(X509Certificate[] chain, String authType) { failWhenUsedOnServer(); }

    @Override public void checkServerTrusted(X509Certificate[] chain, String authType, Socket socket) {}
    @Override public void checkServerTrusted(X509Certificate[] chain, String authType, SSLEngine engine) {}
    @Override public void checkServerTrusted(X509Certificate[] chain, String authType) {}
    @Override public X509Certificate[] getAcceptedIssuers() { return new X509Certificate[0]; }

    private static void failWhenUsedOnServer() {
        throw new IllegalStateException("TrustAllX509TrustManager cannot be used on server, only client");
    }
}

Add trust manager that accepts any server certificate


package com.fsck.k9.mail.store.webdav;

import com.fsck.k9.mail.MessagingException;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.annotation.Config;

import java.util.Collections;

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

@RunWith(RobolectricTestRunner.class)
@Config(manifest = Config.NONE, sdk = 21)
public class WebDavMessageTest {

    private WebDavMessage message;
    @Mock
    private WebDavFolder mockFolder;
    @Mock
    private WebDavStore mockStore;
    @Mock
    private WebDavFolder mockTrashFolder;

    @Before
    public void before() {
        MockitoAnnotations.initMocks(this);
        when(mockFolder.getName()).thenReturn("Inbox");
        message = new WebDavMessage("message1", mockFolder);
    }

    @Test
    public void delete_asks_folder_to_delete_message() throws MessagingException {
        when(mockFolder.getStore()).thenReturn(mockStore);
        when(mockStore.getFolder("Trash")).thenReturn(mockTrashFolder);
        message.delete("Trash");
        verify(mockFolder).moveMessages(Collections.singletonList(message), mockTrashFolder);
    }
}

Create test infrastructure for WebDavMessage


package org.genericsystem.cv.utils;

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import org.testng.annotations.Test;

@Test
public class ExecutorsTest {

	private LongTaskOverrider taskOverrider = new LongTaskOverrider();

	@Test
	void testExecutor000() {
		ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();
		int[] i = new int[] { 0 };
		Runnable command = () -> {
			final int j = i[0];
			taskOverrider.schedule(() -> {
				try {
					Thread.sleep(200);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				System.out.println(i[0] + " " + j);
			});
			i[0]++;
		};

		executor.scheduleAtFixedRate(command, 0, 100, TimeUnit.MILLISECONDS);

		try {
			Thread.sleep(3000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		executor.shutdown();
	}

}

Test executor with Long task overrider

Test executor with Long task overrider


package com.voodoodyne.postguice.usertype;

import com.google.common.base.Objects;
import org.hibernate.HibernateException;
import org.hibernate.engine.spi.SharedSessionContractImplementor;
import org.hibernate.usertype.UserType;

import java.io.Serializable;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Types;

/**
 * Hibernate {@link UserType} that maps to a simple string column. Your class must be immutable.
 *
 * Create a subclass for any specific type you want converted to JSON.
 *
 * @param <T> is the type of the class you want to convert to string with this
 */
abstract public class SimpleStringUserType<T extends Serializable> implements UserType, Serializable {

	private static final long serialVersionUID = 2020526952561198860L;

	private static final int[] SQL_TYPES = new int[]{Types.VARCHAR};

	private final Class<T> classType;

	public SimpleStringUserType(final Class<T> classType) {
		this.classType = classType;
	}

	/** Implement this to convert from the string value in the column to your user type */
	protected abstract T construct(final String value);

	@Override
	public Object assemble(Serializable cached, Object owner) throws HibernateException {
		return cached;
	}

	@Override
	public Object deepCopy(Object value) throws HibernateException {
		return value;
	}

	@Override
	public Serializable disassemble(Object value) throws HibernateException {
		return (Serializable)value;
	}

	@Override
	public boolean equals(Object x, Object y) throws HibernateException {
		return Objects.equal(x, y);
	}

	@Override
	public int hashCode(Object x) throws HibernateException {
		return Objects.hashCode(x);
	}

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

	@Override
	public Object nullSafeGet(final ResultSet rs, final String[] names, final SharedSessionContractImplementor session, final Object owner) throws HibernateException, SQLException {
		String value = rs.getString(names[0]);

		if (value == null) {
			return null;
		} else {
			return construct(value);
		}
	}

	@Override
	public void nullSafeSet(final PreparedStatement st, final Object value, final int index, final SharedSessionContractImplementor session) throws HibernateException, SQLException {
		if (value == null) {
			st.setNull(index, Types.VARCHAR);
		} else {
			st.setString(index, value.toString());
		}
	}

	@Override
	public Object replace(Object original, Object target, Object owner) throws HibernateException {
		return original;
	}

	@Override
	public Class<?> returnedClass() {
		return this.classType;
	}

	@Override
	public int[] sqlTypes() {
		return SQL_TYPES;
	}
}

Add a simple string user type

Add a simple string user type


package org.cbioportal.logging;

import io.sentry.*;
import io.sentry.dsn.Dsn;
import io.sentry.event.helper.ContextBuilderHelper;
import io.sentry.event.helper.ForwardedAddressResolver;
import io.sentry.event.helper.HttpEventBuilderHelper;

public class SentryClientFactory extends DefaultSentryClientFactory {
    @Override
    public SentryClient createSentryClient(Dsn dsn) {
        SentryClient sentryClient = new SentryClient(createConnection(dsn), getContextManager(dsn));

        /*
         Create and use the ForwardedAddressResolver, which will use the
         X-FORWARDED-FOR header for the remote address if it exists.
          */
        ForwardedAddressResolver forwardedAddressResolver = new ForwardedAddressResolver();

        sentryClient.addBuilderHelper(new HttpEventBuilderHelper(forwardedAddressResolver));

        sentryClient.addBuilderHelper(new ContextBuilderHelper(sentryClient));
        return configureSentryClient(sentryClient, dsn);
    }
}

Customize Sentry client to send x-forwarded for ip address as user address instead of ip address of load balancer


package edu.govschool.govchat.socket;

/**
 * Listener interface for sockets used in GovChat.
 * Based on Oracle documentation. While our two sockets will be inheriting from
 * GCGenericSocket to share setup code, this interface will define
 * a few methods that the sockets will use differently depending on what they
 * are listening for.
 * @author Mr. Davis
 */
public interface GCSocketListener
{

}

Add file stub for socket listener

Add file stub for socket listener


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

/**
 * Java 8 functional interface wrappers that apply context snapshots to the mapped functions.
 *
 *

 * The following functional interfaces are available:
 *

 *
{@link nl.talsmasoftware.context.functions.BiConsumerWithContext}
 *
{@link nl.talsmasoftware.context.functions.BiFunctionWithContext}
 *
{@link nl.talsmasoftware.context.functions.BinaryOperatorWithContext}
 *
{@link nl.talsmasoftware.context.functions.BiPredicateWithContext}
 *
{@link nl.talsmasoftware.context.functions.BooleanSupplierWithContext}
 *
{@link nl.talsmasoftware.context.functions.ConsumerWithContext}
 *
{@link nl.talsmasoftware.context.functions.FunctionWithContext}
 *
{@link nl.talsmasoftware.context.functions.PredicateWithContext}
 *
{@link nl.talsmasoftware.context.functions.RunnableWithContext}
 *
{@link nl.talsmasoftware.context.functions.SupplierWithContext}
 *
{@link nl.talsmasoftware.context.functions.UnaryOperatorWithContext}
 *

 *
 *

 * The base class {@link nl.talsmasoftware.context.functions.WrapperWithContextAndConsumer} allows
 * capturing a new context snapshot after the function has finished.
 */
package nl.talsmasoftware.context.functions;

Add javadoc to the java 8 functions package


/* Copyright 2018 The TensorFlow Authors. All Rights Reserved.

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

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

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

package org.tensorflow.lite.benchmark;

/** Helper class for running a native TensorFlow Lite benchmark. */
class BenchmarkModel {
  static {
    System.loadLibrary("tensorflowlite_benchmark");
  }

  // Executes a standard TensorFlow Lite benchmark according to the provided args.
  //
  // Note that {@code args} will be split by the native execution code.
  public static void run(String args) {
    nativeRun(args);
  }

  private static native void nativeRun(String args);
}

/* Copyright 2018 The TensorFlow Authors. All Rights Reserved.

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

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

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

package org.tensorflow.lite.benchmark;

/** Helper class for running a native TensorFlow Lite benchmark. */
class BenchmarkModel {
  static {
    // Try loading flex first if available. If not load regular tflite shared library.
    try {
      System.loadLibrary("tensorflowlite_benchmark_plus_flex");
    } catch (UnsatisfiedLinkError e) {
      System.loadLibrary("tensorflowlite_benchmark");
    }
  }

  // Executes a standard TensorFlow Lite benchmark according to the provided args.
  //
  // Note that {@code args} will be split by the native execution code.
  public static void run(String args) {
    nativeRun(args);
  }

  private static native void nativeRun(String args);
}

[lite] Update benchmark app to try to load flex first if available to support the case when we build the flex version.

PiperOrigin-RevId: 370787699
Change-Id: I6fb52db0c50a3a2fafb7d698960f6ae57cdce8df


package org.simpleframework.xml.core;

import org.simpleframework.xml.Attribute;
import org.simpleframework.xml.Default;
import org.simpleframework.xml.DefaultType;
import org.simpleframework.xml.Element;
import org.simpleframework.xml.Root;
import org.simpleframework.xml.ValidationTestCase;

public class NotRequiredConstructorInjectionTest extends ValidationTestCase{

   private static final String SOURCE =
   "<exampleNotRequired value='value'/>";

   private static final String EXTRA =
   "<exampleNotRequired value='value'>"+
   "  <extra>extra string</extra>"+
   "</exampleNotRequired>";

   @Root
   private static class ExampleNotRequired {
      private final String name;
      private final String value;
      public ExampleNotRequired(@Element(name="name", required=false) String name, @Attribute(name="value") String value) {
         this.name = name;
         this.value = value;
      }
      @Attribute
      public String getValue() {
         return value;
      }
      @Element(required=false)
      public String getName() {
         return name;
      }
   }

   @Default(value=DefaultType.PROPERTY, required=false)
   public static class ExampleNotRequiredByDefault extends ExampleNotRequired {
      private final String extra;
      public ExampleNotRequiredByDefault(@Element(name="name", required=false) String name, @Attribute(name="value") String value, @Element(name="extra", required=false) String extra) {
         super(name, value);
         this.extra = extra;
      }
      public String getExtra() {
         return extra;
      }
   }

   public void s_testInjection() throws Exception {
      ExampleNotRequired example = new Persister().read(ExampleNotRequired.class, SOURCE);
      assertEquals(example.getName(), null);
      assertEquals(example.getValue(), "value");
   }

   public void testInheritance() throws Exception {
      ExampleNotRequiredByDefault example = new Persister().read(ExampleNotRequiredByDefault.class, SOURCE);
      assertEquals(example.getName(), null);
      assertEquals(example.getValue(), "value");
      assertEquals(example.getExtra(), null);

      ExampleNotRequiredByDefault exampleExtra = new Persister().read(ExampleNotRequiredByDefault.class, EXTRA);
      assertEquals(exampleExtra.getName(), null);
      assertEquals(exampleExtra.getValue(), "value");
      assertEquals(exampleExtra.getExtra(), "extra string");
   }
}

Add test for non required constructor injection

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


/*
 * Copyright 2020 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.
 */
@NonNullApi
package org.gradle.initialization.buildsrc;

import org.gradle.api.NonNullApi;

Add `@NonNullApi` to core package `org.gradle.initialization.buildsrc`


/*
 * MockApplication.java
 *
 * Copyright (C) 2018 [ A Legge Up ]
 *
 * This software may be modified and distributed under the terms
 * of the MIT license.  See the LICENSE file for details.
 */

package com.aleggeup.confagrid;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class MockApplication {

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

Create Mock application for test Spring environments


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

package org.sablecc.sablecc.util;

import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.Set;

import org.sablecc.sablecc.exception.InternalException;

public class WorkSet<T> {

    private final Set<T> done = new HashSet<T>();

    private final LinkedHashSet<T> toDo = new LinkedHashSet<T>();

    public boolean hasNext() {

        return !this.toDo.isEmpty();
    }

    public T next() {

        T next = this.toDo.iterator().next();

        this.toDo.remove(next);
        this.done.add(next);

        return next;
    }

    public void add(
            T element) {

        if (element == null) {
            throw new InternalException("element may not be null");
        }

        if (!this.done.contains(element)) {
            this.toDo.add(element);
        }
    }
}

Add class to manage work sets.

Add class to manage work sets.

Signed-off-by: Etienne M. Gagnon <bf06ec0eb40152cd863534753d026b021022c851@j-meg.com>


package org.jdesktop.swingx.graphics;

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

import java.awt.image.BufferedImage;

import org.junit.Test;

public class GraphicsUtilitiesTest {
    @Test
    public void testClear() {
        BufferedImage img = GraphicsUtilities.createCompatibleImage(1, 1);
        GraphicsUtilities.clear(img);
        assertThat(GraphicsUtilities.getPixels(img, 0, 0, 1, 1, null)[0], is(0));
    }
}

Add test for new clear image method.

Add test for new clear image method.


Add test for new clear image method.

Add test for new clear image method.


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

package imagej.legacy;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assume.assumeTrue;
import ij.IJ;

import org.junit.Before;
import org.junit.Test;
import org.scijava.Context;

/**
 * Unit tests for {@link LegacyService}.
 *
 * @author Johannes Schindelin
 */
public class LegacyServiceTest {

	static {
		/*
		 * We absolutely require that the LegacyInjector did its job
		 * before we use the ImageJ 1.x classes here.
		 */
		DefaultLegacyService.getInstance();
	}

	@Before
	public void cannotRunHeadlesslyYet() {
		assumeTrue(!"true".equals(System.getProperty("java.awt.headless")));
	}

	@Test
	public void testContext() {
		final Context context = new Context(LegacyService.class);

		Context context2 = (Context)IJ.runPlugIn(Context.class.getName(), null);
		assertNotNull(context2);
		assertEquals(context, context2);

		final LegacyService legacyService = (LegacyService)
				IJ.runPlugIn(LegacyService.class.getName(), null);
		assertNotNull(legacyService);
		assertEquals(legacyService, context.getService(LegacyService.class));
	}

}

Add a unit test for the LegacyService

Add a unit test for the LegacyService

So far, it only tests that the recommended way for ImageJ 1.x plugins
to obtain the current legacy service or ImageJ2 context works as
advertised.

As we do not allow headless mode to be handled with the LegacyService
yet, we have to be careful not to execute this unit test without a
graphical user interface.

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


package org.rundeck.storage.data.file;

import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.File;
import java.io.IOException;
import java.util.Map;

/**
 * $INTERFACE is ... User: greg Date: 2/18/14 Time: 11:12 AM
 */
public class JsonMetadataMapper implements MetadataMapper {
    private ObjectMapper objectMapper;

    public JsonMetadataMapper() {
        objectMapper = new ObjectMapper();
    }

    public JsonMetadataMapper(ObjectMapper objectMapper) {
        this.objectMapper = objectMapper;
    }

    @Override
    public void writeMetadata(Map<String, String> meta, File destination) throws IOException {
        if (!destination.getParentFile().exists()) {
            destination.getParentFile().mkdirs();
        }
        objectMapper.writeValue(destination, meta);
    }

    @Override
    @SuppressWarnings("unchecked")
    public Map<String, String> readMetadata(File metadata) throws IOException {
        return objectMapper.readValue(metadata, Map.class);
    }
}

package org.rundeck.storage.data.file;

import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.File;
import java.io.IOException;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

/**
 * $INTERFACE is ... User: greg Date: 2/18/14 Time: 11:12 AM
 */
public class JsonMetadataMapper implements MetadataMapper {
    private ObjectMapper objectMapper;

    public JsonMetadataMapper() {
        objectMapper = new ObjectMapper();
    }

    public JsonMetadataMapper(ObjectMapper objectMapper) {
        this.objectMapper = objectMapper;
    }

    @Override
    public void writeMetadata(Map<String, String> meta, File destination) throws IOException {
        if (!destination.getParentFile().exists()) {
            destination.getParentFile().mkdirs();
        }
        objectMapper.writeValue(destination, meta);
    }

    @Override
    @SuppressWarnings("unchecked")
    public Map<String, String> readMetadata(File metadata) throws IOException {
        if(metadata.isFile()){
            return objectMapper.readValue(metadata, Map.class);
        } else {
            return Collections.<String, String>emptyMap();
        }
    }
}

Return empty map if Json metadatafile does not exist


package com.foo.bar.internal;

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

/** Not API */
public class NotApi {

}

[MJAVADOC-384] Allow whitespace in javadoc exclude list
missed a class

git-svn-id: 6038db50b076e48c7926ed71fd94f8e91be2fbc9@1747275 13f79535-47bb-0310-9956-ffa450edef68


package com.eatthepath.jvptree.util;

import com.eatthepath.jvptree.DistanceFunction;
import com.eatthepath.jvptree.IntegerDistanceFunction;
import org.junit.jupiter.api.Test;

import java.util.AbstractList;
import java.util.List;
import java.util.Random;

import static org.junit.jupiter.api.Assertions.*;

class SamplingMedianDistanceThresholdSelectionStrategyTest {

    private static class FakeGiganticList extends AbstractList<Integer> {

        @Override
        public Integer get(final int index) {
            if (index >= size() || index < 0) {
                throw new IndexOutOfBoundsException();
            }

            return index;
        }

        @Override
        public int size() {
            return 305574400;
        }
    }

    @Test
    void selectThreshold() {
        final SamplingMedianDistanceThresholdSelectionStrategy<Integer, Integer> strategy =
                new SamplingMedianDistanceThresholdSelectionStrategy<>();

        final List<Integer> points = new FakeGiganticList();

        assertDoesNotThrow(() -> strategy.selectThreshold(points, 17, (a, b) -> Math.abs(a - b)));
    }
}

Add a failing test to demonstrate an index-out-of-bounds issue.


package com.stratio.sdh.meta.structures;

public class BooleanProperty extends ValueProperty {

    private boolean bool;

    public BooleanProperty(boolean bool) {
        this.type = TYPE_BOOLEAN;
        this.bool = bool;
    }

    public boolean isBool() {
        return bool;
    }

    public void setBool(boolean bool) {
        this.bool = bool;
    }

    @Override
    public String toString() {
        return Boolean.toString(bool);
    }

}

Test for Miguel's sentences added

Test for Miguel's sentences added


/*
 * Licensed to Jasig under one or more contributor license
 * agreements. See the NOTICE file distributed with this work
 * for additional information regarding copyright ownership.
 * Jasig 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 the following location:
 *
 *   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.jasig.cas.adaptors.ldap.lppe.ad;

import javax.security.auth.login.AccountLockedException;
import javax.security.auth.login.LoginException;

import org.jasig.cas.authentication.AccountDisabledException;
import org.jasig.cas.authentication.AccountPasswordMustChangeException;
import org.jasig.cas.authentication.InvalidLoginLocationException;
import org.jasig.cas.authentication.InvalidLoginTimeException;
import org.junit.Test;

/**
 * Unit test for {@link org.jasig.cas.adaptors.ldap.lppe.ad.ActiveDirectoryAccountState}.
 *
 * @author Misagh Moayyed
 * @since 4.0
 */
public class ActiveDirectoryAccountStateTests {

    @Test(expected=InvalidLoginTimeException.class)
    public void testAccountStateLoginTime() throws LoginException {
        final ActiveDirectoryAccountState state = new ActiveDirectoryAccountState(
                org.ldaptive.auth.ext.ActiveDirectoryAccountState.Error.INVALID_LOGON_HOURS);
        state.getError().throwSecurityException();
    }

    @Test(expected=AccountDisabledException.class)
    public void testAccountStateDisabled() throws LoginException {
        final ActiveDirectoryAccountState state = new ActiveDirectoryAccountState(
                org.ldaptive.auth.ext.ActiveDirectoryAccountState.Error.ACCOUNT_DISABLED);
        state.getError().throwSecurityException();
    }

    @Test(expected=InvalidLoginLocationException.class)
    public void testAccountStateInvalidLocation() throws LoginException {
        final ActiveDirectoryAccountState state = new ActiveDirectoryAccountState(
                org.ldaptive.auth.ext.ActiveDirectoryAccountState.Error.INVALID_WORKSTATION);
        state.getError().throwSecurityException();
    }

    @Test(expected=AccountPasswordMustChangeException.class)
    public void testAccountStatePswMustChange() throws LoginException {
        final ActiveDirectoryAccountState state = new ActiveDirectoryAccountState(
                org.ldaptive.auth.ext.ActiveDirectoryAccountState.Error.PASSWORD_MUST_CHANGE);
        state.getError().throwSecurityException();
    }

    @Test(expected=AccountLockedException.class)
    public void testAccountStateNormalException() throws LoginException {
        final ActiveDirectoryAccountState state = new ActiveDirectoryAccountState(
                org.ldaptive.auth.ext.ActiveDirectoryAccountState.Error.ACCOUNT_LOCKED_OUT);
        state.getError().throwSecurityException();
    }
}

Test case for account state detection in AD


/**
 * Copyright (c) 2012 RedEngine Ltd, http://www.redengine.co.nz. All rights reserved.
 *
 * This program is licensed to you under the Apache License Version 2.0,
 * and you may not use this file except in compliance with the Apache License Version 2.0.
 * You may obtain a copy of the Apache License Version 2.0 at http://www.apache.org/licenses/LICENSE-2.0.
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the Apache License Version 2.0 is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the Apache License Version 2.0 for the specific language governing permissions and limitations there under.
 */
package net.stickycode.stereotype;

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

/**
 * This annotation stereotypes a class as being part of a domain and invariably being stateful and relating to the proessing
 * of a request. It will be scoped to a thread by the container.
 *
 *
Example

 * In this example SomeComponent will be instantiated in any classpath scanned from net.stickycode.example.component or above.
 *

 * package net.stickycode.example.component;
 *
 * @StickyDomain
 * public class SomeDomain {
 * }
 *

 */
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Inherited
@Documented
public @interface StickyDomain {

}

Add a domain annotation for stereotyping stateful beans that have a lifecycle related to requests


package de.fu_berlin.cdv.chasingpictures.api;

import android.content.Context;

import org.springframework.core.io.FileSystemResource;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.http.converter.FormHttpMessageConverter;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;

import java.io.File;

import de.fu_berlin.cdv.chasingpictures.R;

/**
 * API request for sending a new photo to the back end.
 *
 * @author Simon Kalt
 */
public class PhotoUploadRequest extends ApiRequest<Picture> {
    private final Place place;
    private final File picture;

    public PhotoUploadRequest(Context context, Place place, File picture) {
        super(context, R.string.api_path_upload);
        this.place = place;
        this.picture = picture;
    }

    @Override
    protected ResponseEntity<Picture> send() {
        // Add a form data message converter, before any others
        FormHttpMessageConverter formMessageConverter = new FormHttpMessageConverter();
        restTemplate.getMessageConverters().add(0, formMessageConverter);

        MultiValueMap<String, Object> formData = new LinkedMultiValueMap<>(2);

        // wrap the ID in a string, otherwise Spring won't be able to convert the value
        formData.set("place_id", String.valueOf(place.getId()));
        FileSystemResource resource = new FileSystemResource(picture);

        // Manually set the content type header for the file
        MultiValueMap<String, String> fileHeaders = new LinkedMultiValueMap<>();
        fileHeaders.set("Content-Type", MediaType.IMAGE_JPEG_VALUE);
        formData.set("file", new HttpEntity<>(resource, fileHeaders));

        return restTemplate.exchange(
                apiUri,
                HttpMethod.POST,
                new HttpEntity<>(formData, headers),
                Picture.class
        );
    }
}

Add API request for photo upload

Add API request for photo upload


package edu.iastate.cs.design.spec.analyze;

import org.eclipse.jdt.core.dom.MethodDeclaration;

import java.util.List;

public class ExceptionDocStructureAnalysis implements ExceptionDocProcessor{

    public void process(String exceptionType, String documentation, List<String> paramTypes, List<String> paramNames, MethodDeclaration methodNode) {

    }
}

Add class for finding common structures in throws comments


package net.restlesscoder.sandbox;

import java.util.List;
import java.util.Set;

import net.imglib2.type.NativeType;
import net.imglib2.type.numeric.RealType;

import org.scijava.Disposable;
import org.scijava.Prioritized;

/**
 * Demonstrates calling a method with type intersections via type variables.
 * Note that it does not work with recursive generics!
 */
public class TypeIntersections {

	public static <T extends Disposable & Prioritized> void simple(T t) {
		t.getPriority();
		t.dispose();
	}

	public static <E, T extends List<E> & Set<E>> void generic(T t) {
		t.get(0);
	}
	public static <T extends RealType<T> & NativeType<T>> void recursive(T t) {
		t.getRealDouble();
		t.getEntitiesPerPixel();
	}

	public static void nonGenericIntersection() {
		final Object o = new Object();
		// simple(o); // compile error
		// simple((Disposable) o); // compile error
		simple((Disposable & Prioritized) o); // works
	}

	public static <E, T extends List<E> & Set<E>> void genericIntersection() {
		final Object o = new Object();
		// generic(o); // compile error
		generic((List<E> & Set<E>) o); // compiler warning, but allowed
	}

	public static <T extends RealType<T> & NativeType<T>> void
		recursiveGenericIntersection()
	{
		final Object o = new Object();
		// recursive(o); // compile error
		// recursive((RealType<T> & NativeType<T>) o); // shockingly, an error!
	}
}

Add a demonstration of type intersections

And another peril of recursive generics.


package arez.integration.observed;

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

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

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

    @OnDepsChanged
    final void onRenderDepsChanged()
    {
      _depsChangedCallCount++;
    }

    @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 ObservedManualScheduleTest_Arez_TestComponent1();

    assertEquals( component._renderCallCount, 1 );
    assertEquals( component._depsChangedCallCount, 0 );

    // Scheduling should have no impact as not dirty
    Arez.context().safeAction( null, true, false, () -> component.getRenderObserver().schedule() );

    assertEquals( component._renderCallCount, 1 );
    assertEquals( component._depsChangedCallCount, 0 );

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

    assertEquals( component._renderCallCount, 1 );
    assertEquals( component._depsChangedCallCount, 1 );

    // Trigger a dependency change - but should not invoke onRenderDepsChanged as still dirty
    safeAction( () -> component.setValue( ValueUtil.randomLong() ) );

    assertEquals( component._renderCallCount, 1 );
    assertEquals( component._depsChangedCallCount, 1 );

    // Scheduling should actually run render!
    Arez.context().safeAction( null, true, false, () -> component.getRenderObserver().schedule() );

    assertEquals( component._renderCallCount, 2 );
    assertEquals( component._depsChangedCallCount, 1 );
  }
}

Add integration tests to ensure manual scheduling works as expected


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

package org.wildfly.security.evidence;

/**
 * A piece of evidence which supports multiple algorithms.
 *
 * @author David M. Lloyd
 */
public interface AlgorithmEvidence extends Evidence {
    /**
     * Get the algorithm name associated with this evidence (will never be {@code null}).
     *
     * @return the algorithm name
     */
    String getAlgorithm();
}

[ELY-365] Add support for algorithm-aware authentication evidence


package com.basho.riak.client.api;

import com.basho.riak.client.api.commands.kv.StoreValue;
import com.basho.riak.client.core.RiakCluster;
import com.basho.riak.client.core.RiakFuture;
import com.basho.riak.client.core.RiakNode;
import com.basho.riak.client.core.query.Location;
import com.basho.riak.client.core.query.Namespace;
import org.junit.Test;

import java.util.Random;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

import static org.junit.Assert.*;

public class ITestClusterLifecycle
{
    protected static RiakCluster cluster;
    protected static boolean testLifecycle;
    protected static String hostname;
    protected static int pbcPort;
    protected static Random random = new Random();

    public ITestClusterLifecycle()
    {
        testLifecycle = Boolean.getBoolean("com.basho.riak.lifecycle");
        hostname = System.getProperty("com.basho.riak.host", RiakNode.Builder.DEFAULT_REMOTE_ADDRESS);

        pbcPort = Integer.getInteger("com.basho.riak.pbcport", RiakNode.Builder.DEFAULT_REMOTE_PORT);

        RiakNode.Builder builder = new RiakNode.Builder()
                                               .withRemoteAddress(hostname)
                                               .withRemotePort(10017)
                                               .withMinConnections(1)
                                               .withMaxConnections(1);

        cluster = new RiakCluster.Builder(builder.build()).build();
    }

    @Test
    public void testManyCommandsOneConnection() throws InterruptedException, ExecutionException, TimeoutException
    {
        RiakClient client = null;
        try
        {
            client = new RiakClient(cluster);
            cluster.start();

            final Namespace namespace = new Namespace("plain", Integer.toString(random.nextInt()));

            for (int i = 0; i < 10000; i++)
            {
                createAndStoreObject(client, new Location(namespace, Integer.toString(i)));
            }

        }
        catch (Exception ex)
        {
            assertNull(ex);
        }
        finally
        {
            final Boolean shutdownClean = client.shutdown().get(3, TimeUnit.SECONDS);
            assertTrue(shutdownClean);
        }
    }

    private void createAndStoreObject(RiakClient client, Location location)
            throws ExecutionException, InterruptedException, TimeoutException
    {
        final StoreValue storeCmd = new StoreValue.Builder("value").withLocation(location).build();
        final RiakFuture<StoreValue.Response, Location> execute = client.executeAsync(storeCmd);
        final StoreValue.Response response = execute.get(1, TimeUnit.SECONDS);

        assertNotNull(response);
    }
}

Add simple cluster lifecycle test

Add simple cluster lifecycle test


package com.redhat.ceylon.compiler.js;

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

import junit.framework.Assert;

import org.junit.Test;

import com.redhat.ceylon.common.tool.ArgumentParserFactory;
import com.redhat.ceylon.common.tool.PluginFactory;
import com.redhat.ceylon.common.tool.PluginLoader;
import com.redhat.ceylon.common.tool.PluginModel;

public class CompileJsToolTest {

    protected final ArgumentParserFactory apf = new ArgumentParserFactory();
    protected final PluginFactory pluginFactory = new PluginFactory(apf);
    protected final PluginLoader pluginLoader = new PluginLoader(apf);

    private List<String> args(String... args) {
        return Arrays.asList(args);
    }

    @Test
    public void testLoad() {
        PluginModel<CompileJsTool> tool = pluginLoader.loadToolModel("compile-js");
        pluginFactory.bindArguments(tool, args());
    }

}

Add a test for the compile-js tool

Add a test for the compile-js tool


package cgeo.geocaching.test;

import cgeo.geocaching.cgeo;
import cgeo.geocaching.compatibility.Compatibility;

import android.test.ActivityInstrumentationTestCase2;

import junit.framework.Assert;

@SuppressWarnings("static-method")
public class CompatibilityTest extends ActivityInstrumentationTestCase2<cgeo> {

    private cgeo activity;

    public CompatibilityTest() {
        super("cgeo.geocaching", cgeo.class);
    }

    @Override
    protected void setUp() throws Exception {
        super.setUp();
        activity = getActivity();
    }

    public void testDataChanged() {
        // This should not raise an exception in any Android version
        Compatibility.dataChanged("cgeo.geocaching");
    }

    public void testGetDirectionNow() {
        final float angle = Compatibility.getDirectionNow(1.0f, activity);
        Assert.assertTrue(angle == 1.0f || angle == 91.0f || angle == 181.0f || angle == 271.0f);
    }

}

Add a new test for Compatibility package

This test should pass in any supported Android version.


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

import java.util.ArrayList;

/**
 *
 * @author Barry DeZonia
 *
 */
public class SamplingGeneral<U extends Duplicatable<U> & Dimensioned & Settable<U>>
	implements Sampling<U>
{
	private final int numD;
	private final ArrayList<U> points;

	public SamplingGeneral(int numD) {
		this.numD = numD;
		this.points = new ArrayList<U>();
	}

	public void add(U pt) {
		if (pt.numDimensions() != numDimensions())
			throw new IllegalArgumentException("mismatched dimensions in SamplingGeneral::add()");
		points.add(pt.duplicate());
	}

	@Override
	public int numDimensions() {
		return numD;
	}

	@Override
	public boolean contains(U samplePoint) {
		for (int i = 0; i < points.size(); i++) {
			if (points.get(i).equals(samplePoint))
				return true;
		}
		return false;
	}

	@Override
	public SamplingIterator<U> iterator() {
		return new Iterator();
	}

	private class Iterator implements SamplingIterator<U> {

		private final java.util.Iterator<U> iter = points.iterator();

		@Override
		public boolean hasNext() {
			return iter.hasNext();
		}

		@Override
		public void next(U value) {
			value.set(iter.next());
		}

	}

}

Add a general sampling for RealIndex or IntegerIndex sets


/*
 * Copyright 2015 Open Networking Laboratory
 *
 * 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.onosproject.net.behaviour;

import com.google.common.annotations.Beta;
import org.onosproject.net.PortNumber;
import org.onosproject.net.driver.HandlerBehaviour;

/**
 * A HandlerBehaviour to check the capability of MPLS.
 */
@Beta
public interface MplsQuery extends HandlerBehaviour {

    /**
     * Indicates if MPLS can be used at the port.

     * @param port port to be checked for the capability
     * @return true if MPLS can be used at the port, false otherwise.
     */
    boolean isEnabled(PortNumber port);
}

ONOS-2729: Define an interface to query about MPLS capability

Change-Id: I509720b0c9ee8a9b652aa966ec19c77aacac8573


package mansonheart.com.database;

import io.realm.RealmQuery;
import rx.functions.Func1;
import rx.subjects.BehaviorSubject;

/**
 * Created by Zherebtsov Alexandr on 02.01.2016.
 */
public class RealmQueryable {

    private Class clazz;
    private Func1<RealmQuery, RealmQuery> predicate;
    private BehaviorSubject subject;

    public RealmQueryable(Class clazz,
                          Func1<RealmQuery, RealmQuery> predicate,
                          BehaviorSubject subject) {
        this.clazz = clazz;
        this.predicate = predicate;
        this.subject = subject;
    }

    public Class getClazz() {
        return clazz;
    }

    public void setPredicate(Func1<RealmQuery, RealmQuery> predicate) {
        this.predicate = predicate;
    }

    public BehaviorSubject getSubject() {
        return subject;
    }

    public void setSubject(BehaviorSubject subject) {
        this.subject = subject;
    }

    public Func1<RealmQuery, RealmQuery> getPredicate() {
        return predicate;
    }
}

Add model for Realm get request

Add model for Realm get request


package leetcode.jump_game;

public class Solution {
    public boolean canJump(int[] A) {
        if(A == null || A.length == 0) return false;
        int right = 0, cur = 0;
        while(cur <= right && right < A.length - 1){
        	if(cur + A[cur] > right)
        		right = cur + A[cur];
        	cur++;
        }
        return right >= A.length - 1;
    }

    public static void main(String[] args){
    	System.err.println(new Solution().canJump(new int[]{1,1,1,2,0}));
    	System.err.println(new Solution().canJump(new int[]{3,2,1,0,4}));
    }
}

Add java solution for 55. Jump Game

Add java solution for 55. Jump Game

55. Jump Game: https://leetcode.com/problems/jump-game/


package leetcode.find_minimum_in_rotated_sorted_array_ii;

public class Solution {
    public int findMin(int[] num) {
    	int min = num[0];
    	for(int n : num){
    		if(n < min){
    			min = n;
    		}
    	}
    	return min;
    }
}

Add java solution for 154. Find Minimum in Rotated Sorted Array II

154. Find Minimum in Rotated Sorted Array II: https://leetcode.com/problems/find-minimum-in-rotated-sorted-array-ii/


/*
 * Copyright 2018 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.pdfbox.pdmodel.interactive.annotation;

import org.apache.pdfbox.pdmodel.interactive.annotation.handlers.PDHighlightAppearanceHandler;
import org.apache.pdfbox.cos.COSDictionary;
import org.apache.pdfbox.pdmodel.interactive.annotation.handlers.PDAppearanceHandler;

/**
 *
 * @author Paul King
 */
public class PDAnnotationHighlight extends PDAnnotationTextMarkup
{
    /**
     * The type of annotation.
     */
    public static final String SUB_TYPE = "Highlight";

    private PDAppearanceHandler appearanceHandler;

     /**
     * Constructor.
     */
    public PDAnnotationHighlight()
    {
        super(SUB_TYPE);
    }

    /**
     * Constructor.
     *
     * @param dict The annotations dictionary.
     */
    public PDAnnotationHighlight(COSDictionary dict)
    {
        super(dict);
    }

    /**
     * Set a custom appearance handler for generating the annotations appearance streams.
     *
     * @param appearanceHandler
     */
    public void setCustomHighlightAppearanceHandler(PDAppearanceHandler appearanceHandler)
    {
        this.appearanceHandler = appearanceHandler;
    }

    @Override
    public void constructAppearances()
    {
        if (appearanceHandler == null)
        {
            PDHighlightAppearanceHandler appearanceHandler = new PDHighlightAppearanceHandler(this);
            appearanceHandler.generateAppearanceStreams();
        }
        else
        {
            appearanceHandler.generateAppearanceStreams();
        }
    }
}

PDFBOX-4075: Split highlight, underline, strikeout and squiggly from text markup annotation

git-svn-id: c3ad59981690829a43dc34c293c4e2cd04bcd994@1821760 13f79535-47bb-0310-9956-ffa450edef68


package com.github.rnowling.bps.datagenerator.algorithms.samplers;

import static org.junit.Assert.assertThat;
import static org.junit.matchers.JUnitMatchers.*;

import java.util.Map;

import org.junit.Test;

import com.github.rnowling.bps.datagenerator.SeedFactory;
import com.google.common.collect.ImmutableMap;

public class TestRouletteWheelSampler
{

	@Test
	public void testSample()
	{
		Map<String, Double> dataPoints = ImmutableMap.of(
				"a", 0.25,
				"b", 0.25,
				"c", 0.25,
				"d", 0.25
				);

		SeedFactory seedFactory = new SeedFactory(1234);

		Sampler<String> sampler = new RouletteWheelSampler<String>(dataPoints, seedFactory);

		String result = sampler.sample();

		assertThat(dataPoints.keySet(), hasItem(result));
	}

	@Test
	public void testSampleUnnormalized()
	{
		Map<String, Double> dataPoints = ImmutableMap.of(
				"a", 1.0,
				"b", 1.0,
				"c", 1.0,
				"d", 1.0
				);

		SeedFactory seedFactory = new SeedFactory(1234);

		Sampler<String> sampler = new RouletteWheelSampler<String>(dataPoints, seedFactory);

		String result = sampler.sample();

		assertThat(dataPoints.keySet(), hasItem(result));
	}

}

Add unit test for RouletteWheelSampler

Add unit test for RouletteWheelSampler


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

import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
import junit.textui.TestRunner;

/**
 * Issue-specific test suite for Commons SCXML.
 *
 */
public class IssuesTestSuite extends TestCase {

    /**
     * Construct a new instance.
     */
    public IssuesTestSuite(String name) {
        super(name);
    }

    /**
     * Command-line interface.
     */
    public static void main(String[] args) {
        TestRunner.run(suite());
    }

    /**
     * Get the suite of tests
     */
    public static Test suite() {
        TestSuite suite = new TestSuite();
        suite.setName("Commons SCXML Issues Tests");
        return suite;
    }
}

Add the oacs.issues test package for adding tests specific to an issue (and its fix, if any).

git-svn-id: af8b92d546565e7258615209d6223c117422c4d5@608640 13f79535-47bb-0310-9956-ffa450edef68


// Create a thread by implementing Runnable.

class MyThread implements Runnable {
	int count;
	String thrdName;

	MyThread(String name) {
		count = 0;
		thrdName = name;
	}

	// Entry point of thread.
	public void run() {
		System.out.println(thrdName + " starting.");
		try {
			do {
				Thread.sleep(100);
				System.out.println("In " + thrdName + ", count is " + count);
				count++;
			} while(count < 10);
		}
		catch(InterruptedException exc) {
			System.out.println(thrdName + " interrupted.");
		}
		System.out.println(thrdName + " terminating.");
	}
}

class UseThreads {
	public static void main(String args[]) {
		System.out.println("Main thread starting.");

		// First, construct a MyThread object.
		MyThread mt = new MyThread("Child #1");

		// Next, construct a thread from that object.
		Thread newThrd = new Thread(mt);

		// Finally, start execution of the thread.
		newThrd.start();

		do {
			System.out.print(".");
			try {
				Thread.sleep(10);
			}
			catch(InterruptedException exc) {
				System.out.println("Main thread interrupted.");
			}
		} while (mt.count != 10);

		System.out.println("Main thread ending.");
	}
}

Create a thread by implementing Runnable

http://ideone.com/b8BVcF


/*******************************************************************************
 * Copyright (c) 1998, 2007 Oracle. All rights reserved.
 * This program and the accompanying materials are made available under the
 * terms of the Eclipse Public License v1.0, which accompanies this distribution
 * and is available at http://www.eclipse.org/legal/epl-v10.html.
 *
 * Contributors:
 *     Oracle - initial API and implementation from Oracle TopLink
 ******************************************************************************/
package org.eclipse.persistence.testing.sdo.helper.xmlhelper.threadsafety;

import junit.framework.Test;
import junit.framework.TestSuite;

public class SDOXMLHelperThreadSafetyTestSuite {

	public SDOXMLHelperThreadSafetyTestSuite() {
    }

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

    public static Test suite() {
        TestSuite suite = new TestSuite("All XMLHelper Thread Safety Tests");

        suite.addTest(new TestSuite(SDOXMLHelperThreadSafetyTestCases.class));

        return suite;
    }

}

Test suite for thread safety tests

Test suite for thread safety tests

Former-commit-id: 414f8d96ad8c8cce3179cbe4ccb5b8c8b79c90bd


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

import org.junit.Test;

public class ReportTestITCase extends AbstractTest {

    @Test
    public void readReportlet() {
        selenium.click("css=img[alt=\"Reports\"]");
        selenium.waitForCondition("selenium.isElementPresent(\"//div[@id='tabs']\");", "30000");

        selenium.click("//table/tbody/tr/td[6]/span/span[7]/a");
        selenium.waitForCondition("selenium.isElementPresent("
                + "\"//form/div[2]/div/div/span/div/div[5]/div[2]/span/div[2]/div/a\");", "30000");

        selenium.click("css=img[alt=\"plus icon\"]");
        selenium.waitForCondition("selenium.isElementPresent("
                + "\"//form/div[2]/div/div/div[2]/div[2]/span/select\");", "30000");

        selenium.select("//form/div[2]/div/div/div[2]/div[2]/span/select",
                "label=org.syncope.client.report.UserReportletConf");
        selenium.waitForCondition("selenium.isElementPresent(\"//form/div[2]/div[2]/div/span/div/div/span\")", "30000");

        selenium.click("css=a.w_close");
        selenium.click("css=a.w_close");
    }

    @Test
    public void execute() {
        selenium.click("css=img[alt=\"Reports\"]");

        selenium.waitForCondition("selenium.isElementPresent(\"//div[@id='tabs']\");", "30000");

        selenium.click("//table/tbody/tr/td[6]/span/span[3]/a");

        selenium.waitForCondition("selenium.isTextPresent(\"Operation executed successfully\");", "30000");
    }
}

Test cases added to selenium profile

[SYNCOPE-6] Test cases added to selenium profile

git-svn-id: 51e9c0635e05060c2a7639df764e0b3ebb09013f@1298457 13f79535-47bb-0310-9956-ffa450edef68


package com.royalrangers.controller;

import com.royalrangers.security.JwtUser;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/user")
public class UserDetailController {

    @RequestMapping(method = RequestMethod.GET)
    @PreAuthorize("isAuthenticated()")
    public @ResponseBody JwtUser getUser() {

        JwtUser user = (JwtUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        return user;
    }
}

Add service that returns information about the user (for testing)


/*
 * See the NOTICE file distributed with this work for additional
 * information regarding copyright ownership.
 *
 * This is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License as
 * published by the Free Software Foundation; either version 2.1 of
 * the License, or (at your option) any later version.
 *
 * This software is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this software; if not, write to the Free
 * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
 * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
 */
package org.xwiki.extension.xar.internal.handler.packager.xml;

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

import org.xml.sax.Attributes;
import org.xml.sax.ContentHandler;
import org.xml.sax.SAXException;
import org.xwiki.component.manager.ComponentManager;

/**
 *
 * @version $Id$
 * @since 4.0M1
 */
public class RootHandler extends AbstractHandler
{
    private Map<String, ContentHandler> handlers = new HashMap<String, ContentHandler>();

    public RootHandler(ComponentManager componentManager)
    {
        super(componentManager, null);
    }

    public void setHandler(String element, ContentHandler handler)
    {
        this.handlers.put(element, handler);
    }

    @Override
    protected void startHandlerElement(String uri, String localName, String qName, Attributes attributes)
        throws SAXException
    {
        ContentHandler handler = this.handlers.get(qName);

        if (handler != null) {
            setCurrentHandler(handler);
        } else {
            throw new UnknownRootElement(qName);
        }
    }
}

Put back class removed by mistake

Put back class removed by mistake


package org.slc.sli.api.security.context;

import org.slc.sli.api.config.EntityDefinitionStore;
import org.slc.sli.api.config.EntityNames;
import org.slc.sli.domain.Entity;
import org.slc.sli.domain.EntityRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

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

/**
 * TeacherAttendanceContextResolver
 * Determine security authorization.
 * Finds the Attendance records a user has context to access.
 */
@Component
public class SectionSessionContextResolver implements EntityContextResolver {

    @Autowired
    private EntityRepository repository;
    @Autowired
    private EntityDefinitionStore definitionStore;

    @Override
    public String getSourceType() {
        return EntityNames.SECTION;
    }

    @Override
    public String getTargetType() {
        return EntityNames.SESSION;
    }

    @Override
    public List<String> findAccessible(Entity principal) {
        return Arrays.asList((String) principal.getBody().get("sessionId"));
    }

    public void setRepository(EntityRepository repository) {
        this.repository = repository;
    }

    public void setDefinitionStore(EntityDefinitionStore definitionStore) {
        this.definitionStore = definitionStore;
    }
}

Add security context resolver for section-session direct reference.


package cec.service;

import java.util.UUID;

import cec.model.FolderFactory;
import cec.model.Rule;
import cec.model.RuleBuilder;
import cec.model.RuleSet;
import cec.model.RuleSetFactory;

import cec.view.RuleViewEntity;

public class RuleService {
	private RuleSet ruleSet;

	public RuleService() {
		ruleSet = RuleSetFactory.getRuleSetInstance();
	}

	public void save(RuleViewEntity ruleViewEntity) {
		Rule rule = (new RuleBuilder())
				.withId(UUID.randomUUID())
				.withRank(ruleSet.getNextRank())
				.withEmailAddresses(ruleViewEntity.getEmailAddresses())
				.withWords(ruleViewEntity.getWords())
				.withTargetFolder(FolderFactory.getFolder(ruleViewEntity.getFolderPath()))
				.withIsActive(true)
				.build();

		rule.save();  // should this call the ruleset?
	}

	public void delete(RuleViewEntity ruleViewEntity) {
		Rule rule = (new RuleBuilder())
				.withId(UUID.fromString(ruleViewEntity.getID()))
				.build();
		rule.delete();
	}
}

Add the Save and Delete methods to the Rule Service


/**
*Question Description:
*
*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.
*
**/

/**
*My Solution:(Java)
**/

/**
 * Definition for singly-linked list with a random pointer.
 * class RandomListNode {
 *     int label;
 *     RandomListNode next, random;
 *     RandomListNode(int x) { this.label = x; }
 * };
 */
public class Solution {
    public RandomListNode copyRandomList(RandomListNode head) {

        if(head==null)
          return head;

        RandomListNode cHead = new RandomListNode(head.label);
        HashMap<RandomListNode,RandomListNode> map = new HashMap<RandomListNode,RandomListNode>();
        map.put(head,cHead);

        RandomListNode cNode = cHead;
        RandomListNode pNode = head.next;
        while(pNode !=null)
        {
            RandomListNode tempNode = new RandomListNode(pNode.label);
            map.put(pNode,tempNode);
            cNode.next = tempNode;
            cNode = tempNode;
            pNode = pNode.next;

        }

        cNode = cHead;
        pNode = head;
        while(pNode !=null)
        {
            cNode.random = map.get(pNode.random);
            cNode = cNode.next;
            pNode = pNode.next;
        }

        return cHead;

}
}

Copy List With Random Pointer

Copy List With Random Pointer


package org.jctools.sets;

import org.openjdk.jcstress.annotations.Actor;
import org.openjdk.jcstress.annotations.JCStressTest;
import org.openjdk.jcstress.annotations.Outcome;
import org.openjdk.jcstress.annotations.State;
import org.openjdk.jcstress.infra.results.BooleanResult1;

import static org.openjdk.jcstress.annotations.Expect.ACCEPTABLE;
import static org.openjdk.jcstress.annotations.Expect.FORBIDDEN;

/**
 * @author Tolstopyatov Vsevolod
 * @since 23/04/17
 */
@JCStressTest
@Outcome(id = "true", expect = ACCEPTABLE, desc = "Ok")
@Outcome(expect = FORBIDDEN, desc = "Removal considered harmful")
@State
public class SingleWriterHashSetRemovalTest {

    private final SingleWriterHashSet<Integer> set = new SingleWriterHashSet<>(16);

    public SingleWriterHashSetRemovalTest() {
        // Collide elements so removal of 1 will shift 17
        set.add(1);
        set.add(17);
    }

    @Actor
    public void actor1() {
        set.remove(1);
    }

    @Actor
    public void actor2(BooleanResult1 result) {
        result.r1 = set.contains(17);
    }
}

Add jcstress test which reveals issue with compacting during removal from SingleWriterHashSet


package leetcode;

/**
 * https://leetcode.com/problems/find-minimum-in-rotated-sorted-array/
 */
public class Problem153 {
    public int findMin(int[] nums) {
        int min = nums[0];
        for (int n : nums) {
            if (n < min) {
                min = Math.min(n, min);
            }
        }
        return min;
    }
}

Solve problem 153 (it's not log N yet)

Solve problem 153 (it's not log N yet)


package leetcode;

/**
 * https://leetcode.com/problems/number-of-islands/
 */
public class Problem200 {
    public int numIslands(char[][] grid) {
        return 0;
    }

    public static void main(String[] args) {
        Problem200 prob = new Problem200();

    }
}

Add a skeleton for problem 200

Add a skeleton for problem 200


/*
 * Copyright 2009-2013 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.jdal.vaadin.ui.bind;

import org.jdal.ui.bind.AbstractControlAccessor;

import com.vaadin.ui.TextField;

/**
 * Control accessor for Vaadin TextField.
 *
 * @author Jose Luis Martin
 * @since 2.0
 */
public class TextFieldAccessor extends AbstractControlAccessor {

	/**
	 * @param control
	 */
	public TextFieldAccessor(Object control) {
		super(control);
	}

	/**
	 * {@inheritDoc}
	 */
	public Object getControlValue() {
		return getControl().getValue();
	}

	/**
	 * {@inheritDoc}
	 */
	public void setControlValue(Object value) {
		getControl().setValue(value.toString());

	}

	@Override
	public TextField getControl() {
		return (TextField) super.getControl();
	}

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

Add ControlAccessor for vaadin TextField


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

import org.powermock.reflect.Whitebox;

import tachyon.master.block.BlockMaster;

/**
 * Class which provides access to private state of {@link TachyonMaster}.
 */
public final class TachyonMasterPrivateAccess {
  public static BlockMaster getBlockMaster(TachyonMaster master) {
    return Whitebox.getInternalState(master, "mBlockMaster");
  }
}

Add private access for TachyonMaster

Add private access for TachyonMaster


package dr.evomodelxml.tree;

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

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

    public static final String TREE_HEIGHT_STATISTIC = "treeHeightStatistic";

        public String getParserName() {
            return TREE_HEIGHT_STATISTIC;
        }

        public Object parseXMLObject(XMLObject xo) throws XMLParseException {

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

            return new TreeHeightStatistic(name, tree);
        }

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

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

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

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

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

Make tree height statistic available

Make tree height statistic available


package co.uk.jiveelection.campaign;

/**
 * Configuration for the Twitter Jive Bots.
 *
 * Placeholder in SCM, this file needs to be correctly filled out prior to launch.
 */
public class TwitConfigPlaceholder {
    // Add your applications tokens here
    public static final String CONSUMER_TOKEN = "";
    public static final String CONSUMER_TOKEN_SECRET = "";

    // Update this pair for each of your Jive Bots
    public static final String JIVEBOT_ACCESS_TOKEN = "";
    public static final String JIVEBOT_ACCESS_TOKEN_SECRET = "";
}

Add an alternate placeholder file to the repo


/*
 * Copyright (c) 2015 Ushahidi Inc
 *
 * 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 in the file LICENSE-AGPL. If not, see
 *  https://www.gnu.org/licenses/agpl-3.0.html
 */

package com.ushahidi.android.data.api.model;

import com.google.gson.annotations.SerializedName;

import com.ushahidi.android.data.entity.TagEntity;

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

/**
 * @author Ushahidi Team <team@ushahidi.com>
 */
public class Tags extends Response implements Serializable {

    private static final long serialVersionUID = 4889644823525958176L;

    @SerializedName("results")
    private List<TagEntity> tags;

    public List<TagEntity> getTags() {
        return tags;
    }

    @Override
    public String toString() {
        return "Tags{" +
                "response=" + super.toString() +
                "tags=" + tags +
                '}';
    }
}

Add tags model for retrofit

Add tags model for retrofit


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

import nom.bdezonia.zorbage.algebra.Addition;
import nom.bdezonia.zorbage.algebra.Algebra;
import nom.bdezonia.zorbage.algebra.Invertible;
import nom.bdezonia.zorbage.algebra.Multiplication;
import nom.bdezonia.zorbage.algebra.NaN;
import nom.bdezonia.zorbage.datasource.IndexedDataSource;

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

	// https://en.wikipedia.org/wiki/Contraharmonic_mean

	/**
	 *
	 * @param alg
	 * @param list
	 * @param result
	 */
	public static <T extends Algebra<T,U> & Addition<U> & Multiplication<U> & Invertible<U> & NaN<U>, U>
		void compute(T alg, IndexedDataSource<U> list, U result)
	{
		long sz = list.size();
		if (sz == 0) {
			alg.nan().call(result);
			return;
		}
		U value = alg.construct();
		U numerSum = alg.construct();
		U denomSum = alg.construct();

		for (long i = 0; i < list.size(); i++) {
			list.get(i, value);
			alg.add().call(denomSum, value, denomSum);
			alg.multiply().call(value,value,value);
			alg.add().call(numerSum, value, numerSum);
		}

		alg.divide().call(numerSum, denomSum, result);
	}
}

Define a contraharmonic mean algorithm

Define a contraharmonic mean algorithm


package org.opendaylight.ovsdb.openstack.netvirt.impl;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.mockito.Matchers.anyString;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

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

import org.junit.Before;
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.INeutronPortCRUD;
import org.opendaylight.neutron.spi.NeutronPort;
import org.opendaylight.neutron.spi.NeutronSecurityGroup;
import org.opendaylight.ovsdb.lib.notation.Column;
import org.opendaylight.ovsdb.lib.schema.GenericTableSchema;
import org.opendaylight.ovsdb.openstack.netvirt.api.Constants;
import org.opendaylight.ovsdb.schema.openvswitch.Interface;

/**
 * Unit test for class SecurityServicesImpl
 */
@RunWith(MockitoJUnitRunner.class)
public class SecurityServicesImplTest {

    @Mock private Interface intf;
    @Mock private NeutronPort neutronPort;

    @InjectMocks private SecurityServicesImpl securityServicesImpl;
    @InjectMocks private INeutronPortCRUD neutronPortCache = mock(INeutronPortCRUD.class);

    private List<NeutronSecurityGroup> securityGroups = new ArrayList<NeutronSecurityGroup>();

    @Before
    public void setUp(){
        Map<String, String> externalIds =new HashMap<String, String>();
        externalIds.put(Constants.EXTERNAL_ID_INTERFACE_ID, "mapValue");
        Column<GenericTableSchema, Map<String, String>> columnMock = mock(Column.class);

        securityGroups.add(mock(NeutronSecurityGroup.class));

        // configure interface
        when(intf.getExternalIdsColumn()).thenReturn(columnMock);
        when(columnMock.getData()).thenReturn(externalIds);

        // configure neutronPort
        when(neutronPort.getSecurityGroups()).thenReturn(securityGroups);
        when(neutronPortCache.getPort(anyString())).thenReturn(neutronPort);
    }

    /**
     * Test method {@link SecurityServicesImpl#isPortSecurityReady(Interface)}
     */
    @Test
    public void testIsPortSecurityReady(){
        // configure neutronPort
        when(neutronPort.getDeviceOwner()).thenReturn("deviceOwner");

        //test
        assertTrue("Error, did not return expected boolean for isPortSecurityReady", securityServicesImpl.isPortSecurityReady(intf));
    }

    /**
     * Test method {@link SecurityServicesImpl#getSecurityGroupInPort(Interface)}
     */
    @Test
    public void testSecurityGroupInPort(){
        // test
        assertEquals("Error, did not return the good neutronSecurityGroup of securityGroups", securityGroups.toArray()[0], securityServicesImpl.getSecurityGroupInPort(intf));
    }
}

Add JUnit testing for SecurityServicesImpl class.

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


package com.peterphi.std.guice.web.rest.jaxrs.exception;

import com.google.inject.Inject;
import com.google.inject.Singleton;
import com.google.inject.name.Named;
import com.peterphi.std.guice.restclient.jaxb.RestFailure;
import com.peterphi.std.guice.web.HttpCallContext;
import com.peterphi.std.guice.web.rest.templating.TemplateCall;
import com.peterphi.std.guice.web.rest.templating.Templater;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;

import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.util.Enumeration;

/**
 * A RestFailureRenderer that uses the configured templating engine to render exceptions destined for humans.
 */
@Singleton
public class CustomTemplateFailureRenderer implements RestFailureRenderer
{
	private static final Logger log = Logger.getLogger(CustomTemplateFailureRenderer.class);
	@Inject
	Templater templater;

	@Inject
	@Named("exception-templater.template")
	String templateName;

	/**
	 * If true, a custom template of "{templateName}_{exceptionSimpleName} will be attempted first
	 */
	@Inject
	@Named("exception-templater.tryCustomised")
	boolean tryCustomised = true;

	@Override
	public Response render(final RestFailure failure)
	{
		if (shouldRender(HttpCallContext.peek()))
		{
			// If we should first try customised exceptions...
			if (tryCustomised)
			{
				try
				{
					final String customTemplateName = templateName + "_" + failure.exception.shortName;

					return render(failure, customTemplateName);
				}
				catch (Exception e)
				{
					log.trace("Error rendering custom failure for " +
					          failure.exception.shortName +
					          ", fall back on general handler", e);
				}
			}

			return render(failure, templateName);
		}
		else
		{
			return null;
		}
	}

	private boolean shouldRender(final HttpCallContext ctx)
	{
		if (ctx == null)
			return false; // Don't run if we can't figure out the HTTP context

		Enumeration<String> enumeration = (Enumeration<String>) ctx.getRequest().getHeaders("Accept");

		while (enumeration.hasMoreElements())
		{
			final String header = enumeration.nextElement();

			if (StringUtils.startsWithIgnoreCase(header, "text/html"))
				return true;
		}

		// Nobody wanted text/html
		return false;
	}

	private Response render(final RestFailure failure, String template)
	{
		final TemplateCall call = templater.template(template);

		call.set("failure", failure);
		call.set("ctx", HttpCallContext.peek());

		return call.process(Response.status(failure.httpCode).type(MediaType.TEXT_HTML_TYPE));
	}
}

Add custom template failure renderer

Add custom template failure renderer


package com.yuzhouwan.hacker.algorithms.thread.sync;

import org.junit.Test;

/**
 * Copyright @ 2017 yuzhouwan.com
 * All right reserved.
 * Function：String Buffer Test
 *
 * @author Benedict Jin
 * @since 2017/9/28
 */
public class StringBufferTest {

    public static void strBufferWithoutSync() {
        StringBuffer buffer = new StringBuffer();
        for (int i = 0; i < 9999999; i++) {
            buffer.append(i);
            buffer.delete(0, buffer.length() - 1);
        }
    }

    public static void strBufferWithSync() {
        StringBuffer buffer = new StringBuffer();
        synchronized (buffer) {
            for (int i = 0; i < 9999999; i++) {
                buffer.append(i);
                buffer.delete(0, buffer.length() - 1);
            }
        }
    }

    public static void strBuilderWithSync() {
        StringBuilder buffer = new StringBuilder();
        synchronized (buffer) {
            for (int i = 0; i < 9999999; i++) {
                buffer.append(i);
                buffer.delete(0, buffer.length() - 1);
            }
        }
    }

    /*
     * 1.8.0_111
     * StringBuffer without sync: 244
     * StringBuffer with sync:    236
     * StringBuilder with sync:   236
     */
    @Test
    public void test() {
        System.out.println(System.getProperty("java.version"));
        // warm up for jit
        for (int i = 0; i < 10; i++) {
            strBufferWithoutSync();
            strBufferWithSync();
            strBuilderWithSync();
        }

        long start = System.currentTimeMillis();
        strBufferWithoutSync();
        long end = System.currentTimeMillis();
        long time = end - start;
        System.out.println("StringBuffer without sync: " + time);

        start = System.currentTimeMillis();
        strBufferWithSync();
        end = System.currentTimeMillis();
        time = end - start;
        System.out.println("StringBuffer with sync: " + time);

        start = System.currentTimeMillis();
        strBuilderWithSync();
        end = System.currentTimeMillis();
        time = end - start;
        System.out.println("StringBuilder with sync: " + time);
    }
}

Add stringbuffer with sync test

Add stringbuffer with sync test