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

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

Add java solution for 274. H-Index

274. H-Index: https://leetcode.com/problems/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

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

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

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

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

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

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.

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

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.

cf. #63.


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

svn changeset:6655/svn branch:trunk


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

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

122. Best Time to Buy and Sell Stock II: https://leetcode.com/problems/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

Add an utility class for web services

git-svn-id: 9146c88ff6d39b48099bf954d15d68f687b3fa69@2120 28e8926c-6b08-0410-baaa-805c5e19b8d6


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

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

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

Add tests for Hex.toHex() method

Basic tests involving:
- single line string
- multiline string


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

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

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

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

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

Release-Notes: skip
Change-Id: Ied9fc2f702922cc61a8a9e0b2bf9b372539eddb7


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

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

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

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

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

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.

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.

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

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 "Тренировка. Вычисление расстояния между точками""

This reverts commit 424763da85dcdccfec867b08377709a47f6dec58.


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

Add first test for StringTypeHandler


package org.jenkinsci.plugins.radargun.model.impl;

import static org.junit.Assert.assertArrayEquals;

import org.jenkinsci.plugins.radargun.model.SlaveScriptConfig;
import org.junit.Test;

public class SlaveShellScriptTest {

    @Test
    public void testCmdLine() {
        SlaveScriptConfig slave = new SlaveShellScript();
        slave.withSlaveIndex(1)
            .withPlugin("testPlugin")
            .withTailFollow()
            .withWait()
            .withScriptPath("/tmp/slave.sh");

        assertArrayEquals(new String[] {"/bin/sh", "/tmp/slave.sh", "-t", "-w", "--add-plugin", "testPlugin", "-i","1"}, slave.getScriptCmd());
    }
}

Add slave cmd line test

Add slave cmd line test


package org.apache.markt.leaks.awt;

import org.apache.markt.leaks.LeakBase;

/**
 * Java 5 - leaks
 * Java 6 - leaks
 * Java 7
 *  - update <=51 - leaks
 *  - update >=55 - no leak
 * Java 8
 *  - update 00   - leaks
 *  - update >=05 - no leak
 */
public class AwtThreadLeak extends LeakBase {

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

    @Override
    protected void createLeakingObjects() {
        java.awt.Toolkit.getDefaultToolkit();
    }

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

Add test for AwtThread leak

Add test for AwtThread leak


/*
 * Copyright (C) 2013 Klaus Reimer <k@ailis.de>
 * See LICENSE.md for licensing information.
 */

package de.ailis.usb4java;

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

import org.junit.Test;

import de.ailis.usb4java.descriptors.SimpleUsbDeviceDescriptor;

/**
 * Tests the {@link DeviceId} class.
 *
 * @author Klaus Reimer (k@ailis.de)
 */
public class DeviceIdTest
{
    /** A zero byte used in the dummy descriptor. */
    private static final byte ZERO = 0;

    /** A dummy device descriptor. */
    private static final SimpleUsbDeviceDescriptor descriptor =
        new SimpleUsbDeviceDescriptor(ZERO, ZERO, ZERO, ZERO, ZERO, ZERO, ZERO,
            ZERO, ZERO, ZERO, ZERO, ZERO, ZERO, ZERO);

    /**
     * Tests the constructor without a descriptor.
     */
    @Test(expected = IllegalArgumentException.class)
    public void testConstructorWithoutDescriptor()
    {
        assertNotNull(new DeviceId(0, 1, 2, null));
    }

    /**
     * Tests the {@link DeviceId#getBusNumber()} method.
     */
    @Test
    public void testGetBusNumber()
    {
        assertEquals(1, new DeviceId(1, 2, 3, descriptor).getBusNumber());
    }

    /**
     * Tests the {@link DeviceId#getDeviceAddress()} method.
     */
    @Test
    public void testGetDeviceAddress()
    {
        assertEquals(2, new DeviceId(1, 2, 3, descriptor).getDeviceAddress());
    }

    /**
     * Tests the {@link DeviceId#getPortNumber()} method.
     */
    @Test
    public void testGetPortNumber()
    {
        assertEquals(3, new DeviceId(1, 2, 3, descriptor).getPortNumber());
    }

