public class MatrixChainMultiplication {
    public static void main(String[] args) {
        System.out.println(solve(new int[] { 6, 4, 30, 2, 10, 5 }));
    }

    public static int solve(int[] matrices) {
        int length = matrices.length;
        int[][] dp = new int[length][length];

        for (int i = 0; i < length; i ++) {
            for (int j = 0; j < length; j ++) {
                dp[i][j] = i == j ? 0 : Integer.MAX_VALUE;
            }
        }

        for (int jump = 1; jump < length - 1; jump ++) {
            for (int i = 1; i + jump < length; i ++) {
                int j = i + jump;
                int product = matrices[i - 1] * matrices[j];
                for (int k = i; k < j; k ++) {
                    dp[i][j] = Math.min(dp[i][j], dp[i][k] + dp[k + 1][j] + (product * matrices[k]));
                }
            }
        }

        for (int i = 0; i < length; i ++) {
            for (int j = 0; j < length; j ++) {
                if (dp[i][j] == Integer.MAX_VALUE) {
                    System.out.print("-\t");
                } else {
                    System.out.print(dp[i][j] + "\t");
                }
            }
            System.out.println("");
        }

        return dp[1][length - 1];

    }
}

Add matrix chain multiplication algorithm


package org.apache.markt;

import java.util.EnumSet;

import javax.servlet.DispatcherType;
import javax.servlet.Filter;
import javax.servlet.FilterRegistration;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;

@WebListener
public class ConfigListener implements ServletContextListener {

    @Override
    public void contextInitialized(ServletContextEvent sce) {
        Filter f = new NoopFilter();

        FilterRegistration.Dynamic reg = sce.getServletContext().addFilter("noop", f);
        reg.addMappingForUrlPatterns(EnumSet.of(DispatcherType.REQUEST), true, "/*");
    }

    @Override
    public void contextDestroyed(ServletContextEvent sce) {
        // NO-OP
    }
}

Add a listener to configure the filter

Add a listener to configure the filter


package com.exalttech.trex.core;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

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

public class RCPCommands {
    private static final class Commands {
        private static final String GET_ACTIVE_PGIDS = "get_active_pgids";
        private static final String GET_PGID_STATS = "get_pgid_stats";
    }

    private RCPCommands() {}

    public static String getActivePGIds() throws JsonProcessingException {
        return sendRequest(Commands.GET_ACTIVE_PGIDS, null);
    }

    public static String getPGIdStats(List<Integer> pgIds) throws JsonProcessingException {
        if (pgIds == null) {
            pgIds = new ArrayList<>();
        }
        final Map<String, Object> parameters = new HashMap<>();
        parameters.put("pgids", pgIds);
        return sendRequest(Commands.GET_PGID_STATS, parameters);
    }

    // Should be removed from here, it is needed only for old architecture
    private static String sendRequest(final String command, final Map<String, Object> parameters) throws
            JsonProcessingException
    {
        String stringParameters = "";
        if (parameters != null) {
            final String jsonParameters = new ObjectMapper().writeValueAsString(parameters);
            stringParameters = jsonParameters.substring(1, jsonParameters.length() - 1);
        }
        return ConnectionManager.getInstance().sendRequest(command, stringParameters);
    }
}

Add getActivePGIds and getPGIdStats commands.


package me.haosdent.cgroup.manage;

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

public class TestAdmin {

  @Before
  public void setUp() {}

  @After
  public void tearDown() {}

  @Test
  public void testUmount() {}

  @Test
  public void testCreateGroup() {}
}

Add admin manage test class.

Add admin manage test class.


package me.haosdent.cgroup.manage;

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

public class TestGroup {

  @Before
  public void setUp() {}

  @After
  public void tearDown() {}

  @Test
  public void testDelete() {}
}

Add group manage test class.

Add group manage test class.


package com.netflix.suro.routing.filter;

import com.google.common.base.Predicate;

/**
 * A contract for filtering events. These filters can be applied/defined both at the publisher and subscriber level.

 * It is recommended to use a filter language as specified in {@link com.netflix.suro.routing.filter.lang} which provides
 * flexible ways of defining filters. However, for programmatic creation of simple or custom filters it may be easy
 * to directly implement this interface.

 * The structure of the event filters is entirely opaque to the event bus and all processing related to evaluation of
 * the same is left to the implementations.
 */
public interface MessageFilter extends Predicate<Object> {

    // Emphasize that every {@code MessageFilter} instance can be used as a key
    // in a collection.
    public int hashCode();

    public boolean equals(Object o);
}

Fix compilation error caused by missing class


package com.hubspot.singularity;

import com.codahale.metrics.servlets.MetricsServlet;
import io.dropwizard.Bundle;
import io.dropwizard.lifecycle.ServerLifecycleListener;
import io.dropwizard.setup.Bootstrap;
import io.dropwizard.setup.Environment;
import org.eclipse.jetty.server.Server;

import javax.servlet.ServletContext;

/**
 * Expose Dropwizard's metrics registry to {@link com.hubspot.jackson.jaxrs.PropertyFilteringMessageBodyWriter}
 * via the servlet context.
 *
 * This class is picked up by autoconfig
 */
public class MetricsBundle implements Bundle {

  @Override
  public void initialize(Bootstrap<?> bootstrap) { }

  @Override
  public void run(final Environment environment) {
    // need to wait until the server is started to do this otherwise an IllegalStateException is thrown
    environment.lifecycle().addServerLifecycleListener(new ServerLifecycleListener() {
      @Override
      public void serverStarted(Server server) {
        ServletContext context = environment.getJerseyServletContainer().getServletContext();
        context.setAttribute(MetricsServlet.METRICS_REGISTRY, environment.metrics());
      }
    });
  }
}

Add a bundle to set the correct MetricsRegistry on the ServletContext


// [START apps_script_execute]
/**
 * Call the API to run an Apps Script function that returns a list
 * of folders within the user's root directory on Drive.
 *
 * @return list of String folder names and their IDs
 * @throws IOException
 */
private List<String> getDataFromApi()
        throws IOException, GoogleAuthException {
    // ID of the script to call. Acquire this from the Apps Script editor,
    // under Publish > Deploy as API executable.
    String scriptId = "ENTER_YOUR_SCRIPT_ID_HERE";

    List<String> folderList = new ArrayList<String>();

    // Create an execution request object.
    ExecutionRequest request = new ExecutionRequest()
            .setFunction("getFoldersUnderRoot");

    // Make the request.
    Operation op =
            mService.scripts().run(scriptId, request).execute();

    // Print results of request.
    if (op.getError() != null) {
        throw new IOException(getScriptError(op));
    }
    if (op.getResponse() != null &&
            op.getResponse().get("result") != null) {
        // The result provided by the API needs to be cast into
        // the correct type, based upon what types the Apps Script
        // function returns. Here, the function returns an Apps
        // Script Object with String keys and values, so must be
        // cast into a Java Map (folderSet).
        Map<String, String> folderSet =
                (Map<String, String>)(op.getResponse().get("result"));

        for (String id: folderSet.keySet()) {
            folderList.add(
                    String.format("%s (%s)", folderSet.get(id), id));
        }
    }

    return folderList;
}

/**
 * Interpret an error response returned by the API and return a String
 * summary.
 *
 * @param op the Operation returning an error response
 * @return summary of error response, or null if Operation returned no
 *     error
 */
private String getScriptError(Operation op) {
    if (op.getError() == null) {
        return null;
    }

    // Extract the first (and only) set of error details and cast as a Map.
    // The values of this map are the script's 'errorMessage' and
    // 'errorType', and an array of stack trace elements (which also need to
    // be cast as Maps).
    Map<String, Object> detail = op.getError().getDetails().get(0);
    List<Map<String, Object>> stacktrace =
            (List<Map<String, Object>>)detail.get("scriptStackTraceElements");

    java.lang.StringBuilder sb =
            new StringBuilder("\nScript error message: ");
    sb.append(detail.get("errorMessage"));

    if (stacktrace != null) {
        // There may not be a stacktrace if the script didn't start
        // executing.
        sb.append("\nScript error stacktrace:");
        for (Map<String, Object> elem : stacktrace) {
            sb.append("\n  ");
            sb.append(elem.get("function"));
            sb.append(":");
            sb.append(elem.get("lineNumber"));
        }
    }
    sb.append("\n");
    return sb.toString();
}
// [END apps_script_execute]

Migrate Apps Script Execution Snippet

Migrate Apps Script Execution Snippet


package no.panopticon.client.sensor.impl;

import no.panopticon.client.model.Measurement;
import no.panopticon.client.sensor.Sensor;

import java.time.LocalDateTime;
import java.util.List;

import static java.util.Collections.singletonList;

public class ReportTimeSensor implements Sensor {
    @Override
    public List<Measurement> measure() {
        return singletonList(
                new Measurement("report.generated", "INFO", LocalDateTime.now().toString(), 0)
        );
    }
}

Add a sensor which gives the time for when the report was generated


/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.laadadra.fitools.option;

import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.runner.RunWith;
import org.junit.runners.Suite;

/**
 *
 * @author nabil.laadadra
 */
