/**
 * Copyright 2016, RadiantBlue Technologies, 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 model.data.deployment;

import io.swagger.annotations.ApiModelProperty;

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonInclude.Include;

/**
 * Basic container object a Deployment Group ID.
 *
 *

 * There is a limitation of GeoServer such that Layer Groups can only be created
 * if there is at least one valid layer populated at the time of creation.
 * However, for Piazza use-cases, we want to allow users to grab a unique ID for
 * a Layer Group before they have created any actual layers. To support this
 * goal, we use this DeploymentGroup model, as persisted in Mongo, to maintain a
 * connection between a GUID delivered to a user, and a Layer Group (once
 * created) in GeoServer. The user only ever receives the GUID as held by this
 * DeploymentGroup object. In that way, we can deliver some placeholder ID to
 * the user before the actual Layer Group is ready to be created on
 * GeoServer.
 *

 *
 * @author Patrick.Doody
 *
 */
@JsonInclude(Include.NON_NULL)
@JsonIgnoreProperties(ignoreUnknown = true)
public class DeploymentGroup {
	@ApiModelProperty(value = "The unique identifier for this Deployment Group.", required = true)
	public String deploymentGroupId;

	@ApiModelProperty(value = "The user who created this Deployment Group.", required = true)
	public String createdBy;

	/**
	 * Creates a new Deployment Group.
	 */
	public DeploymentGroup() {

	}

	/**
	 * Creates a new Deployment Group.
	 *
	 * @param id
	 *            The deployment group ID for this object
	 * @param createdBy
	 *            The user who created this deployment group.
	 */
	public DeploymentGroup(String id, String createdBy) {
		this.deploymentGroupId = id;
		this.createdBy = createdBy;
	}
}

Add model for Deployment Group

Add model for Deployment Group


/**
 * <License>
 */
package edu.colorado.csdms.wmt.client;

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

import com.google.gwt.junit.client.GWTTestCase;

import edu.colorado.csdms.wmt.client.data.ComponentJSO;

/**
 * Tests for {@link ComponentJSO}. JUnit integration is provided by extending
 * {@link GWTTestCase}.
 *
 * @see http://www.gwtproject.org/doc/latest/DevGuideTesting.html
 * @see http://www.gwtproject.org/doc/latest/tutorial/JUnit.html
 * @see http://blog.danielwellman.com/2008/08/testing-json-parsing-using-javascript-overlay-types-in-gwt-15.html
 * @author Mark Piper (mark.piper@colorado.edu)
 */
public class ComponentJSOTest extends GWTTestCase {

  private ComponentJSO componentJSO;
  private String id;
  private String componentClass;
  private String name;

  /**
   * The module that sources this class. Must be present.
   */
  @Override
  public String getModuleName() {
     return "edu.colorado.csdms.wmt.WMT";
  }

  /**
   * A JSNI method that defines a fixture for the tests. Returns a
   * {@link ComponentJSO} object for testing.
   *
   * @param id
   * @param componentClass
   * @param name
   */
  private native ComponentJSO testComponentJSO(String id, String componentClass,
      String name) /*-{
		return {
			"id" : id,
			"class" : componentClass,
			"name" : name
		}
  }-*/;

  @Before
  @Override
  protected void gwtSetUp() throws Exception {
    id = "child";
    componentClass = "Child";
    name = "Child_0";
    componentJSO = testComponentJSO(id, componentClass, name);
  }

  @After
  @Override
  protected void gwtTearDown() throws Exception {
  }

  @Test
  public void testGetId() {
    assertEquals(id, componentJSO.getId());
  }

  @Test
  public void testGetComponentClass() {
    assertEquals(componentClass, componentJSO.getComponentClass());
  }

  @Test
  public void testGetName() {
    assertEquals(name, componentJSO.getName());
  }
}

Add tests for new methods in ComponentJSO


/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */

public class Solution {

    public boolean hasPathSum(TreeNode root, int sum) {

        if (root == null) {
            return false;
        }

        if (root.left == null && root.right == null && root.val == sum) {
            return true;
        }

        return hasPathSum(root.left, sum - root.val) || hasPathSum(root.right, sum - root.val);

    }

}

Create : 112 Path Sum

Create : 112 Path Sum


/**
 * Copyright (C) 2011 Akiban Technologies Inc.
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License, version 3,
 * as published by the Free Software Foundation.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see http://www.gnu.org/licenses.
 */

package com.akiban.server.error;

import java.text.MessageFormat;

public abstract class InvalidOperationException extends RuntimeException
{
    private static final long serialVersionUID = 1L;

    private final ErrorCode code;
    private final String shortMessage;

    private InvalidOperationException(ErrorCode code, String message) {
        super(String.format("%s: %s", code.getFormattedValue(), message));
        this.code = code;
        this.shortMessage = message;
        assert this.getClass().equals(code.associatedExceptionClass());
    }

    InvalidOperationException(ErrorCode code, Object... args) {
        this (code, MessageFormat.format (code.getMessage(), args));
    }

    public ErrorCode getCode() {
        return code;
    }

    public String getShortMessage() {
        return shortMessage;
    }
}

/**
 * Copyright (C) 2011 Akiban Technologies Inc.
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License, version 3,
 * as published by the Free Software Foundation.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see http://www.gnu.org/licenses.
 */

package com.akiban.server.error;

import java.text.MessageFormat;

public abstract class InvalidOperationException extends RuntimeException
{
    private static final long serialVersionUID = 1L;

    private final ErrorCode code;
    private final String shortMessage;

    private InvalidOperationException(ErrorCode code, String message) {
        super(String.format("%s: %s", code.name(), message));
        this.code = code;
        this.shortMessage = message;
        assert this.getClass().equals(code.associatedExceptionClass());
    }

    InvalidOperationException(ErrorCode code, Object... args) {
        this (code, MessageFormat.format (code.getMessage(), args));
    }

    public ErrorCode getCode() {
        return code;
    }

    public String getShortMessage() {
        return shortMessage;
    }
}

Undo change to IOE full message to use ErrorCode name not formatted code number. Due to Adatper tests expecting message text not to change.


/*******************************************************************************
 * Copyright (c) 2012 - 2015 Signal Iduna Corporation and others.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 * Signal Iduna Corporation - initial API and implementation
 * akquinet AG
 *******************************************************************************/
package org.testeditor.ui.parts.commons;

import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertSame;

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

import org.eclipse.e4.core.contexts.ContextInjectionFactory;
import org.eclipse.e4.core.contexts.EclipseContextFactory;
import org.eclipse.e4.core.contexts.IEclipseContext;
import org.eclipse.swt.widgets.Shell;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.testeditor.core.model.teststructure.TestCase;
import org.testeditor.core.model.teststructure.TestProject;
import org.testeditor.core.services.interfaces.TestProjectService;
import org.testeditor.ui.adapter.TestProjectServiceAdapter;

/**
 * Tests for the SearchTestStructureDialog.
 *
 */
public class SearchTestStructureDialogTest {

	private Shell shell;

	/**
	 * Tests the building of the dialog.
	 *
	 * @throws Exception
	 *             on test failure
	 */
	@Test
	public void testCreateDialogAndFillResultView() throws Exception {
		IEclipseContext context = EclipseContextFactory.create();

		context.set(TestProjectService.class, new TestProjectServiceAdapter() {
			@Override
			public List<TestProject> getProjects() {
				ArrayList<TestProject> list = new ArrayList<TestProject>();
				TestCase testCase = new TestCase();
				TestProject testProject = new TestProject();
				testCase.setName("MyTest");
				testProject.addChild(testCase);
				list.add(testProject);
				return list;
			}
		});
		SearchTestStructureDialog dialog = new SearchTestStructureDialog(shell) {
			@Override
			public Shell getShell() {
				return shell;
			}
		};
		ContextInjectionFactory.inject(dialog, context);
		assertNull(dialog.getSelectedTestStructure());
		dialog.createDialogArea(shell);
		dialog.createTestStructureNamesLoader().run();
		assertSame(1, dialog.getResultViewer().getTable().getItemCount());
	}

	/**
	 * Creates UI handle for test.
	 */
	@Before
	public void setup() {
		shell = new Shell();
	}

	/**
	 * Cleanup ui handles.
	 */
	@After
	public void teardown() {
		shell.dispose();
	}
}

Test the Dialog Result view.

Test the Dialog Result view.


/***********************************************************************************************************************
 * Copyright (c) 2008,2010 TOPCASED consortium.
 *
 * All rights reserved. This program and the accompanying materials are made available under the terms of the Eclipse
 * Public License v1.0 which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors: Sebastien GABEL (CS) - initial API and implementation
 *
 **********************************************************************************************************************/
package org.topcased.requirement.export.internal;

import java.util.MissingResourceException;
import java.util.ResourceBundle;

/**
 * Handles internationalization of classes
 *
 * @author Sebastien GABEL
 */
public final class Messages
{
    private static final String BUNDLE_NAME = "org.topcased.requirement.export.internal.messages"; //$NON-NLS-1$

    private static final ResourceBundle RESOURCE_BUNDLE = ResourceBundle.getBundle(BUNDLE_NAME);

    private Messages()
    {
    }

    public static String getString(String key)
    {
        try
        {
            return RESOURCE_BUNDLE.getString(key);
        }
        catch (MissingResourceException e)
        {
            return '!' + key + '!';
        }
    }
}

Refactor import/export plug-ins: - externalize strings - add internal package for messages and activator


package org.apache.sentry.core.indexer;
/*
 * 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.
 */

import junit.framework.Assert;

import org.apache.sentry.core.model.indexer.Indexer;
import org.junit.Test;

public class TestIndexer {

  @Test
  public void testSimple() {
    String name = "simple";
    Indexer simple = new Indexer(name);
    Assert.assertEquals(simple.getName(), name);
  }

  @Test
  public void testIndexerAuthzType() {
    Indexer indexer1 = new Indexer("indexer1");
    Indexer indexer2 = new Indexer("indexer2");
    Assert.assertEquals(indexer1.getAuthzType(), indexer2.getAuthzType());
    Assert.assertEquals(indexer1.getTypeName(), indexer2.getTypeName());
  }

  // just test it doesn't throw NPE
  @Test
  public void testNullIndexer() {
    Indexer nullIndexer = new Indexer(null);
    nullIndexer.getName();
    nullIndexer.toString();
    nullIndexer.getAuthzType();
    nullIndexer.getTypeName();
  }
}