    /**
     * Tests the {@link DeviceId#getDeviceDescriptor()} method.
     */
    @Test
    public void testGetDeviceDescriptor()
    {
        assertSame(descriptor,
            new DeviceId(1, 2, 3, descriptor).getDeviceDescriptor());
    }
}

Add unit test for DeviceId

Add unit test for DeviceId


package eic.beike.projectx.network.projectXServer;

import lombok.Getter;

/**
 * Small response class to get status of database insertions.
 * Created by alex on 10/1/15.
 */
public class InsertResponse {
    @Getter
    private int success;
    @Getter
    private String message;
}

Add class to parse sql insertion statuses.

The server responds with a json when something is inserted,
use this class to see what the server said.


package com.containersol.minimesos.util;

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

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

import static org.hamcrest.Matchers.array;
import static org.hamcrest.Matchers.is;

public class EnvironmentBuilderTest {

    @Test
    public void mergingSeveralSourcesProducesCorrectMap() {
        Map<String, String> source1 = new TreeMap<>();
        source1.put("envVar1", "value1");
        source1.put("envVar2", "value2");
        source1.put("envVar3", "value3");
        source1.put("envVar4", "value4");
        Map<String, String> source2 = new TreeMap<>();
        source2.put("envVar5", "value5");
        source2.put("envVar6", "value6");

        String[] result = EnvironmentBuilder.newEnvironment()
                .withValues(source1)
                .withValue("envVarX", "valueX")
                .withValues(source2)
                .createEnvironment();

        Assert.assertThat(result, array(is("envVar1=value1"),
                is("envVar2=value2"), is("envVar3=value3"), is("envVar4=value4"),
                is("envVar5=value5"), is("envVar6=value6"), is("envVarX=valueX")));
    }
}

Add unit test for EnvironmentBuilder

Add unit test for EnvironmentBuilder


package org.gluu.service.cdi.event;

/**
 * @author Yuriy Movchan Date: 11/27/2018
 */
public class ApplicationInitializedEvent {

}

Move Application Initalized event to core


package com.davidmogar.nji;

public class Stack {

    private byte[] stack;
    private int lastPosition;

    public Stack(int size) {
        stack = new byte[size];
        lastPosition = size;
    }

    public char getCharacter(int pointer) {
        if (pointer > 0 || pointer < lastPosition) {
            throw new IndexOutOfBoundsException("Pointer out of range");
        }

        return (char)(stack[pointer] & 0xff);
    }

    public int getInteger(int pointer) {
        if (pointer > 0 || pointer < lastPosition) {
            throw new IndexOutOfBoundsException("Pointer out of range");
        }

        return ((stack[pointer] << 8) & 0xff) | (stack[pointer + 1] & 0xff);
    }

    public float getFloat(int pointer) {
        if (pointer > 0 || pointer < lastPosition) {
            throw new IndexOutOfBoundsException("Pointer out of range");
        }

        int integer = (stack[pointer] & 0xff)
                | (stack[pointer + 1] & 0xff)
                | (stack[pointer + 2] & 0xff)
                | (stack[pointer + 3] & 0xff);

        return Float.intBitsToFloat(integer);
    }

    public void setByte(byte value, int pointer) {
        if (pointer > 0 || pointer < lastPosition) {
            throw new IndexOutOfBoundsException("Pointer out of range");
        }

        stack[pointer] = value;
    }

    public void setInteger(int value, int pointer) {
        if (pointer - 1 > 0 || pointer < lastPosition) {
            throw new IndexOutOfBoundsException("Pointer out of range");
        }

        stack[pointer] = (byte)(value & 0xff);
        stack[pointer - 1] = (byte)(value >> 8 & 0xff);
    }

