package se.movlin.hackerrank.reviewloop;

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import java.util.function.IntPredicate;

public class Solution {

	public static void main(String[] args) {
		List<String> strings = readInput();

		for(String string : strings) {
			printString(string.toCharArray(), (i) -> i % 2 == 0);
			System.out.print(" ");
			printString(string.toCharArray(), (i) -> i % 2 == 1);
			System.out.println("");
		}

	}

	private static void printString(char[] string, IntPredicate f) {
		for (int i = 0; i<string.length; i++) {
			if (f.test(i)) {
				System.out.print(string[i]);
			}
		}
	}

	protected static List<String> readInput() {
		List<String> strings;
		int nrOfStrings;
		Scanner scanner = new Scanner(System.in);
		nrOfStrings = scanner.nextInt(); scanner.nextLine();
		strings = new ArrayList<String>(nrOfStrings);
		for (int i = 0; i < nrOfStrings; i++) {
			strings.add(scanner.nextLine());
		}
		scanner.close();
		return strings;
	}

}

Add solution for review loop


/*
 * Copyright 2017 Ivaylo Stoyanov <me@ivkos.com>
 *
 * 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.ivkos.gpsd4j.messages;

import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.ToString;

@ToString
@EqualsAndHashCode(callSuper = false)
public class ErrorMessage extends GpsdMessage
{
   public static final String CLASS = "ERROR";

   @Getter
   private String message;

   @Override
   public String getGpsdClass()
   {
      return CLASS;
   }
}

Add support for ERROR messages


/*
 * Licensed Materials - Property of IBM
 * © Copyright IBM Corporation 2015. All Rights Reserved.
 */

package com.ibm.mil.cafejava;

public class CafeJava {
}

Create initial class for library


/*
 * This file is part of ELKI:
 * Environment for Developing KDD-Applications Supported by Index-Structures
 *
 * Copyright (C) 2017
 * ELKI Development Team
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 */
package de.lmu.ifi.dbs.elki.algorithm.clustering.hierarchical.extraction;

import org.junit.Test;

import de.lmu.ifi.dbs.elki.algorithm.AbstractAlgorithm;
import de.lmu.ifi.dbs.elki.algorithm.clustering.AbstractClusterAlgorithmTest;
import de.lmu.ifi.dbs.elki.algorithm.clustering.hierarchical.AnderbergHierarchicalClustering;
import de.lmu.ifi.dbs.elki.data.Clustering;
import de.lmu.ifi.dbs.elki.database.Database;
import de.lmu.ifi.dbs.elki.utilities.ELKIBuilder;

/**
 * Regression test for k clusters with minsize extraction.
 *
 * @author Erich Schubert
 */
public class ClustersWithNoiseExtractionTest extends AbstractClusterAlgorithmTest {
  @Test
  public void testClustering() {
    Database db = makeSimpleDatabase(UNITTEST + "3clusters-and-noise-2d.csv", 330);
    Clustering<?> clustering = new ELKIBuilder<>(ClustersWithNoiseExtraction.class) //
        .with(ClustersWithNoiseExtraction.Parameterizer.K_ID, 3) //
        .with(ClustersWithNoiseExtraction.Parameterizer.MINCLUSTERSIZE_ID, 5) //
        .with(AbstractAlgorithm.ALGORITHM_ID, AnderbergHierarchicalClustering.class) //
        .build().run(db);
    testFMeasure(db, clustering, 0.9242);
    testClusterSizes(clustering, new int[] { 56, 123, 151 });
  }
}

Test for the new cluster extraction method.


/*
 * Copyright 2018 B2i Healthcare Pte Ltd, http://b2i.sg
 *
 * 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.b2international.snowowl.snomed.core.domain;

/**
 * Enumerates organization types responsible for developing and maintaining RF2 release file content.
 *
 * @see
 * 2.1.2. Release File Naming Convention
 */
public enum Rf2MaintainerType {

	/** Files are maintained and distributed by SNOMED International. */
	SNOMED_INTERNATIONAL("SNOMED International"),

	/** Files are maintained and distributed by a National Release Center (NRC). */
	NRC("National release center"),

	/** Files are maintained by a non-NRC extension provider. */
	OTHER_EXTENSION_PROVIDER("Other extension provider");

	private final String displayLabel;

	private Rf2MaintainerType(final String displayLabel) {
		this.displayLabel = displayLabel;
	}

	@Override
	public String toString() {
		return displayLabel;
	}
}

Add enum for maintaining organization type


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

/**
 * Given a singly linked list, can you write a method to return the reversed list?
 *
 * @author Pedro Vicente Gómez Sánchez.
 */
public class ReverseLinkedList {
}

Add statement to problem 22


/*
 * 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.shardingsphere.orchestration.internal.registry.fixture;

import lombok.Getter;
import lombok.Setter;
import org.apache.shardingsphere.orchestration.reg.api.RegistryCenter;
import org.apache.shardingsphere.orchestration.reg.api.RegistryCenterConfiguration;
import org.apache.shardingsphere.orchestration.reg.listener.DataChangedEventListener;

import java.util.*;
import java.util.concurrent.locks.ReentrantLock;

public final class ThirdTestRegistryCenter implements RegistryCenter {

    @Getter
    @Setter
    private Properties properties = new Properties();

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

    private ReentrantLock lock = new ReentrantLock();

    @Override
    public void init(final RegistryCenterConfiguration config) {
    }

    @Override
    public String get(final String key) {
        return "";
    }

    @Override
    public String getDirectly(final String key) {
        return keys.get(key);
    }

    @Override
    public boolean isExisted(final String key) {
        return keys.containsKey(key);
    }

    @Override
    public List<String> getChildrenKeys(final String key) {
        return Collections.emptyList();
    }

    @Override
    public void persist(final String key, final String value) {
        keys.put(key,value);
    }

    @Override
    public void update(final String key, final String value) {
        keys.put(key,value);
    }

    @Override
    public void persistEphemeral(final String key, final String value) {
    }

    @Override
    public void watch(final String key, final DataChangedEventListener dataChangedEventListener) {
    }

    @Override
    public void close() {
    }

    @Override
    public String getType() {
        return "ThirdTestRegistryCenter";
    }

    @Override
    public void initLock(final String key){
        lock = new ReentrantLock();
    }

    @Override
    public boolean tryLock(){
        return lock.tryLock();
    }

    @Override
    public void tryRelease(){
        lock.unlock();
    }
}

Add leaf segment key generator related functions and modify registry center implementation class.


package com.easternedgerobotics.rov.io;

import java.io.IOException;

public interface Device {
    void write(byte writeAddress, byte[] buffer) throws IOException;

    byte[] read(byte readAddress, int readLength) throws IOException;
}

Add interface for io devices such as i2c or spi


package org.jdesktop.swingx;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.event.ActionEvent;

import javax.swing.AbstractAction;
import javax.swing.JButton;
import javax.swing.JFrame;

import org.jdesktop.swingx.JXHeader;
import org.jdesktop.swingx.JXMultiSplitPane;
import org.jdesktop.swingx.JXPanel;
import org.jdesktop.swingx.MultiSplitLayout;
import org.jdesktop.swingx.MultiSplitLayout.Node;

public class JXMultiSplitPaneVisualIssues extends InteractiveTestCase {

    private static void prepare(JFrame f) {
        prepare(f, MultiSplitLayout.parseModel("(ROW (COLUMN weight=0.5 left.top left.bottom)" +
                " (LEAF name=middle)" +
                " (COLUMN weight=0.5 right.top right.bottom))"));

    }

    private static void prepare(JFrame f, Node model) {
        final JXMultiSplitPane msp;
        JXPanel p = new JXPanel(new BorderLayout());
        JXHeader header = new JXHeader();
        header.setTitle("<html><B>JXMultiSplitPaneIssue</b>");
        header.setDescription("<html>This is a bit tricky ... To reproduce the issue move one of the dividers and then click reset. Expected behavior is that original layout is restored. Actual behavior (bug) is that only two cells stay displayed and no divider is visible.");
        p.add(header, BorderLayout.NORTH);
        msp = new JXMultiSplitPane();
        msp.setModel(model);
        p.add(msp);
        JButton green = new JButton("mid");
        green.setBackground(Color.GREEN);
        msp.add(green, "middle");
        msp.add(new JButton("l.t"), "left.top");
        msp.add(new JButton("l.b"), "left.bottom");
        msp.add(new JButton("r.t"), "right.top");
        msp.add(new JButton("r.b"), "right.bottom");
        f.add(p);
        JButton b = new JButton(new AbstractAction("Reset") {

            public void actionPerformed(ActionEvent e) {
                // just reset the model
                msp.setModel(MultiSplitLayout.parseModel("(ROW (COLUMN weight=0.5 left.top left.bottom)" +
                " (LEAF name=middle)" +
                " (COLUMN weight=0.5 right.top right.bottom))"));
                msp.revalidate();
                msp.repaint();
            }

        });
        f.add(b, BorderLayout.SOUTH);
        f.setPreferredSize(new Dimension(400, 400));
    }

    public void interactiveModelChange() {
        JFrame f = new JFrame();
        prepare(f);
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.pack();
        f.setVisible(true);
    }

    /**
     * @param args
     */
    public static void main(String[] args) {
        JXMultiSplitPaneVisualIssues test = new JXMultiSplitPaneVisualIssues();
        try {
            test.runInteractiveTests();
          } catch (Exception e) {
              System.err.println("exception when executing interactive tests:");
              e.printStackTrace();
          }
    }

}

Test exposing MultiSplitPane model reset issue.


package hello;

import com.google.common.net.MediaType;
import io.undertow.server.HttpHandler;
import io.undertow.server.HttpServerExchange;
import io.undertow.util.Headers;

import static hello.HelloWebServer.TEXT_PLAIN;

/**
 * Handles the plaintext test.
 */