SENTRY-653: Add simple Indexer model object test for sentry-core-model-indexer


/*******************************************************************************
 * Copyright (c) 2016 Red Hat Inc. and others.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *     Red Hat Inc. - initial API and implementation
 *******************************************************************************/
package org.jboss.tools.vscode.java.internal.handlers;

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

import java.util.List;

import org.eclipse.lsp4j.Location;
import org.eclipse.lsp4j.Position;
import org.eclipse.lsp4j.TextDocumentIdentifier;
import org.eclipse.lsp4j.TextDocumentPositionParams;
import org.junit.Before;
import org.junit.Test;

/**
 * @author fbricon
 *
 */
public class NavigateToDefinitionHandlerTest {

	private NavigateToDefinitionHandler handler;

	@Before
	public void setUp() {
		handler = new NavigateToDefinitionHandler();
	}

	@Test
	public void testGetEmptyDefinition() throws Exception {
		List<? extends Location> definitions = handler.getDefinition(new TextDocumentPositionParams(new TextDocumentIdentifier("/foo/bar"), "/foo/bar", new Position(1, 1)));
		assertNotNull(definitions);
		assertEquals(1, definitions.size());
		assertNotNull("Location has no Range", definitions.get(0).getRange());
	}

}

Add missing test for 65f2d88

Add missing test for 65f2d88

Signed-off-by: Fred Bricon <3278c038c93c729ae96f0d035919e3fb69e9cff7@gmail.com>


package org.intermine.webservice.server.exceptions;

import org.intermine.webservice.server.output.Output;

public class UnauthorizedException extends ServiceException {

    private static final long serialVersionUID = 1L;

    public UnauthorizedException() {
        super("This service requires authentication.");
        initResponseCode();
    }

    public UnauthorizedException(String message) {
        super(message);
        initResponseCode();
    }

    private void initResponseCode() {
        setHttpErrorCode(Output.SC_UNAUTHORIZED);
    }
}

Send 406 codes when appropriate

Send 406 codes when appropriate


package org.nakedobjects.reflector.java.reflect;

import org.nakedobjects.object.NakedObjectSpecification;
import org.nakedobjects.object.defaults.AbstractSpecificationLoader;
import org.nakedobjects.object.defaults.NakedObjectSpecificationImpl;

public class JavaSpecificationLoader extends AbstractSpecificationLoader {

    protected NakedObjectSpecification load(String className) {
        JavaReflector reflector = new JavaReflector(className);
        NakedObjectSpecificationImpl specification = new NakedObjectSpecificationImpl();
        ((NakedObjectSpecificationImpl) specification).reflect(className, reflector);
        return specification;
    }

}

/*
 * Naked Objects - a framework that exposes behaviourally complete business objects directly to the user.
 * Copyright (C) 2000 - 2005 Naked Objects Group Ltd
 *
 * This program is free software; you can redistribute it and/or modify it under the terms of the GNU General
 * Public License as published by the Free Software Foundation; either version 2 of the License, or (at your
 * option) any later version.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the
 * implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
 * for more details.
 *
 * You should have received a copy of the GNU General Public License along with this program; if not, write to
 * the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
 *
 * The authors can be contacted via www.nakedobjects.org (the registered address of Naked Objects Group is
 * Kingsway House, 123 Goldworth Road, Woking GU21 1NR, UK).
 */

Split the old reflector into two parts: the adapter factory and the specification loader.

git-svn-id: 3f09329b2f6451ddff3637e937fd5de689f72c1f@1008103 13f79535-47bb-0310-9956-ffa450edef68


/*
 * Copyright 2013 Franklin Bristow <franklin.bristow@phac-aspc.gc.ca>.
 *
 * 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 ca.corefacility.bioinformatics.irida.web.exceptions;

import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;

/**
 * An exception that is thrown when an entity is not found.
 *
 * @author Franklin Bristow <franklin.bristow@phac-aspc.gc.ca>
 */
@ResponseStatus(HttpStatus.NOT_FOUND)
public class EntityNotFoundException extends RuntimeException {
}

Add a new type of exception for web projects that Spring MVC handles and renders the appropriate error code.


package arez.integration.observable;

import arez.annotations.ArezComponent;
import arez.annotations.Observable;
import arez.integration.AbstractArezIntegrationTest;
import java.util.concurrent.atomic.AtomicInteger;
import org.testng.annotations.Test;
import static org.testng.Assert.*;

@SuppressWarnings( "Duplicates" )
public class ObservableWriteOutsideTransactionTest
  extends AbstractArezIntegrationTest
{
  @ArezComponent
  static abstract class MyComponent
  {
    @Observable( writeOutsideTransaction = true )
    abstract long getTime();

    abstract void setTime( long value );
  }

  @Test
  public void scenario()
    throws Throwable
  {
    final MyComponent component = new ObservableWriteOutsideTransactionTest_Arez_MyComponent();

    final AtomicInteger callCount = new AtomicInteger();

    observer( () -> {
      component.getTime();
      callCount.incrementAndGet();
    } );

    assertEquals( callCount.get(), 1 );

    // Write outside transaction
    component.setTime( 37L );

    // If gets here it reportObserved so observer re-ran
    assertEquals( callCount.get(), 2 );

    safeAction( () -> assertEquals( component.getTime(), 37L ) );

    // Write inside transaction
    safeAction( () -> component.setTime( 42L ) );

    assertEquals( callCount.get(), 3 );

    safeAction( () -> assertEquals( component.getTime(), 42L ) );
  }
}

Add integration test to verify behaviour


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

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hdfs.DFSConfigKeys;
import org.apache.hadoop.hdfs.MiniDFSCluster;
import org.apache.hadoop.hdfs.protocol.datatransfer.PipelineAck;
import org.junit.Assert;
import org.junit.Test;

import java.io.IOException;

public class TestDataNodeECN {
  @Test
  public void testECNFlag() throws IOException {
    Configuration conf = new Configuration();
    conf.setBoolean(DFSConfigKeys.DFS_PIPELINE_ECN_ENABLED, true);
    MiniDFSCluster cluster = null;
    try {
      cluster = new MiniDFSCluster.Builder(conf).numDataNodes(1).build();
      PipelineAck.ECN ecn = cluster.getDataNodes().get(0).getECN();
      Assert.assertNotEquals(PipelineAck.ECN.DISABLED, ecn);
    } finally {
      if (cluster != null) {
        cluster.shutdown();
      }
    }
  }
}

Add the missing files for HDFS-8009.

Add the missing files for HDFS-8009.


package org.ops4j.pax.exam.regression.nat;

import static org.ops4j.pax.exam.Constants.START_LEVEL_SYSTEM_BUNDLES;
import static org.ops4j.pax.exam.Constants.START_LEVEL_TEST_BUNDLE;
import static org.ops4j.pax.exam.CoreOptions.bootDelegationPackage;
import static org.ops4j.pax.exam.CoreOptions.composite;
import static org.ops4j.pax.exam.CoreOptions.frameworkStartLevel;
import static org.ops4j.pax.exam.CoreOptions.mavenBundle;
import static org.ops4j.pax.exam.CoreOptions.systemProperty;
import static org.ops4j.pax.exam.CoreOptions.url;

import org.ops4j.pax.exam.Option;

public class RegressionConfiguration
{
    public static Option regressionDefaults()
    {
        return composite(
            bootDelegationPackage( "sun.*" ),
            frameworkStartLevel( START_LEVEL_TEST_BUNDLE ),
            url( "link:classpath:META-INF/links/org.ops4j.pax.exam.inject.link" ).startLevel( START_LEVEL_SYSTEM_BUNDLES ),
            url( "link:classpath:META-INF/links/org.ops4j.pax.extender.service.link" ).startLevel( START_LEVEL_SYSTEM_BUNDLES ),
            url( "link:classpath:META-INF/links/org.osgi.compendium.link" ).startLevel( START_LEVEL_SYSTEM_BUNDLES ),
            url( "link:classpath:META-INF/links/org.apache.geronimo.specs.atinject.link" ).startLevel( START_LEVEL_SYSTEM_BUNDLES ),
            mavenBundle("org.slf4j", "slf4j-api").versionAsInProject().startLevel( START_LEVEL_SYSTEM_BUNDLES ),
            mavenBundle("ch.qos.logback", "logback-core").versionAsInProject().startLevel( START_LEVEL_SYSTEM_BUNDLES ),
            mavenBundle("ch.qos.logback", "logback-classic").versionAsInProject().startLevel( START_LEVEL_SYSTEM_BUNDLES ),
            systemProperty("logback.configurationFile").value( "file:src/test/resources/logback.xml" )
            );
    }

}

[PAXEXAM-317] Use logback in Native Container regression tests and
reduce verbosity

added missing source


package org.apache.markt.leaks.rmi;

import java.lang.ref.WeakReference;
import java.net.URL;
import java.net.URLClassLoader;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;

public class RegistryLeak {

    public static void main(String[] args) {

        RegistryLeak registryLeak = new RegistryLeak();

        // Switch TCCL
        registryLeak.start();

        // Register new object in RMI
        registryLeak.register();

        // Deregister object
        registryLeak.deregister();

        // Restore TCCL
        registryLeak.stop();

        // Trigger GC
        System.gc();

        // Check for leak
        registryLeak.leakCheck();
    }

    private static final ClassLoader ORIGINAL_CLASS_LOADER =
            Thread.currentThread().getContextClassLoader();

    private WeakReference<ClassLoader> moduleClassLoaderRef;

    private void start() {
        ClassLoader moduleClassLoader = new URLClassLoader(new URL[] {}, ORIGINAL_CLASS_LOADER);

        Thread.currentThread().setContextClassLoader(moduleClassLoader);
        moduleClassLoaderRef = new WeakReference<>(moduleClassLoader);
    }