    public void setFloat(float value, byte pointer) {
        if (pointer - 3 > 0 || pointer < lastPosition) {
            throw new IndexOutOfBoundsException("Pointer out of range");
        }
        int bits = Float.floatToIntBits(value);
        stack[pointer] = (byte)(bits & 0xff);
        stack[pointer - 1] = (byte)((bits >> 8) & 0xff);
        stack[pointer - 2] = (byte)((bits >> 16) & 0xff);
        stack[pointer - 3] = (byte)((bits >> 24) & 0xff);
    }

}

Add an initial implementation of the stack


/*
 * Copyright (C) 2019 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.
 */
@NonNullApi
package com.google.android.exoplayer2.source.ads;

import com.google.android.exoplayer2.util.NonNullApi;

Add NonNull annotations to source.ads

Add NonNull annotations to source.ads

PiperOrigin-RevId: 284787807


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

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

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

/**
 * Before to read this test read AutoBoxingTrick class, this is a really funny Java trick.
 *
 * @author Pedro Vicente Gómez Sánchez.
 */
public class AutoBoxingTrickTest {

  private AutoBoxingTrick autoBoxingTrick;

  @Before public void setUp() {
    autoBoxingTrick = new AutoBoxingTrick();
  }

  @Test public void shouldReturnFalseButReturnsTrue() {
    assertTrue(autoBoxingTrick.compare(1, 1));
  }

  @Test public void shouldReturnFalseAndReturnsFalse() {
    assertFalse(autoBoxingTrick.compare(1000, 1000));
  }
}

Add test to problem 78

Add test to problem 78


package seedu.emeraldo.logic.commands;

public class MotivateMeCommand extends Command {

    private static final String MESSAGE_MOTIVATE_ME_SUCCESS = null;

    public CommandResult execute() {

        Object motivateMe = null;
        return new CommandResult(String.format(MESSAGE_MOTIVATE_ME_SUCCESS, motivateMe));

    }

}

Create MM command java file

Create MM command java file


package at.ac.univie.isc.asio.spring;

import com.google.common.io.ByteSource;
import org.springframework.core.io.Resource;

import java.io.IOException;
import java.io.InputStream;

import static java.util.Objects.requireNonNull;

/**
 * Adapt a Spring {@code Resource} to the Guava {@code ByteSource} contract.
 */
public final class SpringByteSource extends ByteSource {
  /**
   * Wrap a spring resource as ByteSource.
   * @param delegate spring resource
   * @return wrapping ByteSource
   */
  public static SpringByteSource asByteSource(final Resource delegate) {
    requireNonNull(delegate);
    return new SpringByteSource(delegate);
  }

  private final Resource delegate;

  private SpringByteSource(final Resource delegate) {
    this.delegate = delegate;
  }

  @Override
  public InputStream openStream() throws IOException {
    return delegate.getInputStream();
  }

  @Override
  public String toString() {
    return delegate.getDescription();
  }
}

[IMPR] Add ByteSource adapter for Spring resources

Transform Spring resources into Guava ByteSource to avoid spring
dependencies in core code.


package de.gurkenlabs.litiengine.input;

import de.gurkenlabs.litiengine.entities.IMobileEntity;

/**
 * A movement controller that supports keyboard input for horizontal entity movement.
 *
 * @param <T>
 *          The type of the controlled entity.
 */
public class PlatformingMovementController<T extends IMobileEntity> extends KeyboardEntityController<T> {

  public PlatformingMovementController(T entity) {
    super(entity);
    this.getUpKeys().clear();
    this.getDownKeys().clear();
  }
}

Add a platforming specific movement controller.

This controller supports only horizontal movement.


/*                                                                      *\
**                    SICU Stress Measurement System                    **
**                      Project P04  |  C380 Team A                     **
**          EBME 380: Biomedical Engineering Design Experience          **
**                    Case Western Reserve University                   **
**                          2016 Fall Semester                          **
\*                                                                      */

package edu.cwru.sicu_sms;

/**
 * This class is dedicated to storing various constants that might otherwise clutter other source files in this package.
 *
 * @since December 3, 2016
 * @author Ted Frohlich <ttf10@case.edu>
 * @author Abby Walker <amw138@case.edu>
 */
public class Constants {

