package peergos.server.tests;

import org.junit.*;
import peergos.server.*;
import peergos.server.storage.*;
import peergos.shared.*;
import peergos.shared.crypto.*;
import peergos.shared.crypto.symmetric.*;
import peergos.shared.user.fs.*;
import peergos.shared.user.fs.cryptree.*;

import java.time.*;
import java.util.*;
import java.util.stream.*;

public class BlockSizeTests {
    private static Crypto crypto = Main.initCrypto();

    @Test
    public void largeDirectoryCryptreeNode() {
        SymmetricKey rBase = SymmetricKey.random();
        SymmetricKey wBase = SymmetricKey.random();
        SymmetricKey parent = SymmetricKey.random();
        SymmetricKey parentParent = SymmetricKey.random();
        FileProperties props = new FileProperties("a-directory", true, false, "", 0, 0,
                LocalDateTime.now(), false, Optional.empty(), Optional.empty());
        SigningPrivateKeyAndPublicHash signingPair = ChampTests.createUser(new RAMStorage(), crypto);

        Optional<RelativeCapability> parentCap = Optional.of(new RelativeCapability(Optional.empty(), crypto.random.randomBytes(32), parentParent, Optional.empty()));
        RelativeCapability nextChunk = new RelativeCapability(Optional.empty(), crypto.random.randomBytes(32), parentParent, Optional.empty());

        String nameBase = IntStream.range(0, 252).mapToObj(i -> "A").collect(Collectors.joining());
        List<NamedRelativeCapability> children = IntStream.range(0, 500)
                .mapToObj(i -> new NamedRelativeCapability(nameBase + String.format("%03d", i), nextChunk))
                .collect(Collectors.toList());
        CryptreeNode.ChildrenLinks childrenLinks = new CryptreeNode.ChildrenLinks(children);
        CryptreeNode.DirAndChildren dir = CryptreeNode.createDir(MaybeMultihash.empty(), rBase,
                wBase, Optional.of(signingPair), props, parentCap, parent, nextChunk, childrenLinks, crypto.hasher).join();

        byte[] raw = dir.dir.serialize();
        Assert.assertTrue(raw.length < Fragment.MAX_LENGTH);
    }
}

Add test for large directory raw cryptree size


/*
 * Copyright 2002-2021 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      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 org.springframework.test.context.testng;

import org.junit.platform.suite.api.IncludeEngines;
import org.junit.platform.suite.api.SelectPackages;
import org.junit.platform.suite.api.Suite;

/**
 * JUnit Platform based test suite for tests written in TestNG that involve the
 * Spring TestContext Framework.
 *
 *
This suite is only intended to be used manually within an IDE.
 *
 *
Logging Configuration

 *
 *
In order for our log4j2 configuration to be used in an IDE, you must set the
 * following system property before running any tests — for example, in
 * Run Configurations in Eclipse.
 *
 *

 * -Djava.util.logging.manager=org.apache.logging.log4j.jul.LogManager
 *

 *
 * @author Sam Brannen
 * @since 5.3.11
 */
@Suite
@IncludeEngines("testng")
@SelectPackages("org.springframework.test.context.testng")
class TestNGTestSuite {
}

Introduce @Suite for TestNG tests

Introduce @Suite for TestNG tests

In order to allow developers to execute TestNG tests in Eclipse IDE
without installing the TestNG plugin for Eclipse, this commit introduces
a JUnit Platform @Suite class that can be executed within the IDE.

See gh-27407


package tachyon.client.table;

import tachyon.annotation.PublicApi;

@PublicApi
public class TachyonRawTables {
  private static TachyonRawTables sTachyonRawTables;

  public static class TachyonRawTablesFactory {
    private TachyonRawTablesFactory() {} // prevent init

    public static synchronized TachyonRawTables get() {
      if (sTachyonRawTables == null) {
        sTachyonRawTables = new TachyonRawTables();
      }
      return sTachyonRawTables;
    }
  }

  private TachyonRawTables() {}
}

Add raw table client skeleton.

Add raw table client skeleton.


package fillingjars;

import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;

public class Solution {
    private static Scanner stdin = new Scanner(System.in);

    public static void main(String[] args) {
        long numJars = stdin.nextLong();
        long numOperations = stdin.nextLong();
        long sum = 0;
        for(int i = 0; i < numOperations; i++){
        	long firstJarIndex = stdin.nextLong();
        	long lastJarIndex = stdin.nextLong();
        	long numCandies = stdin.nextLong();
            sum += (lastJarIndex-firstJarIndex+1) * numCandies;
        }
        long average = (long)Math.floor(sum / numJars);
        System.out.println(average);
    }
}

Add solution to "Filling Jars" problem

Add solution to "Filling Jars" problem


package util;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

/**
 * Small helper functions that don't need their own class.
 */
public class Util {

    /**
     * Loads version string from properties file in resources folder.
     *
     * @return Version string
     */
    public static String getVersion() {
        ClassLoader loader = Thread.currentThread().getContextClassLoader();
        InputStream inputStream = loader.getResourceAsStream("version.properties");
        Properties prop = new Properties();
        String version = "";

        try {
            prop.load(inputStream);
        } catch (IOException e) {
            version = "x.y.z";
        }

        version = prop.getProperty("version");
        return version;
    }
}

Add util function to get version string in Java code


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

package org.chromium.chrome.test.util;

import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;

/**
 * This annotation can be used to mark a test that should be enabled only in Document mode.
 */
@Retention(RetentionPolicy.RUNTIME)
public @interface DisableInTabbedMode {
}

Add annotation to stop tests from running in tabbed mode

Need an annotation to run tests only in Document mode, if
it's available.

BUG=394854

Review URL: https://codereview.chromium.org/738183004

