import java.util.Scanner;
import java.io.File;

class Target {
  private static volatile int value;

  private static void method1() {
    for (int i = 0; i < 1000000; ++i)
      ++value;
  }

  private static void method2() {
    for (int i = 0; i < 1000000; ++i)
      ++value;
  }

  private static void method3() throws Exception {
    for (int i = 0; i < 1000; ++i) {
      new Scanner(new File("/proc/cpuinfo")).useDelimiter("\\Z").next();
    }
  }

  public static void main(String[] args) throws Exception {
    while (true) {
      method1();
      method2();
      method3();
    }
  }
}

Add simple Java test application target

Add simple Java test application target

This target burns CPU in a couple of methods, and makes some syscalls
by opening a procfs file repeatedly. This is the target for our
smoke test that verifies we can successfully sample the process.


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

import java.util.Timer;
import java.util.TimerTask;

/**
 * Make the robot "bump" forward a small amount for button-controlled fine
 * position adjustments.
 *
 * @author RAmato
 */
public class DriveBumpForwardCommand extends CommandBase {

    private static final int BUMP_TIMEOUT = 50; //Milliseconds
    private static final double BUMP_SPEED = 0.5;
    private Timer m_bumpTimer;
    private boolean m_isBumpDone;

    public DriveBumpForwardCommand() {
        requires(drive);
        Timer m_bumpTimer = new Timer();
        m_isBumpDone = false;
    }

        class BumpTimerTask extends TimerTask {
        public void run() {
            m_isBumpDone = true;
            m_bumpTimer.cancel(); //Terminate the timer thread
        }
    }

    // Called just before this Command runs the first time
    protected void initialize() {
        m_bumpTimer.schedule(new BumpTimerTask(), BUMP_TIMEOUT);
    }

    // Called repeatedly when this Command is scheduled to run
    protected void execute() {
        drive.driveStraight(BUMP_SPEED);
    }

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

    // Called once after isFinished returns true
    protected void end() {
    }

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

Add "bump" commands for fine position adjustment.


package leetcode.subsets_ii;

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

public class Solution {
	public void dfs(ArrayList<ArrayList<Integer>> ans, ArrayList<Integer> cur, int[] num, int n, int depth){
		if(depth == n){
			ans.add(new ArrayList<Integer>(cur));
		}else{
			int v = num[depth];
			int cnt = 0;
			for(int x = depth; x < n && num[x] == v; x++){
				cnt++;
			}
			dfs(ans, cur, num, n, depth + cnt);
			for(int i = 0; i < cnt; i++){
				cur.add(v);
				dfs(ans, cur, num, n, depth + cnt);
			}
			cur.subList(cur.size() - cnt, cur.size()).clear();
		}
	}

    public ArrayList<ArrayList<Integer>> subsetsWithDup(int[] num) {
    	ArrayList<ArrayList<Integer>> ans = new ArrayList<ArrayList<Integer>>();
    	if(num == null || num.length == 0) return ans;
    	Arrays.sort(num);
    	dfs(ans, new ArrayList<Integer>(), num, num.length, 0);
    	return ans;
    }

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

Add java solution for 90. Subsets II

Add java solution for 90. Subsets II

90. Subsets II: https://leetcode.com/problems/subsets-ii/


// Copyright 2008 Google Inc.
//
// 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.gwtjsonrpc.client;

public class VoidResult_JsonSerializer extends JsonSerializer<VoidResult> {
  public static final VoidResult_JsonSerializer INSTANCE =
      new VoidResult_JsonSerializer();

  private VoidResult_JsonSerializer() {
  }

  @Override
  public void printJson(final StringBuffer sb, final VoidResult o) {
    sb.append("{}");
  }

  @Override
  public VoidResult fromJson(final Object o) {
    return VoidResult.INSTANCE;
  }
}

Implement a custom serializer for VoidResult

The serializer respects the singleton property of the object,
avoiding creating an instance from the JSON stream when we
already have one available as a constant.

Signed-off-by: Shawn O. Pearce <f3ea74d906fa9fe97c1fef6bad9cb871485c7045@google.com>


package org.robockets.stronghold.robot.autonomous;

import org.robockets.stronghold.robot.Direction;
import org.robockets.stronghold.robot.drivetrain.AssistedDrive;
import org.robockets.stronghold.robot.drivetrain.AssistedRotateType;
import org.robockets.stronghold.robot.drivetrain.AssistedTranslateType;
import org.robockets.stronghold.robot.intake.IntakeSide;
import org.robockets.stronghold.robot.intake.ManualSpinIntake;

import edu.wpi.first.wpilibj.command.CommandGroup;

/**
 * ALL VALUES ARE TEMPORARY
 */
public class AutoShootLow extends CommandGroup {

    public  AutoShootLow(int defense) {
    	addSequential(new MoveToMiddleGoal(defense));
        addSequential(new AssistedDrive(AssistedTranslateType.ENCODER, AssistedRotateType.ENCODER, 24, 0));
        addSequential(new ManualSpinIntake(Direction.FORWARD, 3, IntakeSide.FRONT));
    }
}

Add skeleton for auto shoot low

Add skeleton for auto shoot low


package com.uber.hoodie.config;

import static org.junit.Assert.*;

import com.google.common.collect.Maps;
import com.uber.hoodie.config.HoodieWriteConfig.Builder;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Date;
import java.util.Map;
import java.util.Properties;
import org.junit.Test;

public class HoodieWriteConfigTest {
  @Test
  public void testPropertyLoading() throws IOException {
    Builder builder = HoodieWriteConfig.newBuilder().withPath("/tmp");
    Map<String, String> params = Maps.newHashMap();
    params.put(HoodieCompactionConfig.MAX_COMMITS_TO_KEEP, "5");
    params.put(HoodieCompactionConfig.MIN_COMMITS_TO_KEEP, "2");
    ByteArrayOutputStream outStream = saveParamsIntoOutputStream(params);
    ByteArrayInputStream inputStream = new ByteArrayInputStream(outStream.toByteArray());
    try {
      builder = builder.fromInputStream(inputStream);
    } finally {
      outStream.close();
      inputStream.close();
    }
    HoodieWriteConfig config = builder.build();
    assertEquals(config.getMaxCommitsToKeep(), 5);
    assertEquals(config.getMinCommitsToKeep(), 2);
}

  private ByteArrayOutputStream saveParamsIntoOutputStream(Map<String, String> params) throws IOException {
    Properties properties = new Properties();
    properties.putAll(params);
    ByteArrayOutputStream outStream = new ByteArrayOutputStream();
    properties.store(outStream, "Saved on " + new Date(System.currentTimeMillis()));
    return outStream;
  }
}

Test to check if properties set are properly propogated


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

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

import java.io.File;

import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;

import io.github.bonigarcia.wdm.WebDriverManager;

/**
 * Test with Google Chrome beta in Windows.
 *
 * @author Boni Garcia
 * @since 5.1.0
 */
class ChromeBetaWindowsTest {

    static String chromeBetaPath = "C:\\\\PROGRA~1\\\\GOOGLE\\\\CHROME~1\\\\APPLIC~1\\\\CHROME.EXE";
    static File chromeBetaFile = new File(chromeBetaPath);

    WebDriver driver;

    @BeforeAll
    static void setupClass() {
        assumeThat(chromeBetaFile).exists();
        String chromeBetaCommand = String.format(
                "cmd.exe /C wmic datafile where name=\"%s\" get Version /value",
                chromeBetaPath);
        WebDriverManager.chromedriver()
                .browserVersionDetectionCommand(chromeBetaCommand).setup();
    }

    @BeforeEach
    void setupTest() {
        ChromeOptions chromeOptions = new ChromeOptions();
        chromeOptions.setBinary(chromeBetaPath);
        driver = new ChromeDriver(chromeOptions);
    }

    @AfterEach
    void teardown() {
        driver.quit();
    }

    @Test
    void test() {
        driver.get("https://bonigarcia.dev/selenium-webdriver-java/");
        assertThat(driver.getTitle()).contains("Selenium WebDriver");
    }

}

Include test using Chrome Beta in Windows


/*
 * This file is part of COMPASS. It is subject to the license terms in
 * the LICENSE file found in the top-level directory of this distribution.
 * (Also available at http://www.apache.org/licenses/LICENSE-2.0.txt)
 * You may not use this file except in compliance with the License.
 */
package de.dfki.asr.compass.model;

import java.io.IOException;
import org.testng.annotations.Test;
import static org.testng.Assert.*;

public class ProjectDeepCopyTest {

	@Test
	public void deepCopyProjectDeepCopies() throws IOException, ClassNotFoundException {
		Project originalProject = initializeProject();
		Project copiedProject = (Project) originalProject.deepCopy();
		assertTrue(projectIsCopy(originalProject, copiedProject));
	}

	@Test
	public void deepCopyProjectClearedIDs() throws IOException, ClassNotFoundException {
		Boolean clearedIDs = true;
		Project originalProject = initializeProject();
		Project copiedProject = (Project) originalProject.deepCopy();
		if (copiedProject.getId() != 0) {
			clearedIDs = false;
		}
		for (Scenario s: copiedProject.getScenarios()) {
			if (s.getId() != 0) {
				clearedIDs = false;
			}
		}
		assertTrue(clearedIDs);
	}
	private Project initializeProject() {
		Project originalProject = new Project("testProject");
		Scenario scenarioA = new Scenario();
		Scenario scenarioB = new Scenario();

		scenarioA.setName("scenarioA");
		scenarioB.setName("scenarioB");

		scenarioA.getRoot().setName("rootA");
		scenarioB.getRoot().setName("rootB");

		originalProject.addScenario(scenarioA);
		originalProject.addScenario(scenarioB);

		return originalProject;
	}