@RunWith(Suite.class)
@Suite.SuiteClasses(
{
  com.laadadra.fitools.option.OptionTest.class, com.laadadra.fitools.option.GaussianTest.class
})
public class OptionTestSuite
{

  @BeforeClass
  public static void setUpClass() throws Exception
  {
  }

  @AfterClass
  public static void tearDownClass() throws Exception
  {
  }

  @Before
  public void setUp() throws Exception
  {
  }

  @After
  public void tearDown() throws Exception
  {
  }

}

Add test suite for option tests

Add test suite for option tests


package leetcode.recover_binary_search_tree;

import java.util.Random;

import common.TreeNode;

public class Solution {
	TreeNode OffendingNode1;
	TreeNode OffendingNode2;
	TreeNode prev;

	public void inOrder(TreeNode node){
		if(node != null){
			inOrder(node.left);
			if(OffendingNode1 == null && prev != null && prev.val > node.val){
				OffendingNode1 = prev;
			}
			if(OffendingNode1 != null && OffendingNode2 == null && node.val > OffendingNode1.val){
				OffendingNode2 = prev;
			}
			prev = node;
			inOrder(node.right);
		}
	}

    public void recoverTree(TreeNode root) {
    	prev = OffendingNode1 = OffendingNode2 = null;
    	inOrder(root);
    	if(OffendingNode2 == null){
    		OffendingNode2 = prev;
    	}
    	int tmp = OffendingNode1.val;
    	OffendingNode1.val = OffendingNode2.val;
    	OffendingNode2.val = tmp;
    }

	public static int fillNumber = 0;

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

    public static void main(String[] args){
    	final int N = 15;
    	TreeNode[] tree = new TreeNode[N];
    	for(int i = N - 1; i >= 0; i--){
    		tree[i] = new TreeNode(0);
    		if(i * 2 + 1 < N)
    			tree[i].left = tree[i * 2 + 1];
    		if(i * 2 + 2 < N)
    			tree[i].right = tree[i * 2 + 2];
    	}
    	inOrder(tree[0], true);
    	System.err.println("");

    	Random r = new Random();
    	int x = r.nextInt(N);
    	int y = x;
    	while(y == x){
    		y = r.nextInt(N);
    	}
    	System.err.println(tree[x].val + " swaps " + tree[y].val);
    	int tmp = tree[x].val;
    	tree[x].val = tree[y].val;
    	tree[y].val = tmp;

    	inOrder(tree[0], false);
    	System.err.println("");

    	new Solution().recoverTree(tree[0]);

    	inOrder(tree[0], false);
    	System.err.println("");

    	TreeNode tn1 = new TreeNode(2);
    	TreeNode tn2 = new TreeNode(1);
    	tn1.right = tn2;
    	inOrder(tn1, false);
    	System.err.println("");
    	new Solution().recoverTree(tn1);
    	inOrder(tn1, false);
    	System.err.println("");
    }
}

Add java solution for 99. Recover Binary Search Tree

99. Recover Binary Search Tree: https://leetcode.com/problems/recover-binary-search-tree/


package de.fau.amos.virtualledger.dtos;

public class SavingsAccountSubGoal {

    private String name;
    private String amount;

    public String getName() {
        return name;
    }

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

    public String getAmount() {
        return amount;
    }

    public void setAmount(final String amount) {
        this.amount = amount;
    }
}

Add data object for saving SubGoals

Add data object for saving SubGoals


package com.jakewharton.trakt.services;

import com.jakewharton.trakt.entities.TvShow;
import retrofit.http.GET;
import retrofit.http.Path;

/**
 * Endpoints for Show.
 */
public interface Show {

    @GET("/show/summary.json/{apikey}/{title}")
    TvShow summary(
            @Path("title") String slug
    );

    @GET("/show/summary.json/{apikey}/{title}")
    TvShow summary(
            @Path("title") int tvdbId
    );

    @GET("/show/summary.json/{apikey}/{title}/extended")
    TvShow summaryExtended(
            @Path("title") String slug
    );

    @GET("/show/summary.json/{apikey}/{title}/extended")
    TvShow summaryExtended(
            @Path("title") int tvdbId
    );

}

Add retrofit interface for show summary.


package uk.org.taverna.scufl2.api.common;

import org.junit.Test;

import uk.org.taverna.scufl2.api.ExampleWorkflow;
import uk.org.taverna.scufl2.api.common.Visitor.VisitorAdapter;
import uk.org.taverna.scufl2.api.container.WorkflowBundle;

public class TestSetParent {
	WorkflowBundle example = new ExampleWorkflow().makeWorkflowBundle();

	Scufl2Tools tools = new Scufl2Tools();

	@Test
	public void checkParents() throws Exception {
		example.accept(new VisitorAdapter() {
			@Override
			public boolean visit(WorkflowBean node) {
				if (node instanceof Child) {
					Child child = (Child) node;
					WorkflowBean parent = child.getParent();
					WorkflowBean expectedParent = getCurrentPath().peek();
					if (!(parent == expectedParent)) {
						throw new IllegalStateException("Wrong parent for "
								+ node + ": " + parent + ", expected: "
								+ expectedParent);
					}
				}
				return true;
			}

			@Override
			public boolean visitEnter(WorkflowBean node) {
				visit(node);
				return super.visitEnter(node);
			}
		});
	}

}

Test that all parents are set

Test that all parents are set


/*
 * Copyright 2015 iychoi.
 *
 * 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.iplantcollaborative;

import org.apache.commons.collections4.map.LRUMap;

/**
 *
 * @author iychoi
 */
public class UUIDCache {

    private static final int DEFAULT_CACHE_SIZE = 10000;

    private LRUMap<String, String> cache = new LRUMap<String, String>(DEFAULT_CACHE_SIZE);

    public UUIDCache() {
    }

    public void cache(String uuid, String path) {
        this.cache.put(uuid, path);
    }

    public String get(String uuid) {
        return this.cache.get(uuid);
    }

    public void clearCache() {
        this.cache.clear();
    }
}

Use parent Directory for checking access permission. Cache Access permission for frequently requested path and userid. Refactor objectification of an iRODS json message.


package net.openhft.chronicle.map.example;

import net.openhft.chronicle.map.ChronicleMap;
import net.openhft.chronicle.map.ChronicleMapBuilder;
import net.openhft.lang.model.DataValueClasses;
import net.openhft.lang.values.LongValue;

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

public class DistributedSequenceMain {

    public static void main(String... ignored) throws IOException {
        Class<LongValue> longValueClass = DataValueClasses.directClassFor(LongValue.class);
        ChronicleMap<String, LongValue> map =
                ChronicleMapBuilder.of(String.class, longValueClass)
                        .entries(128)
                        .actualSegments(1)
                        .create(new File("/tmp/counters"));
        LongValue value = DataValueClasses.newDirectReference(longValueClass);
        map.acquireUsing("sequence", value);

        for (int i = 0; i < 1000000; i++) {
            long nextId = value.addAtomicValue(1);
        }

        map.close();
    }
}

Add an examples for distributed counters.


//
// EventHandler.java
//

/*
ImageJ software for multidimensional image processing and analysis.

Copyright (c) 2010, ImageJDev.org.
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
    * Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright
      notice, this list of conditions and the following disclaimer in the
      documentation and/or other materials provided with the distribution.
    * Neither the names of the ImageJDev.org developers nor the
      names of its contributors may be used to endorse or promote products
      derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/

package imagej.event;

/**
 * Convenience class for subscribers that wish to be notified of ImageJ events.
 *
 * @author Curtis Rueden
 * @param <E> Type of event for which to listen
 */
public abstract class EventHandler<E extends ImageJEvent> implements
	PriorityEventSubscriber<E>
{

	private int priority;

	public EventHandler() {
		this(Events.NORMAL_PRIORITY);
	}

	public EventHandler(final int priority) {
		this.priority = priority;
	}

	@Override
	public int getPriority() {
		return priority;
	}

}

Add convenience class for prioritized event handling.

This used to be revision r3228.


package org.mastercoin;

/**
 * Number type to represent an Omni protocol property type.
 */
public class PropertyType extends Number {
    private final int value;

    public static final int INDIVISIBLE_VALUE = 1;
    public static final int DIVISIBLE_VALUE = 2;

    public static final PropertyType INDIVISIBLE = new PropertyType(INDIVISIBLE_VALUE);
    public static final PropertyType DIVISIBLE = new PropertyType(DIVISIBLE_VALUE);

    public PropertyType(short value) {
        if (!(value == INDIVISIBLE_VALUE ||
              value == DIVISIBLE_VALUE)) {
            throw new NumberFormatException();
        }
        this.value = value;
    }

    public PropertyType(int value) {
        this.value = value;
    }

    @Override
    public int intValue() {
        return value;
    }

    @Override
    public long longValue() {
        return (long) value;
    }

    @Override
    public float floatValue() {
        return (float) value;
    }

    @Override
    public double doubleValue() {
        return (double) value;
    }

    @Override
    public int hashCode() {
        return Integer.valueOf(value).hashCode();
    }