    private void register() {
        try {
            LocateRegistry.createRegistry(Registry.REGISTRY_PORT);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void deregister() {
        // NO-OP. NO API available.
    }

    private void stop() {
        Thread.currentThread().setContextClassLoader(ORIGINAL_CLASS_LOADER);
    }

    private void leakCheck() {
        if (moduleClassLoaderRef.get() == null) {
            System.out.println("No leak");
        } else {
            System.out.println("Leak");
        }
    }
}

Add a simple Java app that demonstrates a TCCL memory leak with RMI registry creation.


package cgeo.geocaching.utils;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import rx.Single;
import rx.Single.OnSubscribe;
import rx.SingleSubscriber;
import rx.functions.Action0;
import rx.subscriptions.Subscriptions;

import java.io.IOException;
import java.util.concurrent.atomic.AtomicBoolean;

public class RxOkHttpUtils {

    private RxOkHttpUtils() {
        // Do not instantiate
    }

    /**
     * Create a Single for running a cancellable request.
     *
     * @param client the client to use for this request
     * @param request the request
     * @return a Single containing the response or an IOException
     */
    public static Single<Response> request(final OkHttpClient client, final Request request) {
        return Single.create(new OnSubscribe<Response>() {
            @Override
            public void call(final SingleSubscriber<? super Response> singleSubscriber) {
                final Call call = client.newCall(request);
                final AtomicBoolean completed = new AtomicBoolean(false);
                singleSubscriber.add(Subscriptions.create(new Action0() {
                    @Override
                    public void call() {
                        if (!completed.get()) {
                            call.cancel();
                        }
                    }
                }));
                call.enqueue(new Callback() {
                    @Override
                    public void onFailure(final Call call, final IOException e) {
                        completed.set(true);
                        singleSubscriber.onError(e);
                    }

                    @Override
                    public void onResponse(final Call call, final Response response) throws IOException {
                        completed.set(true);
                        singleSubscriber.onSuccess(response);
                    }
                });
            }
        });
    }

}

Add utility class to run a OkHttp requests as a RxJava Single


import java.util.Scanner;

/**
 * This program computes the Fibonacci Sequence using arrays, and the length specified
 * by the user.
 **/
public class Fibonacci_Array {
    public static void main(String[] args) {
        int z;
        System.out.println("How many Fibonacci numbers do you need?");
        Scanner m = new Scanner(System.in);
        z = m.nextInt();
        int a[] = new int[z];
        a[0] = 0;
        a[1] = 1;
        for (int i = 2; i < z; i++) {
            a[i] = a[i-1] + a[i-2];
        }
        for (int i = 0; i < z; i++) {
            System.out.print(a[i] + " ");
        }
        System.out.println();
    }
}

Add problem 2 to unit 2

Add problem 2 to unit 2


package jeranvier.math.dsp;

import jeranvier.math.linearAlgebra.Vector;
import jeranvier.math.util.Complex;

public class ButterworthFilter {

	private final double frequencyCut;
	private final double sampleRate;
	private final int filterOrder;
	private final double DCGain;

	public ButterworthFilter(double sampleRate, double frequencyCut, int filterOrder, double DCGain){
		this.frequencyCut = frequencyCut;
		this.sampleRate = sampleRate;
		this.filterOrder = filterOrder;
		this.DCGain = DCGain;
	}

	public ButterworthFilter(double sampleRate, double frequencyCut, int filterOrder){
			this(frequencyCut, sampleRate, filterOrder, 1.0);
	}

	public Vector filter(Vector signal){
		Vector fft = Fourier.dft(signal);
		int n = signal.size();
		int numBins = n / 2;  // Half the length of the FFT by symmetry
		double binWidth = this.sampleRate / n; // Hz
		Vector.Builder filteredBuilder = new Vector.Builder(n);
		filteredBuilder.set(1, fft.get(1));
		filteredBuilder.set(n, fft.get(n));

		for(int i = 2; i < n/2+1; i++){
			double binFreq = binWidth * i;
			double gain = Math.abs(DCGain)/(Math.sqrt( ( 1 + Math.pow( binFreq / frequencyCut, 2.0 * filterOrder))));
			filteredBuilder.set(i, fft.get(i).multiplyBy(gain));
			filteredBuilder.set(n-i+1, fft.get(n-i+1).multiplyBy(gain));
		}

		Vector filtered = filteredBuilder.build();

		return Fourier.ift(filtered);
	}
}

Add butterworth low path filter. Todo: create hight path and band path filters as well.


package com.fatico.winthing.logging;

import java.util.Arrays;
import java.util.concurrent.ConcurrentLinkedQueue;

import com.fatico.winthing.gui.WindowGUI;

import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.ConsoleAppender;

public class ConsoleLogger extends ConsoleAppender<ILoggingEvent> {
	private static final int LOG_SIZE = 50;
	private static ConcurrentLinkedQueue<String> events = new ConcurrentLinkedQueue<String>();

	public static String getEvents() {
		if (events.size() == 0) {
			return "";
		}

		String[] logs = new String[events.size()];
		events.toArray(logs);

		String result = Arrays.toString(logs);

		return result;
	}

	protected void append(ILoggingEvent event) {
		super.append(event);

		if (events.size() > LOG_SIZE) {
			events.remove();
		}

		byte[] data = encoder.encode(event);
		events.add(new String(data));

		WindowGUI gui = WindowGUI.getInstance();
		gui.reload();
	}
}

Enable logging to a GUI console window

Enable logging to a GUI console window


package org.webbitserver.netty;

import java.util.Set;
import org.junit.Test;

import static org.junit.Assert.assertEquals;

/**
 *
 * @author Kushal Pisavadia
 */
public class NettyWebServerTest {

    /**
     * Tests the stop() method in NettyWebServer. Makes sure that we are stopping
     * the web server cleanly and not leaving any resources hanging.
     *
     * @throws Exception
     * @see NettyWebServer
     */
    @Test
    public void testStop() throws Exception {
        int threadCountStart = 0, threadCountEnd = 0;

        threadCountStart = this.getCurrentThreadCount();

        // Build, start, wait and stop the Netty Web Server
        NettyWebServer instance = new NettyWebServer(8080).start();
        Thread.sleep(1000); // sleep for 1 second
        instance.stop();

        threadCountEnd = this.getCurrentThreadCount();

        assertEquals(threadCountStart, threadCountEnd);
    }

    private int getCurrentThreadCount() {
        Set<Thread> threadSet = Thread.getAllStackTraces().keySet();
        Thread[] threadArray = threadSet.toArray(new Thread[threadSet.size()]);
        return threadArray.length;
    }

}

Add a test for .stop() on NettyWebServer to make sure that all resources have been released cleanly


package edu.columbia.gemma.controller;

import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.validation.BindException;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.View;
import org.springframework.web.servlet.view.RedirectView;

import edu.columbia.gemma.BaseControllerTestCase;

/**
 * This test makes use of Spring's MockHttpServletRequest and MockHttpServletResponse.
 * I have used TaxonLoaderService as the loader of choice as it is fast (small file to read from).
 *

 *

 * Copyright (c) 2004 - 2005 Columbia University
 *
 * @author keshav
 * @version $Id$
 */
public class LoaderControllerTest extends BaseControllerTestCase {

    private LoaderController c;
    private MockHttpServletRequest request;
    private MockHttpServletResponse response;
    private View returnedView;

    public void setUp() throws Exception {
        c = ( LoaderController ) ctx.getBean( "loaderController" );
        request = new MockHttpServletRequest();
        response = new MockHttpServletResponse();
        returnedView = new RedirectView( "home.jsp" );
    }

    public void tearDown() {
        c = null;
    }

    /**
     * hasHeader = true The View returned by the onSubmit method ( a RedirectView(String view) ) will obviously not
     * point to the same place on the heap as returnedView defined in setUp(). Calling toString on both will, however
     * yield the same String value: org.springframework.web.servlet.view.RedirectView: unnamed; URL [home.jsp]
     *
     * @throws Exception
     */
    public void testOnSubmitHeaderIsTrue() throws Exception {
        request.addParameter( "hasHeader", "true" );
        request.addParameter( "typeOfLoader", "taxonLoaderService" );
        ModelAndView mav = c.onSubmit( request, response, ( Object ) null, ( BindException ) null );
        assertEquals( returnedView.toString(), mav.getView().toString() );

    }

    /**
     * hasHeader = false Calling onSubmit with hasHeader = false will cause a NumberFormatException, as expected. This
     * results in a call to the view numberFormatError.jsp (to display the error), with the view name being
     * numberFormatError.
     *
     * @throws Exception
     */
    public void testOnSubmitIsFalse() throws Exception {
        request.addParameter( "hasHeader", "false" );
        request.addParameter( "typeOfLoader", "taxonLoaderService" );
        ModelAndView mav = c.onSubmit( request, response, ( Object ) null, ( BindException ) null );
        assertEquals( "numberFormatError", mav.getViewName() );

    }

}

Test to test the LoaderController

Test to test the LoaderController


package org.beanmaker;

import org.dbbeans.util.Strings;

import org.jcodegen.html.xmlbase.XMLElement;

public class WebXMLConfig {

    private static final String XML_CONFIG_PREFIX = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
            "<web-app xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n" +
            "\t\txmlns=\"http://java.sun.com/xml/ns/javaee\"\n" +
            "\t\txmlns:web=\"http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd\"\n" +
            "\t\txsi:schemaLocation=\"http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd\"\n" +
            "\t\tversion=\"3.0\"\n" +
            "\t\txmlns=\"http://caucho.com/ns/resin\"\n" +
            "\t\txmlns:resin=\"http://caucho.com/ns/resin/core\">\n\n";

    private static final String XML_CONFIG_SUFFIX = "\n</web-app>\n";

    private static final String URL_START = "/Control";

    private final String beanName;
    private final String packageName;

    public WebXMLConfig(final String beanName, final String packageName) {
        this.beanName = beanName;
        this.packageName = packageName;
    }

    private XMLElement getServletConfigXMLElement() {
        final XMLElement servlet = new XMLElement("servlet", 1);
        servlet.addChild(getOneLiner("servlet-name", getServletName()));
        servlet.addChild(getOneLiner("servlet-class", packageName + "." + beanName + "Servlet"));
        return servlet;
    }

    private XMLElement getOneLiner(final String name, final String value) {
        final XMLElement element = new XMLElement(name, value);
        element.setOnOneLine(true);
        return element;
    }

    private String getServletName() {
        return Strings.replace(packageName, ".", "-") + "-" + beanName;
    }

    private XMLElement getServletMappingConfigXMLElement() {
        final XMLElement servletMapping = new XMLElement("servlet-mapping", 1);
        servletMapping.addChild(getOneLiner("servlet-name", getServletName()));
        servletMapping.addChild(getOneLiner("url-pattern", getURLPattern()));
        return servletMapping;
    }

    private String getURLPattern() {
        String[] parts = packageName.split("\\.");
        StringBuilder pattern = new StringBuilder();
        pattern.append(URL_START);
        for (int index = 2; index < parts.length; ++index)
            pattern.append("/").append(Strings.capitalize(parts[index]));
        pattern.append("/").append(beanName);

        return pattern.toString();
    }

    public String getFilename() {
        return "web-" + getServletName() + ".xml";
    }

    public String getSourceCode() {
        return XML_CONFIG_PREFIX + getServletConfigXMLElement().toString() + "\n"
                + getServletMappingConfigXMLElement().toString() + XML_CONFIG_SUFFIX;
    }

}

Add generation of web.xml naming/mapping code for servlets


/*
 * Copyright 2017 haeun kim
 *
 * 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 algorithm.boj;

import java.io.*;

/**
 * Created by haeun on 2017-09-19
 * Site       : https://www.acmicpc.net/problem/10430
 */
public class Boj10430 {

    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        String[] inputs = br.readLine().split(" ");
        int a = Integer.parseInt(inputs[0]);
        int b = Integer.parseInt(inputs[1]);
        int c = Integer.parseInt(inputs[2]);

        System.out.println((a + b) % c);
        System.out.println(((a % c) + (b%c)) % c);
        System.out.println((a*b) % c);
        System.out.println(((a%c) * (b%c)) % c);
    }

}

Solve No.10430 from Baekjoon Online Judge


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

import java.io.CharArrayWriter;
import java.io.PrintWriter;

public class EventsLog extends AbstractLog {
  public EventsLog() {
    super("events");
  }