	private Boolean projectIsCopy(final Project original, final Project copy ) {
		if (!(original.getName().equals(copy.getName()))) {
			return false;
		}
		if (original.getScenarios().size() != copy.getScenarios().size()) {
			return false;
		}
		for (Scenario s: original.getScenarios()) {
			int scenarioIndex = original.getScenarios().indexOf(s);
			Scenario c = copy.getScenarios().get(scenarioIndex);
			if (!scenarioIsCopy(s, c)) {
				return false;
			}
		}
		return true;
	}

	private Boolean scenarioIsCopy(final Scenario original, final Scenario copy) {
		//Just check whether scenarios have been copied by comparing their name.
		//DeepCopy for sceneNodes working correctly is tested seperately and can
		//be assumed to be true here
		if (!(original.getName().equals(copy.getName()))) {
			return false;
		}
		SceneNode rootA = original.getRoot();
		SceneNode rootB = copy.getRoot();

		if (!(rootA.getName().equals(rootB.getName()))) {
			return false;
		}
		return true;
	}
}

Test for deep copying projects

Test for deep copying projects


/*
 * eXist-db Open Source Native XML Database
 * Copyright (C) 2001 The eXist-db Authors
 *
 * info@exist-db.org
 * http://www.exist-db.org
 *
 * 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., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 */
package org.exist.xquery.functions.fn;

import com.googlecode.junittoolbox.ParallelRunner;
import org.exist.test.ExistXmldbEmbeddedServer;
import org.exist.xquery.XPathException;
import org.junit.ClassRule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.xmldb.api.base.ResourceSet;
import org.xmldb.api.base.XMLDBException;

import static org.junit.Assert.assertEquals;

/**
 * @author Dannes Wessels
 */
@RunWith(ParallelRunner.class)
public class FunDocumentUriTest {

    @ClassRule
    public static final ExistXmldbEmbeddedServer existEmbeddedServer = new ExistXmldbEmbeddedServer(true, true, true);

    @Test
    public void testFnFunDocumentUri() {

        try {
            final ResourceSet resourceSet = existEmbeddedServer.executeQuery(
                    "declare context item := 'a'; document-uri()");

        } catch (XMLDBException ex) {
            XPathException cause = (XPathException) ex.getCause();
            assertEquals("XPTY0004", cause.getErrorCode().getErrorQName().getLocalPart());
        }
    }
}

Add test that can not be tested in XQsuite.


package org.sjj.csvstream;

import static org.junit.Assert.*;
import org.junit.Test;

public class QuotingTest {
  @Test
  public void testEncodeDecodeNestedQuotes() {
    String[] inner_data = { "3.14", "test test", "abc", "123,456.00" };
    CsvFormatter formatter = new CsvFormatter();
    String cell = formatter.format(inner_data);
    String[] outer_data = { cell, "another test", "Pipe | Test"};
    formatter = new CsvFormatter(CsvConfig.DEFAULTS.withDelimiter('|'));

    String encoded_string = formatter.format(outer_data);
//    System.out.println("Encoded_string: " + encoded_string);

    // Now break the encoded-string back apart and make sure we get the data back out.
    String[] new_outer_data = CsvParser.split(encoded_string, '|');
    for (int i = 0; i < outer_data.length; i++) {
      assertEquals(outer_data[i], new_outer_data[i]);
    }
    String[] new_inner_data = CsvParser.split(outer_data[0]);
    for (int i = 0; i < inner_data.length; i++) {
      assertEquals(inner_data[i], new_inner_data[i]);
    }
  }

}

Add test for nested CSVs

Add test for nested CSVs


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

import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
import junit.textui.TestRunner;

/**
 * Issue-specific test suite for Commons SCXML.
 *
 */
public class IssuesTestSuite extends TestCase {

    /**
     * Construct a new instance.
     */
    public IssuesTestSuite(String name) {
        super(name);
    }

    /**
     * Command-line interface.
     */
    public static void main(String[] args) {
        TestRunner.run(suite());
    }

    /**
     * Get the suite of tests
     */
    public static Test suite() {
        TestSuite suite = new TestSuite();
        suite.setName("Commons SCXML Issues Tests");
        return suite;
    }
}

Add the oacs.issues test package for adding tests specific to an issue (and its fix, if any).

git-svn-id: 5d8fe9a566db79829532a6a4175371ceef757e7a@608640 13f79535-47bb-0310-9956-ffa450edef68


/*
 * Copyright 2015 Open Networking Laboratory
 *
 * 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.onosproject.vtnrsc.virtualport;

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.notNullValue;
import static org.onlab.junit.ImmutableClassChecker.assertThatClassIsImmutable;

import org.junit.Test;
import org.onlab.packet.IpAddress;
import org.onosproject.vtnrsc.FixedIp;
import org.onosproject.vtnrsc.SubnetId;

import com.google.common.testing.EqualsTester;

/**
 * Unit tests for FixedIp class.
 */
public class FixedIpTest {

    final SubnetId subnetId1 = SubnetId.subnetId("lef11-95w-4er-9c9c");
    final SubnetId subnetId2 = SubnetId.subnetId("lefaa-95w-4er-9c9c");
    final IpAddress ip1 = IpAddress.valueOf("192.168.0.1");
    final IpAddress ip2 = IpAddress.valueOf("192.168.1.1");

    /**
     * Checks that the FixedIp class is immutable.
     */
    @Test
    public void testImmutability() {
        assertThatClassIsImmutable(FixedIp.class);
    }

    /**
     * Checks the operation of equals().
     */
    @Test
    public void testEquals() {
        FixedIp fixedIp1 = FixedIp.fixedIp(subnetId1, ip1);
        FixedIp fixedIp2 = FixedIp.fixedIp(subnetId1, ip1);
        FixedIp fixedIp3 = FixedIp.fixedIp(subnetId2, ip2);
        new EqualsTester().addEqualityGroup(fixedIp1, fixedIp2)
                .addEqualityGroup(fixedIp3).testEquals();
    }

    /**
     * Checks the construction of a FixedIp object.
     */
    @Test
    public void testConstruction() {
        FixedIp fixedIp = FixedIp.fixedIp(subnetId1, ip1);
        assertThat(ip1, is(notNullValue()));
        assertThat(ip1, is(fixedIp.ip()));
        assertThat(subnetId1, is(notNullValue()));
        assertThat(subnetId1, is(fixedIp.subnetId()));
    }
}

Add the junit test code of FixedIp

[ONOS-3250] Add the junit test code of FixedIp

Change-Id: Ic8a6ff9d81b0bfca667bec49c11399e6cd3838db


package arez.downstream;

import java.io.IOException;
import java.nio.file.Path;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import javax.annotation.Nonnull;
import org.intellij.lang.annotations.RegExp;
import static org.testng.Assert.*;

/**
 * Index into which symbolMap can be loadded and assertions invoked on contents of index.
 */
@SuppressWarnings( "WeakerAccess" )
final class SymbolEntryIndex
{
  private final HashMap<String, ArrayList<SymbolEntry>> _classNameToEntry = new HashMap<>();

  /**
   * Read and build an index from symbolMap file.
   *
   * @param symbolMapPath the path to load symbolMap from.
   * @return the new index.
   * @throws IOException    if there is an error reading file.
   * @throws ParseException if there is an error parsing file.
   */
  @Nonnull
  static SymbolEntryIndex readSymbolMapIntoIndex( @Nonnull final Path symbolMapPath )
    throws IOException, ParseException
  {
    final SymbolEntryIndex index = new SymbolEntryIndex();
    SymbolEntry.readSymbolMap( symbolMapPath, index::addEntry );
    return index;
  }

  private void addEntry( @Nonnull final SymbolEntry entry )
  {
    _classNameToEntry
      .computeIfAbsent( entry.getClassName(), e -> new ArrayList<>() )
      .add( entry );
  }

  /**
   * Verify no entry for ClassName exists in index.
   * If a match is found then fail assertion error.
   *
   * @param pattern the pattern
   */
  void assertNoClassNameMatches( @RegExp( prefix = "^", suffix = "$" ) @Nonnull final String pattern )
  {
    assertNoClassNameMatches( Pattern.compile( "^" + pattern + "$" ) );
  }

  /**
   * Verify no entry for ClassName exists in index.
   * If a match is found then fail assertion error.
   *
   * @param pattern the pattern
   */
  void assertNoClassNameMatches( @Nonnull final Pattern pattern )
  {
    final List<String> matches =
      _classNameToEntry.keySet().stream().filter( n -> pattern.matcher( n ).matches() ).collect( Collectors.toList() );
    if ( !matches.isEmpty() )
    {
      fail( "Expected that the SymbolMap would have no classNames that match pattern " + pattern +
            " but the following classNames match: " + matches );
    }
  }
}

Add index that can be used to load and verify assert conditions about index


package main.java.meterstanden.model;
import java.io.Serializable;

import javax.persistence.*;

@Entity @IdClass(Jaarverbruik.class)
@Table(name = "JAARVERBRUIK", schema = "APP")
public class Jaarverbruik implements Serializable {

	/**
	 *
	 */
	private static final long serialVersionUID = 1L;

	//-----------// PRIVATE VARIABLES //-----------//
	@Id
	private Long id;

	@Id
	private String ms;

	private int jaar;

	private float som;

	//-----------// CONSTRUCTORS //-----------//
	public Jaarverbruik() {
		super();
	}

	//-----------// GETTERS & SETTERS //-----------//

	public Long getId() {
		return id;
	}

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

	public String getMs() {
		return ms;
	}

	public void setMs(String metersoort) {
		this.ms = metersoort;
	}

	public int getJaar() {
		return jaar;
	}

	public void setJaar(int jaar) {
		this.jaar = jaar;
	}

	public float getSom() {
		return som;
	}

	public void setSom(float som) {
		this.som = som;
	}

	//-----------// METHODS //-----------//
	@Override
	public String toString() {
		return "Jaarverbruik [id=" + id + ", metersoort=" + ms + ", jaar=" + jaar + ", som=" + som + "]";
	}
}

Add java DTO for jaarverbruik

Add java DTO for jaarverbruik


package starpunk;

import com.artemis.Entity;
import com.artemis.World;
import com.badlogic.gdx.math.MathUtils;
import starpunk.components.Position;
import starpunk.components.Sprite;

public final class EntityFactory
{
  private EntityFactory()
  {
  }