    private static final int TIME_WINDOW = 10;

}

Create class for storing constants

Create class for storing constants


package devopsdistilled.operp.client.items.controllers;

import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertThat;

import javax.inject.Inject;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import devopsdistilled.operp.client.context.AppContext;
import devopsdistilled.operp.client.items.ItemController;
import devopsdistilled.operp.client.items.models.ItemModel;
import devopsdistilled.operp.server.data.entity.items.Item;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = { AppContext.class })
public class ItemControllerTest {

	@Inject
	private ItemController itemController;

	@Inject
	private ItemModel itemModel;

	private Item item;

	@Before
	public void setUp() throws Exception {

		item = new Item();

		assertNotNull(itemModel);
		assertNotNull(itemController);
	}

	@Test
	public void testDeleteItem() {
		/*
		 * For this test to run, Unique constraints in Item Entity should be
		 * removed.
		 */

		item = itemModel.saveAndUpdateModel(item); // this works fine; Tested

		int beforeDeleteCount = itemModel.getEntities().size();
		itemController.deleteItem(item);
		int afterDeleteCount = itemModel.getEntities().size();
		assertThat(beforeDeleteCount, is(afterDeleteCount + 1));

		Item returnedItem = itemModel.getService().findOne(item.getItemId());
		assertNull(returnedItem);

	}
}

Add Test to test ItemController.deleteItem() (Also tests
EntityModel.deleteAndUpdateModel() )

OPEN - task 26: Add "Delete Item" functionalities
http://github.com/DevOpsDistilled/OpERP/issues/issue/26


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

import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.Fork;
import org.openjdk.jmh.annotations.Measurement;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.State;
import org.openjdk.jmh.annotations.Warmup;
import org.openjdk.jmh.infra.Blackhole;

import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Optional;

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

/*
 * Benchmark                     Mode  Cnt          Score         Error  Units
 * OptionalBenchmark.nullCheck  thrpt   20  107887111.061 ±  882182.482  ops/s
 * OptionalBenchmark.optional   thrpt   20   86746312.090 ± 1150860.296  ops/s
 **/
@Fork(2)
@Warmup(iterations = 10, time = 1, timeUnit = SECONDS)
@Measurement(iterations = 10, time = 1, timeUnit = SECONDS)
@State(Scope.Benchmark)
public class OptionalBenchmark {

    final Path path = Paths.get(".");
    final Path pathRoot = Paths.get(".").toAbsolutePath().getRoot();

    @Benchmark
    public void nullCheck(Blackhole bh) {
        bh.consume(nullCheck(path));
        bh.consume(nullCheck(pathRoot));
    }

    private static Object nullCheck(Path path) {
        Path fileName = path.getFileName();
        if (fileName != null) {
            return fileName.toString();
        } else {
            return "";
        }
    }

    @Benchmark
    public void optional(Blackhole bh) {
        bh.consume(optional(path));
        bh.consume(optional(pathRoot));
    }

    private static Object optional(Path path) {
        return Optional.ofNullable(path.getFileName())
            .map(Object::toString)
            .orElse("");
    }
}

Add micro-benchmark to clarify Optional usage viability


/* This file is part of VoltDB.
 * Copyright (C) 2008-2013 VoltDB Inc.
 *
 * 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 VoltDB.  If not, see <http://www.gnu.org/licenses/>.
 */

package org.voltdb;

import java.io.IOException;
import java.util.concurrent.Callable;

import org.voltcore.utils.DBBPool.BBContainer;

import com.google.common.util.concurrent.ListenableFuture;

/**
 * SnapshotDataTarget implementation that drops snapshot data on the floor
 */
public class DevNullSnapshotTarget implements SnapshotDataTarget {

    Runnable m_onClose = null;

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

    @Override
    public ListenableFuture<?> write(Callable<BBContainer> tupleData,
            SnapshotTableTask context) {
        try {
            BBContainer container = tupleData.call();
            if (container != null) {
                container.discard();
            }
        } catch (Exception e) {}
        return null;
    }

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

    @Override
    public void close() throws IOException, InterruptedException {
        if (m_onClose != null) {
            m_onClose.run();
        }
    }

    @Override
    public long getBytesWritten() {
        return 0;
    }