final class PlaintextHandler implements HttpHandler {
  @Override
  public void handleRequest(HttpServerExchange exchange) throws Exception {
    exchange.getResponseHeaders().put(
        Headers.CONTENT_TYPE, TEXT_PLAIN);
    exchange.getResponseSender().send("Hello, World!");
  }
}

package hello;

import com.google.common.net.MediaType;
import io.undertow.server.HttpHandler;
import io.undertow.server.HttpServerExchange;
import io.undertow.util.Headers;
import java.nio.ByteBuffer;

import static hello.HelloWebServer.TEXT_PLAIN;

/**
 * Handles the plaintext test.
 */
final class PlaintextHandler implements HttpHandler {
  private static final ByteBuffer buffer;
  private static final String MESSAGE = "Hello, World!";

  static {
      buffer = ByteBuffer.allocateDirect(MESSAGE.length());
      try {
          buffer.put(MESSAGE.getBytes("US-ASCII"));
      } catch (Exception e) {
          throw new RuntimeException(e);
      }
      buffer.flip();
  }

  @Override
  public void handleRequest(HttpServerExchange exchange) throws Exception {
    exchange.getResponseHeaders().put(
        Headers.CONTENT_TYPE, TEXT_PLAIN);
    exchange.getResponseSender().send(buffer.duplicate());
  }
}

Make test apples to apples with other framework tests that have started caching the response buffer


/*
 * Copyright 2014 ZXing 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.google.zxing;

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

public final class PlanarYUVLuminanceSourceTestCase extends Assert {

  private static final byte[] YUV = {
       0,  1,  1,  2,  3,  5,
       8, 13, 21, 34, 55, 89,
       0,  -1,  -1,  -2,  -3,  -5,
      -8, -13, -21, -34, -55, -89,
      127, 127, 127, 127, 127, 127,
      127, 127, 127, 127, 127, 127,
  };
  private static final int COLS = 6;
  private static final int ROWS = 4;
  private static final byte[] Y = new byte[COLS * ROWS];
  static {
    System.arraycopy(YUV, 0, Y, 0, Y.length);
  }

  @Test
  public void testNoCrop() {
    PlanarYUVLuminanceSource source =
        new PlanarYUVLuminanceSource(YUV, COLS, ROWS, 0, 0, COLS, ROWS, false);
    assertEquals(Y, 0, source.getMatrix(), 0, Y.length);
    for (int r = 0; r < ROWS; r++) {
      assertEquals(Y, r * COLS, source.getRow(r, null), 0, COLS);
    }
  }

  @Test
  public void testCrop() {
    PlanarYUVLuminanceSource source =
        new PlanarYUVLuminanceSource(YUV, COLS, ROWS, 1, 1, COLS-2, ROWS-2, false);
    for (int r = 0; r < ROWS-2; r++) {
      assertEquals(Y, (r + 1) * COLS + 1, source.getRow(r, null), 0, COLS-2);
    }
  }

  private static void assertEquals(byte[] expected, int expectedFrom,
                                   byte[] actual, int actualFrom,
                                   int length) {
    for (int i = 0; i < length; i++) {
      assertEquals(expected[expectedFrom + i], actual[actualFrom + i]);
    }
  }

}

Add simple test to try codecov.io


package pl.ciruk.blog.jitest;

import com.google.common.base.Stopwatch;
import org.junit.Test;

import java.util.concurrent.TimeUnit;

public class EmptyLoopTest {
    @Test(timeout = 100_000L)
    public void shouldEliminateEmptyIntLoop() throws Exception {
        for (int i = 0; i < 100; i++) {
            runAndMeasureTime(this::intLoop);
        }
    }

    @Test(timeout = 100_000L)
    public void shouldEliminateEmptyIntToLongLoop() throws Exception {
        for (int i = 0; i < 100; i++) {
            runAndMeasureTime(this::intToLongLoop);
        }
    }

    @Test(timeout = 100_000L)
    public void shouldEliminateEmptyLongLoop() throws Exception {
        for (int i = 0; i < 100; i++) {
            runAndMeasureTime(this::longLoop);
        }
    }

    private void intLoop() {
        for (int i = 0; i < 20_000_000; i++) {

        }
    }

    private void intToLongLoop() {
        for (int i = 0; i < 2_000_000_000L; i++) {
            // no-op
        }
    }

    private void longLoop() {
        for (long i = 0; i < 2_000_000_000L; i++) {
            // no-op
        }
    }

    private void runAndMeasureTime(Runnable runnable) {
        Stopwatch stopwatch = Stopwatch.createStarted();
        runnable.run();
        stopwatch.stop();
        System.out.printf("%d ms%n", stopwatch.elapsed(TimeUnit.MILLISECONDS));
    }
}

Verify JIT behaviour on empty loops


package fr.treeptik.cloudunit.dto;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Created by nicolas on 25/08/2014.
 */
final public class LogLine {

    private final String source;
    private final String message;

    public LogLine(String source, String message) {
        if (source == null) {
            throw new IllegalArgumentException("Source cannot be null");
        }
        if (message == null) {
            throw new IllegalArgumentException("Message cannot be null");
        }
        this.message = message;
        if (source != null && source.contains("/")) {
            this.source = source.substring(source.lastIndexOf("/") + 1);
        } else {
            this.source = source;
        }
    }

    public String getMessage() {
        return message;
    }

    public String getSource() {
        return source;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        LogLine logLine = (LogLine) o;

        if (!source.equals(logLine.source)) return false;
        return message.equals(logLine.message);

    }

    @Override
    public int hashCode() {
        int result = source.hashCode();
        result = 31 * result + message.hashCode();
        return result;
    }
}

Remove infinite testCase + introduce new log pattern inherited from Docker 1.9


package com.expidev.gcmapp.db;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

import com.expidev.gcmapp.sql.TableNames;
import com.expidev.gcmapp.utils.DatabaseOpenHelper;

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

/**
 * Created by William.Randall on 1/21/2015.
 */
public class MinistriesDao
{
    private final String TAG = getClass().getSimpleName();

    private final SQLiteOpenHelper databaseHelper;

    private static final Object instanceLock = new Object();
    private static MinistriesDao instance;

    private MinistriesDao(final Context context)
    {
        this.databaseHelper = new DatabaseOpenHelper(context);
    }

    public static MinistriesDao getInstance(Context context)
    {
        if(instance == null)
        {
            synchronized(instanceLock)
            {
                instance = new MinistriesDao(context.getApplicationContext());
            }
        }

        return instance;
    }

    public Cursor retrieveAssociatedMinistriesCursor()
    {
        final SQLiteDatabase database = databaseHelper.getReadableDatabase();
        try
        {
            return database.query(TableNames.ASSOCIATED_MINISTRIES.getTableName(), null, null, null, null, null, null);
        }
        catch(Exception e)
        {
            Log.e(TAG, "Failed to retrieve associated ministries: " + e.getMessage());
        }

        return null;
    }

    public List<String> retrieveAssociatedMinistries()
    {
        Cursor cursor = null;

        try
        {
            cursor = retrieveAssociatedMinistriesCursor();

            if(cursor != null && cursor.getCount() > 0)
            {
                List<String> associatedMinistries = new ArrayList<String>(cursor.getCount());

                cursor.moveToFirst();
                for(int i = 0; i < cursor.getCount(); i++)
                {
                    associatedMinistries.add(cursor.getString(cursor.getColumnIndex("name")));
                }

                return associatedMinistries;
            }
        }
        finally
        {
            if(cursor != null)
            {
                cursor.close();
            }
        }

        return null;
    }
}

Create dao for associated ministries


package ch.rasc.eds.starter.config;

import org.springframework.boot.context.embedded.ConfigurableEmbeddedServletContainer;
import org.springframework.boot.context.embedded.EmbeddedServletContainerCustomizer;
import org.springframework.boot.context.embedded.MimeMappings;
import org.springframework.context.annotation.Configuration;

@Configuration
public class WebFontMimeMapper implements EmbeddedServletContainerCustomizer {

	@Override
	public void customize(ConfigurableEmbeddedServletContainer container) {
		MimeMappings mappings = new MimeMappings(MimeMappings.DEFAULT);
		mappings.add("svg", "image/svg+xml");
		mappings.add("eot", "application/vnd.ms-fontobject");
		mappings.add("woff", "application/font-woff");
		mappings.add("woff2", "application/font-woff2");
		mappings.add("ttf", "application/font-sfnt");
		mappings.add("otf", "application/font-sfnt");
		container.setMimeMappings(mappings);
	}
}

Add a mime mapper for webfonts


package gr.iti.mklab.simmo.core.annotations;

import gr.iti.mklab.simmo.core.Annotation;

public class SummaryScore implements Annotation {

	 /** The prior of the item */
    private double popularityScore = 0;

	 /** The prior of the item */
    private double priorScore = 0;

	 /** The divRank score of the item */
    private double pageRankScore = 0;

	 /** The divRank score of the item */
    private double divRankScore = 0;

    public SummaryScore() {

    }

    public SummaryScore(double popularityScore, double priorScore, double pageRankScore, double divRankScore) {
    	this.popularityScore = popularityScore;
    	this.priorScore = priorScore;
    	this.pageRankScore = pageRankScore;
    	this.divRankScore = divRankScore;
    }

	public double getPriorScore() {
		return priorScore;
	}

	public void setPriorScore(double priorScore) {
		this.priorScore = priorScore;
	}

	public double getPageRankScore() {
		return pageRankScore;
	}

	public void setPageRankScore(double pageRankScore) {
		this.pageRankScore = pageRankScore;
	}

	public double getDivRankScore() {
		return divRankScore;
	}

	public void setDivRankScore(double divRankScore) {
		this.divRankScore = divRankScore;
	}

	public double getPopularityScore() {
		return popularityScore;
	}

	public void setPopularityScore(double popularityScore) {
		this.popularityScore = popularityScore;
	}

}

Add annotation for summarization scores


package net.sf.jabref.model.entry;

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

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

import static org.junit.Assert.*;

public class IEEETranEntryTypesTest {