Cr-Commit-Position: 972c6d2dc6dd5efdad1377c0d224e03eb8f276f7@{#305127}


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

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

/**
 * Annotate fields that contain a {@link com.cloudbees.plugins.credentials.common.IdCredentials#getId()}.
 *
 * In future this annotation may be used to allow more credentials lookup over the remote channel layer by
 * ensuring that only those credential ids that were sent across to the remote side of the channel can be
 * retrieved by the remote side.
 *
 * @since 1.11
 */
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface CredentialsId {
}

Add an annotation to allow marking fields that hold credential ids


/*
 * Copyright 2008 The Kuali Foundation.
 *
 * Licensed under the Educational Community License, Version 1.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.opensource.org/licenses/ecl1.php
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.kuali.kra.s2s;

import java.sql.Connection;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.kuali.kra.KraTestBase;
/**
 *
 * This class is to test the database connectivity for coeus s2s engine.
 */
public class KualiDataSourceConnectionManagerTest extends KraTestBase {
    @Before
	public void setUp() throws Exception{
		super.setUp();
	}
    @After
	public void tearDown() throws Exception {
		super.tearDown();
	}
    @Test
	public final void getDatabaseConnectionTest() throws Exception{
        KualiDataSourceConnectionManager cnnMgr = new KualiDataSourceConnectionManager();
        assertNotNull(cnnMgr.getDatabaseConnection());
    }
    @Test
    public final void freeDatabaseConnectionTest() throws Exception{
        KualiDataSourceConnectionManager cnnMgr = new KualiDataSourceConnectionManager();
        Connection conn = cnnMgr.getDatabaseConnection();
        cnnMgr.freeDatabaseConnection(conn);
        assertTrue(conn.isClosed());
    }
}

Test class for coeus-s2s engine

Test class for coeus-s2s engine


/***
 This is free and unencumbered software released into the public domain.

 Anyone is free to copy, modify, publish, use, compile, sell, or
 distribute this software, either in source code form or as a compiled
 binary, for any purpose, commercial or non-commercial, and by any
 means.

 For more information, please refer to <http://unlicense.org/>
 */

package com.path.android.jobqueue;

import android.util.Log;

import nl.changer.enhancedpriorityjobqueue.BuildConfig;

/**
 * @author Mustafa Ferhan Akman
 *         <p/>
 *         Create a simple and more understandable Android logs.
 * @date 21.06.2012
 */

public class DebugLog {

    static String className;
    static String methodName;

    public static boolean isDebuggable() {
        return BuildConfig.DEBUG;
    }

    private static String createLog(String log) {

        StringBuffer buffer = new StringBuffer();
        buffer.append("[");
        buffer.append(methodName);
        buffer.append("] ");
        buffer.append(log);

        return buffer.toString();
    }

    private static void getMethodNames(StackTraceElement[] sElements) {
        className = sElements[1].getFileName();
        methodName = sElements[1].getMethodName();
    }

    public static void e(String message) {
        if (!isDebuggable())
            return;

        // Throwable instance must be created before any methods
        getMethodNames(new Throwable().getStackTrace());
        Log.e(className, createLog(message));
    }

    public static void i(String message) {
        if (!isDebuggable())
            return;

        getMethodNames(new Throwable().getStackTrace());
        Log.i(className, createLog(message));
    }

    public static void d(String message) {
        if (!isDebuggable())
            return;

        getMethodNames(new Throwable().getStackTrace());
        Log.d(className, createLog(message));
    }

    public static void v(String message) {
        if (!isDebuggable())
            return;

        getMethodNames(new Throwable().getStackTrace());
        Log.v(className, createLog(message));
    }

    public static void w(String message) {
        if (!isDebuggable())
            return;

        getMethodNames(new Throwable().getStackTrace());
        Log.w(className, createLog(message));
    }

    public static void wtf(String message) {
        if (!isDebuggable())
            return;

        getMethodNames(new Throwable().getStackTrace());
        Log.wtf(className, createLog(message));
    }

}

Remove non-persistant job queue from the library. All that we intend to do from now should be persistant on disk


package cs437.som.visualization;

import java.awt.Color;

/**
 * Interface for accessing color progressions.
 */
public interface ColorProgression {

    /**
     * Provide a Color object corresponding to this progression and based on a
     * scale of 0-100 (inclusive).
     *
     * @param intensity    The intensity the color should correspond to.
     * @return              The appropriate color to heat map {@code intensity}.
     */
    Color getColor(int intensity);
}

Add a color progression interface.

Add a color progression interface.


/*
 * DownloadClient Geodateninfrastruktur Bayern
 *
 * (c) 2016 GSt. GDI-BY (gdi.bayern.de)
 *
 * 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.bayern.gdi.model;

import junit.framework.TestCase;
import org.junit.Test;

import java.util.ArrayList;

/**
 * Test for ProcessingStepConfiguration.
 */
public class ProcessingStepConfigurationTest extends TestCase {

    /** Test the format getter/setter. */
    @Test
    public void testFormatType() {
        ProcessingStepConfiguration procStepConf
            = new ProcessingStepConfiguration();
        procStepConf.setFormatType("a format type");
        assertEquals("a format type", procStepConf.getFormatType());
    }

    /** Test the title getter/setter. */
    @Test
    public void testTitle() {
        ProcessingStepConfiguration procStepConf
            = new ProcessingStepConfiguration();
        procStepConf.setTitle("a title");
        assertEquals("a title", procStepConf.getTitle());
    }

    /** Test the description getter/setter. */
    @Test
    public void testDescription() {
        ProcessingStepConfiguration procStepConf
            = new ProcessingStepConfiguration();
        procStepConf.setDescription("a description");
        assertEquals("a description", procStepConf.getDescription());
    }

    /** Test the command getter/setter. */
    @Test
    public void testCommand() {
        ProcessingStepConfiguration procStepConf
            = new ProcessingStepConfiguration();
        procStepConf.setCommand("a command");
        assertEquals("a command", procStepConf.getCommand());
    }

    /** Test the parameter getter/setter. */
    @Test
    public void testParameters() {
        ProcessingStepConfiguration procStepConf
            = new ProcessingStepConfiguration();

        ArrayList<ConfigurationParameter> cp
            = new ArrayList<ConfigurationParameter>();

        ArrayList<ConfigurationParameter> emptyList
            = new ArrayList<ConfigurationParameter>();

        procStepConf.setParameters(cp);
        assertEquals(emptyList, procStepConf.getParameters());
    }

}

Add Unit Test for ProcessStepConfigurations


package leetcode.move_zeroes;

public class Solution {
    public void moveZeroes(int[] nums) {
        if(nums == null) return;
        int size = nums.length;
        if(size <= 1) return;
        int last0 = 0;
        for(int i = 0; i < size; i++){
            if(nums[i] != 0){
                if(i != last0){
                    nums[last0] = nums[i];
                    nums[i] = 0;
                }
                last0++;
            }
        }
    }
}

Add solution for 283. Move Zeroes

Add solution for 283. Move Zeroes

283. Move Zeroes: https://leetcode.com/problems/move-zeroes/


/*
 Copyright (C) 2003 EBI, GRL

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

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

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

import java.sql.Connection;

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

/**
 * Check for any coord_system.versions that are blank ('') - they should be NULL for various other things to work.
 */

public class BlankCoordSystemVersions extends SingleDatabaseTestCase {

	/**
	 * Create a new BlankCoordSystem testcase.
	 */
	public BlankCoordSystemVersions() {

		addToGroup("post_genebuild");
		addToGroup("release");
		setDescription("Check for any coord_system.version that are blank ('') - they should be NULL.");
		setTeamResponsible("Genebuilders");

	}

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

		boolean result = true;

		Connection con = dbre.getConnection();

		int rows = getRowCount(con, "SELECT COUNT(*) FROM coord_system WHERE version = ''");

		if (rows > 0) {

			ReportManager.problem(this, con, rows + " rows in coord_system have a blank versions - should be set to null");
			result = false;

		} else {

			ReportManager.correct(this, con, "No blank versions in coord_system");

		}

		return result;

	} // run

} // BlankCoordSystemVersions


package jeranvier.math.dsp.filters;

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

public class MovingAverage {

	public static Vector SimpleMovingAverage(Vector data, int windowRadius){
		Vector.Builder vb = new Vector.Builder(data.size());

		for(int i = 1; i <= windowRadius; i++){
			Complex sum = new Complex();
			for(int j=1; j<=i+windowRadius; j++){
				sum = sum.add(data.get(j));
			}
			vb.set(i, sum.divideBy(i+windowRadius));
		}

		for(int i = windowRadius+1; i < data.size()-windowRadius; i++){
			Complex sum = new Complex();
			for(int j=i-windowRadius; j<i+windowRadius; j++){
				sum = sum.add(data.get(j));
			}
			vb.set(i, sum.divideBy(2*windowRadius));
		}

		for(int i = data.size()-windowRadius; i <= data.size(); i++){
			Complex sum = new Complex();
			for(int j =i; j<=data.size(); j++){
				sum = sum.add(data.get(j));
			}
			vb.set(i, sum.divideBy(data.size()-i+1));
		}
		return vb.build();
	}

}

ADD simple implementation of a moving average


package org.linkeddatafragments.datasource;

import com.hp.hpl.jena.rdf.model.Model;

/**
 * Base implementation of a Basic Linked Data Fragment.
 * @author Ruben Verborgh
 */
public class BasicLinkedDataFragmentImpl implements BasicLinkedDataFragment {
	private final Model triples;
	private final long totalSize;

	/**
	 * Create a new Basic Linked Data Fragment.
	 * @param triples the triples (possibly partial)
	 * @param totalSize the total size
	 */
	public BasicLinkedDataFragmentImpl(Model triples, long totalSize) {
		this.triples = triples;
		this.totalSize = totalSize;
	}

	@Override
	public Model getTriples() {
		return triples;
	}

	@Override
	public long getTotalSize() {
		return totalSize;
	}
}

Add base implementation of BasicLinkedDataFragment.


package com.github.aureliano.verbum_domini.web.ui;

import java.io.IOException;

import javax.faces.component.FacesComponent;
import javax.faces.component.UIComponentBase;
import javax.faces.context.FacesContext;

import com.github.aureliano.verbum_domini.helper.UrlHelper;

@FacesComponent(
		value = "com.github.aureliano.verbum_domini.web.ui.HtmlStyleSheet",
		tagName = "styleSheet", createTag = true
	)
public class HtmlStyleSheet extends UIComponentBase {

	public HtmlStyleSheet() {
		super();
	}

	@Override
	public String getFamily() {
		return "custom.ui.verbum_domini";
	}

	@Override
	public void encodeBegin(FacesContext facesContext) throws IOException {
		StringBuilder tag = new StringBuilder();

		tag.append("<link rel=\"stylesheet\" type=\"text/css\"");

		String source = (String) super.getAttributes().get("source");
		if (source != null) {
			String url = UrlHelper.buildWebAppUrl("css/" + source + ".css");
			tag.append(" href=\"" + url + "\"");
		}

		String media = (String) super.getAttributes().get("media");
		if (media != null) {
			tag.append(" media=\"" + media + "\"");
		}

		tag.append("/>");

		facesContext.getResponseWriter().write(tag.toString());
	}
}

Create style sheet tag component.

Create style sheet tag component.


package com.skraylabs.poker.model;

import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.nullValue;
import static org.hamcrest.MatcherAssert.assertThat;

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

public class InvalidCardFormatExceptionTest {

  @Before
  public void setUp() throws Exception {}

  @After
  public void tearDown() throws Exception {}

  @Test
  public void testDefaultConstructor() {
    // Exercise
    InvalidCardFormatException exception = new InvalidCardFormatException();
    // Verify
    String message = exception.getMessage();
    String invalidString = exception.getInvalidString();
    assertThat(message, equalTo(InvalidCardFormatException.MSG_DEFAULT));
    assertThat(invalidString, is(nullValue()));
  }

