/*
 *    GeoTools - The Open Source Java GIS Toolkit
 *    http://geotools.org
 *
 *    (C) 2012, Open Source Geospatial Foundation (OSGeo)
 *
 *    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;
 *    version 2.1 of the License.
 *
 *    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.
 */
package org.geotools.process.feature.gs;

import static org.junit.Assert.*;

import java.io.File;
import java.io.IOException;
import java.util.EnumSet;
import java.util.List;
import java.util.Set;

import org.geotools.data.DataStore;
import org.geotools.data.property.PropertyDataStore;
import org.geotools.data.simple.SimpleFeatureCollection;
import org.geotools.data.simple.SimpleFeatureSource;
import org.geotools.process.feature.gs.AggregateProcess.AggregationFunction;
import org.geotools.process.feature.gs.AggregateProcess.Results;
import org.geotools.process.feature.gs.ReShapeProcess.Definition;
import org.geotools.test.TestData;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.opengis.feature.simple.SimpleFeatureType;
import org.opengis.feature.type.AttributeDescriptor;
import org.opengis.filter.expression.PropertyName;

/**
 *
 *
 * @source $URL$
 */
public class ReShapeProcessTest {
    DataStore bugs;

    @Before
    public void setup() throws IOException {
        File file = TestData.file(this, null );
        bugs = new PropertyDataStore( file );
    }
    @After
    public void tearDown(){
        bugs.dispose();
    }

    @Test
    public void testDefinition() throws Exception {
        String definition = "the_geom=the_geom";
        List<Definition> def = ReShapeProcess.toDefinition( definition );

        assertEquals( 1, def.size() );

        assertEquals( "the_geom", def.get(0).name );
        assertTrue( def.get(0).expression instanceof PropertyName );
    }

    @Test
    public void testSum() throws Exception {
        SimpleFeatureSource source = bugs.getFeatureSource("bugsites");

        ReShapeProcess process = new ReShapeProcess();

        String definition = "the_geom=the_geom\nnumber=cat";
        SimpleFeatureCollection origional = source.getFeatures();
        SimpleFeatureCollection result = process.execute( origional, definition );

        assertEquals( origional.size(), result.size() );

        SimpleFeatureType schema = result.getSchema();
        AttributeDescriptor number = schema.getDescriptor("number");
        assertTrue( Long.class.isAssignableFrom( number.getType().getBinding() ) );

    }

}

Add a test case to confirm expected schema generated by ReShapeOperation; also added a couple of headers to the various test cases


package com.apptentive.android.sdk.module.rating.impl;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import com.apptentive.android.sdk.R;
import com.apptentive.android.sdk.module.rating.IRatingProvider;
import com.apptentive.android.sdk.module.rating.InsufficientRatingArgumentsException;

import java.util.Map;

/**
 * @author Sky Kelsey
 */
public class AmazonAppstoreRatingProvider implements IRatingProvider {
	public void startRating(Context context, Map<String, String> args) throws InsufficientRatingArgumentsException {
		if (!args.containsKey("package")) {
			throw new InsufficientRatingArgumentsException("Missing required argument 'package'");
		}
		context.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("amzn://apps/android?p=" + args.get("package"))));
	}

	public String activityNotFoundMessage(Context context) {
		return context.getString(R.string.apptentive_rating_provider_no_amazon_appstore);
	}
}

Check in an Amazon Appstore rating provider.


/*
 * 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.flink.runtime.io.network.netty;

import org.apache.flink.runtime.io.network.TaskEventDispatcher;
import org.apache.flink.runtime.io.network.netty.NettyMessage.ErrorResponse;
import org.apache.flink.runtime.io.network.netty.NettyMessage.PartitionRequest;
import org.apache.flink.runtime.io.network.partition.PartitionNotFoundException;
import org.apache.flink.runtime.io.network.partition.ResultPartitionID;
import org.apache.flink.runtime.io.network.partition.ResultPartitionManager;
import org.apache.flink.runtime.io.network.partition.consumer.InputChannelID;
import org.apache.flink.util.TestLogger;

import org.apache.flink.shaded.netty4.io.netty.channel.embedded.EmbeddedChannel;

import org.junit.Test;

import static org.hamcrest.Matchers.instanceOf;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertThat;

/**
 * Tests for {@link PartitionRequestServerHandler}.
 */
public class PartitionRequestServerHandlerTest extends TestLogger {

	/**
	 * Tests that {@link PartitionRequestServerHandler} responds {@link ErrorResponse} with wrapped
	 * {@link PartitionNotFoundException} after receiving invalid {@link PartitionRequest}.
	 */
	@Test
	public void testResponsePartitionNotFoundException() {
		final PartitionRequestServerHandler serverHandler = new PartitionRequestServerHandler(
			new ResultPartitionManager(),
			new TaskEventDispatcher(),
			new PartitionRequestQueue(),
			true);
		final EmbeddedChannel channel = new EmbeddedChannel(serverHandler);
		final ResultPartitionID partitionId = new ResultPartitionID();

		// Write the message of partition request to server
		channel.writeInbound(new PartitionRequest(partitionId, 0, new InputChannelID(), 2));
		channel.runPendingTasks();

		// Read the response message after handling partition request
		final Object msg = channel.readOutbound();
		assertThat(msg, instanceOf(ErrorResponse.class));

		final ErrorResponse err = (ErrorResponse) msg;
		assertThat(err.cause, instanceOf(PartitionNotFoundException.class));

		final ResultPartitionID actualPartitionId = ((PartitionNotFoundException) err.cause).getPartitionId();
		assertThat(partitionId, is(actualPartitionId));
	}
}

Add new unit tests for PartitionRequestServerHandler


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

import org.junit.Test;
import org.junit.runner.RunWith;

import org.springframework.boot.context.embedded.LocalServerPort;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.test.context.junit4.SpringRunner;

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

/**
 * @author Dave Syer
 *
 */
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
public class SampleApplicationTests {

	@LocalServerPort
	private int port;

	@Test
	public void words() {
		assertThat(new TestRestTemplate()
				.getForObject("http://localhost:" + port + "/words", String.class))
						.isEqualTo("{\"value\":\"foo\"}{\"value\":\"bar\"}");
	}

	@Test
	public void uppercase() {
		assertThat(new TestRestTemplate().postForObject(
				"http://localhost:" + port + "/uppercase", "{\"value\":\"foo\"}",
				String.class)).isEqualTo("{\"value\":\"FOO\"}");
	}

}

Add integration tests to the pojo sample


package db.migration;

import org.flywaydb.core.api.migration.spring.SpringJdbcMigration;
import org.springframework.jdbc.core.JdbcTemplate;

/**
 * Created by emma on 06/04/2016.
 *
 * @author emma *         <p> Copy OR and DESCRIPTION values to BETA_NUM, BETA_UNIT and BETA_DIRECTION in ASSOCIATION
 *         table
 */
public class V2_1_2_014__Migrate_or_to_beta_for_description_with_brackets implements SpringJdbcMigration {

    // Query to find beta associations with a description with a bracket.
    private static final String SELECT_ASSOCIATIONS =
            "SELECT ID, OR_PER_COPY_NUM, DESCRIPTION FROM ASSOCIATION \n" +
                    "WHERE OR_TYPE = 0 \n" +
                    "AND DESCRIPTION IS NOT NULL  \n" +
                    "AND OR_PER_COPY_NUM IS NOT NULL \n" +
                    "AND DESCRIPTION LIKE '(unit%'\n";

    private static final String UPDATE_ASSOCIATION =
            "UPDATE ASSOCIATION SET BETA_NUM = ?, BETA_UNIT = ? , BETA_DIRECTION= ? , OR_PER_COPY_NUM=?, DESCRIPTION=? WHERE ID = ?";

    @Override
    public void migrate(JdbcTemplate jdbcTemplate) throws Exception {

        jdbcTemplate.query(SELECT_ASSOCIATIONS, (resultSet, i) -> {
            Long id = resultSet.getLong(1);
            float betaNum = resultSet.getFloat(2);
            String description = resultSet.getString(3).trim();

            // Split description
            int lastIndexOfSpace = description.lastIndexOf(" ");
            String unit = description.substring(1, lastIndexOfSpace);
            String direction = description.substring(lastIndexOfSpace, description.length() - 1);

            // Run update
            jdbcTemplate.update(UPDATE_ASSOCIATION, betaNum, unit.trim(), direction.trim(), null, null, id);
            return null;
        });
    }
}

Migrate betas with brackets in description


/*
 * Copyright (C) 2010 reuillon
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 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 General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package org.openmole.plugin.environment.glite;

/**
 *
 * @author reuillon
 */
public enum GliteAttributes {

    OS_RELEASE("other.GlueHostOperatingSystemRelease");

    final String value;

    private GliteAttributes(String value) {
        this.value = value;
    }

}

Add missing file in previous commit.


package hydrograph.engine.transformation.standardfunctions;

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

/**
 * Created by shivarajn on 3/15/2017.
 */
public class SpecialFunctionsTest {

    @Test
    public void itShouldValidateDecode() {

        String outputCase1 = null, outputCase2 = null, outputCase3 = null, outputCase4 = null, outputCase5 = null;
        try {
            outputCase1 = SpecialFunctions.decode("red", "red", "Abort", "green", "Success", "Status Unknown");
            outputCase2 = SpecialFunctions.decode("purple", "red", "Abort", "green", "Success", "Status Unknown");
            outputCase3 = SpecialFunctions.decode(null, "red", "Abort", "green", "Success", "Status Unknown");
            outputCase4 = SpecialFunctions.decode("red", null);
            outputCase5 = SpecialFunctions.decode("yellow", "red", "Abort", "green", "Success", "yellow", "In Progress", "Status Unknown");
        } catch (Exception exception) {
            exception.printStackTrace();
        }
        Assert.assertEquals("Abort", outputCase1);
        Assert.assertEquals("Status Unknown", outputCase2);
        Assert.assertEquals("Status Unknown", outputCase3);
        Assert.assertNull(outputCase4);
        Assert.assertEquals("In Progress", outputCase5);
    }
}

Test cases for SpecialFunctions class "decode" method


package com.b2international.snowowl.snomed.api.rest.versioning;

import static com.b2international.snowowl.test.commons.rest.RestExtensions.givenAuthenticatedRequest;

import java.util.Map;

import org.junit.Test;

import com.b2international.snowowl.snomed.api.rest.AbstractSnomedApiTest;
import com.google.common.collect.ImmutableMap;
import com.jayway.restassured.http.ContentType;
import com.jayway.restassured.response.Response;
import com.jayway.restassured.specification.RequestSpecification;

public class SnomedVersioningApiTest extends AbstractSnomedApiTest {

	@Test
	public void getNonExistentVersion() {
		assertVersionGetStatus("nonexistent", 404);
	}

