/*******************************************************************************
 * Copyright (c) 2005-2008 VecTrace (Zingo Andersen) and others.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 * Bastian Doetsch	implementation
 *******************************************************************************/
package com.vectrace.MercurialEclipse.synchronize;

import org.eclipse.core.resources.IStorage;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.team.core.TeamException;
import org.eclipse.team.core.variants.IResourceVariant;

import com.vectrace.MercurialEclipse.team.IStorageMercurialRevision;

public class MercurialResourceVariant implements IResourceVariant {
	private IStorageMercurialRevision rev;

	public MercurialResourceVariant(IStorageMercurialRevision rev) {
		this.rev = rev;
	}

	public byte[] asBytes() {
		return getContentIdentifier().getBytes();
	}

	public String getContentIdentifier() {
		return rev.getGlobal();
	}

	public String getName() {
		return rev.getName();
	}

	public IStorage getStorage(IProgressMonitor monitor) throws TeamException {
		return rev;
	}

	public boolean isContainer() {
		return false;
	}

    /**
     * @return the rev
     */
    public IStorageMercurialRevision getRev() {
        return rev;
    }

}

/*******************************************************************************
 * Copyright (c) 2005-2008 VecTrace (Zingo Andersen) and others.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 * Bastian Doetsch	implementation
 *******************************************************************************/
package com.vectrace.MercurialEclipse.synchronize;

import org.eclipse.core.resources.IStorage;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.team.core.TeamException;
import org.eclipse.team.core.variants.IResourceVariant;

import com.vectrace.MercurialEclipse.team.IStorageMercurialRevision;

public class MercurialResourceVariant implements IResourceVariant {
    private final IStorageMercurialRevision rev;

    public MercurialResourceVariant(IStorageMercurialRevision rev) {
        this.rev = rev;
    }

    public byte[] asBytes() {
        return getContentIdentifier().getBytes();
    }

    public String getContentIdentifier() {
        return rev.getGlobal();
    }

    public String getName() {
        return rev.getResource().getName();
    }

    public IStorage getStorage(IProgressMonitor monitor) throws TeamException {
        return rev;
    }

    public boolean isContainer() {
        return false;
    }

    /**
     * @return the rev
     */
    public IStorageMercurialRevision getRev() {
        return rev;
    }

}

Enable right content types (based on file types) in compare editor opened from Synchronization view


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

/**
 * Can you write a method to print a hello world without use a semicolon?.
 *
 * @author Pedro Vicente Gómez Sánchez.
 */
public class HelloWorldWithoutSemicolon {

}

Add statement to problem 77

Add statement to problem 77


import static com.google.appengine.api.datastore.FetchOptions.Builder.withLimit;
import static org.junit.Assert.assertEquals;
import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.EntityNotFoundException;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.appengine.api.datastore.Query;
import com.google.appengine.tools.development.testing.LocalDatastoreServiceTestConfig;
import com.google.appengine.tools.development.testing.LocalServiceTestHelper;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

public class DataServletTests {

  // Maximum eventual consistency.
  private final LocalServiceTestHelper helper =
      new LocalServiceTestHelper(new LocalDatastoreServiceTestConfig()
          .setDefaultHighRepJobPolicyUnappliedJobPercentage(100));

    @Before
    public void setUp() {
        helper.setUp();
    }

    @After
    public void tearDown() {
        helper.tearDown();
    }

    @Test
    public void EntitiesArePutInDatastore(){
        DatastoreService ds = DatastoreServiceFactory.getDatastoreService();
        Entity dummy = new Entity("Dummy");
        ds.put(dummy);
        assertEquals(1, ds.prepare(new Query("Dummy")).countEntities(withLimit(10)));
  }

    @Test
    public void EntitiesCanHaveParentsUsingKeys(){
        DatastoreService ds = DatastoreServiceFactory.getDatastoreService();
        Entity dummyParent = new Entity("DummyParent");
        ds.put(dummyParent);
        Key dummyParentKey = dummyParent.getKey();
        Entity dummy = new Entity("Dummy", dummyParentKey);
        ds.put(dummy);
        Key queriedDummyParentKey = dummy.getParent();
        Entity queriedDummyParent;
        try {
            queriedDummyParent = ds.get(queriedDummyParentKey);
        } catch(EntityNotFoundException e){
            fail("Entity not found in Database")
        }
        assertEquals(true, queriedDummyParent == dummyParent);
    }

    @Test
    public void EntityPropertiesArePutInDatastore(){
        DatastoreService ds = DatastoreServiceFactory.getDatastoreService();
        dummyString = "Bananas";
        Entity dummy = new Entity("Dummy");
        dummy.setProperty("Fruit", dummyString);
        ds.put(dummy);
        Key dummyKey = dummy.getKey();
        Entity queriedDummy;
        try {
            queriedDummy = ds.get(dummyKey);
        } catch(EntityNotFoundException e){
            fail("Entity not found in Database")
        }
        assertEquals(true, queriedDummy.getProperty("Fruit").toString().equals(dummyString));
    }
}

Add basic unit tests for datastore

Add basic unit tests for datastore


package org.realityforge.replicant.client.transport;

import javax.annotation.Nonnull;
import javax.annotation.Nullable;

final class AreaOfInterestAction<T extends Enum>
{
  enum Action
  {
    ADD, REMOVE, UPDATE
  }

  @Nonnull
  private final T _graph;
  @Nonnull
  private final Action _action;
  @Nullable
  private final String _cacheKey;
  @Nullable
  private final Object _id;
  @Nullable
  private final Object _filterParameter;
  @Nullable
  private final Runnable _userAction;
  private boolean _inProgress;

  AreaOfInterestAction( @Nonnull final T graph,
                        @Nonnull final Action action,
                        @Nullable final String cacheKey,
                        @Nullable final Object id,
                        @Nullable final Object filterParameter,
                        @Nullable final Runnable userAction )
  {
    _graph = graph;
    _action = action;
    _cacheKey = cacheKey;
    _id = id;
    _filterParameter = filterParameter;
    _userAction = userAction;
  }

  @Nonnull
  T getGraph()
  {
    return _graph;
  }

  @Nonnull
  Action getAction()
  {
    return _action;
  }

  @Nullable
  String getCacheKey()
  {
    return _cacheKey;
  }

  @Nullable
  Object getId()
  {
    return _id;
  }

  @Nullable
  Object getFilterParameter()
  {
    return _filterParameter;
  }

  @Nullable
  Runnable getUserAction()
  {
    return _userAction;
  }

  boolean isInProgress()
  {
    return _inProgress;
  }

  void markAsInProgress()
  {
    _inProgress = true;
  }

  void markAsComplete()
  {
    _inProgress = false;
  }

  @Override
  public String toString()
  {
    return "AOI[" +
           "Graph=" + _graph +
           ",id=" + _id +
           ",CacheKey=" + _cacheKey +
           ",filter=" + _filterParameter +
           "]" + ( _inProgress ? "(InProgress)" : "" );
  }
}

Add a simple class to contian information pertaining to subscription actions


/*
 * Copyright (c) 2009 Kathryn Huxtable and Kenneth Orr.
 *
 * This file is part of the SeaGlass Pluggable Look and Feel.
 *
 * 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.
 *
 * $Id$
 */
package com.seaglasslookandfeel.state;

import java.awt.Component;
import java.awt.Container;

import javax.swing.JComponent;
import javax.swing.JToolBar;

/**
 * Is the control in a toolbar?
 */
public class ControlInToolBarState extends State {
    public ControlInToolBarState() {
        super("InToolBar");
    }

    public boolean isInState(JComponent c) {
        for (Component comp = (Component) c; comp != null; comp = ((Container) comp).getParent()) {
            if (comp instanceof JToolBar) {
                return true;
            } else if (!(comp instanceof Container)) {
                break;
            }
        }
        return false;
    }
}

Check in state to determine if a control is in a toolbar.


package gjb.experimental;

import com.qualcomm.robotcore.eventloop.opmode.Autonomous;
import com.qualcomm.robotcore.eventloop.opmode.LinearOpMode;

import gjb.interfaces.RuntimeSupportInterface;
import gjb.utils.AndroidRuntimeSupport;

/**
 * New version of auton code - with most of the logic moved to helper class
 * AutonWizard
  */

@Autonomous(name="AOpMode_DepotMoveTestTensorFlow", group="Pushbot")
//@Disabled
public class AOpMode_MoveTestTensorFlow extends LinearOpMode {

    /* Declare OpMode members. */

    private final RuntimeSupportInterface rt = new AndroidRuntimeSupport(this);

    AutonRoverRuckusWizard apu = null;

    @Override
    public void runOpMode() {
        double timeoutS;

        apu = new AutonRoverRuckusWizard(rt) ;
        apu.init();

        // Wait for the game to start (driver presses PLAY)
        waitForStart();
        //TODO: apu.tensorVuforiaInit();

        // Work the wand, detect jewel color and move forward/backward to dislodge
        // the jewel - this is code specific to the BLUE alliance
        apu.firstPath();
    }

}

Joseph: Update the obsolete Vison sub system to initialize tensor flow.


package net.explorviz.landscape.repository.persistence;

import net.explorviz.landscape.model.application.AggregatedClazzCommunication;
import net.explorviz.landscape.model.application.Application;
import net.explorviz.landscape.model.application.ApplicationCommunication;
import net.explorviz.landscape.model.application.Clazz;
import net.explorviz.landscape.model.application.ClazzCommunication;
import net.explorviz.landscape.model.application.Component;
import net.explorviz.landscape.model.application.DatabaseQuery;
import net.explorviz.landscape.model.application.TraceStep;
import net.explorviz.landscape.model.helper.EProgrammingLanguage;
import net.explorviz.landscape.model.landscape.Landscape;
import net.explorviz.landscape.model.landscape.Node;
import net.explorviz.landscape.model.landscape.NodeGroup;
import net.explorviz.landscape.model.landscape.System;
import org.nustaq.serialization.FSTConfiguration;

/**
 * Helper class for FST.
 *
 *
 */
public class FstHelper {