  @Test
  public void testInitializingConstructor() {
    // Exercise
    InvalidCardFormatException exception = new InvalidCardFormatException("5x");
    // Verify
    String message = exception.getMessage();
    String invalidString = exception.getInvalidString();
    String expectedMessage = String.format(InvalidCardFormatException.MSG_WITH_SAMPLE, "5x");
    assertThat(message, equalTo(expectedMessage));
    assertThat(invalidString, equalTo("5x"));
  }
}

Define some constructor tests for InvalidCardFormatException.


package org.xdi.oxauth.service;

import java.util.HashSet;
import java.util.Set;

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

import org.xdi.oxauth.gluu.ws.rs.GluuConfigurationWS;

/**
 * Integration with Resteasy
 *
 * @author Yuriy Movchan
 * @version 0.1, 03/28/2017
 */
@Provider
public class TestResteasyInitializer extends Application {

	@Override
	public Set<Class<?>> getClasses() {
		HashSet<Class<?>> classes = new HashSet<Class<?>>();
		classes.add(GluuConfigurationWS.class);
		return classes;
	}

}

Add RS Test Application provider

Add RS Test Application provider


package org.aslak.github.merge.rest.jaxrs;

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

@Provider
public class CatchAllExceptionMapper implements ExceptionMapper<Throwable> {

    @Override
    public Response toResponse(Throwable exception) {
        return Response.status(Response.Status.INTERNAL_SERVER_ERROR)
            .header("Content-Type", MediaType.APPLICATION_JSON)
            .entity(
                    new StringBuilder()
                        .append("{\n")
                            .append("\"message\": ").append(exception.getMessage()).append("\",")
                        .append("}\n")
                    )
            .build();
    }
}

Add catch all Exception maper

Add catch all Exception maper


package com.souptitlemobile;

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

import android.content.Context;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.ViewGroup;

import com.facebook.react.uimanager.events.EventDispatcher;

public class TableView extends RecyclerView {
    private List<View> mRecycleViews = null;
    private int mRowHeight;
    private int mHoldItems;
    private EventDispatcher mEventDiscpatcher;

    private final MyAdapter mMyAdapter;

    public TableView(Context context) {
        super(context);
        setLayoutManager(new LinearLayoutManager(getContext()));
        mMyAdapter = new MyAdapter(); // TODO: what is it Adapter???
        setAdapter(mMyAdapter);
    }

    protected void onMeasure(int widthSpec, int heightSpec) {
        final int w =
            MeasureSpec.getSize(
              MeasureSpec.makeMeasureSpec(widthSpec, MeasureSpec.AT_MOST)
            );
        final int h =
            MeasureSpec.getSize(
              MeasureSpec.makeMeasureSpec(heightSpec, MeasureSpec.AT_MOST)
            );
        setMeasuredDimension(w, h);
    }
}

mobile: Make initial android table view realisation


/*
 * FindBugs - Find bugs in Java programs
 * Copyright (C) 2003, University of Maryland
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */

package edu.umd.cs.findbugs.detect;
import edu.umd.cs.findbugs.*;
import java.util.*;
import java.io.PrintStream;
import org.apache.bcel.classfile.*;
import java.util.zip.*;
import java.io.*;

import edu.umd.cs.pugh.visitclass.DismantleBytecode;
import edu.umd.cs.pugh.visitclass.Constants2;

public class PreferZeroLengthArrays extends BytecodeScanningDetector implements   Constants2 {
    boolean nullOnTOS = false;
    private BugReporter bugReporter;

  public PreferZeroLengthArrays(BugReporter bugReporter) {
	this.bugReporter = bugReporter;
  }

   public void visit(Code obj) {
	String returnType = methodSig.substring(methodSig.indexOf(")")+1);
	if (returnType.startsWith("[")) {
		nullOnTOS = false;
		super.visit(obj);
		}
	}

    public void sawOpcode(int seen) {

	switch (seen) {
	case ACONST_NULL:
		nullOnTOS = true;
		return;
	case ARETURN:
		if (nullOnTOS)
                  bugReporter.reportBug(new BugInstance("PZLA_PREFER_ZERO_LENGTH_ARRAYS", LOW_PRIORITY)
                        .addClassAndMethod(this)
                        .addSourceLine(this, PC));
		break;
	}
	nullOnTOS = false;
	}
}

Check for methods with array return type that return null

git-svn-id: e7d6bde23f017c9ff4efd468d79d66def666766b@1085 eae3c2d3-9b19-0410-a86e-396b6ccb6ab3


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

package org.jsimpledb;

import java.util.UUID;

import org.jsimpledb.annotation.JSimpleClass;
import org.jsimpledb.annotation.OnChange;
import org.jsimpledb.change.SimpleFieldChange;
import org.jsimpledb.test.TestSupport;
import org.testng.Assert;
import org.testng.annotations.Test;

public class OnChangeNestedGetterTest extends TestSupport {