	@Test
	public void createVersionWithoutDescription() {
		assertVersionPostStatus("", "20150201", 400);
	}

	@Test
	public void createVersionWithNonLatestEffectiveDate() {
		assertVersionPostStatus("sct-v1", "20150101", 400);
	}

	@Test
	public void createVersion() {
		assertVersionPostStatus("sct-v2", "20150201", 201);
		assertVersionGetStatus("sct-v2", 200);
	}

	@Test
	public void createVersionWithSameNameAsBranch() {
		assertBranchCanBeCreated("MAIN", "sct-v3");
		assertVersionPostStatus("sct-v2", "20150202", 409);
	}

	private void assertVersionGetStatus(String version, int status) {
		givenAuthenticatedRequest(API)
		.when()
			.get("/codesystems/SNOMEDCT/versions/{id}", version)
		.then()
		.assertThat()
			.statusCode(status);
	}

	private void assertVersionPostStatus(String version, String effectiveDate, int status) {
		whenCreatingVersion(givenAuthenticatedRequest(API), version, effectiveDate)
		.then()
		.assertThat()
			.statusCode(status);
	}

	private Response whenCreatingVersion(RequestSpecification request, String version, String effectiveDate) {
		Map<?, ?> requestBody = ImmutableMap.of(
			"version", version,
			"description", version,
			"effectiveDate", effectiveDate
		);

		return request
		.and()
			.contentType(ContentType.JSON)
		.and()
			.body(requestBody)
		.when()
			.post("/codesystems/SNOMEDCT/versions");
	}

}

Add replacement test cases for versioning API


package globals;

import util.KawaWrap;

public class WMath extends Globals {
	/**
	 * Add methods related to (random n)
	 *
	 * @param kawa The interpreter to add them to.
	 * @throws Throwable If anything breaks while adding them.
	 */
	@Override
	public void addMethods(KawaWrap kawa) throws Throwable {
    	kawa.eval("(define (sub1 n) (- n 1))");
    	kawa.eval("(define (add1 n) (+ n 1))");
	}
}

package globals;

import gnu.mapping.Procedure1;
import gnu.math.IntNum;
import util.KawaWrap;

public class WMath extends Globals {
	/**
	 * Add methods related to (random n)
	 *
	 * @param kawa The interpreter to add them to.
	 * @throws Throwable If anything breaks while adding them.
	 */
	@Override
	public void addMethods(KawaWrap kawa) throws Throwable {
    	kawa.eval("(define (sub1 n) (- n 1))");
    	kawa.eval("(define (add1 n) (+ n 1))");

    	kawa.bind(new Procedure1("even?") {
			@Override
			public Object apply1(Object arg1) throws Throwable {
				if (!(arg1 instanceof IntNum))
					throw new IllegalArgumentException("Error in even?, expected integer as first argument, got '" + KawaWrap.formatObject(arg1) + "'.");

				return !((IntNum) arg1).isOdd();
			}
    	});

    	kawa.bind(new Procedure1("odd?") {
			@Override
			public Object apply1(Object arg1) throws Throwable {
				if (!(arg1 instanceof IntNum))
					throw new IllegalArgumentException("Error in odd?, expected integer as first argument, got '" + KawaWrap.formatObject(arg1) + "'.");

				return ((IntNum) arg1).isOdd();
			}
    	});
	}
}

Fix for even? and odd?


package db;

public class DBUtils {

	private static final String DB_NAME = "fmps.db";
	public static final String TABLE_FMPS_MAIN = "fmps_main";
	public static final String DLC = ", ";

	// Columns
	public static final String LAST_NAME = "lastname";
	public static final String FIRST_NAME = "firstname";
	public static final String MIDDLE_NAME = "middlename";
	public static final String ST1_PROGRESS = "st1_progress";
	public static final String ST2_PROGRESS = "st2_progress";
	public static final String ST3_PROGRESS = "st3_progress";
	public static final String ST1_FE = "st1_fe";
	public static final String ST1_C = "st1_c";
	public static final String ST1_MN = "st1_mn";
	public static final String ST1_P_ENV = "st1_p_env";
	public static final String ST1_F_SURF_WELD_AREA = "st1_f_surface_area";
	public static final String ST1_MP_WEIGHT_MOLTEN_METAL = "st1_mp_weight_molten_metal";
	public static final String ST1_TEMPERATURE = "st1_temperature";
	public static final String ST1_TIME = "st1_time";
	public static final String ST2_ARGON = "st2_argon";
	public static final String ST2_CO2 = "st2_co2";
	public static final String ST2_O2 = "st2_o2";
	public static final String ST2_CO = "st2_co";
	public static final String ST2_O = "st2_o";
	public static final String ST2_C = "st2_c";
	public static final String ST2_TEMPERATURE = "st2_temperature";
	public static final String ST3_CO_PARTIAL_PRESSURE = "st3_co_partial_pressure";
	public static final String ST3_O_PARTIAL_PRESSURE = "st3_o_partial_pressure";
	public static final String ST3_O_DISSOLVE = "st3_dissolve";
	public static final String ST3_ATM_PRESSURE = "st3_atm_pressure";
	public static final String ST3_TEMPERATURE = "st3_temperature";

}

Add util class for work with db. Add db columns, main table name to this class.


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

package algorithm.boj;

import java.io.*;

/**
 * Created by haeun on 2017-09-25
 * Site       : https://www.acmicpc.net/problem/10817
 */

public class Boj10817 {

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

}

Solve No.10817 from Baekjoon Online Judge


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

public class Rotation
{
	public static void main(String[] args)
	{
		Scanner sc=new Scanner(System.in);
		System.out.println("Enter 1st string:");
		String s1=sc.nextLine();
		System.out.println("Enter 2nd string:");
		String s2=sc.nextLine();

		Rotation obj=new Rotation();
		boolean result=obj.string_rotation(s1,s2);
		if(result)
			System.out.println("String "+s1+" is a rotation of "+s2);
		else
			System.out.println("String "+s1+" is not a rotation of "+s2);

	}

	public boolean string_rotation(String s1, String s2)
	{
		char[] c1=s1.toCharArray();
		char[] c2=s2.toCharArray();
		Arrays.sort(c1);
		Arrays.sort(c2);
		String s3=new String(c1);
		String s4=new String(c2);
		if(!s3.equals(s4))
			return false;
		else
		{
			String s1s1= s1 + s1;		//s1=xy..s2=yx..s1s1=xyxy
			if(s1s1.contains(s2))
				return true;
			else
				return false;
		}
	}
}

Check if one string is rotation of the other


package util;

import java.util.Map;
import java.util.Set;

import org.joda.time.DateTime;

import schedulable.Activity;
import schedulable.Schedulable;
import schedulable.Transportation;
import time.Timeline;

public class Debugger {
	public static void printSchedulables(Timeline timeline) {
		Set<Map.Entry<DateTime, Schedulable>> entries = timeline.getSchedule()
				.entrySet();
		for (Map.Entry<DateTime, Schedulable> entry : entries) {
			System.out.print(entry.getKey().getMillis() + " - "
					+ Util.getEndTime(entry).getMillis() + ": ");
			Schedulable value = entry.getValue();
			if (value instanceof Transportation) {
				System.out.println("transportation");
			} else {
				System.out.println(((Activity) value).title);
			}

		}
	}
}

Add debugger class to print things out to console


package com.vmware.vim25.mo.samples;

import java.net.MalformedURLException;
import java.net.URL;
import java.rmi.RemoteException;

import com.vmware.vim25.mo.ServiceInstance;

public class SampleUtil {

	public static ServiceInstance createServiceInstance() throws RemoteException, MalformedURLException {
		return new ServiceInstance(new URL("https://10.141.72.223/sdk"), "root", "vmware", true);
	}

}

package com.vmware.vim25.mo.samples;

import java.net.MalformedURLException;
import java.net.URL;
import java.rmi.RemoteException;

import com.vmware.vim25.mo.ServiceInstance;

public class SampleUtil {

	public static ServiceInstance createServiceInstance() throws RemoteException, MalformedURLException {
	   ServiceInstance si = new ServiceInstance(new URL("https://10.141.72.223/sdk"), "root", "vmware", true);
	   si.getSessionManager().setLocale("zh-CN"); // set locale for the content of all API result.
	   return si;
	}

}

Set locale for the content of all API result


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

import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
import java.util.Properties;

/** Set various version values to the one of this program's first argument. */
public class Version {

  private static final Path PROPERTIES = Path.of(".bach/bach.properties");

  public static void main(String... args) throws Exception {
    if (args.length == 0) {
      var properties = new Properties();
      try (var reader = Files.newBufferedReader(PROPERTIES)) {
        properties.load(reader);
      }
      var version = properties.getProperty("version");
      if (version == null) throw new Error("Key 'version' not found in: " + PROPERTIES.toUri());
      System.out.println(version);
      return;
    }

    if (args.length > 1) {
      throw new Error("Exactly one argument, the new version, expected! args=" + List.of(args));
    }
    var version = args[0];
    var readmeMd = Path.of("README.md");
    var mavenPom = Path.of("src/de.sormuras.bach/main/maven/pom.xml");
    var bachJava = Path.of("src/bach/Bach.java");
    // var mergedBach = Path.of("src/bach/MergedBach.java");

    sed(PROPERTIES, "version=.+", "version=" + version);
    sed(readmeMd, "# Bach.java .+ -", "# Bach.java " + version + " -");
    sed(mavenPom, "<version>.+</version>", "<version>" + version + "</version>");
    sed(bachJava, "String VERSION = \".+\";", "String VERSION = \"" + version + "\";");
    // mergedBach.toFile().setWritable(true);
    // sed(mergedBach, "String VERSION = \".+\";", "String VERSION = \"" + version + "\";");
    // mergedBach.toFile().setWritable(false);
  }

  private static void sed(Path path, String regex, String replacement) throws Exception {
    Files.writeString(path, Files.readString(path).replaceAll(regex, replacement));
  }
}

Introduce version getter and setter program


package com.example.warner;

/**
 * Simple implementation of the Kalman Filter for 1D data.
 * Originally written in JavaScript by Wouter Bulten
 *
 * Now rewritten into Java
 * 2017
 *
 * @license MIT License
 *
 * @author Andreas Eppler
 *
 * @see https://github.com/wouterbulten/kalmanjs
 *
 */
public class KalmanFilter {

    private double A = 1;
    private double B = 0;
    private double C = 1;

    private double R;
    private double Q;

    private double cov = Double.NaN;
    private double x = Double.NaN;

    /**
     * Constructor
     *
     * @param R Process noise
     * @param Q Measurement noise
     * @param A State vector
     * @param B Control vector
     * @param C Measurement vector
     */

    public KalmanFilter(double R, double Q, double A, double B , double C){
        this.R = R;
        this.Q = Q;

        this.A = A;
        this.B = B;
        this.C = C;

        this.cov = Double.NaN;
        this.x = Double.NaN; // estimated signal without noise
    }

/*
    public KalmanFilter(double R, double Q){
        this.R = R;
        this.Q = Q;

    }
*/