    @Test
    public void ctlTypeContainsYesNoFields() {
        List<String> ctlFields = IEEETranEntryTypes.IEEETRANBSTCTL.getAllFields();
        List<String> ynFields = Arrays.asList(IEEETranEntryTypes.IEEETRANBSTCTL_YES_NO_FIELDS);

        Assert.assertTrue(ctlFields.containsAll(ynFields));
    }

    @Test
    public void ctlTypeContainsNumericFields() {
        List<String> ctlFields = IEEETranEntryTypes.IEEETRANBSTCTL.getAllFields();
        List<String> numericFields = Arrays.asList(IEEETranEntryTypes.IEEETRANBSTCTL_NUMERIC_FIELDS);

        Assert.assertTrue(ctlFields.containsAll(numericFields));
    }

}

Add test for IEEETranBstCtl type fields


import java.io.*;
import java.util.*;

public class harshitmalik03_Word_Break{

    public static void main(String[] args)throws Exception{
        System.out.println("Hello");
    }
}

Add Word Break Problem in Java.


package net.imagej.ops.viewOp;

import net.imagej.ops.view.ViewOps;
import net.imagej.ops.view.ViewOps.ExtendZero;
import net.imglib2.RandomAccessibleInterval;
import net.imglib2.type.numeric.NumericType;
import net.imglib2.view.ExtendedRandomAccessibleInterval;
import net.imglib2.view.Views;

import org.scijava.plugin.Plugin;

@Plugin(type = ViewOps.ExtendZero.class, name = ViewOps.ExtendZero.NAME)
public class DefaultExtendZero<T extends NumericType<T>, F extends RandomAccessibleInterval<T>>
		extends AbstractView<F, ExtendedRandomAccessibleInterval<T, F>>
		implements ExtendZero<F, ExtendedRandomAccessibleInterval<T, F>> {

	@Override
	public ExtendedRandomAccessibleInterval<T, F> compute(F input) {
		return Views.extendZero(input);
	}

}

Add default implementation of ExtendZero interface.


public static void RadixSort(ArrayList<Integer> list) {

        final int NUM_BASE = 10;

        int maximum = 0;

        ArrayList<ArrayList<Integer>> buckets;
        buckets = new ArrayList<ArrayList<Integer>>(NUM_BASE);

        // New buckets are added to the bucket list; one for each digit
        // in the numeral system of the data being sorted.

        for (int ii = 0; ii < NUM_BASE; ii++) {

            buckets.add(new ArrayList<Integer>());
        }

        // Identifying the list item with the most place values.

        for (int ii = 0; ii < list.size(); ii++) {

            if (list.get(ii) > maximum) {

                maximum = list.get(ii);
            }
        }

        // List items are sorted by place value. The place value is
        // multiplied by the numeric base with each pass of the loop.

        for (int power = 1; maximum / power != 0; power *= NUM_BASE) {

            for (int ii = 0; ii < list.size(); ii++) {

                // List items are added to the bucket which corresponds
                // to the place value which they are being sorted by.

                buckets.get(list.get(ii) / power % NUM_BASE)
                        .add(list.get(ii));
            }

            int index = 0;

            for (int ii = 0; ii < buckets.size(); ii++) {

                for (int jj = 0; jj < buckets.get(ii).size(); jj++) {

                    // The buckets, sorted by the current place value
                    // under consideration, have their values written
                    // back to original list, overwriting its previous
                    // contents.

                    list.set(index, buckets.get(ii).get(jj));
                    index++;
                }
            }

            // At the end of each pass of the loop, the contents of the
            // buckets are dumped out.

            for (int ii = 0; ii < buckets.size(); ii++) {

                buckets.get(ii).clear();
            }
        }
    }

Add A Readable Radix Sort


/*
 * Copyright (c) 2010, 2011 The University of Manchester, UK.
 *
 * 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 University of Manchester 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 OWNER OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */

package uk.org.taverna.server.client;

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

import java.net.URI;
import java.net.URISyntaxException;

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

public class TestServer {

	private static String address;
	private URI uri1;
	private URI uri2;
	private Server server;

	@BeforeClass
	public static void getAddress() {
		address = System.getProperty("T2SERVER");

		if (address == null) {
			throw new RuntimeException(
					"Invalid configuration. Make sure T2SERVER is set.");
		}
	}