  /**
   * Creates a new {@link FSTConfiguration} and registers all available model classes.
   *
   * @return the configuration.
   */
  public static FSTConfiguration createFstConfiguration() {
    final FSTConfiguration result = FSTConfiguration.createDefaultConfiguration();
    result.registerClass(Landscape.class);
    result.registerClass(System.class);
    result.registerClass(NodeGroup.class);
    result.registerClass(Node.class);
    result.registerClass(Application.class);
    result.registerClass(ApplicationCommunication.class);
    result.registerClass(AggregatedClazzCommunication.class);
    result.registerClass(DatabaseQuery.class);
    result.registerClass(EProgrammingLanguage.class);
    result.registerClass(Component.class);
    result.registerClass(Clazz.class);
    result.registerClass(ClazzCommunication.class);
    result.registerClass(TraceStep.class);

    return result;
  }

  /**
   * Converts a landscape object to bytes.
   *
   * @param landscape the landscape object
   *
   * @return the given landscape as byte array
   */
  public static byte[] convertLandscapeToBytes(final Landscape landscape,
      final FSTConfiguration conf) {
    // TODO: Move to "ExportHelper"
    return conf.asByteArray(landscape);
  }

}

Create helper class for basic FST operations


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

import java.io.IOException;
import java.io.OutputStream;

/**
 * Define how to dispatch an object.
 *
 * @author Tony Wardell
 * Date: 27/09/2017
 * Time: 14:19
 * Created with IntelliJ IDEA.
 */
public interface DispatchWriter {

    void write(Object object, OutputStream out) throws IOException;
}

Define how to dispatch an object.

Define how to dispatch an object.


/**
 * This Source Code Form is subject to the terms of the Mozilla Public License,
 * v. 2.0. If a copy of the MPL was not distributed with this file, You can
 * obtain one at http://mozilla.org/MPL/2.0/. OpenMRS is also distributed under
 * the terms of the Healthcare Disclaimer located at http://openmrs.org/license.
 *
 * Copyright (C) OpenMRS Inc. OpenMRS is a registered trademark and the OpenMRS
 * graphic logo is a trademark of OpenMRS Inc.
 */
package org.openmrs.customdatatype.datatype;

import org.apache.commons.lang.StringUtils;
import org.openmrs.Provider;
import org.openmrs.api.context.Context;

/**
 * This is a class for custom datatypes for providers
 *
 * @since 2.0
 */
public class ProviderDatatype extends BaseMetadataDatatype<Provider> {

	/**
	 * @see org.openmrs.customdatatype.SerializingCustomDatatype#deserialize(String)
	 * @override
	 */
	public Provider deserialize(String uuid) {
		if (StringUtils.isBlank(uuid)) {
			return null;
		}
		return Context.getProviderService().getProviderByUuid(uuid);
	}
}

Create a custom data type and its associated handler for providers - TRUNK-3623


package es.litesolutions.sonar.grappa;

import com.sonar.sslr.api.Grammar;
import com.sonar.sslr.impl.Parser;
import org.sonar.colorizer.Tokenizer;
import org.sonar.sslr.toolkit.AbstractConfigurationModel;
import org.sonar.sslr.toolkit.ConfigurationProperty;

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

public final class SampleToolkit
{
    private SampleToolkit()
    {
        throw new Error("nice try!");
    }

    public static void main(final String... args)
    {
        /*
         * Initialize your language parser and your rule
         */

        /*
        final MyParser parser
            = Parboiled.createParser(MyParser.class);
        final Rule rule = parser.someRule();
        final Channel<Lexer> channel = new GrappaChannel(rule);
        */

        /*
         * Initialize the lexer; only one channel!
         */

        /*
        final Lexer lexer = Lexer.builder()
            .withFailIfNoChannelToConsumeOneCharacter(true)
            .withChannel(channel)
            .build();
        */

        /*
         * Initialize your rules; here we take the example of a grammar which
         * has no root rule, but which we inject into a builder.
         *
         * Match the GrammarRuleKey with the grappa parser rule.
         */

        /*
        final LexerfulGrammarBuilder builder = LexerfulGrammarBuilder.create();
        MyGrammar.injectInto(builder);
        builder.setRootRule(MyGrammar.MY_RULE_KEY);
        */

        /*
         * Finally, create the Grammar object, the Parser object, initialize
         * the toolkit and run it
         */

        /*
        final Grammar grammar = builder.build();

        final Parser<Grammar> grammarParser = Parser.builder(grammar)
            .withLexer(lexer).build();

        final Toolkit toolkit = new Toolkit("test",
            new DummyConfigurationModel(grammarParser));

        toolkit.run();
        */
    }

    private static final class DummyConfigurationModel
        extends AbstractConfigurationModel
    {
        private final Parser<Grammar> parser;

        private DummyConfigurationModel(final Parser<Grammar> parser)
        {
            this.parser = parser;
        }

        @Override
        public Parser doGetParser()
        {
            return parser;
        }

        @Override
        public List<Tokenizer> doGetTokenizers()
        {
            return Collections.emptyList();
        }

        @Override
        public List<ConfigurationProperty> getProperties()
        {
            return Collections.emptyList();
        }
    }
}

Add a sample ToolKit file

Add a sample ToolKit file


package com.github.aureliano.edocs.app.gui.menu;

import javax.swing.JMenuItem;

public class FindDocumentMenuItem extends JMenuItem {

	private static final long serialVersionUID = -2048071523465789664L;

	public FindDocumentMenuItem() {
		super.setText("Find document...");
	}
}

Create find document menu item.

Create find document menu item.


package org.xdi.service.cdi.event;

import javax.enterprise.util.AnnotationLiteral;
import javax.inject.Qualifier;
import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;

import static java.lang.annotation.ElementType.*;
import static java.lang.annotation.RetentionPolicy.RUNTIME;

/**
 * @author Yuriy Movchan Date: 04/13/2017
 */
@Qualifier
@Retention(RUNTIME)
@Target({ METHOD, FIELD, PARAMETER, TYPE })
@Documented
public @interface ApplicationInitialized {

    public static final class Literal extends AnnotationLiteral<ApplicationInitialized> implements ApplicationInitialized {

        private static final long serialVersionUID = 4891987789146132930L;

        public static final Literal INSTANCE = new Literal();
    }

}

Add event to notify plugins about finish application initialization


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

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.notNullValue;
import static org.onlab.junit.ImmutableClassChecker.assertThatClassIsImmutable;

import org.junit.Test;
import org.onosproject.vtnrsc.SecurityGroup;

import com.google.common.testing.EqualsTester;

/**
 * Unit tests for SecurityGroup class.
 */
public class SecurityGroupTest {

    final SecurityGroup securityGroup1 = SecurityGroup.securityGroup("1");
    final SecurityGroup sameAssecurityGroup = SecurityGroup.securityGroup("1");
    final SecurityGroup securityGroup2 = SecurityGroup.securityGroup("2");

    /**
     * Checks that the SecurityGroup class is immutable.
     */
    @Test
    public void testImmutability() {
        assertThatClassIsImmutable(SecurityGroup.class);
    }

    /**
     * Checks the operation of equals().
     */
    @Test
    public void testEquals() {
        new EqualsTester().addEqualityGroup(securityGroup1, sameAssecurityGroup)
                .addEqualityGroup(securityGroup2).testEquals();
    }

    /**
     * Checks the construction of a SecurityGroup object.
     */
    @Test
    public void testConstruction() {
        final String securityGroupValue = "1";
        final SecurityGroup securityGroup = SecurityGroup.securityGroup(securityGroupValue);
        assertThat(securityGroup, is(notNullValue()));
        assertThat(securityGroup.securityGroup(), is(securityGroupValue));

    }
}

[ONOS-3251] Add the junit test code of SecurityGroup

Change-Id: If436b5e5e7acaed422794bf53a3b2e1d9da18695


package de.unistuttgart.iste.rss.bugminer.api;

import de.unistuttgart.iste.rss.bugminer.api.exceptions.NotFoundException;
import de.unistuttgart.iste.rss.bugminer.model.entities.Bug;
import de.unistuttgart.iste.rss.bugminer.model.entities.IssueTracker;
import de.unistuttgart.iste.rss.bugminer.model.entities.LineChange;
import de.unistuttgart.iste.rss.bugminer.model.entities.Project;
import de.unistuttgart.iste.rss.bugminer.model.repositories.BugRepository;
import de.unistuttgart.iste.rss.bugminer.model.repositories.IssueTrackerRepository;
import de.unistuttgart.iste.rss.bugminer.model.repositories.LineChangeRepository;
import de.unistuttgart.iste.rss.bugminer.model.repositories.ProjectRepository;
import de.unistuttgart.iste.rss.bugminer.tasks.Task;
import de.unistuttgart.iste.rss.bugminer.tasks.TaskManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.support.PagedListHolder;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.Collection;

@RestController
@RequestMapping(value = "/api")
public class TaskController {

    public static final int BUG_LIST_PAGE_SIZE = 10;

	@Autowired
	private TaskManager taskManager;

	protected TaskController() {
		// managed bean
	}

	/**
	 * Returns all tasks of any state
	 */
	@RequestMapping(value = "/tasks", method = RequestMethod.GET)
	public Collection<Task> tasks() {
		return taskManager.getTasks();
	}
}

Add REST API for listing tasks

Add REST API for listing tasks


package org.monospark.spongematchers.type;

import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import static org.monospark.spongematchers.testutil.HamcrestSpongeMatchers.matches;

import java.util.Map;

import org.junit.Test;
import org.monospark.spongematchers.matcher.SpongeMatcher;
import org.monospark.spongematchers.parser.SpongeMatcherParseException;
import org.monospark.spongematchers.parser.element.StringElement;
import org.monospark.spongematchers.parser.element.StringElementParser;
import org.spongepowered.api.block.BlockState;
import org.spongepowered.api.block.BlockType;
import org.spongepowered.api.block.trait.BlockTrait;
import org.spongepowered.api.data.DataContainer;
import org.spongepowered.api.data.DataQuery;
import org.spongepowered.api.data.MemoryDataContainer;

import com.google.common.collect.Maps;

public class BlockStateTypeTest {