    @Override
    public boolean equals(Object obj) {
        if (!(obj instanceof PropertyType)) {
            return false;
        }
        if (obj == this) {
            return true;
        }
        return this.value == ((PropertyType)obj).value;
    }
}

Extend Number type to represent property types


# Copyright [2014] [Kyle McGovern]

# 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.security.NoSuchAlgorithmException;
import javax.crypto.Cipher;

public class UnlimitedSupportJCETest
{
   public static void main(final String[] args)
   {
   int strength = 0;
   try {
      strength = Cipher.getMaxAllowedKeyLength("AES");
   } catch (NoSuchAlgorithmException e) {
      System.out.println("isUnlimitedSupported=FALSE");
      return;
   }
   if ( strength > 128 ){
      System.out.printf("isUnlimitedSupported=TRUE, strength: %d%n", strength);
   } else {
      System.out.printf("isUnlimitedSupported=FALSE, strength: %d%n", strength);
      }
   }
}

Add Java code used for testing JCE policy installation


package com.sdoward.rxgooglemap;

import com.google.android.gms.maps.*;

import org.junit.*;
import org.junit.runner.RunWith;
import org.mockito.*;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;

import rx.observers.TestSubscriber;

import static org.mockito.Mockito.verify;

@RunWith(PowerMockRunner.class)
@PrepareForTest(GoogleMap.class)
public class MapObservableProviderTest {

    @Mock
    private MapFragment mapFragment;
    @Mock
    private SupportMapFragment supportMapFragment;
    @Mock
    private MapView mapView;
    @Mock
    private GoogleMap googleMap;
    @Captor
    private ArgumentCaptor<OnMapReadyCallback> argumentCaptor;

    @Test
    public void shouldReturnMapFromFragment() {
        TestSubscriber<GoogleMap> subscriber = new TestSubscriber<>();
        new MapObservableProvider(mapFragment)
                .getMapReadyObservable()
                .subscribe(subscriber);
        verify(mapFragment).getMapAsync(argumentCaptor.capture());
        argumentCaptor.getValue().onMapReady(googleMap);
        subscriber.assertNoErrors();
        subscriber.assertValue(googleMap);
    }

    @Test
    public void shouldReturnMapFromSupportFragment() {
        TestSubscriber<GoogleMap> subscriber = new TestSubscriber<>();
        new MapObservableProvider(supportMapFragment)
                .getMapReadyObservable()
                .subscribe(subscriber);
        verify(supportMapFragment).getMapAsync(argumentCaptor.capture());
        argumentCaptor.getValue().onMapReady(googleMap);
        subscriber.assertNoErrors();
        subscriber.assertValue(googleMap);
    }

    @Test
    public void shouldReturnMapFromView() {
        TestSubscriber<GoogleMap> subscriber = new TestSubscriber<>();
        new MapObservableProvider(mapView)
                .getMapReadyObservable()
                .subscribe(subscriber);
        verify(mapView).getMapAsync(argumentCaptor.capture());
        argumentCaptor.getValue().onMapReady(googleMap);
        subscriber.assertNoErrors();
        subscriber.assertValue(googleMap);
    }

}

Add tests for receiving googleMap

Add tests for receiving googleMap


package com.networknt.schema;

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

public class ValidatorTypeCodeTest {

    @Test
    public void testFromValueString() {
        assertEquals(ValidatorTypeCode.ADDITIONAL_PROPERTIES, ValidatorTypeCode.fromValue("additionalProperties"));
    }

    @Test
    public void testFromValueAll() {
        for (ValidatorTypeCode code : ValidatorTypeCode.values()) {
            assertEquals(code, ValidatorTypeCode.fromValue(code.getValue()));
        }
    }

    @Test(expected = IllegalArgumentException.class)
    public void testFromValueMissing() {
        assertEquals(ValidatorTypeCode.ADDITIONAL_PROPERTIES, ValidatorTypeCode.fromValue("missing"));
    }

}

Add simple tests for ValidatorTypeCode

Add simple tests for ValidatorTypeCode


package com.jaselogic.adamsonelearn;

import java.util.ArrayList;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

public abstract class BaseListAdapter extends BaseAdapter {
	private ArrayList<ViewProducer> mListItems;
	private LayoutInflater mLayoutInflater;

	public BaseListAdapter(Context context, ArrayList<ViewProducer> arrayList) {
		mListItems = arrayList;
		mLayoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
	}

    @Override
    public final int getItemViewType(int position) {
    	// TODO Auto-generated method stub
    	//return mListItems.get(position).viewType;
    	//return 0;
    	return mListItems.get(position).getViewTypeOrdinal();
    }

    @Override
    public final int getViewTypeCount() {
    	return this.viewTypeCount();
    }

	@Override
    public final int getCount() {
        //getCount() represents how many items are in the list
        return mListItems.size();
    }

    @Override
    //get the data of an item from a specific position
    //i represents the position of the item in the list
    public final Object getItem(int i) {
        return null;
    }

    @Override
    //get the position id of the item from the list
    public final long getItemId(int i) {
        return 0;
    }

    @Override
    public final View getView(int position, View view, ViewGroup viewGroup) {
    	return mListItems.get(position).produceView(view, mLayoutInflater);
    }

	public abstract int viewTypeCount();

	public interface ViewProducer {
		public View produceView(View convertView, LayoutInflater inflater);
		public int getLayoutId();
		public int getViewTypeOrdinal();
	}
}

Add generic base list adapter

Add generic base list adapter


/*
 * 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.android.gnd.rx;

import androidx.annotation.NonNull;
import io.reactivex.Single;
import io.reactivex.functions.Consumer;
import javax.annotation.Nullable;

public class Result<T> {
  public enum State {
    SUCCESS,
    ERROR
  }

  private final State state;

  @Nullable private final T value;
  @Nullable private final Throwable error;

  private Result(State state, @Nullable T value, @Nullable Throwable error) {
    this.state = state;
    this.value = value;
    this.error = error;
  }

  public static <T> Result<T> success(@NonNull T result) {
    return new Result<>(State.SUCCESS, result, null);
  }

  public static <T> Result<T> error(@NonNull Throwable t) {
    return new Result<>(State.ERROR, null, t);
  }

  @Nullable
  public State getState() {
    return state;
  }

  @Nullable
  public T get() {
    return value;
  }

  @Nullable
  public Throwable getError() {
    return error;
  }

  public static <T> Single<Result<T>> wrap(Single<T> single) {
    return single.map(Result::success).onErrorReturn(Result::error);
  }

  public static <T> Consumer<? super Result<T>> unwrap(
      Consumer<T> onSuccess, Consumer<Throwable> onError) {
    return result -> {
      switch (result.getState()) {
        case SUCCESS:
          onSuccess.accept(result.get());
          break;
        case ERROR:
          onError.accept(result.getError());
          break;
      }
    };
  }
}

Add simple wrapper for streaming results


/*
 * Copyright 2000-2010 JetBrains s.r.o.
 *
 * 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.
 */

/*
 * @author max
 */
package com.intellij.rt.execution;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.ArrayList;
import java.util.List;

public class ExternalClasspathClassLoader extends URLClassLoader {
  public ExternalClasspathClassLoader() {
    super(parseUrls());
  }

  private static URL[] parseUrls() {
    final List urls = new ArrayList();
    final File file = new File(System.getProperty("classpath.file"));
    try {
      final BufferedReader reader = new BufferedReader(new FileReader(file));
      try {
        while(reader.ready()) {
          final String fileName = reader.readLine();
          try {
            urls.add(new File(fileName).toURI().toURL());
          }
          catch (NoSuchMethodError e) {
            urls.add(new File(fileName).toURL());
          }
        }
      }
      finally {
        reader.close();
      }

      return (URL[])urls.toArray(new URL[urls.size()]);
    }
    catch (IOException e) {
      throw new RuntimeException("Cannot read classpath entries from file: " + e);
    }
    finally {
      file.delete();
    }
  }
}

Use custom classloader that reads classpath entries from the file to avoid failure creating junit process.


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

import java.util.List;

import uk.ac.ebi.phenotype.imaging.persistence.ImaImageRecord;
import uk.ac.ebi.phenotype.imaging.springrest.images.Image;
import uk.ac.ebi.phenotype.imaging.springrest.images.Images;
/**
 * Images dao interface used by currently hibernate and our images restful web service
 * @author jwarren
 *
 */
public interface ImagesDao {

	public Images getAllImages(int start,int length, String search);

	public ImaImageRecord getImageWithId(int id);

	public long getTotalNumberOfImages();

	public ImaImageRecord queryDatabaseById(String id);
}

Change copyright in Apache 2 license to 2013 documented documented images rest service returns one imagerecord if id requested , id removed from url make ImaImageRecord queryDatabaseById(String id) method public for use in testing imaging java classes added


package cs437.som.topology;

import cs437.som.Dimension;
import cs437.som.GridType;
import cs437.som.SOMError;

/**
 * A square grid strategy for SOMs, using Manhattan distance, which corresponds
 * to the Von Neumann neighborhood.
 */
public class VonNeumann implements GridType {
    private int neuronCount = 0;
    private int width = 0;

    @Override
    public void setNeuronCount(Dimension dimension) {
        width = dimension.x;
        neuronCount = width * dimension.y;
    }