    /**
     * Filters a measurement
     *
     * @param measurement The measurement value to be filtered
     * @param u The controlled input value
     * @return The filtered value
     */
    public double filter(double measurement, double u){

        if (Double.isNaN(this.x)) {
            this.x = (1 / this.C) * measurement;
            this.cov = (1 / this.C) * this.Q * (1 / this.C);
        }else {
            double predX = (this.A * this.x) + (this.B * u);
            double predCov = ((this.A * this.cov) * this.A) + this.R;

            // Kalman gain
            double K = predCov * this.C * (1 / ((this.C * predCov * this.C) + this.Q));

            // Correction
            this.x = predX + K * (measurement - (this.C * predX));
            this.cov = predCov - (K * this.C * predCov);
        }
        return this.x;
    }

    /**
     *
     * @return The last measurement fed into the filter
     */
    public double lastMeasurement(){
        return this.x;
    }

    /**
     * Sets measurement noise
     *
     * @param noise The new measurement noise
     */
    public void setMeasurementNoise(double noise){
        this.Q = noise;
    }

    /**
     * Sets process noise
     *
     * @param noise The new process noise
     */
    public void setProcessNoise(double noise){
        this.R = noise;
    }
}

Add a KalmanFilter for Java that takes input parameter


/*
 Copyright (C) 2004 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.DatabaseType;
import org.ensembl.healthcheck.testcase.SingleDatabaseTestCase;

/**
 * Healthcheck for the dna table.
 * Should be empty in an est database
 */

public class DNAEmpty extends SingleDatabaseTestCase {

    /**
     * Check the assembly_exception table.
     */
    public DNAEmpty() {
        addToGroup("post_genebuild");
        addToGroup("release");
        setDescription("Check that dna table is empty");
    }

    /**
     * Check the data in the assembly_exception table. Note referential
     * integrity checks are done in CoreForeignKeys.
     *
     * @param dbre
     *          The database to use.
     * @return Result.
     */
    public boolean run(DatabaseRegistryEntry dbre) {

        boolean result = true;

        Connection con = dbre.getConnection();

        // check that seq_region_end > seq_region_start
        int rows = getRowCount(con, "SELECT COUNT(*) FROM dna");
        if (rows > 0) {
            result = false;
            ReportManager.problem(this, con, "dna table contains " + rows
                    + " - it should be empty");
        }

        if (result) {
            ReportManager.correct(this, con, "dna table is empty");
        }

        return result;

    }

    /**
     * This applies to all core schema databases apart from 'core'
     */
    public void types() {

        removeAppliesToType(DatabaseType.CORE);

    }

} // DNAEmpty

Test to check dna tables in non core, core schema dbs (eg. est and estgene) are empty (should be using core db as reference).


package org.nwapw.abacus.tests;

import org.junit.Assert;
import org.junit.BeforeClass;
import org.nwapw.abacus.Abacus;
import org.nwapw.abacus.number.NumberInterface;
import org.nwapw.abacus.plugin.StandardPlugin;
import org.nwapw.abacus.tree.TreeNode;

public class CalculationTests {

    private static Abacus abacus = new Abacus();

    @BeforeClass
    public static void prepareTests(){
        abacus.getPluginManager().addInstantiated(new StandardPlugin(abacus.getPluginManager()));
        abacus.getPluginManager().load();
    }

    private void testOutput(String input, String parseOutput, String output){
        TreeNode parsedTree = abacus.parseString(input);
        Assert.assertNotNull(parsedTree);
        Assert.assertEquals(parsedTree.toString(), parseOutput);
        NumberInterface result = abacus.evaluateTree(parsedTree);
        Assert.assertNotNull(result);
        Assert.assertTrue(result.toString().startsWith(output));
    }

    private void testEvalError(String input, String parseOutput){
        TreeNode parsedTree = abacus.parseString(input);
        Assert.assertNotNull(parsedTree);
        Assert.assertEquals(parsedTree.toString(), parseOutput);
        Assert.assertNull(abacus.evaluateTree(parsedTree));
    }

}

Write two functions to help test the code.


/**
 * @file JSONEncodeDemo.java
 * @author Valery Samovich
 * @version 1.0.0
 * @date 11/19/2014
 *
 * Following example to encode JSON Object using Java JSONObject with is
 * subclass of java.util.HashMap.
 */

package com.valerysamovich.java.advanced.json;

import org.json.simple.JSONObject;

public class JSONEncodeDemo {

    public static void main(String[] args) {

        JSONObject obj = new JSONObject();

        obj.put("name", "foo");
        obj.put("num", new Integer(100));
        obj.put("balance", new Double(1000.21));
        obj.put("is_vip", new Boolean(true));

        System.out.print(obj);
    }
}

Add Encoding JSON in Java Example


package se.kth.csc.controller;

import org.junit.Before;
import org.junit.Test;
import org.springframework.security.core.context.SecurityContextHolder;

import se.kth.csc.model.Account;
import se.kth.csc.persist.AccountStore;

import java.security.Principal;

import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.atLeastOnce;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;

public class HomeControllerTest {

  // System under test (SUT):
  private HomeController homeController;

  // Dependencies of this unit
  private AccountStore accountStore;

  @Before
  public void setUp() throws Exception {
    // Mock dependencies
    accountStore = mock(AccountStore.class);

    // Create SUT
    homeController = new HomeController(accountStore);
  }

  @Test
  public void testMakeMeAdmin() {
    // Set up expected behavior of mocks
    Principal principal = mock(Principal.class);
    when(principal.getName()).thenReturn("testuser");

    Account account = mock(Account.class);
    when(accountStore.fetchAccountWithPrincipalName("testuser")).thenReturn(account);

    // Run the system under test
    String result = homeController.makeMeAdmin(principal);

    // Verify that interactions with mocks happened
    verify(account, atLeastOnce()).setAdmin(true);

    // Verify actual returned results
    assertEquals("redirect:/debug", result);
  }
}

Add example test to show how it's done


package Pair;

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

import static org.junit.Assert.*;

public class PairTest {

    Pair pair;

    @Before
    public void setUp() throws Exception {
        pair = new Pair<String, String>("Name", "Ogunde Kehinde");
    }

    @After
    public void tearDown() throws Exception {

    }

    @Test
    public void testGetKey() throws Exception {
        assertEquals(pair.getKey(), "Name");
    }

    @Test
    public void testGetValue() throws Exception {
        assertEquals(pair.getValue(), "Ogunde Kehinde");
    }
}

Create Test for Pair Class


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

// https://www.hackerrank.com/challenges/ctci-ransom-note/problem
public class RansomNote {

    private static final String NO = "No";
    private static final String YES = "Yes";
    private static final String SPACE = " ";

    private static String[] readWords(BufferedReader reader) throws IOException {
        return reader.readLine().split(SPACE);
    }

    private static Map<String, Integer> getFrequencies(String[] words) {
        Map<String, Integer> frequencies = new HashMap<>();
        for (String word : words) {
            int frequency = frequencies.getOrDefault(word, 0);
            frequencies.put(word, frequency + 1);
        }
        return frequencies;
    }

    public static void main(String[] args) throws IOException {
        try (BufferedReader reader = new BufferedReader(new InputStreamReader(System.in))) {
            reader.readLine(); // Skip first line.
            String[] magazineWords = readWords(reader);
            String[] noteWords = readWords(reader);
            if (noteWords.length > magazineWords.length) {
                System.out.println(NO);
                return;
            }
            Map<String, Integer> magazineFrequencies = getFrequencies(magazineWords);
            Map<String, Integer> noteFrequencies = getFrequencies(noteWords);
            for (String noteWord : noteFrequencies.keySet()) {
                int noteFrequency = noteFrequencies.get(noteWord);
                int magazineFrequency = magazineFrequencies.getOrDefault(noteWord, 0);
                if (noteFrequency > magazineFrequency) {
                    System.out.println(NO);
                    return;
                }
            }
            System.out.println(YES);
        }
    }
}

Add solution for Ransom note problem.


/**
 * Twist in the Tale 2.3 from the OCA Java SE 7 book by Mala Gupta (Manning Publications)
 * Created by Josef on 12/17/13.
 */
public class TwistInTheTale2_3 {
    public static void main (String[] args) {
        int a = 10;
        a = ++a + a + --a - --a + a++;
        System.out.println(a);
    }
}

Add code for Twist in the Tale 2.3 - Commented out bad code from 2.2 so that code can run.


package age;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;

public class CSVReader {

	public static void main(String[] args){

	}

	public static List<String> readCSV(Path path){
		List<String> content = new ArrayList<>();
		try{
			Files.lines(path).forEach( (String line) -> {
				content.add(line);
			});
		} catch (IOException e) {
			e.printStackTrace();
		} finally {

		}
		return null;
	}

}

Add helper class for reading CSV files


package com.trit.security.utils.ws;

import org.junit.Test;

public class WsResourceTest {

    @Test(expected = IllegalArgumentException.class)
    public void testNullResource() {
        new WsResource(null);
    }

    @Test(expected = IllegalArgumentException.class)
    public void testNullResourceAndNullId() {
        new WsResource(null, null);
    }

    @Test(expected = IllegalArgumentException.class)
    public void testNullId() {
        new WsResource("users", null);
    }

}

Test class for WsResource class


/**
 * Created by Josef on 12/20/13.
 */
public class TwistInTheTale2_4 {
    public static void main (String[] args) {
        int a = 10;
        int b = 20;
        int c = 40;

//        System.out.println(a++ > 10 || ++b < 30);
        System.out.println(a++ > 10);
        System.out.println(++b < 30);
        System.out.println(a > 90 && ++b < 30);
        System.out.println(!(c > 20) && a == 10);
        System.out.println(a >= 99 || a <= 33 && b == 10);
        System.out.println(a >= 99 && a <= 33 || b == 10);
    }
}

Add code for Twist in the Tale 2.4


/**
 * Copyright (c) 2011, Jilles van Gurp
 *
 * 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 org.jsonj;

import static org.jsonj.tools.JsonBuilder.array;
import static org.jsonj.tools.JsonBuilder.nullValue;
import static org.jsonj.tools.JsonBuilder.object;
import static org.jsonj.tools.JsonBuilder.primitive;
import static org.jsonj.tools.JsonSerializer.serialize;
import static org.jsonj.tools.JsonSerializer.write;

import java.io.IOException;

import org.jsonj.tools.JsonParser;
import org.testng.annotations.Test;

/**
 * Not really a test but a nice place to show off some how to use this.
 */
@Test
public class ShowOffTheFramework {

	/** this could be a singleton or a spring injected object, threadsafe of course. */
	private final JsonParser jsonParser = new JsonParser();;