    @Test
    public void canMatch_NonBlockStateObject_ReturnsFalse() throws SpongeMatcherParseException {
        Object o = 5;

        boolean canMatch = MatcherType.BLOCK_STATE.canMatch(o);

        assertThat(canMatch, is(false));
    }

    @Test
    public void canMatch_BlockStateObject_ReturnsTrue() throws Exception {
        Object o = mock(BlockState.class);

        boolean canMatch = MatcherType.BLOCK_STATE.canMatch(o);

        assertThat(canMatch, is(true));
    }

    @SuppressWarnings({"unchecked", "rawtypes"})
    @Test
    public void parseMatcher_ValidMapElement_ReturnsCorrectSpongeMatcher() throws SpongeMatcherParseException {
        StringElement element = StringElementParser.parseStringElement("{'type':{'id':'minecraft:appl.'},"
                + "'traits':{'trait1':1,'trait2':false},'data':{'boolean':true,'integer':>0}}");

        SpongeMatcher<BlockState> matcher = MatcherType.BLOCK_STATE.parseMatcher(element);

        BlockType type = mock(BlockType.class);
        when(type.getId()).thenReturn("minecraft:apple");
        BlockState state = mock(BlockState.class);
        when(state.getType()).thenReturn(type);
        BlockTrait<Integer> trait1 = mock(BlockTrait.class);
        when(trait1.getId()).thenReturn("trait1");
        when(trait1.getValueClass()).thenReturn(Integer.class);
        BlockTrait<Boolean> trait2 = mock(BlockTrait.class);
        when(trait2.getId()).thenReturn("trait2");
        when(trait2.getValueClass()).thenReturn(Boolean.class);
        Map traits = Maps.newHashMap();
        traits.put(trait1, 1);
        traits.put(trait2, false);
        when(state.getTraitMap()).thenReturn(traits);
        DataContainer container = new MemoryDataContainer();
        container.set(DataQuery.of("UnsafeData","boolean"), true);
        container.set(DataQuery.of("UnsafeData","integer"), 1);
        when(state.toContainer()).thenReturn(container);
        assertThat(matcher, matches(state));
    }
}

Add tests for parsing BlockState matchers


package study.hard.javalib.nativelib;

public class CloserTest {

	public static void main(String[] args) {
        int counter = 0;
//        counter++; // compile error!
        Thread thread1 = new Thread(new Runnable() {
            @Override
            public void run() {
//                counter++; // compile error!
                System.out.println(counter);
            }
        });
        Thread thread2 = new Thread(new Runnable() {
            @Override
            public void run() {
//                counter++; // compile error!
                System.out.println(counter);
            }
        });
        thread1.start();
        thread2.start();
	}

}

Add a test case for Closer in Java8.

Add a test case for Closer in Java8.


/*
 * #%L
 * %%
 * Copyright (C) 2018 BMW Car IT GmbH
 * %%
 * 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.
 * #L%
 */
package io.joynr.statusmetrics;

public class DefaultStatusReceiver implements StatusReceiver {
    @Override
    public void updateMessageWorkerStatus(int messageWorkerId, MessageWorkerStatus messageWorkerStatus) {
    }
}

[Java] Add default implementation for status receiver

Change-Id: I87e839dfb8ebcb30518ecc4c065b2600101e021b


package me.christine.housewifesolution;

import android.test.ActivityInstrumentationTestCase2;
import android.test.TouchUtils;
import android.test.ViewAsserts;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.ImageButton;
import android.widget.EditText;
import android.widget.ListView;

/**
 * Created by christine on 15-5-18.
 */
public class MainActivityTest extends ActivityInstrumentationTestCase2<MainActivity>{
    private MainActivity mainActivity;
    private ImageButton imageButton;
    private EditText editText;
    private ListView listView;

    public MainActivityTest() {
        super(MainActivity.class);
    }

    protected void setUp() throws Exception {
        super.setUp();

        setActivityInitialTouchMode(true);

        mainActivity = getActivity();
        imageButton = (ImageButton) mainActivity.findViewById(R.id.add_shopping_cart);
        editText = (EditText) mainActivity.findViewById(R.id.add_shopping_items);
        listView = (ListView) mainActivity.findViewById(R.id.shopping_list);
    }

    public void testPreconditions() {
        assertNotNull("MainActivity is null", mainActivity);
        assertNotNull("ImageButton is null", imageButton);
        assertNotNull("EditText is null", editText);
        assertNotNull("ListView is null", listView);
    }

    //Verify that button is displayed correctly.
    public void testImageButton_layout() {
        final View decorView = mainActivity.getWindow().getDecorView();
        ViewAsserts.assertOnScreen(decorView, imageButton);
        final ViewGroup.LayoutParams layoutParams = imageButton.getLayoutParams();
        assertNotNull(layoutParams);
        assertEquals(layoutParams.width, WindowManager.LayoutParams.WRAP_CONTENT);
        assertEquals(layoutParams.height, WindowManager.LayoutParams.WRAP_CONTENT);
    }
}

Build simple test cases to test the app and UI components.


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

import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import io.trino.plugin.jdbc.BaseAutomaticJoinPushdownTest;
import io.trino.testing.MaterializedRow;
import io.trino.testing.QueryRunner;
import org.jdbi.v3.core.Handle;
import org.jdbi.v3.core.Jdbi;
import org.testng.SkipException;

import static io.trino.plugin.mysql.MySqlQueryRunner.createMySqlQueryRunner;
import static java.lang.String.format;

public class TestMySqlAutomaticJoinPushdown
        extends BaseAutomaticJoinPushdownTest
{
    private TestingMySqlServer mySqlServer;

    @Override
    protected QueryRunner createQueryRunner()
            throws Exception
    {
        // Using MySQL 8.0.15 because test is sensitive to quality of NDV estimation and 5.5.46 we use
        // in other places does very poor job; for 10000 row table with 1000 distinct keys it estimates NDV at ~2500
        mySqlServer = closeAfterClass(new TestingMySqlServer("mysql:8.0.15", false));

        return createMySqlQueryRunner(
                mySqlServer,
                ImmutableMap.of(),
                ImmutableMap.<String, String>builder()
                        .put("metadata.cache-ttl", "0m")
                        .put("metadata.cache-missing", "false")
                        .buildOrThrow(),
                ImmutableList.of());
    }

    @Override
    public void testJoinPushdownWithEmptyStatsInitially()
    {
        throw new SkipException("MySQL statistics are automatically collected");
    }

    @Override
    protected void gatherStats(String tableName)
    {
        for (MaterializedRow row : computeActual("SHOW COLUMNS FROM " + tableName)) {
            String columnName = (String) row.getField(0);
            String columnType = (String) row.getField(1);
            if (columnType.startsWith("varchar")) {
                // varchar index require length
                continue;
            }
            onRemoteDatabase(format("CREATE INDEX \"%2$s\" ON %1$s (\"%2$s\")", tableName, columnName).replace("\"", "`"));
        }
        onRemoteDatabase("ANALYZE TABLE " + tableName.replace("\"", "`"));
    }

    protected void onRemoteDatabase(String sql)
    {
        try (Handle handle = Jdbi.open(() -> mySqlServer.createConnection())) {
            handle.execute("USE tpch");
            handle.execute(sql);
        }
    }
}

Add MySQL automatic Join pushdown test

Add MySQL automatic Join pushdown test


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

import com.github.daytron.revworks.authentication.AccessControl;
import com.github.daytron.revworks.ui.AdminLoginPopup;
import com.vaadin.ui.Button;
import com.vaadin.ui.UI;

/**
 * Click listener for webmaster link click event. Opens a modal sub-window for
 * admin login form.
 *
 * @author Ryan Gilera
 */
public class WebmasterLinkButtonListener implements Button.ClickListener {

    private static final long serialVersionUID = 1L;

    private final AccessControl userAccessControl;

    public WebmasterLinkButtonListener(AccessControl uac) {
        this.userAccessControl = uac;
    }

    @Override
    public void buttonClick(Button.ClickEvent event) {
        AdminLoginPopup adminLoginPopup = new AdminLoginPopup(userAccessControl);

        adminLoginPopup.setSizeUndefined();

        adminLoginPopup.center();

        UI.getCurrent().addWindow(adminLoginPopup);
    }

}

Add button click behaviour for webmaster link


package nl.tehdreamteam.se42.data;

/**
 * Defines certain constants for the data layer.
 *
 * @author Lesley
 */
public final class DataConstants {

    /**
     * The persistency-unit name for Hiberbante.
     */
    public static final String HIBERNATE_PERSISTENCY_UNIT_NAME = "manager";

    private DataConstants() {
        throw new UnsupportedOperationException("Should not be instantiated.");
    }

}

Define constants for the data layer.

Define constants for the data layer.


package ahlers.phantom.embedded;

import de.flapdoodle.embed.process.config.ExecutableProcessConfig;
import de.flapdoodle.embed.process.config.ISupportConfig;
import de.flapdoodle.embed.process.distribution.IVersion;

/**
 * Command line options for PhantomJS.
 *
 * @author [[mailto:michael@ahlers.consulting Michael Ahlers]]
 * @see Command Line Interface
 */
public class PhantomProcessConfig
        extends ExecutableProcessConfig {

    private final Boolean debug;

    protected PhantomProcessConfig(
            final IVersion version,
            final Boolean debug
    ) {
        super(version, new ISupportConfig() {
            @Override
            public String getName() {
                return "phantomjs";
            }

            @Override
            public String getSupportUrl() {
                return "https://github.com/michaelahlers/embedded-phantom/issues";
            }

            @Override
            public String messageOnException(final Class<?> context, final Exception exception) {
                return "";
            }
        });

        this.debug = debug;
    }

    public static class Builder {

        private final IVersion version;

        private Boolean debug;

        public Builder(final IVersion version) {
            this.version = version;
        }

        public void withDebug(final Boolean debug) {
            this.debug = debug;
        }

        public PhantomProcessConfig build() {
            return new PhantomProcessConfig(version, debug);
        }

    }

}

Add initial CLI config. class

Add initial CLI config. class


package org.concord.otrunk.test;

import java.util.Random;

import junit.framework.TestCase;