    @Override
    public double gridDistance(int neuron0, int neuron1) {
        if (neuron0 > neuronCount || neuron0 < 0) {
            throw new SOMError("Invalid neuron index: " + neuron0);
        }

        if (neuron1 > neuronCount || neuron1 < 0) {
            throw new SOMError("Invalid neuron index: " + neuron1);
        }

        int row0 = neuron0 / width;
        int col0 = neuron0 % width;
        int row1 = neuron1 / width;
        int col1 = neuron1 % width;

        int dr = Math.abs(row1 - row0);
        int dc = Math.abs(col1 - col0);

        return dr + dc;
    }

    @Override
    public String toString() {
        return "VonNeumann";
    }
}

Add Von Neumann neighborhood square grid to topologies.


package leetcode;

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

/**
 * https://leetcode.com/problems/combination-sum-iii/
 */
public class Problem216 {
    public List<List<Integer>> combinationSum3(int k, int n) {
        List<List<Integer>> result = new ArrayList<>();
        // TODO
        return result;
    }

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

Add a skeleton for problem 216

Add a skeleton for problem 216


package org.gwtbootstrap3.client.ui;

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

import org.gwtbootstrap3.client.ui.CheckBoxButton;

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

public class GwtTestCheckBoxButton extends GWTTestCase {

    /**
     * Specifies a module to use when running this test case. The returned
     * module must include the source for this class.
     *
     * @see com.google.gwt.junit.client.GWTTestCase#getModuleName()
     */
    @Override
    public String getModuleName() {
        return "org.gwtbootstrap3.GwtBootstrap3";
    }

    public void testLabel() {
        final String label = "label";

        final CheckBoxButton button = new CheckBoxButton(label);

        assertEquals(label, button.getText());
    }

}

Add a simple test of CheckBoxButton

Add a simple test of CheckBoxButton


package com.boundary.metrics.vmware;

import java.io.File;

import com.boundary.metrics.vmware.poller.MORCatalog;
import com.boundary.metrics.vmware.poller.MORCatalogFactory;

public class CatalogValidate {

	CatalogValidate() {

	}

	public boolean validate(File catalogFile) {
		boolean valid = true;
		MORCatalog catalog = MORCatalogFactory.create(catalogFile);

		valid = catalog.isValid(false);

		return valid;
	}

	public static void main(String [] args) {

		if (args.length != 1) {
			System.err.println("usage: " + CatalogValidate.class.getCanonicalName() + " <path to catalog>");
			System.exit(1);
		}
		CatalogValidate validator = new CatalogValidate();
		boolean valid = validator.validate(new File(args[0]));
		System.err.printf("catalog %s is %s\n",args[0], valid ? "valid" : "not valid");
	}

}

Add program to validate catalog

Add program to validate catalog


/*
 * Copyright (C) 2015 Archie L. Cobbs. All rights reserved.
 */

package org.jsimpledb;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.util.List;

import javax.validation.Constraint;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import javax.validation.Payload;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;

import org.jsimpledb.annotation.JField;
import org.jsimpledb.annotation.JListField;
import org.jsimpledb.annotation.JSimpleClass;
import org.jsimpledb.annotation.OnValidate;
import org.jsimpledb.test.TestSupport;
import org.testng.Assert;
import org.testng.annotations.Test;

public class ValidationInvalidTargetTypeTest extends TestSupport {

    @Test
    public void testValidationInvalidTargetType() {

        final JSimpleDB jdb = BasicTest.getJSimpleDB(Person1.class, Person2.class);

        JTransaction tx = jdb.createTransaction(true, ValidationMode.AUTOMATIC);
        JTransaction.setCurrent(tx);
        try {

            Person1 p1 = tx.create(Person1.class);
            Person1 p1m = tx.create(Person1.class);

            p1.setFriend(p1m);

            // A bug was causing the following exception on the following statement:
            // java.lang.IllegalArgumentException: invalid target type org.jsimpledb.SelfReferenceTest$HasFriend
            //      for index query on field `friend' in interface org.jsimpledb.SelfReferenceTest$HasFriend:
            //      should be a super-type or sub-type of org.jsimpledb.SelfReferenceTest$Person
            tx.validate();

            tx.commit();
        } finally {
            JTransaction.setCurrent(null);
        }
    }

// Model Classes

    public interface HasFriend {

        @JField(storageId = 200, unique = true)
        HasFriend getFriend();
        void setFriend(HasFriend person);
    }

    public abstract static class Person implements JObject {
    }

    @JSimpleClass(storageId = 100)
    public abstract static class Person1 extends Person implements HasFriend {
    }

    @JSimpleClass(storageId = 101)
    public abstract static class Person2 extends Person implements HasFriend {
    }
}

Add unit test exposing a bug in validation.


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

package de.sormuras.bach.task;

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

import de.sormuras.bach.API;
import de.sormuras.bach.Workspace;
import org.junit.jupiter.api.Test;

class BuildTaskFactoryTests {

  @Test
  void empty() {
    var factory = new BuildTaskFactory(Workspace.of(), API.emptyProject(), false);
    var task = assertDoesNotThrow(factory::get);
    assertTrue(task.composite());
  }
}

Check non-verbose build task generation

Check non-verbose build task generation


/*
 Copyright (C) 2003 EBI, GRL

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

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

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

import java.sql.Connection;
import java.util.HashMap;
import java.util.Map;

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

/**
 * Check the padding in the stable_id_1051 column in certain species.
 */

public class StableIDPadding extends SingleDatabaseTestCase {

	String column = "stable_id_1051";
	Map<String,Integer> tablePaddingLength;

	/**
	 * Constructor.
	 */
	public StableIDPadding() {

		setTeamResponsible("biomart");
		addToGroup("post_martbuild");
		setDescription("Check the padding in the stable_id_1051 column in certain species.");

		tablePaddingLength = new HashMap<String,Integer>();
		tablePaddingLength.put("hsapiens_functional_genomics__regulatory_feature__dm",  15);
		tablePaddingLength.put("mmusculus_functional_genomics__regulatory_feature__dm", 18);

	}

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

		boolean result = true;

		Connection con = dbre.getConnection();

		for (String table : tablePaddingLength.keySet()) {

			int paddingLength = tablePaddingLength.get(table);

			int rows = getRowCount(con, "SELECT COUNT(*) FROM " + table + " WHERE LENGTH(" + column + ") != " + paddingLength);

			if (rows > 0) {

				ReportManager.problem(this, con, rows + " rows in " + table + " do not have padded stable IDs of required length (" + paddingLength + ")");
				result = false;

			} else {

				ReportManager.correct(this, con, "All rows in " + table + " have padded stable IDs of required length (" + paddingLength + ")");

			}
		}

		return result;

	} // run

} // StableIDPadding


public class Solution {

    public int maxCount(int m, int n, int[][] ops) {

        int row = m;
        int col = n;

        for (int[] op : ops) {
            row = Math.min(row, op[0]);
            col = Math.min(col, op[1]);
        }

        return row * col;

    }

}

Create : 598 Range Addition II

Create : 598 Range Addition II


package org.nwapw.abacus.fx;

import javafx.beans.property.BooleanProperty;
import javafx.beans.property.SimpleBooleanProperty;

public class ToggleablePlugin {

    private final BooleanProperty enabled;
    private final String className;

    public ToggleablePlugin(boolean enabled, String className){
        this.enabled = new SimpleBooleanProperty();
        this.enabled.setValue(enabled);
        this.className = className;
    }

    public BooleanProperty enabledProperty() {
        return enabled;
    }

    public boolean isEnabled() {
        return enabled.get();
    }

    public String getClassName() {
        return className;
    }

}

Add a data model for the plugins displayed in the enabled plugins list.


/*
 * Copyright (C) 2009 Jayway AB
 * Copyright (C) 2007-2008 JVending Masa
 * Copyright (C) 2010 akwuinet A.G.
 *
 * 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.jayway.maven.plugins.android.standalonemojos;

import com.jayway.maven.plugins.android.AbstractIntegrationtestMojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;

import java.io.File;

/**
 * Redeploys the built apk file, or another specified apk, to a connected device.
 * This simply tries to undeploy the APK and re-deploy it.
 * @author clement.escoffier@akquinet.de
 * @goal redeploy
 * @requiresProject false
 * @requiresDependencyResolution runtime
 */
public class RedeployMojo extends AbstractIntegrationtestMojo {

    /**
     * Optionally used to specify a different apk file to deploy to a connected emulator or usb device, instead of the
     * built apk from this project.
     *
     * @parameter expression="${android.file}"
     */
    private File file;

    public void execute() throws MojoExecutionException, MojoFailureException {
        if (file == null) {
            String packageToUndeploy = extractPackageNameFromAndroidManifest(androidManifestFile);
            undeployApk(packageToUndeploy);
            deployBuiltApk();
        } else {
            undeployApk(file);
            deployFile(file);
        }
    }

}

Fix issue-49. Add a simple redeploy mojo.


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

package imagej.core.plugins.display;