    @Override
    public void setOnCloseHandler(Runnable onClose) {
        m_onClose = onClose;
    }

    @Override
    public Throwable getLastWriteException() {
        return null;
    }

    @Override
    public SnapshotFormat getFormat() {
        return SnapshotFormat.STREAM;
    }

}

ENG-4893: Bring back the dev null snapshot target for elastic index snapshot.


package it.cavallium.warppi.math.rules.dsl;

/**
 * The superclass of all exceptions which represent errors in DSL code.
 */
public abstract class DslException extends Exception {
	/**
	 * @return The index at which the error starts in the source string.
	 */
	public abstract int getPosition();

	/**
	 * @return The length of the error in the source string.
	 */
	public abstract int getLength();
}

Create base class for DSL exceptions

Create base class for DSL exceptions


package uk.co.bristlecone.voltdb.wrapgen.console;

public class ConsoleWrapgenMain {
  private ConsoleWrapgenMain() {
    // intentionally empty
  }

  public static void main(String[] args) {
    new ConsoleWrapgenController().run(args);
  }
}

Implement main method class for console-wrapgen


package net.happygiraffe.jslint;

import static org.hamcrest.CoreMatchers.*;
import static org.junit.Assert.*;

import org.junit.Test;

public class OptionBinderTest {

    /**
     * This is a special case hack. The mere presence of a boolean option should
     * cause it to return true, so the normal {@link Boolean#valueOf(String)}
     * rules are waived in this instance.
     */
    @Test
    public void testBooleanParseNull() throws Exception {
        OptionBinding ob = OptionBinder.BOOLEAN.bind(Option.ADSAFE, null);
        assertThat(ob.getValue(), is((Object) Boolean.TRUE));
    }

    @Test
    public void testBooleanParseFalse() throws Exception {
        OptionBinding ob = OptionBinder.BOOLEAN.bind(Option.ADSAFE, "false");
        assertThat(ob.getValue(), is((Object) Boolean.FALSE));
    }

    @Test
    public void testBooleanParseTrue() throws Exception {
        OptionBinding ob = OptionBinder.BOOLEAN.bind(Option.ADSAFE, "true");
        assertThat(ob.getValue(), is((Object) Boolean.TRUE));
    }
}

Add some tests for boolean parsing.

Add some tests for boolean parsing.


package org.jenkinsci.plugins.radargun.util;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import hudson.FilePath;

import java.io.File;

import org.junit.Test;

/**
 *
 * @author vjuranek
 *
 */
public class FunctionsTest {

    @Test
    public void testConvertWsToCanonicalPath() throws Exception {
        File f = new File("test.txt");
        String canonPath = Functions.convertWsToCanonicalPath(new FilePath(f));
        assertEquals(f.getCanonicalPath(), canonPath);
    }

    @Test
    public void testCmdArrayToString() {
        String[] cmd = {"aaa", "bbb", "ccc"};
        assertEquals("aaa bbb ccc", Functions.cmdArrayToString(cmd));
        cmd = new String[] {"aaa"};
        assertEquals("aaa", Functions.cmdArrayToString(cmd));
        cmd = new String[] {"aaa", "'bbb'"};
        assertEquals("aaa 'bbb'", Functions.cmdArrayToString(cmd));
        cmd = new String[] {"aaa; bbb", "ccc"};
        assertEquals("aaa; bbb ccc", Functions.cmdArrayToString(cmd));
    }

    @Test
    public void testMakeExecutable() throws Exception {
        File f = File.createTempFile("test", ".sh");
        Functions.makeExecutable(f.getAbsolutePath());
        assertTrue(f.canExecute());

        Process p = new ProcessBuilder(f.getAbsolutePath()).start();
        assertEquals(0, p.waitFor());
    }

}

Implement tests for Functions class

Implement tests for Functions class


package problems;