  public void addMessage(String event, String message) {
    CharArrayWriter charWriter = new CharArrayWriter();
    PrintWriter writer = new PrintWriter(charWriter);

	writer.append(event + "\t" + message);
    super.addMessage(charWriter.toString());

    writer.close();
    charWriter.close();
  }
}

Add support for dedicated events logfile (2 out of 3)


package edu.iu.grid.oim.test;

import static org.junit.Assert.*;
/**
 * MT
 * Unit Test Cases for CNValidator
 */

import org.junit.Test;
import edu.iu.grid.oim.view.divrep.form.validator.CNValidator;

public class CNValidatorTest {

	@Test
	public final void testIsValidCertificate() {
		CNValidator cnv = new CNValidator();

		// List of valid certificates
		String[] validCertNames = {"iu.edu", "*.edu", "www.something.com"};

		for (String validCertName : validCertNames) 	{

			assertTrue("Certificate >" + validCertName + "< is valid", cnv.isValid(validCertName));
		}
	}

	@Test
	public final void testIsInvalidCertificate() {
		CNValidator cnv = new CNValidator();

		// List of invalid certificates
		String[] invalidCertNames = {".iu.edu", "/edu"};

		for (String invalidCertName : invalidCertNames) 	{

			assertFalse("Certificate >" + invalidCertName + "< is invalid", cnv.isValid(invalidCertName));
		}
	}
}

Test case for Jira OIM-82

MT: Test case for Jira OIM-82


package integration;

import com.codeborne.selenide.*;
import org.junit.Before;
import org.junit.Test;

import static com.codeborne.selenide.CollectionCondition.*;
import static com.codeborne.selenide.Condition.visible;
import static com.codeborne.selenide.Selenide.$;
import static com.codeborne.selenide.Selenide.$$;

public class LazyEvaluationTest extends IntegrationTest {

  static SelenideElement h1 = $("h1");
  static SelenideElement button = $("#double-clickable-button");

  static SelenideElement input1 = $$("input").first();
  static SelenideElement input2 = $$("input").last();
  static SelenideElement input3 = $$("input").get(1);

  static ElementsCollection inputs = $$("input").filterBy(visible);

  @Before
  public void openTestPageWithImages() {
    openFile("page_with_jquery.html");
  }

  @Test
  public void singleElementLazyFound() {
    h1.shouldBe(visible);
    button.click();
  }

  @Test
  public void collectionRelatedLazyOperations() {
    input1.shouldBe(visible);
    input2.shouldBe(visible);
    input3.shouldBe(visible);
    inputs.shouldHave(sizeGreaterThanOrEqual(1));
  }

}

Test for lazy evaluations is added (failing at the moment)


/*
 * Copyright 2008 The Kuali Foundation.
 *
 * Licensed under the Educational Community License, Version 1.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.opensource.org/licenses/ecl1.php
 *
 * 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.kuali.kra.budget.web;

import org.kuali.kra.proposaldevelopment.web.ProposalDevelopmentWebTestBase;

import com.gargoylesoftware.htmlunit.html.HtmlElement;
import com.gargoylesoftware.htmlunit.html.HtmlPage;

public class BudgetWebTestBase extends ProposalDevelopmentWebTestBase {

    private static final String PDDOC_BUDGET_VERSIONS_LINK_NAME = "methodToCall.headerTab.headerDispatch.save.navigateTo.budgetVersions.x";
    private static final String NEW_BUDGET_VERSION_NAME = "newBudgetVersionName";
    private static final String ADD_BUDGET_VERSION_BUTTON = "methodToCall.addBudgetVersion";

    private String documentNumber;

    protected HtmlPage getBudgetVersionsPage() throws Exception {
        HtmlPage proposalPage = this.getProposalDevelopmentPage();
        documentNumber = getFieldValue(proposalPage, "document.documentHeader.documentNumber");

        setRequiredFields(proposalPage, DEFAULT_DOCUMENT_DESCRIPTION,
                DEFAULT_PROPOSAL_SPONSOR_CODE,
                DEFAULT_PROPOSAL_TITLE,
                DEFAULT_PROPOSAL_REQUESTED_START_DATE,
                DEFAULT_PROPOSAL_REQUESTED_END_DATE,
                DEFAULT_PROPOSAL_ACTIVITY_TYPE,
                DEFAULT_PROPOSAL_TYPE_CODE,
                DEFAULT_PROPOSAL_OWNED_BY_UNIT);
        HtmlPage budgetVersionsPage = clickOn(proposalPage, PDDOC_BUDGET_VERSIONS_LINK_NAME);
        return budgetVersionsPage;
    }

    protected HtmlPage addBudgetVersion(HtmlPage budgetVersionsPage) throws Exception {
        setFieldValue(budgetVersionsPage, NEW_BUDGET_VERSION_NAME, "Test Budget Version - 1");
        HtmlElement addBtn = getElementByName(budgetVersionsPage, ADD_BUDGET_VERSION_BUTTON, true);
        budgetVersionsPage = clickOn(addBtn);
        HtmlElement openBtn = getElementByName(budgetVersionsPage, "methodToCall.openBudgetVersion.line0.x");
        budgetVersionsPage = clickOn(openBtn);
        return budgetVersionsPage;
    }

    protected String getDocumentNumber() {
        return documentNumber;
    }

    protected void setDocumentNumber(String documentNumber) {
        this.documentNumber = documentNumber;
    }

}

Update budget versions page flow

KRACOEUS-939: Update budget versions page flow


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

public class DefinitionTest {

    @Rule
    public ClearRule clearRule = new ClearRule();

    @Test
    public void definition_instantiatesCorrectly_true() {
        Definition definition = new Definition("a flying animal", "the bird flew away");
        assertEquals(true, definition instanceof Definition);
    }

    public void definition_hasDefinitionString_correctString() {
        Definition definition = new Definition("a flying animal", "the bird flew away");
        assertEquals("a flying animal", definition.getString());
    }

    public void definition_hasExample_correctString() {
        Definition definition = new Definition("a flying animal", "the bird flew away");
        assertEquals("the bird flew away", definition.getExample());
    }

}

Add initial unit tests for Definition class


package yaz4jtest;
import org.junit.*;
import static org.junit.Assert.*;
import org.yaz4j.*;

/**
 * @author adam
 */
public class DinosaurTest {
    @Test
    public void test() {
        Connection con = new Connection("z3950.loc.gov:7090/voyager", 0);
        assertNotNull(con);
        con.setSyntax("usmarc");
        PrefixQuery pqf = new PrefixQuery("@attr 1=7 0253333490");
        assertNotNull(pqf);
        ResultSet set = con.Search(pqf);
        assertNotNull(set);
        Record rec = set.getRecord(0);
	assertNotNull(rec);
	// System.out.println(rec.render());
    }
}

Add other test case (uses render).

Add other test case (uses render).


package leetcode.isomorphic_strings;

public class Solution {
    public boolean isIsomorphic(String s, String t) {
        int idx;

        int[] charMapS = new int[128];
        int[] codeS = new int[s.length()];
        char[] charS = s.toCharArray();
        idx = 0;
        for(int i = 0; i < charS.length; i++){
            char c = charS[i];
            if(charMapS[c] == 0){
                charMapS[c] = ++idx;
            }
            codeS[i] = charMapS[c];
        }

        int[] charMapT = new int[128];
        char[] charT = t.toCharArray();
        idx = 0;
        for(int i = 0; i < charT.length; i++){
            char c = charT[i];
            if(charMapT[c] == 0){
                charMapT[c] = ++idx;
            }
            if(codeS[i] != charMapT[c]) return false;
        }
        return true;
    }
}

Add java solution for 205. Isomorphic Strings

205. Isomorphic Strings: https://leetcode.com/problems/isomorphic-strings/


/* sbt -- Simple Build Tool
 * Copyright 2012 Eugene Vigdorchik
 */
package xsbti;

/** An addition to standard reporter. Used by the IDE. */
public interface ExtendedReporter extends Reporter
{
	public void comment(Position pos, String msg);
}

Extend reporter to be used by the IDE.

Extend reporter to be used by the IDE.


/*******************************************************************************
 * This file is part of OpenNMS(R).
 *
 * Copyright (C) 2016 The OpenNMS Group, Inc.
 * OpenNMS(R) is Copyright (C) 1999-2016 The OpenNMS Group, Inc.
 *
 * OpenNMS(R) is a registered trademark of The OpenNMS Group, Inc.
 *
 * OpenNMS(R) is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published
 * by the Free Software Foundation, either version 3 of the License,
 * or (at your option) any later version.
 *
 * OpenNMS(R) is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with OpenNMS(R).  If not, see:
 *      http://www.gnu.org/licenses/
 *
 * For more information contact:
 *     OpenNMS(R) Licensing <license@opennms.org>
 *     http://www.opennms.org/
 *     http://www.opennms.com/
 *******************************************************************************/

package org.opennms.smoketest;

import org.junit.Test;

public class ForecastIT extends OpenNMSSeleniumTestCase {
    @Test
    public void canLoadGraph() throws Exception {
        // Request a known graph with an invalid resource id
        m_driver.get(BASE_URL + "opennms/graph/forecast.jsp?resourceId=node[999].nodeSnmp[]&report=mib2.tcpopen");
        // The graph should be rendered
        findElementByXpath("//div[@class='flot-datatable-tabs']");
        // It won't have any data, but this is sufficient to very that all of the required
        // Javascript files have been loaded, and the AJAX call to get the graph was successful
    }
}

Add a simple smoke test used to validate some of the Javascript rendering.


package leetcode.search_for_a_range;

public class Solution {
    public int[] searchRange(int[] A, int target) {
    	if(A == null || A.length == 0) return new int[]{-1, -1};
    	int U, L;
    	int left, right;
    	U = A.length;
    	L = -1;
    	while(L + 1 < U){
    		int mid = L + (U - L) / 2;
    		if(A[mid] >= target){
    			U = mid;
    		}else{
    			L = mid;
    		}
    	}
    	if(U < A.length && A[U] == target) left = U;
    	else left = -1;

    	U = A.length;
    	L = -1;
    	while(L + 1 < U){
    		int mid = L + (U - L) / 2;
    		if(A[mid] <= target){
    			L = mid;
    		}else{
    			U = mid;
    		}
    	}
    	if(L >= 0 && A[L] == target) right = L;
    	else right = -1;
    	return new int[]{left, right};
    }