import imagej.data.Dataset;
import imagej.data.display.ScreenCaptureService;
import imagej.ext.menu.MenuConstants;
import imagej.ext.module.ItemIO;
import imagej.ext.plugin.RunnablePlugin;
import imagej.ext.plugin.Menu;
import imagej.ext.plugin.Parameter;
import imagej.ext.plugin.Plugin;

/**
 * Captures the entire screen to a {@link Dataset}.
 *
 * @author Barry DeZonia
 */
@Plugin(menu = {
	@Menu(label = MenuConstants.PLUGINS_LABEL,
			weight = MenuConstants.PLUGINS_WEIGHT,
			mnemonic = MenuConstants.PLUGINS_MNEMONIC),
	@Menu(label = "Utilities"),
	@Menu(label = "Capture Screen", weight = 19,
				accelerator = "shift control G")})
public class CaptureScreen implements RunnablePlugin {

	// -- Parameters --

	@Parameter
	private ScreenCaptureService captureService;

	@Parameter(type=ItemIO.OUTPUT)
	private Dataset output;

	// -- accessors --

	public Dataset getOutput() {
		return output;
	}

	// -- run() method --

	@Override
	public void run() {
		output = captureService.captureScreen();
		output.setName("Screen capture");
	}

}

Add a pure IJ2 version of Capture Screen plugin


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

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import javax.swing.table.AbstractTableModel;

/**
 * A super simple table model for the navigator UI.
 *
 * @author Michael J. Simons, 2016-09-16
 */
public class MappedElementsModel extends AbstractTableModel {

    private static final long serialVersionUID = 5870247061989235811L;

    private final List<MappedElement> data = Collections.synchronizedList(new ArrayList<MappedElement>());

    @Override
    public String getColumnName(int column) {
        String rv;
        switch (column) {
            case 0:
                rv = "Resource URL";
                break;
            case 1:
                rv = "Request Method";
                break;
            case 2:
                rv = "Handler Method";
                break;
            default:
                rv = null;
        }
        return rv;
    }

    @Override
    public int getRowCount() {
        return this.data.size();
    }

    @Override
    public int getColumnCount() {
        return 3;
    }

    @Override
    public Object getValueAt(int rowIndex, int columnIndex) {
        final MappedElement mappedElement = this.data.get(rowIndex);
        Object rv;
        switch (columnIndex) {
            case 0:
                rv = mappedElement.getUrl();
                break;
            case 1:
                rv = mappedElement.getMethod();
                break;
            case 2:
                rv = mappedElement.getElement().toString();
                break;
            default:
                rv = null;
        }

        return rv;
    }

    void refresh(final List<MappedElement> newData) {
        this.data.clear();
        this.data.addAll(newData);
        this.fireTableDataChanged();
    }
}

Add table model for mapped elements

Add table model for mapped elements


package leetcode.summary_ranges;

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

public class Solution {
    public List<String> summaryRanges(int[] nums) {
        List<String> ans = new ArrayList<String>();
        if(nums == null || nums.length == 0) return ans;
        int from = nums[0], cur = nums[0];
        for(int i = 1; i < nums.length; i++){
            if(nums[i] == cur + 1){
                cur = nums[i];
            }else{
                if(from == cur){
                    ans.add(Integer.toString(cur));
                }else{
                    ans.add(from + "->" + cur);
                }
                from = cur = nums[i];
            }
        }
        if(from == cur){
            ans.add(Integer.toString(cur));
        }else{
            ans.add(from + "->" + cur);
        }
        return ans;
    }
}

Add java solution for 228. Summary Ranges

228. Summary Ranges: https://leetcode.com/problems/summary-ranges/


/**
 *
 */
package com.trendrr.strest.contrib.filters;

import java.util.Date;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jboss.netty.handler.codec.http.HttpResponse;

import com.trendrr.strest.StrestException;
import com.trendrr.strest.server.StrestController;
import com.trendrr.strest.server.StrestControllerFilter;

/**
 * @author Dustin Norlander
 * @created May 17, 2011
 *
 */
public class TimingFilter implements StrestControllerFilter {

	protected Log log = LogFactory.getLog(TimingFilter.class);

	/* (non-Javadoc)
	 * @see com.trendrr.strest.server.StrestControllerFilter#before(com.trendrr.strest.server.StrestController)
	 */
	@Override
	public void before(StrestController controller) throws StrestException {
		controller.getTxnStorage().put("timing_filter_start", new Date());
		System.out.println("timing start");
	}

	/* (non-Javadoc)
	 * @see com.trendrr.strest.server.StrestControllerFilter#after(com.trendrr.strest.server.StrestController)
	 */
	@Override
	public void after(StrestController controller) throws StrestException {
		System.out.println("timing start");
		Date start = (Date)controller.getTxnStorage().remove("timing_filter_start");
		if (start == null)
			return;
		this.timingResult(controller, new Date().getTime()-start.getTime());
	}

	/**
	 * Override this to do something else with the timing information.
	 *
	 * Examples: logging, tracking long running actions, ect.
	 *
	 * @param controller
	 * @param millis
	 */
	public void timingResult(StrestController controller, long millis) {
		System.out.println(millis);

		StringBuilder str = new StringBuilder();
		str.append("*************** Action COMPLETE ****\n");
		str.append("Route : " );
		for (String r : controller.routes()) {
			str.append(r + ",");
		}
		str.append("\nParams: ");
		str.append( controller.getParams().toJSONString());
		str.append("\nMillis: ");
		str.append(millis);
		str.append("\n************************************\n");
		log.info(str.toString());
	}

	/* (non-Javadoc)
	 * @see com.trendrr.strest.server.StrestControllerFilter#error(com.trendrr.strest.server.StrestController, org.jboss.netty.handler.codec.http.HttpResponse, java.lang.Exception)
	 */
	@Override
	public void error(StrestController controller, HttpResponse response,
			Exception exception) {
		// TODO Auto-generated method stub

	}
}

Add a filter to measure number of millis a controller takes


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

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

import javax.validation.Constraint;
import javax.validation.Payload;
import javax.validation.ReportAsSingleViolation;
import javax.validation.constraints.Pattern;

/**
 * A constraint for validating email addresses.
 *
 * Based on:
 * - http://stackoverflow.com/q/4459474
 * - https://gist.github.com/php-coder/1616466
 *
 * @author Piotr Rusin <piotr.rusin88@gmail.com>
 *
 */
@org.hibernate.validator.constraints.Email
@Pattern(regexp = ".+@.+\\..+")
@ReportAsSingleViolation
@Target({ElementType.FIELD, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = {})
@Documented
public @interface Email {
	String message() default "{org.hibernate.validator.constraints.Email.message}";
	Class<?>[] groups() default {};
    Class<? extends Payload>[] payload() default {};
}

Add an email validation constraint

Add an email validation constraint


/*
 * See LICENSE file in distribution for copyright and licensing information.
 */
package ioke.lang.performance;

import java.io.*;

import ioke.lang.*;
import ioke.lang.parser.*;

/**
 * @author Ola Bini
 */
public class Parsing {
    public static void main(String[] args) throws Exception, ioke.lang.exceptions.ControlFlow {
        String filename = args[0];
        System.out.println("Reading of file: \"" + filename + "\"");

        File f = new File(filename);
        InputStream reader = new FileInputStream(f);
        byte[] result = new byte[(int)f.length()];

        int offset = 0;
        int numRead = 0;
        while(offset < result.length && (numRead = reader.read(result, offset, result.length-offset)) >= 0) {
            offset += numRead;
        }
        reader.close();

        long before, after, time;
        double timeS;

        ioke.lang.Runtime runtime = new ioke.lang.Runtime();
        runtime.init();
        for(int j=0;j<10;j++) {
            before = System.currentTimeMillis();
            for(int i=0;i<100;i++) {
                IokeParser parser = new IokeParser(runtime, new InputStreamReader(new ByteArrayInputStream(result)), null, null);
                IokeObject m = parser.parseFully();
                ((Message)IokeObject.data(m.runtime.opShuffle)).sendTo(m.runtime.opShuffle, m.runtime.ground, m);
            }
            after = System.currentTimeMillis();
            time = after-before;
            timeS = (after-before)/1000.0;
            System.out.printf(" %-10d %-10f\n", time, timeS);
        }
    }
}// Parsing

Add a performance tester for parsing

Add a performance tester for parsing


package com.cyq7on.leetcode.stack;

import java.util.Stack;

/**
 * @author cyq7on
 * @description Given a string S of lowercase letters, a duplicate removal consists of choosing two adjacent and equal letters, and removing them.
 *

 * We repeatedly make duplicate removals on S until we no longer can.
 *

 * Return the final string after all such duplicate removals have been made.  It is guaranteed the answer is unique.
 *

 *

 *

 * Example 1:
 *

 * Input: "abbaca"
 * Output: "ca"
 * Explanation:
 * For example, in "abbaca" we could remove "bb" since the letters are adjacent and equal, and this is the only possible move.
 * The result of this move is that the string is "aaca", of which only "aa" is possible, so the final string is "ca".
 * @create 2019/12/11
 **/
public class RemoveAllAdjacentDuplicatesInString {

    public String removeDuplicates(String s) {
        Stack<Character> stack = new Stack<>();
        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            if (stack.isEmpty() || stack.peek() != c) {
                stack.push(c);
            }else {
                stack.pop();
            }
        }
        int size = stack.size();
        char[] chars = new char[size];
        for (int i = 0; i < size; i++) {
            chars[size - i - 1] = stack.pop();
        }
        return new String(chars);
    }

    public static void main(String[] args) {
        RemoveAllAdjacentDuplicatesInString duplicatesInString = new RemoveAllAdjacentDuplicatesInString();
        System.out.println(duplicatesInString.removeDuplicates("abbaca"));
    }
}

