/*
* 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.jackrabbit.oak.plugins.document.util;

import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.UUID;

import org.junit.Test;

public class UTF8EncoderTest {

    private static char[] SURROGATE_PAIR = Character.toChars(0x1f4a9);

    @Test
    public void encodeValid() throws IOException {

        // a a-umlaut euro plane-1-char
        String test = "a \u00E4 \u20ac " + new String(SURROGATE_PAIR);

        byte[] withStringClass = test.getBytes(StandardCharsets.UTF_8);
        byte[] withUtilsClass = UTF8Encoder.encodeAsByteArray(test);
        assertArrayEquals(withStringClass, withUtilsClass);
        assertEquals(test, new String(withUtilsClass, StandardCharsets.UTF_8));
    }

    @Test
    public void encodeInValid() {

        // a a-umlaut euro plane-1-char, second char in surrogate pair missing
        String test = "a \u00E4 \u20ac " + SURROGATE_PAIR[0];

        try {
            UTF8Encoder.encodeAsByteArray(test);
            fail("expected encoding to fail");
        } catch (IOException expected) {
            // expected
        }
    }

    @Test
    public void encodeMultiThreaded() throws InterruptedException {

        int tc = 20;

        Thread[] threads = new Thread[tc];

        for (int i = 0; i < tc; i++) {
            threads[i] = new Thread(new Runnable() {
                @Override
                public void run() {
                    // encode and decode 100 random UUID strings
                    for (int j = 0; j < 100; j++) {
                        String test = UUID.randomUUID().toString();
                        String roundtripped = null;
                        try {
                            byte[] bytes = UTF8Encoder.encodeAsByteArray(test);
                            roundtripped = new String(bytes, StandardCharsets.UTF_8);
                        } catch (IOException exignored) {
                        }
                        assertEquals(test, roundtripped);
                    }

                }
            });
        }
        for (int i = 0; i < tc; i++) {
            threads[i].start();
        }
        for (int i = 0; i < tc; i++) {
            threads[i].join();
        }
    }
}

OAK-7268: Create charset encoding utility that detects malformed input

(add test coverage)

git-svn-id: 67138be12999c61558c3dd34328380c8e4523e73@1824255 13f79535-47bb-0310-9956-ffa450edef68


/**
 * 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.activemq.leveldb.test;

import org.apache.activemq.broker.BrokerService;
import org.apache.activemq.leveldb.LevelDBStore;

import java.io.File;

public class IDERunner {

    public static void main(String[]args) throws Exception {
        BrokerService bs = new BrokerService();
        bs.addConnector("tcp://localhost:61616");
        LevelDBStore store = new LevelDBStore();
        store.setDirectory(new File("target/activemq-data/haleveldb"));
        bs.setPersistenceAdapter(store);
        bs.deleteAllMessages();
        bs.start();
        bs.waitUntilStopped();
    }
}

Add a little main class to the leveldb store module to make it easier to run a broker from your IDE.

git-svn-id: d2a93f579bd4835921162e9a69396c846e49961c@1481014 13f79535-47bb-0310-9956-ffa450edef68


/**
 * Copyright 2016 Palantir Technologies
 *
 * Licensed under the BSD-3 License (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://opensource.org/licenses/BSD-3-Clause
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.palantir.atlasdb.ete;

import java.util.List;

import org.junit.ClassRule;
import org.junit.rules.RuleChain;
import org.junit.runner.RunWith;
import org.junit.runners.Suite;

import com.google.common.collect.ImmutableList;

@RunWith(Suite.class)
@Suite.SuiteClasses({
        CassandraMultinodeEteTest.class, // rename
        TodoEteTest.class,
        DropwizardEteTest.class
})
public class CassandraMultinodeTestSuite {
    // OUR SETUP
}

Revert "Remove mistakenly added file"

Revert "Remove mistakenly added file"

This reverts commit 667de5b07f52f2dbf1f400c95d08966b957e7f67.


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

package org.onosproject.drivers.polatis.netconf;

import org.junit.Before;
import org.onosproject.net.driver.AbstractDriverLoaderTest;
import org.onosproject.ui.UiExtensionServiceAdapter;

/**
 * Polatis drivers loader test.
 */
public class PolatisDriversLoaderTest extends AbstractDriverLoaderTest {

    @Before
    public void setUp() {
        loader = new PolatisDriversLoader();
         ((PolatisDriversLoader) loader).uiExtensionService = new UiExtensionServiceAdapter();
    }
}

Add loader test for the Polatis netconf driver

Change-Id: I557d0374dc87ad6df3a412622a45834dc0982cc5


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

import java.io.File;

import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugins.annotations.LifecyclePhase;
import org.apache.maven.plugins.annotations.Mojo;
import org.apache.maven.plugins.annotations.Parameter;
import org.apache.maven.plugins.annotations.ResolutionScope;
import org.apache.maven.project.MavenProject;
import org.xwiki.tool.extension.util.AbstractExtensionMojo;

/**
 * Generate complete extension descriptor for current artifact.
 *
 * @version $Id$
 * @since 8.4
 */
@Mojo(name = "register", defaultPhase = LifecyclePhase.GENERATE_RESOURCES, requiresDependencyResolution = ResolutionScope.RUNTIME, requiresProject = true, threadSafe = true)
public class RegisterMojo extends AbstractExtensionMojo
{
    /**
     * The directory where the war is generated.
     */
    @Parameter(defaultValue = "${project.build.outputDirectory}", required = true)
    private File outputDirectory;

    /**
     * The maven project.
     */
    @Parameter(defaultValue = "${project}", required = true, readonly = true)
    protected MavenProject project;

    @Override
    public void execute() throws MojoExecutionException
    {
        initializeComponents();

        // Register the WAR
        register();
    }

    private void register() throws MojoExecutionException
    {
        // Make sure "/META-INF/" exists
        File directory = new File(this.outputDirectory, "META-INF");
        directory.mkdirs();

        // Write descriptor
        try {
            saveExtension(new File(directory, "extension.xed"), this.project.getModel());
        } catch (Exception e) {
            throw new MojoExecutionException("Failed to write WAR descriptor", e);
        }
    }
}

XCOMMONS-1098: Introduce Maven plugin to generate extension descriptos in a WAR


package com.blackducksoftware.integration.hub.dataservices.parallel;

import static org.junit.Assert.assertEquals;

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

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.junit.Test;

import com.blackducksoftware.integration.hub.dataservices.ItemTransform;
import com.blackducksoftware.integration.hub.exception.HubItemTransformException;
import com.blackducksoftware.integration.hub.test.TestLogger;

public class ParallelResourceProcessorTest {

	private List<Number> createNumberList() {
		final List<Number> numberList = new ArrayList<>();
		for (int index = 1; index <= 9; index++) {
			numberList.add(new Integer(index));
		}
		return numberList;
	}

	private List<String> createStringList(final List<Number> numberList) {
		final int count = numberList.size();
		final List<String> stringList = new ArrayList<>(count);
		List<String> subStringList = new ArrayList<>(3);
		for (int index = 0; index < count; index++) {
			final Integer integer = new Integer(index + 1);
			subStringList.add(integer.toString());
			if (integer % 3 == 0) {
				final String commaSeparated = StringUtils.join(subStringList, ",");
				stringList.add(commaSeparated);
				subStringList = new ArrayList<>(3);
			}
		}
		return stringList;
	}

	private ItemTransform<List<Number>, String> createTransform() {
		return new ItemTransform<List<Number>, String>() {

			@Override
			public List<Number> transform(final String item) throws HubItemTransformException {
				final String[] numberArray = StringUtils.split(item, ",");

				final List<Number> numberList = new ArrayList<>(numberArray.length);
				for (final String numString : numberArray) {
					final Integer value = NumberUtils.createInteger(numString);
					numberList.add(value);
				}
				return numberList;
			}
		};
	}

	@Test
	public void testParallelProcessing() {
		final TestLogger logger = new TestLogger();
		final ParallelResourceProcessor<Number, String> parallelProcessor = new ParallelResourceProcessor<>(logger);
		parallelProcessor.addTransform(String.class, createTransform());
		final List<Number> numberList = createNumberList();
		final List<String> stringList = createStringList(numberList);
		final List<Number> transformedNumberList = parallelProcessor.process(stringList);
		final int count = numberList.size();
		for (int index = 0; index < count; index++) {
			final Number original = numberList.get(index);
			final Number created = transformedNumberList.get(index);
			assertEquals(original, created);
		}
	}
}

Create the unit test for the ParallelResourceProcessor

Add the class to test the ParallelResourceProcessor in order to test
that the transform is invoked as intended.


/*
 * Copyright (c) 2018, WSO2 Inc. (http://www.wso2.com). All Rights Reserved.
 *
 * This software is the property of WSO2 Inc. and its suppliers, if any.
 * Dissemination of any information or reproduction of any material contained
 * herein is strictly forbidden, unless permitted by WSO2 in accordance with
 * the WSO2 Commercial License available at http://wso2.com/licenses. For specific
 * language governing the permissions and limitations under this license,
 * please see the license as well as any agreement you’ve entered into with
 * WSO2 governing the purchase of this software and any associated services.
 */

package org.wso2.carbon.identity.sso.saml.dao;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.opensaml.saml2.core.Assertion;
import org.wso2.carbon.identity.base.IdentityException;
import org.wso2.carbon.identity.core.persistence.JDBCPersistenceManager;
import org.wso2.carbon.identity.sso.saml.util.SAMLSSOUtil;

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

/**
 * DAO class used to manipulate SAML artifacts data in the database.
 */
public class SAMLArtifactDAO {

    private final static Log log = LogFactory.getLog(SAMLArtifactDAO.class);

    private final static String ARTIFACT_STORE_SQL = "INSERT INTO IDN_SAML2_ARTIFACT_STORE(TYPE_CODE," +
            "ENDPOINT_INDEX, SOURCE_ID, MESSAGE_HANDLER, SAML2_ASSERTION, STATUS) VALUES (?, ?, ?, ?, ?, ?)";