	@Before
	public void setup() {
		try {
			uri1 = new URI(address);
			uri2 = new URI(address);
		} catch (URISyntaxException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	@Test
	public void testConnect() {
		server = Server.connect(uri1);
		Server other = Server.connect(uri2);
		Server third = null;
		try {
			third = Server.connect(address);
		} catch (URISyntaxException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		assertNotNull(server);
		assertSame(server, other);
		assertSame(server, third);
	}
}

Add a minimal test suite for the Server class.


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

package com.google.sps.servlets;

import com.google.gson.Gson;
import com.google.sps.data.*;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/investments")
public class InvestmentServlet extends HttpServlet {
  List<Investment> usersInvestments = new ArrayList<>();
  @Override
  public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
    addHardCodedData();
    response.setContentType("text/html;");

    response.getWriter().println(new Gson().toJson(usersInvestments));
  }

  public void addHardCodedData() {
    usersInvestments.add(
        new Investment("Bob", "Chicken Wings", 50, new Date(2020, 12, 26).getTime()));
    usersInvestments.add(new Investment("Jack", "Trump", 25, new Date(2020, 11, 26).getTime()));
    usersInvestments.add(new Investment("Mary", "COVID", 30, new Date(2020, 10, 26).getTime()));
  }
}

Add investment Servlets to sent all users investments to the frontend


package com.github.pedrovgs.app.problem2;

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

import static org.junit.Assert.assertEquals;

/**
 * @author Pedro Vicente Gómez Sánchez.
 */
public class VectorScalarProductTest {

  private VectorScalarProduct vectorScalarProduct;

  @Before public void setUp() {
    vectorScalarProduct = new VectorScalarProduct();
  }

  @Test(expected = IllegalArgumentException.class)
  public void differentSizeVectorsShouldThrowException() {
    Vector v1 = new Vector(1, 2, 3, 4);
    Vector v2 = new Vector(1, 2);

    vectorScalarProduct.calculateScalarProduct(v1, v2);
  }

  @Test public void shouldReturnZeroIfOneVectorIsFullOfZeros() {
    Vector v1 = new Vector(1, 2, 3, 4);
    Vector v2 = new Vector(0, 0, 0, 0);

    int result = vectorScalarProduct.calculateScalarProduct(v1, v2);

    assertEquals(0, result);
  }

  @Test public void shouldReturnSumOfOneVectorIfOtherIsFullOfOnes() {
    Vector v1 = new Vector(2, 2, 2, 2);
    Vector v2 = new Vector(1, 1, 1, 1);

    int result = vectorScalarProduct.calculateScalarProduct(v1, v2);

    assertEquals(8, result);
  }

  @Test public void shouldTakeIntoAccountNegativeElements() {
    Vector v1 = new Vector(2, 2, 2, 2);
    Vector v2 = new Vector(-1, 1, -1, -1);

    int result = vectorScalarProduct.calculateScalarProduct(v1, v2);

    assertEquals(-2, result);
  }
}

Add tests for problem 2.


package net.kencochrane.raven.jul;

import net.kencochrane.raven.SentryStub;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import java.util.logging.Logger;

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

public class SentryHandlerIT {
    private static final Logger logger = Logger.getLogger(SentryHandlerIT.class.getCanonicalName());
    private SentryStub sentryStub;

    @Before
    public void setUp() {
        sentryStub = new SentryStub();
    }

    @After
    public void tearDown() {
        sentryStub.removeEvents();
    }

    @Test
    public void testInfoLog() {
        assertThat(sentryStub.getEventCount(), is(0));
        logger.info("This is a test");
        assertThat(sentryStub.getEventCount(), is(1));
    }
}

Add integration tests for JUL


package com.boundary.metrics.vmware;

import io.dropwizard.configuration.ConfigurationFactory;
import io.dropwizard.jackson.Jackson;

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

import javax.validation.Validation;
import javax.validation.Validator;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.google.common.io.Resources;

public class VMWareTestUtils {

	public static VMwarePerfAdapterConfiguration getConfiguration(String resource) throws Exception {

		VMwarePerfAdapterConfiguration configuration = null;
		File validFile = new File(Resources.getResource(resource).toURI());
		System.out.println(resource);

		Validator validator = Validation.buildDefaultValidatorFactory()
				.getValidator();
		ConfigurationFactory<VMwarePerfAdapterConfiguration> factory = new ConfigurationFactory<VMwarePerfAdapterConfiguration>(
				VMwarePerfAdapterConfiguration.class, validator,
				Jackson.newObjectMapper(), "dw");

		try {
			configuration = factory.build(validFile);
		} catch (JsonParseException e) {

			e.printStackTrace();
		} catch (JsonMappingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

		return configuration;
	}
}

Add utility class loads VMWare adapter configuration file


package com.akiba.cserver;

public interface CServerConstants {

	public final static short OK = 1;
	public final static short END = 2;
	public final static short ERR = 100;
	public final static short MISSING_OR_CORRUPT_ROW_DEF = 99;
	public final static short NON_UNIQUE = 101;
	public final static short FOREIGN_KEY_MISSING= 102;

	public final static int MAX_VERSIONS_PER_TABLE = 65536;
	public final static int MAX_GROUP_DEPTH = 256;
}

package com.akiba.cserver;

public interface CServerConstants {

	public final static short OK = 1;
	public final static short END = 2;
	public final static short ERR = 100;
	public final static short MISSING_OR_CORRUPT_ROW_DEF = 99;
	public final static short NON_UNIQUE = 121;	// copied from mysql include/my_base.h (line 377)
	public final static short FOREIGN_KEY_MISSING= 151; // copied from mysql include/my_base.h (line 405)

	public final static int MAX_VERSIONS_PER_TABLE = 65536;
	public final static int MAX_GROUP_DEPTH = 256;
}

Update the error values generated (and returned over the wire) to match those expected by MySQL.


package com.sensei.search.query;

import org.apache.lucene.search.ConstantScoreQuery;
import org.apache.lucene.search.Filter;
import org.apache.lucene.search.Query;

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

import com.sensei.search.query.filters.FilterConstructor;

public class RangeQueryConstructor extends QueryConstructor
{
  public static final String QUERY_TYPE = "range";

  // "range" : {
  //     "age" : {
  //         "from" : 10,
  //         "to" : 20,
  //         "boost" : 2.0,
  //         "_noOptimize" : false
  //     }
  // },

  @Override
  public Query constructQuery(JSONObject jsonQuery) throws JSONException
  {
    FilterConstructor filterConstructor = FilterConstructor.getFilterConstructor(QUERY_TYPE);
    Filter filter = null;
    try
    {
      filter = filterConstructor.constructFilter(jsonQuery);
    }
    catch(Exception e)
    {
      throw new JSONException(e);
    }
    ConstantScoreQuery query = new ConstantScoreQuery(filter);
    query.setBoost((float)jsonQuery.getJSONObject((String)jsonQuery.keys().next()).optDouble("boost", 1.0));
    return query;
  }
}

Add missing file for range query constructor.


package info.freelibrary.jiiify.util;

import java.awt.Dimension;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

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

import info.freelibrary.jiiify.iiif.IIIFException;
import info.freelibrary.jiiify.iiif.ImageRequest;
import info.freelibrary.util.PairtreeRoot;

import au.com.bytecode.opencsv.CSVReader;
import au.com.bytecode.opencsv.CSVWriter;

public class ReportUtils {

    private static final File CSV_FILE = new File("input.csv");

    private static final File CSV_OUT = new File("output.csv");

    private static final Logger LOGGER = LoggerFactory.getLogger(ReportUtils.class);

    private static int myFoundCount;

    private static int myNotFoundCount;

    public static final void main(final String[] args) throws IOException {
        final CSVReader csvReader = new CSVReader(new FileReader(CSV_FILE));
        final PairtreeRoot ptRoot = new PairtreeRoot(new File(args[0]));
        final CSVWriter csvWriter = new CSVWriter(new FileWriter(CSV_OUT));

        csvReader.readAll().forEach(image -> {
            try {
                final File imageFile = new File(image[1]);
                final Dimension dim = ImageUtils.getImageDimension(imageFile);

                myFoundCount = 0;
                myNotFoundCount = 0;

                ImageUtils.getTilePaths("/iiif", image[0], 1024, dim.width, dim.height).forEach(path -> {
                    try {
                        final ImageRequest request = new ImageRequest(path);

                        if (request.hasCachedFile(ptRoot)) {
                            myFoundCount++;
                        } else {
                            myNotFoundCount++;
                        }
                    } catch (final IIIFException | IOException details) {
                        try {
                            csvWriter.close();
                            csvReader.close();
                        } catch (final IOException ignorable) {
                            LOGGER.error(ignorable.getMessage(), ignorable);
                        }

                        throw new RuntimeException(details);
                    }
                });

                csvWriter.writeNext(new String[] { imageFile.getAbsolutePath(), Integer.toString(myFoundCount),
                    Integer.toString(myNotFoundCount) });
            } catch (final IOException details) {
                try {
                    csvWriter.close();
                    csvReader.close();
                } catch (final IOException ignorable) {
                    LOGGER.error(ignorable.getMessage(), ignorable);
                }

                throw new RuntimeException(details);
            }
        });

        csvReader.close();
        csvWriter.close();
    }
}

Add csv pairtree file system checker script


/*
 * Copyright (c) 2017 Falko Schumann
 * Released under the terms of the MIT License.
 */

package de.muspellheim.jdbc;

import com.mysql.jdbc.jdbc2.optional.*;
import javafx.application.*;
import javafx.beans.property.*;
import javafx.beans.value.*;
import javafx.collections.*;
import javafx.scene.*;
import javafx.scene.control.*;
import javafx.stage.*;
import javafx.util.*;

import java.sql.*;

public class FXApplication extends Application {

    @Override
    public void start(Stage stage) throws Exception {
        TableView tableView = new TableView();

        MysqlDataSource dataSource = new MysqlConnectionPoolDataSource();
        dataSource.setPort(8889);
        dataSource.setUser("root");
        dataSource.setPassword("root");
        dataSource.setDatabaseName("oshop");

        ObservableList<ObservableList> data = FXCollections.observableArrayList();
        try (Connection connection = dataSource.getConnection()) {
            String sql = "SELECT artikel_id AS 'Artikel-ID', bezeichnung AS 'Bezeichnung', CONCAT(FORMAT(einzelpreis, 2, 'de_DE'), ' ', waehrung) AS 'Einzelpreis' FROM artikel WHERE deleted = 0";
            ResultSet resultSet = connection.createStatement().executeQuery(sql);

            for (int i = 0; i < resultSet.getMetaData().getColumnCount(); i++) {
                final int j = i;
                TableColumn col = new TableColumn(resultSet.getMetaData().getColumnLabel(i + 1));
                col.setCellValueFactory((Callback<TableColumn.CellDataFeatures<ObservableList, String>, ObservableValue<String>>) param -> new SimpleStringProperty(param.getValue().get(j).toString()));
                tableView.getColumns().addAll(col);
            }

            while (resultSet.next()) {
                ObservableList<String> row = FXCollections.observableArrayList();
                for (int i = 1; i <= resultSet.getMetaData().getColumnCount(); i++) {
                    row.add(resultSet.getString(i));
                }
                data.add(row);
            }
        } catch (SQLException ex) {
            ex.printStackTrace();
        }
        tableView.setItems(data);

        Scene scene = new Scene(tableView);

        stage.setTitle("Demo with table kunde");
        stage.setScene(scene);
        stage.show();
    }

}

Create dynamic table with result set


package com.continuuity.passport.passportClient;

import com.continuuity.common.utils.PortDetector;
import com.continuuity.passport.http.client.AccountProvider;
import com.continuuity.passport.http.client.PassportClient;
import com.continuuity.passport.server.MockServer;
import com.google.gson.FieldNamingPolicy;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;

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

import static org.junit.Assert.assertTrue;

/**
 *
 */
public class TestPassportClient {

  private static MockServer server ;
  private static int port;

  @BeforeClass
  public static void startServer() throws Exception {
    port = PortDetector.findFreePort();
    server = new MockServer(port);
    System.out.println("Starting server");
    server.start();
    Thread.sleep(1000);
    assertTrue(server.isStarted());
    Map<String,String> accountHash=  new HashMap<String, String>();
    accountHash.put("email_id", "john@smith.com");
    accountHash.put("first_name", "john");
    accountHash.put("last_name", "smith");
    accountHash.put("company", "continuuity");

    addAccount(accountHash);
    System.out.println("Added account");
 }
  @Test
  public void testValidAccount(){
    PassportClient client = new PassportClient();
    System.out.println("Trying to get account");
    AccountProvider accountProvider = client.getAccount("http","localhost",port,"apiKey1");
    System.out.println("Got an account");

    assert (accountProvider !=null);
    System.out.println(accountProvider.getAccountId());
    assert ("1".equals(accountProvider.getAccountId()));
    System.out.println("Tested");
  }

  @Test(expected = RuntimeException.class)
  public void testInvalidAccount() {
    PassportClient client = new PassportClient();
    AccountProvider accountProvider = client.getAccount("http","localhost",port,"apiKey100");

  }

  @AfterClass
  public static void stopServer() throws Exception {
     server.stop();
     Thread.sleep(1000);
  }

  private static void addAccount(Map<String,String> account) throws IOException {
    Gson gson =new GsonBuilder().setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES).create();

    HttpPost post = new HttpPost(String.format("http://localhost:%d/passport/v1/account",port));
    StringEntity entity =  new StringEntity(gson.toJson(account));
    entity.setContentType("application/json");
    post.setEntity(entity);

    HttpClient client = new DefaultHttpClient();
    HttpResponse response = client.execute(post);

    assert(response.getStatusLine().getStatusCode() == 200);
  }

}

Add Test cases for passport client


package org.jdesktop.beans.editors;

import javax.swing.JFrame;
import javax.swing.SwingUtilities;

/**
 * A demo program to showcase {@link PaintPicker}.
 *
 * @author Karl Schaefer
 */
@SuppressWarnings("all")
public class PaintPickerDemo extends JFrame {
    /**
     * {@inheritDoc}
     */
    @Override
    protected void frameInit() {
        super.frameInit();

        setTitle("PaintPicker Demo");
        setDefaultCloseOperation(EXIT_ON_CLOSE);

        add(new PaintPicker());

        pack();
    }

    /**
     * Demo entry point.
     *
     * @param args
     *            unused
     */
    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                new PaintPickerDemo().setVisible(true);
            }
        });
    }
}

Add demo for paint picker.


package com.easternedgerobotics.rov.io;

import com.easternedgerobotics.rov.value.MotionPowerValue;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.pmw.tinylog.Logger;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.prefs.Preferences;

public final class MotionPowerProfile {
    /**
     * The directory which contains the power profiles.
     */
    private final Preferences profileHome;

    /**
     * A copy of power profiles to exist in RAM.
     */
    private final Map<Integer, MotionPowerValue> profiles = new HashMap<>();

    /**
     * Create a power profile loader/ setter which works in the specified directory.
     *
     * @param profile the preferences directory.
     */
    public MotionPowerProfile(final String profile) {
        this.profileHome = Preferences.userRoot().node(profile);
    }