import org.concord.framework.otrunk.OTChangeEvent;
import org.concord.framework.otrunk.OTChangeListener;
import org.concord.framework.otrunk.OTrunk;
import org.concord.otrunk.view.OTFolderObject;
import org.concord.otrunk.view.OTViewerHelper;
import org.concord.otrunk.xml.XMLDatabase;

public class OTObjectInternalTest extends TestCase
{
	OTFolderObject folder;
	OTFolderObject item;
	OTChangeListener listener;
	Thread changeObjectThread;
	Thread changeListenersThread;
	boolean noExceptionThrown;

	// run test for 500 ms
    final long endTime = System.currentTimeMillis() + 1000;

    /**
     * If OTObjectInternal believes it has listeners when an otObject is
     * being changed, and another removes the last listener during the
     * change event, OTObjectInternal should handle it gracefully.
     */
	public void testListenersNotNull(){
		OTViewerHelper viewerHelper = new OTViewerHelper();

		// create  an empty database
		XMLDatabase db = new XMLDatabase();

		noExceptionThrown = true;

		try {
	        viewerHelper.loadOTrunk2(null, db);

	        OTrunk otrunk = viewerHelper.getOtrunk();
	        folder = otrunk.createObject(OTFolderObject.class);
	        item = otrunk.createObject(OTFolderObject.class);

	        otrunk.setRoot(folder);

	        changeObjectThread = new Thread(){
	        	public void run(){
	        		while(System.currentTimeMillis() < endTime){
	        			try {
		        			if (folder.getChildCount() == 0){
		        				folder.addChild(item);
		        			} else {
		        				folder.removeAllChildren();
		        			}
	        			} catch (java.lang.NullPointerException e){
	        				noExceptionThrown = false;
	        			}
	        		}
	        	}
	        };

	        changeListenersThread = new Thread(){
	        	public void run(){
	        		listener = new OTChangeListener() {

	    				public void stateChanged(OTChangeEvent e){}
	    			};

	        		boolean added = false;

	        		while(System.currentTimeMillis() < endTime){
	        			if (!added){
	        				folder.addOTChangeListener(listener);
	        				added = true;
	        			} else {
	        				folder.removeOTChangeListener(listener);
	        				added = false;
	        			}
	        		}
	        	}
	        };

	        changeObjectThread.start();
	        changeListenersThread.start();

	        // FIXME we should automatically check if the id is actually saved in the string.

        } catch (Exception e) {
	        // TODO Auto-generated catch block
	        e.printStackTrace();
        }

//        System.out.println(noExceptionThrown);
//        assertTrue(noExceptionThrown);
        while (System.currentTimeMillis() < (endTime)){
        	assertTrue(noExceptionThrown);
        }
	}

}

Add JUnit test which checks that OTObjectInternal gracefully handles the case where another thread removes a listener during a change event.

git-svn-id: 8ebed0c25533aaea68ca43268d4d516467f97e6a@20852 6e01202a-0783-4428-890a-84243c50cc2b


/**
 *
 */
package eu.aleon.aleoncean.device.remote;

import eu.aleon.aleoncean.packet.radio.userdata.UserDataScaleValueException;
import eu.aleon.aleoncean.packet.radio.RadioPacket4BS;
import eu.aleon.aleoncean.packet.radio.userdata.UserDataEEPA50205;
import org.junit.After;
import org.junit.AfterClass;
import static org.junit.Assert.*;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;

/**
 * @author Thomas Stezaly (thomas.stezaly@aleuon.eu)
 *
 */
public class RemoteDeviceEEPA50205Test {

    /**
     * @throws java.lang.Exception
     */
    @BeforeClass
    public static void setUpBeforeClass() throws Exception {
    }

    /**
     * @throws java.lang.Exception
     */
    @AfterClass
    public static void tearDownAfterClass() throws Exception {
    }

    /**
     * @throws java.lang.Exception
     */
    @Before
    public void setUp() throws Exception {

    }

    /**
     * @throws java.lang.Exception
     */
    @After
    public void tearDown() throws Exception {
    }

    @Test
    public void testSetGetTemperature() {

        final double temperatureSet = 20.0;
        final UserDataEEPA50205 userData = new UserDataEEPA50205();

        try {
            userData.setTemperature(temperatureSet);
            userData.setTeachIn(false);
        } catch (UserDataScaleValueException e) {
            fail("Throws exception: UserDataScaleValueException");
        }

        final RadioPacket4BS packet = userData.generateRadioPacket();
        final RemoteDeviceEEPA50205 testDevice = new RemoteDeviceEEPA50205(null, packet.getSenderId(), packet.getDestinationId());

        testDevice.parseRadioPacket(packet);

        double temperatureGet = testDevice.getTemperature();
        double delta = temperatureGet - temperatureSet;

        System.out.println("temperatureSet: "+temperatureSet);
        System.out.println("temperatureGet: "+temperatureGet);

        // We use a delta of 0.2, because one range point fits to 0.15 degree.
        // So is this value acceptable
        assertTrue(delta < 0.2);
    }
}

Add unit test for RD A5-02-05

Add unit test for RD A5-02-05


/*
 Copyright 2006 Paul Zepernick

 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.sf.pzfilereader.parserutils;

import net.sf.pzfilereader.util.ParserUtils;
import junit.framework.TestCase;

/**
 * Tests the functionality of the left trim in the ParserUtils
 *
 * @author paul zepernick
 */
public class LTrimTest extends TestCase{

    /**
     * Make sure all spaces are properly removed from the front of the String
     *
     */
    public void testTrimLeadingSpaces(){
        final String testS = "     RemoveAllSpacesFromMe";
        assertEquals(true , ParserUtils.lTrim(testS).indexOf(" ") == -1);
    }

    /**
     * Make sure all spaces are properly removed from the front of the String
     * leaving the trailing spaces at the end
     *
     */
    public void testTrimLeadingSpacesWithTrailingSpaces(){
        final String testS = "     RemoveAllSpacesFromMe     ";
        final String tResult = ParserUtils.lTrim(testS);
        assertEquals(true , !tResult.startsWith(" ") && tResult.endsWith(" "));
    }

    /**
     * Make sure all TAB chars are properly removed from the front of the String
     * leaving the trailing spaces at the end
     *
     */
    public void testTrimLeadingTabs(){
        final String testS = "\t\t\tRemoveAllSpacesFromMe     ";
        final String tResult = ParserUtils.lTrim(testS);
        assertEquals(true , !tResult.startsWith("\t") && tResult.endsWith(" "));
    }

    /**
     * Make sure all TAB chars are properly removed from the front of the String
     * leaving the trailing spaces at the end
     *
     */
    public void testKeepLeadingTabs(){
        final String testS = "     \t\t\tRemoveAllSpacesFromMe     ";
        final String tResult = ParserUtils.lTrimKeepTabs(testS);
        assertEquals(true , !tResult.startsWith("\t") && tResult.endsWith(" "));
    }

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

Test cases for lTrim and lTrimKeepTabs

Test cases for lTrim and lTrimKeepTabs

Former-commit-id: d300819cf24d945698e6fbb491ada29f46409f62


// 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 com.cloud.region;

import java.util.Date;

/**
 *
 */
public interface RegionSync  {

    public long getId();

    public int getRegionId();

	public String getApi();

	Date getCreateDate();
}

Add sync entry to region_sunc table on region api failure


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

package org.jeecqrs.bundle.jcommondomain.sagas;

import java.util.Map;
import org.jeecqrs.common.event.Event;
import org.jeecqrs.sagas.Saga;
import org.jeecqrs.sagas.SagaIdentificationStrategy;

/**
 * A simple saga identification strategy that simply maps a saga to
 * the id of an incomiong event.
 * This obviously means that the corresponding saga may only handle exactly
 * on event.
 */
public class EventIdSagaIdentificationStrategy<S extends Saga<Event>>
    implements SagaIdentificationStrategy<S, Event> {

    @Override
    public String identifySaga(Event event) {
        return event.id().toString();
    }

}

Add a simple saga ident strat by event id


package io.github.ddebree.game.ai.core.strategy;

import javax.annotation.Nonnull;
import java.util.stream.Stream;

/**
 * A basic representation of a player's strategy.
 *
 * At a given state, for a particular player, what is the best possible set of moves
 *
 * @param <S> The class that represents a game state
 * @param <P> The class that represents a player
 * @param <M> The class used to represent a player's move
 *
 * @author Dean de Bree
 */
public interface IStrategy<S, P, M> {

    /**
     * Get the best moves that a player could make at the current game state
     *
     * @param state The current game state
     * @param player The player to determine the best current state for
     * @return A stream of moves that would result in the best outcome for the provided player
     */
    @Nonnull
    Stream<M> getBestMoves(@Nonnull S state, P player);

}

Add the basic strategy interface

Add the basic strategy interface


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

package com.google.android.apps.mytracks.services.sensors.ant;

/**
 * A enum which stores static data about ANT sensors.
 *
 * @author Matthew Simmons
 */
public enum AntSensor {
  SENSOR_HEART_RATE (Constants.ANT_DEVICE_TYPE_HRM),
  SENSOR_CADENCE (Constants.ANT_DEVICE_TYPE_CADENCE),
  SENSOR_SPEED (Constants.ANT_DEVICE_TYPE_SPEED),
  SENSOR_POWER (Constants.ANT_DEVICE_TYPE_POWER);

  private static class Constants {
    public static byte ANT_DEVICE_TYPE_POWER = 11;
    public static byte ANT_DEVICE_TYPE_HRM = 120;
    public static byte ANT_DEVICE_TYPE_CADENCE = 122;
    public static byte ANT_DEVICE_TYPE_SPEED = 123;
  };

  private final byte deviceType;

  private AntSensor(byte deviceType) {
    this.deviceType = deviceType;
  }

  public byte getDeviceType() {
    return deviceType;
  }
}

Add an enum which stores static data about ANT sensors.


package flyway.oskari;

import java.sql.Connection;

import org.flywaydb.core.api.migration.jdbc.JdbcMigration;

import fi.nls.oskari.db.BundleHelper;
import fi.nls.oskari.domain.map.view.Bundle;

public class V1_54_2__register_3d_camera_controls_bundle implements JdbcMigration {