	public void whatCanThisBabyDo() throws IOException {
		JsonObject object = object()
			.put("its", "just a hash map")
			.put("and", array(primitive("adding"), primitive("stuff"), object().put("is", "easy").get(), array("another array")))
			.put("numbers", 42)
			.put("including_this_one", 42.0)
			.put("booleanstoo", true)
			.put("nulls_if_you_insist", nullValue())
			.put("arrays_are_easy", array("1", "2", "etc", "varargs are nice")).get();

		// serialize like this
		String serialized = serialize(object);

		System.out.println(serialized);

		// parse it
		JsonElement json = jsonParser.parse(serialized);

		// and write it straight to some stream
		write(System.out, json, false);

		// or pretty print it like this
		System.out.println("\n" + serialize(json, true));

	}
}

Add test to show off the features of this framework.


import org.svetovid.io.StandardSvetovidErrorWriter;
import org.svetovid.io.StandardSvetovidReader;
import org.svetovid.io.StandardSvetovidWriter;
import org.svetovid.io.SvetovidReader;
import org.svetovid.io.SvetovidWriter;

public class Svetovid {

    public static StandardSvetovidReader in = org.svetovid.io.Svetovid.in;
    public static StandardSvetovidWriter out = org.svetovid.io.Svetovid.out;
    public static StandardSvetovidErrorWriter err = org.svetovid.io.Svetovid.err;

    public static SvetovidReader in(String source) {
        return org.svetovid.io.Svetovid.in(source);
    }

    public static SvetovidWriter out(String source) {
        return org.svetovid.io.Svetovid.out(source);
    }

    public static SvetovidWriter append(String source) {
        return org.svetovid.io.Svetovid.append(source);
    }

    public static SvetovidWriter out(String source, boolean append) {
        return org.svetovid.io.Svetovid.out(source, append);
    }
}

Add shorthand access for default package


package galileo.graph;

import galileo.dataset.feature.Feature;

import java.util.NavigableSet;
import java.util.TreeSet;

/**
 * Represents the buckets described by "Tick Marks" in the system.  For example,
 * a TickHash with values 0, 10, 20, and 30 would output "30" for an input of
 * 33, "0" for an input of 5, etc.  It allows incoming samples to be placed into
 * coarser-grained buckets.  Additionally, the first and last ticks stretch off
 * to infinity; Feature-specific constraints on the tick marks should be managed
 * by classes using TickHash.
 *
 * @author malensek
 */
public class TickHash {

    private NavigableSet<Feature> tickSet = new TreeSet<>();
    private Feature low;
    private Feature high;

    public TickHash(Feature... features) {
        for (Feature f : features) {
            addTick(f);
        }
    }

    public void addTick(Feature feature) {
        if (low == null || feature.less(low)) {
            low = feature;
        }

        if (high == null || feature.greater(high)) {
            high = feature;
        }

        tickSet.add(feature);
    }

    public NavigableSet<Feature> getTicks() {
        return tickSet;
    }

    public Feature getBucket(Feature feature) {
        if (feature.greater(high)) {
            return high;
        }

        if (feature.less(low)) {
            return low;
        }

        return tickSet.floor(feature);
    }

    @Override
    public String toString() {
        String str = "";
        for (Feature f : tickSet) {
            str += f.dataToString() + " - ";
        }
        return str.substring(0, str.length() - 3);
    }
}

Add managing class for tick mark generation


package leetcode.powx_n;

public class Solution {
    public double pow(double x, long n) {
    	if(x == 0){
    		if(n == 0) return Double.NaN;
    		else return 0;
    	}else{
    		if(n < 0){
    			return 1 / pow(x, -n);
    		}else if(n > 0){
    			if(n % 2 == 0){
    				double tmp = pow(x, n / 2);
    				return tmp * tmp;
    			}else{
    				double tmp = pow(x, n - 1);
    				return tmp * x;
    			}
    		}else{
    			return 1;
    		}
    	}
    }
    public double pow(double x, int n){
    	return pow(x, (long)n);
    }

    public static void main(String[] args){
    	double x = 1.;
    	long n = -2147483648;
    	System.err.println(new Solution().pow(x, n));
    }
}

Add java solution for 50. Pow(x, n)


package org.cyclops.cyclopscore.helper;

import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.BlockPos;
import net.minecraft.world.IBlockAccess;

/**
 * Contains helper methods for various tile entity specific things.
 * @author rubensworks
 */
public final class TileHelpers {

    /**
     * Safely cast a tile entity.
     * @param world The world.
     * @param pos The position of the block providing the tile entity.
     * @param <T> The type of tile to cast at.
     * @return The tile entity or null.
     */
    public static <T extends TileEntity> T getSafeTile(IBlockAccess world, BlockPos pos) {
        TileEntity tile = world.getTileEntity(pos);
        if(tile != null) {
            try {
                return (T) world.getTileEntity(pos);
            } catch (ClassCastException e) {}
        }
        return null;
    }

}

Add convenience method to safely autocast Tile Entities


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

package com.google.sps.servlets;

import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.PreparedQuery;
import com.google.appengine.api.datastore.Query;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/authstatus")
public class AuthStatus extends HttpServlet {

  @Override
  public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
    UserService userService = UserServiceFactory.getUserService();
    if (!userService.isUserLoggedIn()) {
      response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
    }
  }

@Override
  public void doHead(HttpServletRequest request, HttpServletResponse response) throws IOException {
    UserService userService = UserServiceFactory.getUserService();
    if (!userService.isUserLoggedIn()) {
      response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
    }
  }
}

Add auth status java servlet.


package org.zwobble.mammoth.tests.conversion;

import org.junit.jupiter.api.Test;
import org.zwobble.mammoth.internal.conversion.RawText;
import org.zwobble.mammoth.internal.documents.Break;
import org.zwobble.mammoth.internal.documents.Document;
import org.zwobble.mammoth.internal.documents.DocumentElement;
import org.zwobble.mammoth.internal.documents.Text;

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
import static org.zwobble.mammoth.tests.documents.DocumentElementMakers.*;

public class RawTextTests {
    @Test
    public void textElementIsConvertedToTextContent() {
        DocumentElement element = new Text("Hello.");

        String result = RawText.extractRawText(element);

        assertThat(result, equalTo("Hello."));
    }

    @Test
    public void paragraphsAreTerminatedWithNewlines() {
        DocumentElement element = paragraph(
            withChildren(new Text("Hello "), new Text("world."))
        );

        String result = RawText.extractRawText(element);

        assertThat(result, equalTo("Hello world.\n\n"));
    }

    @Test
    public void childrenAreRecursivelyConvertedToText() {
        Document element = document(
            withChildren(
                paragraph(
                    withChildren(new Text("Hello "), new Text("world."))
                )
            )
        );

        String result = RawText.extractRawText(element);

        assertThat(result, equalTo("Hello world.\n\n"));
    }

    @Test
    public void nonTextElementWithoutChildrenIsConvertedToEmptyString() {
        DocumentElement element = Break.LINE_BREAK;

        String result = RawText.extractRawText(element);

        assertThat(result, equalTo(""));
    }
}

Add tests for raw text extraction


package com.kgp.imaging;

import java.awt.RenderingHints;
import java.awt.geom.Point2D;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import java.awt.image.BufferedImageOp;
import java.awt.image.ColorModel;
import java.awt.image.Raster;
import java.awt.image.WritableRaster;

public class FlashOp implements BufferedImageOp {

	public float[] color;

	public FlashOp(float[] color){
		this.color = color;
	}

	@Override
	public BufferedImage createCompatibleDestImage(BufferedImage arg0,
			ColorModel arg1) {
		return null;
	}

	@Override
	public BufferedImage filter(BufferedImage arg0, BufferedImage arg1) {
		if (arg1 == null)
			arg1 = new BufferedImage(arg0.getWidth(), arg0.getHeight(), BufferedImage.TYPE_INT_ARGB);

		Raster r = arg0.getData();
		WritableRaster w = arg1.getRaster();
		for (int x = 0; x < arg0.getWidth(); x++)
			for (int y = 0; y < arg0.getHeight(); y++)
			{
				int[] f = new int[4];
				r.getPixel(x, y, f);
				f[0] *= color[0];
				f[1] *= color[1];
				f[2] *= color[2];

				w.setPixel(x, y, f);
			}

		return arg1;
	}

	@Override
	public Rectangle2D getBounds2D(BufferedImage arg0) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public Point2D getPoint2D(Point2D arg0, Point2D arg1) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public RenderingHints getRenderingHints() {
		// TODO Auto-generated method stub
		return null;
	}

}

Create BufferedImageOp for flexible color rescale


package org.verapdf.metadata.fixer.impl.pb;

import org.apache.pdfbox.pdmodel.PDDocument;
import org.verapdf.metadata.fixer.entity.Metadata;
import org.verapdf.metadata.fixer.entity.PDFDocument;
import org.verapdf.metadata.fixer.impl.pb.model.PDFDocumentImpl;
import org.verapdf.metadata.fixer.utils.FixerConfig;
import org.verapdf.metadata.fixer.utils.parser.ProcessedObjectsParser;
import org.verapdf.metadata.fixer.utils.parser.XMLProcessedObjectsParser;
import org.verapdf.validation.profile.model.ValidationProfile;
import org.verapdf.validation.report.model.Result;
import org.verapdf.validation.report.model.ValidationInfo;

/**
 * @author Evgeniy Muravitskiy
 */
public class FixerConfigImpl implements FixerConfig {

	private final PDFDocument document;
	private final ValidationInfo validationResult;
	private final ProcessedObjectsParser parser;

	public FixerConfigImpl(PDDocument document, ValidationInfo validationResult) {
		this(document, validationResult, XMLProcessedObjectsParser.getInstance());
	}

	public FixerConfigImpl(PDDocument document, ValidationInfo validationResult, ProcessedObjectsParser parser) {
		if (document == null) {
			throw new NullPointerException("Document can not be null");
		}
		if (validationResult == null) {
			throw new NullPointerException("Validation infor can not be null.");
		}
		if (parser == null) {
			throw new NullPointerException("Parser can not be null.");
		}
		this.document = new PDFDocumentImpl(document);
		this.validationResult = validationResult;
		this.parser = parser;
	}

	@Override
	public Result getValidationResult() {
		return validationResult != null ? validationResult.getResult() : null;
	}

	@Override
	public ValidationProfile getValidationProfile() {
		return validationResult == null ? null :
				validationResult.getProfile().getValidationProfile();
	}

	@Override
	public Metadata getMetadata() {
		return document.getMetadata();
	}

	@Override
	public PDFDocument getDocument() {
		return document;
	}

	@Override
	public ProcessedObjectsParser getParser() {
		return parser;
	}

}

Implement metadata fixes configuration object


package io.cattle.iaas.healthcheck.process;

import static io.cattle.platform.core.model.tables.InstanceTable.*;