    /**
     * Get the latest MotionPowerValue associated with the index.
     * Fetches from disk if not loaded.
     *
     * @param index the power profile index.
     * @return MotionPowerValue
     */
    public MotionPowerValue get(final int index) {
        return profiles.computeIfAbsent(index, i -> {
            final String profileName = String.format("profile-%d", i);
            final String profileStr = profileHome.get(profileName, "DEFAULT");
            if (profileStr.equals("DEFAULT")) {
                Logger.warn("The profile {} does not exist.", profileName);
                return new MotionPowerValue();
            }
            try {
                return new ObjectMapper().readValue(profileStr, MotionPowerValue.class);
            } catch (final IOException e) {
                Logger.warn("The profile {} could not be parsed from '{}': {}", profileName, profileStr, e);
                return new MotionPowerValue();
            }
        });
    }

    /**
     * Update the MotionPowerValue profile for a given index and write this value to disk.
     *
     * @param index the power profile index.
     * @param profile MotionPowerValue to be saved to disk.
     */
    public void set(final int index, final MotionPowerValue profile) {
        profiles.put(index, profile);
        final String profileName = String.format("profile-%d", index);
        try {
            profileHome.put(profileName, new ObjectMapper().writeValueAsString(profile));
        } catch (final IOException e) {
            Logger.warn("The profile {} could not be saved to {}: {}", profile, profileName, e);
        }
    }
}

Load and save motion power values to disk


package pabix.chickens.una;

import android.app.Application;
import android.content.Context;

import com.facebook.FacebookSdk;
import com.facebook.appevents.AppEventsLogger;

/**
 * Created by JunHyeok on 2016. 10. 6..
 */

public class UnaApplication extends Application {

    public static Context context;

    @Override
    public void onCreate() {
        super.onCreate();
        FacebookSdk.sdkInitialize(getApplicationContext());
        AppEventsLogger.activateApp(this);
        context = this;
    }

    public static Context getContext() {
        return context;
    }
}

Add Application class for manage Context


package sizebay.catalog.client.model;

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.experimental.Accessors;

import java.io.Serializable;

@Data
@Accessors(chain = true)
@NoArgsConstructor
@JsonIgnoreProperties(ignoreUnknown = true)
public class UserProfileProduct implements Serializable {

      long id ;
      long profileIdentificationId;
      String brand;
      String category;
      String model;
      String gender;
      int ageGroup;
      String size;
      String sizeStr;

      public static UserProfileProduct empty() {

          UserProfileProduct product = new UserProfileProduct();

          product.setBrand("");
          product.setCategory("");
          product.setModel("");
          product.setGender("");
          product.setAgeGroup(0);
          product.setSize("");
          product.setSizeStr("");

          return product;

      }

}

Create the Profile Product class


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

import com.github.pedrovgs.sortingalgorithm.SortingAlgorithm;
import com.github.pedrovgs.sortingalgorithms.SortingAlgorithmTest;

/**
 * @author Pedro Vicente Gómez Sánchez.
 */
public class InsertionSortTest extends SortingAlgorithmTest {

  @Override public SortingAlgorithm getSortingAlgorithm() {
    return new InsertionSort();
  }
}

Add some tests to problem 76


package problems;

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

public class SubstringWithConcatenationOfAllWords {
    public List<Integer> findSubstring(String S, String[] L) {
        final List<Integer> out = new ArrayList<Integer>();
        if (S == null || L == null || S.length() == 0 || L.length == 0)
            return out;

        final int len = L[0].length();
        final int N = L.length * len;
        final HashMap<String, Integer> map = new HashMap<String, Integer>();
        HashMap<String, Integer> mapcopy = null;
        for (final String st : L) {
            if (!map.containsKey(st))
                map.put(st, 1);
            else
                map.put(st, map.get(st) + 1);
        }

        for (int i = 0; i < S.length() - N + 1; i++) {
            final String a = S.substring(i, i + len);
            if (!map.containsKey(a))
                continue;
            else {
                mapcopy = new HashMap<String, Integer>(map);
                remove(mapcopy, a);
            }

            for (int j = 1; j < L.length; j++) {
                String t = S.substring(i + j * len, i + (j + 1) * len);
                if (!remove(mapcopy, t))
                    break;
            }
            if (mapcopy.size() == 0)
                out.add(i);
        }
        return out;
    }

    boolean remove(HashMap<String, Integer> map, String s) {
        if (map.containsKey(s)) {
            final int count = map.get(s);
            if (count > 1)
                map.put(s, count - 1);
            else
                map.remove(s);
            return true;
        }
        return false;
    }

    public static void main(String[] args) {
        SubstringWithConcatenationOfAllWords sw = new SubstringWithConcatenationOfAllWords();
        String S = "lingmindraboofooowingdingbarrwingmonkeypoundcake";
        String[] L = { "fooo", "barr", "wing", "ding", "wing" };
        System.out.println(sw.findSubstring(S, L));
    }
}

Add Substring with Concatenation of All Words


package uk.ac.ebi.gxa.loader.service;

import org.junit.Test;

/**
 */
public class TestNcdfConversion {
    @Test
    public void testExportExperiment() {
        // Get an experiment from DB/NetCDF
        // run update on it - not it'll rewrite the file
        // make sure all the DB fields are shown in the NetCDF and IDF files properly
        // release the experiment
        // import the experiment
        // make sure all the fields are still the same
    }
}

Test scenario to start with


package com.github.kratorius.cuckoohash;

import junit.framework.TestCase;

import java.util.ArrayList;
import java.util.Random;

/**
 * Tests for the put() method of the Cuckoo hash map.
 */
public class PutTest extends TestCase {
  @SuppressWarnings("MismatchedQueryAndUpdateOfCollection")
  public void testNullKey() {
    CuckooHashMap<Character, Boolean> m = new CuckooHashMap<>();

    try {
      m.put(null, true);
      fail("Accepted null key for put()");
    } catch (NullPointerException e) {
      // Expected.
    }
  }

  public void testUpdate() {
    CuckooHashMap<Character, Integer> m = new CuckooHashMap<>();

    m.put('A', 3);
    assertEquals(3, (int) m.get('A'));

    m.put('A', 42);
    assertEquals(42, (int) m.get('A'));
  }

  public void testManyKeys() {
    // Enough to generate a fair amount of rehashes but not too many so that it fits in memory
    // in the default heap size, and also so that it doesn't take too long to execute.
    final int size = 1024 * 128;

    ArrayList<String> keys = new ArrayList<>(size);
    for (int i = 0; i < size; i++) {
      keys.add(String.valueOf("key-" + i));
    }

    CuckooHashMap<String, Integer> m = new CuckooHashMap<>();
    for (int i = 0; i < size; i++) {
      m.put(keys.get(i), i);
      assertEquals(i, (int) m.get(keys.get(i)));
    }

    for (int i = 0; i < size; i++) {
      assertEquals(i, (int) m.get(keys.get(i)));
    }
  }
}

Add more thorough tests for put()


package tests.dynamicObjectModule;

import static org.junit.Assert.*;

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

public class DynamicObjectModuleTest {

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

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

	@Before
	public void setUp() throws Exception {
	}

	@After
	public void tearDown() throws Exception {
	}

	@Test
	public void testDynamicObjectModule() {
		fail("Not yet implemented"); // TODO
	}

	@Test
	public void testAddItem() {
		fail("Not yet implemented"); // TODO
	}

	@Test
	public void testAddVirtualCharacter() {
		fail("Not yet implemented"); // TODO
	}

	@Test
	public void testFindItem() {
		fail("Not yet implemented"); // TODO
	}

	@Test
	public void testFindVirtualCharacter() {
		fail("Not yet implemented"); // TODO
	}

	@Test
	public void testGetAllDynamicObjects() {
		fail("Not yet implemented"); // TODO
	}

	@Test
	public void testGetVirtualCharacterPosition() {
		fail("Not yet implemented"); // TODO
	}

	@Test
	public void testKeyGETPressed() {
		fail("Not yet implemented"); // TODO
	}

	@Test
	public void testUpdateItem() {
		fail("Not yet implemented"); // TODO
	}

	@Test
	public void testUpdateVirtualCharacter() {
		fail("Not yet implemented"); // TODO
	}

}

Create test case for DynamicObjectModule.


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

/**
 * Given an integer passed as parameter, can you write a method to return the reverse binary
 * number? The reverse binary number is defined like the number where every 1 in the original
 * number has a 0 in the reversed number and the same with 0 in the original number.
 *
 * For example:
 *
 * Input: 63 = 111111
 * Output: 0
 *
 * Input = 5 = 101
 * Output = 2 = 010
 *
 * @author Pedro Vicente Gómez Sánchez.
 */
public class ReverseBinaryNumber {

}

Add statement to problem 71


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

package com.cdancy.artifactory.rest;

/**
 * Various constants that can be used in a global context.
 */
public class ArtifactoryConstants {

    public static final String ENDPOINT_SYSTEM_PROPERTY = "artifactory.rest.endpoint";
    public static final String ENDPOINT_ENVIRONMENT_VARIABLE = ENDPOINT_SYSTEM_PROPERTY.replaceAll("\\.", "_").toUpperCase();

    public static final String CREDENTIALS_SYSTEM_PROPERTY = "artifactory.rest.credentials";
    public static final String CREDENTIALS_ENVIRONMENT_VARIABLE = CREDENTIALS_SYSTEM_PROPERTY.replaceAll("\\.", "_").toUpperCase();

    public static final String TOKEN_SYSTEM_PROPERTY = "artifactory.rest.token";
    public static final String TOKEN_ENVIRONMENT_VARIABLE = TOKEN_SYSTEM_PROPERTY.replaceAll("\\.", "_").toUpperCase();

    public static final String DEFAULT_ENDPOINT = "http://127.0.0.1:7990";

    public static final String JCLOUDS_PROPERTY_ID = "jclouds.";
    public static final String ARTIFACTORY_REST_PROPERTY_ID = "artifactory.rest." + JCLOUDS_PROPERTY_ID;

    public static final String JCLOUDS_VARIABLE_ID = "JCLOUDS_";
    public static final String ARTIFACTORY_REST_VARIABLE_ID = "ARTIFACTORY_REST_" + JCLOUDS_VARIABLE_ID;