    @Test
    public void testSimpleFieldChange() {

        final JSimpleDB jdb = BasicTest.getJSimpleDB(Person.class);
        final JTransaction tx = jdb.createTransaction(true, ValidationMode.AUTOMATIC);
        JTransaction.setCurrent(tx);
        try {

            final Person p = tx.create(Person.class);
            p.setId(UUID.randomUUID());
            p.setId(null);
            tx.commit();

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

// Model Classes

    @JSimpleClass(storageId = 100)
    public abstract static class Person implements JObject {

        @org.jsimpledb.annotation.JField(storageId = 101)
        public abstract UUID getId();
        public abstract void setId(UUID id);

        @OnChange("id")
        private void change(SimpleFieldChange<Person, ?> change) {
            Assert.assertEquals(this.getId(), change.getNewValue());
        }
    }
}

Add unit test exposing @OnChange bug.

Add unit test exposing @OnChange bug.


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


/*******************************************************************************
 * Copyright (c) 2004, 2005 Actuate Corporation.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *  Actuate Corporation  - initial API and implementation
 *******************************************************************************/

package org.eclipse.birt.core.data;

/**
 *	This class help to manipulate expressions.
 *
 */
public final class ExpressionUtil
{
	private static final String ROW_INDICATOR = "row";

	/**
	 * Return a row expression text according to given row name.
	 *
	 * @param rowName
	 * @return
	 */
	public static String createRowExpression( String rowName )
	{
		return ROW_INDICATOR + "[\"" + rowName + "\"]";
	}

	/**
	 * Return a row expression text according to given row index, which
	 * is 1-based.
	 *
	 * @param index
	 * @return
	 */
	public static String createRowExpression( int index )
	{
		return ROW_INDICATOR + "[" + index + "]";
	}
}

Add a utility class that can help to create row expressions.


package com.getbase.android.db.cursors;

import com.google.common.base.Function;

import android.database.Cursor;

public abstract class SingleRowTransforms {
  private SingleRowTransforms() {
  }

  public static Builder getColumn(String columnName) {
    return new Builder(columnName);
  }

  public static class Builder {
    private final String mColumnName;

    Builder(String columnName) {
      mColumnName = columnName;
    }

    public Function<Cursor, String> asString() {
      return new CursorRowFunction<String>(mColumnName) {
        @Override
        protected String getValue(Cursor c, int columnIndex) {
          return c.getString(columnIndex);
        }
      };
    }

    public Function<Cursor, Short> asShort() {
      return new CursorRowFunction<Short>(mColumnName) {
        @Override
        protected Short getValue(Cursor c, int columnIndex) {
          return c.getShort(columnIndex);
        }
      };
    }

    public Function<Cursor, Integer> asInteger() {
      return new CursorRowFunction<Integer>(mColumnName) {
        @Override
        protected Integer getValue(Cursor c, int columnIndex) {
          return c.getInt(columnIndex);
        }
      };
    }

    public Function<Cursor, Long> asLong() {
      return new CursorRowFunction<Long>(mColumnName) {
        @Override
        protected Long getValue(Cursor c, int columnIndex) {
          return c.getLong(columnIndex);
        }
      };
    }

    public Function<Cursor, Float> asFloat() {
      return new CursorRowFunction<Float>(mColumnName) {
        @Override
        protected Float getValue(Cursor c, int columnIndex) {
          return c.getFloat(columnIndex);
        }
      };
    }

    public Function<Cursor, Double> asDouble() {
      return new CursorRowFunction<Double>(mColumnName) {
        @Override
        protected Double getValue(Cursor c, int columnIndex) {
          return c.getDouble(columnIndex);
        }
      };
    }

    public Function<Cursor, Boolean> asBoolean() {
      return new CursorRowFunction<Boolean>(mColumnName) {
        @Override
        protected Boolean getValue(Cursor c, int columnIndex) {
          return c.getInt(columnIndex) == 1;
        }
      };
    }
  }

  private abstract static class CursorRowFunction<T> implements Function<Cursor, T> {
    protected final String mColumnName;
    private int mColumnIndex;
    private boolean mInitialized;

    protected CursorRowFunction(String columnName) {
      mColumnName = columnName;
    }

    private int getColumnIndex(Cursor c) {
      if (!mInitialized) {
        mColumnIndex = c.getColumnIndexOrThrow(mColumnName);
        mInitialized = true;
      }

      return mColumnIndex;
    }

    @Override
    public final T apply(Cursor c) {
      int index = getColumnIndex(c);
      return c.isNull(index)
          ? null
          : getValue(c, index);
    }

    protected abstract T getValue(Cursor c, int columnIndex);
  }
}

Add helper class for building functions for getting single column


package org.infinispan.demo;

import org.infinispan.client.hotrod.RemoteCache;
import org.infinispan.client.hotrod.RemoteCacheManager;
import org.infinispan.client.hotrod.configuration.ConfigurationBuilder;
import org.infinispan.client.hotrod.impl.ConfigurationProperties;

public class HotRodClientRepl {

    public static final String ISPN_IP = "127.0.0.1";
    public static final String CACHE_NAME = "replicated";

    public static void main(String[] args) throws Exception {

        // run cluster of two servers with replicated cache using predefined replicated confing
        // ./standalone.sh -c clustered.xml
        // ./standalone.sh -c clustered.xml -Djboss.socket.binding.port-offset=100
        // later on kill the first server, listening on default HR port 11222

        ConfigurationBuilder builder = new ConfigurationBuilder();
        builder.addServer().host(ISPN_IP).port(ConfigurationProperties.DEFAULT_HOTROD_PORT);
        RemoteCacheManager cacheManager = new RemoteCacheManager(builder.build());

        RemoteCache<Object, Object> cache = cacheManager.getCache();
        cache.put("key", "value");

        System.out.println("key pushed into cluter, kill server 1 listening on 127.0.0.1:11222");
        System.out.println("sleeping for 15s");

        Thread.sleep(15_000);

        System.out.println("getting key from cluster");
        System.out.printf("got value '%s'\n", cache.get("key"));

        cacheManager.stop();
    }

}

Add HR client example, which fails over to another ISPN server


package com.easternedgerobotics.rov.control;

import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;

import java.util.Arrays;

@RunWith(Parameterized.class)
@SuppressWarnings({"checkstyle:magicnumber"})
public class AnalogToPowerLevelTest {
    @Parameterized.Parameters(name = "Input {0} => Output {1}")
    public static Iterable<Object[]> data() {
        return Arrays.asList(new Object[][] {
            {-1.00f, 100},
            {-0.75f, 100},
            {-0.50f, 100},
            {-0.25f, 100},
            {0.00f,  100},
            {0.05f,  100},
            {0.10f,   94},
            {0.15f,   89},
            {0.20f,   83},
            {0.25f,   78},
            {0.30f,   72},
            {0.35f,   67},
            {0.40f,   61},
            {0.45f,   56},
            {0.50f,   50},
            {0.55f,   45},
            {0.60f,   39},
            {0.65f,   34},
            {0.70f,   28},
            {0.75f,   23},
            {0.80f,   17},
            {0.85f,   11},
            {0.90f,    6},
            {0.95f,    1},
            {1.00f,    0},
            {1.25f,    0},
            {1.50f,    0},
            {1.75f,    0},
            {2.00f,    0},
        });
    }

    private final float input;

    private final int expected;

    public AnalogToPowerLevelTest(final Object input, final Object expected) {
        this.input = (Float) input;
        this.expected = (Integer) expected;
    }

    @Test
    public final void analogToPowerLevel() {
        Assert.assertEquals(AnalogToPowerLevel.convert(input), expected);
    }
}

Add test for AnalogToPowerLevel control

Add test for AnalogToPowerLevel control


package org.fxmisc.richtext.api;

import javafx.stage.Stage;
import org.fxmisc.richtext.InlineCssTextAreaAppTest;
import org.fxmisc.richtext.TextBuildingUtils;
import org.junit.Test;

import java.util.Optional;

import static org.junit.Assert.assertEquals;

public class ParagraphIndexMappingTests extends InlineCssTextAreaAppTest {

    private static final int TOTAL_NUMBER_OF_LINES = 80;
    private static final int LAST_PAR_INDEX = TOTAL_NUMBER_OF_LINES - 1;
    private static final String CONTENT = TextBuildingUtils.buildLines(TOTAL_NUMBER_OF_LINES);

    @Override
    public void start(Stage stage) throws Exception {
        super.start(stage);
        area.replaceText(CONTENT);
    }

    @Test
    public void all_par_to_visible_par_index_is_correct() {
        interact(() -> area.showParagraphAtTop(0));
        assertEquals(Optional.of(0), area.allParToVisibleParIndex(0));

        interact(() -> area.showParagraphAtBottom(LAST_PAR_INDEX));
        assertEquals(Optional.of(area.getVisibleParagraphs().size() - 1), area.allParToVisibleParIndex(LAST_PAR_INDEX));
    }

    @Test
    public void visible_par_to_all_par_index_is_correct() {
        interact(() -> area.showParagraphAtTop(0));
        assertEquals(0, area.visibleParToAllParIndex(0));

        interact(() -> area.showParagraphAtBottom(LAST_PAR_INDEX));
        assertEquals(LAST_PAR_INDEX, area.visibleParToAllParIndex(area.getVisibleParagraphs().size() - 1));

    }
}

Add test: paragraph index mapping (allPar <-> visiblePar) works


class UntilContinue {
    public static void main(String[] args) {
	int i = 1;
	until (i == 6) {
	    i = i + 1;
	    System.out.println(3);
	    continue;
	    System.out.println(i);
	}
    }
}

Add until test (with continue).

Add until test (with continue).


package shadow.typecheck.type;

import java.util.ArrayList;

/**
 * Represents the contents of a Shadow documentation comment. Should be
 * associated with a class/interface/exception/singleton declaration or
 * a field/method declaration.
 */
public class Documentation
{
	private ArrayList<String> lines;

	public Documentation()
	{
		lines = new ArrayList<String>();
	}

	public void addLine(String line)
	{
		lines.add(line);
	}

	public String[] getLines()
	{
		return (String[]) lines.toArray();
	}
}

Reset the branch and created a class to store documentation comments


package org.robockets.buttonmanager.joysticks;

public enum XboxOne {
	A(1),
	B(2),
	X(3),
	Y(4),
	RIGHT_BUMPER(6),
	LEFT_BUMPER(5),
	RIGHT_TRIGGER_AXIS(3),
	LEFT_TRIGGER_AXIS(2),
	LEFT_X_AXIS(0),
	LEFT_Y_AXIS(1),
	RIGHT_X_AXIS(4),
	RIGHT_Y_AXIS(5);

	private int buttonNumber = 0;
	XboxOne(int buttonNumber) {
        this.buttonNumber = buttonNumber;
    }

    public int getButtonNumber() {
        return this.buttonNumber;
    }
}

Add enum for Xbox One controllers

Add enum for Xbox One controllers


/*
 * Zed Attack Proxy (ZAP) and its related class files.
 *
 * ZAP is an HTTP/HTTPS proxy for assessing web application security.
 *
 * Copyright 2015 The ZAP Development Team
 *
 * 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.zaproxy.zap.model;

/**
 * Signals that a {@code Message} is not valid.
 *
 * @see org.zaproxy.zap.extension.httppanel.Message
 * @since 2.4.0
 */
public class InvalidMessageException extends Exception {

    private static final long serialVersionUID = -1198168846311407641L;

    public InvalidMessageException() {
        super();
    }

    public InvalidMessageException(String message) {
        super(message);
    }

    public InvalidMessageException(String message, Throwable cause) {
        super(message, cause);
    }

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

    protected InvalidMessageException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
        super(message, cause, enableSuppression, writableStackTrace);
    }
}

Add exception to signal invalid messages


package org.example;

import javax.inject.Inject;

import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.forge.arquillian.archive.ForgeArchive;
import org.jboss.forge.container.ContainerControl;
import org.jboss.forge.container.Status;
import org.jboss.shrinkwrap.api.ArchivePaths;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.asset.StringAsset;
import org.jboss.shrinkwrap.api.spec.JavaArchive;
import org.jboss.shrinkwrap.resolver.api.DependencyResolvers;
import org.jboss.shrinkwrap.resolver.api.maven.MavenDependencyResolver;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;

/**
 * @author Lincoln Baxter, III
 */
@RunWith(Arquillian.class)
public class AddonIncludingJARsTest
{
   @Deployment
   public static ForgeArchive getDeployment()
   {
      ForgeArchive archive = ShrinkWrap
               .create(ForgeArchive.class)
               .addAsLibraries(
                        DependencyResolvers.use(MavenDependencyResolver.class).loadMetadataFromPom("pom.xml")
                                 .artifact("javax.enterprise:cdi-api:1.0").resolveAs(JavaArchive.class))
               .addAsManifestResource(new StringAsset(""), ArchivePaths.create("beans.xml"))
               .setAsForgeXML(new StringAsset("<addon/>"));

      return archive;
   }