import io.cattle.platform.core.constants.HealthcheckConstants;
import io.cattle.platform.engine.handler.HandlerResult;
import io.cattle.platform.engine.handler.ProcessPostListener;
import io.cattle.platform.engine.process.ProcessInstance;
import io.cattle.platform.engine.process.ProcessState;
import io.cattle.platform.process.common.handler.AbstractObjectProcessLogic;

import java.util.Date;

import javax.inject.Named;

@Named
public class InstanceHealthCheckUpdate extends AbstractObjectProcessLogic implements ProcessPostListener {

    @Override
    public String[] getProcessNames() {
        return new String[] { HealthcheckConstants.PROCESS_UPDATE_HEALTHY,
                HealthcheckConstants.PROCESS_UPDATE_UNHEALTHY, HealthcheckConstants.PROCESS_UPDATE_REINITIALIZING };
    }

    @Override
    public HandlerResult handle(ProcessState state, ProcessInstance process) {
        return new HandlerResult(INSTANCE.HEALTH_UPDATED, new Date());
    }
}

package io.cattle.iaas.healthcheck.process;

import static io.cattle.platform.core.model.tables.InstanceTable.*;

import io.cattle.platform.core.constants.HealthcheckConstants;
import io.cattle.platform.engine.handler.HandlerResult;
import io.cattle.platform.engine.handler.ProcessPostListener;
import io.cattle.platform.engine.process.ProcessInstance;
import io.cattle.platform.engine.process.ProcessState;
import io.cattle.platform.process.common.handler.AbstractObjectProcessLogic;

import java.util.Date;

import javax.inject.Named;

@Named
public class InstanceHealthCheckUpdate extends AbstractObjectProcessLogic implements ProcessPostListener {

    @Override
    public String[] getProcessNames() {
        return new String[] { HealthcheckConstants.PROCESS_UPDATE_HEALTHY,
                HealthcheckConstants.PROCESS_UPDATE_UNHEALTHY, HealthcheckConstants.PROCESS_UPDATE_REINITIALIZING };
    }

    @Override
    public HandlerResult handle(ProcessState state, ProcessInstance process) {
        Object now = state.getData().get("now");
        Long nowLong = System.currentTimeMillis();
        if (now instanceof Number) {
            nowLong = ((Number) now).longValue();
        } else {
            state.getData().put("now", nowLong);
        }
        return new HandlerResult(INSTANCE.HEALTH_UPDATED, new Date(nowLong));
    }
}

Fix idepotency issues in healthcheck update


package com.heynt.permutation.tests;

import java.io.IOException;
import java.util.Arrays;

import org.apache.commons.io.IOUtils;

/**
 * Can be used to perform tests on the dictionary
 *
 * @author cnibley
 *
 */
public class EnglishWordsTest
{
    private static final String DICTIONARY_FILE = "dict/english_words.txt";

    public static void main(String[] args)
    {
        EnglishWordsTest test = new EnglishWordsTest();
        String dict = test.getFile(DICTIONARY_FILE);

        test.printDictionary(dict);
    }

    private void printDictionary(String dict)
    {
        String[] separated = dict.split("\n");

        for (String word : Arrays.asList(separated))
        {
            System.out.println(word);
        }
    }

    private String getFile(String fileName)
    {
        String result = "";
        final ClassLoader classLoader = getClass().getClassLoader();
        try
        {
            result = IOUtils.toString(classLoader.getResourceAsStream(fileName));
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
        return result;
    }

}

Read in all english words


package com.alexrnl.request.shows;

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

import com.alexrnl.request.Request;
import com.alexrnl.request.Verb;

/**
 * Archive a show in the logged member account.

 * @author Alex
 */
public class ShowUnarchive extends Request {

	/** Address of the method */
	private static final String	ADDRESS			= "/shows/archive";
	/** Name of the id parameter */
	private static final String	PARAMETER_ID	= "id";

	/** The id of the show to archive */
	private final Integer		id;

	/**
	 * Constructor #1.

	 * @param id
	 *        the id of the show to archive.
	 */
	public ShowUnarchive (final Integer id) {
		super(Verb.DELETE, ADDRESS);
		this.id = id;
	}

	/**
	 * Return the attribute id.
	 * @return the attribute id.
	 */
	public Integer getId () {
		return id;
	}

	@Override
	public Map<String, String> getParameters () {
		final Map<String, String> parameters = new HashMap<>();
		parameters.put(PARAMETER_ID, getId().toString());
		return parameters;
	}

}

Add request for unarchiving show


package com.example.web;

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

@ControllerAdvice
public class GlobalDefaultExceptionHandler {

    // Convert a predefined exception to an HTTP Status code
    @ResponseStatus(value= HttpStatus.NOT_FOUND, reason="Id must be an integer.") // Default: 400
    @ExceptionHandler(NumberFormatException.class)
    public void idParseError() {
        // Nothing to do
    }
}

Fix id parse error (String can not be parsed to Long)


package org.corpus_tools.annis.gui.admin;

import static com.github.mvysny.kaributesting.v8.LocatorJ._click;
import static com.github.mvysny.kaributesting.v8.LocatorJ._get;
import static org.junit.jupiter.api.Assertions.assertEquals;

import com.github.mvysny.kaributesting.v8.MockVaadin;
import com.vaadin.spring.internal.UIScopeImpl;
import com.vaadin.ui.Button;
import com.vaadin.ui.TabSheet;
import java.io.IOException;
import net.jcip.annotations.NotThreadSafe;
import org.corpus_tools.annis.gui.AnnisUI;
import org.corpus_tools.annis.gui.SingletonBeanStoreRetrievalStrategy;
import org.corpus_tools.annis.gui.admin.reflinks.MigrationPanel;
import org.corpus_tools.annis.gui.admin.reflinks.ReferenceLinkEditor;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.web.WebAppConfiguration;

@SpringBootTest
@ActiveProfiles({"desktop", "test", "headless"})
@WebAppConfiguration
@NotThreadSafe
class AdminViewTest {

  @Autowired
  private BeanFactory beanFactory;

  private AnnisUI ui;

  @BeforeEach
  void setup() throws IOException {
    UIScopeImpl.setBeanStoreRetrievalStrategy(new SingletonBeanStoreRetrievalStrategy());
    this.ui = beanFactory.getBean(AnnisUI.class);

    MockVaadin.setup(() -> ui);

    _click(_get(Button.class, spec -> spec.withCaption("Administration")));

  }

  @AfterEach
  public void tearDown() throws IOException {
    MockVaadin.tearDown();
  }

  @Test
  void testFragmentChanges() throws Exception {
    // Select all of the available tabs and check that the fragment is updated
    TabSheet tab = _get(TabSheet.class);

    tab.setSelectedTab(_get(ImportPanel.class));
    assertEquals("!admin/import", ui.getPage().getUriFragment());

    tab.setSelectedTab(_get(CorpusAdminPanel.class));
    assertEquals("!admin/corpora", ui.getPage().getUriFragment());

    tab.setSelectedTab(_get(ReferenceLinkEditor.class));
    assertEquals("!admin/reference-link-editor", ui.getPage().getUriFragment());

    tab.setSelectedTab(_get(MigrationPanel.class));
    assertEquals("!admin/reference-link-migration", ui.getPage().getUriFragment());
  }

}

Add a test that the admin view fragment changes


/*-
 * Copyright 2015 Diamond Light Source Ltd.
 *
 * 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
 */

package org.eclipse.dawnsci.analysis.api.processing;

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

/**
 * This is an annotation for marking an IOperation as having a threadsafe execute method
 */
@Retention(RetentionPolicy.RUNTIME)
@Target(value = ElementType.TYPE)
public @interface Atomic {

}

Add atomic thread safe marker annotation


package com.bignerdranch.android.photogallery;

import android.os.HandlerThread;
import android.util.Log;

public class ThumbnailDownloader<T> extends HandlerThread {

    private static final String TAG = "ThumbnailDownloader";

    public ThumbnailDownloader() {
        super(TAG);
    }

    public void queueThumbnail(T target, String url) {
        Log.i(TAG, "Gor a URL: " + url);
    }
}

Create class that will manage image download in background


import junit.framework.*;

public class AssignInExpr extends TestCase {

    public void testExpr() {
        int a = 1, b = 2, c = 3;

        a = b += c;
        Assert.assertEquals(b, 5);
        Assert.assertEquals(a, 5);

        a = b += c += a;
        Assert.assertEquals(c, 8);
        Assert.assertEquals(b, 13);
        Assert.assertEquals(a, 13);

        a = (b = 1) * (c = 10);
        Assert.assertEquals(a, 10);
        Assert.assertEquals(b, 1);
        Assert.assertEquals(a, 10);

    }

    public void testIf() {
        int a = 4, b = 6, c = 10;

        if ((a +=b) == c) {
            c = 20;
        }
        Assert.assertEquals(a, 10);
        Assert.assertEquals(b, 6);
        Assert.assertEquals(c, 20);
    }

    public void testWhile() {
        int i = 0;

        while (++i < 10) {
            Assert.assertTrue(i < 10);
        }
        Assert.assertEquals(i, 10);

    }

    public void testDo() {
        int i = 0;
        do {
            Assert.assertTrue(i < 10);
        } while (++i < 10);
        Assert.assertEquals(i, 10);
    }

    public void testPostIncDec() {
        int i = 0, j = 0, k = 0;
        i = j++;
        Assert.assertEquals(i, 0);
        Assert.assertEquals(j, 1);

        if (++i == j++) {
            k = 3;
        }
        Assert.assertEquals(i, 1);
        Assert.assertEquals(j, 2);
        Assert.assertEquals(k, 3);
    }

    public void testAndOr() {
        int i = 0, j = 0;

        if (i++ == 1 && j++ == 1) {
            Assert.fail("and test fail");
        } else {
            Assert.assertEquals(i, 1);
            Assert.assertEquals(j, 0);
        }

        if (--i != 0 || j-- == 0) {
            Assert.assertEquals(i, 0);
            Assert.assertEquals(j, -1);
        } else {
            Assert.fail("or test fail");
        }

    }

}

Add assign in expression testcase


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

package com.google.sps.servlets;

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

// Delivers a list of strings representing today's trending searches worldwide
@WebServlet("/trending")
public class TrendingServlet extends HttpServlet {

    private List<String> trendingSearches = new ArrayList<>();

    @Override
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
        getTrendingSearches();
        Gson gson = new Gson();
        response.setContentType("text/html;");
        response.getWriter().println(gson.toJson(trendingSearches));
    }

    public void getTrendingSearches() {
        //fetch trending searches from db - hard coded data for now
        trendingSearches.add("Giraffes");
        trendingSearches.add("Chicken nuggets");
    }
}

Add servlet to deliver today's trending searches


package net.restlesscoder.sandbox.imagej;

import java.io.IOException;