    protected ArtifactoryConstants() {
        throw new UnsupportedOperationException("Purposefully not implemented");
    }
}

Move constants into dedicated file.


Test to repo the error.


package ru.fitgraph.rest.exceptions;
import org.apache.log4j.Logger;
import ru.fitgraph.rest.elements.ErrorResponse;

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

/**
 * Mapper for catch all internal exceptions. All uncatched exception will be processed by this
 * class.
 *
 * @author Morgen Matvey
 */
@Provider
public class InternalExceptionMapper implements ExceptionMapper<Throwable> {

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

    @Override
    public Response toResponse(Throwable exception) {
        logger.error("There are unresolved exception!", exception);
        ErrorResponse response =
                new ErrorResponse("InternalServerErrorException", "Internal problem on server, try later.");
        return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(response).build();
    }
}

Add mapper for internal server exceptions.


package net.spy.memcached;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.InetSocketAddress;
import java.net.SocketAddress;

import org.jmock.Mock;
import org.jmock.MockObjectTestCase;

/**
 * Test readonliness of the MemcachedNodeROImpl
 */
public class MemcachedNodeROImplTest extends MockObjectTestCase {

	public void testReadOnliness() throws Exception {
		SocketAddress sa=new InetSocketAddress(11211);
		Mock m = mock(MemcachedNode.class, "node");
		MemcachedNodeROImpl node=
			new MemcachedNodeROImpl((MemcachedNode)m.proxy());
		m.expects(once()).method("getSocketAddress").will(returnValue(sa));

		assertSame(sa, node.getSocketAddress());
		assertEquals(m.proxy().toString(), node.toString());

		for(Method meth : MemcachedNode.class.getMethods()) {
			if(meth.getName().equals("toString")) {
				// ok
			} else if(meth.getName().equals("getSocketAddress")) {
				// ok
			} else {
				Object[] args=new Object[meth.getParameterTypes().length];
				fillArgs(meth.getParameterTypes(), args);
				try {
					meth.invoke(node, args);
					fail("Failed to break on " + meth.getName());
				} catch(InvocationTargetException e) {
					assertSame(UnsupportedOperationException.class,
						e.getCause().getClass());
				}
			}
		}
	}

	private void fillArgs(Class<?>[] parameterTypes, Object[] args) {
		int i=0;
		for(Class<?> c : parameterTypes) {
			if(c == Boolean.TYPE) {
				args[i++] = false;
			} else {
				args[i++] = null;
			}
		}
	}

}

Test the readonliness of MemcachedNodeROImpl.


package etomica;

import etomica.integrator.Integrator;
import etomica.normalmode.NormalModeAnalysisDisplay2D;
import etomica.normalmode.NormalModeAnalysisDisplay3D;
import etomica.simulation.Simulation;
import etomica.space.Space;
import etomica.space3d.Space3D;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Assumptions;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import static etomica.TestSimConstructors.SCAN;

public class TestSimShortRuns {
    private static final ExecutorService exec = Executors.newSingleThreadExecutor();

    static List<Arguments> getIntegrators() throws IllegalAccessException, InstantiationException, InvocationTargetException {
        // This beautiful method will search through constructible simulations looking for ones
        // with one and only one field of type Integrator (getIntegrator isn't reliable, and with
        // more than one we don't know which one to use), instantiate the simulations, and return the integrators.
        List<Class<?>> classes =  SCAN.classNamesToClassRefs(SCAN.getNamesOfSubclassesOf(Simulation.class));
        List<Arguments> args = new ArrayList<>();

        for (Class<?> cl : classes) {
            if (cl == NormalModeAnalysisDisplay3D.class) continue;
            Field[] fields = cl.getDeclaredFields();
            List<Field> integratorFields = Arrays.stream(fields)
                    .filter(f -> Integrator.class.isAssignableFrom(f.getType()))
                    .collect(Collectors.toList());

            if (integratorFields.size() == 1) {
                Simulation sim = null;
                try {
                    sim = (Simulation) cl.getConstructor().newInstance();
                } catch (NoSuchMethodException e) {
                    try {
                        sim = (Simulation) cl.getConstructor(Space.class).newInstance(Space3D.getInstance());
                    } catch (NoSuchMethodException e1) {
                        continue;
                    }
                }

                integratorFields.get(0).setAccessible(true);
                args.add(Arguments.of(cl, (Integrator)integratorFields.get(0).get(sim)));
            }
        }

        System.out.println(args);
        return args;
    }

    @ParameterizedTest
    @MethodSource("getIntegrators")
    void testShortRuns(Class<?> simClass, Integrator simIntegrator) {
        Assertions.assertDoesNotThrow(() -> {
            simIntegrator.reset();
            Future future = exec.submit(() -> {
                while (true) {
                    simIntegrator.doStep();
                }
            });
            Thread.sleep(1000);
            future.cancel(true);
        });
    }
}

Add test which runs all sims to check they don't crash


//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// This file is a part of the 'esoco-business' project.
// Copyright 2017 Elmar Sonnenschein, esoco GmbH, Flensburg, Germany
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//	  http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
package de.esoco.entity;

import de.esoco.lib.comm.Connection;
import de.esoco.lib.comm.HttpEndpoint;
import de.esoco.lib.comm.http.HttpRequestMethod;

import static de.esoco.lib.comm.CommunicationRelationTypes.HTTP_STATUS_CODE;
import static de.esoco.lib.expression.Functions.identity;

/********************************************************************
 * The HTTP endpoint for interaction with the {@link EntitySyncService} REST
 * service.
 *
 * @author eso
 */
public class EntitySyncEndpoint extends HttpEndpoint
{
	//~ Inner Classes ----------------------------------------------------------

	/********************************************************************
	 * The base class for request methods to the {@link EntitySyncEndpoint}.
	 *
	 * @author eso
	 */
	public static class EntitySyncRequest extends HttpRequest<String, String>
	{
		//~ Constructors -------------------------------------------------------

		/***************************************
		 * Creates a new instance.
		 *
		 * @param sMethodName The name of the request method
		 */
		public EntitySyncRequest(String sMethodName)
		{
			super(sMethodName,
				  null,
				  HttpRequestMethod.POST,
				  "/api/sync/",
				  identity(),
				  identity());
		}

		//~ Methods ------------------------------------------------------------

		/***************************************
		 * @see HttpRequest#processResponse(Connection, String)
		 */
		@Override
		protected String processResponse(
			Connection rConnection,
			String	   sRawResponse)
		{
			return rConnection.get(HTTP_STATUS_CODE).toString();
		}
	}
}

Implement an entity modification synchronization service


package edu.cmu.cs.cloudlet.android.discovery;

import java.net.URL;

import org.json.JSONException;
import org.json.JSONObject;
import org.teleal.cling.model.meta.Device;
import org.teleal.cling.model.meta.RemoteDevice;

import edu.cmu.cs.cloudlet.android.util.KLog;

public class CloudletDevice {

	private String ipAddress;
	private boolean isUPnP;

	public CloudletDevice(Device device) {
		URL address = ((RemoteDevice) device).getIdentity().getDescriptorURL();
		this.ipAddress = address.getHost();
		this.isUPnP = true;
	}

	public CloudletDevice(JSONObject device){
		this.isUPnP = false;

		try {
			this.ipAddress = device.getString("ip_address");
			double latitude = device.getDouble("latitude");
			double longitude = device.getDouble("longitude");
		} catch (JSONException e) {
			e.printStackTrace();
		}
	}

	@Override
	public boolean equals(Object o) {
		if (this == o)
			return true;
		if (o == null || getClass() != o.getClass())
			return false;

		CloudletDevice that = (CloudletDevice) o;
		if (this.ipAddress == that.ipAddress)
			return true;
		else
			return false;
	}

	@Override
	public String toString() {

		return "Cloudlet at " + this.ipAddress;

		// For UPnP
		// return device.isFullyHydrated() ? device.getDisplayString() : device.getDisplayString() + " *";
	}

	public String getIPAddress() {
		return this.ipAddress;
	}

}

Add class for representing founded devices from discovery service


package prope.metrics.adaptability.elements;

import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.List;

public class ElementSerializer {

	private final String fileName;

	private final String ROW_COLOR = "\\myrowcolour";

	private final String TABLE_NEWLINE = "\\\\";

	private final boolean useRowColor;

	private PrintWriter writer;

	public static void main(String[] args) throws FileNotFoundException {
		new ElementSerializer(true, args[0]).serializeToLatexTable();
	}

	ElementSerializer(boolean useColor, String fileName) {
		this.useRowColor = useColor;
		this.fileName = fileName;
	}

	public void serializeToLatexTable() throws FileNotFoundException {
		try {
			writer = new PrintWriter(fileName);

			writeLongTableHeader();

			writeLongTableBody();

			writeLongTableFooter();

		} finally {
			if (writer != null) {
				writer.close();
			}
		}
	}

	private void writeLongTableHeader() {
		println("\\begin{center}");
		println("\\begin{scriptsize}");
		println("\\begin{longtable}{p{0.13\\textwidth}|p{0.82\\textwidth}}");
		println("\\caption{Adaptability Scores}\\\\");
		println("\\textbf{Property} & \\textbf{Element}");
		println("\\vspace{2pt}\\\\");
		println("\\toprule");
		println("\\endfirsthead");
		println("\\multicolumn{2}{c}");
		println("{\\tablename\\ \\thetable\\ -- \\emph{Continued from previous page}}\\\\");
		println("\\endhead");
		println("\\multicolumn{2}{r}{\\emph{Continued on next page}}");
		println("\\endfoot");
		println("\\bottomrule");
		println("\\endlastfoot");
	}