  /**
   * Create a star entity within a particular bound.
   */
  public static Entity createStar( final World world, final int width, final int height )
  {
    final Entity e = world.createEntity();

    final Position position = new Position();
    position.setX( MathUtils.random( -width / 2, width / 2 ) );
    position.setY( MathUtils.random( -height / 2, height / 2 ) );
    e.addComponent( position );

    final Sprite sprite = new Sprite();
    sprite.setName( "star" );
    final float scale = MathUtils.random( 0.5f, 1f );
    sprite.setScaleY( scale );
    sprite.setScaleX( scale );
    sprite.setR( MathUtils.random( 0.3f, 0.9f ) );
    sprite.setG( MathUtils.random( 0.3f, 0.9f ) );
    sprite.setB( MathUtils.random( 0.3f, 0.9f ) );
    sprite.setA( MathUtils.random( 0.1f, 0.5f ) );
    sprite.setLayer( Sprite.Layer.BACKGROUND );

    e.addComponent( sprite );

    return e;
  }
}

Add a factory method for stars!

Add a factory method for stars!


package MaximumSubarray;

/**
 * User: Danyang
 * Date: 1/22/2015
 * Time: 20:49
 *
 * Find the contiguous subarray within an array (containing at least one number) which has the largest sum.

 For example, given the array [−2,1,−3,4,−1,2,1,−5,4],
 the contiguous subarray [4,−1,2,1] has the largest sum = 6.

 More practice:
 If you have figured out the O(n) solution, try coding another solution using the divide and conquer approach, which is more subtle.

 */
public class Solution {
    /**
     * O(n) iterative is trivial
     * Divide and Conquer Approach
     * O(n lgn)
     * 1. divide in half
     * 2. left max sub
     * 3. right max sub
     * 4. max sub crossing the middle point
     * @param A
     * @return
     */
    public int maxSubArray(int[] A) {
        return maxSubArray(A, 0, A.length);
    }

    int maxSubArray(int[] A, int s, int e) {
        if(s>=e)
            return Integer.MIN_VALUE;
        if(s==e-1)
            return A[s];

        int m = (s+e)/2;
        int l = maxSubArray(A, s, m);
        int r = maxSubArray(A, m, e);
        int c = maxCross(A, s, e, m);
        return Math.max(Math.max(l, r), c);
    }

    int maxCross(int[] A, int s, int e, int m) {
        int max_l = A[m];
        int max_r = A[m];

        int acc = A[m];
        for(int i=m-1; i>=s; i--) {
            acc += A[i];
            max_l = Math.max(max_l, acc);
        }
        acc = A[m];
        for(int i=m+1; i<e; i++) {
            acc += A[i];
            max_r = Math.max(max_r, acc);
        }
        return max_l+max_r-A[m];
    }
}

Divide and Conquer Approach for Max Subarray Problem


package dr.inference.operators;

import dr.inference.model.Parameter;
import dr.math.MathUtils;
import dr.xml.*;

/**
 * @author Chieh-Hsi Wu
 * Operator that performs independent random walks on k elements in a parameter
 */
public class MultipleRandomWalkIntegerOperator extends RandomWalkIntegerOperator{
    public static final String SAMPLE_SIZE = "sampleSize";
    private int sampleSize = 1;
    public MultipleRandomWalkIntegerOperator(Parameter parameter, int windowSize, int sampleSize, double weight) {
        super(parameter,windowSize, weight);
        this.sampleSize = sampleSize;
    }

    public double doOperation() {

        int[] shuffledInd = MathUtils.shuffled(parameter.getDimension());
        int index;
        for(int i = 0; i < sampleSize; i++){

            index = shuffledInd[i];

            // a random non zero integer around old value within windowSize * 2
            int oldValue = (int) parameter.getParameterValue(index);
            int newValue;
            int roll = MathUtils.nextInt(2 * windowSize);
            if (roll >= windowSize) {
                newValue = oldValue + 1 + roll - windowSize;

                if (newValue > parameter.getBounds().getUpperLimit(index))
                    newValue = 2 * (int)(double)parameter.getBounds().getUpperLimit(index) - newValue;
            } else {
                newValue = oldValue - 1 - roll;

                if (newValue < parameter.getBounds().getLowerLimit(index))
                    newValue = 2 * (int)(double)parameter.getBounds().getLowerLimit(index) - newValue;
            }

            parameter.setParameterValue(index, newValue);

        }

        return 0.0;
    }

    public static dr.xml.XMLObjectParser PARSER = new AbstractXMLObjectParser() {

        public String getParserName() {
            return "multipleRandomWalkIntegerOperator";
        }

        public Object parseXMLObject(XMLObject xo) throws XMLParseException {

            double weight = xo.getDoubleAttribute(WEIGHT);

            double w = xo.getDoubleAttribute(WINDOW_SIZE);
            if (w != Math.floor(w)) {
                throw new XMLParseException("The window size of a randomWalkIntegerOperator should be an integer");
            }

            double s = xo.getDoubleAttribute(SAMPLE_SIZE);
            if (s != Math.floor(s)) {
                throw new XMLParseException("The window size of a randomWalkIntegerOperator should be an integer");
            }

            int windowSize = (int)w;
            int sampleSize = (int)s;
            Parameter parameter = (Parameter) xo.getChild(Parameter.class);

            return new MultipleRandomWalkIntegerOperator(parameter, windowSize, sampleSize, weight);
        }

        //************************************************************************
        // AbstractXMLObjectParser implementation
        //************************************************************************

        public String getParserDescription() {
            return "This element returns a random walk operator on a given parameter.";
        }

        public Class getReturnType() {
            return MCMCOperator.class;
        }

        public XMLSyntaxRule[] getSyntaxRules() {
            return rules;
        }

        private XMLSyntaxRule[] rules = new XMLSyntaxRule[]{
                AttributeRule.newDoubleRule(WINDOW_SIZE),
                AttributeRule.newDoubleRule(SAMPLE_SIZE),
                AttributeRule.newDoubleRule(WEIGHT),
                new ElementRule(Parameter.class)
        };

    };

}

Allow multiple independent random walks for different indices of the same parameter.

git-svn-id: 67bc77c75b8364e4e9cdff0eb6560f5818674cd8@2790 ca793f91-a31e-0410-b540-2769d408b6a1


package com.googlecode.gentyref;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

import com.googlecode.gentyref.GenericTypeReflector;

public class GenericTypeReflectorTest extends AbstractGenericsReflectorTest {
	@Override
	protected void testExactSuperclass(Type expectedSuperclass, Type type) {
		// test if it's really seen as a supertype
		assertTrue(GenericTypeReflector.isSuperType(expectedSuperclass, type));

		// test if the supertype of the given class is as expected
		assertEquals(expectedSuperclass, getExactSuperType(type, getClass(expectedSuperclass)));
	}

	@Override
	protected void testInexactSupertype(Type superType, Type subType) {
		// first if it's seen as a supertype
		assertTrue(GenericTypeReflector.isSuperType(superType, subType));

		if (superType instanceof ParameterizedType || superType instanceof Class) {
			// test if it's not exact
			assertFalse(superType.equals(getExactSuperType(subType, getClass(superType))));
		}
	}

	private Type getExactSuperType(Type type, Class<?> searchClass) {
		return GenericTypeReflector.getExactSuperType(type, searchClass);
	}

	@Override
	protected Type getExactReturnType(Method m, Type type) {
		return GenericTypeReflector.getExactReturnType(m, type);
	}

	@Override
	protected Type getExactFieldType(Field f, Type type) {
		return GenericTypeReflector.getExactFieldType(f, type);
	}

}

Rename main class to match project name

Rename main class to match project name

git-svn-id: 326906f25eac0196cf968068262a06313b1d5d7a@5 9a24f7ba-d458-11dd-86d7-074df07e0730


package no.stelar7.api.l4j8.basic.constants.types;

import javafx.util.Pair;

import java.util.*;

public final class InhibitorLocationType
{
    private InhibitorLocationType()
    {
        // empty constructor
    }

    private static final Map<MapType, Map<LaneType, Map<TeamType, Pair<Integer, Integer>>>> inhibs = new EnumMap<>(MapType.class);

    static
    {
        Map<LaneType, Map<TeamType, Pair<Integer, Integer>>> one;
        Map<TeamType, Pair<Integer, Integer>>                two;
        one = inhibs.getOrDefault(MapType.SUMMONERS_RIFT, new HashMap<>());

        two = one.getOrDefault(LaneType.BOT, new HashMap<>());
        two.put(TeamType.BLUE, new Pair<>(3452, 1236));
        two.put(TeamType.RED, new Pair<>(13604, 11316));
        one.put(LaneType.BOT, two);

        two = one.getOrDefault(LaneType.MID, new HashMap<>());
        two.put(TeamType.BLUE, new Pair<>(3203, 3208));
        two.put(TeamType.RED, new Pair<>(11598, 11667));
        one.put(LaneType.MID, two);

        two = one.getOrDefault(LaneType.TOP, new HashMap<>());
        two.put(TeamType.BLUE, new Pair<>(1171, 3571));
        two.put(TeamType.RED, new Pair<>(11261, 13676));
        one.put(LaneType.TOP, two);

        inhibs.put(MapType.SUMMONERS_RIFT, one);
    }

    public static Map<LaneType, Map<TeamType, Pair<Integer, Integer>>> getInhibMap(MapType map)
    {
        return inhibs.get(map);
    }

    public static List<Pair<Integer, Integer>> getInhibs(MapType map)
    {
        List<Pair<Integer, Integer>> retTowers = new ArrayList<>();

        inhibs.getOrDefault(map, new HashMap<>()).forEach((k, v) -> v.forEach((k2, v2) -> retTowers.add(v2)));

        return retTowers;
    }
}

Add summoners rift inhibitors to the api


package leetcode;

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

/**
 * https://leetcode.com/problems/binary-tree-postorder-traversal/
 */
public class Problem145 {
    public static class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

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