    /**
     * Store SAML artifact in the database.
     *
     * @param typeCode       Type code of the artifact.
     * @param endpointIndex  Endpoint index of the artifact.
     * @param sourceID       Source ID  of the artifact.
     * @param messageHandler Message Handler  of the artifact.
     * @param samlAssertion  Generated SAML assertion.
     * @param status         Status of the artifact. {INITIATED, RETRIEVED}
     * @throws IdentityException
     */
    public void storeArtifact(byte[] typeCode, byte[] endpointIndex, byte[] sourceID, byte[] messageHandler,
                              Assertion samlAssertion, String status) throws IdentityException {

        try (Connection connection = JDBCPersistenceManager.getInstance().getDBConnection();
             PreparedStatement preparedStatement = connection.prepareStatement(ARTIFACT_STORE_SQL)) {

            preparedStatement.setBytes(1, typeCode);
            preparedStatement.setBytes(2, endpointIndex);
            preparedStatement.setBytes(3, sourceID);
            preparedStatement.setBytes(4, messageHandler);
            preparedStatement.setString(5, SAMLSSOUtil.marshall(samlAssertion));
            preparedStatement.setString(6, status);

            preparedStatement.executeUpdate();
            connection.commit();

        } catch (SQLException e) {
            log.error("Error while storing SAML artifact data: ", e);
        }
    }
}

Add DAO class for SAML artifacts

Add DAO class for SAML artifacts


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

import com.google.gwt.i18n.client.Constants;

public interface SqlEditorConstants extends Constants {

    @DefaultStringValue("SQL file")
    String newSqlWizardTitle();
}

Add constants file for the SQL resource provider


/**
* Licensed to niosmtp developers ('niosmtp') under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* niosmtp 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 me.normanmaurer.niosmtp.delivery.impl;

/**
 * LMTP-Servers MUST support PIPELINING according the RFC. So this
 * configuration force them todo so by return {@link PipeliningMode#DEPEND} via the
 * {@link #getPipeliningMode()} method.
 *
 * @author Maurer
 *
 */
public class StrictLMTPDeliveryAgentConfig extends SMTPDeliveryAgentConfigImpl{

    /**
     * Returns {@link PipeliningMode#DEPEND}
     */
    @Override
    public PipeliningMode getPipeliningMode() {
        return PipeliningMode.DEPEND;
    }

    /**
     * Throws an {@link IllegalArgumentException} if set it to something
     * different then {@link PipeliningMode#DEPEND}
     */
    @Override
    public void setPipeliningMode(PipeliningMode pipeliningMode) {
        if (pipeliningMode != PipeliningMode.DEPEND) {
            throw new IllegalArgumentException("LMTP-Servers MUST implement PIPELINING");
        }
    }

}

Add some configuration implementation for LMTP


package info.elexis.server.core.connector.elexis.jpa.model.annotated;

import java.io.Serializable;

public class UserconfigId implements Serializable {

	private static final long serialVersionUID = -654453520781303717L;

	private String ownerId;
	private String param;

	public UserconfigId() {
	}

	public UserconfigId(final String ownerId, final String param) {
		this.ownerId = ownerId;
		this.param = param;
	}

	public String getOwner() {
		return ownerId;
	}

	public String getParam() {
		return param;
	}

	public void setOwner(String ownerId) {
		this.ownerId = ownerId;
	}

	public void setParam(String param) {
		this.param = param;
	}
}

[14494] Fix wrong loading of Userconfig entities, missing class


Add invalid seat test to Table

Add invalid seat test to Table


/**
 * 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.hadoop.mapreduce.jobhistory;

import org.apache.avro.util.Utf8;
import org.apache.hadoop.mapreduce.JobID;

@SuppressWarnings("deprecation")
public class JobQueueChangeEvent implements HistoryEvent {
  private JobQueueChange datum = new JobQueueChange();

  public JobQueueChangeEvent(JobID id, String queueName) {
    datum.jobid = new Utf8(id.toString());
    datum.jobQueueName = new Utf8(queueName);
  }

  JobQueueChangeEvent() { }

  @Override
  public EventType getEventType() {
    return EventType.JOB_QUEUE_CHANGED;
  }

  @Override
  public Object getDatum() {
    return datum;
  }

  @Override
  public void setDatum(Object datum) {
    this.datum = (JobQueueChange) datum;
  }

  /** Get the Job ID */
  public JobID getJobId() {
    return JobID.forName(datum.jobid.toString());
  }

  /** Get the new Job queue name */
  public String getJobQueueName() {
    if (datum.jobQueueName != null) {
      return datum.jobQueueName.toString();
    }
    return null;
  }

}

Add missing file for MAPREDUCE-5732

Add missing file for MAPREDUCE-5732

git-svn-id: 18f68cb356f2bf53a217c39a7af1470588d83bce@1562642 13f79535-47bb-0310-9956-ffa450edef68


package com.fasterxml.jackson.core.read;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonToken;

public class NextNameParserTest
    extends com.fasterxml.jackson.core.BaseTest
{
    public void testBasicNextNameWithReader() throws Exception
    {
        _testBasicNextName(MODE_READER);
    }

    public void testBasicNextNameWithStream() throws Exception
    {
        _testBasicNextName(MODE_INPUT_STREAM);
        _testBasicNextName(MODE_INPUT_STREAM_THROTTLED);
    }

    private void _testBasicNextName(int mode) throws Exception
    {
        final String DOC = aposToQuotes(
"{ 'data' : { 'primary' : 15, 'vector' : [ 'yes', false ]  },\n"
+"  'array' : [ true,   {'message':'hello', 'value' : 42, 'misc' : [1, 2] }, null, 0.25 ]\n"
+"}");

        JsonParser p = createParser(mode, DOC);

        assertToken(JsonToken.START_OBJECT, p.nextToken());

        assertToken(JsonToken.FIELD_NAME, p.nextToken());
        assertEquals("data", p.currentName());
        assertToken(JsonToken.START_OBJECT, p.nextToken());

        assertEquals("primary", p.nextFieldName());
        assertToken(JsonToken.VALUE_NUMBER_INT, p.nextToken());
        assertEquals(15, p.getIntValue());

        assertEquals("vector", p.nextFieldName());
        assertToken(JsonToken.START_ARRAY, p.nextToken());
        assertToken(JsonToken.VALUE_STRING, p.nextToken());
        assertEquals("yes", p.getText());
        assertToken(JsonToken.VALUE_FALSE, p.nextToken());
        assertToken(JsonToken.END_ARRAY, p.nextToken());

        assertToken(JsonToken.END_OBJECT, p.nextToken());

        assertEquals("array", p.nextFieldName());
        assertToken(JsonToken.START_ARRAY, p.nextToken());
        assertToken(JsonToken.VALUE_TRUE, p.nextToken());

        assertToken(JsonToken.START_OBJECT, p.nextToken());
        assertEquals("message", p.nextFieldName());
        assertToken(JsonToken.VALUE_STRING, p.nextToken());
        assertEquals("hello", p.getText());
        assertEquals("value", p.nextFieldName());
        assertToken(JsonToken.VALUE_NUMBER_INT, p.nextToken());
        assertEquals(42, p.getIntValue());
        assertEquals("misc", p.nextFieldName());

        assertToken(JsonToken.START_ARRAY, p.nextToken());
        assertToken(JsonToken.VALUE_NUMBER_INT, p.nextToken());
        assertEquals(1, p.getIntValue());
        assertToken(JsonToken.VALUE_NUMBER_INT, p.nextToken());
        assertEquals(2, p.getIntValue());
        assertToken(JsonToken.END_ARRAY, p.nextToken());
        assertToken(JsonToken.END_OBJECT, p.nextToken());

        assertToken(JsonToken.VALUE_NULL, p.nextToken());
        assertToken(JsonToken.VALUE_NUMBER_FLOAT, p.nextToken());

        assertToken(JsonToken.END_ARRAY, p.nextToken());

        assertToken(JsonToken.END_OBJECT, p.nextToken());

        p.close();
    }
}

Add a unit test for `JSonParser.nextName()`


package pt.fccn.mobile.arquivo.tests.pagesearch;

import static org.hamcrest.CoreMatchers.containsString;
import static org.hamcrest.MatcherAssert.assertThat;

import org.junit.Test;
import org.openqa.selenium.By;

import pt.fccn.arquivo.selenium.Retry;
import pt.fccn.arquivo.selenium.WebDriverTestBaseParalell;

/**
 *
 * @author Ivo Branco <ivo.branco@fccn.pt>
 *
 */
public class PageSearchQuerySuggestionTest extends WebDriverTestBaseParalell {

	public PageSearchQuerySuggestionTest(String os, String version, String browser, String deviceName,
			String deviceOrientation) {
		super(os, version, browser, deviceName, deviceOrientation);
	}

	@Test
	@Retry
	public void pageSearchTest() {
		run("Search with testre", () -> {
			driver.findElement(By.id("txtSearch")).clear();
			driver.findElement(By.id("txtSearch")).sendKeys("testre");
			driver.findElement(By.xpath("//*[@id=\"buttonSearch\"]/button")).click();
		});

		assertThat("Verify if a suggestion is presented",
				driver.findElement(By.xpath("//*[@id=\"second-column\"]/div[1]/span/a")).getText(),
				containsString("teste"));
	}

}

Add new page search query suggestion test


package org.ovirt.engine.core.common.businessentities;

import java.util.Date;

import org.ovirt.engine.core.compat.Guid;

import com.google.gwt.user.client.rpc.SerializationException;
import com.google.gwt.user.client.rpc.SerializationStreamReader;
import com.google.gwt.user.client.rpc.SerializationStreamWriter;

/**
 * We need this custom field serializer for {@link RepoImage} because otherwise
 * the GWT compiler will optimize out some of the fields of the entity and that
 * causes exceptions in the standard deserialization mechanism in the server
 * side.
 */
public class RepoImage_CustomFieldSerializer {

    public static RepoImage instantiate(SerializationStreamReader reader) throws SerializationException {
        return new RepoImage();
    }

    public static void serialize(SerializationStreamWriter writer, RepoImage instance) throws SerializationException {
        writer.writeObject(instance.getStoragePoolId());
        writer.writeObject(instance.getStoragePoolStatus());
        writer.writeObject(instance.getVdsStatus());
        writer.writeObject(instance.getRepoDomainId());
        writer.writeObject(instance.getStorageDomainStatus());
        writer.writeString(instance.getRepoImageId());
        writer.writeString(instance.getRepoImageName());
        writer.writeLong(instance.getSize());
        writer.writeObject(instance.getDateCreated());
        writer.writeLong(instance.getLastRefreshed());
        writer.writeObject(instance.getFileType());
    }