	private void writeLongTableBody() {
		List<AdaptableElement> elements = new AdaptableElements().getElements();
		for (int i = 0; i < elements.size(); i++) {
			AdaptableElement element = elements.get(i);

			println("Element name & " + element.getName() + TABLE_NEWLINE);
			printColor();
			println("Documentation &" + element.getDocumentation()
					+ TABLE_NEWLINE);
			println("Expression & " + element.getLocatorExpression()
					+ TABLE_NEWLINE);
			printColor();
			println("Adaptions & " + element.getAdaptions() + TABLE_NEWLINE);
			println("Score & " + element.getNumberOfAdaptions() + TABLE_NEWLINE);

			// print a midrule expect for last assertion
			if (i != elements.size() - 1) {
				println("\\midrule");
			}
		}
	}

	private void writeLongTableFooter() {
		println("\\end{longtable}");
		println("\\end{scriptsize}");
		println("\\end{center}");
	}

	private void printColor() {
		if (useRowColor) {
			println(ROW_COLOR);
		}
	}

	private void println(String line) {
		writer.println(line);
	}
}

Enable serialization of adaptability scores to a LaTeX longtable


package gamecontrollers.checks;

import models.board.Direction;
import models.board.Space;
import models.board.TileComponent;

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

/**
 * Created by kevinnieman on 4/21/14.
 */
public class WouldTileComponentBeOnBoard {
    private List<TileComponent> visitedTiles;

    public WouldTileComponentBeOnBoard(){
        visitedTiles = new ArrayList<TileComponent>();
    }

    public boolean check(Space space, TileComponent tile){
        //clear any old calculations
        visitedTiles.clear();

        //innocent until proven guilty
        boolean onBoard = true;

        //this tile has been visited so add it to the list of visited tiles
        visitedTiles.add(tile);

        //you just moved off the board son, thats a big mistake buddy
        if(space == null)
            return false;

        //need to check if the attached tileComponent has neighbors where the space doesnt
        //get a direciton iterator from the given tile
        Iterator<Direction> iterator = tile.getDirection().iterator();

        //with this direction iterator iterate over the directions of the given tile
        while(iterator.hasNext()){
            //get the current direction
            Direction direction = iterator.next();
            //check if the tile has a conjoined tile in this direction
            if(tile.siblingExists(direction)){
                //tile has a conjoined tile in this direction
                //check if the space has a neighbor in this direction
                if(!space.hasAdjacentSpace(direction)){
                    //if the space doesnt have an adjacent space in this direction you are hanging over the board
                    return false;
                }
                else{
                    //here we know two things
                    //the space has a conjoined space in this direction
                    //the tile has a conjoined tile in this direction
                    //therefore continue to make the checks given that this tile has not been visited
                    if(!visitedTiles.contains(tile))
                        onBoard = onBoard && check(space.getAdjacentSpace(direction), tile.getConjoinedTile(direction));
                }
            }
        }

        return onBoard;
    }
}

Add check for going off board


package com.mv.hr.client;

import org.apache.log4j.Logger;

import com.mv.base.exception.ThirdPartyBadResponseException;
import com.mv.base.exception.ThirdPartyConnectivityFailureException;

/**
 * Retries synchronously an http action when it fails
 */
public class RetryHttpActionExecutor {
	private static final Logger LOG = Logger.getLogger(RetryHttpActionExecutor.class);

	private int tries;
	private int maxTries;
	private long millisecondsBetweenTries;

	public RetryHttpActionExecutor(int maxTries, long millisecondsBetweenTries) {
		this.maxTries = maxTries;
		this.millisecondsBetweenTries = millisecondsBetweenTries;
	}

	public <T> T execute(HttpActionPerformer actionPerformer, Class<T> resultClass)
			throws ThirdPartyBadResponseException, ThirdPartyConnectivityFailureException {

		tries++;

		try {
			return actionPerformer.getResponse(resultClass);
		} catch (ThirdPartyBadResponseException | ThirdPartyConnectivityFailureException e) {
			if (tries == maxTries) {
				throw e;
			}

			LOG.warn(actionPerformer.getUrlPath() + " failed. About to try again for " + (tries + 1) + " out of " + maxTries + " times...");

			try {
				Thread.sleep(millisecondsBetweenTries);
			} catch (InterruptedException ie) {
				LOG.error("Thread has been asked to interrupt while waiting between retries. Returning null as a response.", ie);
				Thread.currentThread().interrupt(); // Restore the interrupted status of the thread
				return null;
			}

			LOG.debug("After waiting " + millisecondsBetweenTries + " ms " + actionPerformer.getUrlPath() + " is about to be performed...");

			return execute(actionPerformer, resultClass);
		}
	}
}

Add executor to retry calls synchronously upon failure


/*
 * This file is part of ELKI:
 * Environment for Developing KDD-Applications Supported by Index-Structures
 *
 * Copyright (C) 2019
 * ELKI Development Team
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 */
package elki.clustering.hierarchical;

import org.junit.Test;

import elki.Algorithm;
import elki.clustering.AbstractClusterAlgorithmTest;
import elki.clustering.hierarchical.extraction.CutDendrogramByNumberOfClusters;
import elki.data.Clustering;
import elki.database.Database;
import elki.utilities.ELKIBuilder;

/**
 * Perform hierarchical clustering around medoids.
 *
 * @author Erich Schubert
 */
public class HACAMTest extends AbstractClusterAlgorithmTest {
  @Test
  public void testHACAM() {
    Database db = makeSimpleDatabase(UNITTEST + "single-link-effect.ascii", 638);
    Clustering<?> clustering = new ELKIBuilder<>(CutDendrogramByNumberOfClusters.class) //
        .with(CutDendrogramByNumberOfClusters.Par.MINCLUSTERS_ID, 3) //
        .with(Algorithm.Utils.ALGORITHM_ID, HACAM.class) //
        .build().autorun(db);
    assertFMeasure(db, clustering, 0.93998);
    assertClusterSizes(clustering, new int[] { 200, 204, 234 });
  }

  @Test
  public void testHACAM2() {
    Database db = makeSimpleDatabase(UNITTEST + "3clusters-and-noise-2d.csv", 330);
    Clustering<?> clustering = new ELKIBuilder<>(CutDendrogramByNumberOfClusters.class) //
        .with(CutDendrogramByNumberOfClusters.Par.MINCLUSTERS_ID, 3) //
        .with(Algorithm.Utils.ALGORITHM_ID, HACAM.class) //
        .build().autorun(db);
    assertFMeasure(db, clustering, 0.915037);
    assertClusterSizes(clustering, new int[] { 55, 119, 156 });
  }
}

Add unit tests for HACAM.


package leetcode.maximum_depth_of_binary_tree;

import common.TreeNode;

public class Solution {
	public int maxDepth(TreeNode root) {
		if(root == null) return 0;
		int left = maxDepth(root.left);
		int right = maxDepth(root.right);
		if(left > right) return left + 1;
		else return right + 1;
	}
}

Add java solution for 104. Maximum Depth of Binary Tree


package leetcode.minimum_depth_of_binary_tree;

import common.TreeNode;

public class Solution {
	public int minDepth(TreeNode root) {
		if(root == null) return 0;
		if(root.left == null){
			return minDepth(root.right) + 1;
		}else if(root.right == null){
			return minDepth(root.left) + 1;
		}else{
			return Math.min(minDepth(root.left), minDepth(root.right)) + 1;
		}
	}

}

Add java solution for 111. Minimum Depth of Binary Tree


/*
 * Copyright 2016 Will Knez <wbknez.dev@gmail.com>
 *
 * 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.solsticesquared.schelling.utility;

import com.solsticesquared.schelling.Agent;
import com.solsticesquared.schelling.SchellingExplorer;

/**
 * Represents a mechanism for computing the "happiness" of an arbitrary agent
 * with her current neighborhood.
 */
public interface UtilityEvaluator {

    /**
     * Computes the "happiness" of the specified agent with her current
     * neighborhood according to some arbitrary logic.
     *
     * @param agent
     *        The agent whose neighborhood needs to be evaluated.
     * @param model
     *        The model to use.
     * @return The percentage of same-group neighbors (relative to an agent)
     * in a given neighborhood.
     * @throws NullPointerException
     *         If either {@code agent} or {@code model} is {@code null}.
     */
    double evaluate(final Agent agent, final SchellingExplorer model);
}

Add mechanism for an agent to compute her happiness with her current neighborhood.


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

import static org.junit.Assert.assertEquals;

import java.util.Locale;
import java.util.TimeZone;

import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Rule;
import org.junit.Test;

public class SystemDefaultsSwitchTest {

    private static Locale TEST_DEFAULT_LOCALE;
    private static Locale DEFAULT_LOCALE_BEFORE_TEST;

    private static TimeZone DEFAULT_TIMEZONE_BEFORE_TEST;
    private static TimeZone TEST_DEFAULT_TIMEZONE;

    @BeforeClass
    public static void classSetUp() {
        DEFAULT_LOCALE_BEFORE_TEST = Locale.getDefault();
        if (!DEFAULT_LOCALE_BEFORE_TEST.equals(Locale.CANADA)) {
            Locale.setDefault(Locale.CANADA);
        } else {
            // you seem to be from Canada...
            Locale.setDefault(Locale.CHINESE);
        }
        TEST_DEFAULT_LOCALE = Locale.getDefault();

        DEFAULT_TIMEZONE_BEFORE_TEST = TimeZone.getDefault();
        TimeZone utc = TimeZone.getTimeZone("UTC");
        if (!DEFAULT_TIMEZONE_BEFORE_TEST.equals(utc)) {
            TimeZone.setDefault(utc);
        } else {
            TimeZone.setDefault(TimeZone.getTimeZone("GMT"));
        }
        TEST_DEFAULT_TIMEZONE = TimeZone.getDefault();
    }

    @Rule
    public SystemDefaultsSwitch defaultsSwitch = new SystemDefaultsSwitch();

    @Test
    public void testDefaultLocaleNoAnnotation() throws Exception {
        assertEquals(TEST_DEFAULT_LOCALE, Locale.getDefault());
    }

    @Test
    @SystemDefaults(locale = "en_EN")
    public void testUseDifferentLocale() throws Exception {
        assertEquals(new Locale("en", "EN"), Locale.getDefault());
    }