    public static void main(String[] args){
    	for(int x : new Solution().searchRange(new int[]{1, 2, 3, 3}, 4))
    		System.err.print(x + ", ");
    	System.err.println("");
    }
}

Add java solution for 34. Search for a Range

34. Search for a Range: https://leetcode.com/problems/search-for-a-range/


package com.twu.biblioteca;

import org.junit.Test;

import static org.junit.Assert.assertEquals;

public class BookTest {

    @Test
    public void shouldReturnBookName() {
        Book book = new Book("The Alchemist", "Paulo Coelho", 1988);

        assertEquals("The Alchemist", book.getName());
    }

    @Test
    public void shouldReturnAuthorName() {
        Book book = new Book("The Alchemist", "Paulo Coelho", 1988);

        assertEquals("Paulo Coelho", book.getAuthor());
    }

    @Test
    public void shouldReturnPublicationYear() {
        Book book = new Book("The Alchemist", "Paulo Coelho", 1988);

        assertEquals(1988, book.getPublicationYear());
    }

    @Test
    public void shouldReturnABook() {
        Book book = new Book("The Alchemist", "Paulo Coelho", 1988);

        assertEquals("Book name = The Alchemist, Author = Paulo Coelho, Year of publication = 1988", book.toString());
    }

}

Test the attributes of Book class

Test the attributes of Book class


/**
 * END USER LICENSE AGREEMENT (“EULA”)
 *
 * READ THIS AGREEMENT CAREFULLY (date: 9/13/2011):
 * http://www.akiban.com/licensing/20110913
 *
 * BY INSTALLING OR USING ALL OR ANY PORTION OF THE SOFTWARE, YOU ARE ACCEPTING
 * ALL OF THE TERMS AND CONDITIONS OF THIS AGREEMENT. YOU AGREE THAT THIS
 * AGREEMENT IS ENFORCEABLE LIKE ANY WRITTEN AGREEMENT SIGNED BY YOU.
 *
 * IF YOU HAVE PAID A LICENSE FEE FOR USE OF THE SOFTWARE AND DO NOT AGREE TO
 * THESE TERMS, YOU MAY RETURN THE SOFTWARE FOR A FULL REFUND PROVIDED YOU (A) DO
 * NOT USE THE SOFTWARE AND (B) RETURN THE SOFTWARE WITHIN THIRTY (30) DAYS OF
 * YOUR INITIAL PURCHASE.
 *
 * IF YOU WISH TO USE THE SOFTWARE AS AN EMPLOYEE, CONTRACTOR, OR AGENT OF A
 * CORPORATION, PARTNERSHIP OR SIMILAR ENTITY, THEN YOU MUST BE AUTHORIZED TO SIGN
 * FOR AND BIND THE ENTITY IN ORDER TO ACCEPT THE TERMS OF THIS AGREEMENT. THE
 * LICENSES GRANTED UNDER THIS AGREEMENT ARE EXPRESSLY CONDITIONED UPON ACCEPTANCE
 * BY SUCH AUTHORIZED PERSONNEL.
 *
 * IF YOU HAVE ENTERED INTO A SEPARATE WRITTEN LICENSE AGREEMENT WITH AKIBAN FOR
 * USE OF THE SOFTWARE, THE TERMS AND CONDITIONS OF SUCH OTHER AGREEMENT SHALL
 * PREVAIL OVER ANY CONFLICTING TERMS OR CONDITIONS IN THIS AGREEMENT.
 */

package com.akiban.sql.server;

import java.util.ArrayDeque;
import java.util.Deque;

public class ServerCallContextStack
{
    private ServerCallContextStack() {
    }

    private static final ThreadLocal<Deque<ServerQueryContext>> tl = new ThreadLocal<Deque<ServerQueryContext>>() {
        @Override
        protected Deque<ServerQueryContext> initialValue() {
            return new ArrayDeque<ServerQueryContext>();
        }
    };

    public static Deque<ServerQueryContext> stack() {
        return tl.get();
    }

    public static ServerQueryContext current() {
        return stack().peekLast();
    }

    public static void push(ServerQueryContext call) {
        stack().addLast(call);
    }

    public static void pop(ServerQueryContext call) {
        ServerQueryContext last = stack().removeLast();
        assert (call == last);
    }
}

Add a stack of calls.

Add a stack of calls.


// Copyright 2019 Google LLC
//
// 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.

package com.google.sps.servlets;

import java.io.IOException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/availability")
public class AvailabilityServlet extends HttpServlet {

    @Override
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
        response.setContentType("plain/text");
        response.getWriter().println("To be implemented");
    }

    @Override
    public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
        response.setContentType("plain/text");
        response.getWriter().println("To be implemented");
    }
}

Create servlet to handle displaying a tutor's availability.


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

import com.google.devtools.build.lib.Constants;
import com.google.devtools.build.lib.analysis.ConfiguredRuleClassProvider;
import com.google.devtools.build.lib.packages.RuleClass;
import com.google.devtools.build.lib.packages.RuleClassProvider;

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

/**
 * Prints out list of known rules.
 */
public class ListRuleMain {

  private static ConfiguredRuleClassProvider createRuleClassProvider()
      throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException,
          IllegalAccessException {
    Class<?> providerClass = Class.forName(Constants.MAIN_RULE_CLASS_PROVIDER);
    Method createMethod = providerClass.getMethod("create");
    return (ConfiguredRuleClassProvider) createMethod.invoke(null);
  }

  public static void main(String[] args) throws Exception {
    RuleClassProvider provider = createRuleClassProvider();
    Map<String, RuleClass> rcMap = provider.getRuleClassMap();
    for (String name : rcMap.keySet()) {
      System.out.println(name);
    }
  }
}

Add main to print list of rules.

Add main to print list of rules.

--
MOS_MIGRATED_REVID=94762936


public class HybridSort {

    private static final int number = 154; // use insertion sort if size < number

    public static void hybridSort(int[] arr, int start, int end) {
        if ( end - start < number) {
            insertionSort(arr, start, end);
        } else {
            if (start < end) {
                int part = QuickSort.partition(arr, start, end);
                hybridSort(arr, start, part - 1);
                hybridSort(arr, part + 1, end);
            }
        }
    }

    private static void insertionSort(int[] arr, int start, int end) {
        for (int i = start; i <= end; i++) {
            int tmp = arr[i];
            for (int j = i - 1; j >= 0 && tmp < arr[j] ; j-- ) {
                arr[j+1] = arr[j];
                arr[j] = tmp ;
            }
        }
    }
}

Add hybrid sort java implementation

Add hybrid sort java implementation


package au.org.ands.vocabs.toolkit.db;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;

/** Test of parsing JSON. */
public final class TestJsonParsing {

    /** Private constructor for test class. */
    private TestJsonParsing() {
    }

    /** Main program.
     * @param args Command-line arguments.
     */
    public static void main(final String[] args) {
      String jsonString =
              "[{\"type\": \"HARVEST\",\"provider_type\":"
              + " \"PoolParty\",\"project_id\":"
              + " \"1DCE1494-A022-0001-FFBD-12DE19E01FEB\"},"
              + "{\"type\": \"TRANSFORM\"},{\"type\": \"IMPORT\"}]";
      JsonNode root = TasksUtils.jsonStringToTree(jsonString);
      if (root == null) {
          System.out.println("Got null.");
      } else {
          System.out.println("Got instance of:" + root.getClass().toString());
          if (!(root instanceof ArrayNode)) {
              System.out.println("Didn't get an array.");
          } else {
              for (JsonNode node : (ArrayNode) root) {
                  System.out.println("Got element: " + node.toString());
                  if (!(node instanceof ObjectNode)) {
                      System.out.println("Didn't get an object.");
                  } else {
                      System.out.println("task type: "
                              + node.get("type"));
                  }
              }
          }
      }
    }

}

Add test of JSON parsing

Add test of JSON parsing


/*
 * 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.logging.log4j.core.appender.rolling;

import org.junit.Test;
import static org.junit.Assert.*;

/**
 *
 */
public class FileSizeTest {

    private final static long EXPECTED = 10 * 1024;
    @Test
    public void testFileSize() throws Exception {

        long value = FileSize.parse("10KB", 0);
        assertTrue("unexpected value " + value, value == EXPECTED);
        value = FileSize.parse("10 KB", 0);
        assertTrue("unexpected value " + value, value == EXPECTED);
    }
}

Verify that file sizes are parsed correctly.


package cl.fatman.capital.fund;

import static org.junit.Assert.*;

import java.time.LocalDate;

import org.junit.Test;

public class ExtractFundDataTest {

	@Test
	public void getFundDataTest() {
		ExtractFundData efData = new ExtractFundData("blabla");
		assertNotNull("List with Fund data should not be null", efData.getFundData());
	}

	@Test
	public void getFundRateDataTest() {
		ExtractFundData efData = new ExtractFundData("blabla");
		LocalDate frDate = LocalDate.now();
		assertNotNull("List with Fund Rate data should not be null", efData.getFundRateData(frDate));
	}
}

Add junit test to check the fund data extraction is not empty.