    public static void deserialize(SerializationStreamReader reader, RepoImage instance) throws SerializationException {
        instance.setStoragePoolId((Guid) reader.readObject());
        instance.setStoragePoolStatus((StoragePoolStatus) reader.readObject());
        instance.setVdsStatus((VDSStatus) reader.readObject());
        instance.setRepoDomainId((Guid) reader.readObject());
        instance.setStorageDomainStatus((StorageDomainStatus) reader.readObject());
        instance.setRepoImageId(reader.readString());
        instance.setRepoImageName(reader.readString());
        instance.setSize(reader.readLong());
        instance.setDateCreated((Date) reader.readObject());
        instance.setLastRefreshed(reader.readLong());
        instance.setFileType((ImageFileType) reader.readObject());
    }

}

frontend: Add custom field serializer for RepoImage

This is a workaround to resolve some current issues with GWT RPC
serialization.

Change-Id: I137d47dee58dce90a66a3c4accfe75e146223749
Bug-Url: https://bugzilla.redhat.com/988021
Signed-off-by: Juan Hernandez <59e5b8140de97cc91c3fb6c5342dce948469af8c@redhat.com>


package net.tascalate.concurrent;

import static org.junit.Assert.assertTrue;

import java.time.Duration;
import java.util.concurrent.TimeUnit;

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

public class OrTimeoutExceptionTests {

    private TaskExecutorService executor;

    @Before
    public void setUp() {
        executor = TaskExecutors.newFixedThreadPool(4);
    }

    @After
    public void tearDown() {
        executor.shutdown();
    }

    @Test
    public void testExceptionalOrTimeout() {
        Promise<?> p =
        CompletableTask
            .submit(this::doTask, executor)
            .orTimeout(Duration.ofSeconds(5L))
            .whenComplete((res, err) -> {
                if (res != null)
                    System.out.println("RESULT: " + res);
                else
                    System.out.println("ERROR: " + err.getMessage());
             });
        p.join();
    }

    private String doTask () throws Exception {
        TimeUnit.SECONDS.sleep(3);
        if (null != System.out)
            throw new Exception("my error");
        return "executed ok";
    }

}

Test for exceptional handling of Promise.orTimeout


package year2012;

import java.util.Scanner;

/**
 *
UPC Check Digit

 *
The most common form of Universal Product Code (UPC) is UPC-A
 * which has 12 digits arranged to make a unique number.
 * The twelfth digit is a check digit calculated
 * based on the values in digits one through eleven.
 * Calculate a UPC-A check digit given the eleven digits.

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

    public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);

        String input = scanner.nextLine();
        char[] inputChars = input.toCharArray();

        scanner.close();

        if (input.length() != 11)
            throw new IllegalArgumentException("Input must be 11 digits only");

        int checkNumber = 0;

        //Add the digits in the odd numbered positions (first, third, fifth, ...)

        int sumOddDigits = 0;

        for (int i = 0; i < 11; i += 2) {

            int digit = Character.getNumericValue(inputChars[i]);

            sumOddDigits += digit;

        }

        checkNumber += sumOddDigits;

        //Multiply the above sum by three.

        checkNumber *= 3;

        //Add the digits in the even numbered positions (second, fourth, sixth, …) to the total from above

        int sumEvenDigits = 0;

        for (int i = 0; i < 11; i++) {

            if (i % 2 == 0)
                continue;

            int digit = Character.getNumericValue(inputChars[i]);

            sumEvenDigits += digit;

        }

        checkNumber += sumEvenDigits;

        //Find the remainder when you divide the result by ten

        int remainder = (checkNumber % 10);

        //The check digit is zero if the remainder is zero

        if (remainder == 0)
            checkNumber = 0;
        else ////Otherwise subtract the remainder from ten to get the check digit.
            checkNumber = 10 - remainder;

        System.out.println("Check digit for " + input + " is " + checkNumber);

    }

}

Add UPC Check Digit (2012) solution

Add UPC Check Digit (2012) solution


package org.svetovid.demo;

import org.svetovid.io.Svetovid;
import org.svetovid.util.Stopwatch;

public class Factorial {

    public static void main(String[] args) {

        // Ask for n
        int n = Svetovid.in.readInt("Factorial of which number would you like me to calculate? ");

        // Start the calculation timing
        Stopwatch stopwatch = new Stopwatch();

        // Calculate the factorial
        long factorial = 1;
        for (int i = 2; i < n; i++) {
            factorial = i * factorial;
        }

        // Print the result
        double time = stopwatch.time();
        Svetovid.out.writeln("The factorial is:", factorial);
        Svetovid.out.writeln("It took", time, "seconds to calculate");

    }
}

Add a demo for the Stopwatch class

Add a demo for the Stopwatch class


package leetcode.convert_sorted_array_to_binary_search_tree;

import common.TreeNode;

public class Solution {
	public TreeNode sortedArrayToBST(int[] num, int from, int to) {
		if(from == to) return null;
		TreeNode root;
		int mid = from + (to - from) / 2;
		root = new TreeNode(num[mid]);
		root.left = sortedArrayToBST(num, from, mid);
		root.right = sortedArrayToBST(num, mid + 1, to);
		return root;
	}

	public TreeNode sortedArrayToBST(int[] num) {
        if(num == null) return null;
        return sortedArrayToBST(num, 0, num.length);
    }

	public static void inOrder(TreeNode node){
		if(node != null){
			inOrder(node.left);
			System.err.print(node.val + " ");
			inOrder(node.right);
		}
	}

	public static void main(String[] args){
		inOrder(new Solution().sortedArrayToBST(new int[]{}));
	}
}

Add java solution for 108. Convert Sorted Array to Binary Search Tree

108. Convert Sorted Array to Binary Search Tree: https://leetcode.com/problems/convert-sorted-array-to-binary-search-tree/


package com.github.bedrin.jdbc.sniffer;

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

import java.lang.ref.WeakReference;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;

import static org.junit.Assert.*;

public class SnifferListenersTest extends BaseTest {

    @Test
    public void testSpyRemovedOnClose() throws Exception {
        Spy spy = Sniffer.spy();
        spy.close();

        for (WeakReference<Spy> spyReference : Sniffer.registeredSpies()) {
            if (spyReference.get() == spy) fail("Spy was not removed from Sniffer observers");
        }

    }

    @Test
    @Ignore("H2 doesn't seem to support batch queries against DUAL table")
    public void testBatchIsLogged() throws Exception {
        try { try (Spy spy = Sniffer.expectNever();
             Connection connection = DriverManager.getConnection("sniffer:jdbc:h2:~/test", "sa", "sa");
             PreparedStatement preparedStatement = connection.prepareStatement("SELECT 1 FROM DUAL WHERE 1 = ?")) {
            preparedStatement.setLong(1, 1);
            preparedStatement.addBatch();
            preparedStatement.setLong(1, 2);
            preparedStatement.addBatch();
            preparedStatement.executeBatch();
        } } catch (WrongNumberOfQueriesError e) {
            assertNotNull(e);
        }

    }

}

Test that spy is removed from sniffer when closed


// Copyright (c) 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

package org.chromium.components.navigation_interception;

import org.chromium.base.CalledByNative;

public class NavigationParams {
    // Target url of the navigation.
    public final String url;
    // True if the the navigation method is "POST".
    public final boolean isPost;
    // True if the navigation was initiated by the user.
    public final boolean hasUserGesture;
    // Page transition type (e.g. link / typed).
    public final int pageTransitionType;
    // Is the navigation a redirect (in which case url is the "target" address).
    public final boolean isRedirect;

    public NavigationParams(String url, boolean isPost, boolean hasUserGesture,
            int pageTransitionType, boolean isRedirect) {
        this.url = url;
        this.isPost = isPost;
        this.hasUserGesture = hasUserGesture;
        this.pageTransitionType = pageTransitionType;
        this.isRedirect = isRedirect;
    }

    @CalledByNative
    public static NavigationParams create(String url, boolean isPost, boolean hasUserGesture,
            int pageTransitionType, boolean isRedirect) {
        return new NavigationParams(url, isPost, hasUserGesture, pageTransitionType,
                isRedirect);
    }
}

[android] Add param struct to navigation interception Java code.

This is a prerequisite to refactoring the navigation interception
Java code to use a class to pass around parameters.

TBR=jknotten@chromium.org
BUG=None
TESTS=components_unittests,AndroidWebViewTests
NOTRY=true

Review URL: https://chromiumcodereview.appspot.com/12095061

git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@179669 0039d316-1c4b-4281-b951-d872f2087c98


/*
 * Copyright 2017, TeamDev Ltd. All rights reserved.
 *
 * Redistribution and use in source and/or binary forms, with or without
 * modification, must retain the above copyright notice and the following
 * disclaimer.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

package org.spine3.string;

import org.junit.Test;
import org.spine3.time.ZoneOffset;

import static org.junit.Assert.assertEquals;
import static org.spine3.time.ZoneOffsets.ofHoursMinutes;

/**
 * @author Alexander Yevsyukov
 */
public class ZoneOffsetStringifierShould {

    private static final Stringifier<ZoneOffset> stringifier = TimeStringifiers.forZoneOffset();

    @Test
    public void convert_back_and_forth() {
        final ZoneOffset positive = ofHoursMinutes(7, 40);
        final ZoneOffset negative = ofHoursMinutes(-3, -45);

        assertEquals(positive, stringifier.reverse()
                                          .convert(stringifier.convert(positive)));
        assertEquals(negative, stringifier.reverse()
                                          .convert(stringifier.convert(negative)));
    }
}

Add test for zone offset stringifier

Add test for zone offset stringifier


/*
 * Copyright (c) 2014, Colorado State University All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * 1. Redistributions of source code must retain the above copyright notice,
 * this list of conditions and the following disclaimer. 2. Redistributions in
 * binary form must reproduce the above copyright notice, this list of
 * conditions and the following disclaimer in the documentation and/or other
 * materials provided with the distribution.
 *
 * This software is provided by the copyright holders and contributors "as is"
 * and any express or implied warranties, including, but not limited to, the
 * implied warranties of merchantability and fitness for a particular purpose
 * are disclaimed. In no event shall the copyright holder or contributors be
 * liable for any direct, indirect, incidental, special, exemplary, or
 * consequential damages (including, but not limited to, procurement of
 * substitute goods or services; loss of use, data, or profits; or business
 * interruption) however caused and on any theory of liability, whether in
 * contract, strict liability, or tort (including negligence or otherwise)
 * arising in any way out of the use of this software, even if advised of the
 * possibility of such damage.
 */