	private static final String BUNDLE_ID = "camera-controls-3d";

	@Override
	public void migrate(Connection connection) throws Exception {

		// BundleHelper checks if these bundles are already registered
        Bundle bundle = new Bundle();
        bundle.setName(BUNDLE_ID);
        BundleHelper.registerBundle(bundle, connection);
	}
}

Add migration to register camera-controls-3d bundle


package leetcode.binary_tree_level_order_traversal_ii;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Random;

import common.TreeNode;

public class Solution {
	public ArrayList<ArrayList<Integer>> levelOrderBottom(TreeNode root) {
		Queue<MyNode> queue = new LinkedList<MyNode>();
		ArrayList<ArrayList<Integer>> ans = new ArrayList<ArrayList<Integer>>();
		if(root == null) return ans;
		queue.offer(new MyNode(root, 0));
		while(!queue.isEmpty()){
			MyNode myNode = queue.remove();
			TreeNode tn = myNode.node;
			ArrayList<Integer> lvl = null;
			if(ans.size() <= myNode.level){
				lvl = new ArrayList<Integer>();
				ans.add(lvl);
			}else{
				lvl = ans.get(myNode.level);
			}
			lvl.add(tn.val);
			if(tn.left != null) queue.offer(new MyNode(tn.left, myNode.level + 1));
			if(tn.right != null) queue.offer(new MyNode(tn.right, myNode.level + 1));
		}
		int size = ans.size();
		for(int i = 0; i < size / 2; i++){
			ArrayList<Integer> tmp = ans.get(i);
			ans.set(i, ans.get(size - 1 - i));
			ans.set(size - 1 - i, tmp);
		}
		return ans;
	}
	public static class MyNode{
		TreeNode node;
		int level;
		public MyNode(TreeNode node, int level){
			this.node = node;
			this.level = level;
		}
	}

	public static void main(String[] args){
		final int N = 15;
		final int R = 5;
		ArrayList<TreeNode> nodes = new ArrayList<TreeNode>();
		for(int i = 0; i < N; i++){
			nodes.add(new TreeNode(i));
		}
		Random r = new Random();
		for(int i = 0; i < N; i++){
			if(i * 2 + 1 < N){
				nodes.get(i).left = nodes.get(i * 2 + 1);
			}
			if(i * 2 + 2 < N){
				nodes.get(i).right = nodes.get(i * 2 + 2);
			}
		}
		for(int i = 0; i < R; i++){
			int ran = r.nextInt(N);
			System.err.println("ran:" + ran);
			nodes.get(ran).left = null;
		}

		for(ArrayList<Integer> row : new Solution().levelOrderBottom(nodes.get(0))){
			for(int x : row){
				System.err.print(x + ", ");
			}
			System.err.println("");
		}
	}
}

Add java solution for 107. Binary Tree Level Order Traversal II

107. Binary Tree Level Order Traversal II: https://leetcode.com/problems/binary-tree-level-order-traversal-ii/


package io.github.satoshinm.WebSandboxMC.sponge;

import com.google.inject.Inject;
import org.slf4j.Logger;
import org.spongepowered.api.event.Listener;
import org.spongepowered.api.event.game.state.GameStartedServerEvent;
import org.spongepowered.api.plugin.Plugin;

@Plugin(id = "websandboxmc", name = "WebSandboxMC", version = "1.6.0")
public class WebSandboxSpongePlugin {

    @Inject
    private Logger logger;

    @Listener
    public void onServerStart(GameStartedServerEvent event) {
        logger.info("WebSandboxMC/Sponge starting");
    }
}

Add a skeletal Sponge plugin class

Add a skeletal Sponge plugin class


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

/**
 *
 * @author Ryan Gilera
 */
public class ConversionClient {

}

Add a base conversion client class

Add a base conversion client class


package com.fasterxml.jackson.failing;

import com.fasterxml.jackson.core.BaseTest;
import com.fasterxml.jackson.core.JsonPointer;

// For https://bugs.chromium.org/p/oss-fuzz/issues/detail?id=51806
// (via databind, but we don't need that)
public class Fuzz51806JsonPointerParseTest extends BaseTest
{
    // Before fix, looks like this is enough to cause StackOverflowError
    private final static int TOO_DEEP_PATH = 6000;

    // Verify that very deep/long (by number of segments) JsonPointer
    // may still be parsed ok
    public void testJsonPointerParseTail() throws Exception
    {
        JsonPointer p = JsonPointer.compile(_generatePath(TOO_DEEP_PATH));
        assertNotNull(p);
    }

    private String _generatePath(int depth) {
        StringBuilder sb = new StringBuilder(4 * depth);
        for (int i = 0; i < depth; ++i) {
            sb.append("/a").append(depth);
        }
        return sb.toString();
    }
}

Add a failing test for JsonParser.compile() and Very Deeply Nested expressions


/*
 * Copyright 2016 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 de.vorb.platon.web.rest;

import de.vorb.platon.persistence.CommentRepository;

import com.google.common.collect.Sets;
import com.google.common.truth.Truth;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.runners.MockitoJUnitRunner;

import java.util.Set;
import java.util.function.Function;
import java.util.stream.Collectors;

@RunWith(MockitoJUnitRunner.class)
public class CommentCountResourceTest {

    @Mock
    private CommentRepository commentRepository;

    @InjectMocks
    private CommentCountResource commentCountResource;

    private final Set<String> sampleThreadUrls = Sets.newHashSet("/article-a.html", "/2016/11/article-b.html");

    @Before
    public void setUp() throws Exception {

        Mockito.when(commentRepository.countByThreadUrls(Mockito.eq(sampleThreadUrls)))
                .thenReturn(sampleThreadUrls.stream()
                        .collect(Collectors.toMap(Function.identity(), String::length)));
    }

    @Test
    public void getCommentCounts() throws Exception {
        commentCountResource.getCommentCounts(sampleThreadUrls)
                .getCommentCounts()
                .forEach((threadUrl, count) -> {
                    Truth.assertThat(count).isEqualTo(threadUrl.length());
                });
    }
}

Implement unit test for CommentCountResource


package jp.naist.inet_lab.android.ipv6multicast;

/**
 * Throw if something issue related to networking is occurred.
 *
 * @author yohei-ka
 *
 */
public class MulticastException extends Exception {

    /**
     * Auto-generated serial version UID
     */
    private static final long serialVersionUID = -8561020680607603227L;

    public MulticastException(Throwable cause) {
        super(cause);
    }

}

Implement MutlicastException, which handle the exception related to networking


package com.blankstyle.vertx.php.http;

import org.vertx.java.core.buffer.Buffer;

import com.blankstyle.vertx.php.Handler;
import com.blankstyle.vertx.php.streams.ExceptionSupport;
import com.blankstyle.vertx.php.streams.ReadStream;
import com.caucho.quercus.env.Callback;
import com.caucho.quercus.env.Env;
import com.caucho.quercus.env.Value;

/**
 * A PHP compatible implementation of the Vert.x HttpClientResponse.
 *
 * @author Jordan Halterman
 */
public class HttpClientResponse implements ReadStream, ExceptionSupport {

  private org.vertx.java.core.http.HttpClientResponse response;

  public HttpClientResponse(org.vertx.java.core.http.HttpClientResponse response) {
    this.response = response;
  }

  public HttpClientResponse(Env env, org.vertx.java.core.http.HttpClientResponse response) {
    this.response = response;
  }

  @Override
  public Value pause(Env env) {
    response.pause();
    return env.wrapJava(this);
  }

  @Override
  public Value resume(Env env) {
    response.resume();
    return env.wrapJava(this);
  }

  public Value cookies(Env env) {
    return env.wrapJava(response.cookies());
  }

  public Value headers(Env env) {
    return env.wrapJava(response.headers());
  }

  public Value trailers(Env env) {
    return env.wrapJava(response.trailers());
  }

  public Value netSocket(Env env) {
    return env.wrapJava(response.netSocket());
  }

  public Value statusCode(Env env) {
    return env.wrapJava(response.statusCode());
  }

  public Value statusMessage(Env env) {
    return env.wrapJava(response.statusMessage());
  }

  @Override
  public Value dataHandler(Env env, Callback handler) {
    response.dataHandler(new Handler<Buffer>(env, handler));
    return env.wrapJava(this);
  }

  public Value bodyHandler(Env env, Callback handler) {
    response.bodyHandler(new Handler<Buffer>(env, handler));
    return env.wrapJava(this);
  }

  @Override
  public Value endHandler(Env env, Callback handler) {
    response.endHandler(new Handler<Void>(env, handler));
    return env.wrapJava(this);
  }

  @Override
  public Value exceptionHandler(Env env, Callback handler) {
    response.exceptionHandler(new Handler<Throwable>(env, handler));
    return env.wrapJava(this);
  }

}

Add HTTP client response handler.

Add HTTP client response handler.


package io.quarkus.runtime;

import java.util.Optional;

import io.quarkus.runtime.annotations.ConfigItem;
import io.quarkus.runtime.annotations.ConfigPhase;
import io.quarkus.runtime.annotations.ConfigRoot;

/**
 * This configuration class is here to avoid warnings when using {@code -Dquarkus.args=...}.
 */
@ConfigRoot(name = ConfigItem.PARENT, phase = ConfigPhase.RUN_TIME)
public class CommandLineRuntimeConfig {

    /**
     * The arguments passed to the command line.
     * <p>
     * We don't make it a list as the args are separated by a space, not a comma.
     */
    @ConfigItem
    public Optional<String> args;

}

Add a config class to avoid a warning for -Dquarkus.args=...


package uk.ac.ebi.phenotype.dao;

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

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.transaction.TransactionConfiguration;
import org.springframework.transaction.annotation.Transactional;

import uk.ac.ebi.phenotype.bean.StatisticalResultBean;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "classpath:test-config.xml" })
@TransactionConfiguration
@Transactional
public class StatisticalResultDAOTest {

	@Autowired
	StatisticalResultDAO statisticalResultDAO;