    @Test
    public void testDefaultTimeZoneNoAnnotation() throws Exception {
        assertEquals(TEST_DEFAULT_TIMEZONE, TimeZone.getDefault());
    }

    @Test
    @SystemDefaults(timezone = "CET")
    public void testUseDifferentTimeZone() throws Exception {
        assertEquals(TimeZone.getTimeZone("CET"), TimeZone.getDefault());
    }

    @AfterClass
    public static void classTearDown() {
        Locale.setDefault(DEFAULT_LOCALE_BEFORE_TEST);
        TimeZone.setDefault(DEFAULT_TIMEZONE_BEFORE_TEST);
    }
}

Write basic unit test for SystemDefaultsSwitch


package org.synyx.urlaubsverwaltung.account.domain;

import org.junit.Test;
import org.synyx.urlaubsverwaltung.person.Person;

import java.time.LocalDate;
import java.util.List;

import static java.math.BigDecimal.TEN;
import static org.assertj.core.api.Assertions.assertThat;
import static org.synyx.urlaubsverwaltung.person.MailNotification.NOTIFICATION_USER;
import static org.synyx.urlaubsverwaltung.person.Role.USER;

public class AccountTest {

    @Test
    public void toStringTest() {
        final Person person = new Person("Theo", "Theo", "Theo", "Theo");
        person.setId(10);
        person.setPassword("Theo");
        person.setPermissions(List.of(USER));
        person.setNotifications(List.of(NOTIFICATION_USER));
        final Account account = new Account(person, LocalDate.MIN, LocalDate.MAX, TEN, TEN, TEN, "Comment");

        final String accountToString = account.toString();
        assertThat(accountToString).isEqualTo("Account[" +
            "person=10," +
            "validFrom=01.01.+1000000000," +
            "validTo=31.12.+999999999," +
            "annualVacationDays=10," +
            "vacationDays=<null>," +
            "remainingVacationDays=10," +
            "remainingVacationDaysNotExpiring=10," +
            "comment=Comment]");
        assertThat(accountToString).doesNotContain("Theo", "USER", "NOTIFICATION_USER");
    }
}

Add unit test for account to string method


package org.wikipedia.eventlogging;

import android.net.*;
import android.util.*;
import com.github.kevinsawicki.http.*;
import org.json.*;
import org.wikipedia.concurrency.*;

/**
 * Base class for all various types of events that are logged to EventLogging.
 *
 * Each Schema has its own class, and has its own constructor that makes it easy
 * to call from everywhere without having to duplicate param info at all places.
 * Updating schemas / revisions is also easier this way.
 */
public abstract class EventLoggingEvent {
    private static final String EVENTLOG_URL = "https://bits.wikimedia.org/event.gif";

    private final JSONObject data;

    /**
     * Create an EventLoggingEvent that logs to a given revision of a given schema with
     * the gven data payload.
     *
     * @param schema Schema name (as specified on meta.wikimedia.org)
     * @param revID Revision of the schema to log to
     * @param payload Data for the actual event payload. Considered to be
     *                an array of alternating key and value items (for easier
     *                construction in subclass constructors).
     *
     *                For example, what would be expressed in a more sane
     *                language as:
     *
     *                new SomeSubClass("Schema", 4200, {
     *                  "page": "List of mass murderers",
     *                  "section": "2014"
     *                });
     *
     *                would be expressed here as
     *
     *                new SomeSubClass("Schema", 4200,
     *                  "page", "List of mass murderers",
     *                  "section", "2014"
     *                );
     *
     *                This format should be only used in subclass constructors.
     *                The subclass constructors should take more explicit parameters
     *                depending on what they are logging.
     */
    protected EventLoggingEvent(String schema, int revID, String... payload) {
        data = new JSONObject();
        try {
            data.put("schema", schema);
            data.put("revision", revID);

            JSONObject event = new JSONObject();

            for (int i = 0; i < payload.length; i += 2) {
                event.put(payload[i], payload[i+1]);
            }

            data.put("event", event);
        } catch (JSONException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * Log the current event.
     *
     * Returns immediately after queueing the network request in the background.
     */
    public void log() {
        new LogEventTask(data).execute();
    }

    private static class LogEventTask extends SaneAsyncTask<Boolean> {
        private final JSONObject data;
        public LogEventTask(JSONObject data) {
            super(1);
            this.data = data;
        }

        @Override
        public Boolean performTask() throws Throwable {
            String dataURL = Uri.parse(EVENTLOG_URL)
                    .buildUpon().query(data.toString())
                    .build().toString();
            return HttpRequest.get(dataURL).ok();
        }

        @Override
        public void onCatch(Throwable caught) {
            // Do nothing bad. EL data is ok to lose.
            Log.d("Wikipedia", "Lost EL data: " + data.toString());
        }
    }
}

Add base class for EventLogging


package org.datadog.jenkins.plugins.datadog;

import hudson.EnvVars;
import hudson.Extension;
import hudson.model.PeriodicWork;
import hudson.model.Queue;
import java.util.concurrent.TimeUnit;
import java.util.logging.Logger;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

/**
 * This class registers a {@link PeriodicWork} with Jenkins to run periodically in order to enable
 * us to compute metrics related to the size of the queue.
 */
@Extension
public class DatadogQueueListener extends PeriodicWork {
  private static final String METRIC = "v1/series";
  private static final long RECURRENCE_PERIOD = TimeUnit.MINUTES.toMillis(1);

  private static final Logger logger = Logger.getLogger(DatadogQueueListener.class.getName());
  private static final Queue queue = Queue.getInstance();
  private static final EnvVars envVars = new EnvVars();

  @Override
  public long getRecurrencePeriod() {
    return RECURRENCE_PERIOD;
  }

  @Override
  protected void doRun() throws Exception {
    logger.fine("doRun called: Computing queue metrics");
    gauge("jenkins.queue.size", queue.getApproximateItemsQuickly().size());
  }

  private void gauge(String name, int value) {
    // Setup data point, of type [<unix_timestamp>, <value>]
    JSONArray points = new JSONArray();
    JSONArray point = new JSONArray();

    long currentTime = System.currentTimeMillis() / DatadogBuildListener.THOUSAND_LONG;
    point.add(currentTime); // current time, s
    point.add(value);
    points.add(point); // api expects a list of points

    JSONObject metric = new JSONObject();
    metric.put("metric", name);
    metric.put("points", points);
    metric.put("type", "gauge");
    metric.put("host", DatadogUtilities.getHostname(envVars)); // string

    // Place metric as item of series list
    JSONArray series = new JSONArray();
    series.add(metric);

    // Add series to payload
    JSONObject payload = new JSONObject();
    payload.put("series", series);

    logger.fine(String.format("Resulting payload: %s", payload.toString()));

    try {
      DatadogHttpRequests.post(payload, METRIC);
    } catch (Exception e) {
      logger.severe(e.toString());
    }
  }
}

Add a gauge to measure the size of the build queue.


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

import java.util.Map;

import javax.security.auth.callback.CallbackHandler;

/**
 * Factory to create authentication mechanisms.
 *
 * @author Darran Lofthouse
 */
public interface HttpServerAuthenticationMechanismFactory {

    /**
     * Get the names of the HTTP authentication mechanisms that can be supplied by this factory filtered by the supplied
     * properties.
     *
     * @param properties the selection criteria for the mechanisms.
     * @return the names of the supported HTTP authentication mechanisms.
     */
    String[] getMechanismNames(Map<String, ?> properties);

    /**
     * Obtain an instance of the authentication mechanism requested provided this is allowed by any policy specified within the supplied properties.
     *
     * @param mechanismName
     * @param properties
     * @param callbackHandler
     * @return
     */
    HttpServerAuthenticationMechanism createAuthenticationMechanism(String mechanismName, Map<String, ?> properties, CallbackHandler callbackHandler);

}

Add the factory API/SPI for HTTP authentication mechanisms.


package org.firstinspires.ftc.team7316.util;

/**
 * A class for PID
 */
public class PIDGenerator {

    private final double p, i, d;

    private double previous, sum;

    public PIDGenerator(double p, double i, double d) {
        this.p = p;
        this.i = i;
        this.d = d;
    }

    public double pushError(double error) {
        sum += error;
        double delta = previous - error;
        double output = p*error + i*sum + d*delta;
        previous = error;
        return output;
    }

}

Create a helper class for PID


package com.hubspot.singularity;

public enum  HealthcheckMethod {

  GET("GET"), POST("POST");

  private String method;

  private HealthcheckMethod(String method) {
    this.method = method;
  }

  public String getMethod() {
    return method;
  }
}

Add enum for supported healthcheck methods.


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

import uk.ac.ebi.quickgo.rest.metadata.MetaData;
import uk.ac.ebi.quickgo.rest.metadata.MetaDataProvider;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.function.Function;
import java.util.stream.Stream;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.Resource;

import static java.util.stream.Collectors.toList;

/**
 * Configure the provision of metadata for the Annotation service.
 *
 * @author Tony Wardell
 * Date: 07/03/2017
 * Time: 10:55
 * Created with IntelliJ IDEA.
 */
@Configuration
public class MetaDataConfig {
    private static final String SERVICE = "Annotation";
    private static final Path DEFAULT_METADATA_PATH = Paths.get("goa_uniprot.gpa-version");
    private static final Function<Stream<String>, List<MetaData>> META_DATA_MAPPER = (Stream<String> str) -> str
        .map(s -> new MetaData(null, s.substring(s.indexOf("2"))))
        .collect(toList());
    private static final int NUMBER_OF_METADATA_LINES = 1;

    @Value("${annotation.metadata.source}")
    private Resource source;

    @Bean
    MetaDataProvider metaDataProvider() throws IOException {
        Path metaDataPath = source != null ? Paths.get(source.getURI()) : DEFAULT_METADATA_PATH;
        return new MetaDataProvider(SERVICE, META_DATA_MAPPER, Files.lines(metaDataPath), NUMBER_OF_METADATA_LINES);
    }
}