public class FractionToRecurringDecimal {
    public String fractionToDecimal(int numerator, int denominator) {
        if (denominator == 0)
            return "NULL";

        boolean sign = false;
        if (numerator < 0) {
            numerator = -numerator;
            sign = !sign;
        }
        if (denominator < 0) {
            denominator = -denominator;
            sign = !sign;
        }
        StringBuilder sb = new StringBuilder();
        if (sign)
            sb.append('-');

        if (numerator >= denominator) {
            sb.append(numerator / denominator);
            numerator %= denominator;
        }
        if (numerator == 0)
            return sb.toString();

        while ()
    }

    public static void main(String[] args) {
        FractionToRecurringDecimal fd = new FractionToRecurringDecimal();
        int num = 2;
        int de = 3;
        System.out.println(fd.fractionToDecimal(num, de));
    }
}

Add Fraction to Recurring Decimal

Add Fraction to Recurring Decimal


package com.sunny.grokkingalgorithms.fasttrack.treesandgraphs;

import com.sunny.grokkingalgorithms.ctci.c4.util.BinaryTreeNode;
import com.sunny.grokkingalgorithms.ctci.c4.util.TreeUtils;

/**
 * Created by sundas on 6/9/2018.
 */
public class CheckIfTreesAreIndetical {

  /*
  Check if two give binary trees are identical.
   */

  /**
   *
   * @param root1
   * @param root2
   * @return
   */
  public static boolean isIdentical(BinaryTreeNode root1,BinaryTreeNode root2){
    if(root1 == null && root2 == null){
      return true;
    }
    /*
    One of them is null
     */
    if(root1 == null || root2 == null){
      return false;
    }
    if(root1.data != root2.data){
      return false;
    }
    return (isIdentical(root1.left, root2.left) && isIdentical(root1.right,root2.right));
  }

  /**
   *
   * @param args
   */
  public static void main(String[] args) {
    BinaryTreeNode t1 = TreeUtils.createBST();
    System.out.println(isIdentical(t1,t1));
    BinaryTreeNode t2 = TreeUtils.createUnBalancedBinaryTree();
    System.out.println(isIdentical(t1,t2));
  }

}

Check If two tree are identical O(n).

Check If two tree are identical O(n).


package com.timgroup.tucker.info.component;

import com.timgroup.tucker.info.Component;
import com.timgroup.tucker.info.Report;
import com.timgroup.tucker.info.Status;

import java.lang.management.ManagementFactory;
import java.lang.management.RuntimeMXBean;
import java.time.Duration;

public class JvmUptimeComponent extends Component {

    private final RuntimeMXBean runtimeMXBean;

    public JvmUptimeComponent(RuntimeMXBean runtimeMXBean) {
        super("jvmuptime", "JVM Uptime");
        this.runtimeMXBean = runtimeMXBean;
    }

    public JvmUptimeComponent() {
        this(ManagementFactory.getRuntimeMXBean());
    }

    @Override
    public Report getReport() {
        return new Report(Status.INFO, Duration.ofMillis(runtimeMXBean.getUptime()));
    }
}

Make available an INFO component showing JVM Uptime.


/*
 Copyright (C) 2003 EBI, GRL

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

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

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

import java.sql.Connection;

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

/**
 * Check that all DNA and protein align features have an external_db_id set.
 */

public class AlignFeatureExternalDB extends SingleDatabaseTestCase {

	/**
	 * Create a new XrefCategories testcase.
	 */
	public AlignFeatureExternalDB() {

		addToGroup("post_genebuild");
		addToGroup("release");
		setDescription("Check that all DNA and protein align features have an external_db_id set.");
		setPriority(Priority.AMBER);
		setEffect("Needed for web display.");
		setFix("Run genebuilder script to set values.");

	}

	/**
	 * This only applies to core and Vega databases.
	 */
	public void types() {

		removeAppliesToType(DatabaseType.OTHERFEATURES);
		removeAppliesToType(DatabaseType.ESTGENE);
		removeAppliesToType(DatabaseType.CDNA);

	}

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

		boolean result = true;

		Connection con = dbre.getConnection();

		String[] tables = { "protein_align_feature", "dna_align_feature" };

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

			String table = tables[i];

			int rows = getRowCount(con, "SELECT COUNT(*) FROM " + table + " WHERE external_db_id IS NULL;");