import net.imagej.Dataset;
import net.imagej.ImageJ;
import net.imagej.ImgPlus;
import net.imglib2.RandomAccessibleInterval;
import net.imglib2.converter.Converters;
import net.imglib2.type.numeric.RealType;
import net.imglib2.type.numeric.integer.UnsignedByteType;

public class ConvertersClamp {

	public static void main(final String... args) throws IOException {
		final ImageJ ij = new ImageJ();
		ij.ui().showUI();

		// Load an image of a colorful bird.
		final String path = "/Users/curtis/data/toucan.png";
		final Dataset toucan = ij.scifio().datasetIO().open(path);
		final ImgPlus<UnsignedByteType> img = toucan.typedImg(new UnsignedByteType());

		// Make bird less colorful.
		RandomAccessibleInterval<UnsignedByteType> clamped = clamp(img, 50, 100, new UnsignedByteType());
		ij.ui().show("Clamped", clamped);
	}

	public static <T extends RealType<T>> RandomAccessibleInterval<T> clamp(
		final RandomAccessibleInterval<T> image, final double min, final double max, final T type)
	{
		return Converters.convert(image, (in, out) -> {
			double value = in.getRealDouble();
			if (value < min) value = min;
			else if (value > max) value = max;
			out.setReal(value);
		}, type);
	}
}

Add example that clamps image values to (min, max)


package org.robockets.stronghold.robot.highgoalshooter;

import edu.wpi.first.wpilibj.command.Command;
import org.robockets.stronghold.robot.Robot;

/**
 * Roll the jeff rollers to fire a cannonball.
 */
public class FireShooter extends Command {

    public FireShooter() {
        // Use requires() here to declare subsystem dependencies
        // eg. requires(chassis);
    }

    // Called just before this Command runs the first time
    protected void initialize() {
    	setTimeout(0.7);
    }

    // Called repeatedly when this Command is scheduled to run
    protected void execute() {
    	Robot.shooter.spinJeffRollers(1);
    }

    // Make this return true when this Command no longer needs to run execute()
    protected boolean isFinished() {
        return isTimedOut();
    }

    // Called once after isFinished returns true
    protected void end() {
    	Robot.shooter.spinJeffRollers(0);
    }

    // Called when another command which requires one or more of the same
    // subsystems is scheduled to run
    protected void interrupted() {
    	end();
    }
}

Add shoot command for high goal shooter.


@Configuration
public class ServerConfig {

	public class FaviconConfiguration extends WebMvcConfigurerAdapter{

		@Override
		public void addResourceHandlers(ResourceHandlerRegistry registry){
			registry.setOrder(Integer.MIN_VALUE);
			registry.addResourceHandler("/favicon.ico").addResourceLocations("/");

			registry.addResourceHandler("/static/**")
			        .addResourceLocations("/")
			        .resourceChain(false)
			        .addResolver(new GzipResourceResolver())
			        .addResolver(new VersionResourceResolver().addContentVersionStrategy("/**"));
		}
	}
}

Enable gzip in springboot project


/**
 *
 */
package com.trendrr.strest.tests;

import junit.framework.Assert;

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

import com.trendrr.strest.examples.HelloWorld;
import com.trendrr.strest.server.routing.MatchedRoute;
import com.trendrr.strest.server.routing.RouteMatcher;
import com.trendrr.strest.server.routing.UriMapping;

/**
 * @author Dustin Norlander
 * @created Jun 28, 2011
 *
 */
public class RouteMatchingTests {

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

	@Test
	public void testRoutes() {

		RouteMatcher tree = new RouteMatcher();

		tree.addMapping(new UriMapping("/", HelloWorld.class));
		tree.addMapping(new UriMapping("/test", HelloWorld.class));
		tree.addMapping(new UriMapping("/test/*filenames", HelloWorld.class));
		tree.addMapping(new UriMapping("/test/:id", HelloWorld.class));
		tree.addMapping(new UriMapping("/test/:name/:id", HelloWorld.class));
		tree.addMapping(new UriMapping("/test/idmatch/:id", HelloWorld.class));
		tree.addMapping(new UriMapping("/test/idmatch/namematch", HelloWorld.class));

		/*
		 * Notes on matching:
		 *
		 * matched route allways strips leading /
		 *
		 * Will always return the MOST specific match, ie exact matches take precidence over wildcards
		 *
		 */

		Assert.assertTrue(match(tree, "hello", null));
		Assert.assertTrue(match(tree, "/", ""));

		Assert.assertTrue(match(tree, "/test/1/2/3/4", "test/*filenames"));
		Assert.assertTrue(match(tree, "/test/1", "test/:id"));
		Assert.assertTrue(match(tree, "/test/name/1", "test/:name/:id"));

		Assert.assertTrue(match(tree, "/test/idmatch/1", "test/idmatch/:id"));
		Assert.assertTrue(match(tree, "/test/idmatch/namematch", "test/idmatch/namematch"));

//		System.out.println(tree.find("/dustin/blah"));
//		System.out.println(tree.find("/dustin/blah/asdf"));
//		System.out.println(tree.find("/"));

	}

	protected boolean match(RouteMatcher tree, String route, String expected) {
		MatchedRoute rt = tree.find(route);
		if (rt == null && expected == null)
			return true;
		if (rt == null) {
			log.warn("Route matched was null: " + route);
			return false;
		}
		if (rt.getMapping().getRoute().equals(expected)) {
			return true;
		}

		log.warn("Route didn't match: " + route + " GOT: " + rt.getMapping().getRoute() + " EXPECTED: " + expected);

		return false;
	}
}

Add tests for route matching


package com.kurento.kmf.media;

import com.kurento.kmf.media.events.ErrorEvent;
import com.kurento.kmf.media.events.MediaEventListener;
import com.kurento.tool.rom.RemoteClass;

@RemoteClass
public interface MediaObject {

	MediaPipeline getMediaPipeline();

	void getMediaPipeline(Continuation<MediaPipeline> cont);

	MediaObject getParent();

	void getParent(Continuation<MediaObject> cont);

	ListenerRegistration addErrorListener(
			MediaEventListener<ErrorEvent> listener);

	void addErrorListener(MediaEventListener<ErrorEvent> listener,
			Continuation<ListenerRegistration> cont);

	void release();

	void release(Continuation<Void> continuation);
}

package com.kurento.kmf.media;

import com.kurento.kmf.media.events.ErrorEvent;
import com.kurento.kmf.media.events.MediaEventListener;
import com.kurento.tool.rom.RemoteClass;

@RemoteClass
public interface MediaObject {

	MediaPipeline getMediaPipeline();

	void getMediaPipeline(Continuation<MediaPipeline> cont);

	MediaObject getParent();

	void getParent(Continuation<MediaObject> cont);

	ListenerRegistration addErrorListener(
			MediaEventListener<ErrorEvent> listener);

	void addErrorListener(MediaEventListener<ErrorEvent> listener,
			Continuation<ListenerRegistration> cont);

	/**
	 *
	 * Explicitly release a media object form memory. All of its children will
	 * also be released.
	 *
	 **/
	void release();

	/**
	 *
	 * Explicitly release a media object form memory. All of its children will
	 * also be released. Asynchronous call.
	 *
	 * @param continuation
	 *            {@link #onSuccess(void)} will be called when the actions
	 *            complete. {@link #onError} will be called if there is an
	 *            exception.
	 *
	 **/
	void release(Continuation<Void> continuation);

}

Add generated documentation for release methods


package moe.tristan.easyfxml.util;

import javafx.application.Platform;
import javafx.scene.Node;
import javafx.scene.control.Button;
import javafx.scene.input.MouseEvent;

import java.util.function.Consumer;

public final class Buttons {

    private Buttons() {
    }

    public static void setOnClick(final Button button, final Runnable action) {
        button.addEventFilter(MouseEvent.MOUSE_CLICKED, e -> Platform.runLater(action));
    }

    public static void setOnClickWithNode(final Button button, final Node node, final Consumer<Node> action) {
        setOnClick(button, () -> action.accept(node));
    }

}

Add convenience methods for Button on-click event reaction


package probos;

import static org.junit.Assert.*;
import jnr.posix.POSIX;
import jnr.posix.POSIXFactory;

import org.junit.Test;

public class TestPosix {
	//static final

	@Test public void testGroup()
	{
		POSIX posix = POSIXFactory.getPOSIX();
		System.err.println(posix.isNative());
		String egroup = posix.getgrgid(posix.getegid()).getName();
		assertNotNull(egroup);
	}
}

Check posix calls work on this platform


/*
 * AsTest.java
 *
 * Created on 10. September 2001, 09:44
 */

package freetds;
import java.sql.*;
import java.math.BigDecimal;
import com.internetcds.util.Logger;
import junit.framework.TestCase;
import junit.framework.TestSuite;
import junit.framework.AssertionFailedError;
import java.io.*;
import java.lang.reflect.*;

/**
 *
 * @author  builder
 * @version
 */
public class AsTest extends DatabaseTestCase {

  public AsTest(String name) {
    super(name);
  }

  public static void main(String args[]) {
    try {
      Logger.setActive(true);
    }
    catch (java.io.IOException ex) {
      throw new RuntimeException("Unexpected Exception " + ex + " occured in main");
    }
    if (args.length > 0) {
      junit.framework.TestSuite s = new TestSuite();
      for (int i = 0; i < args.length; i++) {
        s.addTest(new AsTest(args[i]));
      }
      junit.textui.TestRunner.run(s);
    }
    else
      junit.textui.TestRunner.run(AsTest.class);
  }

  public void testProc1() throws Exception
  {

    boolean passed = false;
    Statement stmt = con.createStatement();
    stmt.executeUpdate("  if (exists (select * from sysobjects where name = 'spTestExec')) drop procedure spTestExec");
    stmt.executeUpdate("  if (exists (select * from sysobjects where name = 'spTestExec2')) drop procedure spTestExec2");

    stmt.executeUpdate(" create procedure spTestExec2 as " +
                    "select 'Did it work?' as Result");
    stmt.executeUpdate("create procedure spTestExec as " +
		"create table #tmp ( Result varchar(50) ) " +
		"insert #tmp execute spTestExec2 " +
		"select * from #tmp");
    CallableStatement cstmt = con.prepareCall("exec spTestExec");
    ResultSet rs = cstmt.executeQuery();
    while (rs.next()) {
      passed = true;
    }
    assertTrue(passed);
    // stmt.executeQuery("execute spTestExec");

  }

}

Test PMoores Problem with Procedure sptestexec


/**
 *
 */
package com.trendrr.oss;

import java.util.concurrent.ConcurrentHashMap;

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

import com.trendrr.oss.concurrent.ReinitObject;

/**
 *
 * A threadsafe file cache.
 *
 *
 * @author Dustin Norlander
 * @created Apr 7, 2011
 *
 */
public class FileCache {

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