/**
 * Utility classes for parsing FASTA, SAM/BAM, GenBank, and other sequence data
 * formats to be stored in Mendel
 *
 * @author ctolooee
 *
 */
package mendel.parse;

Add mednel.parse package for biological files


/*
 * Copyright 2015 Open mHealth
 *
 * 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.openmhealth.shimmer.common.service;

import org.openmhealth.shimmer.common.domain.DataPointRequest;
import org.openmhealth.shimmer.common.domain.RequestEntityBuilder;

/**
 * FIXME
 *
 * @author Emerson Farrugia
 */
public interface RequestEntityAssembler {

    /**
     * FIXME Assembles a request entity builder.
     *
     * @param builder the request entity builder to assemble
     * @return the builder
     */
    RequestEntityBuilder assemble(RequestEntityBuilder builder, DataPointRequest request);
}

Add a skeletal request entity assembler

Add a skeletal request entity assembler


package me.jacobcrofts.simplestructureloader.listeners;

import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerQuitEvent;

import me.jacobcrofts.simplestructureloader.managers.SelectionManager;

public class TrafficListener implements Listener {

	private final SelectionManager manager;

	public TrafficListener(SelectionManager manager) {
		this.manager = manager;
	}

	@EventHandler(priority = EventPriority.HIGH)
	public void onPlayerQuit(PlayerQuitEvent event) {
		this.manager.unregister(event.getPlayer());
	}

}

Add feature: upon logout, selections are forgotten


package io.dropwizard.testing.junit;

import com.google.common.collect.ImmutableMap;
import com.sun.jersey.api.client.Client;
import io.dropwizard.Application;
import io.dropwizard.Configuration;
import io.dropwizard.setup.Bootstrap;
import io.dropwizard.setup.Environment;
import org.junit.Assert;
import org.junit.ClassRule;
import org.junit.Test;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.util.Map;

public class DropwizardAppRuleWithoutConfigTest {

    @ClassRule
    public static final DropwizardAppRule<Configuration> RULE = new DropwizardAppRule<>(TestApplication.class, null);

    Client client = new Client();

    @Test
    public void runWithoutConfigFile() {
        Map response = client.resource("http://localhost:" + RULE.getLocalPort() + "/test").get(Map.class);
        Assert.assertEquals(ImmutableMap.of("color", "orange"), response);
    }

    static class TestApplication extends Application<Configuration> {
        @Override
        public void initialize(Bootstrap<Configuration> bootstrap) {
        }

        @Override
        public void run(Configuration configuration, Environment environment) throws Exception {
            environment.jersey().register(new TestResource());
        }
    }

    @Path("test")
    @Produces(MediaType.APPLICATION_JSON)
    public static class TestResource {
        @GET
        public Response get() {
            return Response.ok(ImmutableMap.of("color", "orange")).build();
        }
    }
}

Test for DropwizardAppRule with no (null) configPath


/*
 * Copyright 2009-2010 by The Regents of the University of California
 * 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 from
 *
 *     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 edu.uci.ics.hyracks.api.dataflow.value;

import org.json.JSONException;
import org.json.JSONObject;

public interface JSONSerializable {
    /**
     * Returns the JSON representation of the object.
     *
     * @return A new JSONObject instance representing this Java object.
     */
    public JSONObject toJSON() throws JSONException;
}

Implement an interface to represent all objects that can be JSON serialized.

git-svn-id: 45400e483b316c70cab0969c275555ef2720fd29@2848 123451ca-8445-de46-9d55-352943316053


/*
 *    Copyright 2019 West Coast Informatics, LLC
 */
package org.ihtsdo.otf.mapping.services.helpers;

import java.util.Properties;

// TODO: Auto-generated Javadoc
/**
 * Config utility integration tests.
 */
public class ConfigUtilityIntegrationTest {

	/**
	 * Test email.
	 *
	 * @throws Exception the exception
	 */
	// @Test
	public void testEmail() throws Exception {
		final Properties details = new Properties();
		details.setProperty("mail.enabled", "true");
		ConfigUtility.getConfigProperties().setProperty("mail.smtp.user", "support@westcoastinformatics.com");
		ConfigUtility.getConfigProperties().setProperty("mail.smtp.password", "EDIT_THIS");
		details.setProperty("mail.smtp.host", "smtp.gmail.com");
		details.setProperty("mail.smtp.port", "587");
		details.setProperty("mail.smtp.starttls.enable", "true");
		details.setProperty("mail.smtp.auth", "true");

		ConfigUtility.sendEmail("Test Email", "support@westcoastinformatics.com", "test@westcoastinformatics.com",
				"Test support email.", details, true);

	}
}

Add harness for testing sending email

Add harness for testing sending email


package com.peterphi.std.guice.hibernate.webquery.impl;

import org.apache.commons.lang.StringUtils;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class PropertyWrapper
{
	public final Class<?> clazz;

	public final String name;

	public Field field;

	public Method getter;
	public Method setter;

	public PropertyWrapper(final Class<?> clazz, final String name)
	{
		this.clazz = clazz;
		this.name = name;

		{
			final String getterName = "get" + name;
			final String setterName = "set" + name;

			for (Method method : clazz.getMethods())
			{
				if (getter == null && StringUtils.equalsIgnoreCase(method.getName(), getterName))
					getter = method;
				else if (setter == null && StringUtils.equalsIgnoreCase(method.getName(), setterName))
					setter = method;
			}
		}

		if (getter == null && setter == null)
		{
			try
			{
				field = clazz.getField(name);
			}
			catch (NoSuchFieldException e)
			{
				throw new RuntimeException("Unable to find field/getter for " + clazz + " property " + name, e);
			}
		}
	}

	public void set(final Object object, Object value)
	{
		try
		{
			if (field != null)
				field.set(object, value);
			else if (setter != null)
				setter.invoke(object, value);
			else
				throw new IllegalArgumentException("No Field or Setter stored!");
		}
		catch (IllegalAccessException | InvocationTargetException e)
		{
			throw new RuntimeException("Error calling field.set or setter.invoke", e);
		}
	}

	public Object get(final Object object)
	{
		try
		{
			if (field != null)
				return field.get(object);
			else if (setter != null)
				return getter.invoke(object);
			else
				throw new IllegalArgumentException("No Field or Getter stored!");
		}
		catch (IllegalAccessException | InvocationTargetException e)
		{
			throw new RuntimeException("Error calling field.get or getter.invoke", e);
		}
	}

	public Class getReturnType()
	{
		if (field != null)
			return field.getType();
		else if (setter != null)
			return getter.getReturnType();
		else
			throw new IllegalArgumentException("No Field or Getter stored!");
	}
}

Add helper class that calls a getter/setter on a java field


package net.imagej.ops.views;

import net.imagej.ops.view.ViewOps;
import net.imagej.ops.view.ViewOps.DropSingletonDimensions;
import net.imglib2.RandomAccessibleInterval;
import net.imglib2.view.Views;

import org.scijava.plugin.Plugin;

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

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

}

Add default implementation of DropSingletonDimension interace.


package org.stagemonitor.core.instrument;

import net.bytebuddy.matcher.ElementMatcher;

public class ReflectionClassLoaderMatcher extends ElementMatcher.Junction.AbstractBase<ClassLoader> {

	public static ElementMatcher.Junction.AbstractBase<ClassLoader> isReflectionClassLoader() {
		return new ReflectionClassLoaderMatcher();
	}

	@Override
	public boolean matches(ClassLoader target) {
		return target != null && "sun.reflect.DelegatingClassLoader".equals(target.getClass().getName());
	}
}

Exclude classes loaded by sun.reflect.DelegatingClassLoader


package org.apache.beam.runners.spark.structuredstreaming.utils;

import java.util.ArrayList;
import java.util.List;
import org.apache.beam.runners.spark.structuredstreaming.translation.helpers.EncoderHelpers;
import org.apache.beam.sdk.coders.VarIntCoder;
import org.apache.spark.sql.SparkSession;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;

@RunWith(JUnit4.class)
/**
 * Test of the wrapping of Beam Coders as Spark ExpressionEncoders.
 */
public class EncodersTest {

  @Test
  public void beamCoderToSparkEncoderTest() {
    SparkSession sparkSession = SparkSession.builder().appName("beamCoderToSparkEncoderTest")
        .master("local[4]").getOrCreate();
    List<Integer> data = new ArrayList<>();
    data.add(1);
    data.add(2);
    data.add(3);
//    sparkSession.createDataset(data, EncoderHelpers.fromBeamCoder(VarIntCoder.of()));
    sparkSession.createDataset(data, EncoderHelpers.genericEncoder());
  }
}

[BEAM-8470] Add a simple spark native test to test Beam coders wrapping into Spark Encoders


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

import com.intellij.lang.HelpID;
import uk.co.reecedunn.intellij.plugin.xquery.ast.xquery.XQueryFile;
import uk.co.reecedunn.intellij.plugin.xquery.ast.xquery.XQueryNCName;
import uk.co.reecedunn.intellij.plugin.xquery.ast.xquery.XQueryVarName;
import uk.co.reecedunn.intellij.plugin.xquery.ast.xquery.XQueryVarRef;
import uk.co.reecedunn.intellij.plugin.xquery.findUsages.XQueryFindUsagesProvider;
import uk.co.reecedunn.intellij.plugin.xquery.tests.parser.ParserTestCase;

import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import static uk.co.reecedunn.intellij.plugin.xquery.functional.PsiTreeWalker.children;
import static uk.co.reecedunn.intellij.plugin.xquery.functional.PsiTreeWalker.descendants;