    public List<Integer> postorderTraversal(TreeNode root) {
        List<Integer> result = new ArrayList<>();
        Set<TreeNode> set = new HashSet<>();
        Stack<TreeNode> stack = new Stack<>();
        stack.add(root);
        boolean right = false;
        while (!stack.isEmpty()) {
            TreeNode node = stack.pop();
            while (node.left == null) {
                TreeNode n = node.left;
                stack.add(n);
            }

            System.out.println("popping: " + node.val);
            while ((node.left == null || set.contains(node.left))
                && (node.right == null || set.contains(node.right))) {
                System.out.println(node.val);
                result.add(node.val);
                set.add(node);
            }
            if (node.left != null) {
                System.out.println("adding: " + node.left.val);
                stack.add(node.left);
                right = false;
            } else {
                right = true;
                if (right) {
                    if (node.right != null) {
                        System.out.println("adding: " + node.right.val);
                        stack.add(node.right);
                    }
                }
            }
        }
        return result;
    }

    private List<Integer> recursivePostOrderTraversal(TreeNode root) {
        List<Integer> result = new ArrayList<>();
        recursivePostOrderTraversal(root, result);
        return result;
    }

    private void recursivePostOrderTraversal(TreeNode root, List<Integer> result) {
        if (root == null) {
            return;
        }
        recursivePostOrderTraversal(root.left, result);
        recursivePostOrderTraversal(root.right, result);
        result.add(root.val);
    }

    public static void main(String[] args) {
        TreeNode root = new TreeNode(1);
        root.left = new TreeNode(2);
        root.right = new TreeNode(3);
        root.left.left = new TreeNode(4);
        root.left.right = new TreeNode(5);
        root.left.right.right = new TreeNode(6);

        Problem145 prob = new Problem145();
//        System.out.println(prob.recursivePostOrderTraversal(root));
        System.out.println(prob.postorderTraversal(root));
    }
}

Create a skeleton for problem 145

Create a skeleton for problem 145


package de.unistuttgart.iste.rss.bugminer.cli;

import de.unistuttgart.iste.rss.bugminer.computing.SshConnector;
import de.unistuttgart.iste.rss.bugminer.model.entities.Project;
import de.unistuttgart.iste.rss.bugminer.model.repositories.ProjectRepository;
import org.apache.commons.lang.NotImplementedException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.shell.core.CommandMarker;
import org.springframework.shell.core.annotation.CliAvailabilityIndicator;
import org.springframework.shell.core.annotation.CliCommand;
import org.springframework.shell.core.annotation.CliOption;
import org.springframework.stereotype.Component;

import java.util.Optional;

@Component
public class BugsCommand implements CommandMarker {
	@Autowired
	private SshConnector sshConnector;

	@Autowired
	private ProjectsService projectsService;

	@Autowired
	private ProjectRepository projectRepository;

	protected BugsCommand() {
		// managed bean
	}

	@CliCommand(value = "bugs sync", help = "Synchronize the bugs in a repository with upstream issue tracker")
	public String simple(
			@CliOption(key = "project", mandatory = true, help = "the project name") final String projectName) {
		Project project = projectRepository.findByName(projectName)
				.orElseThrow(() -> new IllegalArgumentException("There is no such project"));

		throw new NotImplementedException();
	}
}

Add structure for bugs sync command

Add structure for bugs sync command


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

package com.akiban.server.store.statistics;

import com.akiban.sql.pg.PostgresServerFilesITBase;
import static com.akiban.sql.TestBase.*;

import org.junit.Before;
import org.junit.Test;
import static junit.framework.Assert.*;

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

public class PersistitStoreIndexStatisticsIT extends PostgresServerFilesITBase
{
    public static final File RESOURCE_DIR =
        new File("src/test/resources/"
                 + IndexStatisticsYamlTest.class.getPackage().getName().replace('.', '/'));
    public static final File YAML_FILE = new File(RESOURCE_DIR, "stats.yaml");

    private IndexStatisticsService service;

    @Before
    public void loadDatabase() throws Exception {
        loadDatabase(RESOURCE_DIR);
    }

    @Before
    public void getService() throws Exception {
        service = serviceManager().getServiceByClass(IndexStatisticsService.class);
    }

    @Override
    public void openTheConnection() throws Exception {
        // TODO: Test class modularity isn't right.
    }

    @Test
    public void testLoadDump() throws Exception {
        service.loadIndexStatistics(session(), "user", YAML_FILE);
        File tempFile = File.createTempFile("stats", "yaml");
        service.dumpIndexStatistics(session(), "user", tempFile);
        assertEquals("dump matches load",
                     fileContents(YAML_FILE).replace("\r", ""),
                     fileContents(tempFile).replace("\r", ""));
    }

}

Add an IT for Persistit storage.

Add an IT for Persistit storage.


package org.redalert1741.steamworks;

import org.redalert1741.robotBase.logging.DataLogger;
import org.redalert1741.robotBase.logging.Loggable;

import edu.wpi.first.wpilibj.Spark;

public class Climber implements Loggable
{
	private Spark climber1;
	private Spark climber2;

	public Climber(int c1, int c2)
	{
		climber1 = new Spark(c1);
		climber2 = new Spark(c2);
	}

	@Override
	public void setupLogging(DataLogger logger)
	{
		logger.addAttribute("climber1_Setpoint");
		logger.addAttribute("climber2_Setpoint");
	}

	@Override
	public void log(DataLogger logger)
	{
		logger.log("climber1_Setpoint", climber1.get());
		logger.log("climber2_Setpoint", climber2.get());
	}

}

Add basic climber with logging

Add basic climber with logging


package gate.plugin.learningframework.pipelines;

import gate.creole.PackagedController;
import gate.creole.metadata.AutoInstance;
import gate.creole.metadata.AutoInstanceParam;
import gate.creole.metadata.CreoleResource;

/**
 *
 * @author Johann Petrak <johann.petrak@gmail.com>
 */
@CreoleResource(
        name = "LF_TrainTopicModel-Mallet-EN",
        comment = "Example steps to prepare and train a topic model using Mallet LDA",
        // icon = "measurements",
        autoinstances = @AutoInstance(parameters = {
          @AutoInstanceParam(name="pipelineURL", value="resources/pipelines/LF_TrainTopicModel-Mallet-EN.xgapp"),
          @AutoInstanceParam(name="menu", value="LearningFramework")}))
public class LF_TrainTopicModel_Mallet_EN extends PackagedController {

}

Add the file for creating the ready made topic model training app.


package com.alexrnl.jbetaseries.request.shows;

import com.alexrnl.jbetaseries.request.APIAddresses;
import com.alexrnl.jbetaseries.request.Request;
import com.alexrnl.jbetaseries.request.Verb;
import com.alexrnl.jbetaseries.request.parameters.ShowId;

/**
 * Unset the note on a given show for the identified user.

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

	/**
	 * Constructor #1.

	 * @param showId
	 *        the id of the show.
	 */
	public ShowUnnote (final Integer showId) {
		super(Verb.DELETE, APIAddresses.SHOWS_NOTE);
		addParameter(new ShowId(showId));
	}
}

Add the shows/note DELETE request

Add the shows/note DELETE request


package leetcode;

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

/**
 * @author fredy
 */
public class Problem341 {
    public interface NestedInteger {
        // @return true if this NestedInteger holds a single integer, rather than a nested list.
        public boolean isInteger();

        // @return the single integer that this NestedInteger holds, if it holds a single integer
        // Return null if this NestedInteger holds a nested list
        public Integer getInteger();

        // @return the nested list that this NestedInteger holds, if it holds a nested list
        // Return null if this NestedInteger holds a single integer
        public List<NestedInteger> getList();
    }

    public static class NestedIterator implements Iterator<Integer> {
        public NestedIterator(List<NestedInteger> nestedList) {
            // TODO
        }

        @Override
        public Integer next() {
            // TODO:
            return null;
        }

        @Override
        public boolean hasNext() {
            // TODO:
            return false;
        }
    }

    public static void main(String[] args) {
        NestedIterator i = new NestedIterator(null);
        while (i.hasNext()) {
            System.out.println(i.next());
        }
    }
}

Create a skeleton for problem 341

Create a skeleton for problem 341


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

import jaist.echonet.EOJ;
import jaist.echonet.EchonetCharacterProperty;
import jaist.echonet.EchonetNode;
import jaist.echonet.EchonetProperty;
import jaist.echonet.LocalEchonetObject;
import jaist.echonet.gui.NetworkScanner;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author haha
 */
public class TemperatureSensorApp {

    EchonetNode context;
    LocalEchonetObject temperaturesensor;
    byte numberofsensors = 1;
    static byte TEMPSENSORCLASSGROUP = 0x00;
    static byte TEMPSENSORCLASS = 0x11;

    public static void main(String args[]) {
        InetAddress address = null;
        try {
            if (args.length > 0) {
                address = InetAddress.getByName(args[0]);
            }
        } catch (UnknownHostException ex) {
            Logger.getLogger(NetworkScanner.class.getName()).log(Level.SEVERE, null, ex);
        }
        new TemperatureSensorApp(address);
    }