	private static ConcurrentHashMap<String, ReinitObject<byte[]>> cache = new ConcurrentHashMap<String, ReinitObject<byte[]>> ();

	/**
	 * loads a file from the cache.  All exceptions are logged as warnings, and null is returned.
	 * @param filename filename to load
	 * @param timeoutPeriod number of milliseconds between reload of the file.
	 * @return
	 */
	public byte[] getFileBytes(String filename, long timeoutPeriod) {
		final String f = filename;

		//fancy timeout cache.
		cache.putIfAbsent(filename, new ReinitObject<byte[]>(timeoutPeriod) {
			@Override
			public byte[] init() {
				try {
					System.out.println("LOADING FROM FILE SYSTEM!");
					return FileHelper.loadBytes(f);
				} catch (Exception e) {
					log.warn("Caught", e);
				}
				return null;
			}
		});
		return cache.get(filename).get();
	}
}

Add a simple, fast, threadsafe file cache


/**
 *
 */
/**
 * @author roart
 *
 */
module iclij.evolutionchromosome {
    exports roart.iclij.evolution.marketfilter.chromosome.impl;
    exports roart.iclij.evolution.chromosome.impl;
    exports roart.iclij.evolution.chromosome.winner;
    requires iclij.common.config;
    requires iclij.common.componentdata;
    requires iclij.evolutionmarketfilter;
    requires iclij.evolutioniclijconfigmap;
    requires evolution.gene;
    requires evolution.model;
    requires common.util;
    requires io.jenetics.base;
    requires com.fasterxml.jackson.core;
    requires com.fasterxml.jackson.databind;
    requires slf4j.api;
    requires common.constants;
    requires iclij.common.model;
    requires common.config;
    requires org.apache.commons.lang3;
    requires jackson.annotations;
}

Move to subproject, Jackson annotations and remove classes, evolution refactor (I111).


package leetcode;

/**
 * https://leetcode.com/problems/edit-distance/
 */
public class Problem72 {
    public int minDistance(String word1, String word2) {
        // TODO
        return 0;
    }

    public static void main(String[] args) {
        Problem72 prob = new Problem72();
        System.out.println(prob.minDistance("geek", "gesek")); // 1
        System.out.println(prob.minDistance("cat", "cut")); // 1
        System.out.println(prob.minDistance("sunday", "saturday")); // 3
    }
}

Create a skeleton for problem 72


package starpunk;

import com.badlogic.gdx.ApplicationListener;
import com.badlogic.gdx.backends.lwjgl.LwjglApplication;
import com.badlogic.gdx.backends.lwjgl.LwjglApplicationConfiguration;

public class Main
{
  public static void main( final String[] args )
  {
    final LwjglApplicationConfiguration configuration = new LwjglApplicationConfiguration();
    configuration.fullscreen = false;
    configuration.width = 1280;
    configuration.height = 900;
    configuration.useCPUSynch = false;
    configuration.vSyncEnabled = false;
    configuration.title = "Star Punk";
    new LwjglApplication( new ApplicationListener() {
      @Override
      public void create()
      {
      }

      @Override
      public void resize( final int width, final int height )
      {
      }

      @Override
      public void render()
      {
      }

      @Override
      public void pause()
      {
      }

      @Override
      public void resume()
      {
      }

      @Override
      public void dispose()
      {
      }
    }, configuration );
  }
}

Add minimal do nothig application


package com.lightbulbz.net;

import java.io.IOException;
import java.net.*;

/**
 * Created by kevin on 6/3/15.
 */
public class WOLPacketSender {
    private static final byte FF = (byte) 0xff;
    private static final byte[] PAYLOAD_START = {FF, FF, FF, FF, FF, FF};
    private static final int WOL_PACKET_SIZE = 6 + 16 * 6;
    private DatagramPacket packet;
    private final DatagramSocket sock;

    public WOLPacketSender(InetAddress targetAddr, MacAddress targetMac) throws SocketException {
        sock = new DatagramSocket();
        byte[] packetBytes = new byte[WOL_PACKET_SIZE];
        byte[] macBytes = targetMac.getAddressBytes();
        System.arraycopy(PAYLOAD_START, 0, packetBytes, 0, PAYLOAD_START.length);
        for (int i = PAYLOAD_START.length; i < WOL_PACKET_SIZE; i += macBytes.length) {
            System.arraycopy(macBytes, 0, packetBytes, i, macBytes.length);
        }
        packet = new DatagramPacket(packetBytes, packetBytes.length, new InetSocketAddress(targetAddr, 9));
    }

    public void sendPacket() throws IOException {
        sock.send(packet);
    }
}

Move code to send WOL packet into library


package com.zulip.android.networking;

import java.io.IOException;

import okhttp3.MediaType;
import okhttp3.ResponseBody;
import okio.Buffer;
import okio.BufferedSource;
import okio.ForwardingSource;
import okio.Okio;
import okio.Source;

/**
 * TODO: add description
 */

public class UploadProgressResponse extends ResponseBody {
    private final ResponseBody responseBody;
    private final ProgressListener progressListener;
    private BufferedSource bufferedSource;
    private int mNotificationId;

    public UploadProgressResponse(ResponseBody responseBody, ProgressListener progressListener,
                                  int notificationId) {
        this.responseBody = responseBody;
        this.progressListener = progressListener;
        this.mNotificationId = notificationId;
    }

    @Override
    public MediaType contentType() {
        return responseBody.contentType();
    }

    @Override
    public long contentLength() {
        return responseBody.contentLength();
    }

    @Override
    public BufferedSource source() {
        if (bufferedSource == null) {
            bufferedSource = Okio.buffer(source(responseBody.source()));
        }
        return bufferedSource;
    }

    private Source source(Source source) {
        return new ForwardingSource(source) {
            long totalBytesRead = 0L;

            @Override
            public long read(Buffer sink, long byteCount) throws IOException {
                long bytesRead = super.read(sink, byteCount);
                // read() returns the number of bytes read, or -1 if this source is exhausted.
                totalBytesRead += bytesRead != -1 ? bytesRead : 0;
                progressListener.update(totalBytesRead, responseBody.contentLength(), bytesRead == -1, mNotificationId);
                return bytesRead;
            }
        };
    }

    public interface ProgressListener {
        void update(long bytesRead, long contentLength, boolean done, int notificationId);
    }
}

Add custom upload progress RequestBody.


package checkpoint.andela.members;

import org.junit.Test;
import checkpoint.andela.main.Book;

import static org.junit.Assert.*;

/**
 * Created by Semiu on 26/11/2015.
 */
public class StudentTest {
  Student student1 = new Student();
  Book book4 = new Book();

  @Test
  public void testBorrowBook() throws Exception {
    book4.setNumberOfCopies(10);
    student1.borrowBook(book4);
    assertEquals(book4.getNumberOfCopies(), 9);
  }

  @Test
  public void testReturnBook() throws Exception {
    book4.setNumberOfCopies(9);
    student1.returnBook(book4);
    assertEquals(book4.getNumberOfCopies(), 10);
  }
}

Update Test for Student class


/*
 * Copyright 2015 Attribyte, LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * 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.attribyte.metrics.cloudwatch;

import com.codahale.metrics.Counter;
import com.codahale.metrics.MetricRegistry;
import org.attribyte.metrics.RegistryTranslation;
import org.junit.Test;

import java.io.FileInputStream;
import java.util.Properties;

public class CloudwatchReporterTest {

   @Test
   public void reportToCloudwatch() throws Exception  {

      Properties secrets = new Properties();
      String userHome = System.getProperty("user.home");
      try(FileInputStream fis = new FileInputStream(userHome+"/cwsecrets")) {
         secrets.load(fis);
      }

      Properties props = new Properties(secrets);
      props.put(CloudwatchReporter.METRIC_NAMESPACE_PROPERTY, "test01");
      props.put(RegistryTranslation.TRANSLATE_PREFIX + "internal-counter-02", "counter-02");

      MetricRegistry registry = new MetricRegistry();
      Counter counter01 = registry.counter("internal-counter-01");
      counter01.inc(14L);
      Counter counter02 = registry.counter("internal-counter-02");
      counter02.inc(15L);
      Counter counter03 = registry.counter("internal-counter-03");
      counter03.inc(16L);

      CloudwatchReporter reporter = new CloudwatchReporter();
      reporter.init("cloudwatch", props, registry, null); //No filter...
      reporter.start();
      Thread.sleep(61000L);
      reporter.stop();
   }
}

Add cloudwatch reporter test. Requires manual verification...but have verified that the mechanics do work.


@API(apiVersion = "1.0.0", owner = "Boilerplate", provides = "Boilerplate|FantasyKingdomAPI")
package boilerplate.kingdomapi;

import cpw.mods.fml.common.API;

Add the base class for the FantasyKingdoms API.


package ca.nrc.cadc.vos;

import javax.sql.DataSource;

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

public abstract class VOSpaceFileMetadataSourceTest extends PersistenceTest
{
    private VOSpaceFileMetadataSource vospaceFileMetadataSource;
    private DataNode testNode;

    @Before
    public void before() throws Exception
    {
        super.commonBefore();
        vospaceFileMetadataSource = new VOSpaceFileMetadataSource();
        vospaceFileMetadataSource.setNodePersistence(nodeDAO);

        ContainerNode rootContainer = (ContainerNode) nodeDAO.getFromParent(getRootContainerName(), null);
        testNode = new DataNode(getVOSURIPrefix() + getRootContainerName() + "/" + getNodeName("testNode"));
        nodeDAO.putInContainer(testNode, rootContainer);
    }

    public abstract DataSource getDataSource();

    public abstract NodeDAO getNodeDAO(DataSource dataSource);

    public abstract String getVOSURIPrefix();

    public abstract String getRootContainerName();

    public abstract String getNodeOwner();

    @Test
    public void testMetadata() throws Exception
    {

    }

}

Put common persistence test code in abstract class PersistenceTest


package leetcode._4sum;

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

public class Solution {
    public ArrayList<ArrayList<Integer>> fourSum(int[] num, int target) {
    	int length = num.length;
    	ArrayList<ArrayList<Integer>> ans = new ArrayList<ArrayList<Integer>>();
    	Arrays.sort(num);
    	for(int i = 0; i < length; i++){
    		if(i > 0 && num[i] == num[i - 1]) continue;
    		for(int j = i + 1; j < length; j++){
    			if(j > i + 1 && num[j] == num[j - 1]) continue;
    			int head = j + 1, tail = length - 1;
        		while(head < tail){
        			while(head > j + 1 && head < tail && num[head] == num[head - 1]) head++;
        			while(tail < length - 1 && head < tail && num[tail] == num[tail + 1]) tail--;
        			int sum = num[i] + num[j] + num[head] + num[tail];
        			if(head < tail){
        				if(sum < target){
        					head++;
        				}else if(sum > target){
        					tail--;
        				}else{
        					ans.add(new ArrayList<Integer>(Arrays.asList(new Integer[]{num[i], num[j], num[head], num[tail]})));
        					head++;
        					tail--;
        				}
        			}
        		}
    		}
    	}
    	return ans;
    }

    public static void main(String[] args){
    	for(ArrayList<Integer> row : new Solution().fourSum(new int[]{1, 0, -1, 0, -2, 2}, 0)){
    		for(int x : row){
    			System.err.print(x + " ");
    		}
    		System.err.println("");
    	}
    }
}

Add java solution for 18. 4Sum


package net.darkmorford.btweagles.eventhandler;

import net.darkmorford.btweagles.BetterThanWeagles;
import net.minecraft.item.Item;
import net.minecraftforge.event.RegistryEvent;
import net.minecraftforge.fml.common.Mod;
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent;

@Mod.EventBusSubscriber
public class EventHandlerMappings
{
	@SubscribeEvent
	public static void missingItemMapping(RegistryEvent.MissingMappings<Item> event)
	{
		BetterThanWeagles.logger.warn("Caught missing item mappings! Attempting to repair them...");

		for (RegistryEvent.MissingMappings.Mapping<Item> mapping : event.getMappings())
		{
			BetterThanWeagles.logger.info("Item mapping for " + mapping.key + " is missing, taking default action.");
		}
	}
}

Add an event handler to deal with missing item mappings.


package openmods.calc;

import com.google.common.base.Strings;
import com.google.common.base.Supplier;
import openmods.Log;

public class SingleExprEvaluator<E, M> {

	public interface EnvironmentConfigurator<E> {
		public void accept(Environment<E> env);
	}

	private final Calculator<E, M> calculator;

	private boolean useFallback;

	private M exprType;

	private String expr;

	private IExecutable<E> compiledExpr;

	public SingleExprEvaluator(Calculator<E, M> calculator) {
		this.calculator = calculator;
	}

	public static <E, M> SingleExprEvaluator<E, M> create(Calculator<E, M> calculator) {
		return new SingleExprEvaluator<E, M>(calculator);
	}

	public void setExpr(M exprType, String expr) {
		this.exprType = exprType;
		this.expr = expr;
		this.compiledExpr = null;
		this.useFallback = false;
	}

	public E evaluate(EnvironmentConfigurator<E> conf, Supplier<E> fallbackValue) {
		if (useFallback || Strings.isNullOrEmpty(expr) || exprType == null) return fallbackValue.get();

		if (compiledExpr == null) {
			try {
				compiledExpr = calculator.compilers.compile(exprType, expr);
			} catch (Exception ex) {
				useFallback = true;
				Log.warn(ex, "Failed to compile formula %s", expr);
				return fallbackValue.get();
			}
		}

		conf.accept(calculator.environment);

		try {
			return calculator.environment.executeAndPop(compiledExpr);
		} catch (Exception ex) {
			useFallback = true;
			Log.warn(ex, "Failed to execute formula %s", expr);
			return fallbackValue.get();
		}
	}

}

Add helper for single-formula calculators


package flyway.myplaces;

import fi.nls.oskari.domain.map.OskariLayer;
import org.flywaydb.core.api.migration.BaseJavaMigration;
import org.flywaydb.core.api.migration.Context;
import org.json.JSONException;
import org.json.JSONObject;
import org.oskari.usercontent.LayerHelper;

/**
 * The label for field "link" on my places layers for english, finnish and swedish
 */
