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

package org.springframework.test.context.env;

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

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
import org.springframework.core.env.Environment;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.TestPropertySource;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import static org.junit.Assert.*;

/**
 * Integration tests for {@link TestPropertySource @TestPropertySource} support with
 * inlined properties that overrides properties files.
 *
 * @author Sam Brannen
 * @since 4.3
 */
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration
@TestPropertySource(locations = "explicit.properties", properties = "explicit = inlined")
public class InlinedPropertiesOverridePropertiesFilesTestPropertySourceTests {

	@Autowired
	Environment env;

	@Value("${explicit}")
	String explicit;

	@Test
	public void inlinedPropertyOverridesValueFromPropertiesFile() {
		assertEquals("inlined", env.getProperty("explicit"));
		assertEquals("inlined", this.explicit);
	}

	@Configuration
	static class Config {

		@Bean
		public static PropertySourcesPlaceholderConfigurer placeholderConfigurer() {
			return new PropertySourcesPlaceholderConfigurer();
		}
	}

}

Verify inlined props override files in @TestPropertySource


/*******************************************************************************
 * Copyright (c) 1998, 2007 Oracle. All rights reserved.
 * This program and the accompanying materials are made available under the
 * terms of the Eclipse Public License v1.0, which accompanies this distribution
 * and is available at http://www.eclipse.org/legal/epl-v10.html.
 *
 * Contributors:
 *     Oracle - initial API and implementation from Oracle TopLink
 ******************************************************************************/
package org.eclipse.persistence.testing.sdo.helper.xmlhelper.threadsafety;

import junit.framework.Test;
import junit.framework.TestSuite;

public class SDOXMLHelperThreadSafetyTestSuite {

	public SDOXMLHelperThreadSafetyTestSuite() {
    }

    public static void main(String[] args) {
        junit.textui.TestRunner.run(suite());
    }

    public static Test suite() {
        TestSuite suite = new TestSuite("All XMLHelper Thread Safety Tests");

        suite.addTest(new TestSuite(SDOXMLHelperThreadSafetyTestCases.class));

        return suite;
    }

}

Test suite for thread safety tests


package org.hibernate.collection.internal;

import java.util.ArrayList;

/**
 * This is how we tell GWT to serialize the hibernate class PersistentBag.
 * We don't need the real implementation in the UI, and since we only use
 * the List interface, the transformation to ArrayList is valid.
 */
public class PersistentBag extends ArrayList {

}

Allow GWT to work with Hibernate


/*-
 * Copyright (c) 2014 Mikolaj Izdebski
 *
 * 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.lbzip2.impl;

import static org.junit.Assert.assertEquals;
import static org.lbzip2.impl.Utils.insertion_sort;

import java.util.Arrays;
import java.util.Random;

import org.junit.Test;

/**
 * @author Mikolaj Izdebski
 */
public class UtilsTest
{
    private final Random r = new Random( 7541 );

    @Test
    public void testInsertionSort()
    {
        for ( int nRep = 0; nRep < 1000; nRep++ )
        {
            int n = 50 + r.nextInt( 100 );
            long[] A = new long[n];
            for ( int i = 0; i < n; i++ )
                A[i] = r.nextLong();

            long[] B = new long[n];
            System.arraycopy( A, 0, B, 0, n );
            Arrays.sort( B );

            insertion_sort( A, 0, n );

            for ( int i = 0; i < n; i++ )
                assertEquals( B[n - i - 1], A[i] );
        }
    }
}

Add unit test for insertion sort


/*
 * (C) Copyright 2018 Boni Garcia (http://bonigarcia.github.io/)
 *
 * 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 io.github.bonigarcia.wdm.test;

import static org.junit.Assert.assertTrue;

import java.net.MalformedURLException;
import java.net.URL;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.remote.RemoteWebDriver;

/**
 * Test with Android device.
 *
 * @author Boni Garcia (boni.gg@gmail.com)
 * @since 1.0.0
 */
public class AndroidTest {

    private WebDriver driver;

    @Before
    public void setupTest() throws MalformedURLException {
        DesiredCapabilities capabilities = new DesiredCapabilities();
        capabilities.setCapability("platformName", "android");
        capabilities.setCapability("browserName", "browser");
        capabilities.setCapability("deviceName", "Samsung Galaxy S6");
        driver = new RemoteWebDriver(new URL("http://172.17.0.1:4444/wd/hub"),
                capabilities);
    }

    @After
    public void teardown() {
        if (driver != null) {
            driver.quit();
        }
    }

    @Test
    public void test() {
        driver.get("https://en.wikipedia.org/wiki/Main_Page");
        assertTrue(
                driver.getTitle().equals("Wikipedia, the free encyclopedia"));
    }

}

Include test for Android device using RemoteWebDriver


package com.skraylabs.poker.model;

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

import org.junit.Test;

public class CardTest {

  @Test
  public void testGetRank() {
    // Set up
    Card card = new Card(Rank.Ace, Suit.Clubs);
    // Exercise
    Rank rank = card.getRank();
    // Verify
    Rank expectedRank = Rank.Ace;
    assertThat(rank, equalTo(expectedRank));
  }

  @Test
  public void testGetSuit() {
    // Set up
    Card card = new Card(Rank.Eight, Suit.Diamonds);
    // Exercise
    Suit suit = card.getSuit();
    // Verify
    Suit expectedSuit = Suit.Diamonds;
    assertThat(suit, equalTo(expectedSuit));
  }

}

Add some tests for Card class.


package org.micromanager.nativegui;

import javax.swing.JFileChooser;
import java.io.File;

public class NativeGUI {
  public static String runMDABrowser(String startDirectory) {
         JFileChooser fc = new JFileChooser();
         fc.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
         fc.setSelectedFile(new File(startDirectory));
         int retVal = fc.showOpenDialog(null);
         if (retVal == JFileChooser.APPROVE_OPTION) {
            return fc.getSelectedFile().getAbsolutePath();
         } else {
            return "";
        }
  }

}

Put this file back in, needed in Windows.


package liquibase.sqlgenerator.core;

import java.util.Arrays;
import java.util.Date;
import java.util.HashSet;
import liquibase.database.Database;
import liquibase.database.core.MySQLDatabase;
import liquibase.database.typeconversion.TypeConverterFactory;
import liquibase.sqlgenerator.SqlGeneratorChain;
import liquibase.statement.core.InsertOrUpdateStatement;

/**
 *
 * @author Carles
 */
public class InsertOrUpdateGeneratorMySQL extends InsertOrUpdateGenerator {
    @Override
    public boolean supports(InsertOrUpdateStatement statement, Database database) {
         return database instanceof MySQLDatabase;
    }

    @Override
    protected String getInsertStatement(InsertOrUpdateStatement insertOrUpdateStatement, Database database, SqlGeneratorChain sqlGeneratorChain) {
        StringBuffer sql = new StringBuffer(super.getInsertStatement(insertOrUpdateStatement, database, sqlGeneratorChain));
        String updateSql = super.getUpdateStatement(insertOrUpdateStatement, database, "", sqlGeneratorChain);

        sql.deleteCharAt(sql.lastIndexOf(";"));
        sql.append("ON DUPLICATE KEY UPDATE ");
        String[] pkFields=insertOrUpdateStatement.getPrimaryKey().split(",");
        HashSet<String> hashPkFields = new HashSet<String>(Arrays.asList(pkFields));
        for(String columnKey:insertOrUpdateStatement.getColumnValues().keySet())
        {
            if (!hashPkFields.contains(columnKey)) {
                sql.append(columnKey).append(" = ");
                sql.append(convertToString(insertOrUpdateStatement.getColumnValue(columnKey),database));
                sql.append(",");
            }
        }
        sql.deleteCharAt(sql.lastIndexOf(","));

        System.out.println("SQL :" + sql.toString());

        return sql.toString();
    }

    @Override
    protected String getUpdateStatement(InsertOrUpdateStatement insertOrUpdateStatement, Database database, String whereClause, SqlGeneratorChain sqlGeneratorChain) {
        return "";
    }

    @Override
    protected String getRecordCheck(InsertOrUpdateStatement insertOrUpdateStatement, Database database, String whereClause) {
        return "";
    }

    @Override
    protected String getElse(Database database) {
        return "";
    }

    private String convertToString(Object newValue, Database database) {
        String sqlString;
        if (newValue == null || newValue.toString().equals("") || newValue.toString().equalsIgnoreCase("NULL")) {
            sqlString = "NULL";
        } else if (newValue instanceof String && database.shouldQuoteValue(((String) newValue))) {
            sqlString = "'" + database.escapeStringForDatabase(newValue.toString()) + "'";
        } else if (newValue instanceof Date) {
            sqlString = database.getDateLiteral(((Date) newValue));
        } else if (newValue instanceof Boolean) {
            if (((Boolean) newValue)) {
                sqlString = TypeConverterFactory.getInstance().findTypeConverter(database).getBooleanType().getTrueBooleanValue();
            } else {
                sqlString = TypeConverterFactory.getInstance().findTypeConverter(database).getBooleanType().getFalseBooleanValue();
            }
        } else {
            sqlString = newValue.toString();
        }
        return sqlString;
    }
}

Support to loadUpdateDate for MySQL using "INSERT .... ON DUPLICATE KEY UPDATE" syntax.


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

package org.openmhealth.schema.domain.omh;

import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonValue;

import javax.annotation.Nullable;
import java.util.HashMap;
import java.util.Map;

/**
 * A unit of a signal-to-noise ratio.
 *
 * @author Emerson Farrugia
 * @version 1.0
 * @see geoposition
 */
public enum SignalToNoiseRatioUnit implements Unit {

    DECIBEL("dB");

    private String schemaValue;
    private static final Map<String, SignalToNoiseRatioUnit> constantsBySchemaValue = new HashMap<>();

    static {
        for (SignalToNoiseRatioUnit constant : values()) {
            constantsBySchemaValue.put(constant.getSchemaValue(), constant);
        }
    }