package org.tinylog.impl.test;

import org.tinylog.impl.format.style.Style;

/**
 * Renderer for {@link Style Styles}.
 */
public class StyleRenderer {

	private final Style style;

	/**
	 * @param style The style to render
	 */
	public StyleRenderer(Style style) {
		this.style = style;
	}

	/**
	 * Renders the stored style with the passed text as input.
	 *
	 * @param text The text to style
	 * @return The render result
	 */
	public String render(String text) {
		StringBuilder builder = new StringBuilder(text);
		style.apply(builder, 0);
		return builder.toString();
	}

}

Add style render for JUnit tests

Add style render for JUnit tests


// Copyright Verizon Media. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package ai.vespa.feed.client;

import java.util.concurrent.CompletableFuture;

/**
 * Determines the number of requests to have inflight at any point.
 *
 * @author jonmv
 */
interface Throttler {

    /**
     * A request was just sent with {@code vessel}, with {@code inflight} total in flight.
     */
    void sent(long inflight, CompletableFuture<HttpResponse> vessel);

    /**
     * A successful response was obtained.
     */
    void success();

    /**
     * A throttle signal was obtained from the server.
     */
    void throttled(long inflight);

    /**
     * The target inflight operations right now.
     */
    long targetInflight();

}

Add interface that was moved up

Add interface that was moved up


package com.andela.voluminotesapp.utilities;

import android.graphics.Region;
import android.view.View;

import com.andela.voluminotesapp.callbacks.OnIntersectListener;

public class Collision {
    private Region region1;
    private Region region2;

    public Collision(View layout1, View layout2) {
        region1 = getRegion(layout1);
        region2 = getRegion(layout2);
    }

    public void intersect(OnIntersectListener listener){
        if (region1.op(region2, Region.Op.INTERSECT)) {
            listener.onIntersect();
        }
    }

    private Region getRegion(View viewHolder) {
        int[] layout = new int[2];
        viewHolder.getLocationOnScreen(layout);
        int x = layout[0];
        int y = layout[1];
        int width = viewHolder.getWidth();
        int height = viewHolder.getHeight();

        return new Region(x, y, x + width, y + height);
    }
}

Add class to detect collision on layouts


/*
 * Multiples of 3 or 5
 * Problem 1
 * If we list all the natural numbers below 10 that are multiples of 3 or 5,
 * we get 3, 5, 6 and 9. The sum of these multiples is 23.
 * Find the sum of all the multiples of 3 or 5 below 1000.
 */
public class Problem1 {
    public static void main (String[] args) {
        int sum = 0;
        for(int i = 1; i < 1000 ; i++){
            if(i%3==0 || i%5==0){   //if number is multiple of 3 OR 5...
               sum += i;            //add that number to the total sum
            }
        }
        System.out.println(sum);
    }
}

Check in solution to problem 1 in java

Check in solution to problem 1 in java


/**
 *
 * Copyright (c) Microsoft Corporation. All rights reserved.
 * Licensed under the MIT License. See License.txt in the project root for license information.
 *
 */

package com.microsoft.rest;

import com.fasterxml.jackson.annotation.JsonProperty;
import org.apache.commons.lang3.ClassUtils;
import org.apache.commons.lang3.reflect.FieldUtils;
import org.joda.time.DateTime;

import java.lang.reflect.Field;
import java.time.LocalDate;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * ServiceClient is the abstraction for accessing REST operations and their payload data types.
 */
public class Validator {
    public static void validate(Object request, Class type) throws NullPointerException {
        Field[] fields = FieldUtils.getAllFields(type);
        for (Field field : fields) {
            field.setAccessible(true);
            JsonProperty annotation = field.getAnnotation(JsonProperty.class);
            Object property = null;
            try {
                property = field.get(request);
            } catch (IllegalAccessException e) {
                // Ignore inaccessible fields
            }
            if (annotation != null && annotation.required()) {
                Objects.requireNonNull(property, field.getName() + " == null");
            }

            if (property != null) {
                Class propertyType = property.getClass();
                if (ClassUtils.isAssignable(propertyType, List.class)) {
                    List<?> items = (List<?>)property;
                    for (Object item : items) {
                        Validator.validate(item, item.getClass());
                    }
                }
                if (ClassUtils.isAssignable(propertyType, Map.class)) {
                    Map<?, ?> entries = (Map<?, ?>)property;
                    for (Map.Entry<?, ?> entry : entries.entrySet()) {
                        Validator.validate(entry.getKey(), entry.getKey().getClass());
                        Validator.validate(entry.getValue(), entry.getValue().getClass());
                    }
                }
                else if (!(ClassUtils.isPrimitiveOrWrapper(propertyType) ||
                        ClassUtils.isAssignable(propertyType, LocalDate.class) ||
                        ClassUtils.isAssignable(propertyType, DateTime.class) ||
                        ClassUtils.isAssignable(propertyType, String.class))) {
                    Validator.validate(property, propertyType);
                }
            }
        }
    }
}

Add validator based on JSON annotation

Add validator based on JSON annotation


//
// $Id$

package com.threerings.util;

import com.threerings.util.unsafe.Unsafe;

/**
 * Does something extraordinary.
 */
public class UIDTest
{
    public static void main (String[] args)
    {
        if (Unsafe.setuid(1000)) {
            System.err.println("Yay! My uid is changed.");
        } else {
            System.err.println("Boo hoo! I couldn't change my uid.");
        }
        if (Unsafe.setgid(60)) {
            System.err.println("Yay! My gid is changed.");
        } else {
            System.err.println("Boo hoo! I couldn't change my gid.");
        }
        try {
            Thread.sleep(60*1000L);
        } catch (Exception e) {
        }
    }
}

Test program for the uid fiddly business.

git-svn-id: a1a4b28b82a3276cc491891159dd9963a0a72fae@3654 542714f4-19e9-0310-aa3c-eee0fc999fb1


package org.concord.framework.otrunk.wrapper;

import org.concord.framework.otrunk.OTObjectInterface;
import org.concord.framework.otrunk.OTObjectMap;

public interface OTHash extends OTObjectInterface {
	public OTObjectMap getEntries();
}

Add a wrapper for OTObjectMap.

Add a wrapper for OTObjectMap.

git-svn-id: fdf63cc6b6871a635be2b727c8623e4c3a9a9ed7@18003 6e01202a-0783-4428-890a-84243c50cc2b


package org.apache.pig.tools.grunt;

import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;

import org.apache.pig.ExecType;
import org.apache.pig.PigServer;
import org.apache.pig.tools.grunt.GruntParser.ExplainState;
import org.junit.Before;
import org.junit.Test;

public class TestGruntParser {
    private GruntParser parser;
    static PigServer pig;

    @Before
    public void setup() throws IOException {
        pig = new PigServer(ExecType.LOCAL);
    }

    @Test
    public void testProcessRemove() throws IOException {
        File tmpFile = File.createTempFile("TestGruntParser", "testProcessRemove");
        String dummyScript = "";
        parser = new GruntParser(new ByteArrayInputStream(dummyScript.getBytes()));
        parser.setParams(pig);

        //Delete existing file and check that it doesn't exist
        parser.processRemove(tmpFile.getAbsolutePath(), "");
        assertFalse(tmpFile.exists());

        //Delete non-existing file and check for exception
        try {
            parser.processRemove(tmpFile.getAbsolutePath(), "");
            fail("processRemove should throw exception when deleting missing file.");
        } catch (IOException e) {
            //Yay
        }

        //Delete non-existing file with force, no exception
        parser.processRemove(tmpFile.getAbsolutePath(), "force");

        //Ensure that remove isn't processed when in explain mode
        tmpFile = File.createTempFile("TestGruntParser", "testProcessRemove");
        parser.setExplainState(new ExplainState("","","",false,""));
        parser.processRemove(tmpFile.getAbsolutePath(), "force");
        assertTrue(tmpFile.exists());
    }
}

Add support for removing s3 files

PIG-3426: Add support for removing s3 files

git-svn-id: c4d08399a8c07badad33cbf13a0909bacb78f41f@1521211 13f79535-47bb-0310-9956-ffa450edef68


package edu.stuy.commands;

/**
 * Drives to fender, shoots balls at two point hoop.
 * @author 694
 */

import edu.stuy.subsystems.Flywheel;
import edu.wpi.first.wpilibj.command.CommandGroup;

public class AutonSetting7_3Point extends CommandGroup {

    public AutonSetting7_3Point() {
        addSequential(new AutonDriveToFender(Autonomous.t_closeKeyToFender));
        double distanceInches = Flywheel.distances[Flywheel.FENDER_INDEX];
        addParallel(new AutonWaitThenConvey());
        addSequential(new FlywheelRun(distanceInches, Flywheel.speedsTopHoop));
    }
}

Add 3 point auton drive to fender.

Add 3 point auton drive to fender.


package imagej2.ij1bridge.plugin;

import ij.IJ;
import ij.ImageJ;
import ij.Menus;
import imagej2.plugin.PluginEntry;
import imagej2.plugin.PluginFinder;

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

import org.openide.util.lookup.ServiceProvider;

@ServiceProvider(service=PluginFinder.class)
public class Ij1PluginFinder implements PluginFinder {

	@Override
	public void findPlugins(List<PluginEntry> plugins) {
		if (IJ.getInstance() == null) {
			// TODO -- use NO_SHOW mode (requires ImageJ 1.44)
			new ImageJ();
			IJ.getInstance().setVisible(false);
		}
		final Hashtable<?, ?> commands = Menus.getCommands();
		for (final Object key : commands.keySet()) {
			final String pluginClass = commands.get(key).toString();
			final List<String> parentMenu = new ArrayList<String>();
			// TODO -- populate with actual menu location
			parentMenu.add("Plugins");
			final String label = key.toString();
			final PluginEntry pluginEntry = new PluginEntry(pluginClass, parentMenu, label);
			plugins.add(pluginEntry);
		}
	}

	/**
	 * Tests the IJ1 plugin discovery mechanism,
	 * printing a list of all discovered plugins.
	 */
	public static void main(String[] args) {
		System.setProperty("plugins.dir", "/Applications/Science/ImageJ/plugins");//TEMP
		System.out.println("Finding plugins...");
		List<PluginEntry> plugins = new ArrayList<PluginEntry>();
		new Ij1PluginFinder().findPlugins(plugins);
		System.out.println("Discovered plugins:");
		for (PluginEntry plugin : plugins) {
			System.out.println("\t" + plugin);
		}
		System.exit(0);
	}

}