public class XQueryFindUsagesProviderTest extends ParserTestCase {
    public void testNCName() {
        final XQueryFindUsagesProvider provider = new XQueryFindUsagesProvider();

        XQueryFile file = parseResource("tests/parser/xquery-1.0/VarRef.xq");
        XQueryVarRef varRef = descendants(file).findFirst(XQueryVarRef.class).get();
        XQueryVarName varName = children(varRef).findFirst(XQueryVarName.class).get();
        XQueryNCName ncName = children(varName).findFirst(XQueryNCName.class).get();

        assertThat(provider.canFindUsagesFor(ncName), is(true));
        assertThat(provider.getHelpId(ncName), is(HelpID.FIND_OTHER_USAGES));
        assertThat(provider.getType(ncName), is(""));
        assertThat(provider.getDescriptiveName(ncName), is("one"));
        assertThat(provider.getNodeText(ncName, true), is("one"));
        assertThat(provider.getNodeText(ncName, false), is("one"));
    }
}

Add a test case for XQueryFindUsagesProvider.


package com.terrabeata.wcm.siteRenderer.internal.site;

import javax.jcr.Node;
import javax.jcr.Property;

import org.apache.sling.api.resource.Resource;
import org.apache.sling.api.resource.ResourceResolver;

public class DefaultConfigurations {
	private static final String PERSISTENT_DATA_PATH = "/var/siteRender/intallDate";

	public void createDefaultConfigurations(ResourceResolver resourceResolver) {
		Resource installData = resourceResolver.getResource("/var/siteRender/i001");
		if (installData != null) {

		}
	}

	public void createDefaultQueue(ResourceResolver resourceResolver) {

	}
}

Create stub for configuration creating class


/**
 *
 */
package org.slc.sli.modeling.rest;

import static org.junit.Assert.*;

import java.util.ArrayList;

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

/**
 * JUnit test for Option class.
 *
 * @author wscott
 *
 */
public class OptionTest {

    private Option option; //class under test

    private static final String VALUE = "option-test";
    private static final ArrayList<Documentation> DOC = new ArrayList<Documentation>(0);

    @Before
    public void setup() {
        option = new Option(VALUE, DOC);
    }

    @Test (expected = NullPointerException.class)
    public void testNullValue() {
        new Option(null, DOC);
    }

    @Test (expected = NullPointerException.class)
    public void testNullDocumentation() {
        new Option(VALUE, null);
    }

    @Test
    public void testGetValue() {
        assertEquals(VALUE, option.getValue());
    }

    @Test
    public void testGetDocumentation() {
        assertEquals(DOC, option.getDocumentation());
    }

}

Add JUnit test for Option class in rest modeling module.


package de.asw.courses.web2016.demo.backend.el;

import javax.el.ELContext;
import javax.el.ELManager;
import javax.el.ELProcessor;
import javax.ws.rs.GET;
import javax.ws.rs.Path;

@Path("/el")
public class ElExampleResource {

	@GET
	public String evaluatePath() {

		Person person = new Person("Luke", new Address("Tatooine Way", "133", "232423"));

		ELProcessor processor = new ELProcessor();

		ELContext context = processor.getELManager().getELContext();
		context.getVariableMapper().setVariable("person",
				ELManager.getExpressionFactory().createValueExpression(person, Person.class));

		Object address = processor.getValue("person.address.street", String.class);

		return address.toString();
	}

	public static class Person {
		String name;
		Address address;

		public Person(String name, Address address) {
			this.name = name;
			this.address = address;
		}

		public Address getAddress() {
			return address;
		}

		public void setAddress(Address address) {
			this.address = address;
		}

		public String getName() {
			return name;
		}

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

	}

	public static class Address {
		String street;
		String houseNo;
		String zipCode;

		public Address(String street, String houseNo, String zipCode) {
			this.street = street;
			this.houseNo = houseNo;
			this.zipCode = zipCode;
		}

		public String getStreet() {
			return street;
		}

		public void setStreet(String street) {
			this.street = street;
		}

		public String getHouseNo() {
			return houseNo;
		}

		public void setHouseNo(String houseNo) {
			this.houseNo = houseNo;
		}

		public String getZipCode() {
			return zipCode;
		}

		public void setZipCode(String zipCode) {
			this.zipCode = zipCode;
		}
	}
}

Add example for using EL Expressions in code


package com.sap.cloud.lm.sl.cf.core.activiti;

import static org.junit.Assert.assertEquals;

import org.junit.Test;
import org.mockito.Mock;

public class ActivitiActionFactoryTest {

    private static final String RESUME_ACTION_ID = "resume";
    private static final String RETRY_ACTION_ID = "retry";
    private static final String USER_ID = "test-user";
    private static final String ABORT_ACTION_ID = "abort";
    @Mock
    ActivitiFacade facade;

    @Test
    public void testAbortAction() {
        testAction(ABORT_ACTION_ID, AbortActivitiAction.class);
    }

    @Test
    public void testRetryAction() {
        testAction(RETRY_ACTION_ID, RetryActivitiAction.class);
    }

    @Test
    public void testResumeAction() {
        testAction(RESUME_ACTION_ID, ResumeActivitiAction.class);
    }

    private void testAction(String actionId, Class<? extends ActivitiAction> actionClass) {
        ActivitiAction action = ActivitiActionFactory.getAction(actionId, facade, USER_ID);
        assertEquals(action.getClass(), actionClass);
        action = ActivitiActionFactory.getAction(actionId.toUpperCase(), facade, USER_ID);
        assertEquals(action.getClass(), actionClass);
    }
}

Add unit test for ActivitiActionFactory

Add unit test for ActivitiActionFactory


package com.easternedgerobotics.rov.control;

public final class AnalogToPowerLevel {
    private AnalogToPowerLevel() {
    }

    /**
     * Used to scale the value to the [0, 110] range.
     */
    private static final int SCALAR = 110;

    /**
     * Used to shift the value to the [-5, 105] range.
     */
    private static final int OFFSET = 5;

    /**
     * Lower bound for the result.
     */
    private static final int MINIMUM = 0;

    /**
     * Upper bound for the result.
     */
    private static final int MAXIMUM = 100;

    /**
     * Transform an analog pin value into an appropriate power slider value
     * with dead-bands at the top and bottom of the slider.
     *
     * @param analogValue the input.
     * @return power slider value.
     */
    public static int convert(final float analogValue) {
        return clamp(((1 - analogValue) * SCALAR) - OFFSET);
    }

    /**
     * Clamp the value between the maximum and minimum supported power values.
     *
     * @param value the power slider value.
     * @return clamped value.
     */
    private static int clamp(final float value) {
        if (value < MINIMUM) {
            return MINIMUM;
        }
        if (value > MAXIMUM) {
            return MAXIMUM;
        }
        return Math.round(value);
    }
}

Convert an analog pin value into a slider value


import java.awt.Color;

public interface Colors {
  Color[] allColors = {
      Color.BLACK,
      Color.BLUE,
      Color.CYAN,
      Color.DARK_GRAY,
      Color.GRAY,
      Color.GREEN,
      Color.LIGHT_GRAY,
      Color.MAGENTA,
      Color.ORANGE,
      Color.PINK,
      Color.RED,
      Color.WHITE,
      Color.YELLOW
    };
}

Create a fancy interface to allow for easy randomization of colors! Ooh, ahh!


package edu.ksu.cis.projects.mdcf.aadltranslator.model.hazardanalysis;

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

public class ErrorBehaviorModel {
	Set<String> states = new LinkedHashSet<>();

	public void addState(String stateName){
		states.add(stateName);
	}

}

Add file missing from previous commit

Add file missing from previous commit


/**
 * Copyright 2017 Pivotal Software, 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 io.micrometer.spring.autoconfigure.export.humio;

import io.micrometer.core.instrument.Clock;
import io.micrometer.humio.HumioConfig;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.util.EnvironmentTestUtils;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;

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

/**
 * Tests for {@link HumioMetricsExportAutoConfiguration}.
 */
class HumioMetricsExportAutoConfigurationTest {

    private AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();

    @Test
    void anyAdditionToTagsReplacesDefault() {
        EnvironmentTestUtils.addEnvironment(context, "management.metrics.export.humio.tags.app=myapp");
        registerAndRefresh(ClockConfiguration.class, HumioMetricsExportAutoConfiguration.class);
        assertThat(context.getBean(HumioConfig.class).tags()).containsOnlyKeys("app");
    }

    @Test
    void defaultTag() {
        registerAndRefresh(ClockConfiguration.class, HumioMetricsExportAutoConfiguration.class);
        assertThat(context.getBean(HumioConfig.class).tags()).containsOnlyKeys("name");
    }

    @AfterEach
    void cleanUp() {
        if (context != null) {
            context.close();
        }
    }

    private void registerAndRefresh(Class<?>... configurationClasses) {
        context.register(configurationClasses);
        context.refresh();
    }

    @Configuration
    static class ClockConfiguration {
        @Bean
        public Clock clock() {
            return Clock.SYSTEM;
        }

    }
}

Test humio tag setting from properties

Test humio tag setting from properties


package org.radargun.stages.monitor;

import org.radargun.DistStageAck;
import org.radargun.config.Property;
import org.radargun.config.Stage;
import org.radargun.stages.AbstractDistStage;
import org.radargun.traits.Clustered;
import org.radargun.traits.InjectTrait;

/**
 * This stage needs to be defined twice:
 *
 *     <cluster-split-verify />
 *     ... other stages ...
 *     <cluster-split-verify verify="true" />
 *
 * First run will record the cluster size, and the second will verify that that the size didn't change
 * during the time.
 */
@Stage(doc = "Verifies that there weren't any changes to the cluster size during testing.")
public class ClusterSplitVerifyStage extends AbstractDistStage {

   public static final String CLUSTER_SIZE_AT_START = "CLUSTER_SIZE_AT_START";
   public static final String MEMBERSHIP_HISTORY_SIZE_AT_START = "MEMBERSHIP_HISTORY_SIZE_AT_START";

   @Property(doc = "Set to true in 2nd definition of the stage in benchmark to verify that no splits occurred. Default is false.")
   private boolean verify = false;

   @InjectTrait
   private Clustered clustered;