	@Test
	public void testGetPvaluesByAlleleAndPhenotypingCenterAndPipeline() {

		// MGI:4432021?phenotyping_center=HMGU&pipeline_stable_id=ESLIM_001
		String alleleAccession = "MGI:4432021";
		String phenotypingCenter = "HMGU";
		String pipelineStableId = "ESLIM_001";

		Map<String, List<StatisticalResultBean>> results = statisticalResultDAO.getPvaluesByAlleleAndPhenotypingCenterAndPipeline(
				alleleAccession, phenotypingCenter, pipelineStableId);

		for (String key: results.keySet()) {
			System.out.println(key);
			for (StatisticalResultBean bean: results.get(key)) {
				System.out.println(bean.getStatisticalMethod() + "\t" + bean.getpValue() + "\t" + bean.getEffectSize());
			}
		}
	}

}

Test to get all p-values from a line

Test to get all p-values from a line


package eu.nimble.service.dashboard.services;

import javax.enterprise.context.ApplicationScoped;
import javax.enterprise.event.Observes;
import javax.inject.Inject;

import org.apache.marmotta.platform.core.api.config.ConfigurationService;
import org.apache.marmotta.platform.core.events.SystemStartupEvent;

@ApplicationScoped
public class StartupConfigurator {
	@Inject
	ConfigurationService config;

	public StartupConfigurator() {
		// TODO Auto-generated constructor stub
	}
	public void onSystemStartup(@Observes SystemStartupEvent event) {

		String[] databaseVal = new String [] {"database.type","database.url","database.user","database.password" };
		String[] hostVal = new String [] {"kiwi.path","kiwi.context","kiwi.host" };

		if ( processEnvironmentVariables(databaseVal)) {
			config.setBooleanConfiguration("kiwi.setup.database", Boolean.TRUE);
		}
		if ( processEnvironmentVariables(hostVal)) {
			config.setBooleanConfiguration("kiwi.setup.host", Boolean.TRUE);
		}
		/*
			security.enabled
			database.type
			database.url
			database.user
			database.password
			kiwi.setup.database
			kiwi.path
			kiwi.context
			kiwi.host
			kiwi.setup.host
		*/
	}

	private boolean processEnvironmentVariables(String[] variables) {
		boolean variablesPresent = true;
		String[] values = new String[variables.length];

		for ( int i = 0; i < variables.length; i++ ) {
			// try to get from environment
			values[i] = System.getenv(variables[i]);

			if ( values[i]  == null ) {
				values[i] = System.getProperty(variables[i]);
			}

			if ( values[i] == null ) {
				variablesPresent = false;
			}
		}
		if (variablesPresent) {
			for ( int i = 0; i < variables.length; i++) {
				config.setConfiguration(variables[i], values[i]);
			}
			return true;
		}
		return false;
	}

}

Configure Environment Variables for database and host

Allow to adjust environment variables for

--> database.[type|url|user|password]
--> kiwi.[path|context|host]

all variables must be present to be set. when successful,

--> kiwi.setup.database
--> kiwi.setup.host

are set to true


package net.minecraftforge.test;

import net.minecraft.init.Blocks;
import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.event.world.BlockEvent.CreateFluidSourceEvent;
import net.minecraftforge.fml.common.Mod;
import net.minecraftforge.fml.common.event.FMLInitializationEvent;
import net.minecraftforge.fml.common.eventhandler.Event.Result;
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent;

@Mod(modid = "CreateFluidSourceTest", version = "1.0")
public class CreateFluidSourceTest
{
    public static final boolean ENABLE = false;

    @Mod.EventHandler
    public static void init(FMLInitializationEvent event)
    {
        if (ENABLE)
            MinecraftForge.EVENT_BUS.register(CreateFluidSourceTest.class);
    }

    @SubscribeEvent
    public static void onCreateFluidSource(CreateFluidSourceEvent event)
    {
        // make it work exactly the opposite of how it works by default
        if (event.getState().getBlock() == Blocks.FLOWING_WATER)
            event.setResult(Result.DENY);
        else
            event.setResult(Result.ALLOW);
    }
}

Add a test for CreateFluidSourceEvent

Add a test for CreateFluidSourceEvent


public class Upi {

	public static String getUpi( long id ) {
		String str = Long.toHexString( id ).toUpperCase();
		return "URS0000000000".substring(0, 13 - str.length() ) + str;
	}

	public static void main (String args[]) {
		long l = Long.parseLong(args[0]);
		System.out.println(getUpi(l));
	}
}

Add the java file that calculates the UPI that is executed in the Oracle database


package org.ocpsoft.prettytime.i18n;

import java.util.Date;
import java.util.Locale;

import org.junit.Assert;
import org.junit.Test;
import org.ocpsoft.prettytime.PrettyTime;

public class Resources_hrTest {

	   private static final int MINUTES = 1000 * 60;

	@Test
	   public void testFormatMinute() throws Exception
	   {
	      PrettyTime prettyTime = new PrettyTime(new Locale("hr"));

	      Assert.assertEquals("za 1 minutu", prettyTime.format(new Date(System.currentTimeMillis() + 1*MINUTES)));
	      Assert.assertEquals("za 2 minute", prettyTime.format(new Date(System.currentTimeMillis() + 2*MINUTES)));
	      Assert.assertEquals("za 3 minute", prettyTime.format(new Date(System.currentTimeMillis() + 3*MINUTES)));
	      Assert.assertEquals("za 4 minute", prettyTime.format(new Date(System.currentTimeMillis() + 4*MINUTES)));
	      Assert.assertEquals("za 5 minuta", prettyTime.format(new Date(System.currentTimeMillis() + 5*MINUTES)));
	      Assert.assertEquals("za 6 minuta", prettyTime.format(new Date(System.currentTimeMillis() + 6*MINUTES)));

	      Assert.assertEquals("prije 1 minutu", prettyTime.format(new Date(System.currentTimeMillis() - 1*MINUTES)));
	      Assert.assertEquals("prije 2 minute", prettyTime.format(new Date(System.currentTimeMillis() - 2*MINUTES)));
	      Assert.assertEquals("prije 3 minute", prettyTime.format(new Date(System.currentTimeMillis() - 3*MINUTES)));
	      Assert.assertEquals("prije 4 minute", prettyTime.format(new Date(System.currentTimeMillis() - 4*MINUTES)));
	      Assert.assertEquals("prije 5 minuta", prettyTime.format(new Date(System.currentTimeMillis() - 5*MINUTES)));
	      Assert.assertEquals("prije 6 minuta", prettyTime.format(new Date(System.currentTimeMillis() - 6*MINUTES)));
	   }

}

Fix - updated Croatian translation

Fix - updated Croatian translation

Added test for updated Croatian translation.
Croatian durations have more complex rules for plurals, depending on
quantity (2, 3 and 4 usualy use different plural word than other
plurals - example for minutes - 1 minuta, 2 minute, 5 minuta).


package eu.mosaic_cloud.tools.callbacks.core;

import java.lang.reflect.Method;

public interface CallbackFunnelHandler
		extends
			CallbackHandler
{
	public CallbackCompletion<?> executeCallback (final Callbacks Proxy, final Method method, final Object[] arguments);
}

Add callback funnel handler (like `InvocationHandler` from `java.lang.reflect`)


package edu.berkeley.eecs.cfc_tracker.log;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.os.Environment;
import android.widget.Toast;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.util.logging.StreamHandler;

/**
 * Created by shankari on 7/16/15.
 */
public class DatabaseLogHandler extends SQLiteOpenHelper {
    private String TABLE_LOG = "logTable";
    private String KEY_LINE = "log_line";
    private String KEY_ID = "ID";
    private static final int DATABASE_VERSION = 1;

    private Context cachedContext;

    public DatabaseLogHandler(Context context) {
        super(context, "logDB", null, DATABASE_VERSION);
        cachedContext = context;
    }

    @Override
    public void onCreate(SQLiteDatabase sqLiteDatabase) {
        String CREATE_LOG_TABLE = "CREATE TABLE " + TABLE_LOG +" (" +
                KEY_ID + " INTEGER PRIMARY_KEY, "+ KEY_LINE +" TEXT)";
        System.out.println("CREATE_CLIENT_STATS_TABLE = " + CREATE_LOG_TABLE);
        sqLiteDatabase.execSQL(CREATE_LOG_TABLE);
    }

    @Override
    public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
        sqLiteDatabase.execSQL("DROP TABLE IF EXISTS " + TABLE_LOG);
        onCreate(sqLiteDatabase);
    }

    public void log(String line) {
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues cv = new ContentValues();
        cv.put(KEY_LINE, line);
        db.insert(TABLE_LOG, null, cv);
        db.close();
    }

    public void export() {
        SQLiteDatabase db = this.getReadableDatabase();
        try {
            String ourFileName = Log.getLogBase(cachedContext) + "/dumped_log_file.txt";
            System.out.println("ourFileName = "+ourFileName);
            PrintStream out = new PrintStream(new FileOutputStream(ourFileName, true));
            String queryString = "SELECT * from " + TABLE_LOG;
            Cursor cur = db.rawQuery(queryString, null);
            int resultCount = cur.getCount();
            if (cur.moveToFirst()) {
                for (int i = 0; i < resultCount; i++) {
                    out.println(cur.getString(0));
                }
            }
        } catch (IOException e) {
            Toast.makeText(cachedContext, e.getMessage(), Toast.LENGTH_LONG).show();
            System.err.println();
        }
        db.close();
    }
}

Add a new database oriented logger

Add a new database oriented logger

Add a new logger in which we store log lines in an SQLite database.
This ensures thread safety, although we need to export the data to a file or to
a server to view it, since we cannot store the database on the external drive.


package org.realityforge.arez;

import java.util.ArrayList;
import javax.annotation.Nonnull;
import static org.testng.Assert.*;

final class TestSpyEventHandler
  implements SpyEventHandler
{
  private final ArrayList<Object> _events = new ArrayList<>();

  @Override
  public void onSpyEvent( @Nonnull final Object event )
  {
    _events.add( event );
  }

  <T> T assertEvent( @Nonnull final Class<T> type, final int index )
  {
    assertTrue( eventCount() > index );
    final Object event = _events.get( index );
    assertTrue( type.isInstance( event ),
                "Expected event at index " + index + " to be of type " + type + " but is " +
                event + " which is of type " + event.getClass() );
    return type.cast( event );
  }

  void assertEventCount( final int count )
  {
    assertEquals( eventCount(), count );
  }

  int eventCount()
  {
    return _events.size();
  }
}