    public TemperatureSensorApp(InetAddress address) {
        context = new EchonetNode(address);
        context.registerEchonetObject(getTemperatureSensorInstance());
        Thread t = context.start();
        //prevent exit of program; t is a daemon thread.
        while (true) {
            try {
                t.join();
            } catch (InterruptedException ex) {
                Logger.getLogger(TemperatureSensorApp.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }

    private LocalEchonetObject getTemperatureSensorInstance() {
        EOJ sensoreoj = new EOJ(TEMPSENSORCLASSGROUP, TEMPSENSORCLASS, numberofsensors++);
        List<EchonetProperty> properties = new ArrayList<>();
        properties.add(new EchonetCharacterProperty((byte) 0x80, true, false, true, 1, 0, new byte[]{0x30}));
        properties.add(new EchonetProperty((byte) 0xE0, true, false, true, 2, 1) {

            short temperature = 0;

            @Override
            public byte[] read() {
                byte[] result = new byte[2];
                //convert the temperature
                result[0] = (byte) (temperature >> 8);
                result[1] = (byte) (temperature & 0x00ff);
                System.out.println("Current temperature: " + temperature * 10 + "\n");

                //increase temperature for next time
                temperature++;
                return result;
            }

            @Override
            public boolean write(byte[] data) {
                throw new UnsupportedOperationException("This will never be called");
            }

            @Override
            public boolean isEmpty() {
                return false;
            }
        });

        LocalEchonetObject sensor = new LocalEchonetObject(sensoreoj, properties);
        return sensor;
    }
}

Add sample temperature sensor application.


/*
 * Copyright 2015 Michael Rozumyanskiy
 *
 * 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.michaelrocks.lightsaber;

import javax.inject.Provider;

public class SingletonProvider<T> implements Provider<T> {
    private final Provider<T> provider;
    private volatile T instance;
    private final Object instanceLock = new Object();

    public SingletonProvider(final Provider<T> provider) {
        this.provider = provider;
    }

    @Override
    public T get() {
        if (instance == null) {
            synchronized (instanceLock) {
                if (instance == null) {
                    instance = provider.get();
                }
            }
        }
        return instance;
    }
}

Implement provider for singleton scope

Implement provider for singleton scope


package gov.nih.nci.objectCart.jUnit.applicationService.impl;
import gov.nih.nci.objectCart.util.xml.ValidationErrorHandler;
import gov.nih.nci.objectCart.util.xml.Validator;

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

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import javax.xml.transform.Source;
import javax.xml.transform.stream.StreamSource;
import javax.xml.validation.SchemaFactory;

import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;

import junit.framework.TestCase;

public class GMETest extends TestCase{

		public void test1()
		{
			SAXParserFactory factory = SAXParserFactory.newInstance();
			factory.setValidating(false);
			factory.setNamespaceAware(true);

			SchemaFactory schemaFactory = SchemaFactory
					.newInstance("http://www.w3.org/2001/XMLSchema");

			String schema = Validator.getSchema("gme://caCORE.caBIG/3.0/gov.nih.nci.cadsr.domain");

			System.out.println(schema);
//			try {
//			factory.setSchema(
//					schemaFactory.newSchema(
//							new Source[] {new StreamSource(schema)} ));
//
//			SAXParser parser = factory.newSAXParser();
//
//			XMLReader reader = parser.getXMLReader();
//
//			reader.setErrorHandler(new ValidationErrorHandler());
//			StringReader strReader = new StringReader("TEST DATA HERE");
//			InputSource inputSource = new InputSource(strReader);
//
//			reader.parse(inputSource);
//
//			} catch (SAXException se){
//				se.printStackTrace();
//			} catch (IOException ioe){
//				ioe.printStackTrace();
//			} catch (ParserConfigurationException pce){
//				pce.printStackTrace();
//			}
		}

}

Test for GME connection.  Still not working

SVN-Revision: 9


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

package com.ajah.spring.mvc.editor;

import java.beans.PropertyEditorSupport;

import com.ajah.util.Identifiable;

/**
 * Generic class that will map an enum based on its {@link Identifiable#getId()}
 * method.
 *
 * @author Eric F. Savage, code@efsavage.com.
 *
 * @param <E>
 */
public class IdentifiableEnumPropertyEditor<E extends Identifiable<?>> extends PropertyEditorSupport {

	private E[] values;

	/**
	 * Pass the result of Enum.getValues() because I can't seem to find a way to
	 * derive this from the type parameter.
	 *
	 * @param values
	 *            The values of the enum.
	 */
	public IdentifiableEnumPropertyEditor(E[] values) {
		this.values = values;
	}

	/**
	 * Sets the property value by parsing a given String. May raise
	 * java.lang.IllegalArgumentException if either the String is badly
	 * formatted or if this kind of property can't be expressed as text.
	 *
	 * @param text
	 *            The string to be parsed.
	 */
	@Override
	public void setAsText(String text) throws java.lang.IllegalArgumentException {
		for (E candidate : this.values) {
			if (candidate.getId().toString().equals(text)) {
				setValue(candidate);
				return;
			}
		}
		throw new java.lang.IllegalArgumentException(text);
	}

	/**
	 * Gets the property value as a string suitable for presentation to a human
	 * to edit.
	 *
	 * @return The property value as a string suitable for presentation to a
	 *         human to edit.
	 *

	 *         Returns null if the value can't be expressed as a string.
	 *

	 *         If a non-null value is returned, then the PropertyEditor should
	 *         be prepared to parse that string back in setAsText().
	 */
	@SuppressWarnings("unchecked")
	@Override
	public String getAsText() {
		return (this.getValue() != null) ? ((E) this.getValue()).getId().toString() : null;
	}

}

Add property editor for identifiable enums


public class Solution {

    public int rob(int[] nums) {

        int current = 0;
        int last = 0;

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

            int tmp = current;
            current = Math.max(last + nums[i], current);
            last = tmp;

        }

        return current;

    }

}

Create : 198 House Robber

Create : 198 House Robber


package org.jdbi.v3.pg;

import com.opentable.db.postgres.embedded.EmbeddedPostgreSQLRule;

import org.jdbi.v3.DBI;
import org.jdbi.v3.Handle;
import org.junit.rules.TestRule;
import org.junit.runner.Description;
import org.junit.runners.model.Statement;

/**
 * Helper for a single, superuser privileged Postgres database.
 */
public class PostgresDbRule implements TestRule {

    public EmbeddedPostgreSQLRule pg = new EmbeddedPostgreSQLRule();
    private DBI dbi;
    private Handle h;

    @Override
    public Statement apply(Statement base, Description description) {
        return pg.apply(new Statement() {
            @Override
            public void evaluate() throws Throwable {
                dbi = DBI.create(pg.getEmbeddedPostgreSQL().getDatabase("postgres", "postgres"))
                        .installPlugin(new PostgresJdbiPlugin());
                h = dbi.open();

                try {
                    base.evaluate();
                } finally {
                    dbi = null;
                    h.close();
                    h = null;
                }
            }
        }, description);
    }

    public DBI getDbi() {
        if (dbi == null) throw new AssertionError("Test not running");
        return dbi;
    }

    public Handle getSharedHandle() {
        if (h == null) throw new AssertionError("Test not running");
        return h;
    }
}

Add a Rule to make writing tests easy

Add a Rule to make writing tests easy


/*
 * Copyright 2011 Google Inc.
 *
 * 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.bitcoin.examples;

import com.google.bitcoin.core.*;

import java.io.File;
import java.math.BigInteger;
import java.net.InetAddress;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

/**
 * RefreshWallet loads a wallet, then processes the block chain to update the transaction pools within it.
 */
public class RefreshWallet {
    public static void main(String[] args) throws Exception {
        File file = new File(args[0]);
        Wallet wallet = Wallet.loadFromFile(file);
        System.out.println(wallet.toString());

        // Set up the components and link them together.
        final NetworkParameters params = NetworkParameters.testNet();
        BlockStore blockStore = new MemoryBlockStore(params);
        NetworkConnection conn = new NetworkConnection(InetAddress.getLocalHost(), params,
                                                       blockStore.getChainHead().getHeight(), 60000);
        BlockChain chain = new BlockChain(params, wallet, blockStore);
        Peer peer = new Peer(params, conn, chain);
        peer.start();

        wallet.addEventListener(new WalletEventListener() {
            public void onCoinsReceived(Wallet w, Transaction tx, BigInteger prevBalance, BigInteger newBalance) {
                System.out.println("\nReceived tx " + tx.getHashAsString());
                System.out.println(tx.toString());
            }
        });

        // Now download and process the block chain.
        CountDownLatch progress = peer.startBlockChainDownload();
        long max = progress.getCount();  // Racy but no big deal.
        if (max > 0) {
            System.out.println("Downloading block chain. " + (max > 1000 ? "This may take a while." : ""));
            long current = max;
            while (current > 0) {
                double pct = 100.0 - (100.0 * (current / (double) max));
                System.out.println(String.format("Chain download %d%% done", (int) pct));
                progress.await(1, TimeUnit.SECONDS);
                current = progress.getCount();
            }
        }
        peer.disconnect();
        wallet.saveToFile(file);
        System.out.println("\nDone!\n");
        System.out.println(wallet.toString());
    }
}

Add a program that just loads a wallet, runs through the block chain, and then saves/prints out the resulting wallet at the end.


/*
 * Copyright 2013-2016 Netherlands Forensic Institute
 *
 * 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 nl.minvenj.nfi.metal;

import static nl.minvenj.nfi.metal.Shorthand.con;
import static nl.minvenj.nfi.metal.Shorthand.def;
import static nl.minvenj.nfi.metal.Shorthand.ref;
import static nl.minvenj.nfi.metal.Shorthand.seq;

import java.io.IOException;

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

import nl.minvenj.nfi.metal.data.ByteStream;
import nl.minvenj.nfi.metal.data.Environment;
import nl.minvenj.nfi.metal.data.ParseResult;
import nl.minvenj.nfi.metal.encoding.Encoding;
import nl.minvenj.nfi.metal.token.Token;
import nl.minvenj.nfi.metal.util.InMemoryByteStream;

public class DefSizeTest {
    public static final Token FORMAT =
        seq(
            def("length", con(4)),
            def("data", ref("length"))
        );

    @Test
    public void testValidLength() throws IOException {
        final ByteStream stream = new InMemoryByteStream(new byte[]{
            0x00, 0x00, 0x00, 0x02, // length = 2
            0x04, 0x08
        });
        final ParseResult result = FORMAT.parse(new Environment(stream), new Encoding());

        Assert.assertTrue(result.succeeded());
        Assert.assertArrayEquals(
            new byte[]{0x04, 0x08},
            result.getEnvironment().order.flatten().get("data").getValue()
        );
    }

    @Test
    public void testInvalidLength() throws IOException {
        final ByteStream stream = new InMemoryByteStream(new byte[]{
            -1, -1, -1, -1, // length = -1
            0x04, 0x08
        });
        final ParseResult result = FORMAT.parse(new Environment(stream), new Encoding());

        Assert.assertFalse(result.succeeded());
        Assert.assertEquals(-1, result.getEnvironment().order.flatten().get("length").asNumeric().intValue());
    }
}

METAL-18: Test valid vs. invalid length reference handling


/*
 * Copyright 2011 Greplin, Inc. All Rights Reserved.
 */

package com.greplin.lucene.query;

import com.sun.istack.internal.Nullable;
import org.apache.lucene.search.BooleanClause;
import org.apache.lucene.search.BooleanFilter;
import org.apache.lucene.search.Filter;
import org.apache.lucene.search.FilterClause;

/**
 * Static utility methods for Filters.
 */
public final class Filters {

  /** Not instantiable. */
  private Filters() { }

  /**
   * Returns a filter that allows documents that match every constituent
   * filter.  For convenience, null values are accepted and ignored.  If
   * all values are null, null will be returned.
   * @param filters the filters to combine
   * @return the combined filter
   */
  @Nullable public static Filter and(@Nullable final Filter... filters) {
    final BooleanFilter booleanFilter = new BooleanFilter();

    Filter lastFilter = null;
    int count = 0;
    for (Filter filter : filters) {
      if (filter != null) {
        booleanFilter.add(new FilterClause(filter, BooleanClause.Occur.MUST));
        count += 1;
        lastFilter = filter;
      }
    }

    if (count == 0) {
      return null;
    } else if (count == 1) {
      return lastFilter;
    } else {
      return booleanFilter;
    }
  }

  /**
   * Returns a filter matching the inverse of the given filter.
   * @param filter the filter to return the opposite ofnegate
   * @return the negated filter
   */
  public static Filter not(final Filter filter) {
    final BooleanFilter booleanFilter = new BooleanFilter();
    booleanFilter.add(new FilterClause(filter, BooleanClause.Occur.MUST_NOT));
    return booleanFilter;
  }

}

Add static utility methods for filters

Add static utility methods for filters


package at.ac.tuwien.inso.controller.student;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.security.Principal;
import java.util.List;

import at.ac.tuwien.inso.entity.Course;
import at.ac.tuwien.inso.entity.Student;
import at.ac.tuwien.inso.service.CourseService;
import at.ac.tuwien.inso.service.StudentService;
import at.ac.tuwien.inso.service.SubjectService;
import at.ac.tuwien.inso.service.course_recommendation.RecommendationService;

@Controller
@RequestMapping("/student/courses/semester/subject")
public class StudentCoursesForSemesterAndSubjectController {

    private static final Logger log = LoggerFactory.getLogger(StudentCoursesForSemesterAndSubjectController.class);

    @Autowired
    private CourseService courseService;

    @Autowired
    private SubjectService subjectService;

    @GetMapping
    public String courses(@RequestParam Long subjectId, Model model) {

        log.info("getting courses for subject " + subjectId);

        List<Course> courses = courseService.findCoursesForSubjectAndCurrentSemester(subjectService.findOne(subjectId));

        if (courses.size() == 1) {
            log.info("Subject only has one course this semester. Redirecting to course");
            return "redirect:/student/courses/" + courses.get(0).getId();
        }

        model.addAttribute("coursesForSemesterAndSubject", courses);
        return "/student/courses-for-subject";
    }

}

Add controller for courses of a subject in the current semester


package org.usfirst.frc2832.Robot_2016.vision;

import java.util.NavigableMap;
import java.util.TreeMap;

public class InterpolatedLookupTable {
	private NavigableMap<Double, Double> map;

	public InterpolatedLookupTable() {
		map = new TreeMap<>();
	}

	public void put(double key, double value) {
		map.put(key, value);
	}

	/**
	 * Gets a value, interpolating linearly
	 * @param key The key, or x-coordinate
	 * @return The value at key, or the analytic expansion of it
	 */
	public double get(double key) {
		if (map.containsKey(key))
			return (map.get(key));

		Double keyHigh = map.higherKey(key);
		Double keyLow  = map.lowerKey(key);

		if (keyHigh == null)
			keyHigh = map.lastKey();
		if (keyLow == null)
			keyLow = map.firstKey();

		double valLow = map.get(keyLow);
		double valHigh = map.get(keyHigh);

		if (keyHigh == keyLow)
			return (valLow);

		double t = (key - keyLow) / (keyHigh - keyLow);
		return ((1 - t) * valLow + (t) * valHigh);
	}
}

Add amazing lookup table class

Add amazing lookup table class


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

package org.apache.flink.api.connector.sink;

import org.apache.flink.api.common.serialization.SerializationSchema;
import org.apache.flink.metrics.MetricGroup;
import org.apache.flink.util.UserCodeClassLoader;

import java.util.function.Supplier;

/**
 * Adapter between {@link Sink.InitContext} and {@link SerializationSchema.InitializationContext}.
 */
public class InitContextInitializationContextAdapter
        implements SerializationSchema.InitializationContext {

    private final UserCodeClassLoader userCodeClassLoader;
    private final Supplier<MetricGroup> metricGroupSupplier;
    private MetricGroup cachedMetricGroup;

    public InitContextInitializationContextAdapter(
            UserCodeClassLoader userCodeClassLoader, Supplier<MetricGroup> metricGroupSupplier) {
        this.userCodeClassLoader = userCodeClassLoader;
        this.metricGroupSupplier = metricGroupSupplier;
    }

    @Override
    public MetricGroup getMetricGroup() {
        if (cachedMetricGroup == null) {
            cachedMetricGroup = metricGroupSupplier.get();
        }
        return cachedMetricGroup;
    }

    @Override
    public UserCodeClassLoader getUserCodeClassLoader() {
        return userCodeClassLoader;
    }
}

[hotfix][core] Add adapter between Sink.InitContext and SerializationSchema.InitializationContext


package com.thinkbiganalytics.metadata.upgrade.v084;

/*-
 * #%L
 * kylo-upgrade-service
 * %%
 * Copyright (C) 2017 ThinkBig Analytics
 * %%
 * 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.
 * #L%
 */

import com.thinkbiganalytics.KyloVersion;
import com.thinkbiganalytics.metadata.modeshape.JcrMetadataAccess;
import com.thinkbiganalytics.server.upgrade.KyloUpgrader;
import com.thinkbiganalytics.server.upgrade.UpgradeException;
import com.thinkbiganalytics.server.upgrade.UpgradeState;

import org.modeshape.jcr.api.Workspace;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Profile;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import javax.jcr.RepositoryException;

/**
 * Initializes all of the ModeShape indexes introduced in 0.8.4.
 */
@Component("reindexUpgradeAction084")
@Order(0)
@Profile(KyloUpgrader.KYLO_UPGRADE)
public class ReindexUpgradeAction implements UpgradeState {

    private static final Logger log = LoggerFactory.getLogger(ReindexUpgradeAction.class);

    @Override
    public boolean isTargetVersion(KyloVersion version) {
        return version.matches("0.8", "4", "");
    }

    @Override
    public void upgradeTo(final KyloVersion startingVersion) {
        log.info("Re-indexing metadata for version:: {}", startingVersion);

        try {
            Workspace workspace = (Workspace) JcrMetadataAccess.getActiveSession().getWorkspace();
            workspace.reindex();
        } catch (RepositoryException e) {
            log.error("Failed to re-index metadata", e);
            throw new UpgradeException("Failed to re-index metadata", e);
        }
    }
}

KYLO-1188: Initialize ModeShape indexes during 0.8.4 upgrade.


/*
 * Copyright 2019, TeamDev. All rights reserved.
 *
 * Redistribution and use in source and/or binary forms, with or without
 * modification, must retain the above copyright notice and the following
 * disclaimer.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

package io.spine.io;

import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.junitpioneer.jupiter.TempDirectory;
import org.junitpioneer.jupiter.TempDirectory.TempDir;

import java.io.File;
import java.net.URL;
import java.nio.file.Path;
import java.util.Iterator;
import java.util.UUID;

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

@DisplayName("Resource files should")
@ExtendWith(TempDirectory.class)
class ResourceFilesTest {

    @Test
    @DisplayName("return an empty iterator if queried for a non-existing file ")
    void throwOnInvalidFileName(@TempDir Path path) {
        Path nonExistentFilePath = path.resolve(UUID.randomUUID()
                                                    .toString());
        File nonExistingFile = nonExistentFilePath.toFile();
        String name = nonExistingFile.getName();
        Iterator<URL> result = ResourceFiles.loadAll(name);
        assertFalse(result.hasNext());
    }
}

Add a resource files test.

Add a resource files test.


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

import static org.junit.Assert.assertEquals;

import org.testng.annotations.Test;

public class DeliverSmTest {

  @Test
  public void testDeliverSm() {
    DeliverSm deliverSm = new DeliverSm();
    deliverSm.sourceAddr = "31612345678";
    deliverSm.sourceAddrTon = TypeOfNumber.INTERNATIONAL.value();
    deliverSm.sourceAddrNpi = NumberingPlanIndicator.ISDN.value();
    deliverSm.destAddress = "33600000000";
    deliverSm.destAddrTon = TypeOfNumber.INTERNATIONAL.value();
    deliverSm.destAddrNpi = NumberingPlanIndicator.ISDN.value();
    deliverSm.setOptionalParameters(
        new OptionalParameter.Message_state((byte) 0x02),
        new OptionalParameter.Receipted_message_id("123456"));

    assertEquals(OptionalParameter.Message_state.Message_state_enum.DELIVERED,
        ((OptionalParameter.Message_state)deliverSm.getOptionalParameter(OptionalParameter.Tag.MESSAGE_STATE)).getMessageState());
    assertEquals("123456",
        ((OptionalParameter.Receipted_message_id) deliverSm.getOptionalParameter(OptionalParameter.Tag.RECEIPTED_MESSAGE_ID)).getValueAsString());
  }

}

Add unit test for deliver_sm with optional parameters.


package whelk.export.servlet;

import org.junit.Assert;
import org.junit.Test;
import whelk.Document;
import whelk.Whelk;
import whelk.triples.JsonldSerializer;

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

public class Other {
    /**
     * These tests have nothing to do with OAIPMH. Rather they are here because this test suite is the only one that
     * combines requiring example data, and being able to do white box code testing (test code internals).
     */

    /**
     * This test case dissolves a record into triples, and then reassembles the tripples. The reassembled version
     * must equal the original version.
     */
    /* This testcase unfortunately breaks due to repeatableTerms/forcedSetTerms inconsistencies. Reactivate once fixed!
    @Test
    public void testTripleDissolutionReassembly() throws Exception
    {
        Whelk whelk = Whelk.createLoadedCoreWhelk();
        Set<String> repeatableTerms = whelk.getJsonld().getRepeatableTerms();

        Document originalDocument = whelk.getStorage().load("s93qhl340tcvtcp"); // Alice in Wonderland and Through the looking-glass

        List<String[]> triples = new JsonldSerializer().deserialize(originalDocument.data);

        Document reassembledDocument = new Document(JsonldSerializer.serialize(triples, repeatableTerms));
        JsonldSerializer.normalize(reassembledDocument.data, reassembledDocument.getCompleteId(), false);
        JsonldSerializer.normalize(reassembledDocument.data, reassembledDocument.getCompleteId(), false);

        //System.out.println("original:\n" + originalDocument.getDataAsString());
        //System.out.println("reassembly:\n" + reassembledDocument.getDataAsString());

        Assert.assertEquals(reassembledDocument.getChecksum(), originalDocument.getChecksum());
    }
    */
}

Add triple-reassembly testcase. Unfortunately it won't pass at the moment, because the 'repeatableterms' logic isn't completely consistent.


/*
 * Copyright 2012 Splunk, Inc.
 *
 * 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.splunk;

import java.util.Map;

import org.junit.Test;

public class EntityTest extends SDKTestCase {
    private static final String QUERY = "search index=_internal | head 10";

    private static final String KEY = "isSavedSearch";
    private static final String VALUE = "0";

    @Test
    public void testMapOverrides() {
        Entity entity = service.getJobs().create(QUERY);

        assertFalse(entity.isEmpty());
        assertEquals(VALUE, entity.get(KEY));
        assertTrue(entity.containsKey(KEY));
        assertTrue(entity.containsValue(VALUE));
        assertTrue(entity.keySet().contains(KEY));
        assertTrue(entity.values().contains(VALUE));
        for (Map.Entry<String, Object> e : entity.entrySet()) {
            assertTrue(entity.containsKey(e.getKey()));
            assertTrue(entity.containsValue(e.getValue()));
        }

        try {
            entity.putAll(null);
            fail("Expected UnsupportedOperationException.");
        } catch (UnsupportedOperationException e) {
            // Good
        }

        try {
            entity.clear();
            fail("Expected UnsupportedOperationException.");
        } catch (UnsupportedOperationException e) {
            // Good
        }

        try {
            entity.remove(null);
            fail("Expected UnsupportedOperationException.");
        } catch (UnsupportedOperationException e) {
            // Good
        }
    }
}

Test map overrides on Entity.

Test map overrides on Entity.


package info.u_team.u_team_test2.init;

import org.apache.logging.log4j.LogManager;

import info.u_team.u_team_core.api.construct.*;
import info.u_team.u_team_test2.TestMod2;
import net.minecraft.block.Block;
import net.minecraftforge.event.RegistryEvent.Register;
import net.minecraftforge.fml.common.Mod.EventBusSubscriber.Bus;

@Construct(modid = TestMod2.MODID)
public class Test2CommonBusRegister implements IModConstruct {

	@Override
	public void construct() {
		Bus.MOD.bus().get().addGenericListener(Block.class, this::registerCall);
	}

	private void registerCall(Register<Block> event) {
		LogManager.getLogger().info("Hello from the register event for test mod 2");
	}

}

Add test common bus register for test mod 2


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

package org.apache.karaf.tooling.exam.regression;

import static junit.framework.Assert.assertFalse;
import static junit.framework.Assert.assertTrue;
import static org.apache.karaf.tooling.exam.options.KarafDistributionOption.editConfigurationFilePut;
import static org.apache.karaf.tooling.exam.options.KarafDistributionOption.karafDistributionConfiguration;
import static org.ops4j.pax.exam.CoreOptions.maven;
import static org.ops4j.pax.exam.CoreOptions.scanFeatures;

import javax.inject.Inject;

import org.apache.karaf.features.FeaturesService;
import org.apache.karaf.tooling.exam.options.configs.FeaturesCfg;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.ops4j.pax.exam.Option;
import org.ops4j.pax.exam.junit.Configuration;
import org.ops4j.pax.exam.junit.ExamReactorStrategy;
import org.ops4j.pax.exam.junit.JUnit4TestRunner;
import org.ops4j.pax.exam.spi.reactors.AllConfinedStagedReactorFactory;

/**
 * This test should validate if the versionAsInProject tags work as expected.
 */
@RunWith(JUnit4TestRunner.class)
@ExamReactorStrategy(AllConfinedStagedReactorFactory.class)
public class MixFeatureAndDeployFolderFalseTest {