   @Inject
   private ContainerControl control;

   @Test
   public void testContainerInjectionWorksWithConflictingCDIDependency()
   {
      Assert.assertNotNull(control);
      Assert.assertEquals(Status.STARTED, control.getStatus());
   }

}

Test container functionality with conflicting JARs from core impl


/**
 * Copyright (C) 2009-2013 FoundationDB, LLC
 *
 * 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 com.foundationdb.server.service.plugins;

import java.util.Collection;
import java.util.Collections;

public final class NoPluginsFinder implements PluginsFinder {
    @Override
    public Collection<? extends Plugin> get() {
        return Collections.emptyList();
    }
}

Add an empty implementation of PluginsFinder that can be bound when there is no convenient file system.


package com.grayben.riskExtractor.helpers;

import com.grayben.riskExtractor.htmlScorer.ScoredText;
import com.grayben.riskExtractor.htmlScorer.partScorers.Scorer;
import org.apache.commons.io.IOUtils;
import org.jsoup.nodes.Element;
import org.jsoup.nodes.Node;

import java.io.InputStream;
import java.util.Set;

/**
 * Created by beng on 20/04/2016.
 */
public class ScoredTextReverseEngineerer {

    public static Node treeFrom(ScoredText scoredText, Set<Scorer<Element>> elementScorers){
        throw new UnsupportedOperationException("Not implemented");
    }

    public static String htmlFrom(Node tree){
        StringBuilder sb = new StringBuilder();
        tree.html(sb);
        return sb.toString();
    }

    public static String htmlFrom(ScoredText scoredText, Set<Scorer<Element>> elementScorers){
        Node tree = treeFrom(scoredText, elementScorers);
        return htmlFrom(tree);
    }

    public static InputStream inputStreamFrom(String html){
        return IOUtils.toInputStream(html);
    }

    public static InputStream inputStreamFrom(Node tree){
        String html = htmlFrom(tree);
        return inputStreamFrom(html);
    }

    public static InputStream inputSteamFrom(ScoredText scoredText, Set<Scorer<Element>> elementScorers){
        String html = htmlFrom(scoredText, elementScorers);
        return inputStreamFrom(html);
    }

}

Add static methods which reverse engineer ScoredText


package net.engin33r.luaspigot.lua;

import org.luaj.vm2.LuaTable;
import org.luaj.vm2.LuaValue;

/**
 * Utility class for validating arguments against {@link WeakType} types.
 */
public class TypeValidator {
    public static void validate(LuaTable val, String type) {
        LuaValue ttype = val.get("type");
        if (ttype == LuaValue.NIL) {
            LuaValue.error(type + " expected, got table");
        } else {
            String vtype = ttype.tojstring();
            if (!vtype.equals(type))
                LuaValue.error(type + " expected, got " + vtype);
        }
    }
}

Add utility class for validating tables against WeakTypes


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

package de.sormuras.bach;

import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;

import java.net.URI;
import java.nio.file.Path;
import java.util.List;

import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertLinesMatch;

class MainrunnerTests {

  /** https://github.com/sormuras/mainrunner/releases */
  private static final String VERSION = "2.0.5";

  @Test
  void buildMainrunner(@TempDir Path temp) throws Exception {
    var uri = URI.create("https://github.com/sormuras/mainrunner/archive/" + VERSION + ".zip");
    var zip = new Downloader(new TestRun(temp, temp), temp).download(uri);
    var extract =
        new ProcessBuilder("jar", "--extract", "--file", zip.getFileName().toString())
            .directory(temp.toFile())
            .inheritIO()
            .start();
    assertEquals(0, extract.waitFor(), extract.toString());

    var test = new TestRun(temp, temp);
    var bach = new Bach(test);
    assertDoesNotThrow(bach::build, test::toString); // not test.toString()

    assertLinesMatch(List.of(), test.errLines());
    assertLinesMatch(List.of("TODO"), test.outLines());
  }
}

Load and extract "Mainrunner" project sample


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

import org.apache.commons.collections.OrderedIterator;
import org.apache.commons.collections.ResettableIterator;

/**
 * Provides an implementation of an empty ordered iterator.
 *
 * @since Commons Collections 3.1
 * @version $Revision: 1.1 $ $Date: 2004/05/26 21:52:40 $
 *
 * @author Stephen Colebourne
 */
public class EmptyOrderedIterator extends AbstractEmptyIterator implements OrderedIterator, ResettableIterator {

    /**
     * Singleton instance of the iterator.
     * @since Commons Collections 3.1
     */
    public static final OrderedIterator INSTANCE = new EmptyOrderedIterator();

    /**
     * Constructor.
     */
    protected EmptyOrderedIterator() {
        super();
    }

}

Add iterator to ensure implementation is as per v3.0

git-svn-id: b713d2d75405ee089de821fbacfe0f8fc04e1abf@131751 13f79535-47bb-0310-9956-ffa450edef68


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

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

import org.testng.annotations.Test;
import org.zanata.common.LocaleId;
import org.zanata.model.HLocale;
import org.zanata.model.HPerson;

import com.google.common.collect.Lists;

import java.util.List;

/**
 * @author Carlos Munoz <a
 *         href="mailto:camunoz@redhat.com">camunoz@redhat.com</a>
 */
@Test
public class FilterUtilTest {

    private static final List<HLocale> ALL_LOCALES = Lists.newArrayList(
            new HLocale(
                    LocaleId.DE), new HLocale(LocaleId.EN), new HLocale(
                    LocaleId.FR));

    @Test
    public void filterOutEmptyPersonList() throws Exception {
        assertThat(
                FilterUtil.filterOutPersonList(Lists.<HPerson> newArrayList(),
                        Lists.<HPerson> newArrayList())).isEmpty();
    }

    @Test
    public void filterOutSamePersonList() throws Exception {
        HPerson person1 = new HPerson();
        HPerson person2 = new HPerson();
        HPerson person3 = new HPerson();
        List<HPerson> all = Lists.newArrayList(person1, person2, person3);
        List<HPerson> filter = Lists.newArrayList(person1, person2, person3);

        assertThat(
                FilterUtil.filterOutPersonList(all, filter)).isEmpty();
    }

    @Test
    public void localeNotIncluded() throws Exception {
        assertThat(
                FilterUtil.isIncludeLocale(ALL_LOCALES,
                        new HLocale(LocaleId.EN), null)).isFalse();
    }
}

Add unit tests to satisfy coverage requirements.


/*
 * Perfclispe
 *
 *
 * Copyright (c) 2013 Jakub Knetl
 *
 * 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.perfclipse.ui.swt.widgets;

import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.RowLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;

/**
 * @author Jakub Knetl
 *
 */
public class TableViewerControl extends Composite {

	private Button addElementButton;
	private Button editElementButton;
	private Button deleteElementButton;

	/**
	 * @param parent
	 * @param style
	 */
	public TableViewerControl(Composite parent, boolean hasEditButton, int style) {
		super(parent, style);

		setLayout(new RowLayout(SWT.VERTICAL));

		addElementButton = new Button(this, SWT.PUSH);
		addElementButton.setText("Add");

		if (hasEditButton){
			editElementButton = new Button(this, SWT.PUSH);
			editElementButton.setText("Edit");
		}

		deleteElementButton = new Button(this, SWT.PUSH);
		deleteElementButton.setText("Delete");
	}

	public Button getAddElementButton() {
		return addElementButton;
	}
	public Button getEditElementButton() {
		return editElementButton;
	}
	public Button getDeleteElementButton() {
		return deleteElementButton;
	}
}

Add composite widget for tableViewer contorls


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

import java.lang.annotation.Retention;
import java.lang.annotation.Target;

import static java.lang.annotation.ElementType.ANNOTATION_TYPE;
import static java.lang.annotation.ElementType.CONSTRUCTOR;
import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.ElementType.PARAMETER;
import static java.lang.annotation.RetentionPolicy.CLASS;

/**
 * Denotes that the annotated element should only be called on the given API level
 * or higher.
 * <p>
 * This is similar in purpose to the older {@code @TargetApi} annotation, but more
 * clearly expresses that this is a requirement on the caller, rather than being
 * used to "suppress" warnings within the method that exceed the {@code minSdkVersion}.
 */
@Retention(CLASS)
@Target({ANNOTATION_TYPE,METHOD,CONSTRUCTOR,FIELD,PARAMETER})
public @interface RequiresApi {
    @IntRange(from=1)
    int api();
}

189699: Add @RequiredApi annotation as the dual of @TargetApi

Change-Id: I0310b642a049f077c839d1408efa90d10f01756a


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

import static java.util.concurrent.TimeUnit.SECONDS;

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.core.Is.is;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import org.junit.Test;

public class LastReturnedTimestampTest {
    private static final long INITIAL_VALUE = 100;