Add SpyEventHandler useful during tests

Add SpyEventHandler useful during tests


package lt.dariusl.rxfirebaseandroid;

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

public class TestTest {
    @Test
    public void testTest() throws Exception {
        Assert.assertTrue(true);
    }
}

Add random test to try out drone

Add random test to try out drone


package com.rackspacecloud.blueflood.eventemitter;

import com.rackspacecloud.blueflood.types.Locator;
import com.rackspacecloud.blueflood.types.Points;
import com.rackspacecloud.blueflood.types.Rollup;
import com.rackspacecloud.blueflood.types.SimpleNumber;
import junit.framework.Assert;
import org.junit.Before;
import org.junit.Test;

import java.io.IOException;

import static org.junit.Assert.assertEquals;

public class RollupEventTest {

    Locator locator;
    Rollup rollup;
    String unit;
    String granularity;
    long timestamp;

    RollupEvent event;

    @Before
    public void setUp() throws IOException {

        locator = Locator.createLocatorFromPathComponents("tenant", "a", "b");
        Points<SimpleNumber> points = new Points<SimpleNumber>();
        rollup = Rollup.BasicFromRaw.compute(points);
        unit = "Some init";
        granularity = "Some granularity";
        timestamp = 1451631661000L;     // 2016-01-01 01:01:01 CST

        event = new RollupEvent(locator, rollup, unit, granularity, timestamp);
    }

    @Test
    public void locatorGetsSetInConstructor() {
        Assert.assertSame(locator, event.getLocator());
    }

    @Test
    public void rollupGetsSetInConstructor() {
        Assert.assertSame(rollup, event.getRollup());
    }

    @Test
    public void unitGetsSetInConstructor() {
        Assert.assertEquals(unit, event.getUnit());
    }

    @Test
    public void granularityGetsSetInConstructor() {
        Assert.assertEquals(granularity, event.getGranularityName());
    }

    @Test
    public void timestampGetsSetInConstructor() {
        Assert.assertEquals(timestamp, event.getTimestamp());
    }

    @Test
    public void setUnitChangesUnit() {
        //given
        String unit2= "Some other unit";
        // when
        event.setUnit(unit2);
        // then
        assertEquals(unit2, event.getUnit());
    }
}

Add a test class for RollupEvent.

Add a test class for RollupEvent.


package org.thinkinghub.gateway.oauth.exception;

public class OAuthProcessingException extends GatewayException {

	private static final long serialVersionUID = -253028809896546433L;

	public OAuthProcessingException(String errCode, String errMsg) {
		super(errMsg);
	}

	protected String getErrorCode() {
		return "GW100";
	}

}

Add exception class for oauth processing


/*
 * Copyright 2013 Red Hat, Inc. and/or its affiliates.
 *
 * Licensed under the Eclipse Public License version 1.0, available at http://www.eclipse.org/legal/epl-v10.html
 */
package io.liveoak.git;

import io.liveoak.spi.Config;
import io.liveoak.spi.resource.RootResource;
import io.liveoak.testtools.AbstractHTTPResourceTestCase;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.junit.Test;

import java.io.File;

import static org.fest.assertions.Assertions.assertThat;

/**
 * @author Ken Finnigan
 */
public class HTTPGitResourceTest extends AbstractHTTPResourceTestCase {
    @Override
    public RootResource createRootResource() {
        return new GitRepoResource( "git" );
    }

    @Override
    public Config createConfig() {
        File repoDir = new File(this.projectRoot, "/target/repo_http");
        if (!repoDir.exists()) {
            repoDir.mkdirs();
        }

        Config config = super.createConfig();
        config.put("repoPath", repoDir.getAbsolutePath());
        return config;
    }

    @Test
    public void enumerateRoot() throws Exception {
        HttpGet get = new HttpGet( "http://localhost:8080/git" );
        get.addHeader( "Accept", "application/json" );

        try {
            System.out.println( "DO GET" );
            CloseableHttpResponse result = httpClient.execute( get );
            System.out.println( "=============>>>" );
            System.out.println( result );

            HttpEntity entity = result.getEntity();
            if ( entity.getContentLength() > 0 ) {
                entity.writeTo( System.out );
            }
            System.out.println( "\n<<<=============" );
            assertThat( result.getStatusLine().getStatusCode() ).isEqualTo( 200 );
        } finally {
            httpClient.close();
        }
    }
}

Add HTTP test for git resource

Add HTTP test for git resource


package org.robolectric.res;

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

import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamReader;

import java.io.StringReader;

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

public class StaxValueLoaderTest {

  private PackageResourceTable resourceTable;
  private NodeHandler topLevelNodeHandler;
  private StaxDocumentLoader staxDocumentLoader;

  @Before
  public void setUp() throws Exception {
    resourceTable = new PackageResourceTable("pkg");

    topLevelNodeHandler = new NodeHandler();
    staxDocumentLoader = new StaxDocumentLoader("pkg", null, topLevelNodeHandler);
  }

  @Test
  public void ignoresXliffTags() throws Exception {
    topLevelNodeHandler.addHandler("resources", new NodeHandler()
        .addHandler("string", new StaxValueLoader(resourceTable, "string", ResType.CHAR_SEQUENCE))
    );

    parse("<resources xmlns:xliff=\"urn:oasis:names:tc:xliff:document:1.2\">" +
        "<string name=\"preposition_for_date\">on <xliff:g id=\"date\" example=\"May 29\">%s</xliff:g></string>" +
        "</resources>");

    assertThat(resourceTable.getValue(new ResName("pkg:string/preposition_for_date"), "").getData())
        .isEqualTo("on %s");
  }

  @Test
  public void ignoresBTags() throws Exception {
    topLevelNodeHandler.addHandler("resources", new NodeHandler()
        .addHandler("item[@type='string']", new StaxValueLoader(resourceTable, "string", ResType.CHAR_SEQUENCE))
    );

    parse("<resources xmlns:xliff=\"urn:oasis:names:tc:xliff:document:1.2\">" +
        "<item type=\"string\" name=\"sms_short_code_details\">This <b>may cause charges</b> on your mobile account.</item>" +
        "</resources>");

    assertThat(resourceTable.getValue(new ResName("pkg:string/sms_short_code_details"), "").getData())
        .isEqualTo("This may cause charges on your mobile account.");
  }

  private void parse(String xml) throws XMLStreamException {
    XMLInputFactory factory = XMLInputFactory.newFactory();
    XMLStreamReader xmlStreamReader = factory.createXMLStreamReader(new StringReader(xml));
    staxDocumentLoader.doParse(xmlStreamReader, new XmlContext("pkg", Fs.fileFromPath("/tmp/fake.txt")));
  }
}

Add test for StaxValueLoader of strings.


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

import static org.junit.Assert.assertNotNull;

import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.attribute.UserPrincipalLookupService;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileUtil;
import org.apache.hadoop.hdfs.MiniDFSCluster;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;

public class TestUserPrincipalLookupService {

	private static MiniDFSCluster cluster;
    private static URI clusterUri;

    @BeforeClass
    public static void setUpBeforeClass() throws Exception {
        cluster = startMini(TestFileSystem.class.getName());
        clusterUri = cluster.getFileSystem().getUri();
    }

    @AfterClass
    public static void teardownClass() throws Exception {
        if (cluster != null)
        {
            cluster.shutdown();
        }
    }

    private static MiniDFSCluster startMini(String testName) throws IOException {
        File baseDir = new File("./target/hdfs/" + testName).getAbsoluteFile();
        FileUtil.fullyDelete(baseDir);
        Configuration conf = new Configuration();
        conf.set(MiniDFSCluster.HDFS_MINIDFS_BASEDIR, baseDir.getAbsolutePath());
        MiniDFSCluster.Builder builder = new MiniDFSCluster.Builder(conf);
        MiniDFSCluster hdfsCluster = builder.clusterId(testName).build();
        hdfsCluster.waitActive();
        return hdfsCluster;
    }

    /**
     * Test UserPrincipalLookupService support.
     *
     * @throws IOException
     */
    @Test
    public void testGetPosixViewSetOwner() throws IOException {
        Path rootPath = Paths.get(clusterUri);

        UserPrincipalLookupService lus = rootPath.getFileSystem().getUserPrincipalLookupService();
        assertNotNull(lus);
    }
}

Add unit test for UserPrincipalLookupService


package org.jenkinsci.plugins.relution_publisher.unittest.mocks;

import org.jenkinsci.plugins.relution_publisher.logging.Log;

import java.io.PrintWriter;
import java.io.StringWriter;

public class MockLog implements Log {

    private static final long serialVersionUID = 1L;

    private static String valueOf(final Throwable t) {
        final StringWriter sw = new StringWriter();
        final PrintWriter pw = new PrintWriter(sw);

        t.printStackTrace(pw);

        return sw.toString();
    }

    @Override
    public void write() {
        // Do nothing
    }

    @Override
    public void write(final Class<?> source, final String format, final Object... args) {
        System.out.format(format, args);
        System.out.println();
    }

    @Override
    public void write(final Object source, final String format, final Object... args) {
        System.out.format(format, args);
        System.out.println();
    }

    @Override
    public void write(final Object source, final String format, final Throwable t) {
        System.out.format(format, valueOf(t));
        System.out.println();
    }
}

Add mock log implementation for unit tests


package arez.integration;

import arez.ArezContext;
import arez.annotations.ArezComponent;
import arez.annotations.ContextRef;
import org.testng.annotations.Test;
import static org.testng.Assert.*;

public class ContextRefReferencedInCtorTest
  extends AbstractIntegrationTest
{
  @ArezComponent( allowEmpty = true )
  static abstract class TestComponent
  {
    TestComponent()
    {
      getContext();
    }

    @ContextRef
    abstract ArezContext getContext();
  }

  @Test
  public void scenario()
    throws Throwable
  {
    final IllegalStateException exception =
      expectThrows( IllegalStateException.class, ContextRefReferencedInCtorTest_Arez_TestComponent::new );
    assertEquals( exception.getMessage(), "Method invoked on uninitialized component of type 'TestComponent'" );
  }
}