   @Override
   public DistStageAck executeOnSlave() {
      if (!verify) {
         int clusterSizeAtTestStart = clustered.getMembers().size();
         int membershipHistorySizeAtStart = clustered.getMembershipHistory().size();
         slaveState.put(CLUSTER_SIZE_AT_START, clusterSizeAtTestStart);
         slaveState.put(MEMBERSHIP_HISTORY_SIZE_AT_START, membershipHistorySizeAtStart);
      } else {
         int clusterSizeAtTestStart = (int) slaveState.get(CLUSTER_SIZE_AT_START);
         int membershipHistorySizeAtStart = (int) slaveState.get(MEMBERSHIP_HISTORY_SIZE_AT_START);
         for (int i = membershipHistorySizeAtStart; i < clustered.getMembershipHistory().size(); i++) {
            int clusterSizeDuringTest = clustered.getMembershipHistory().get(i).members.size();
            if (clusterSizeDuringTest != clusterSizeAtTestStart) {
               return errorResponse("Cluster size at the beginning of the test was " + clusterSizeAtTestStart + " but changed to " + clusterSizeDuringTest +
                  " during the test! Perhaps a split occured, or a new node joined?");
            }
         }
      }
      return successfulResponse();
   }

}

Add a stage that verifies that cluster size haven't changed during testing


package org.royjacobs.lazybot.hipchat.server;

public class Paths {
    public static String PATH_CAPABILITIES = "capabilities";
    public static String PATH_INSTALL = "install";
    public static String PATH_WEBHOOK_ROOM_MESSAGE = "webhooks/room_message";
    public static String PATH_GLANCES = "glances";
}

package org.royjacobs.lazybot.hipchat.server;

public class Paths {
    public static String PATH_CAPABILITIES = "";
    public static String PATH_INSTALL = "install";
    public static String PATH_WEBHOOK_ROOM_MESSAGE = "webhooks/room_message";
    public static String PATH_GLANCES = "glances";
}

Set capabilities path to root

Set capabilities path to root


package com.example.whatsmymood;

import android.app.Activity;
import android.test.ActivityInstrumentationTestCase2;
import android.widget.AutoCompleteTextView;
import android.widget.EditText;

import com.robotium.solo.Solo;

/**
 * Created by ejtang on 2017-03-13.
 *
 * testing our Login activity to make sure that everything works
 */
public class LoginTest extends ActivityInstrumentationTestCase2 {
    private Solo solo;

    public LoginTest() {
        super(LoginActivity.class);
    }

    public void setUp() throws Exception {
        solo = new Solo(getInstrumentation(), getActivity());
    }

    public void testStart() throws Exception {
        Activity activity = getActivity();
    }

    public void testLoginWithExisting() {
        LoginActivity activity = (LoginActivity) solo.getCurrentActivity();

        solo.assertCurrentActivity("Wrong Activity", LoginActivity.class);
        solo.enterText((AutoCompleteTextView) solo.getView(R.id.Username), "testUser");
        solo.enterText((EditText) solo.getView(R.id.password), "password");

        solo.clickOnButton("Login");
        solo.assertCurrentActivity("Wrong Activity", MainActivity.class);
    }

    public void testLoginWithNonExisting() {
        LoginActivity activity = (LoginActivity) solo.getCurrentActivity();

        solo.assertCurrentActivity("Wrong Activity", LoginActivity.class);
        solo.enterText((AutoCompleteTextView) solo.getView(R.id.Username), "Non-existing User");
        solo.enterText((EditText) solo.getView(R.id.password), "password");

        solo.clickOnButton("Login");
        solo.assertCurrentActivity("Wrong Activity", LoginActivity.class);

        assertTrue(solo.waitForText("Wrong Username/Password Combination"));
    }

    public void testLoginWithoutPassword() {
        LoginActivity activity = (LoginActivity) solo.getCurrentActivity();

        solo.assertCurrentActivity("Wrong Activity", LoginActivity.class);
        solo.enterText((AutoCompleteTextView) solo.getView(R.id.Username), "Non-existing User");

        solo.clickOnButton("Login");
        solo.assertCurrentActivity("Wrong Activity", LoginActivity.class);

        assertTrue(solo.waitForText("This field is required"));
    }

    public void testLoginWithoutUsername() {
        LoginActivity activity = (LoginActivity) solo.getCurrentActivity();

        solo.assertCurrentActivity("Wrong Activity", LoginActivity.class);
        solo.enterText((EditText) solo.getView(R.id.password), "password");

        solo.clickOnButton("Login");
        solo.assertCurrentActivity("Wrong Activity", LoginActivity.class);

        assertTrue(solo.waitForText("This field is required"));
    }
}

Add intent testing for Login Activity

Add intent testing for Login Activity