    @Inject
    private FeaturesService featuresService;

    @Configuration
    public Option[] config() {
        return new Option[]{
            karafDistributionConfiguration()
                .frameworkUrl(
                    maven().groupId("org.apache.karaf").artifactId("apache-karaf").type("zip")
                        .versionAsInProject())
                .useDeployFolder(false), editConfigurationFilePut(FeaturesCfg.BOOT,
                "config,standard,region,package,ssh"),
            scanFeatures(maven().groupId("org.apache.karaf.features").artifactId("standard").type("xml")
                .classifier("features").versionAsInProject(), "kar").start() };
    }

    @Test
    public void test() throws Exception {
        assertFalse(featuresService.isInstalled(featuresService.getFeature("management")));
        assertTrue(featuresService.isInstalled(featuresService.getFeature("kar")));
    }

}

Add itest to prove fixes

[KARAF-1406,KARAF-1407] Add itest to prove fixes

Signed-off-by: Andreas Pieber <anpieber@gmail.com>

git-svn-id: 71d8a689455c5fbb0f077bc40adcfc391e14cb9d@1330774 13f79535-47bb-0310-9956-ffa450edef68


/*
 * Java Genetic Algorithm Library (@__identifier__@).
 * Copyright (c) @__year__@ Franz Wilhelmstötter
 *
 * 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.
 *
 * Author:
 *    Franz Wilhelmstötter (franz.wilhelmstoetter@gmx.at)
 */
package org.jenetics.example.tsp;

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

import org.testng.annotations.Test;

import org.jenetics.example.tsp.GPX.*;

/**
 * @author Franz Wilhelmstötter
 * @version !__version__!
 * @since !__version__!
 */
public class GPXTest {