Add (overly) simple IJ1 discovery code, using ij.Menus.

This used to be revision r1679.


package org.apache.ddlutils.platform;

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

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

import org.apache.ddlutils.PlatformInfo;
import org.apache.ddlutils.TestPlatformBase;
import org.apache.ddlutils.model.Database;

/**
 * Test the SqlBuilder (abstract) class.
 *
 * @author Martin van den Bemt
 * @version $Revision: $
 */
public class SqlBuilderTest extends TestPlatformBase {

    String xml = "<?xml version='1.0' encoding='ISO-8859-1'?>\n"+
                 "<database name='ddlutils'>\n"+
                 "
\n"+
                 "    <column name='id' autoIncrement='true' type='INTEGER' primaryKey='true'/>\n"+
                 "    <column name='name' type='VARCHAR' size='15'/>\n"+
                 "
\n"+
                 "</database>";

    public void setUp()
    {
    }

    /**
     * Test the updateSql method
     */
    public void testUpdateSql()
    {
        SqlBuilder sqlBuilder = new SqlBuilderImpl(new PlatformInfo());
        Database database = parseDatabaseFromString(xml);
        Map map = new HashMap();
        map.put("name", "ddlutils");
        map.put("id", new Integer(0));
        String sql = sqlBuilder.getUpdateSql(database.getTable(0), map, false);
        assertEquals("UPDATE \"TestTable\" SET \"name\" = 'ddlutils' WHERE \"id\" = '0'", sql);
    }

    protected String getDatabaseName() {
        return null;
    }

    public class SqlBuilderImpl extends SqlBuilder {

        public SqlBuilderImpl(PlatformInfo info) {
            super(info);
        }
    }
}

Add test for updateSql. Far from complete, but a start..

git-svn-id: 9ba7b058a3825ad085cc988a898da8cc978da7ce@331927 13f79535-47bb-0310-9956-ffa450edef68


public class Solution {
    public static boolean isAbbr(String name, String abbr) {
        int namePos = 0;
        int abbrPos = 0;
        while (namePos < name.length() && abbrPos < abbr.length()) {
            if (Character.isDigit(abbr.charAt(abbrPos))) {
                int digitEnd = abbrPos;
                while (Character.isDigit(abbr.charAt(digitEnd))) {
                    digitEnd++;
                }
                int abbrNum = Integer.parseInt(abbr.substring(abbrPos, digitEnd));
                namePos += abbrNum;
                abbrPos = digitEnd;
            } else {
                if (name.charAt(namePos) != abbr.charAt(abbrPos)) {
                    return false;
                }
                namePos++;
                abbrPos++;
            }
        }
        return namePos == name.length() && abbrPos == abbr.length();
    }

    public static void main(String[] args) {
        System.out.println(isAbbr("LOCALIZATION", "L10N"));
        System.out.println(isAbbr("LOCALIZATION", "L9N"));
        System.out.println(isAbbr("LOCALIZATION", "L10Q"));
    }
}

Add java solution to q2

Add java solution to q2


/**
 *  @author georgeda
 *
 *  $Id: EvsTreeUtil.java,v 1.1 2005-09-21 20:34:59 georgeda Exp $
 *
 *  $Log: not supported by cvs2svn $
 *
 */
package gov.nih.nci.camod.util;

import gov.nih.nci.camod.Constants;
import gov.nih.nci.evs.query.EVSQuery;
import gov.nih.nci.evs.query.EVSQueryImpl;
import gov.nih.nci.system.applicationservice.ApplicationService;

import java.util.*;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * Static helper class for caching EVS values.
 *
 */
public class EvsTreeUtil {

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

    static private Map ourOrganDescriptions = new HashMap();

    private EvsTreeUtil() {
    }

    /**
     * Get a preferred name based on a concept code. Will return the cached
     * value if it has been fetched before.
     *
     * @param inConceptCode the concept code to get the preferred name for.
     *
     * @return the preferred name, or an empty string if something goes wrong.
     */
    public static synchronized String getEVSPreferedOrganDescription(String inConceptCode) {

        log.trace("Entering getEVSPreferedOrganDescription");

        String theDescription = "";

        if (ourOrganDescriptions.containsKey(inConceptCode)) {
            theDescription = (String) ourOrganDescriptions.get(inConceptCode);
        } else {

            try {
                // Get the app service uri
                ResourceBundle theBundle = ResourceBundle.getBundle("camod");

                ApplicationService appService = ApplicationService.getRemoteInstance(theBundle
                        .getString(Constants.Evs.URI_KEY));

                EVSQuery theConceptNameQuery = new EVSQueryImpl();
                theConceptNameQuery.getConceptNameByCode(Constants.Evs.NAMESPACE, inConceptCode);

                List theConceptNames = (List) appService.evsSearch(theConceptNameQuery);

                // Should only be one
                if (theConceptNames.size() > 0) {

                    String theDisplayName = (String) theConceptNames.get(0);

                    EVSQuery theDisplayNameQuery = new EVSQueryImpl();
                    theDisplayNameQuery.getPropertyValues(Constants.Evs.NAMESPACE, theDisplayName,
                            Constants.Evs.DISPLAY_NAME_TAG);

                    // Should only be one
                    List theDisplayNameList = (List) appService.evsSearch(theDisplayNameQuery);

                    if (theDisplayNameList.size() > 0) {
                        theDescription = (String) theDisplayNameList.get(0);

                        // Cache for next time
                        ourOrganDescriptions.put(inConceptCode, theDescription);
                    }
                }

            } catch (Exception e) {
                log.error("Exception getting preferred description: ", e);
            }
        }
        log.trace("Exiting getEVSPreferedOrganDescription");

        return theDescription;
    }
}

Create util for fetching/caching EVS data

SVN-Revision: 416


package io.miti.shortstop.util;

public final class HeaderField
{
  public static final String HK_CONTENT_LENGTH = "Content-Length";
  public static final String HK_ACCEPT_ENCODING = "Accept-Encoding";
  public static final String HK_TRANSFER_ENCODING = "Transfer-Encoding";
  public static final String HK_CONTENT_ENCODING = "Content-Encoding";

  /** Make the default constructor private. */
  private HeaderField() {
    super();
  }
}

Use constants for header field keys.

Use constants for header field keys.


package com.elmakers.mine.bukkit.action.builtin;

import com.elmakers.mine.bukkit.action.BaseSpellAction;
import com.elmakers.mine.bukkit.api.action.CastContext;
import com.elmakers.mine.bukkit.api.block.MaterialBrush;
import com.elmakers.mine.bukkit.api.spell.SpellResult;
import org.bukkit.block.Block;

public class CheckBlockAction extends BaseSpellAction {
    @SuppressWarnings("deprecation")
    @Override
    public SpellResult perform(CastContext context) {
        MaterialBrush brush = context.getBrush();
        Block block = context.getTargetBlock();
        if (brush != null && brush.isErase()) {
            if (!context.hasBreakPermission(block)) {
                return SpellResult.CANCELLED;
            }
        } else {
            if (!context.hasBuildPermission(block)) {
                return SpellResult.CANCELLED;
            }
        }
        if (!context.isDestructible(block)) {
            return SpellResult.CANCELLED;
        }
        return SpellResult.CAST;
    }

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

Add CheckBlock action, for conditionally cancelling a spell


package org.svetovid.installer;

import java.io.File;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

public final class JavaInstallation {

    private Path location;
    private Path binLocation;
    private Path libLocation;

    private JavaInstallation() {
        this.location = null;
        String[] extdirs = System.getProperty("java.ext.dirs").split(File.pathSeparator);
        if (extdirs.length > 1) {
            libLocation = Paths.get(extdirs[1]);
        }
    }

    private JavaInstallation(Path location) {
        this.location = location;
        initialize();
    }

    private void initialize() {
        if (location == null) {
            return;
        }
        binLocation = libLocation = null;
        if (!Files.isDirectory(location)) {
            return;
        }
        binLocation = location.resolve("bin");
        if (!Files.isDirectory(binLocation)) {
            return;
        }
        libLocation = location.resolve("jre/lib/ext");
        if (!Files.isDirectory(libLocation)) {
            libLocation = location.resolve("lib/ext");
        }
        if (!Files.isDirectory(libLocation)) {
            return;
        }
    }

    public Path getLocation() {
        return location;
    }

    public Path getBinLocation() {
        return binLocation;
    }

    public Path getLibLocation() {
        return libLocation;
    }
}

Add class for representation of Java installations


/***************************************************************************
 *   Copyright (C) 2015 by Fabrizio Montesi <famontesi@gmail.com>          *
 *                                                                         *
 *   This program is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU Library General Public License as       *
 *   published by the Free Software Foundation; either version 2 of the    *
 *   License, or (at your option) any later version.                       *
 *                                                                         *
 *   This program is distributed in the hope that it will be useful,       *
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
 *   GNU General Public License for more details.                          *
 *                                                                         *
 *   You should have received a copy of the GNU Library General Public     *
 *   License along with this program; if not, write to the                 *
 *   Free Software Foundation, Inc.,                                       *
 *   59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
 *                                                                         *
 *   For details about the authors of this software, see the AUTHORS file. *
 ***************************************************************************/

package jolie;

import java.util.Map;
import java.util.concurrent.Future;
import jolie.net.SessionMessage;
import jolie.runtime.InputOperation;

/**
 *
 * @author Fabrizio Montesi
 */
public abstract class TransparentExecutionThread extends ExecutionThread
{
	public TransparentExecutionThread( jolie.process.Process process, ExecutionThread parent )
	{
		super( process, parent );
	}

	public jolie.State state()
	{
		return parent.state();
	}

	public Future< SessionMessage> requestMessage( InputOperation operation, ExecutionThread ethread )
	{
		return parent.requestMessage( operation, ethread );
	}

	public Future< SessionMessage> requestMessage( Map< String, InputOperation> operations, ExecutionThread ethread )
	{
		return parent.requestMessage( operations, ethread );
	}

	@Override
	public String getSessionId()
	{
		return parent.getSessionId();
	}
}

Fix for invoke@Reflection, part 2

Fix for invoke@Reflection, part 2

Former-commit-id: 776857b21442ba09a1c3944411dac07eb18b2f73


package lemming.data;

import java.util.AbstractMap;

/**
 * An Entry maintaining a key and a value. The value may be changed using the setValue method.
 *
 * @param <K> key data type
 * @param <V> value data type
 * @see java.util.AbstractMap.SimpleEntry
 */
public class Tuple<K, V> extends AbstractMap.SimpleEntry<K, V> {