Remove All Adjacent Duplicates In String


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

import java.io.IOException;

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

/**
 * A simple action that redirects to the main page of the wiki
 *
 * @author sgm
 */
public class HomePageRedirect extends HttpServlet {
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO: configure the main page?
        response.sendRedirect("bin/view/Main/");
    }
}

XWIKI-608: Add a default index page redirecting to /bin/view/Main/
Implemented using a simple servlet.

git-svn-id: 50c93b9c2d9041e46610830dd7836bad08be8b2e@1859 f329d543-caf0-0310-9063-dda96c69346f


/*
 * 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.usergrid.rest.exceptions;

import javax.ws.rs.core.Response;
import javax.ws.rs.ext.Provider;

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

import static javax.ws.rs.core.Response.Status.INTERNAL_SERVER_ERROR;

@Provider
public class RuntimeExceptionMapper extends AbstractExceptionMapper<RuntimeException> {

    private static final Logger logger = LoggerFactory.getLogger(RuntimeExceptionMapper.class);

    @Override
    public Response toResponse( RuntimeException e ) {

        if(logger.isTraceEnabled()) {
            logger.trace("Error during runtime processing", e.getMessage());
        }

        return toResponse( INTERNAL_SERVER_ERROR, e );
    }
}

Add runtime exception mapper to 500 status code.


package io.vertx.rxjava.ext.swagger.router;

import io.swagger.models.Swagger;
import io.swagger.parser.SwaggerParser;

import io.vertx.core.json.JsonArray;
import io.vertx.ext.unit.Async;
import io.vertx.ext.unit.TestContext;
import io.vertx.ext.unit.junit.VertxUnitRunner;
import io.vertx.rxjava.core.Vertx;
import io.vertx.rxjava.core.buffer.Buffer;
import io.vertx.rxjava.core.eventbus.EventBus;
import io.vertx.rxjava.core.file.FileSystem;
import io.vertx.rxjava.ext.web.Router;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;

import java.nio.charset.Charset;

@RunWith(VertxUnitRunner.class)
public class SwaggerRouterTest {
    private static Vertx vertx;
    private static EventBus eventBus;
    private static JsonArray definitions;

    @BeforeClass
    public static void beforeClass(TestContext context) {
        Async async = context.async();
        vertx = Vertx.vertx();
        eventBus = vertx.eventBus();

        FileSystem vertxFileSystem = vertx.fileSystem();
        vertxFileSystem.readFile("swaggerRouterTest.json", readFile -> {
            try {
                if (readFile.succeeded()) {
                    final Buffer buffer = readFile.result();
                    definitions = new JsonArray(buffer.toString(Charset.forName("utf-8").toString()));
                } else {
                    context.fail(readFile.cause());
                }
            } catch (Throwable cause) {
                context.fail(cause);
            } finally {
                async.complete();
            }
        });
    }

    @Test(expected = IllegalArgumentException.class)
    public void testIllegalPathParameterName() {
        String definition = definitions.getJsonObject(0).encode();
        Swagger swagger = new SwaggerParser().parse(definition);
        SwaggerRouter.swaggerRouter(Router.router(vertx), swagger, eventBus);
    }

    @Test(expected = IllegalArgumentException.class)
    public void testEmptyPathParameterName() {
        String definition = definitions.getJsonObject(1).encode();
        Swagger swagger = new SwaggerParser().parse(definition);
        SwaggerRouter.swaggerRouter(Router.router(vertx), swagger, eventBus);
    }

    @Test(expected = IllegalArgumentException.class)
    public void testNumericPathParameterName() {
        String definition = definitions.getJsonObject(2).encode();
        Swagger swagger = new SwaggerParser().parse(definition);
        SwaggerRouter.swaggerRouter(Router.router(vertx), swagger, eventBus);
    }

    @Test(expected = IllegalArgumentException.class)
    public void testPathParameterNameStartsWithNumber() {
        String definition = definitions.getJsonObject(3).encode();
        Swagger swagger = new SwaggerParser().parse(definition);
        SwaggerRouter.swaggerRouter(Router.router(vertx), swagger, eventBus);
    }

    @Test
    public void testAlphaNumericPathParameterName() {
        String definition = definitions.getJsonObject(4).encode();
        Swagger swagger = new SwaggerParser().parse(definition);
        SwaggerRouter.swaggerRouter(Router.router(vertx), swagger, eventBus);
    }

}

Test added for SwaggerRouter Rx wrapper

Test added for SwaggerRouter Rx wrapper


package io.netty.testsuite.transport.socket.nio.oio;

import java.util.concurrent.Executor;

import io.netty.channel.socket.DatagramChannelFactory;
import io.netty.channel.socket.nio.NioDatagramChannelFactory;
import io.netty.channel.socket.oio.OioDatagramChannelFactory;
import io.netty.testsuite.transport.socket.AbstractDatagramMulticastTest;

public class NioOioDatagramMulticastTest extends AbstractDatagramMulticastTest {

    @Override
    protected DatagramChannelFactory newServerSocketChannelFactory(Executor executor) {
        return new OioDatagramChannelFactory(executor);
    }

    @Override
    protected DatagramChannelFactory newClientSocketChannelFactory(Executor executor) {
        return new NioDatagramChannelFactory(executor);

    }

}

package io.netty.testsuite.transport.socket.nio.oio;

import java.util.concurrent.Executor;

import io.netty.channel.socket.DatagramChannelFactory;
import io.netty.channel.socket.nio.NioDatagramChannel;
import io.netty.channel.socket.nio.NioDatagramChannelFactory;
import io.netty.channel.socket.oio.OioDatagramChannelFactory;
import io.netty.testsuite.transport.socket.AbstractDatagramMulticastTest;

public class NioOioDatagramMulticastTest extends AbstractDatagramMulticastTest {

    @Override
    protected DatagramChannelFactory newServerSocketChannelFactory(Executor executor) {
        return new OioDatagramChannelFactory(executor);
    }

    @Override
    protected DatagramChannelFactory newClientSocketChannelFactory(Executor executor) {
        return new NioDatagramChannelFactory(executor, NioDatagramChannel.ProtocolFamily.INET);

    }

}

Make sure multicast tests pass on all os'es


package com.informatorio;

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

/**
 * Created by Informatorio on 05/09/2016.
 */
public class Main {
    public static void main(String[] args) {
        Pilot pilot = new Pilot("Pilot", 14, "undefined");
        Eva one = new Eva(100, "01", Color.BLUE, pilot, Collections.emptyList());
        Eva two = new Eva(75, "02", Color.RED, pilot, Collections.emptyList());
        Eva three = new Eva(80, "03", Color.RED, pilot, Collections.emptyList());
        List<Eva> evas = new ArrayList<Eva>();
        evas.add(one);
        evas.add(two);
        evas.add(three);
        //Comparator<Eva> color = ColorComparator.INSTANCE;
        Collections.sort(evas);
        printList(evas);
        Collections.sort(evas, new Comparator<Eva>() {
            @Override
            public int compare(Eva o1, Eva o2) {
                return Integer.compare(o1.getCharge(), o2.getCharge());
            }
        });
        printList(evas, "charge");
    }

    private static void printList(List<Eva> evas, String field) {
        System.out.println("============================ " + field + "============================");
        for (Eva e : evas) {
            System.out.println(e);
        }
        System.out.println("============================ Funny Line ============================");
    }

    private static void printList(List<Eva> evas) {
        printList(evas, "Normal");
    }
}

Move class to the correct folder

Move class to the correct folder


/* $Id$ */

/**
* 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.manifoldcf.core.interfaces;

/** An IThrottleSpec object describes what throttling criteria to apply
* per bin.
*/
public interface IThrottleSpec
{
  public static final String _rcsid = "@(#)$Id$";

  /** Given a bin name, find the max open connections to use for that bin.
  *@return -1 if no limit found.
  */
  public int getMaxOpenConnections(String binName);

  /** Look up minimum milliseconds per byte for a bin.
  *@return 0.0 if no limit found.
  */
  public double getMinimumMillisecondsPerByte(String binName);

  /** Look up minimum milliseconds for a fetch for a bin.
  *@return 0 if no limit found.
  */
  public long getMinimumMillisecondsPerFetch(String binName);

}

Add definition of throttler class

Add definition of throttler class

git-svn-id: 1c3cc8ce44b6d2f166b170cdd93b19b2713d8895@1550265 13f79535-47bb-0310-9956-ffa450edef68


/**
 * Twist in the Tale 3.1 from the OCA Java SE 7 book by Mala Gupta (Manning Publications)
 * Created by Josef on 12/24/13.
 */