    LastReturnedTimestamp timestamp = new LastReturnedTimestamp(INITIAL_VALUE);
    private ExecutorService executor = Executors.newFixedThreadPool(4);

    @Test
    public void shouldIncreaseTheValueToAHigherNumber() {
        timestamp.increaseToAtLeast(INITIAL_VALUE + 10);

        assertThat(timestamp.get(), is(INITIAL_VALUE + 10));
    }

    @Test
    public void shouldNotIncreaseTheValueToALowerNumber() {
        timestamp.increaseToAtLeast(INITIAL_VALUE - 10);

        assertThat(timestamp.get(), is(INITIAL_VALUE));
    }

    @Test
    public void handleConcurrentlyIncreasingTheValue() throws InterruptedException {
        for(int i = 0; i <= 100; i++) {
            final int value = i;
            executor.submit(new Runnable() {
                @Override
                public void run() {
                    timestamp.increaseToAtLeast(INITIAL_VALUE + value);
                }
            });
        }

        waitForExecutorToFinish();

        assertThat(timestamp.get(), is(INITIAL_VALUE + 100));
    }

    private void waitForExecutorToFinish() throws InterruptedException {
        executor.shutdown();
        executor.awaitTermination(10, SECONDS);
    }
}

Add last returned timestamp tests

Add last returned timestamp tests


/*
 * Copyright (c) 2014 Ben Murphy
 *
 * 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.smurph.openlicenseparserlib.frags;

import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.os.Bundle;

import com.smurph.openlicenseparserlib.R;

public class LicenseActivity extends Activity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.activity_license);

		Bundle args = getIntent().getExtras();

		FragmentManager fm = getFragmentManager();

		Fragment frag = fm.findFragmentByTag(LicenseFragment.FRAG_TAG);

		if (frag == null) {
			frag = new LicenseFragment();
			frag.setArguments(args);
		} else {
			if (frag.getArguments() == null)
				frag.setArguments(args);
			else {
				if (args != null) {
					Bundle arg = frag.getArguments();
					arg.clear();
					arg.putAll(args);
				}
			}
		}

		fm.beginTransaction()
				.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE)
				.replace(R.id.container, frag, LicenseFragment.FRAG_TAG)
				.commit();
	}
}

Create a ListActivity so that the Fragment functionality can also be used as an Activity


package org.opennms.web.element;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;

import javax.sql.DataSource;

import org.opennms.core.resource.Vault;
import org.opennms.core.resource.db.DbConnectionFactory;
import org.opennms.netmgt.dao.db.PopulatedTemporaryDatabaseTestCase;

public class NetworkElementFactoryTest extends PopulatedTemporaryDatabaseTestCase {
    @Override
    protected void setUp() throws Exception {
        setSetupIpLike(true);

        super.setUp();

        Vault.setDbConnectionFactory(new DataSourceDbConnectionFactory(getDataSource()));
    }

    public void testGetNodesWithIpLikeOneInterface() throws Exception {
        jdbcTemplate.update("INSERT INTO node (nodeId, nodeCreateTime, nodeType) VALUES (1, now(), 'A')");
        jdbcTemplate.update("INSERT INTO ipInterface (nodeId, ipAddr, isManaged) VALUES (1, '1.1.1.1', 'M')");

        assertEquals("node count in DB", 1, jdbcTemplate.queryForInt("SELECT count(*) FROM node"));
        assertEquals("ipInterface count in DB", 1, jdbcTemplate.queryForInt("SELECT count(*) FROM ipInterface"));

        Node[] nodes = NetworkElementFactory.getNodesWithIpLike("*.*.*.*");
        assertEquals("node count", 1, nodes.length);
    }

    // bug introduced in revision 2932
    public void testGetNodesWithIpLikeTwoInterfaces() throws Exception {
        jdbcTemplate.update("INSERT INTO node (nodeId, nodeCreateTime, nodeType) VALUES (1, now(), 'A')");
        jdbcTemplate.update("INSERT INTO ipInterface (nodeId, ipAddr, isManaged) VALUES (1, '1.1.1.1', 'M')");
        jdbcTemplate.update("INSERT INTO ipInterface (nodeId, ipAddr, isManaged) VALUES (1, '1.1.1.2', 'M')");

        assertEquals("node count in DB", 1, jdbcTemplate.queryForInt("SELECT count(*) FROM node"));
        assertEquals("ipInterface count in DB", 2, jdbcTemplate.queryForInt("SELECT count(*) FROM ipInterface"));

        Node[] nodes = NetworkElementFactory.getNodesWithIpLike("*.*.*.*");
        assertEquals("node count", 1, nodes.length);
    }

    public class DataSourceDbConnectionFactory implements DbConnectionFactory {
        private DataSource m_dataSource;

        public DataSourceDbConnectionFactory(DataSource dataSource) {
            m_dataSource = dataSource;
        }

        public void destroy() throws SQLException {
            throw new UnsupportedOperationException("not implemented");
        }

        public Connection getConnection() throws SQLException {
            return m_dataSource.getConnection();
        }

        public void init(String dbUrl, String dbDriver) throws ClassNotFoundException, SQLException {
            throw new UnsupportedOperationException("not implemented");
        }

        public void init(String dbUrl, String dbDriver, String username, String password) throws ClassNotFoundException, SQLException {
            throw new UnsupportedOperationException("not implemented");
        }

        public void init(String dbUrl, String dbDriver, Properties properties) throws ClassNotFoundException, SQLException {
            throw new UnsupportedOperationException("not implemented");
        }

        public void releaseConnection(Connection connection) throws SQLException {
            connection.close();
        }

    }
}

Add tests for NetworkElementFactory.getNodesWithIpLike with multiple interfaces on the same node. This uses the new iplike functionality in PopulatedTemporaryDatabaseTestCase


package com.twilio.ivrrecording.servlet.extension;

import com.twilio.ivrrecording.models.Agent;
import com.twilio.ivrrecording.repositories.AgentRepository;
import com.twilio.ivrrecording.servlet.WebAppServlet;
import com.twilio.ivrrecording.servlet.common.Redirect;
import com.twilio.sdk.verbs.*;
import com.twilio.sdk.verbs.Number;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public class ConnectServlet extends WebAppServlet {

    private AgentRepository agentRepository;

    public ConnectServlet() {
        this(new AgentRepository());
    }

    public ConnectServlet(AgentRepository agentRepository) {
        this.agentRepository = agentRepository;
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws IOException {

        String selectedOption = request.getParameter("Digits");

        Agent agent = findAgentByExtension(selectedOption);
        if (agent == null) {
            try {
                redirectToMenu(response);
            } catch (TwiMLException e) {
                e.printStackTrace();
            }
        } else {
            TwiMLResponse twiMLResponse = new TwiMLResponse();
            Say say = new Say("You'll be connected shortly to your planet.");
            say.setVoice("alice");
            say.setLanguage("en-GB");

            Dial dial = new Dial();
            dial.setAction(String.format("/agents/call?agentId=%s", agent.getId()));

            Number number = new Number(agent.getPhoneNumber());
            number.setUrl("/agents/screen-call");

            try {
                dial.append(number);
                twiMLResponse.append(dial);
            } catch (TwiMLException e) {
                e.printStackTrace();
            }
            respondTwiML(response, twiMLResponse);
        }
    }

    private void redirectToMenu(HttpServletResponse response)
            throws TwiMLException, IOException {
        TwiMLResponse twiMLResponse = new TwiMLResponse();
        twiMLResponse.append(new com.twilio.sdk.verbs.Redirect("/ivr/welcome"));

        respondTwiML(response, twiMLResponse);
    }

    private Agent findAgentByExtension(String extension) {
        Map<String, String> planetsExtensiosn = new HashMap<>();
        planetsExtensiosn.put("2", "Brodo");
        planetsExtensiosn.put("3", "Dagobah");
        planetsExtensiosn.put("4", "Oober");

        return planetsExtensiosn.containsKey(extension)
                ? agentRepository.findByExtension(planetsExtensiosn.get(extension))
                : null;
    }
}

Fix missing file and git troubles

Fix missing file and git troubles


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

import java.io.IOException;
import java.io.StringReader;

import junit.framework.TestCase;

public class DotTerminatedMessageReaderTest extends TestCase {

	private DotTerminatedMessageReader reader;
	private StringBuilder str = new StringBuilder();
	private char[] buf = new char[64];

	public void testReadSimpleString() throws IOException {
		final String test = "Hello World!\r\n.\r\n";
		reader = new DotTerminatedMessageReader(new StringReader(test));

		int read = 0;
		while ((read = reader.read(buf)) != -1) {
			str.append(buf, 0, read-1);
		}

		assertEquals(str.toString(), "Hello World!");
	}

	public void testEmbeddedNewlines() throws IOException {
		final String test = "Hello\r\nWorld\nA\rB\r\n.\r\n";
		reader = new DotTerminatedMessageReader(new StringReader(test));

		int read = 0;
		while ((read = reader.read(buf)) != -1) {
			str.append(buf, 0, read-1);
		}

		assertEquals(str.toString(), "Hello\nWorld\nA\rB");
	}

	public void testDoubleCrBeforeDot() throws IOException {
		final String test = "Hello World!\r\r\n.\r\n";
		reader = new DotTerminatedMessageReader(new StringReader(test));

		int read = 0;
		while ((read = reader.read(buf)) != -1) {
			str.append(buf, 0, read-1);
		}

		assertEquals("Hello World!\r",str.toString());
	}

}

Fix and test case for NET-290 (incl test case this time)

git-svn-id: 4de9e10a8372d59eb4972153ee28637d84aca65e@920259 13f79535-47bb-0310-9956-ffa450edef68


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

package com.google.gerrit.acceptance.rest;

import static com.google.common.truth.Truth.assertThat;
import static org.apache.http.HttpStatus.SC_NOT_FOUND;

import com.google.gerrit.acceptance.AbstractDaemonTest;
import com.google.gerrit.acceptance.RestResponse;
import org.junit.Test;

public class NotFoundIT extends AbstractDaemonTest {
  @Test
  public void nonExistingRootCollection() throws Exception {
    RestResponse response = adminRestSession.get("/non-existing/");
    assertThat(response.getStatusCode()).isEqualTo(SC_NOT_FOUND);
    assertThat(response.getEntityContent()).isEqualTo("Not Found");

    response = adminRestSession.post("/non-existing/");
    assertThat(response.getStatusCode()).isEqualTo(SC_NOT_FOUND);
    assertThat(response.getEntityContent()).isEqualTo("Not Found");
  }

  @Test
  public void nonExistingView() throws Exception {
    RestResponse response = adminRestSession.get("/accounts/self/non-existing");
    assertThat(response.getStatusCode()).isEqualTo(SC_NOT_FOUND);
    assertThat(response.getEntityContent()).isEqualTo("Not found: non-existing");

    response = adminRestSession.post("/accounts/self/non-existing");
    assertThat(response.getStatusCode()).isEqualTo(SC_NOT_FOUND);
    assertThat(response.getEntityContent()).isEqualTo("Not found: non-existing");
  }
}

Add a test to verify that 404 is returned for non-existing REST endpoints

The error messages for non-existing root collections and non-existing
views / child collections are a bit inconsistent. This is because for
non-existing root collections no RestApiServlet is bound (generic not
found message), while for non-existing views and child collections the
error response is created within RestApiServlet (specific not found
message).

Change-Id: I1b6093a15546d554f7854ed9fcd022b18a0e27f8
Signed-off-by: Edwin Kempin <d43fb6c98c97e553b671ed9a9318100f1de386e7@google.com>


package exm.stc.common.lang;

import java.util.Collections;
import java.util.Map;
import java.util.TreeMap;

import exm.stc.common.Logging;

/**
 * Store bindings for argv that are specified at compile time
 */
public class CompileTimeArgs {
  /** Store in sorted order as nicety */
  private static final Map<String, String> compileTimeArgs =
                                    new TreeMap<String, String>();