public class V1_0_14__change_link_label extends BaseJavaMigration {

    private static final String NAME = "oskari:my_places";

    public void migrate(Context ignored) throws Exception {
        OskariLayer layer = LayerHelper.getLayerWithName(NAME);
        JSONObject attrs = layer.getAttributes();
        modifyAttributes(attrs);
        layer.setAttributes(attrs);
        LayerHelper.update(layer);
    }

    /**
     * Set up for overriding to make future migration easier
     * @param attrs
     * @throws JSONException
     */
    void modifyAttributes(JSONObject attrs) throws JSONException {
        String field = "link";
        // this repeats digging the locale from attributes multiple times
        // but allows developers to easily adjust other fields and languages as well in the future
        changeLabel(attrs, "en", field, "More information");
        changeLabel(attrs, "fi", field, "Lisätiedot");
        changeLabel(attrs, "sv", field, "Mera information");
    }

    /**
     * Note! This can throw null pointer if the database was modified outside the
     * Flyway migrations and these blocks were removed.
     *
     * But it's better to catch that with failing migration than
     * let the migration die silently
     *
     * @param attrs
     * @return
     * @throws JSONException
     */
    void changeLabel(JSONObject attrs, String lang, String field, String label) throws JSONException {
        JSONObject data = attrs.optJSONObject("data");
        JSONObject locale = data.optJSONObject("locale");
        JSONObject en = locale.optJSONObject(lang);
        en.put(field, label);
    }
}

Change label for myplaces link


public class Solution {

    public int removeElement(int[] nums, int val) {

        int lenCount = 0;

        for (int i = 0; i < nums.length; i++) {

            if (nums[i] != val) {
                nums[lenCount] = nums[i];
                lenCount++;
            }

        }

        return lenCount;

    }

}

Create : 27 Remove Element


package com.github.aureliano.achmed.resources.types;

import static org.junit.Assert.assertEquals;

import static com.github.aureliano.achmed.resources.types.PackageProvider.*;
import static com.github.aureliano.achmed.resources.types.OperatingSystemFamily.*;

import org.junit.Test;

public class PackageProviderTest {

	@Test
	public void testOperatingSystemFamily() {
		assertEquals(DEBIAN, APT.getOperatingSystemFamily());
		assertEquals(RPM, YUM.getOperatingSystemFamily());
		assertEquals(APP, GEM.getOperatingSystemFamily());
	}

	@Test
	public void testPackageManagement() {
		assertEquals("apt-get", APT.getPackageManagement());
		assertEquals("yum", YUM.getPackageManagement());
		assertEquals("gem", GEM.getPackageManagement());
	}
}

Create unit test to package provider type.


import io.specto.hoverfly.junit.HoverflyRule;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.springframework.http.RequestEntity;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;

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

import static net.javacrumbs.jsonunit.fluent.JsonFluentAssert.assertThatJson;
import static org.assertj.core.api.Assertions.assertThat;
import static org.springframework.http.HttpStatus.CREATED;
import static org.springframework.http.HttpStatus.OK;
import static org.springframework.http.MediaType.APPLICATION_JSON;

public class URLHoverflyRuleTest {

    @Rule
    public HoverflyRule hoverflyRule = HoverflyRule.buildFromUrl("http://raw.githubusercontent.com/SpectoLabs/hoverfly-junit/d0d41dfdcb250c6bb02ada63d304b4afddf5f2e4/src/test/resources/test-service.json").build();

    private RestTemplate restTemplate;

    @Before
    public void setUp() {
        restTemplate = new RestTemplate();
    }

    @Test
    public void shouldBeAbleToMakeABookingUsingHoverfly() throws URISyntaxException {
        // Given
        final RequestEntity<String> bookFlightRequest = RequestEntity.post(new URI("http://www.my-test.com/api/bookings"))
                .contentType(APPLICATION_JSON)
                .body("{\"flightId\": \"1\"}");

        // When
        final ResponseEntity<String> bookFlightResponse = restTemplate.exchange(bookFlightRequest, String.class);

        // Then
        assertThat(bookFlightResponse.getStatusCode()).isEqualTo(CREATED);
        assertThat(bookFlightResponse.getHeaders().getLocation()).isEqualTo(new URI("http://localhost/api/bookings/1"));
    }

    @Test
    public void shouldBeAbleToGetABookingUsingHoverfly() {
        // When
        final ResponseEntity<String> getBookingResponse = restTemplate.getForEntity("http://www.my-test.com/api/bookings/1", String.class);

        // Then
        assertThat(getBookingResponse.getStatusCode()).isEqualTo(OK);
        assertThatJson(getBookingResponse.getBody()).isEqualTo("{" +
                "\"bookingId\":\"1\"," +
                "\"origin\":\"London\"," +
                "\"destination\":\"Singapore\"," +
                "\"time\":\"2011-09-01T12:30\"," +
                "\"_links\":{\"self\":{\"href\":\"http://localhost/api/bookings/1\"}}" +
                "}");
    }

}

Test for rule where a URL is configured as the source json


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

package org.gradle.api.internal.file;

import org.gradle.api.file.FileTree;

public interface FileTreeInternal extends FileTree, FileCollectionInternal {
}

Add missing file from previous commit.


/*
   Copyright (C) 2011-2014 AC Inc. (Andy Cheung)

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
*/

import java.net.*;
import java.io.*;

public class ReserveMC{
  public static void main(String[] a){
    System.out.println("Craftbukkit Port Preserve Util");
    System.out.println("(C) 2011-2014 AC Inc.");
    System.out.println();
    new Thread(new PortReserveThread(25565)).start();
    new Thread(new PortReserveThread(1139)).start();
  }
}

class PortReserveThread implements Runnable{
  int port; // This thread's port.

  // The TCP Settings Part.
  Socket s; //The Socket, not for use.
  ServerSocket ss; // The ServerSocket.

  public void out(String t){
    System.out.println(t);
  }

  public PortReserveThread(int which){
    out("Creating instance of PRT...");
    port = which; // Set port.
    try {
      ss = new ServerSocket(port);  //Get New SS (ServerSocket[TCP]) instance.
      out("Created instance of TCP Socket. This will reserve port " + port);
    } catch (IOException e) {  //Catch the exception.
      System.out.println("Error,Will exit.");
      System.exit(1);
    }
  }

  public void run(){ // Thread method body.
    while(true){ // Unlimited Accept.
      try{
        out("Accepting TCP on " + port);
        s = ss.accept(); // Reserve TCP.
        s.close();
      }
      catch(SocketTimeoutException ste){
        try {
          s.close();
	} catch (IOException e) {
          System.out.println("Error,Will exit.");
          System.exit(1);
	}
      }
      catch(IOException ioe){
	try {
	  s.close();
	} catch (IOException e) {
	  System.out.println("Error,Will exit.");
	  System.exit(1);
	}
      }
      finally{
	try {
	  s.close();
	} catch (IOException e) {
	  System.out.println("Error,Will exit.");
	  System.exit(1);
	}
        s = null;
      }
    }
  }

  public void stopSelf(){  //Stop Procress.
    Thread.currentThread().interrupt();
  }
  public int getPort(){
    return port;
  }
}

Add a very simple killer.


package forklift.decorators;

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

/**
 * Specify how many processor threads should be launched by forklift for the annotated processor.
 */
@Documented
@Inherited
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE})
public @interface MultiThreaded {
    /**
     * The maximum number of threads to run.
     */
    int value();
}

Add a multithreaded annotation that will allow forklift to spin up a specified number of threads to run a processor.