    SignalToNoiseRatioUnit(String schemaValue) {
        this.schemaValue = schemaValue;
    }

    @Override
    @JsonValue
    public String getSchemaValue() {
        return this.schemaValue;
    }

    @Nullable
    @JsonCreator
    public static SignalToNoiseRatioUnit findBySchemaValue(String schemaValue) {
        return constantsBySchemaValue.get(schemaValue);
    }
}

Add an enum for SNR units


package org.realityforge.arez.doc.examples.observables;

import org.realityforge.arez.Observable;

public class ObservableExample
{
  private Observable<Integer> _valueObservable;
  private int _value;

  public int getValue()
  {
    _valueObservable.reportObserved();
    return _value;
  }

  public void setValue( final int value )
  {
    if ( value != _value )
    {
      _value = value;
      _valueObservable.reportChanged();
    }
  }
}

Add java code referenced in documentation


package org.apache.aries.subsystem.core.internal;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.fail;

import java.net.MalformedURLException;

import org.junit.Test;

public class LocationTest {
	@Test
	public void testAnyLocationString() {
		String locationStr = "anyLocation";
		try {
			Location location = new Location(locationStr);
			assertNull("Wrong symbolic name", location.getSymbolicName());
			assertEquals("Wrong value", locationStr, location.getValue());
			assertNull("Wrong version", location.getVersion());
			try {
				location.open();
				fail("Opening a location that does not represent a URL should fail");
			}
			catch (MalformedURLException e) {
				// Okay
			}
			catch (Throwable t) {
				t.printStackTrace();
				fail("Wrong exception");
			}
		}
		catch (Throwable t) {
			t.printStackTrace();
			fail("Any location string must be supported");
		}
	}
}

Test support for any location string.


package com.shunix.scavenger.log;

import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Build;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.PrintStream;

/**
 * This class represent a crash
 * Created by shunix on 15-2-2.
 */
public class Crash {
    protected Throwable mException;
    protected Context mContext;
    private StringBuilder mBuilder;

    public Crash(Throwable throwable, Context context) {
        this.mException = throwable;
        this.mContext = context;
    }