package com.atreceno.it.javanese.concurrency;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class SplitWorkIntoThreads {

	public static void main(String[] args) throws InterruptedException {
		System.out.println("Start");
		SplitWorkIntoThreads split = new SplitWorkIntoThreads();
		split.start();
	}

	private void start() throws InterruptedException {
		BlockingQueue<Runnable> queue = new LinkedBlockingQueue<Runnable>();
		/* There are 10 tasks to work on */
		for (int i = 0; i < 3; i++) {
			final int j = i;
			queue.add(new Runnable() {

				@Override
				public void run() {
					doSomething(j);
				}
			});
		}
		ThreadPoolExecutor executor = new ThreadPoolExecutor(3, 3, 1000,
				TimeUnit.MILLISECONDS, queue);
		executor.prestartAllCoreThreads();
		executor.shutdown();
		executor.awaitTermination(100000, TimeUnit.MILLISECONDS);

		System.out.println("End");
	}

	private double doSomething(int i) {
		System.out.println("Thread " + Thread.currentThread().getName()
				+ " is working on task #" + i);
		double result = 1;
		for (int j = 0; j < 100; j++) {
			result *= Math.sqrt(i + j);
		}
		try {
			Thread.sleep(i * 1000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		System.out.println("Thread " + Thread.currentThread().getName()
				+ " finished task #" + i);
		return result;
	}
}

Add class to split work

Add class to split work


package com.example.profbola.bakingtime.provider;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

import com.example.profbola.bakingtime.provider.RecipeContract.StepEntry;
/**
 * Created by prof.BOLA on 6/23/2017.
 */

public class StepDbHelper extends SQLiteOpenHelper {

    private static final String DATABASE_NAME = "bakingapp.db";

    private static final int DATABASE_VERSION = 1;

    public StepDbHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }
    @Override
    public void onCreate(SQLiteDatabase db) {
        final String SQL_CREATE_STEPS_TABLE = "CREATE TABLE " + StepEntry.TABLE_NAME + " ( "                    +
                StepEntry._ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "                                          +
                StepEntry.COLUMN_DESCRIPTION + " TEXT NOT NULL, "                                               +
                StepEntry.COLUMN_SHORT_DESCRIPTION + " TEXT NOT NULL, "                                         +
                StepEntry.COLUMN_THUMBNAIL_URL + " STRING, "                                                    +
                StepEntry.COLUMN_VIDEO_URL + " STRING, "                                                        +
                StepEntry.COLUMN_RECIPE_ID + " INTEGER, "                                                       +
                StepEntry.COLUMN_ID + " INTEGER NOT NULL, "                                                     +
                " FOREIGN KEY ( " + StepEntry.COLUMN_RECIPE_ID + " ) REFERENCES "                               +
                RecipeContract.RecipeEntry.TABLE_NAME + " ( " + RecipeContract.RecipeEntry.COLUMN_ID + " ) "    +
                " UNIQUE ( " + StepEntry.COLUMN_ID + " ) ON CONFLICT REPLACE "                                  +
                ");";

        db.execSQL(SQL_CREATE_STEPS_TABLE);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        db.execSQL("DROP TABLE IF EXISTS " + StepEntry.TABLE_NAME);

        onCreate(db);
    }
}

Create DB schema for Step

Create DB schema for Step


package pylos.test;

import java.util.LinkedList;
import java.util.List;

import pylos.model.Model;
import pylos.model.Position;

public class PlaceBallTest extends PylosTestCase {

	/**
	 * Test
	 */
	public void testCanPlaceBallAt() {
		assertTrue(Model.canPlaceBallAt(Position.at(0, 0, 0)));
		assertFalse(Model.canPlaceBallAt(Position.at(0, 0, 1))); // plateau vide donc pas de sens placer boule z = 1

		List<Position> balls = MainTest.gameSample();
		for (Position pos : balls) {
			assertFalse(Model.canPlaceBallAt(pos));
		}

		assertFalse(Model.canPlaceBallAt(Position.at(0, 0, 1)));
		assertFalse(Model.canPlaceBallAt(Position.at(0, 0, 2)));
		assertFalse(Model.canPlaceBallAt(Position.at(0, 0, 3)));
		assertTrue(Model.canPlaceBallAt(Position.at(1, 2, 0)));
		assertTrue(Model.canPlaceBallAt(Position.at(1, 0, 1)));
	}

	public void complexTestCanPlaceBallAt() {
		List<Position> balls = MainTest.complexGameSample();

		/**
		 * o.oo
		 * oooo ...
		 * ooo. oo. ..
		 * ooo. oo. .. .
		 */

		for (Position position : balls) {
			assertFalse(Model.canPlaceBallAt(position));
		}

		List<Position> accessible = new LinkedList<Position>();
		accessible.add(Position.at(1, 0, 0));
		accessible.add(Position.at(3, 2, 0));
		accessible.add(Position.at(3, 3, 0));
		accessible.add(Position.at(2, 0, 1));
		accessible.add(Position.at(0, 0, 2));

		for (Position position : accessible) {
			assertTrue(Model.canPlaceBallAt(position));
		}
	}
}

Test CanPlaceBallAt() for complex game sample


/*
 * Bach - Java Shell Builder
 * Copyright (C) 2019 Christian Stein
 *
 * 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
 *
 *     https://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.
 */

// --main-class de.sormuras.bach.Bach
open /*test*/ module de.sormuras.bach /*extends "main" module*/ {
  requires org.junit.jupiter;

  // ---

  requires java.compiler;
  requires java.net.http;

  // exports de.sormuras.bach;
  // exports de.sormuras.bach.project;
  // exports de.sormuras.bach.project;

  uses java.util.spi.ToolProvider;
}

Add missing test module declaration

Add missing test module declaration


package co.phoenixlab.dn.dngearsim.bootstrap;

import javafx.beans.binding.Bindings;
import javafx.concurrent.Task;
import javafx.fxml.FXML;
import javafx.scene.control.Label;
import javafx.scene.layout.AnchorPane;
import javafx.scene.shape.Rectangle;

public class BootstrapUi {

    @FXML
    private AnchorPane pane;

    @FXML
    private Rectangle loadingBar;

    @FXML
    private Label statusText;

    @FXML
    void initialize() {
        assert pane != null : "fx:id=\"pane\" was not injected: check your FXML file 'splash.fxml'.";
        assert loadingBar != null : "fx:id=\"loadingBar\" was not injected: check your FXML file 'splash.fxml'.";
        assert statusText != null : "fx:id=\"statusText\" was not injected: check your FXML file 'splash.fxml'.";

    }

    public void bindToTask(Task<?> task) {
        assert task != null : "Task cannot be null, check invocation site";
        statusText.textProperty().
                bind(task.messageProperty());
        loadingBar.widthProperty().
                bind(Bindings.multiply(pane.widthProperty(), task.progressProperty()));
    }

    public void unbind() {
        statusText.textProperty().unbind();
        loadingBar.widthProperty().unbind();
    }
}

Add UI controller for bootstrap

Add UI controller for bootstrap


class App{
	public static  void main(String... args) {
		calcTime(Integer.parseInt(args[0]));
		// calc(Integer.parseInt(args[0]), args[1], Integer.parseInt(args[2]));
	}
	private static void calc(int m, String ops, int mm){
		if (ops.equals("*")) {
			System.err.println(m * mm);
		}else if (ops.equals("/")) {
			System.err.println(m / mm);
		}else if (ops.equals("%")) {
			System.err.println(m % mm);
		}

	}
	private static void calcTime(int $sumOfSeconds){
		try{
		int $houers=	( $sumOfSeconds		   ) / 3600;
		int $minutes=	( $sumOfSeconds % (3600)) / 60 ;
		int $secounds=	( $sumOfSeconds % (3600)  - $minutes * 60) ;
		System.err.println($houers+":"+$minutes+":"+$secounds);
	}catch(ArithmeticException ex){System.err.println(ex.getMessage());}
	}
}

Write a java program that inputs an integer that represents a length of time in seconds. The program should then output the number of hours, minutes, and seconds that corresponds to that number of seconds. For example, if the user inputs 50391 total seconds then the program should output 13 hours, 59 minutes, and 51 seconds. (Note: Don't use loops or if condition)


package leetcode.valid_number;

public class Solution {

	public boolean isExponent(String s){
		if(s.length() == 0) return false;
		int first = s.toLowerCase().indexOf('e');
		int last = s.toLowerCase().lastIndexOf('e');
		if(first != last) return false;
		if(first < 0) return false;
		return isFloat(s.substring(0, first)) && isInteger(s.substring(first + 1));
	}

	public boolean isFloat(String s){
		if(s.length() == 0) return false;
		if(isInteger(s)) return true;
		int first = s.indexOf('.');
		int last = s.lastIndexOf('.');
		if(first != last) return false;
		if(first < 0) return false;
		int start = 0;
		if(s.charAt(0) == '+' || s.charAt(0) == '-') start = 1;
		if(isAllDigit(s.substring(start, first), true) && isAllDigit(s.substring(first + 1), false)) return true;
		if(isAllDigit(s.substring(start, first), false) && isAllDigit(s.substring(first + 1), true)) return true;
		return false;
	}

	public boolean isAllDigit(String s, boolean canBeEmpty){
		if(s.length() == 0 && !canBeEmpty) return false;
		char [] chars = s.toCharArray();
		for(int i = 0; i < chars.length; i++){
			char c = chars[i];
			if(!Character.isDigit(c)) return false;
		}
		return true;
	}

	public boolean isInteger(String s){
		if(s.length() == 0) return false;
		char[] chars = s.toCharArray();
		if(chars[0] == '+' || chars[0] == '-') return isAllDigit(s.substring(1), false);
		return isAllDigit(s, false);
	}

    public boolean isNumber(String s) {
    	s = s.trim();
    	if(s.length() == 0) return false;
    	// floating point
    	if(isFloat(s)) return true;
    	// Exponent +1e10
    	if(isExponent(s)) return true;
    	return false;
    }

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

Add java solution for 65. Valid Number

Add java solution for 65. Valid Number

65. Valid Number: https://leetcode.com/problems/valid-number/


package org.opendatakit.consts;

/**
 * Created by jbeorse on 7/17/17.
 */

public class RequestCodeConsts {
    /**
     * Request codes, used with startActivityForResult
     */
    public static final class RequestCodes {
        /**
         * Used to view a collection or a join table in a SpreadsheetFragment in
         * TableDisplayActivity
         */
        public static final int DISPLAY_VIEW = 1;
        /**
         * Used when launching the file picker to change the detail view file
         */
        public static final int CHOOSE_DETAIL_FILE = 2;
        /**
         * Used when launching the file picker to change the list view file
         */
        public static final int CHOOSE_LIST_FILE = 3;
        /**
         * Used when launching the file picker to change the map view file
         */
        public static final int CHOOSE_MAP_FILE = 4;
        /**
         * A generic code for now. Can refactor to make more specific if needed.
         */
        public static final int LAUNCH_VIEW = 5;
        /**
         * Used to launch the device preferences screen (the one with the server settings, device
         * settings, tables specific settings, user restrictions, etc... options)
         */
        public static final int LAUNCH_DISPLAY_PREFS = 6;
        /**
         * For launching an intent to import csv files into a table
         */
        public static final int LAUNCH_IMPORT = 7;
        /**
         * For launching an intent to sync
         */
        public static final int LAUNCH_SYNC = 8;
        /**
         * For launching an HTML file not associated with a table. Unused
         */
        public static final int LAUNCH_WEB_VIEW = 10;
        /**
         * For launching an intent to edit a table's properties.
         */
        public static final int LAUNCH_TABLE_PREFS = 11;
        /**
         * For launching an intent to list a column's color rules
         */
        public static final int LAUNCH_COLOR_RULE_LIST = 16;
        /**
         * For launching an intent to add a row in survey
         */
        public static final int ADD_ROW_SURVEY = 17;
        /**
         * For launching an intent to edit a row in survey
         */
        public static final int EDIT_ROW_SURVEY = 18;
        /**
         * For launching an intent to resolve checkpoints
         */
        public static final int LAUNCH_CHECKPOINT_RESOLVER = 19;
        /**
         * For launching an intent to resolve conflicts
         */
        public static final int LAUNCH_CONFLICT_RESOLVER = 20;
        /**
         * For launching an intent to export a table to a csv
         */
        public static final int LAUNCH_EXPORT = 21;
        /**
         * Used when the javascript has started a DoAction and needs to be notified of its result
         */
        public static final int LAUNCH_DOACTION = 22;
        /**
         * Used to launch an intent to open a column preference fragment via table level preference
         * activity
         */
        public static final int LAUNCH_COLUMN_PREFS = 23;

        /**
         * Do not instantiate this class
         */
        private RequestCodes() {
        }
    }

}

Generalize request code constants out of Tables


/*
 *  Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
 *
 *  WSO2 Inc. 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.wso2.carbon.connector.framework.websocket;

import java.util.HashMap;
import java.util.Map;
import javax.websocket.Session;

/**
 * This interface can be used to set the common details of a given WebSocket message.

 * Note: Use this class in the application level only and only if the user needs to set the parameters of a given
 * WebSocket message or need transport properties in any mean.

 *
 * Casting any WebSocket message to this class in the application level is not recommended. If user needs this class
 * for any casting in application level indicates that there is a missing functionality from the given WebSocket
 * message type.

 *
 * Also note that this class is public since developers might need to create WebSocket messages in the application
 * level for testing purposes and this class can be extended to use the setter methods for those purposes.
 */
public abstract class WebSocketMessagePropertiesManager {

    private Map<String, Object> properties = new HashMap<>();

    public void setProperty(String key, Object value) {
        properties.put(key, value);
    }

    public void setProperties(Map<String, Object> properties) {
        properties.entrySet().forEach(
                entry -> this.properties.put(entry.getKey(), entry.getValue())
        );
    }

    public Object getProperty(String key) {
        return properties.get(key);
    }

    public Map<String, Object> getProperties() {
        return properties;
    }

    // WebSocket channel context related setters
    abstract void setSubProtocol(String subProtocol);
    abstract void setTarget(String target);
    abstract void setListenerPort(String listenerPort);
    abstract void setWebSocketProtocolVersion(String protocolVersion);
    abstract void setIsConnectionSecured(boolean isConnectionSecured);

    // WebSocket Session context related setters
    abstract void setServerSession(Session serverSession);
    abstract void addClientSession(Session clientSession);
}

Introduce WebSocket message properties manager


package leetcode;

/**
 * https://oj.leetcode.com/problemset/algorithms/
 */
public class Problem29 {
    public int divide(int dividend, int divisor) {
        // TODO: to be implemented
        return 0;
    }

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

Put skeleton for problem 29

Put skeleton for problem 29


package info.u_team.u_team_test.init;

import info.u_team.u_team_test.entity.TestLivingEntity;
import net.minecraft.entity.ai.attributes.GlobalEntityTypeAttributes;
import net.minecraftforge.eventbus.api.IEventBus;
import net.minecraftforge.fml.event.lifecycle.FMLCommonSetupEvent;

public class TestGlobalEntityTypeAttributes {

	private static void setup(FMLCommonSetupEvent event) {
		event.enqueueWork(() -> {
			GlobalEntityTypeAttributes.put(TestEntityTypes.TEST_LIVING.get(), TestLivingEntity.registerAttributes().create());
		});
	}

	public static void registerMod(IEventBus bus) {
		bus.addListener(TestGlobalEntityTypeAttributes::setup);
	}

}

Create test entity type attributes

Create test entity type attributes


/*
 * (C) Copyright 2018 Boni Garcia (http://bonigarcia.github.io/)
 *
 * 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.github.bonigarcia.test.forced;

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

import java.util.List;

import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.openqa.selenium.WebDriver;

import io.github.bonigarcia.SeleniumExtension;

@ExtendWith(SeleniumExtension.class)
public class ForcedEmptyListJupiterTest {

    @Test
    public void test(List<WebDriver> drivers) {
        assertThrows(NullPointerException.class, () -> drivers.get(0));
    }

}

Include test with empty list of Docker browsers


package net.kencochrane.raven.log4j;

import mockit.Expectations;
import mockit.Injectable;
import mockit.Mocked;
import mockit.Verifications;
import net.kencochrane.raven.Raven;
import net.kencochrane.raven.event.Event;
import net.kencochrane.raven.event.EventBuilder;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.apache.log4j.spi.LoggingEvent;
import org.hamcrest.Matchers;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;

import java.util.Date;
import java.util.UUID;

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

public class SentryAppenderNGTest {
    private SentryAppender sentryAppender;
    @Mocked
    private Raven mockRaven = null;

    @BeforeMethod
    public void setUp() {
        sentryAppender = new SentryAppender(mockRaven);
    }

    @Test
    public void testSimpleMesageLogging(@Injectable final Logger logger) throws Exception {
        final String loggerName = UUID.randomUUID().toString();
        final String message = UUID.randomUUID().toString();
        final String threadName = UUID.randomUUID().toString();
        final Date date = new Date(1373883196416L);
        new Expectations() {{
                logger.getName();
                result = loggerName;
            }};

        sentryAppender.append(new LoggingEvent(null, logger, date.getTime(), Level.INFO, message, threadName,
                null, null, null, null));

        new Verifications() {{
            Event event;
            mockRaven.runBuilderHelpers(withAny(new EventBuilder()));
            mockRaven.sendEvent(event = withCapture());
            assertThat(event.getMessage(), is(message));
            assertThat(event.getLogger(), is(loggerName));
            assertThat(event.getExtra(), Matchers.<String, Object>hasEntry(SentryAppender.THREAD_NAME, threadName));
            assertThat(event.getTimestamp(), is(date));
        }};
    }
}

Add new tests using testNG in raven-log4j


package org.slc.sli.modeling.rest;

import static org.junit.Assert.*;

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

import org.junit.Before;
import org.junit.Test;
import org.slc.sli.modeling.xdm.DmNode;

/**
 *
 * JUnit test for Documentation class.
 *
 * @author wscott
 *
 */
public class DocumentationTest {

    private Documentation documentation;  //class under test
    private static final String TITLE = "doctest";
    private static final String LANGUAGE = "en";
    private final List<DmNode> CONTENTS = new ArrayList<DmNode>(0);

    @Before
    public void setup() {
        documentation = new Documentation(TITLE, LANGUAGE, CONTENTS);
    }

    @Test (expected = NullPointerException.class)
    public void testNullContents() {
        new Documentation(TITLE, LANGUAGE, null);
    }

    @Test
    public void testGetTitle() {
        assertEquals(TITLE, documentation.getTitle());
    }

    @Test
    public void testGetLanguage() {
        assertEquals(LANGUAGE, documentation.getLanguage());
    }

    @Test
    public void testGetContents() {
        assertEquals(CONTENTS, documentation.getContents());
    }

    @Test
    public void testToString() {
        String expected = "{language : " + LANGUAGE + ", title : " + TITLE + ", contents : []}";
        assertEquals(expected, documentation.toString());
    }

}

Add JUnit test for Documentation class in rest modeling module.


package leetcode;

import java.util.Iterator;

/**
 * https://leetcode.com/problems/peeking-iterator/
 */
public class Problem284 {
    private static class PeekingIterator implements Iterator<Integer> {
        public PeekingIterator(Iterator<Integer> iterator) {
            // initialize any member here.
        }

        // Returns the next element in the iteration without advancing the iterator.
        public Integer peek() {
            // TODO
            return null;
        }

        // hasNext() and next() should behave the same as in the Iterator interface.
        // Override them if needed.
        @Override
        public Integer next() {
            // TODO
            return null;
        }

        @Override
        public boolean hasNext() {
            // TODO
            return false;
        }
    }

    public static void main(String[] args) {

    }
}

Add a skeleton for problem 284

Add a skeleton for problem 284


package io.pivotal.arca.provider;

import android.content.ContentValues;
import android.database.Cursor;
import android.database.MatrixCursor;
import android.net.Uri;

public abstract class SearchDataset extends ContextDataset {

    public abstract Cursor search(String[] args) throws Exception;

    @Override
    public Cursor query(final Uri uri, final String[] projection, final String selection, final String[] selectionArgs, final String sortOrder) {
        try {
            return search(selectionArgs);
        } catch (final Exception e) {
            return new MatrixCursor(new String[] { "_id" });
        }
    }

    @Override
    public int update(final Uri uri, final ContentValues values, final String selection, final String[] selectionArgs) {
        throw new UnsupportedOperationException();
    }

    @Override
    public Uri insert(final Uri uri, final ContentValues values) {
        throw new UnsupportedOperationException();
    }

    @Override
    public int bulkInsert(final Uri uri, final ContentValues[] values) {
        throw new UnsupportedOperationException();
    }

    @Override
    public int delete(final Uri uri, final String selection, final String[] selectionArgs) {
        throw new UnsupportedOperationException();
    }
}

Add search dataset to provider

Add search dataset to provider


package roart.common.inmemory.model;

import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;

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

import roart.common.constants.Constants;

import org.apache.commons.codec.digest.DigestUtils;

public class InmemoryUtil {
    private static Logger log = LoggerFactory.getLogger(InmemoryUtil.class);

    public static boolean validate(String md5, String content) {
        String contentMd5 = DigestUtils.md5Hex(content.getBytes(StandardCharsets.ISO_8859_1) );
        if (!md5.equals(contentMd5)) {
            log.error("Md5 differs {} {}", md5, contentMd5);
            return false;
        }
        return true;
    }

    public static boolean validate(String md5, InputStream content) {
        String contentMd5;
        try {
            contentMd5 = DigestUtils.md5Hex(content);
        } catch (Exception e) {
            log.error(Constants.EXCEPTION, e);
            return false;
        }
        if (!md5.equals(contentMd5)) {
            log.error("Md5 differs {} {}", md5, contentMd5);
            return false;
        }
        return true;
    }

    public static byte[] convertWithCharset(String content) {
        return content.getBytes(StandardCharsets.ISO_8859_1);
    }

    public static String convertWithCharset(byte[] bytes) {
        try {
            return new String(bytes, "ISO_8859_1");
        } catch (Exception e) {
            log.error(Constants.EXCEPTION, e);
        }
        return null;
    }

    public static String convertWithCharset(Path path) {
        try {
            return new String(Files.readAllBytes(path), "ISO_8859_1");
        } catch (Exception e) {
            log.error(Constants.EXCEPTION, e);
        }
        return null;
    }
}

Add utils for communication with small msg and data in memory (I243).


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

/**
 * Given a String as input, can you write a method to check if that String is a palindrome?
 *
 * A palindrome is a word, phrase, number, or other sequence of characters which reads the same
 * backward or forward. Allowances may be made for adjustments to capital letters, punctuation, and
 * word dividers.
 *
 * @author Pedro Vicente Gómez Sánchez.
 */
public class Palindromes {
}

Add statement to problem 26

Add statement to problem 26


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

package com.google.gerrit.index.query;

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

import com.google.common.truth.ThrowableSubject;
import com.google.gerrit.testing.GerritBaseTests;
import java.util.Collection;
import java.util.Objects;
import org.junit.Test;

public class QueryBuilderTest extends GerritBaseTests {
  private static class TestPredicate extends Predicate<Object> {
    private final String field;
    private final String value;

    TestPredicate(String field, String value) {
      this.field = field;
      this.value = value;
    }

    @Override
    public Predicate<Object> copy(Collection<? extends Predicate<Object>> children) {
      throw new UnsupportedOperationException();
    }

    @Override
    public int hashCode() {
      return Objects.hash(field, value);
    }

    @Override
    public boolean equals(Object o) {
      if (!(o instanceof TestPredicate)) {
        return false;
      }
      TestPredicate p = (TestPredicate) o;
      return Objects.equals(field, p.field) && Objects.equals(value, p.value);
    }
  }

  private static class TestQueryBuilder extends QueryBuilder<Object> {
    TestQueryBuilder() {
      super(new QueryBuilder.Definition<>(TestQueryBuilder.class));
    }

    @Operator
    public Predicate<Object> a(String value) {
      return new TestPredicate("a", value);
    }
  }

  @Test
  public void fieldNameAndValue() throws Exception {
    assertThat(parse("a:foo")).isEqualTo(new TestPredicate("a", "foo"));
  }

  @Test
  public void fieldWithParenthesizedValues() throws Exception {
    assertThatParseException("a:(foo bar)")
        .hasMessageThat()
        .isEqualTo("line 1:2 no viable alternative at input '('");
  }

  private static Predicate<Object> parse(String query) throws Exception {
    return new TestQueryBuilder().parse(query);
  }

  private static ThrowableSubject assertThatParseException(String query) {
    try {
      new TestQueryBuilder().parse(query);
      throw new AssertionError("expected QueryParseException for " + query);
    } catch (QueryParseException e) {
      return assertThat(e);
    }
  }
}

Add simple test of index-agnostic QueryBuilder

Change-Id: I570410f5e32a7306017330c7455d5d19bcc530eb


package by.vshkl.mvp.domain;

import by.vshkl.mvp.model.Quote;
import by.vshkl.repository.Repository;
import io.reactivex.Observable;

public class DeleteQuoteUsecase implements Usecase<Boolean> {

    private Repository repository;
    private Quote quote;

    public DeleteQuoteUsecase(Repository repository) {
        this.repository = repository;
    }

    public void setQuote(Quote quote) {
        this.quote = quote;
    }

    @Override
    public Observable<Boolean> execute() {
        return repository.deleteQuote(quote);
    }
}

Delete quote from favourites usecase added


package com.btkelly.gnag.utils;

import org.gradle.api.Project;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

public interface DefaultRelativeFilePathComputer {

    /**
     * @param absoluteFilePath the absolute path to a target file. Should be trimmed of all excess whitespace and
     *                         newlines.
     * @param project the current project
     * @return the path to the target file, relative to the root directory of the current project, iff the target file
     *         is contained within that directory; null otherwise
     */
    @Nullable
    default String computeFilePathRelativeToProjectRoot(
            @NotNull final String absoluteFilePath, @NotNull final Project project) {

        final String expectedFilePathPrefix = project.getRootDir().getAbsolutePath() + "/";

        if (!absoluteFilePath.startsWith(expectedFilePathPrefix)) {
            // The target file _is not_ contained within the root directory of the current project. Return null.
            return null;
        } else {
            /*
             * The target file _is_ contained within the root directory of the current project. Return the path to the
             * target file relative to the root directory.
             */
            return absoluteFilePath.replace(expectedFilePathPrefix, "");
        }
    }

}

Add interface that handles default absolute -> relative file path conversions