  public static void addCompileTimeArg(String key, String value) {
    String prev = compileTimeArgs.put(key, value);
    if (prev != null) {
      Logging.getSTCLogger().warn("Overwriting old value of \"" + key + "\"."
          + " Replaced \"" + prev + "\" with \"" + value + "\"");
    }
  }

  public static String lookup(String key) {
    return compileTimeArgs.get(key);
  }

  public static Map<String, String> getCompileTimeArgs() {
    return Collections.unmodifiableMap(compileTimeArgs);
  }
}

Add support to turbine for adding additional keyword arguments

git-svn-id: 47705994653588c662f4ea400dfe88107361c0e2@7203 dc4e9af1-7f46-4ead-bba6-71afc04862de


package com.google.sps.servlets;

import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceConfig;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.EmbeddedEntity;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.EntityNotFoundException;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseAuthException;
import com.google.firebase.auth.FirebaseToken;
import com.google.firebase.auth.UserRecord;
import com.google.gson.Gson;
import com.google.sps.firebase.FirebaseAppManager;
import java.io.IOException;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/get-ta")
public class GetTAHelping extends HttpServlet {
  FirebaseAuth authInstance;
  DatastoreService datastore;
  Gson gson;

  @Override
  public void init(ServletConfig config) throws ServletException {
    try {
      authInstance = FirebaseAuth.getInstance(FirebaseAppManager.getApp());
      gson = new Gson();
    } catch (IOException e) {
      throw new ServletException(e);
    }
  }

  @Override
  public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
    datastore = DatastoreServiceFactory.getDatastoreService();
    System.setProperty(
        DatastoreServiceConfig.DATASTORE_EMPTY_LIST_SUPPORT, Boolean.TRUE.toString());

    try {
      // Retrive class entity
      String classCode = request.getParameter("classCode").trim();
      Key classKey = KeyFactory.stringToKey(classCode);
      Entity classEntity = datastore.get(classKey);

      String studentToken = request.getParameter("studentToken");
      FirebaseToken decodedToken = authInstance.verifyIdToken(studentToken);
      String studentID = decodedToken.getUid();

      // Get TA id
      EmbeddedEntity beingHelped = (EmbeddedEntity) classEntity.getProperty("beingHelped");
      String taID = (String) beingHelped.getProperty(studentID);

      // Get TA email
      UserRecord userRecord = authInstance.getUser(taID);
      String taEmail = userRecord.getEmail();

      response.setContentType("application/json;");
      response.getWriter().print(gson.toJson(taEmail));

    } catch (EntityNotFoundException e) {
      response.sendError(HttpServletResponse.SC_NOT_FOUND);
    } catch (IllegalArgumentException e) {
      response.sendError(HttpServletResponse.SC_BAD_REQUEST);
    } catch (FirebaseAuthException e) {
      response.sendError(HttpServletResponse.SC_FORBIDDEN);
    }
  }
}

Create servlet to get TA email helping student


package org.opendatakit.consts;

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

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

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

}

Generalize request code constants out of Tables


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

package org.scijava.console;

/**
 * Listener for output on {@code stdout} or {@code stderr}.
 *
 * @author Curtis Rueden
 * @see ConsoleService
 */
public interface OutputListener {

	/** Method called when output occurs on {@code stdout} or {@code stderr}. */
	void outputOccurred(final OutputEvent event);

}

Add an interface for OutputEvent listeners


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

import com.nexmo.client.AbstractClient;
import com.nexmo.client.HttpWrapper;
import com.nexmo.client.auth.TokenAuthMethod;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpUriRequest;
import org.junit.Before;

import java.io.ByteArrayInputStream;

import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

public abstract class ClientTest<T extends AbstractClient> {
    protected HttpWrapper wrapper;
    protected T client;

    @Before
    public void setupWrapper() {
        wrapper = new HttpWrapper(new TokenAuthMethod("not-an-api-key", "secret"));
    }

    protected HttpClient stubHttpClient(int statusCode, String content) throws Exception {
        HttpClient result = mock(HttpClient.class);

        HttpResponse response = mock(HttpResponse.class);
        StatusLine sl = mock(StatusLine.class);
        HttpEntity entity = mock(HttpEntity.class);

        when(result.execute(any(HttpUriRequest.class))).thenReturn(response);
        when(entity.getContent()).thenReturn(new ByteArrayInputStream(content.getBytes("UTF-8")));
        when(sl.getStatusCode()).thenReturn(statusCode);
        when(response.getStatusLine()).thenReturn(sl);
        when(response.getEntity()).thenReturn(entity);

        return result;
    }
}

Add abstract client test for shared functionality.


package nl.weeaboo.gdx.test;

import org.junit.Assert;

import nl.weeaboo.common.Dim2D;

public final class DimAssert {

    private DimAssert() {
    }

    /**
     * Checks if two dimensions are equal, allowing up to a small {@code epsilon} difference.
     */
    public static void assertEquals(Dim2D expected, Dim2D actual, double epsilon) {
        Assert.assertEquals("Invalid w: " + actual, expected.w, actual.w, epsilon);
        Assert.assertEquals("Invalid h: " + actual, expected.h, actual.h, epsilon);
    }

}

Add test helper methods for Dim2D

Add test helper methods for Dim2D


package gr.demokritos.iit.ydsapi.responses;

import com.google.gson.*;
import gr.demokritos.iit.ydsapi.model.DashboardConfig;

import java.lang.reflect.Type;
import java.util.List;

public class DashboardConfigListLoadResponse extends BaseResponse implements IResponse {
    private final List<DashboardConfig> items;

    public DashboardConfigListLoadResponse(Status status, String message, List<DashboardConfig> items) {
        super(status, message);
        this.items = items;
    }