class Phone {
    String phoneNumber = "123456789";
    void setNumber() {
        String phoneNumber;
        phoneNumber = "987654321";
    }
}

class TestPhone {
    public static void main(String[] args) {
        Phone p1 = new Phone();
        p1.setNumber();
        System.out.println(p1.phoneNumber);
    }
}

Add code for Twist In The Tale 3.1

Add code for Twist In The Tale 3.1


package leetcode;

import java.util.Arrays;

/**
 * https://leetcode.com/problems/set-matrix-zeroes/
 */
public class Problem73 {
    public void setZeroes(int[][] matrix) {

    }

    public static void main(String[] args) {
        Problem73 prob = new Problem73();
        int[][] matrix = new int[][] {
            new int[]{1, 0, 1, 1},
            new int[]{0, 1, 1, 1},
            new int[]{0, 1, 1, 1}
        };
        prob.setZeroes(matrix);
        for (int i = 0; i < matrix.length; i++) {
            System.out.println(Arrays.toString(matrix[i]));
        }
    }
}

Add skeleton for problem 73

Add skeleton for problem 73


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

/**
 * Implementations of various hash functions.
 *
 * @author ctolooee
 */
package mendel.dht.hash;

Add dht.hash pkg for various hash functions


class List {
  public int head;
  public List tail;

  public List(int h, List t) {
    head = h;
    tail = t;
  }
}

public class Main {
  public static void main(String[] args) {
    List L1 = list(1, list(2, list(3, null)));
    List L2 = list(5, list(6, list(7, null)));
    write("L1 is ");write_list(L1);
    writeln("L1 length is " + length(L1));
    writeln("L1 sum is " + sum(L1));
    writeln("L1 last element is " + last(L1));
    writeln("Are there duplicated elements is L1? " + duplicated(L1));
    write("L1 reversed WITHOUT accumulator is ");write_list(reverse(L1));
  }

  static List list(int head, List tail) {
    return new List(head, tail);
  }

  static int head(List xs) {
    return xs.head;
  }

  static List tail(List xs) {
    return xs.tail;
  }

  static boolean empty(List xs) {
    return xs == null;
  }

  static int length(List xs) {
    if (empty(xs)) return 0;
    return 1 + length(tail(xs));
  }

  static int sum(List xs) {
    if (empty(xs))
      return 0;
    return head(xs) + sum(tail(xs));
  }

  static int last(List xs) {
    if (empty(tail(xs)))
      return head(xs);
    return last(tail(xs));
  }

  static boolean member(int x, List xs) {
    if (empty(xs))
      return false;
    if (x == head(xs))
      return true;
    return member(x , tail(xs));
  }

  static boolean duplicated(List xs) {
    if (empty(xs))
      return false;
    if (member(head(xs), tail(xs)))
      return true;
    return duplicated(tail(xs));
  }

  static void reverse(List xs) {

  }

  static void write_list(List xs) {
    if (empty(xs))
      write("\n");
    else {
      write(" " +head(xs) + " ");
      write_list(tail(xs));
    }
  }

  static void write(String str) {
    System.out.print(str);
  }

  static void writeln(String str) {
    write(str);
    write("\n");
  }
}

Add recursived list in Java

Add recursived list in Java


package todomore.android;

import android.app.Application;

public class TodoMoreApplication extends Application {

	private TaskDao mTaskDao;

	@Override
	public void onCreate() {
		super.onCreate();
		mTaskDao = new TaskDao(this);
	}

	public TaskDao getTaskDao() {
		return mTaskDao;
	}
}

Bring back an App Singleton, to house a single copy of the TaskDao.


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

import java.util.Dictionary;
import java.util.Hashtable;
import junit.framework.TestCase;
import org.osgi.framework.Filter;
import org.osgi.framework.FrameworkUtil;

public class FilterTest extends TestCase
{
    public void testMissingAttribute()
    {
        Dictionary dict = new Hashtable();
        dict.put("one", "one-value");
        dict.put("two", "two-value");
        dict.put("three", "three-value");
        Filter filter = null;
        try
        {
            filter = FrameworkUtil.createFilter("(missing=value)");
        }
        catch (Exception ex)
        {
            assertTrue("Filter should parse: " + ex, false);
        }
        assertFalse("Filter should not match: " + filter, filter.match(dict));
    }
}

Add a test case for missing attributes in filters, which was previously
causing an NPE. (FELIX-2401)

git-svn-id: e057f57e93a604d3b43d277ae69bde5ebf332112@957239 13f79535-47bb-0310-9956-ffa450edef68


package xyz.juanes.atakingos.ui;

import android.util.Log;

public class AtakingosLayer
{
  //Default width
  public static int def_width = 400;

  //Default height (only for landscape)
  public static int def_height = 400;

  //Screen width and height
  public static int width, height;

  //Scale
  public static float scale;

  //Game zone class
  public static class zone
  {
    //Zone positions
    public static int width, height, px, py;
  }

  //Game background class
  public static class background
  {
    //background positions
    public static int width, height, px, py;
  }

  //Constructor
  public static void init(int w, int h, String mode)
  {
    //Save the game width
    width = w;

    //Save the game height
    height = h;

    //Calculate the game scale
    scale = (mode.equals("landscape")) ? (float) height / def_height : (float) width / def_width;

    //Display in console
    Log.i("Blocks Scale", scale + "");

    //Zone width
    zone.width = (mode.equals("landscape")) ? (int)(450 * scale) : (int)(350 * scale);

    //Zone height
    zone.height = (mode.equals("landscape")) ? (int)(350 * scale) : (int)(450 * scale);

    //Background width
    background.width = (mode.equals("landscape")) ? (int)(800 * scale) : (int)(400 * scale);

    //Background height
    background.height = (mode.equals("landscape")) ? (int)(400 * scale) : (int)(800 * scale);

    //Zone position x
    zone.px = (int)(width / 2 - zone.width / 2);

    //Zone position y
    zone.py = (int)(height / 2 - zone.height / 2);

    //Background position x
    background.px = (int)(width / 2 - background.width / 2);

    //Background position y
    background.py = (int)(height / 2 - background.height / 2);
  }
}

Initialize the game layer definitions

Initialize the game layer definitions


// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.concurrent;

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

/**
 * @author bjorncs
 */
public class Threads {

    private Threads() {}

    /** Returns all threads in JVM */
    public static Collection<Thread> getAllThreads() {
        ThreadGroup root = Thread.currentThread().getThreadGroup();
        ThreadGroup parent;
        while ((parent = root.getParent()) != null) {
            root = parent;
        }
        // The number of threads may increase between activeCount() and enumerate()
        Thread[] threads = new Thread[root.activeCount() + 100];
        int count;
        while ((count = root.enumerate(threads, true)) == threads.length) {
            threads = new Thread[threads.length + 1000];
        }
        return List.of(Arrays.copyOf(threads, count));
    }
}

Add helper to get all threads in JVM

Add helper to get all threads in JVM


package com.pm.server;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

@Configuration
public class PmServerConfiguration {

    @Bean
    public WebMvcConfigurer corsConfigurer() {
        return new WebMvcConfigurerAdapter() {
            @Override
            public void addCorsMappings(CorsRegistry registry) {
                registry.addMapping("/**");
            }
        };
    }
}

Add CORS access header to configuration

Add CORS access header to configuration


package net.straylightlabs.hola.utils;

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

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

public class Utils {
    private static int nextDumpPathSuffix;
    private final static Logger logger = LoggerFactory.getLogger(Utils.class);

    static {
        nextDumpPathSuffix = 1;
    }

    /**
     * Save @buffer to a new file beginning with @prefix. Append a sequential suffix to ensure we don't
     * overwrite existing files.
     * @param buffer The byte buffer to dump to disk
     * @param prefix The start of the file name
     */
    @SuppressWarnings("unused")
    public static void dumpBuffer(byte[] buffer, String prefix) {
        try {
            Path path = getNextPath(prefix);
            logger.info("Dumping buffer to {}", path);
            Files.write(path, buffer);
        } catch (IOException e) {
            logger.error("Error writing file: {}", e.getLocalizedMessage());
        }
    }

    /**
     * Get the next sequential Path for a binary dump file, ensuring we don't overwrite any existing files.
     * @param prefix The start of the file name
     * @return Next sequential Path
     */
    public static Path getNextPath(String prefix) {
        Path path;

        do {
            path = Paths.get(prefix, Integer.toString(nextDumpPathSuffix));
            nextDumpPathSuffix++;
        } while (Files.exists(path));

        return path;
    }
}

Add utility methods for dumping binary packets to disk.


/*
 * Copyright 2011 Bert van Brakel
 *
 * 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.codemucker.lang.annotation;

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

/**
 * Marks a class as immutable
 */
@Documented
@Retention(RetentionPolicy.SOURCE)
@Target({ElementType.TYPE})
public @interface Immutable {

	/**
	 * Any special conditions attached to being immutable
	 */
	String caveats() default "";
}

Add annotation to mark immutability

Add annotation to mark immutability


package com.andela.webservice.parser;

import com.andela.webservice.model.Flower;

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

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

/**
 * Created by Spykins on 08/06/16.
 */