    @Override
    public String toString() {
        if (mBuilder != null) {
            return mBuilder.toString();
        }
        mBuilder = new StringBuilder();
        mBuilder.append(getPackageInfo());
        mBuilder.append(getDeviceInfo());
        if (mException != null) {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            try {
                mException.printStackTrace(new PrintStream(baos));
                mBuilder.append(new String(baos.toByteArray()));
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (baos != null) {
                    try {
                        baos.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
        return mBuilder.toString();
    }

    protected String getPackageInfo() {
        String packageInfoString = "";
        if (mContext == null) {
            return "";
        }
        PackageManager packageManager = mContext.getPackageManager();
        try {
            PackageInfo packageInfo = packageManager.getPackageInfo(mContext.getPackageName(), PackageManager.GET_ACTIVITIES);
            StringBuilder stringBuilder = new StringBuilder();
            stringBuilder
                    .append("Package Name: ")
                    .append(packageInfo.packageName)
                    .append(" Package Version Name: ")
                    .append(packageInfo.versionName)
                    .append(" Package Version Code: ")
                    .append(packageInfo.versionCode)
                    .append("\n");
            packageInfoString = stringBuilder.toString();
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return packageInfoString;
    }

    protected String getDeviceInfo() {
        if (mContext == null) {
            return "";
        }
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder
                .append("Device Model: ")
                .append(Build.MODEL)
                .append(" Android Version: ")
                .append(Build.VERSION.RELEASE)
                .append("\n");
        return stringBuilder.toString();
    }
}

Add a class to represent crash


/*
 * ServeStream: A HTTP stream browser/player for Android
 * Copyright 2010 William Seemann
 *
 * 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 net.sourceforge.servestream.transport;

public class ProtocolFactory {

	public static final String HTTP_HINT = "hostname/path";
	public static final String HTTPS_HINT = "hostname/path";

	/**
	 * Default constructor
	 */
	public ProtocolFactory() {

	}

	/**
	 * Returns a hint for the protocol passed in
	 *
	 * @param protocol The protocol
	 * @return String The hint for the protocol
	 */
	public static String getProtocolHint(String protocol) {
		if (protocol.equals("http")) {
			return HTTP_HINT;
		} else if (protocol.equals("https")) {
			return HTTPS_HINT;
		} else {
			return null;
		}
	}

	/**
	 *
	 *
	 * @param scheme
	 * @return String Protocol
	 */
	public static String getProtocol(String scheme) {
		if (scheme.equals("http")) {
			return "http://";
		} else if (scheme.equals("https")) {
			return "https://";
		} else {
			return null;
		}
	}

}

Add class for protocol spinner


package learn_to_code.java_api.net.local_multiple_times_one_connection;

import learn_to_code.java_api.net.local_one_time_one_connection.SimpleNetworkProtocol;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * This server will open port 10000 on your machine (Can be changed obviously), accept a SINGLE connection but do not shutdown
 * after the first connection ends. If multiple clients try to connect simultaneously, they will be blocked,
 * because a client connection cannot proceed unless the server makes a call to accept() method
 * <br>
 * The communication is defined by {@link SimpleNetworkProtocol} class
 * Client can be {@link learn_to_code.java_api.net.local_one_time_one_connection.SingleConnectionLocalClient}
 */
public class SingleConnectionNoShutdownLocalServer {
    public static void main(String[] args) throws IOException {

        try (ServerSocket serverSocket = new ServerSocket(10000)) {
            while (true) {

                /* This call will block, until first user finishes his requests, after this,
                 * server will return to waiting state and wait for another user.
                 * The only way to shutdown this server is to kill JVM where it is running.
                 * Most of the time, you'll need to implement a better way to shutdown server
                 * something like polling on server-shutdown signal once in a while
                 */
                createAndKeepConnection(serverSocket);

            }
        }
    }

    private static void createAndKeepConnection(ServerSocket serverSocket) {
        try (
                Socket clientSocket = serverSocket.accept();
                PrintWriter toClient =
                        new PrintWriter(clientSocket.getOutputStream(), true);
                BufferedReader fromClient = new BufferedReader(
                        new InputStreamReader(clientSocket.getInputStream()));
        ) {
            SimpleNetworkProtocol protocol = new SimpleNetworkProtocol(fromClient, toClient);

            protocol.initialMessage();
            /* This call will not return unless user ends connection with 'bye' response */
            protocol.proceedData();
            protocol.lastMessage();

        } catch (IOException e) {
            System.out.println("Connection error!");
            e.printStackTrace();
        }
    }
}

Add local server-client over socket example where server does not shutdown instantly, when the connection ends


package org.lantern;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetSocketAddress;

import javax.net.ssl.SSLSocket;
import javax.net.ssl.SSLSocketFactory;

import org.apache.commons.io.IOUtils;

import com.google.common.base.Charsets;

public class HostSpoofingTest {

    public static void main(final String... args) throws Exception {
        final SSLSocket sock = (SSLSocket) SSLSocketFactory.getDefault().createSocket();
        sock.connect(new InetSocketAddress("www.google.com", 443), 10000);

        OutputStream os = null;
        try {
            os = sock.getOutputStream();
            writeHttpRequest(os);
            readResponse(sock.getInputStream());
        } finally {
            IOUtils.closeQuietly(os);
        }
    }

    private static void readResponse(InputStream inputStream) throws IOException {
        /*
        BufferedReader br = null;
        br = new BufferedReader(new InputStreamReader(inputStream));
        String cur = br.readLine();
        while (!StringUtils.isEmpty(cur)) {
            System.err.println(cur);
            cur = br.readLine();
        }
        */
        final byte[] body = new byte[1200];
        inputStream.read(body);
        System.err.println(new String(body, "UTF-8"));
    }

    private static void writeHttpRequest(final OutputStream os) throws IOException {
        os.write("GET / HTTP/1.1\r\n".getBytes(Charsets.UTF_8));
        //os.write("Host: lantern-compute-engine-test.c.o59bxf5.internal\r\n".getBytes(Charsets.UTF_8));
        //os.write("Host: 23.236.59.9\r\n".getBytes(Charsets.UTF_8));
        os.write("Host: 10.240.200.99\r\n".getBytes(Charsets.UTF_8));
        os.write("\r\n".getBytes(Charsets.UTF_8));
    }

}

Test for host spoofing on different sites


package org.apache.markt.leaks.java2d;

import org.apache.markt.leaks.LeakBase;

/**
 * Java 5
 *  - update 22 - leaks
 * Java 6
 *  - update =<00 - leaks
 *    ??? when was this fixed ???
 *  - update >=45 - no leak
 * Java 7 - no leak
 * Java 8 - no leak
 */
public class Java2dDisposerThreadLeak extends LeakBase {

    public static void main(String[] args) {
        Java2dDisposerThreadLeak java2dDisposerThreadLeak = new Java2dDisposerThreadLeak();
        java2dDisposerThreadLeak.doLeakTest();
    }

    @Override
    protected void createLeakingObjects() {
        try {
            Class.forName("sun.java2d.Disposer");
        } catch (ClassNotFoundException e) {
            RuntimeException r = new RuntimeException();
            r.initCause(e);
            throw r;
        }
    }

    @Override
    protected void cleanUpLeakingObjects() {
        // None
    }
}

Add Java 2D Disposer thread leak test


/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package epfc.cours3449;

/**
 *
 * @author jedepaepe
 */
public class lesson11 {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // TODO code application logic here
    }

}

Create first class in repository


package org.twig.functional;

import org.junit.Assert;
import org.junit.Test;
import org.twig.exception.TwigException;

import java.util.HashMap;

public class RenderLogicTests extends FunctionalTests {
    @Test
    public void canRenderPlainBoolean() throws TwigException {
        HashMap<String, String> templates = new HashMap<>();
        templates.put("foo.twig", "{{ true }}");
        setupEnvironment(templates);

        Assert.assertEquals("Bool should render text bool", "true", environment.render("foo.twig"));
    }
}

Add a functional test suite for logic


// 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;

import com.google.sps.data.ProductDetectionData;

/**
 * Interface for ProductDetectionAPIImpl, respective FakeProductDetectionAPI, used for testing.
 */
public interface ProductDetectionAPI {
  public ProductDetectionData detectProductPhotoContent(byte[] imageBytes) throws PhotoDetectionException;
}

Create interface for product detection classes


package org.opendroidphp.app.common.tasks;

import org.opendroidphp.app.Constants;
import org.opendroidphp.app.common.shell.SH;

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

public class DestroyServer implements Runnable {

    @Override
    public void run() {

        initialize();
    }

    protected void initialize() {

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

        command.add(Constants.BUSYBOX_SBIN_LOCATION + " killall lighttpd");
        command.add(Constants.BUSYBOX_SBIN_LOCATION + " killall mysqld");
        command.add(Constants.BUSYBOX_SBIN_LOCATION + " killall php");

        SH.run(command);
    }
}

Destroy the running web servers process


import java.util.*;

public class Solution {

    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);

        if(!scan.hasNext()) {
            System.out.print(0);
            scan.close();
            return;
        }

        String sentence = scan.nextLine().trim();
        scan.close();

        String delimeters = "[ !,?._'@]+";
        String[] tokens = sentence.split(delimeters);
        System.out.println(tokens.length);
        for (String token: tokens) {
            System.out.println(token);
        }
    }
}

Solve java string tokens, test case 9 stinks


package Utils;

import java.io.IOException;

import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
import javax.sound.sampled.DataLine;
import javax.sound.sampled.LineUnavailableException;

public class Player {
	public static void playStream(AudioInputStream inputStream) {
		AudioFormat format = inputStream.getFormat();
		DataLine.Info info = new DataLine.Info(Clip.class, format);
		Clip clip;

		try {
			clip = (Clip) AudioSystem.getLine(info);
			clip.open(inputStream);
			clip.start();
		} catch (LineUnavailableException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}

Add utility class for playing streams


package com.aviras.mrassistant.models;

import io.realm.RealmModel;
import io.realm.RealmObject;
import io.realm.annotations.PrimaryKey;

/**
 * Unit for medicines
 * <p/>
 * Created by ashish on 8/6/16.
 */
public class Unit extends RealmObject {

    @PrimaryKey
    private int id;

    private String name;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

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

Add unit model to represent unit for medicine


package org.cyclops.commoncapabilities.modcompat.tconstruct.capability.work;

import org.cyclops.commoncapabilities.api.capability.work.IWorker;
import slimeknights.tconstruct.gadgets.tileentity.TileDryingRack;

/**
 * Worker capability for the drying rack.
 * @author rubensworks
 */
public class TileDryingRackWorker implements IWorker {

    private final TileDryingRack tile;

    public TileDryingRackWorker(TileDryingRack tile) {
        this.tile = tile;
    }

    @Override
    public boolean hasWork() {
        return !tile.getStackInSlot(0).isEmpty();
    }

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

}

Add worker capability for TCon's Drying Rack


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

package com.foundationdb.util;

public class FileTestUtils {

    public static void printClickableFile(String filename, String suffix, int lineNumber) {
        if (filename != null) {
            try {
                System.err.println("  at " + filename.replace("src/test/resources/", "").
                        replaceFirst("/([^/]+.)$", "($1." + suffix + ":" + lineNumber + ")").replaceAll("/", "."));
                // for those running from maven or elsewhere
                System.err.println("  aka: " + filename + "." + suffix + ":" + lineNumber);
            } catch (Exception e) {
                System.err.println("Tried to write filename but failed: " +
                        filename + "." + suffix + ":" + lineNumber + " -- " + e.getMessage());
            }
        } else {
            System.err.println("NULL filename");
        }
    }
}

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

package com.foundationdb.util;

public class FileTestUtils {

    public static void printClickableFile(String filename, String suffix, int lineNumber) {
        if (filename != null) {
            System.err.println("  at " + filename.replace("src/test/resources/", "").
                    replaceFirst("/([^/]+.)$", "($1." + suffix + ":" + lineNumber + ")").replaceAll("/", "."));
            // for those running from maven or elsewhere
            System.err.println("  aka: " + filename + "." + suffix + ":" + lineNumber);
        } else {
            System.err.println("NULL filename");
        }
    }
}

Revert "Made printClickableFilename more robust"


import java.time.LocalDateTime;
import java.util.Random;
import java.util.stream.Collectors;

/**
 * This class is used to generate sample data.
 */
public class Generator {

    private static final String[] levels = {"VERBOSE", "DEBUG", "INFO", "WARN", "ERROR"};

    private static final String[] classes =
            {"com.amadeus.DataMap", "org.bigfoot.Toe", "java.util.Map", "com.fizzy.Twizzer", "org.whynot.Question",
                    "com.enterprise.Business"};

    private static final String[] nouns = {"file", "message", "id", "PNR", "reservation", "service", "class", "object"};

    private static final String[] participates = {"found", "deleted", "inserted", "retrieved", "read", "downloaded", "accessed", "returned"};

    private static final String[] verbs = {"cannot be", "was", "has been", "could not be"};

    private final Random random = new Random();

    public static void main(String[] args) {
        new Generator().generate();
    }

    private void generate() {
        String format = "<%s> <%s> <%s> <> <%s;jsessionid=%s>%n";

        for (int i = 0; i < 600; i++) {
            System.out.printf(format, LocalDateTime.now(), rand(levels), rand(classes), randMsg(), randSID());
        }
    }

    private String rand(String[] array) {
        return array[random.nextInt(array.length)];
    }

    private String randMsg() {
        return String.format("The %s %s %s", rand(nouns), rand(verbs), rand(participates));
    }

    private String randSID() {
        return random.ints(16, 0, 0xFFFF).mapToObj(Integer::toHexString).collect(Collectors.joining());
    }
}

Add log generator to have test data


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.EntityNotFoundException;
import com.google.appengine.api.datastore.KeyFactory;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/envStatus")
public class GetEnvStatus extends HttpServlet {
  @Override
  protected void doGet(HttpServletRequest req, HttpServletResponse resp)
      throws ServletException, IOException {
    String envID = req.getParameter("envID");

    try {
      DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
      Entity e = datastore.get(KeyFactory.stringToKey(envID));

      resp.getWriter().print(e.getProperty("status"));
    } catch (EntityNotFoundException e) {
      resp.sendError(HttpServletResponse.SC_NOT_FOUND);
    }
  }
}

Add a servlet to get the status of an image pull.


package ruke.vrj.compiler;

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

/**
 * MIT License
 *
 * Copyright (c) 2017 Franco Montenegro
 *
 * 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.
 */
public class GlobalVariableTest {

  @Test
  public void define() {
    final String code = String.join("\n",
        "globals",
          "integer i",
          "constant integer e = 3",
          "string array s",
        "endglobals"
    );

    final Compiler compiler = new Compiler();

    compiler.compile(code);

    Assert.assertTrue(compiler.getResults().isEmpty());
  }

  @Test
  public void alreadyDefined() {
    final String code = String.join("\n",
        "globals",
          "integer i",
          "string i",
        "endglobals"
    );

    final Compiler compiler = new Compiler();

    compiler.compile(code);

    Assert.assertEquals(1, compiler.getResults().size());
    Assert.assertEquals(
        "(3,7,8): Symbol i is already defined in (2,8,9)",
        compiler.getResults().get(0).toString()
    );
  }

}

Add global variables compiler test


package leetcode.h_index;

import java.util.Arrays;

public class Solution {
    public int hIndex(int[] citations) {
        if(citations == null || citations.length == 0) return 0;
        Arrays.sort(citations);
        int ans = 0;
        int size = citations.length;
        for(int i = 1; i <= size; i++){
            if(citations[size - i] >= i){
                if(i < size){
                    if(citations[size - i - 1] <= i){
                        ans = i;
                    }
                }else{
                    ans = i;
                }
            }
        }
        return ans;
    }
}

Add java solution for 274. H-Index


package galileo.comm;

import galileo.event.EventMap;

public class GalileoEventMap extends EventMap {
    public GalileoEventMap() {
        addMapping(StorageEvent.class);
        addMapping(StorageRequest.class);

        addMapping(QueryEvent.class);
        addMapping(QueryRequest.class);
        addMapping(QueryPreamble.class);
        addMapping(QueryResponse.class);
    }
}

Add a galileo-net event mapper


import java.util.Scanner;

/**
 * This program prints out a specified amount of the Fibonacci Sequence
 **/
public class Fibonacci {
    public static void main(String[] args) {
        int a = 0, b = 1, c, count = 2;
        System.out.println("How many Fibonacci numbers do you need?");
        Scanner m = new Scanner(System.in);
        int limit = m.nextInt();

        // Hard code small limits
        if (limit == 1) {
            System.out.println("0");
        } else if (limit == 2) {
            System.out.println("0 1");
        } else {
            System.out.print(a + " " + b + " ");
            while (count < limit) {
                c = a + b;
                a = b;
                b = c;
                count++;
                System.out.print(c + " ");
            }
            System.out.println();
        }
    }
}

Add problem 9 to unit 1


package uk.gov.migration;

import org.flywaydb.core.api.migration.MigrationChecksumProvider;
import org.flywaydb.core.api.migration.jdbc.BaseJdbcMigration;

import java.sql.Connection;
import java.sql.Statement;

public class V__16_AddOrderToBlobs extends BaseJdbcMigration implements MigrationChecksumProvider {
    @Override
    public void migrate(Connection connection) throws Exception {
        Statement stmt = connection.createStatement();

        try {
            stmt.execute("alter table item add column item_order serial");

            // Work out the order of an item using the entries and system entries that reference it
            // since the two logs are independent, smoosh them together and treat the system entries
            // as coming first.
            stmt.execute("" +
                    "with all_entry as (\n" +
                    "  select * from entry union all select * from entry_system\n" +
                    ")\n" +
                    ", combined_log as (\n" +
                    "  select sha256hex, row_number() over(order by type::text,entry_number) as combined_entry_number, row_number() over(partition by sha256hex order by type::text, entry_number) as item_entry_number from all_entry\n" +
                    ")\n" +
                    ", first_snapshot as (\n" +
                    "  select sha256hex, combined_entry_number from combined_log where item_entry_number=1\n" +
                    ")\n" +
                    "\n" +
                    "update item set item_order=first_snapshot.combined_entry_number from first_snapshot where item.sha256hex=first_snapshot.sha256hex");

            stmt.execute("alter table item alter column item_order set not null");

        } finally {
            stmt.close();
        }
    }

    @Override
    public Integer getChecksum() {
        return 1;
    }
}

Add an order field to the items table


package fgis.server.support.geojson;

import java.util.HashMap;
import javax.json.JsonValue;
import org.geolatte.geom.Envelope;
import org.geolatte.geom.Geometry;
import org.geolatte.geom.crs.CrsId;
import org.geolatte.geom.crs.CrsRegistry;
import org.testng.annotations.Test;
import static org.testng.Assert.*;

public final class GjElementTest
  extends AbstractGjElementTest
{
  @Test
  public void basicInteraction()
    throws Exception
  {
    final Geometry geometry = fromWkT( "POINT (1 1)" );
    final CrsId crsId = CrsRegistry.getCrsIdForEPSG( 1234 );
    final Envelope bbox = new Envelope( 0, 0, 2, 2, crsId );
    final HashMap<String, JsonValue> additional = new HashMap<>();
    additional.put( "foo", JsonValue.FALSE );
    final GjGeometry e = new GjGeometry( geometry, crsId, bbox, additional );
    assertEquals( e.getGeometry(), geometry );
    assertEquals( e.getBBox(), bbox );
    assertEquals( e.getCrsId(), crsId );
    assertEquals( e.getAdditionalProperties(), additional );
    assertPropertyAllowed( e, "X" );
    assertPropertyNotAllowed( e, "crs" );
    assertPropertyNotAllowed( e, "bbox" );
    assertPropertyNotAllowed( e, "type" );
  }

  @Test
  public void nullMetadata()
    throws Exception
  {
    final Geometry geometry = fromWkT( "POINT (1 1)" );
    final GjGeometry e = new GjGeometry( geometry, null, null, null );
    assertEquals( e.getGeometry(), geometry );
    assertNull( e.getBBox() );
    assertNull( e.getCrsId() );
    assertEquals( e.getAdditionalProperties().size(), 0 );
  }

  @Test
  public void invalidAdditionalData()
    throws Exception
  {
    verifyAdditionalDataRestricted( "type" );
    verifyAdditionalDataRestricted( "crs" );
    verifyAdditionalDataRestricted( "bbox" );
  }

  private void verifyAdditionalDataRestricted( final String key )
  {
    final HashMap<String, JsonValue> additional = new HashMap<>();
    additional.put( key, JsonValue.FALSE );
    try
    {
      new GjGeometry( fromWkT( "POINT (1 1)" ), null, null, additional );
    }
    catch ( final IllegalArgumentException e )
    {
      return;
    }
    fail( "Expected to receive an exception for addition data: " + additional );
  }
}

Add some simple tests around element functionality


package utask.model.task;

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

import org.junit.Test;

//@@author A0138423J
public class StatusTest {

    @Test
    public void isValidTimestamp() {
        // blank Status
        assertFalse(Status.isValidBoolean("")); // empty string
        assertFalse(Status.isValidBoolean(" ")); // spaces only

        // missing parts
        assertFalse(Status.isValidBoolean("TRU")); // Upper case with incomplete
                                                   // spelling
        assertFalse(Status.isValidBoolean("complet")); // Lower case with
                                                       // incomplete spelling

        // invalid parts
        assertFalse(Status.isValidBoolean("0")); // integer
        assertFalse(Status.isValidBoolean("1.0")); // double
        assertFalse(Status.isValidBoolean("@$#%")); // symbols
        assertFalse(Status.isValidBoolean("accomplished")); // strings

        // valid timestamp
        assertTrue(Status.isValidBoolean("TRUE"));
        assertTrue(Status.isValidBoolean("false"));
        assertTrue(Status.isValidBoolean("YES"));
        assertTrue(Status.isValidBoolean("no"));
        assertTrue(Status.isValidBoolean("Complete"));
        assertTrue(Status.isValidBoolean("Incomplete"));
    }

}

Add unit test for Status


import db.DBConnection;

public class StudyStatus {
    private DBConnection dbConn;

    public static void main(String[] argv) {
        StudyStatus instance = new StudyStatus();
        instance.initialize();
        instance.run();
    }

    private void connect() {
        this.dbConn = DBConnection.getInstance();
    }

    protected void initialize() {
        this.connect();
    }

    protected void run() {

    }
}

Add some basic classes for the start of the project


package com.sendgrid;

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

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.Calendar;

public class LicenseTest {

    @Test
    public void testLicenseShouldHaveCorrectYear() throws IOException {
        String copyrightText = null;
        try (BufferedReader br = new BufferedReader(new FileReader("./LICENSE.md"))) {
            for (String line; (line = br.readLine()) != null; ) {
                if (line.startsWith("Copyright")) {
                    copyrightText = line;
                    break;
                }
            }
        }
        String expectedCopyright = String.format("Copyright (c) 2016-%d SendGrid, Inc.", Calendar.getInstance().get(Calendar.YEAR));
        Assert.assertEquals("License has incorrect year", copyrightText, expectedCopyright);
    }
}

Test to check year in license file


package design_patterns.observer_design_pattern;
import design_patterns.observer_design_pattern.Observer;
import design_patterns.observer_design_pattern.Subject;
import design_patterns.observer_design_pattern.ModeChanger;
import design_patterns.observer_design_pattern.ModeObserver;

/*
	Class to test Observer Design Pattern
*/

class TestObserver{

	public static void testA(){

		// Create ModeChanger
		ModeChanger mc = new ModeChanger();

		// Create three subscribers
		ModeObserver ob1 = new ModeObserver();
		ModeObserver ob2 = new ModeObserver();
		ModeObserver ob3 = new ModeObserver();

		// Change mode
		System.out.println("\nChanging Mode to set");
		mc.set();

		// ob1 subscribes
		ob1.subscribe(mc);

		// Change mode
		System.out.println("\nChanging Mode to reset");
		mc.reset();

		// ob2 subscribes
		ob2.subscribe(mc);

		// Change mode set
		System.out.println("\nChanging Mode to set");
		mc.set();

		// ob1 unsubscribes
		ob1.unsubscribe(mc);

		// Change mode
		System.out.println("\nChanging Mode to reset");
		mc.reset();

		// ob2 unsubscribes
		ob2.unsubscribe(mc);

		// Change mode set
		System.out.println("\nChanging Mode to set");
		mc.set();

		// ob3 subscribes
		ob3.subscribe(mc);

		// Change mode
		System.out.println("\nChanging Mode to reset");
		mc.reset();

	}

	public static void main(String args[]){

		testA();
	}

}

Add test class for observer design pattern


package com.google.sps.servlets;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.Process;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.ArrayList;
import java.util.Arrays;
import com.google.gson.Gson;

/** Servlet that actions items.*/
@WebServlet("/actions")
public class ActionsServlet extends HttpServlet {

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

  @Override
  public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
    List<String> jsonResultList = new ArrayList<>();
    String apiKey = "API_KEY"; //Insert the API_KEY here for testing
    for (String term : terms) {
      String queryTerm = encodeTerm(term);
      String jsonResult = curlProjects(apiKey, queryTerm);
      jsonResultList.add(jsonResult);
    }

    String jsonResultString = "{\"results\": ["+String.join(",", jsonResultList)+"]}";
    response.setContentType("application/json;");
    response.getWriter().println(jsonResultString);
  }

  private String encodeTerm(String term) throws RuntimeException {
    try {
        return URLEncoder.encode(term, StandardCharsets.UTF_8.toString());
    } catch (UnsupportedEncodingException ex) {
        throw new RuntimeException(ex.getCause());
    }
  }

  private String curlProjects(String apiKey, String queryTerm) throws IOException{
    String path = "https://api.globalgiving.org/api/public/services/search/projects";
    String queryString = String.format("?api_key=%s&q=%s", apiKey, queryTerm);

		String[] curlCommand = { "curl", "-H", "Accept: application/json", "-H", "Content-Type: application/json", "-X", "GET", path+queryString};
    ProcessBuilder process = new ProcessBuilder(curlCommand);
		Process p = process.start();
    BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
    StringBuilder builder = new StringBuilder();
    String line = null;
    while ((line = reader.readLine()) != null) {
      builder.append(line);
      builder.append(System.getProperty("line.separator"));
    }
    return builder.toString();
  }
}

Add java servlet to get action items


package cn.libofeng.air.core;

public class ServiceException extends RuntimeException {
    /**
     * Constructs a new runtime exception with {@code null} as its
     * detail message.  The cause is not initialized, and may subsequently be
     * initialized by a call to {@link #initCause}.
     */
    public ServiceException() {
        super();
    }

    /**
     * Constructs a new runtime exception with the specified detail message.
     * The cause is not initialized, and may subsequently be initialized by a
     * call to {@link #initCause}.
     *
     * @param message the detail message. The detail message is saved for
     *                later retrieval by the {@link #getMessage()} method.
     */
    public ServiceException(String message) {
        super(message);
    }

    /**
     * Constructs a new runtime exception with the specified detail message and
     * cause.
Note that the detail message associated with
     * {@code cause} is not automatically incorporated in
     * this runtime exception's detail message.
     *
     * @param message the detail message (which is saved for later retrieval
     *                by the {@link #getMessage()} method).
     * @param cause   the cause (which is saved for later retrieval by the
     *                {@link #getCause()} method).  (A <tt>null</tt> value is
     *                permitted, and indicates that the cause is nonexistent or
     *                unknown.)
     * @since 1.4
     */
    public ServiceException(String message, Throwable cause) {
        super(message, cause);
    }

    /**
     * Constructs a new runtime exception with the specified cause and a
     * detail message of <tt>(cause==null ? null : cause.toString())</tt>
     * (which typically contains the class and detail message of
     * <tt>cause</tt>).  This constructor is useful for runtime exceptions
     * that are little more than wrappers for other throwables.
     *
     * @param cause the cause (which is saved for later retrieval by the
     *              {@link #getCause()} method).  (A <tt>null</tt> value is
     *              permitted, and indicates that the cause is nonexistent or
     *              unknown.)
     * @since 1.4
     */
    public ServiceException(Throwable cause) {
        super(cause);
    }
}

Add an base service exception.


package main.java;

import de.proteinms.xtandemparser.xtandem.*;
import de.proteinms.xtandemparser.interfaces.Modification;
import org.junit.Test;
import static org.junit.Assert.fail;
import org.xml.sax.SAXException;

import java.util.ArrayList;

public class XTandemFileTest {

    XTandemFile xTandemFile;
    public XTandemFileTest(){
        try {
            xTandemFile = new XTandemFile("C:/Users/User/IntelliJ_workspace/XTandem-Parser/orbitrap001756.xml");
            //xTandemFile = new XTandemFile("C:/Users/User/IntelliJ_workspace/XTandem-Parser/orbitrap001888.xml");

        } catch (SAXException saxException) {
                    saxException.getMessage();
        }
    }

    /**
     * Test the support data.
     */
    @Test
	public void testSupportData() {
		try {
		xTandemFile.getSupportData(1);
		} catch (Exception e) {
			e.printStackTrace();
			fail();
		}
	}

    @Test
    public void testVariableModificationMap() {
        try {
            ModificationMap modMap = xTandemFile.getModificationMap();
            ArrayList<Modification> varModList = modMap.getVariableModifications("2433.1.1");
            if (varModList.size() > 0) {
                for (Modification varMod : varModList) {
                    System.out.println("varMod name: " + varMod.getName());
                    System.out.println("varMod mass: " + varMod.getMass());
                    System.out.println("varMod location: " + varMod.getLocation());
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
            fail();
        }
    }

     @Test
    public void testFixedModificationMap() {
        try {
            ModificationMap modMap = xTandemFile.getModificationMap();
            ArrayList<Modification> fixedModList = modMap.getFixedModifications("2433.1.1");
            if (fixedModList.size() > 0) {
                for (Modification fixedMod : fixedModList) {
                    System.out.println("varMod name: " + fixedMod.getName());
                    System.out.println("varMod mass: " + fixedMod.getMass());
                    System.out.println("varMod location: " + fixedMod.getLocation());
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            fail();
        }
    }

    @Test
    public void testInputParams() {
        try {
            InputParams inputParams = xTandemFile.getInputParameters();
            System.out.println("modification mass: " + inputParams.getResidueModMass());
            System.out.println("potential modification mass: " + inputParams.getResiduePotModMass());
        } catch (Exception e) {
            e.printStackTrace();
            fail();
        }
    }
}

Test cases for the XTandemFile


package org.barbon.acash.compat;

import android.app.ListActivity;
import android.app.Dialog;

import android.os.Bundle;

import android.view.KeyEvent;

public class CompatListActivity extends ListActivity {
    // emulate onBackPressed for Android 1.6
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode != KeyEvent.KEYCODE_BACK)
            return super.onKeyDown(keyCode, event);

        onBackPressed();

        return true;
    }

    public void onBackPressed() {
        finish();
    }

    // Android 1.6 compatibility
    protected Dialog onCreateDialog(int id) {
        return onCreateDialog(id, null);
    }

    protected Dialog onCreateDialog(int id, Bundle bundle) {
        return null;
    }
}

Add Android 1.6 compatibility class for ListActivity.


/*
 *  JavaSMT is an API wrapper for a collection of SMT solvers.
 *  This file is part of JavaSMT.
 *
 *  Copyright (C) 2007-2016  Dirk Beyer
 *  All rights reserved.
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */

package org.sosy_lab.java_smt.api;

/**
 * Possible floating point rounding modes.
 */
public enum FloatingPointRoundingMode {
  NEAREST_TIES_TO_EVEN,
  NEAREST_TIES_AWAY,
  TOWARD_POSITIVE,
  TOWARD_NEGATIVE,
  TOWARD_ZERO
}

Add a class to represent floating point rounding mode.


package org.webassembly.annotation;

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

@Retention(RetentionPolicy.CLASS)
@Target(ElementType.METHOD)
public @interface Export {

    String name() default "";
}

Add export annotation to mark methods for export


package com.itmill.toolkit.tests.components.combobox;

import java.util.Date;

import com.itmill.toolkit.data.Item;
import com.itmill.toolkit.terminal.Resource;
import com.itmill.toolkit.terminal.ThemeResource;
import com.itmill.toolkit.tests.components.TestBase;
import com.itmill.toolkit.ui.ComboBox;

public class ComboBoxLargeIcons extends TestBase {

    @Override
    protected Integer getTicketNumber() {
        return null;
    }

    @Override
    protected String getDescription() {
        return "All items in the Combobox has large icons. The size of the dropdown should fit the contents, also when changing pages. The size of the shadow behind the dropdown must also be correctly sized. Note that the image URL change for every restart to keep the browser from using cached images.";
    }

    @Override
    protected void setup() {
        ComboBox cb = new ComboBox();
        cb.addContainerProperty("icon", Resource.class, null);
        cb.setItemIconPropertyId("icon");
        getLayout().addComponent(cb);
        cb.setNullSelectionAllowed(false);
        String[] icons = new String[] { "folder-add", "folder-delete",
                "arrow-down", "arrow-left", "arrow-right", "arrow-up",
                "document-add", "document-delete", "document-doc",
                "document-edit", "document-image", "document-pdf",
                "document-ppt", "document-txt", "document-web", "document-xls",
                "document" };
        for (String icon : icons) {
            Item item = cb.addItem(new Object());
            item.getItemProperty("icon").setValue(
                    new ThemeResource("icons/64/" + icon + ".png?"
                            + new Date().getTime()));
        }

    }
}

Test case for ComboBox containing large icons


package info.u_team.u_team_core.util;

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

import org.objectweb.asm.Type;

import net.minecraftforge.fml.ModList;
import net.minecraftforge.forgespi.language.ModFileScanData.AnnotationData;

public class AnnotationUtil {

	public static List<AnnotationData> getAnnotations(String modid, Type type) {
		return ModList.get() //
				.getModFileById(modid) //
				.getFile() //
				.getScanResult() //
				.getAnnotations() //
				.stream() //
				.filter(data -> type.equals(data.getAnnotationType())) //
				.collect(Collectors.toList());
	}

}

Add annotation util to get all annotations of a mod by type


package org.bouncycastle.crypto.tls;

/**
 * RFC 5246
 */
public class PRFAlgorithm {
    /*
     * Note that the values here are implementation-specific and arbitrary. It is recommended not to
     * depend on the particular values (e.g. serialization).
     */
    public static final int tls_prf_sha256 = 0;
}

Add new enumeration from RFC 5246


package nl.fifth.postulate.bin;

import nom.tam.fits.BinaryTableHDU;
import nom.tam.fits.Fits;
import nom.tam.fits.FitsException;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.awt.image.WritableRaster;
import java.io.File;
import java.io.IOException;

import static java.lang.Math.floor;

public class Info {
    public static void main(String[] args) throws FitsException, IOException {
        String filename = args[0];
        Fits f = new Fits(filename);
        BinaryTableHDU hdu = (BinaryTableHDU) f.getHDU(1);
        hdu.info(System.out);
    }
}

Create a binary to read information of the headers


package leetcode.best_time_to_buy_and_sell_stock_ii;

public class Solution {
	public int maxProfit(int[] prices) {
        int buy = 0;
        int profit = 0;
        for(int i = 1; i <= prices.length; i++){
            if(i == prices.length || prices[i] < prices[i - 1]){
                profit += prices[i - 1] - prices[buy];
                buy = i;
            }
        }
        return profit;
    }

	public static void main(String[] args){
		Solution sol = new Solution();
		System.err.println("" + sol.maxProfit(new int[]{3,1,4,1,5,9,2,6,5,3,5,8,9,7,9,3,2,3,8,4,6}));
	}
}

Add java solution for 122. Best Time to Buy and Sell Stock II


/*
 * Created on Mar 21, 2005
 *
 * To change the template for this generated file go to
 * Window>Preferences>Java>Code Generation>Code and Comments
 */
package org.objectweb.proactive.ext.webservices;

import org.apache.soap.util.xml.QName;

import java.math.BigDecimal;

import java.util.Date;
import java.util.GregorianCalendar;
import java.util.Vector;

/**
 * @author vlegrand
 * Utility constants for deploying active objects and components as Web Services
 */
public class WSConstants {
    public static final String PROACTIVE_PROVIDER = "org.objectweb.proactive.ext.webservices.soap.ProActiveProvider";
    public static final String PROACTIVE_STUB = "Stub";
    public static final String WSDL_FILE = "Wsdl";
    public static final String ROUTER = "/soap/servlet/rpcrouter";
    public static final String DOCUMENTATION = "ProActive Active Object";
    public static final String COMPONENT_INTERFACE = "Compoment Interface";
    public static final String URL_PUBLICATION = "URL";
    public static final Vector disallowedMethods = new Vector();

    static {
        disallowedMethods.addElement("equals");
        disallowedMethods.addElement("toString");
        disallowedMethods.addElement("runActivity");
        disallowedMethods.addElement("setProxy");
        disallowedMethods.addElement("getProxy");
        disallowedMethods.addElement("setFcItfName");
        disallowedMethods.addElement("isFcInternalItf");
        disallowedMethods.addElement("setFcOwner");
        disallowedMethods.addElement("setFcIsInternal");
        disallowedMethods.addElement("getFcItfName");
        disallowedMethods.addElement("getFcItfType");
        disallowedMethods.addElement("getFcItfOwner");
        disallowedMethods.addElement("IsFcInternalItf");
        disallowedMethods.addElement("setFcItfImpl");
        disallowedMethods.addElement("getFcItfImpl");
        disallowedMethods.addElement("setFcType");
        disallowedMethods.addElement("getFcItfImpl");
        disallowedMethods.addElement("getFcItfImpl");
        disallowedMethods.addElement("wait");
        disallowedMethods.addElement("notify");
        disallowedMethods.addElement("notifyAll");
        disallowedMethods.addElement("getClass");
        disallowedMethods.addElement("hashCode");
    }

    /* A vector containing all supported types by Apache Soap */
    protected static Vector supportedTypes = new Vector();

    static {
        supportedTypes.addElement(String.class);
        supportedTypes.addElement(Boolean.class);
        supportedTypes.addElement(Boolean.TYPE);
        supportedTypes.addElement(Double.class);
        supportedTypes.addElement(Double.TYPE);
        supportedTypes.addElement(Long.class);
        supportedTypes.addElement(Long.TYPE);
        supportedTypes.addElement(Float.class);
        supportedTypes.addElement(Float.TYPE);
        supportedTypes.addElement(Integer.class);
        supportedTypes.addElement(Integer.TYPE);
        supportedTypes.addElement(Short.class);
        supportedTypes.addElement(Byte.class);
        supportedTypes.addElement(Byte.TYPE);
        supportedTypes.addElement(BigDecimal.class);
        supportedTypes.addElement(GregorianCalendar.class);
        supportedTypes.addElement(Date.class);
        supportedTypes.addElement(QName.class);
    }
}

Add an utility class for web services


import static org.testng.Assert.*;

/**
 * Created by nadia on 02/10/2016.
 */
public class Point3DTest {

    Point3D p ;
    @org.testng.annotations.BeforeMethod
    public void setUp() throws Exception {

    }

    @org.testng.annotations.AfterMethod
    public void tearDown() throws Exception {

    }

    @org.testng.annotations.Test
    public void testTranslate() throws Exception {
        p=new Point3D(1,1,1);
        p.translate(0,0);
        assertEquals(1.0,p.getX());
        assertEquals(1.0,p.getY());
        assertEquals(1.0,p.getZ());
    }

    @org.testng.annotations.Test
    public void testIsOrigin() throws Exception {
         p=new Point3D(0,0,0);
        p.IsOrigin();
        assertEquals(true,p.IsOrigin());
    }

    @org.testng.annotations.Test
    public void testDistance() throws Exception {
         p=new Point3D(1,1,1);
       Point3D  p1=new Point3D(1,1,1);
        p.distance(p1);
        assertEquals(0.0,p.distance(p1));
    }

}

ADD THE TEST OF Point3D


package de.gurkenlabs.litiengine.entities;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;

import org.junit.jupiter.api.Test;

import de.gurkenlabs.litiengine.annotation.MovementInfo;

public class MobileEntityTests {
  @Test
  public void testInitializationByAnnotation() {
    IMobileEntity entity = new TestMobileEntity();

    assertEquals(111, entity.getVelocity().getCurrentValue().intValue());
    assertEquals(222, entity.getAcceleration());
    assertEquals(333, entity.getDeceleration());
    assertFalse(entity.turnOnMove());
  }

  @MovementInfo(velocity = 111, acceleration = 222, deceleration = 333, turnOnMove = false)
  private class TestMobileEntity extends MobileEntity {

  }
}

Add initialization test for the MobileEntity class.


package com.example.profbola.bakingtime.utils;

import android.content.Context;
import android.support.annotation.NonNull;
import android.support.design.widget.Snackbar;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.example.profbola.bakingtime.R;

/**
 * Created by prof.BOLA on 6/29/2017.
 */

public class RecipeAdapter extends RecyclerView.Adapter<RecipeAdapter.RecipeViewHolder> {

    private final Context mContext;

    public RecipeAdapter(@NonNull Context context) {
        mContext = context;
    }

    @Override
    public RecipeViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view  = LayoutInflater.from(parent.getContext())
                                    .inflate(R.layout.recipe_card, parent, false);

        return new RecipeViewHolder(view);
    }

    @Override
    public void onBindViewHolder(RecipeViewHolder holder, int position) {
        Recipe recipe = mRecipes.get(position);
        holder.bind(recipe);
    }

    @Override
    public int getItemCount() {
        return 0;
    }

    public class RecipeViewHolder extends RecyclerView.ViewHolder
            implements View.OnClickListener  {

        public final TextView mTitleView;
        public final TextView mServingsView;
        public final ImageView mRecipeImage;

        public RecipeViewHolder(View view) {
            super(view);

            mTitleView = (TextView) view.findViewById(R.id.recipe_title);
            mRecipeImage = (ImageView) view.findViewById(R.id.recipe_image);
            mServingsView = (TextView) view.findViewById(R.id.recipe_servings);

        }

        @Override
        public void onClick(View v) {
            Snackbar.make(v, "Congrats!!! You Just Clicked a cake!!!! Stay tuned for how to bake!!!", Snackbar.LENGTH_LONG)
                    .setAction("Action", null).show();
        }

        void bind(Recipe recipe) {
            mTitleView.setText(recipe.title);
            mServingsView.setText(recipe.servings);
            int id = mContext.getResources().getIdentifier(recipe.image, "drawable", mContext.getPackageName());
            mRecipeImage.setImageResource(id);
        }
    }
}

Add Adapter for Recipe RecyclerView


package org.webbitserver.helpers;

import org.junit.Test;

import static org.junit.Assert.assertEquals;

public class HexTest {
	@Test
    public void testEncodesByteArray() {
        byte input[] = "hello world".getBytes();
        String expected = "68656C6C6F20776F726C64";
        assertEquals(expected, Hex.toHex(input));
    }

	@Test
	public void testEncodesMultilineByteArray() {
		byte input[] = "the quick\r\nbrown fox\n\njumps over the\nlazy dog".getBytes();
        String expected = "74686520717569636B0D0A62726F776E20666F78" +
        				"0A0A6A756D7073206F766572207468650A6C617A7920646F67";
        assertEquals(expected, Hex.toHex(input));
	}
}

Add tests for Hex.toHex() method


package leetcode;

/**
 * https://leetcode.com/problems/construct-binary-tree-from-inorder-and-postorder-traversal/
 */
public class Problem106 {
    public static class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode(int x) {
            val = x;
        }
    }

    public TreeNode buildTree(int[] inorder, int[] postorder) {
        return null;
    }

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

Create a skeleton for problem 106


/*
 * Copyright 2016 Peter Kenji Yamanaka
 *
 * 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.pyamsoft.pydroid.widget;

import android.content.Context;
import android.util.AttributeSet;
import android.widget.FrameLayout;

public class SquareFrameLayout extends FrameLayout {

  public SquareFrameLayout(Context context) {
    super(context);
  }

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

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

  @SuppressWarnings("SuspiciousNameCombination") @Override
  protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    // Use width for both
    super.onMeasure(widthMeasureSpec, widthMeasureSpec);
  }
}

Add square frame layout widget


package sg.ncl.testbed_interface.repositories.jpa;

import org.springframework.data.annotation.CreatedDate;
import org.springframework.data.annotation.LastModifiedDate;
import org.springframework.data.jpa.domain.support.AuditingEntityListener;

import javax.persistence.Column;
import javax.persistence.EntityListeners;
import javax.persistence.MappedSuperclass;
import java.time.ZonedDateTime;

/**
 * @author Christopher Zhong
 */
@MappedSuperclass
@EntityListeners({AuditingEntityListener.class})
public class AbstractEntity {

//    @Column(name = "creadted_by")
//    @CreatedBy
//    private String createdBy;

    @Column(name = "created_date", nullable = false)
    @CreatedDate
    private ZonedDateTime createdDate;

//    @Column(name = "last_modified_by")
//    @LastModifiedBy
//    private String lastModifiedBy;

    @Column(name = "last_modified_date", nullable = false)
    @LastModifiedDate
    private ZonedDateTime lastModifiedDate;

    public ZonedDateTime getCreatedDate() {
        return createdDate;
    }

    public ZonedDateTime getLastModifiedDate() {
        return lastModifiedDate;
    }

}

Add abstract class for auditing (DEV-15)


package gp.e3.sentinel.domain.repositories;

import static org.junit.Assert.*;
import gp.e3.sentinel.domain.entities.Request;
import gp.e3.sentinel.persistence.daos.RequestDAO;
import gp.e3.sentinel.util.RequestFactoryForTests;

import java.sql.Connection;

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

public class RequestRepositoryTest {

	private Connection dbConnectionMock;
	private RequestDAO requestDAOMock;
	private RequestRepository requestRepository;

	@Before
	public void setUp() {

		dbConnectionMock = Mockito.mock(Connection.class);
		requestDAOMock = Mockito.mock(RequestDAO.class);
		requestRepository = new RequestRepository(requestDAOMock);
	}

	@After
	public void tearDown() {

		dbConnectionMock = null;
		requestDAOMock = null;
		requestRepository = null;
	}

	@Test
	public void testCreateRequest_OK() {

		Request request = RequestFactoryForTests.getDefaultRequest();

		long expectedRequestId = 1;
		Mockito.when(requestDAOMock.createRequest(dbConnectionMock, request)).thenReturn(expectedRequestId);
		long requestId = requestRepository.createRequest(dbConnectionMock, request);

		assertEquals(expectedRequestId, requestId);
	}

	@Test
	public void testCreateRequest_NOK() {

		Request request = RequestFactoryForTests.getDefaultRequest();

		long expectedRequestId = 0;
		Mockito.when(requestDAOMock.createRequest(dbConnectionMock, request)).thenReturn(expectedRequestId);
		long requestId = requestRepository.createRequest(dbConnectionMock, request);

		assertEquals(expectedRequestId, requestId);
	}
}

Add tests for the class RequestRepository.


package fault.metrics;

import fault.concurrent.LongAdder;

/**
 * Created by timbrooks on 6/1/15.
 */
public class Second {

    private final LongAdder successes = new LongAdder();
    private final LongAdder errors = new LongAdder();
    private final LongAdder timeouts = new LongAdder();
    private final LongAdder circuitOpen = new LongAdder();
    private final LongAdder queueFull = new LongAdder();
    private final LongAdder maxConcurrencyExceeded = new LongAdder();
}

Add object for containing metrics for a certain second


package sge.math;

/**
 * Two Dimensional Line Segment (finite).
 */
public class Line2D {

    public final Vector2 start;
    public final Vector2 end;

    public Line2D (Vector2 start, Vector2 end) {
        this.start = start;
        this.end = end;
    }

    public float getLengthSqr () {
        return end.sub(start).getLengthSqr();
    }

    public float getLength () {
        return end.sub(start).getLength();
    }

    public Vector2 getCenter () {
        return start.add(end.scale(0.5f));
    }

    /**
     * Test if this Line2D intersects another Line2D. If there is an
     * intersection, return the point at which the intersects occurs,
     * otherwise return null.
     *
     * @param other Line2D to test for intersection.
     * @return Vector2 Intersection point, or null if no intersection.
     */
    public Vector2 intersects (Line2D other) {
        Vector2 line1 = end.sub(start);
        Vector2 line2 = other.end.sub(other.start);

        // ls1 + line1 * a == ls2 + line2 * b
        float cross = line1.cross(line2);
        if (cross == 0.0f) {
            return null;
        }

        Vector2 dStart = other.start.sub(start);
        float a = dStart.cross(line2) / cross;
        float b = dStart.cross(line1) / cross;

        if (0f < a && a < 1f && 0f < b && b < 1f)
            return start.add(line1.scale(a));

        return null;
    }

    @Override
    public String toString () {
        return String.format("<Line2D %s -> %s>", start, end);
    }
}

Add 2D Line + intersection test


/*
 * Copyright (c) 2016 Qiscus.
 *
 * 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.qiscus.sdk.ui.view;

import android.content.Context;
import android.support.annotation.DrawableRes;
import android.util.AttributeSet;

import com.bumptech.glide.Glide;

import de.hdodenhof.circleimageview.CircleImageView;

public class QiscusCircularImageView extends CircleImageView {
    private String imageUrl;

    public QiscusCircularImageView(Context context) {
        super(context);
    }

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

    public QiscusCircularImageView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    public void setImageUrl(String url) {
        imageUrl = url;
        Glide.with(getContext())
                .load(url)
                .into(this);
    }

    public void setImageUrl(String url, @DrawableRes int placeHolderResourceId) {
        imageUrl = url;
        Glide.with(getContext())
                .load(url)
                .dontAnimate()
                .placeholder(placeHolderResourceId)
                .error(placeHolderResourceId)
                .into(this);
    }

    public void setImageUrl(String url, @DrawableRes int placeHolderResourceId, @DrawableRes int errorResourceId) {
        imageUrl = url;
        Glide.with(getContext())
                .load(url)
                .placeholder(placeHolderResourceId)
                .error(errorResourceId)
                .into(this);
    }

    public String getImageUrl() {
        return imageUrl;
    }
}

Add custom circle image view


package edu.stuy.starlorn.upgrades;

public class SpeedShotUpgrade extends GunUpgrade {
    public SpeedShotUpgrade() {
        super();
        _name = "Speed Shot";
        _description = "Shot Speed x 2!";
    }

    @Override
    public int getShotSpeed(int shotspeed) {
        return shotspeed * 2;
    }
}

Add SpeedShot upgrade. Doubles shot speed.


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

package com.google.gerrit.server.notedb;

import static com.google.common.truth.Truth.assertThat;
import static com.google.common.truth.Truth8.assertThat;

import com.google.gson.Gson;
import com.google.inject.TypeLiteral;
import java.util.Optional;
import org.junit.Test;

public class ChangeNoteJsonTest {
  private final Gson gson = new ChangeNoteJson().getGson();

  @Test
  public void shouldSerializeAndDeserializeEmptyOptional() {
    // given
    Optional<?> empty = Optional.empty();

    // when
    String json = gson.toJson(empty);

    // then
    assertThat(json).isEqualTo("{}");

    // and when
    Optional<?> result = gson.fromJson(json, Optional.class);

    // and then
    assertThat(result).isEmpty();
  }

  @Test
  public void shouldSerializeAndDeserializeNonEmptyOptional() {
    // given
    String value = "foo";
    Optional<String> nonEmpty = Optional.of(value);

    // when
    String json = gson.toJson(nonEmpty);

    // then
    assertThat(json).isEqualTo("{\n  \"value\": \"" + value + "\"\n}");

    // and when
    Optional<String> result = gson.fromJson(json, new TypeLiteral<Optional<String>>() {}.getType());

    // and then
    assertThat(result).isPresent();
    assertThat(result.get()).isEqualTo(value);
  }
}

Add Optional type JSON (de)serialization unit tests


package com.rampatra.misc;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * Various ways to read a file in Java.
 *
 * @author rampatra
 * @since 2019-06-03
 */
public class ReadFile {

    private static Stream<String> readFile(String filePath) throws IOException {
        return Files.lines(Paths.get(filePath)); // use Files.readAllLines() to return a List<String> instead of Stream<String>
    }

    private static String readFile(Path filePath) throws IOException {
        Stream<String> lines = Files.lines(filePath);
        String data = lines.collect(Collectors.joining("\n"));
        lines.close();
        return data;
    }

    private static List<String> readLargeFile(Path filePath) throws IOException {
        try (BufferedReader reader = Files.newBufferedReader(filePath)) {
            List<String> result = new ArrayList<>();
            for (; ; ) {
                String line = reader.readLine();
                if (line == null)
                    break;
                result.add(line);
            }
            return result;
        }
    }

    private static String readFileOldWay(String filePath) throws IOException {
        try (BufferedReader reader = new BufferedReader(new FileReader(filePath))) {
            StringBuilder builder = new StringBuilder();
            String currentLine = reader.readLine();
            while (currentLine != null) {
                builder.append(currentLine);
                builder.append("\n");
                currentLine = reader.readLine();
            }
            // reader.close(); not required as try-with-resources is used

            return builder.toString();
        }
    }

    public static void main(String[] args) throws IOException {
        readFile("src/main/java/com/rampatra/misc/reverseandadd.txt").forEach(System.out::println);
        System.out.println("==================");
        System.out.println(readFile(Paths.get("src/main/java/com/rampatra/misc/reverseandadd.txt")));
        System.out.println("==================");
        System.out.println(readLargeFile(Paths.get("src/main/java/com/rampatra/misc/reverseandadd.txt")));
        System.out.println("==================");
        System.out.println(readFileOldWay("src/main/java/com/rampatra/misc/reverseandadd.txt"));
    }
}

Read file in Java: done


package cc.twittertools.words;

//=================================================================================================
//Copyright 2011 Twitter, Inc.
//-------------------------------------------------------------------------------------------------
//Licensed under the Apache License, Version 2.0 (the "License");
//you may not use this work except in compliance with the License.
//You may obtain a copy of the License in the LICENSE file, or 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.
//=================================================================================================

//=================================================================================================
// Amended to handle the 'ts case, notably the phrase "do's and don'ts", but also references to
// "gov'ts" as an abbreviation for "governement's".
//
// - Bryan Feeney
//=================================================================================================

import java.util.regex.Pattern;

import com.twitter.common.text.combiner.ExtractorBasedTokenCombiner;
import com.twitter.common.text.extractor.RegexExtractor;
import com.twitter.common.text.token.TokenStream;

/**
* Combines multiple tokens denoting a possessive form (e.g., Twitter's) or
* a contraction form (e.g., isn't) back into a single token.
*/
public class MyPossessiveContractionTokenCombiner extends ExtractorBasedTokenCombiner {
	private static final Pattern APOSTROPHE_S = Pattern.compile("([a-zA-Z]+'(?i:t|ts|s|m|re|ve|ll|d))([^a-zA-Z]|$)");

	public MyPossessiveContractionTokenCombiner(TokenStream inputStream) {
	  super(inputStream);
	  setExtractor(
			new RegexExtractor
			.Builder()
			.setRegexPattern(APOSTROPHE_S, 1, 1)
	    .setTriggeringChar('\'')
	    .build()
	  );
	}
}

Add support for better apostrophe-d abbrevations such as don'ts and gov'ts


package com.kduda.battleships.models.units;

public enum UnitType {
    Ship1,
    Ship2,
    Ship3,
    Ship4,
    Tank2,
    Tank3,
    Tank4,
    Plane
}

Add Enum for unit types


package com.example.profbola.bakingtime.provider;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

import com.example.profbola.bakingtime.provider.RecipeContract.RecipeEntry;

/**
 * Created by prof.BOLA on 6/23/2017.
 */

public class RecipeDbHelper extends SQLiteOpenHelper {

    private static final String DATABASE_NAME = "bakingapp.db";

    private static final int DATABASE_VERSION = 1;

    public RecipeDbHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {

        final String SQL_CREATE_RECIPES_TABLE = "CREATE TABLE " + RecipeEntry.TABLE_NAME + " ( " +
                RecipeEntry._ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "                         +
                RecipeEntry.COLUMN_NAME + " TEXT NOT NULL, "                                     +
                RecipeEntry.COLUMN_IMAGE + " STRING, "                                           +
                RecipeEntry.COLUMN_SERVINGS + " INTEGER NOT NULL, "                              +
                RecipeEntry.COLUMN_ID + " INTEGER NOT NULL, "                                    +
//                RecipeEntry.COLUMN_OVERVIEW + " TEXT NOT NULL, "                                 +
                "UNIQUE ( "  +  RecipeEntry.COLUMN_NAME  +  ", " + RecipeEntry.COLUMN_ID         +
                " ) ON CONFLICT REPLACE "                                                        +
                "); ";

        db.execSQL(SQL_CREATE_RECIPES_TABLE);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        db.execSQL("DROP TABLE IF EXISTS " + RecipeEntry.TABLE_NAME);
        onCreate(db);
    }
}

Create DB schema for Recipe


package se.kits.gakusei.controller;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.mockito.runners.MockitoJUnitRunner;
import se.kits.gakusei.content.model.Course;
import se.kits.gakusei.content.repository.CourseRepository;

import static org.junit.Assert.*;

@RunWith(MockitoJUnitRunner.class)
public class CourseControllerTest {

    @InjectMocks
    private CourseController courseController;

    @Mock
    private CourseRepository courseRepository;

    private Course testCourse;

    @Before
    public void setUp(){
        MockitoAnnotations.initMocks(this);
    }

    @Test
    public void getAllCourses() throws Exception {
    }

    @Test
    public void getCourseByID() throws Exception {
    }

    @Test
    public void getCourseByName() throws Exception {
    }

    @Test
    public void getCourseByCode() throws Exception {
    }

}

Add test class for CourseController


package net.darkmorford.btweagles.eventhandler;

import net.darkmorford.btweagles.block.ModBlocks;
import net.darkmorford.btweagles.sound.ModSounds;
import net.minecraft.block.Block;
import net.minecraft.util.EnumParticleTypes;
import net.minecraft.util.SoundCategory;
import net.minecraft.util.math.BlockPos;
import net.minecraftforge.event.world.NoteBlockEvent;
import net.minecraftforge.fml.common.Mod;
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent;

@Mod.EventBusSubscriber
public class EventHandlerNoteBlock
{
	@SubscribeEvent
	public static void playNote(NoteBlockEvent.Play event) {
		// Check the block underneath the Note Block
		Block belowBlock = event.getWorld().getBlockState(event.getPos().down()).getBlock();

		// If it's butter, cancel the regular event
		if (belowBlock == ModBlocks.butter)
		{
			int note = event.getVanillaNoteId();
			float pitch = (float)Math.pow(2.0D, (double)(note - 12) / 12.0D);

			BlockPos pos = event.getPos();
			event.getWorld().playSound(null, pos, ModSounds.airhorn, SoundCategory.RECORDS, 3.0F, pitch);
			event.getWorld().spawnParticle(EnumParticleTypes.NOTE, (double)pos.getX() + 0.5D, (double)pos.getY() + 1.2D, (double)pos.getZ() + 0.5D, (double)note / 24.0D, 0.0D, 0.0D);

			if (event.isCancelable())
			{
				event.setCanceled(true);
			}
		}
	}
}

Add event handler to play airhorn when Note Block is activated.


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

/**
 * Implement a function to check if a binary tree is balanced. For the purposes of this question, a
 * balanced tree is defined to be a tree such that the heights of the two subtrees of any node
 * never differ by more than one.
 *
 * @author Pedro Vicente Gómez Sánchez.
 */
public class IsTreeBalanced {

}

Add statement to problem 65


package org.apache.ddlutils.platform;

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

import java.util.Map;

import org.apache.commons.beanutils.DynaBean;
import org.apache.ddlutils.TestPlatformBase;
import org.apache.ddlutils.dynabean.SqlDynaBean;
import org.apache.ddlutils.dynabean.SqlDynaClass;
import org.apache.ddlutils.model.Database;
import org.apache.ddlutils.model.Table;

/**
 * Tests the {@link org.apache.ddlutils.PlatformImplBase} (abstract) class.
 *
 * @author Martin van den Bemt
 * @version $Revision: 279421 $
 */
public class TestPlatformImplBase extends TestPlatformBase
{

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

    public void setUp()
    {
    }

    /**
     * Test the toColumnValues method
     */
    public void testToColumnValues()
    {
        Database database = parseDatabaseFromString(xml);
        PlatformImplBase platform = new PlatformBase();
        Table table = database.getTable(0);
        SqlDynaClass clz = SqlDynaClass.newInstance(table);
        DynaBean db = new SqlDynaBean(SqlDynaClass.newInstance(table));
        db.set("name", "name");
        Map map = platform.toColumnValues(clz.getSqlDynaProperties(), db);

        assertEquals("name", map.get("name"));
        assertEquals(true, map.containsKey("id"));
    }

    public class PlatformBase extends PlatformImplBase
    {
        public String getName()
        {
            return null;
        }
    }

    protected String getDatabaseName() {
        return null;
    }

}

Add test for abstract PlatformImplBase.


package study.hard.javalib.nativelib;

import org.junit.Test;

public class LanguageTest {

	@Test
	public void testStaticVariable() {
		ClassThatHasStaticVariable a1 = new ClassThatHasStaticVariable();
		ClassThatHasStaticVariable a2 = new ClassThatHasStaticVariable();
	}

}

class ClassThatHasStaticVariable {
	static int count = 0;

	ClassThatHasStaticVariable() {
		count++;
		System.out.print(count);
	}
}

Add the codes to test Java language.


/*
 * This file is generated by jOOQ.
*/
package generated;

import generated.tables.Queue;

import javax.annotation.Generated;

import org.jooq.Index;
import org.jooq.OrderField;
import org.jooq.impl.Internal;

/**
 * A class modelling indexes of tables of the public schema.
 */
@Generated(
    value = {
        "http://www.jooq.org",
        "jOOQ version:3.10.5"
    },
    comments = "This class is generated by jOOQ"
)
@SuppressWarnings({ "all", "unchecked", "rawtypes" })
public class Indexes {

    // -------------------------------------------------------------------------
    // INDEX definitions
    // -------------------------------------------------------------------------

    public static final Index QUEUE_ID_UINDEX = Indexes0.QUEUE_ID_UINDEX;
    public static final Index TABLE_NAME_ID_UINDEX = Indexes0.TABLE_NAME_ID_UINDEX;

    // -------------------------------------------------------------------------
    // [#1459] distribute members to avoid static initialisers > 64kb
    // -------------------------------------------------------------------------

    private static class Indexes0 {
        public static Index QUEUE_ID_UINDEX = Internal.createIndex("queue_id_uindex", Queue.QUEUE, new OrderField[] { Queue.QUEUE.ID }, true);
        public static Index TABLE_NAME_ID_UINDEX = Internal.createIndex("table_name_id_uindex", Queue.QUEUE, new OrderField[] { Queue.QUEUE.UUID }, true);
    }
}

Add missing JOOQ generated file


package ggordeev.sandbox;

/**
 * Created by g.gordeev on 29.02.2016.
 */
public class Point {

  public double x;
  public double y;

  public Point (double x, double y) {
    this.x = x;
    this.y = y;
  }

  public Point() {

  }

  public double distance(Point p1, Point p2) {
    double x = p1.x - p2.x;
    double y = p1.y - p2.y;
    return Math.sqrt(x * x + y * y);
  }
}

Revert "Revert "Тренировка. Вычисление расстояния между точками""


/*
 * SIP Communicator, the OpenSource Java VoIP and Instant Messaging client.
 *
 * Distributable under LGPL license.
 * See terms of license at gnu.org.
 */
package net.java.sip.communicator.service.protocol.event;

import java.util.*;
import net.java.sip.communicator.service.protocol.*;

/**
 * <tt>TypingNotificationEvent</tt>s are delievered upon reception of a
 * corresponding message from a remote contact.
 * <tt>TypingNotificationEvent</tt>s contain a state id, identifying the exact
 * typing event that has occurrend (a user has started or stopped typing at us),
 * the source <tt>Contact</tt> that generated the event and others.
 * @author Emil Ivov
 */
public class TypingNotificationEvent
    extends EventObject
{
    private int typingState = OperationSetTypingNotifications.STATE_UNKNOWN;

    /**
     * Creats a TypingNotificationEvent with the specified parameters.
     * <p>
     * @param source Object
     */
    public TypingNotificationEvent(Contact sourceContact, int state)
    {
        super(sourceContact);
        this.typingState = state;
    }

    /**
     * Returns the typing state that this <tt>TypingNotificationEvent</tt> is
     * carrying.
     * @return one of the <tt>STATE_XXX int</tt>s indicating the typing state
     * that this notification is about.
     */
    public int getTypingState()
    {
        return typingState;
    }

    /**
     * Returns a reference to the <tt>Contact</tt> that has sent this event.
     * @return a reference to the <tt>Contact</tt> whose typing state we're
     * being notified about.
     */
    public Contact getSourceContact()
    {
        return (Contact)getSource();
    }
}

Support for typing notifications in icq (testing is still pending though)


package com.github.legioth.propertysource.rebind;

import com.google.gwt.user.rebind.StringSourceWriter;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import static org.testng.Assert.*;

public class StringTypeHandlerTest
{
  @DataProvider( name = "writeValues" )
  public Object[][] actionDescriptions()
  {
    return new Object[][]{
      new Object[]{ "hi", "\"hi\"" },
      new Object[]{ "1\n2", "\"1\\n2\"" },
      new Object[]{ "&", "\"&\"" },
      new Object[]{ "Å", "\"Å\"" },
    };
  }

  @Test( dataProvider = "actionDescriptions" )
  public void writeValues( final String input, final String output )
  {
    final StringSourceWriter writer = new StringSourceWriter();
    StringTypeHandler.INSTANCE.writeValue( null, writer, input );
    assertEquals( writer.toString(), output );
  }
}

Add first test for StringTypeHandler