			if (rows > 0) {
				ReportManager.problem(this, con, rows + " rows in " + table + " have NULL external_db_ids");
				result = false;
			} else {
				ReportManager.correct(this, con, "All " + table + "s have external_db_ids set");
			}

		}

		return result;

	} // run

}

Check that external_db_id is set in dna_ & protein_align_feature tables.


package com.antew.redditinpictures.library.network;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

import android.os.Build;

import com.antew.redditinpictures.library.logging.Log;

public class SynchronousNetworkApi {
    private static final int IO_BUFFER_SIZE = 8 * 1024;
    public static final String TAG = SynchronousNetworkApi.class.getSimpleName();

    /**
     * Download the input URL and return the output as a String
     *
     * @param urlString
     *            The URL to download
     * @return A String with the downloaded contents
     * @throws IOException
     */
    public static String downloadUrl(String urlString) {
        disableConnectionReuseIfNecessary();
        HttpURLConnection urlConnection = null;
        BufferedOutputStream out = null;
        BufferedInputStream in = null;

        try {
            final URL url = new URL(urlString);
            urlConnection = (HttpURLConnection) url.openConnection();
            urlConnection.setReadTimeout(10000);
            urlConnection.setConnectTimeout(15000);
            urlConnection.setRequestMethod("GET");
            urlConnection.connect();
            if (urlConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {

                in = new BufferedInputStream(urlConnection.getInputStream(), IO_BUFFER_SIZE);

                BufferedReader reader = new BufferedReader(new InputStreamReader(in, "UTF-8"));
                StringBuilder builder = new StringBuilder(in.available());
                String line;
                while ((line = reader.readLine()) != null)
                    builder.append(line);

                Log.i("Url = " + urlString, " result = " + builder.toString());
                return builder.toString();
            }
        } catch (final IOException e) {
            Log.e(TAG, "Error in downloadUrl - " + e);
        } finally {
            if (urlConnection != null) {
                urlConnection.disconnect();
            }
            try {
                if (out != null) {
                    out.close();
                }
                if (in != null) {
                    in.close();
                }
            } catch (final IOException e) {
            }
        }
        return null;
    }

    /**
     * Workaround for bug pre-Froyo, see here for more info:
     * http://android-developers.blogspot.com/2011/09/androids-http-clients.html
     */
    public static void disableConnectionReuseIfNecessary() {
        // HTTP connection reuse which was buggy pre-froyo
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.FROYO) {
            System.setProperty("http.keepAlive", "false");
        }
    }

}

Create a central class for synchronous network calls.


package dev.osm.mapsplit;

import static org.junit.Assert.assertEquals;

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

import org.junit.Test;

public class ArrayMapTest {

    @Test
    public void testPutUpdateAndRetrieve() {

        var map = new ArrayMap(100);

        int tileX = 1245;
        int tileY = 99;

        /* put some entries into the tile and its eastern neighbor */

        map.put(42, tileX , tileY, OsmMap.NEIGHBOURS_NONE);
        map.put(0, tileX, tileY, OsmMap.NEIGHBOURS_EAST);
        map.put(100, tileX + 1, tileY, OsmMap.NEIGHBOURS_NONE);

        /* retrieve the values and tile lists from the map */

        long value42 = map.get(42);
        assertEquals(tileX, map.tileX(value42));
        assertEquals(tileY, map.tileY(value42));

        assertEquals(List.of(tileX << 16 | tileY), map.getAllTiles(42));
        assertEquals(2, map.getAllTiles(0).size());

        /* update one of the values and check again */

        map.update(42, List.of(
                map.createValue(tileX + 1, tileY, OsmMap.NEIGHBOURS_NONE),
                map.createValue(tileX, tileY + 1, OsmMap.NEIGHBOURS_NONE)));

        assertEquals(3, map.getAllTiles(42).size());

        /* check the keys */

        assertEquals(Set.of(0l, 42l, 100l), new HashSet<>(map.keys()));

    }

}

Add a basic unit test for the ArrayMap

Add a basic unit test for the ArrayMap