public class FlowerJsonParser {

    public static List<Flower> parseFeed(String content) {
        List<Flower> flowerList = new ArrayList<>();
        try {
            JSONArray ar = new JSONArray(content);
            // we can't use for  each loop on JSonArray
            for(int i = 0; i < ar.length(); i++) {
                JSONObject obj = ar.getJSONObject(i);
                Flower flower = new Flower();
                flower.setProductId(obj.getInt("productId"));
                flower.setCategory(obj.getString("category"));
                flower.setInstructions(obj.getString("instructions"));
                flower.setPhoto(obj.getString("photo"));
                flower.setPrice(obj.getDouble("price"));
                flowerList.add(flower);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return flowerList;
    }
}

Implement JsonParser to read the data

Implement JsonParser to read the data


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

import com.yahoo.container.bundle.BundleInstantiationSpecification;
import com.yahoo.container.handler.ThreadPoolProvider;
import com.yahoo.container.handler.ThreadpoolConfig;
import com.yahoo.osgi.provider.model.ComponentModel;
import com.yahoo.vespa.model.container.component.SimpleComponent;

import java.time.Duration;

/**
 * Component definition for a {@link java.util.concurrent.Executor} using {@link ThreadPoolProvider}.
 *
 * @author bjorncs
 */
public class ThreadPoolExecutorComponent extends SimpleComponent implements ThreadpoolConfig.Producer {

    private final String name;
    private final Integer maxPoolSize;
    private final Integer corePoolSize;
    private final Duration keepAliveTime;
    private final Integer queueSize;
    private final Duration maxThreadExecutionTime;

    private ThreadPoolExecutorComponent(Builder builder) {
        super(new ComponentModel(
                BundleInstantiationSpecification.getFromStrings(
                        "threadpool-provider@" + builder.name,
                        ThreadPoolProvider.class.getName(),
                        null)));
        this.name = builder.name;
        this.maxPoolSize = builder.maxPoolSize;
        this.corePoolSize = builder.corePoolSize;
        this.keepAliveTime = builder.keepAliveTime;
        this.queueSize = builder.queueSize;
        this.maxThreadExecutionTime = builder.maxThreadExecutionTime;
    }

    @Override
    public void getConfig(ThreadpoolConfig.Builder builder) {
        builder.name(this.name);
        if (maxPoolSize != null) builder.maxthreads(maxPoolSize);
        if (corePoolSize != null) builder.corePoolSize(corePoolSize);
        if (keepAliveTime != null) builder.keepAliveTime(keepAliveTime.toMillis() / 1000D);
        if (queueSize != null) builder.queueSize(queueSize);
        if (maxThreadExecutionTime != null) builder.maxThreadExecutionTimeSeconds((int)maxThreadExecutionTime.toMillis() / 1000);
    }

    public static class Builder {

        private final String name;
        private Integer maxPoolSize;
        private Integer corePoolSize;
        private Duration keepAliveTime;
        private Integer queueSize;
        private Duration maxThreadExecutionTime;

        public Builder(String name) { this.name = name; }

        Builder maxPoolSize(int size) { this.maxPoolSize = size; return this; }
        Builder corePoolSize(int size) { this.corePoolSize = size; return this; }
        Builder keepAliveTime(Duration time) { this.keepAliveTime = time; return this; }
        Builder queueSize(int size) { this.queueSize = size; return this; }
        Builder maxThreadExecutionTime(Duration time) { this.maxThreadExecutionTime = time; return this; }

        ThreadPoolExecutorComponent build() { return new ThreadPoolExecutorComponent(this); }

    }
}

Add component definition for ThreadPoolProvider with custom config


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

package com.github.pedrovgs.lynx;

import android.content.Context;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.widget.AbsListView;
import android.widget.ListView;
import android.widget.RelativeLayout;

/**
 * Main library view. This ViewGroup extension shows all the information
 *
 * @author Pedro Vicente Gómez Sánchez.
 */
public class LynxView extends RelativeLayout {

  private ListView lv_traces;

  public LynxView(Context context) {
    super(context);
    initializeLynxView(null);
  }

  public LynxView(Context context, AttributeSet attrs) {
    super(context, attrs);
    initializeLynxView(attrs);
  }

  public LynxView(Context context, AttributeSet attrs, int defStyleAttr) {
    super(context, attrs, defStyleAttr);
    initializeLynxView(attrs);
  }

  private void initializeLynxView(AttributeSet attrs) {
    if (attrs == null) {
      initializeConfiguration(attrs);
    }
    inflateView();
  }

  private void initializeConfiguration(AttributeSet attrs) {
    //Obtain configuration
  }

  private void inflateView() {
    Context context = getContext();
    LayoutInflater layoutInflater = LayoutInflater.from(context);
    layoutInflater.inflate(R.layout.lynx_view, this);
    mapGui();
    hookListeners();
  }

  private void mapGui() {
    lv_traces = (ListView) findViewById(R.id.lv_traces);
  }

  private void hookListeners() {
    lv_traces.setOnScrollListener(new AbsListView.OnScrollListener() {
      @Override public void onScrollStateChanged(AbsListView view, int scrollState) {

      }

      @Override public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount,
          int totalItemCount) {

      }
    });
  }
}

Add LinxView and start working with the first approximation to the library user interface


package com.ericgrandt.commands;

import org.spongepowered.api.command.Command;

public class CommandBuilder {
    public Command.Builder getBuilder() {
        return Command.builder();
    }
}

Add wrapper around the Command.builder() function to allow for unit testing


package com.google.sps.servlets;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Given a tweet or sentence, the servlet will extract salient terms from those
 * and store them in a list.
 */
@WebServlet("/keyword")
public class KeywordServlet extends HttpServlet {

  private static final List<String> tweets = new ArrayList<>();
  private static final List<String> terms = Arrays.asList("Black Lives Matter", "COVID-19");

  @Override
  public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
    // TODO: Extract saliency
    String json = mustacheJsonBuilder(terms);
    response.getWriter().println(json);
  }

  @Override
  public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
    final String tweet = request.getParameter("keyword-sentence");
    if (tweet != null && !tweet.equals("")) {
      tweets.add(request.getParameter("keyword-sentence"));
    }
    response.sendRedirect("/main.html");
  }

  /**
   * Generates and returns a JSON usable by Mustache.
   */
  private String mustacheJsonBuilder(Collection<String> toJson) {
    String builder = "{\"keywords\": [";
    for (String term : toJson) {
      builder += "{\"term\": \"" + term + "\"},";
    }

    // Remove extra comma at the end.
    builder = builder.substring(0, builder.length() - 1) + "]}";
    return builder;
  }

}

Add servlet to query Keywords

Add servlet to query Keywords


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

package com.google.gerrit.acceptance.rest.config;

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

import com.google.gerrit.acceptance.AbstractDaemonTest;
import com.google.gerrit.acceptance.RestResponse;
import com.google.gerrit.server.config.ListTasks.TaskInfo;
import com.google.gson.reflect.TypeToken;

import org.apache.http.HttpStatus;
import org.junit.Test;

import java.io.IOException;
import java.util.List;

public class ListTasksIT extends AbstractDaemonTest {

  @Test
  public void listTasks() throws IOException {
    RestResponse r = adminSession.get("/config/server/tasks/");
    assertEquals(HttpStatus.SC_OK, r.getStatusCode());
    List<TaskInfo> result =
        newGson().fromJson(r.getReader(),
            new TypeToken<List<TaskInfo>>() {}.getType());
    assertTrue(result.size() > 0);
    boolean foundLogFileCompressorTask = false;
    for (TaskInfo info : result) {
      if ("Log File Compressor".equals(info.command)) {
        foundLogFileCompressorTask = true;
      }
      assertNotNull(info.id);
      Long.parseLong(info.id, 16);
      assertNotNull(info.command);
      assertNotNull(info.startTime);
    }
    assertTrue(foundLogFileCompressorTask);
  }

  @Test
  public void listTasksWithoutViewQueueCapability() throws IOException {
    RestResponse r = userSession.get("/config/server/tasks/");
    assertEquals(HttpStatus.SC_OK, r.getStatusCode());
    List<TaskInfo> result =
        newGson().fromJson(r.getReader(),
            new TypeToken<List<TaskInfo>>() {}.getType());

    assertTrue(result.isEmpty());
  }
}

Add test for list tasks REST endpoint

Add test for list tasks REST endpoint

Change-Id: Ia8d22b2c39d82e8c4e05c7800912361f43d936a3
Signed-off-by: Edwin Kempin <b444e279ad95fdef4fbdd82c813b624595df204a@sap.com>


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

import java.util.concurrent.TimeUnit;

import org.junit.Test;

public class PostageTest {

    @Test
    public void test() throws InterruptedException {
        Main.main("./src/main/resources/postage.xml", "extended_resources");
        TimeUnit.MINUTES.sleep(1);
    }

}

Add simple temp test (POSTAGE-23)

Add simple temp test (POSTAGE-23)

git-svn-id: 0cbd32e9b25c4c4b053e190198f2521e2d278401@1350157 13f79535-47bb-0310-9956-ffa450edef68