Add integration test to verify that invariant is correctly generated


package arez.integration.observe;

import arez.Arez;
import arez.ArezContext;
import arez.Environment;
import arez.Function;
import arez.SafeFunction;
import arez.annotations.ArezComponent;
import arez.annotations.Executor;
import arez.annotations.Observe;
import arez.annotations.OnDepsChanged;
import arez.integration.AbstractArezIntegrationTest;
import java.util.ArrayList;
import java.util.Arrays;
import javax.annotation.Nonnull;
import org.testng.annotations.Test;
import static org.testng.Assert.*;

public class TrackInEnvironmentTest
  extends AbstractArezIntegrationTest
{
  @ArezComponent
  public static abstract class TestComponent1
  {
    private final ArrayList<String> _steps;

    TestComponent1( final ArrayList<String> steps )
    {
      _steps = steps;
    }

    @Observe( executor = Executor.APPLICATION, requireEnvironment = true )
    public void render()
    {
      _steps.add( "render1" );
      observeADependency();
    }

    @OnDepsChanged
    final void onRenderDepsChanged()
    {
    }

    @Observe( executor = Executor.APPLICATION, requireEnvironment = false )
    public void render2()
    {
      _steps.add( "render2" );
      observeADependency();
    }

    @OnDepsChanged
    final void onRender2DepsChanged()
    {
    }
  }

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

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

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

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

    final TestComponent1 component = new TrackInEnvironmentTest_Arez_TestComponent1( steps );

    component.render();

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

    component.render2();

    assertEquals( steps, Arrays.asList( "EnvironmentStart", "render1", "EnvironmentEnd", "render2" ) );
  }
}

Add integration test for tracking observer


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

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

import org.junit.jupiter.api.Test;

/**
 * Tests {@link ToBooleanBiFunction}.
 */
public class ToBooleanBiFunctionTest {

    @Test
    public void test() {
        final ToBooleanBiFunction<String, Integer> func = (t, u) -> Integer.valueOf(t).equals(u);
        assertTrue(func.applyAsBoolean("1", 1));
    }
}

Add standalone test for ToBooleanBiFunction.


package org.hyperledger.indy.sdk.demo;

import org.hyperledger.indy.sdk.IndyIntegrationTest;
import org.hyperledger.indy.sdk.agent.Agent;
import org.hyperledger.indy.sdk.agent.AgentResults;
import org.hyperledger.indy.sdk.crypto.Crypto;
import org.hyperledger.indy.sdk.wallet.Wallet;
import org.junit.Assert;
import org.junit.Test;

public class AgentDemoTest extends IndyIntegrationTest {

	@Test
	public void testAgentDemo() throws Exception {
		// 1. Create and open wallets for Alice and Bob
		Wallet.createWallet("no pool", "alice_wallet", null, null, null).get();
		Wallet aliceWallet = Wallet.openWallet("alice_wallet", null, null).get();
		Wallet.createWallet("no pool", "bob_wallet", null, null, null).get();
		Wallet bobWallet = Wallet.openWallet("bob_wallet", null, null).get();

		// 2. Create keys for Alice and Bob
		String aliceKey = Crypto.createKey(aliceWallet, "{}").get();
		String bobKey = Crypto.createKey(bobWallet, "{}").get();

		// 3. Prepare authenticated message from Alice to Bob
		byte[] encryptedAuthMsg = Agent.prepMsg(aliceWallet, aliceKey, bobKey, MESSAGE).get();

		// 4. Parse authenticated message on Bob's side
		{
			AgentResults.ParseMsgResult decryptedAuth = Agent.parseMsg(bobWallet, bobKey, encryptedAuthMsg).get();
			Assert.assertEquals(aliceKey, decryptedAuth.getSenderKey());
			Assert.assertArrayEquals(MESSAGE, decryptedAuth.getMessage());
		}

		// 5. Prepare anonymous message from Bob to Alice
		byte[] encryptedAnonMsg = Agent.prepAnonymousMsg(aliceKey, MESSAGE).get();

		// 6. Parse anonymous message on Alice's side
		{
			AgentResults.ParseMsgResult decryptedAnon = Agent.parseMsg(aliceWallet, aliceKey, encryptedAnonMsg).get();
			Assert.assertNull(decryptedAnon.getSenderKey());
			Assert.assertArrayEquals(MESSAGE, decryptedAnon.getMessage());
		}
	}
}

Add Agent Demo for java wrapper.

Add Agent Demo for java wrapper.

Signed-off-by: Sergey Minaev <322af3f2df10918c6ef5280f56be0b711278b1ae@dsr-company.com>


package edu.harvard.iq.dataverse.engine.command.impl;

import edu.harvard.iq.dataverse.Dataset;
import edu.harvard.iq.dataverse.authorization.Permission;
import edu.harvard.iq.dataverse.authorization.users.User;
import edu.harvard.iq.dataverse.engine.command.CommandContext;
import edu.harvard.iq.dataverse.engine.command.RequiredPermissions;
import edu.harvard.iq.dataverse.engine.command.exception.CommandException;
import edu.harvard.iq.dataverse.engine.command.exception.IllegalCommandException;

/**
 * Deletes a data set.
 * @author michael
 */
@RequiredPermissions( Permission.DeleteDatasetDraft )
public class DeleteDatasetCommand extends DestroyDatasetCommand {

	private final Dataset doomed;

	public DeleteDatasetCommand(Dataset doomed, User aUser) {
		super(doomed, aUser);
		this.doomed = doomed;
	}

	@Override
	protected void executeImpl(CommandContext ctxt) throws CommandException {
		if ( doomed.isReleased() ) {
			throw new IllegalCommandException("Cannot delete a released dataset", this);
		}
		super.executeImpl(ctxt);
	}

}

package edu.harvard.iq.dataverse.engine.command.impl;

import edu.harvard.iq.dataverse.Dataset;
import edu.harvard.iq.dataverse.authorization.Permission;
import edu.harvard.iq.dataverse.authorization.users.User;
import edu.harvard.iq.dataverse.engine.command.AbstractVoidCommand;
import edu.harvard.iq.dataverse.engine.command.CommandContext;
import edu.harvard.iq.dataverse.engine.command.RequiredPermissions;
import edu.harvard.iq.dataverse.engine.command.exception.CommandException;

/**
 * Deletes a data set.
 *
 * @author michael
 */
@RequiredPermissions(Permission.DeleteDatasetDraft)
public class DeleteDatasetCommand extends AbstractVoidCommand {

    private final Dataset doomed;

    public DeleteDatasetCommand(User aUser, Dataset dataset) {
        super(aUser, dataset);
        this.doomed = dataset;
    }

    public DeleteDatasetCommand(Dataset dataset, User aUser) {
        super(aUser, dataset);
        this.doomed = dataset;
    }

    @Override
    protected void executeImpl(CommandContext ctxt) throws CommandException {
        // TODO: REMOVE THIS COMMAND
        // for now it just calls DeleteDatasetVersion
        ctxt.engine().submit(new DeleteDatasetVersionCommand(getUser(), doomed));
    }

}

TODO: REMOVE THIS COMMAND
 for now it just calls DeleteDatasetVersion


// Copyright 2013 Daniel de Kok
//
// 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 eu.danieldk.dictomaton.collections;

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

import com.carrotsearch.junitbenchmarks.AbstractBenchmark;
import org.junit.Assert;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.experimental.categories.Category;

import eu.danieldk.dictomaton.DictionaryBuilderException;
import eu.danieldk.dictomaton.Util;
import eu.danieldk.dictomaton.categories.Benchmarks;

@Category(Benchmarks.class)
public class ImmutableStringIntMapBenchmark extends AbstractBenchmark
{
	private static SortedSet<String> d_words;
	private ImmutableStringIntMap map;

	@BeforeClass
	public static void initializeExpensive() throws DictionaryBuilderException, IOException
	{
		d_words = Util.loadWordList("eu/danieldk/dictomaton/web2-1");
	}

	@Before
	public void initialize() throws DictionaryBuilderException
	{
		ImmutableStringIntMap.Builder builder = new ImmutableStringIntMap.Builder();

		int i = 0;
		for (String word : d_words)
		{
			builder.put(word, i++);
		}

		map = builder.build();
	}

	@Test
	public void getBenchmark()
	{
        int i = 0;
		for (String word : d_words)
            Assert.assertEquals(i++, (int) map.get(word));
	}
}

Add a benchmark for ImmutableStringIntMap.get().


/*
 * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
 * or more contributor license agreements. Licensed under the Elastic License;
 * you may not use this file except in compliance with the Elastic License.
 */
package org.elasticsearch.smoketest;

import org.elasticsearch.test.ESIntegTestCase;

public class PreventFailingBuildIT extends ESIntegTestCase {

    public void testSoThatTestsDoNotFail() {
        // Noop

        // This is required because if tests are not enable no
        // tests will be run in the entire project and all tests will fail.
    }
}

Add noop test to prevent test failures

Tests: Add noop test to prevent test failures

Follow up for elastic/x-pack-elasticsearch@a15338415ac1bd06fdebad1bf93c5e2fec45de5c

Original commit: elastic/x-pack-elasticsearch@c0a46a5977fe0dd28a955c8ab3760f0861b9394a


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

package net.imagej.ops.deconvolve;

import net.imagej.ops.AbstractNamespaceTest;
import net.imagej.ops.DeconvolveOps.RichardsonLucy;

import org.junit.Test;

/**
 * Tests that the ops of the math namespace have corresponding type-safe Java
 * method signatures declared in the {@link DeconvolveNamespace} class.
 *
 * @author Alison Walter
 */
public class DeconvolveNamespaceTest extends AbstractNamespaceTest {

	/** Tests for {@link RichardsonLucy} method convergence. */
	@Test
	public void testRichardsonLucy() {
		assertComplete("deconvolve", DeconvolveNamespace.class, RichardsonLucy.NAME);
	}

}

Add tests for DeconvolveNamespace built-ins