    /**
     * Creates a tuple.
     *
     * @param key   key object
     * @param value value object
     */
    public Tuple(K key, V value) {
        super(key, value);
    }
}

Implement a tuple data type based on class AbstractMap.SimpleEntry.


package leetcode.triangle;

import java.util.ArrayList;
import java.util.Arrays;

public class Solution {
    public int minimumTotal(ArrayList<ArrayList<Integer>> triangle) {
        if(triangle == null || triangle.size() == 0) return 0;
        int size = triangle.size();
        for(int i = size - 1; i > 0; i--){
        	for(int j = 0; j < i; j++){
        		ArrayList<Integer> row_i = triangle.get(i);
        		ArrayList<Integer> row_i_1 = triangle.get(i - 1);
        		int a = row_i.get(j);
        		int b = row_i.get(j + 1);
        		int v = row_i_1.get(j);
        		row_i_1.set(j, v + Math.min(a, b));
        	}
        }
        return triangle.get(0).get(0);
    }
    public static void main(String[] args){
    	ArrayList<ArrayList<Integer>> input = new ArrayList<ArrayList<Integer>>();
    	input.add(new ArrayList<Integer>(Arrays.asList(new Integer[]{2})));
    	input.add(new ArrayList<Integer>(Arrays.asList(new Integer[]{3, 4})));
    	input.add(new ArrayList<Integer>(Arrays.asList(new Integer[]{6, 5, 7})));
    	input.add(new ArrayList<Integer>(Arrays.asList(new Integer[]{4, 1, 8, 3})));
    	System.err.println(new Solution().minimumTotal(input) + "");
    }
}

Add java solution for 120. Triangle

Add java solution for 120. Triangle

120. Triangle: https://leetcode.com/problems/triangle/


package com.google.sps.tool;

import java.io.IOException;
import javax.servlet.http.HttpServletResponse;
import com.google.gson.Gson;
import java.util.Map;
import java.util.HashMap;

public class ResponseHandler {

  public static void sendErrorMessage(HttpServletResponse response, String error) throws IOException {
    Map<String, String> jsonErrorInfo = new HashMap<>();
    jsonErrorInfo.put("error", error);
    response.setContentType("application/json;");
    response.getWriter().println(new Gson().toJson(jsonErrorInfo));
  }
}

Add class that handles error

Add class that handles error


package com.vtence.molecule.examples.session;

import com.vtence.molecule.Application;
import com.vtence.molecule.Request;
import com.vtence.molecule.Response;
import com.vtence.molecule.Session;
import com.vtence.molecule.middlewares.Router;
import com.vtence.molecule.routing.DynamicRoutes;
import com.vtence.molecule.simple.SimpleServer;
import com.vtence.molecule.simple.session.CookieTracker;
import com.vtence.molecule.simple.session.SessionPool;

import java.io.IOException;

public class EnablingSessions {

    public static void main(String[] args) throws IOException {
        SimpleServer server = new SimpleServer(8080);

        // Enable sessions, using a cookie tracking strategy with an in-memory session pool
        server.enableSessions(new CookieTracker(new SessionPool()));

        server.run(Router.draw(new DynamicRoutes() {{

            map("/").to(new Application() {
                public void handle(Request request, Response response) throws Exception {
                    Session session = request.session(false);
                    String username = (session != null) ?
                            session.<String>get("username") : "Guest";
                    response.body("Welcome, " + username);
                }
            });

            post("/login").to(new Application() {
                public void handle(Request request, Response response) throws Exception {
                    String username = request.parameter("username");
                    request.session().put("username", username);
                    response.redirectTo("/");
                }
            });

            delete("/logout").to(new Application() {
                public void handle(Request request, Response response) throws Exception {
                    Session session = request.session(false);
                    if (session != null) session.invalidate();
                    response.redirectTo("/");
                }
            });
        }}));
    }
}

Add example showing basic session usage

Add example showing basic session usage


package dijkstras;

import dijkstras.Dijkstras;		// My implementation of Dijkstras algorithm in package dijkstras

/*
	This class test Dijkstras shortest path algorithm
*/

class TestDijkstras
{

	// Test A

	public static void testA(){

		int N = 6;		// No. of vertices
		int M = 10;		// No. of edges
		int edges[][] = {	{1,2,10}, 		// Edges
							{2,3,1},
							{3,4,4},
							{4,3,6},
							{5,4,2},
							{1,5,5},
							{2,5,2},
							{5,2,3},
							{5,3,9},
							{4,1,7}
						};

		int s = 1;		// source vertex

		Dijkstras dk = new Dijkstras(N, M, edges, s);

		dk.findShortestPaths();

		System.out.println("Shortest Distances: ");
		dk.showDist();

		System.out.println("Shortest Paths: ");
		for(int i=1;i<=N;i++){

			System.out.print(i+ ": ");
			dk.printPath(i);
			System.out.println();
		}

	}

	public static void main(String args[]){

			// Call testA()

			testA();
	}
}

Add test class for dijkstras algorithm

Add test class for dijkstras algorithm


package leetcode.maximal_rectangle;

import java.util.Random;
import java.util.Stack;

public class Solution {
    public int maximalRectangle(char[][] matrix) {
    	if(matrix == null || matrix.length == 0 || matrix[0].length == 0) return 0;
    	int height = matrix.length;
    	int width = matrix[0].length;
    	int[][] subsum = new int[height][width];
        for(int i = 0; i < height; i++){
        	for(int j = 0; j < width; j++){
        		if(i == 0){
        			subsum[i][j] = (matrix[i][j] == '1' ? 1 : 0);
        		}else{
        			if(matrix[i][j] == '1'){
        				subsum[i][j] = subsum[i - 1][j];
        			}
        			subsum[i][j] += (matrix[i][j] == '1' ? 1 : 0);
        		}
        	}
        }
        int maxArea = 0;
        for(int i = 0; i < height; i++){
        	int area = largestRectangleArea(subsum[i]);
        	if(area > maxArea) maxArea = area;
        }
        return maxArea;
    }

    public static class Histogram{
		int offset, height;
		public Histogram(int offset, int height){
			this.offset = offset;
			this.height = height;
		}
	}

    public int largestRectangleArea(int[] height) {
    	Stack<Histogram> stack = new Stack<Histogram>();
    	int length = height.length;
    	int max = 0;
    	for(int i = 0; i < length; i++){
    		int left = i;
    		while(!stack.isEmpty() && stack.peek().height >= height[i]){
    			Histogram hist = stack.pop();
    			int area = hist.height * (i - hist.offset);
    			left = hist.offset;
    			if(area > max) max = area;
    		}
    		stack.push(new Histogram(left, height[i]));
    	}
    	while(!stack.isEmpty()){
			Histogram hist = stack.pop();
			int area = hist.height * (length - hist.offset);
			if(area > max) max = area;
    	}
    	return max;
    }

    public static void main(String[] args){
    	int W = 10, H = 5;
    	char[][] matrix = new char[H][W];
    	Random r = new Random();
    	for(int i = 0; i < H; i++){
    		for(int j = 0; j < W; j++){
    			int d = r.nextInt(7);
    			if(d > 0)
    				matrix[i][j] = '1';
    			else
    				matrix[i][j] = '0';
    		}
    	}
    	for(char[] s : matrix){
    		System.err.println(s);
    	}
    	System.err.println(new Solution().maximalRectangle(matrix));
    }
}

Add java solution for 85. Maximal Rectangle

85. Maximal Rectangle: https://leetcode.com/problems/maximal-rectangle/


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

import org.junit.Test;
import org.spine3.test.Tests;

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

    @Test
    public void have_private_utility_ctor() {
        Tests.hasPrivateParameterlessCtor(Versions.class);
    }

    @Test(expected = IllegalArgumentException.class)
    public void check_version_increment() {
        Versions.checkIsIncrement(
                Tests.newVersionWithNumber(2),
                Tests.newVersionWithNumber(1)
        );
    }
}

Increase coverage of `Versions` tests

Increase coverage of `Versions` tests


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

/**
 * FIXME
 *
 * @author Emerson Farrugia
 */
public class DataPointRequest {

}

Add a bare data point request

Add a bare data point request


package edu.chl.proton.model;

import org.testng.annotations.Test;
import static org.junit.Assert.assertTrue;

/**
 * @author Stina Werme
 * Created by stinawerme on 09/05/17.
 */
public class FileTest {

    @Test public void test() {
    }
}

Add test class for File

Add test class for File


package leetcode;

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

/**
 * https://leetcode.com/problems/n-queens/
 */
public class Problem51 {
    public List<List<String>> solveNQueens(int n) {
        List<List<String>> result = new ArrayList<>();
        // TODO
        return result;
    }

    public static void main(String[] args) {
        Problem51 prob = new Problem51();
        List<List<String>> result = prob.solveNQueens(4);
        for (List<String> row : result) {
            System.out.println(row);
        }
    }
}

Add skeleton for problem 51

Add skeleton for problem 51


package mylab.puzzles;

/**
 * Minimum Horizontal Strokes
 *
 * Sample input:
 * A[] = new int[]{1,1,1,1}
 * Output:
 * 1
 *
 * Sample input:
 * A[] = new int[]{1,3,2,1,2,1,5,3,3,4,2}
 * Output:
 * 9
 *
 * If strokes > 1,000,000,000 then return -1
 *
 * http://stackoverflow.com/questions/33399211/how-to-find-least-strokes-required-to-paint-a-skyline-with-time-and-storage-comp
 *
 */

public class MinHorizontalStrokes {

		public int solve(int A[]) {
        int level = 0;
        int strokes = 0;

        for (int i = 0;i < A.length;i++) {
            if (A[i] > level) {
                strokes += A[i] - level;
                level = A[i];
            } else if (A[i] < level) {
                level = A[i];
            }

            if (strokes > 1000000000)
                return -1;
      	}
      	return strokes;
		}

		public static void main(String[] args) {
				MinHorizontalStrokes problem = new MinHorizontalStrokes();
				System.out.println(problem.solve(new int[]{ 1,1,1,1 }));
				System.out.println(problem.solve(new int[]{ 1,3,2,1,2,1,5,3,3,4,2 }));
		}

}

Add puzzle from OrionHealth interview question taken from codility.com