	@Test
	public void writeGPX() throws IOException {
		final GPX gpx = new GPX();
		gpx.addWayPoint(GPX.Location.of(23, 34));
		gpx.addWayPoint(GPX.Location.of(24, 35));

		GPX.write(gpx, System.out);
	}

	@Test
	public void readGPX() throws IOException {
		final String resource = "/org/jenetics/example/tsp/gpx_way_points.gpx";
		try (InputStream in = getClass().getResourceAsStream(resource)) {
			final GPX gpx = GPX.read(GPX.class, in);
			GPX.write(gpx, System.out);
		}
	}

}

Add test for GPX data-structures.

Add test for GPX data-structures.


package org.labkey.dbutils.jooq;

import org.jetbrains.annotations.Nullable;
import org.jooq.DataType;
import org.jooq.Field;
import org.jooq.Record;
import org.jooq.Table;
import org.labkey.api.data.AbstractTableInfo;
import org.labkey.api.data.DbSchema;
import org.labkey.api.data.JdbcType;
import org.labkey.api.data.SQLFragment;
import org.labkey.api.query.ExprColumn;
import org.labkey.api.query.UserSchema;

/**
 * Created by jon on 3/28/17.
 */
public abstract class jOOQTableInfo<RecordType extends Record> extends AbstractTableInfo {
    protected UserSchema userSchema;

    public jOOQTableInfo(String tableName, String dbSchema, UserSchema userSchema) {
        super(DbSchema.get(dbSchema), tableName);
        this.userSchema = userSchema;

        registerColumns();
    }

    protected void registerColumns() {
        for (Field field : getjOOQTable().fields()) {
            this.registerColumn(field);
        }
    }

    protected void registerColumn(Field field) {
        DataType fieldType = field.getDataType();
        JdbcType jdbcType = JdbcType.valueOf(fieldType.getSQLType());
        String name = field.getName();

        this.addColumn(new ExprColumn(this, name, new SQLFragment(ExprColumn.STR_TABLE_ALIAS + "." + name), jdbcType));
    }

    @Override
    protected SQLFragment getFromSQL() {
        SQLFragment sql = new SQLFragment();

        try (jOOQConnection jOOQConnection = new jOOQConnection(userSchema.getSchemaName())) {
            sql.append(jOOQConnection.create().selectFrom(getjOOQTable()).getSQL());
        }

        return sql;
    }

    @Nullable
    @Override
    public UserSchema getUserSchema() {
        return this.userSchema;
    }

    public abstract Table<RecordType> getjOOQTable();
}

Add TableInfo wrapper for jOOQ Tables.

Add TableInfo wrapper for jOOQ Tables.


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

import org.apache.qpid.protonj2.client.Message;

/**
 * Exception thrown from {@link Message} instances when the body section specified
 * violates the configure message format of the message that is being created.
 */
public class ClientMessageFormatViolationException extends ClientException {