    public DashboardConfigListLoadResponse(List<DashboardConfig> items) {
        super();

        if (items == null || items.isEmpty()) {
            setStatus(Status.NOT_EXISTS);
            setMessage("no dashboard configuration items found");
        } else {
            setStatus(Status.OK);
        }

        this.items = items;
    }

    @Override
    public String toJSON() {
        GsonBuilder gsonBuilder = new GsonBuilder();
        gsonBuilder
                .registerTypeAdapter(DashboardConfigListLoadResponse.class, new DashboardConfigListLoadResponseSerializer())
                .disableHtmlEscaping()
                .setPrettyPrinting();
        Gson gson = gsonBuilder.create();

        return gson.toJson(this);
    }

    @Override
    public JsonElement toJSONElement() {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    public class DashboardConfigListLoadResponseSerializer implements JsonSerializer<DashboardConfigListLoadResponse> {
        @Override
        public JsonElement serialize(DashboardConfigListLoadResponse r, Type type, JsonSerializationContext jsc) {
            final JsonObject jsonObject = new JsonObject();
            jsonObject.addProperty("status", r.getStatus().toString());
            jsonObject.addProperty("msg", r.getMessage());
            final JsonArray jsonItems = new JsonArray();
            if (r.items != null && !r.items.isEmpty()) {
                // Add items
                for (final DashboardConfig dc : r.items) {
                    final JsonElement jsonI = dc.toJSONElement();
                    jsonItems.add(jsonI);
                }
            }
            jsonObject.add("items", jsonItems);

            return jsonObject;
        }
    }
}

Add Dashboard Configurations list load response class


package com.braintreegateway.util;

import org.junit.Test;

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

public class CryptoTest {

    @Test
    public void secureCompareWithEqualStrings() {
        assertTrue(new Crypto().secureCompare("a_string", "a_string"));
    }

    @Test
    public void secureCompareWithNotEqualStrings() {
        assertFalse(new Crypto().secureCompare("a_string", "a_strong"));
    }

    @Test
    public void secureCompareWithLongerNotEqualStrings() {
        assertFalse(new Crypto().secureCompare("a_string", "a_string_that_is_longer"));
    }
}

Add tests for secure compare

Add tests for secure compare


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

package org.scijava.plugin;

/**
 * Abstract base class for {@link HandlerPlugin} implementations.
 *
 * @author Curtis Rueden
 */
public abstract class AbstractHandlerPlugin<D> extends AbstractRichPlugin
	implements HandlerPlugin<D>
{
	// NB: No implementation needed.
}

Add abstract base class for HandlerPlugins

While this class is not strictly necessary, it provides a nice symmetry
when implementing new HandlerPlugin types. Otherwise, the new plugin
type's interface extends HandlerPlugin, but the corresponding abstract
base class extends AbstractRichPlugin, which is a bit weird.


package technology.tabula;

import java.io.File;
import java.io.FilenameFilter;
import java.nio.file.Files;

import org.junit.Test;
import org.w3c.dom.*;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

/**
 * Created by matt on 2015-12-14.
 */
public class TestTableDetection {

    @Test
    public void testDetectionOfTables() throws Exception {
        String[] regionCodes = {"eu", "us"};

        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();

        for (String regionCode : regionCodes) {
            String directoryName = "src/test/resources/technology/tabula/icdar2013-dataset/competition-dataset-" + regionCode + "/";
            File dir = new File(directoryName);

            File[] pdfs = dir.listFiles(new FilenameFilter() {
                @Override
                public boolean accept(File dir, String name) {
                    return name.toLowerCase().endsWith(".pdf");
                }
            });

            for (File pdf : pdfs) {

                System.out.println("Testing " + pdf.getName());

                Document regionDocument = builder.parse(pdf.getAbsolutePath().replace(".pdf", "-reg.xml"));

                NodeList tables = regionDocument.getElementsByTagName("table");

                for (int i=0; i<tables.getLength(); i++) {

                    Element table = (Element) tables.item(i);
                    int tableId = Integer.parseInt(table.getAttribute("id"));

                    Element region = (Element) table.getElementsByTagName("region").item(0);
                    int regionId = Integer.parseInt(region.getAttribute("id"));
                    int page = Integer.parseInt(region.getAttribute("page"));

                    Element boundingBox = (Element) region.getElementsByTagName("bounding-box").item(0);
                    int x1 = Integer.parseInt(boundingBox.getAttribute("x1"));
                    int y1 = Integer.parseInt(boundingBox.getAttribute("y1"));
                    int x2 = Integer.parseInt(boundingBox.getAttribute("x2"));
                    int y2 = Integer.parseInt(boundingBox.getAttribute("y2"));

                    System.out.println("Table " + tableId + " is region " + regionId + " on page " + page + " with coords " + x1 + ", " + y1 + ", " + x2 + ", " + y2);
                }
            }
        }
    }
}

Create a test that reads in the icdar xml data


package com.sudoku.grid.ihm_grid_cells;

import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.text.Text;

/**
 *
 * @author groudame
 */
abstract class IhmGridLayout {
    private Group root;
    private Scene layout;
    private Text title;
    //Grid grille;
    public IhmGridLayout(String ttl){
        root = new Group();
        layout = new Scene(getRoot(), 300, 250);
        title = new Text(30,20,ttl);
        root.getChildren().add(title);

    }

    /**
     * @return the root
     */
    public Group getRoot() {
        return root;
    }

    /**
     * @return the layout
     */
    public Scene getLayout() {
        return layout;
    }

    /**
     * @return the title
     */
    public Text getTitle() {
        return title;
    }

}

Change pakage name to "grid"

Change pakage name to "grid"


package com.javarush.test.level09.lesson11.home03;

/* Метод в try..catch
Вводить с клавиатуры числа. Код по чтению чисел с клавиатуры вынести в отдельный метод readData.
Обернуть все тело (весь код внутри readData, кроме объявления списка, где будут храниться числа и BufferedReader -а)
этого метода в try..catch.
Если пользователь ввёл какой-то текст, вместо ввода числа, то метод должен перехватить исключение и
вывести на экран все введенные числа в качестве результата.
Числа выводить с новой строки сохраняя порядок ввода.
*/

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;

public class Solution
{
    public static void main(String[] args) {
        try
        {
            readData();
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
    }

    public static void readData() throws IOException {
        ArrayList<Integer> listInt = new ArrayList<Integer>();
        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
        try
        {
            while(true)
            {
                listInt.add(Integer.parseInt(reader.readLine()));
            }
        }
        catch (Exception e)
        {
            for(Integer i : listInt) System.out.println(i);
        }
    }
}

Insert numerals while enter literals

Insert numerals while enter literals


/**
 * Copyright (C) 2014 android10.org. All rights reserved.
 * @author Fernando Cejas (the android10 coder)
 */
package com.fernandocejas.android10.gandalf.internal;

import com.fernandocejas.android10.gandalf.joinpoint.GandalfJoinPoint;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;

import static org.mockito.BDDMockito.given;
import static org.mockito.Matchers.anyObject;
import static org.mockito.Matchers.anyString;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.verify;

public class MessageManagerTest {

  private MessageManager messageManager;

  @Mock
  private MessageBuilder mockMessageBuilder;
  @Mock
  private DebugLog mockDebugLog;
  @Mock
  private GandalfJoinPoint mockGandalfJoinPoint;

  @Before
  public void setUp() {
    MockitoAnnotations.initMocks(this);
    messageManager = new MessageManager(mockMessageBuilder, mockDebugLog);
    setupMocks();
  }

  @After
  public void tearDown() {
    verifyLogcat();
  }

  private void setupMocks() {
    given(mockGandalfJoinPoint.getClassSimpleName()).willReturn(anyString());
  }

  private void verifyLogcat() {
    verify(mockDebugLog).log(anyString(), anyString());
  }

  @Test
  public void testTracingAspectEnterMessage() {
    messageManager.printTracingAspectEnterMessage(mockGandalfJoinPoint);

    verify(mockMessageBuilder).buildTracingAspectEnterMessage(mockGandalfJoinPoint);
  }

  @Test
  public void testTracingAspectExitMessage() {
    messageManager.printTracingAspectExitMessage(mockGandalfJoinPoint, anyObject(), anyString());

    verify(mockMessageBuilder).buildTracingAspectExitMessage(eq(mockGandalfJoinPoint), anyObject(), anyString());
  }
}

Add tests for MessageManager class.

Add tests for MessageManager class.


package removeDuplicatesFromSortedArray;

public class Solution {
    public int removeDuplicates(int[] nums) {
        int fast = 1, slow = 1;
        while(fast < nums.length){
            if(nums[fast] != nums[fast-1]){
                nums[slow++] = nums[fast];
            }
            fast++;
        }
        return slow;
    }
}

Remove Duplicates from Sorted Array -- easy in place, two pointer