    private static final long serialVersionUID = -7731216779946825581L;

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

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

Add new exception type to throw when validating message body sections

The current advnaced message implementation throws illegal argument
exception but the method should be altered to throw ClientException and
throw a message format violation error among other things.


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

/**
* @author Vera Y. Petrashkova
* @version $Revision$
*/

package org.apache.harmony.security.tests.support;

import java.security.KeyStore;

/**
 * Additional class extends KeyStore.LoadStoreParameter
 */
public class MyLoadStoreParams implements
        KeyStore.LoadStoreParameter {

    KeyStore.ProtectionParameter protPar;

    public MyLoadStoreParams(KeyStore.ProtectionParameter p) {
        this.protPar = p;
    }

    public KeyStore.ProtectionParameter getProtectionParameter() {
        return protPar;
    }
}

Remove unnecessary check - testing scenario may need to pass null parameter

svn path=/harmony/; revision=498542


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

package imagej.script.io;

import imagej.io.AbstractIOPlugin;
import imagej.io.IOPlugin;
import imagej.script.ScriptService;

import java.io.IOException;

import org.scijava.plugin.Plugin;

/**
 * {@link IOPlugin} for scripts.
 *
 * @author Curtis Rueden
 * @see ScriptService
 */
@Plugin(type = IOPlugin.class)
public class ScriptIOPlugin extends AbstractIOPlugin<String> {

	// -- IOPlugin methods --

	@Override
	public Class<String> getDataType() {
		return String.class;
	}

	@Override
	public boolean supportsOpen(final String source) {
		final ScriptService scriptService =
			getContext().getService(ScriptService.class);
		return scriptService.canHandleFile(source);
	}

	@Override
	public String open(final String source) throws IOException {
		final ScriptService scriptService =
			getContext().getService(ScriptService.class);
		// TODO: Use the script service to open the file in the script editor.
		return null;
	}

}

Add I/O plugin stub for scripts

Add I/O plugin stub for scripts

It doesn't work yet, because the ScriptService does not yet provide the
API necessary to actually open the script in the script editor.


/*
 * Copyright (c) 2016 Spotify AB
 *
 * 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.
 */

/**
 * Extends the {@link java.util.concurrent.CompletableFuture Java completable future} API.  The main
 * entry point of this package is the {@link com.spotify.futures.CompletableFutures} class, that
 * contains useful static utility methods.
 *
 * <p> This package uses the convention that all method parameters are non-null by default, i.e.
 * unless indicated by a {@link javax.annotation.Nullable @Nullable} annotation.
 *
 * @since 0.1.0
 */
@ParametersAreNonnullByDefault
package com.spotify.futures;

import javax.annotation.ParametersAreNonnullByDefault;

Document the main package of the library


package com.github.onsdigital.babbage.api.endpoint;

import com.github.davidcarboni.restolino.framework.Api;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.GET;
import javax.ws.rs.core.Context;
import java.io.IOException;

/**
 * Created by mrout on 29/08/2017.
 */

@Api
public class Healthcheck {

    @GET
    public void get(@Context HttpServletRequest request, @Context HttpServletResponse response) throws IOException {
        response.setStatus(HttpServletResponse.SC_OK);
    }
}

Add healthcheck endpoint to service

Add healthcheck endpoint to service


import java.util.*;

class Player {

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

        // game loop
        while (true) {
            String enemy1 = in.next(); // name of enemy 1
            int dist1 = in.nextInt(); // distance to enemy 1
            String enemy2 = in.next(); // name of enemy 2
            int dist2 = in.nextInt(); // distance to enemy 2

            // Write an action using System.out.println()

            // Enter the code here

            if (dist1 < dist2) {
                System.out.println(enemy1);
            } else {
                System.out.println(enemy2);
            }
        }
    }
}

Add source code to Onboarding game

Add source code to Onboarding game


package org.apache.pig.impl.logicalLayer.validators;

import org.apache.pig.impl.logicalLayer.LogicalOperator;
import org.apache.pig.impl.logicalLayer.LogicalPlan;
import org.apache.pig.impl.plan.CompilationMessageCollector;
import org.apache.pig.impl.plan.PlanValidationException;
import org.apache.pig.impl.plan.PlanValidator;

public class SchemaAliasValidator extends PlanValidator<LogicalOperator, LogicalPlan> {
    public SchemaAliasValidator() {
    }

    public void validate(LogicalPlan plan,
                         CompilationMessageCollector msgCollector)
                                        throws PlanValidationException {
        // The first msgCollector is used in visitor
        // The second msgCollector is used by the validator
        super.validateSkipCollectException(new SchemaAliasVisitor(plan),
                                           msgCollector) ;

    }
}

PIG-644: Duplicate column names in foreach do not throw parser error

git-svn-id: 8c49d51cc539c84b28b5042abd6e265f31af12f8@826816 13f79535-47bb-0310-9956-ffa450edef68


package leetcode.intersection_of_two_linked_lists;

import common.ListNode;

public class Solution {
    public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
        if(headA == null || headB == null){
        	return null;
        }
        if(headA == headB)
        	return headA;
        ListNode endA = headA, endB = headB;
        while(endA.next != null)
        	endA = endA.next;
        while(endB.next != null)
        	endB = endB.next;
        if(endA != endB)
        	return null;
        ListNode end = endA;
        end.next = headA;
        ListNode tortoise = headB.next, hare = headB.next.next;
        while(tortoise != hare){
        	tortoise = tortoise.next;
        	hare = hare.next.next;
        }
        hare = headB;
        while(hare != tortoise){
        	hare = hare.next;
        	tortoise = tortoise.next;
        }
        end.next = null;
        return tortoise;
    }
}

Add java solution for 160. Intersection of Two Linked Lists

160. Intersection of Two Linked Lists: https://leetcode.com/problems/intersection-of-two-linked-lists/


package ru.stqa.selenium;

import org.openqa.selenium.Alert;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.testng.annotations.Test;

import java.util.List;
import java.util.concurrent.TimeUnit;

public class SearchMovieTest extends TestNgTestBase{

  @Test
    public void testSearchMovie() throws Exception {
    //login
    LoginTest.testLogin(driver);

    //search movie
    driver.manage().timeouts().implicitlyWait(0, TimeUnit.SECONDS);
    WebDriverWait wait = new WebDriverWait(driver, 30);
    List<WebElement> movieBoxesBefore = driver.findElements(By.xpath("//*[@class='movie_box']"));
    driver.findElement(By.xpath("//*[@class='movie_box']")).click();
    driver.findElement(By.xpath("//*[@title='Remove']")).click();
    wait.until(ExpectedConditions.alertIsPresent());
    Alert alert = driver.switchTo().alert();
    alert.accept();

    //check movies counter
    driver.findElement(By.linkText("Home")).click();
    wait.until(ExpectedConditions. //wait for home page to load
            presenceOfElementLocated(By.
                    xpath("//*[@class='searchbox']")));
    List<WebElement> movieBoxesAfter = driver.findElements(By.xpath("//*[@class='movie_box']"));
    if (movieBoxesAfter.size() != movieBoxesBefore.size() - 1)
      throw new Error("Фильм не удален");
  }
}

Revert "1. moviesAfter в AddMovieTest не получает нужного значения. Wait дожидается загрузки searchbox, но фильмы могут загрузиться позже. Нужно ждать загрузки именно нужного элемента."

This reverts commit fa6cf3d93a25e4007901f4e218ceb5132bbfe3e7.


package org.cyclops.colossalchests.block;

import net.minecraft.client.model.ModelChest;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
import org.cyclops.colossalchests.ColossalChests;
import org.cyclops.colossalchests.client.render.tileentity.RenderTileEntityUncolossalChest;
import org.cyclops.colossalchests.tileentity.TileUncolossalChest;
import org.cyclops.cyclopscore.config.extendedconfig.BlockContainerConfig;

/**
 * Config for the {@link ColossalChest}.
 * @author rubensworks
 *
 */
public class UncolossalChestConfig extends BlockContainerConfig {

    /**
     * The unique instance.
     */
    public static UncolossalChestConfig _instance;

    /**
     * Make a new instance.
     */
    public UncolossalChestConfig() {
        super(
                ColossalChests._instance,
        	true,
            "uncolossalChest",
            null,
            UncolossalChest.class
        );
    }

    @Override
    @SideOnly(Side.CLIENT)
    public void onRegistered() {
        super.onRegistered();
        ModelChest model = new ModelChest();
        ColossalChests._instance.getProxy().registerRenderer(TileUncolossalChest.class, new RenderTileEntityUncolossalChest(model));
    }

}

Add missing Uncolossal Chest config

Add missing Uncolossal Chest config


package util.game;

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

import util.gdl.grammar.Gdl;
import util.kif.KifReader;

/**
 * Test game repository that provides rulesheet-only access to games with no
 * associated metadata or other resources, to be used only for unit tests.
 *
 * @author Sam
 */
public final class TestGameRepository extends GameRepository {
    protected Set<String> getUncachedGameKeys() {
        Set<String> theKeys = new HashSet<String>();
        for(File game : new File("games/test").listFiles()) {
            if(!game.getName().endsWith(".kif")) continue;
            theKeys.add(game.getName().replace(".kif", ""));
        }
        return theKeys;
    }

    protected Game getUncachedGame(String theKey) {
    	try {
    		List<Gdl> theRules = KifReader.read(new File("games/test/" + theKey + ".kif").getAbsolutePath());
    		return new Game(theKey, null, null, null, null, theRules);
    	} catch (Exception e) {
    		throw new RuntimeException(e);
    	}
    }
}

Add a game repository specifically for unit tests, that can provide a listing of all of the available test games and load rulesheet-only versions of specific games.

git-svn-id: 4739e81c2fe647bfb539b919360e2c658e6121ea@463 716a755e-b13f-cedc-210d-596dafc6fb9b