package leetcode.swap_nodes_in_pairs;

import java.util.ArrayList;

import common.ListNode;

public class Solution {
	public ListNode swapPairs(ListNode head) {
		if(head == null || head.next == null) return head;
		ListNode ret = head.next;
		ListNode cur = head;
		ListNode prev = null;
		while(cur != null && cur.next != null){
			ListNode nxt = cur.next;
			cur.next = nxt.next;
			nxt.next = cur;
			if(prev != null){
				prev.next = nxt;
			}
			prev = cur;
			cur = cur.next;
		}
		return ret;
	}

	public static void dump(ListNode head){
		ListNode cur = head;
		while(cur != null){
			System.err.print(cur.val + ", ");
			cur = cur.next;
		}
		System.err.println("");
	}

	public static void main(String[] args){
		final int N = 3;
		ArrayList<ListNode> ary = new ArrayList<ListNode>();
		for(int i = 0; i < N; i++){
			ary.add(new ListNode(i));
			if(i > 0) ary.get(i - 1).next = ary.get(i);
		}
		ListNode ret = new Solution().swapPairs(ary.get(0));
		dump(ret);
	}
}

Add java solution for 24. Swap Nodes in Pairs

24. Swap Nodes in Pairs: https://leetcode.com/problems/swap-nodes-in-pairs/


package to.etc.domui.component.delayed;

import to.etc.domui.component.misc.MsgBox;
import to.etc.domui.dom.html.Div;
import to.etc.domui.dom.html.HTag;
import to.etc.domui.util.Msgs;
import to.etc.parallelrunner.IAsyncRunnable;
import to.etc.util.CancelledException;
import to.etc.util.StringTool;

/**
 * @author Frits Jalvingh
 * Created on 14-12-21.
 */
abstract public class AsyncDiv<T extends IAsyncRunnable> extends Div {
	final private T m_runnable;

	private final String m_what;

	public AsyncDiv(T runnable, String what) {
		m_runnable = runnable;
		m_what = what;
	}

	@Override
	final public void createContent() throws Exception {
		String what = m_what;
		if(null != what) {
			add(new HTag(1, what));
		}
		add(new AsyncContainer(m_runnable, (cancelled, errorException) -> {
			//-- If we've got an exception replace the contents with the exception message.
			if(errorException != null && !(errorException instanceof CancelledException)) {
				//errorException.printStackTrace();
				StringBuilder sb = new StringBuilder(8192);
				StringTool.strStacktrace(sb, errorException);
				String s = sb.toString();
				s = s.replace("\n", "
\n");

				MsgBox.error(this, Msgs.BUNDLE.getString(Msgs.ASYNC_ERROR) + "
" + s);
			} else if(cancelled) {
				MsgBox.info(this, Msgs.BUNDLE.getString(Msgs.ASYNC_CONTAINER_CANCELLED));
			} else {
				removeAllChildren();
				createContent(m_runnable);
			}
		}));
	}

	abstract public void createContent(T task) throws Exception;
}

Add test page, fix 1st issues.

[loadreport] Add test page, fix 1st issues.


package com.github.maven_nar;

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

public class ProcessLibraryCommand {

    /**
     * The executable to run
     *
     * @parameter default-value=""
     */
    private String executable;

    /**
     * The library type that this command is valid for
     *
     * @parameter default-value=""
     */
    private String libraryType;

    /**
     * Any additional arguments to pass into the executable
     *
     * @parameter default-value=""
     */
    private List<String> arguments;

    public List<String> getCommandList() {
	List<String> command = new ArrayList<String>();
	command.add(executable);
	command.addAll(arguments);
	return command;
    }

    public String getExecutable() {
        return executable;
    }
    public void setExecutable(String executable) {
        this.executable = executable;
    }
    public List<String> getArguments() {
        return arguments;
    }
    public void setArguments(List<String> arguments) {
        this.arguments = arguments;
    }
    public String getType() {
	// TODO Auto-generated method stub
	return libraryType;
    }

}

package com.github.maven_nar;

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

public class ProcessLibraryCommand {

    /**
     * The executable to run
     *
     * @parameter default-value=""
     */
    private String executable;

    /**
     * The library type that this command is valid for
     *
     * @parameter default-value=""
     */
    private String libraryType;

    /**
     * Any additional arguments to pass into the executable
     *
     * @parameter default-value=""
     */
    private List<String> arguments;

    public List<String> getCommandList() {
	List<String> command = new ArrayList<String>();
	command.add(executable);
	if (arguments != null) {
		command.addAll(arguments);
	}
	return command;
    }

    public String getExecutable() {
        return executable;
    }
    public void setExecutable(String executable) {
        this.executable = executable;
    }
    public List<String> getArguments() {
        return arguments;
    }
    public void setArguments(List<String> arguments) {
        this.arguments = arguments;
    }
    public String getType() {
	// TODO Auto-generated method stub
	return libraryType;
    }

}

Fix NPE for command with no arguments

Fix NPE for command with no arguments

[jes: fixed whitespace and commit message]

Signed-off-by: Johannes Schindelin <53fb8db7833fca1e1746dd8592f61048d350f64c@gmx.de>


/**
 * Enable to use HibernateIdGenerator on identifiers in the package: <code>@GeneratedValue(generator = HibernateIdGenerator.NAME)</code>
 */
@org.hibernate.annotations.GenericGenerator(name = com.coreoz.plume.db.hibernate.HibernateIdGenerator.NAME, strategy = "com.coreoz.plume.db.hibernate.HibernateIdGenerator")
package ${package}.db.entities;

Package info added for code generation

Package info added for code generation


/**
 * Copyright (C) 2014 - present by OpenGamma Inc. and the OpenGamma group of companies
 *
 * Please see distribution for license.
 */
package com.opengamma.bbg.component;

import com.opengamma.bbg.referencedata.statistics.BloombergReferenceDataStatistics;
import com.opengamma.bbg.referencedata.statistics.NullBloombergReferenceDataStatistics;
import com.opengamma.component.ComponentRepository;

/**
 * Component factory for the Null Bloomberg Reference Data Statistics.
 */
public class NoneBloombergReferenceDataStatisticsComponentFactory extends DefaultBloombergReferenceDataStatisticsComponentFactory {

  @Override
  protected BloombergReferenceDataStatistics initReferenceDataStatistics(ComponentRepository repo) {
    return NullBloombergReferenceDataStatistics.INSTANCE;
  }

}

[PLAT-6431] Add a NULL bloomberg ref data statistics component factory


package guitests;

import guitests.guihandles.TaskCardHandle;
import static org.junit.Assert.assertTrue;
import static seedu.task.logic.commands.UpdateCommand.MESSAGE_UPDATE_TASK_SUCCESS;

import org.junit.Test;

import seedu.task.commons.core.Messages;
import seedu.task.commons.exceptions.IllegalValueException;
import seedu.task.logic.commands.UpdateCommand;
import seedu.task.model.tag.Tag;
import seedu.task.model.task.*;
import seedu.task.testutil.TestTask;
import seedu.task.testutil.TestUtil;

public class UndoCommandTest extends TaskManagerGuiTest {
    @Test
    public void update() throws IllegalValueException {
        TestTask[] currentList = td.getTypicalTasks();
        int targetIndex = 1;

        // undo add command
        assertUndoSuccess(td.hoon.getAddCommand(), currentList);

        // undo delete command
        assertUndoSuccess("delete " + targetIndex, currentList);

        // undo update command
        assertUndoSuccess("update " + targetIndex + td.ida.getArgs(), currentList);
    }

    private void assertUndoSuccess(String command, TestTask... originalList) {
        commandBox.runCommand(command);
        commandBox.runCommand("undo");
        assertTrue(taskListPanel.isListMatching(originalList));
    }
}

Add basic test for undo command

Add basic test for undo command


package com.einevault.users;

import static spark.Spark.get;

/**
 * Created by einevea on 16/08/15.
 */
public class UsersApp {

    public static void main(String[] args) {
        get("/hello", (req, res) -> "Hello World");
    }
}

Create a basic user main

Create a basic user main


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

package it;

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

import de.sormuras.bach.Resources;
import java.net.URI;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.condition.DisabledIfSystemProperty;

class ResourcesTests {

  @Test
  @DisabledIfSystemProperty(named = "offline", matches = "true")
  void headRequestOfHttpsGoogleComUsingSystemResourcesIsRespondedWithStatus200() throws Exception {
    assertEquals(200, Resources.ofSystem().head(URI.create("https://google.com")).statusCode());
  }
}

Add test case for Resources

Add test case for Resources


/**
 * @license
 * Copyright 2018 The FOAM Authors. All Rights Reserved.
 * http://www.apache.org/licenses/LICENSE-2.0
 */

package foam.nanos.servlet;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Typically used to alias short paths like "/" or "/merchant" to specific services.
 */
public class RedirectServlet
    extends HttpServlet
{
  @Override
  protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    String path = getServletConfig().getInitParameter("path");
    RequestDispatcher view = req.getRequestDispatcher(path);
    view.forward(req, resp);
  }
}

Add redirect sevlet, a non tomcat specific version of the Tomcat SubdomainRouter


package org.opennms.web.svclayer;

public class ProgressMonitor {

	private int m_phaseCount = 1;
	private int m_phase = 0;
	private String m_phaseLabel = "Loading";
	private Object m_result = null;
	private Exception m_exception = null;

	public int getPhaseCount() {
		return m_phaseCount;
	}

	public void setPhaseCount(int phaseCount) {
		m_phaseCount = phaseCount;
	}

	public String getPhaseLabel() {
		return m_phaseLabel;
	}

	public int getPhase() {
		return m_phase;
	}

	public void beginNextPhase(String phaseLabel) {
		m_phaseLabel = phaseLabel;
		m_phase++;
	}

	public void finished(Object result) {
		m_result = result;
		m_phaseLabel = "Done";
		m_phase = m_phaseCount;
	}

	public boolean isFinished() {
		return m_result != null;
	}

	public Object getResult() {
		return m_result;
	}

	public boolean isError() {
		return m_exception != null;
	}

	public Exception getException() {
		return m_exception;
	}

	public void errorOccurred(Exception e) {
		m_exception = e;
	}

}

Add progress bar to loading of Surveillence page


/*
 * The Alluxio Open Foundation licenses this work under the Apache License, version 2.0
 * (the "License"). You may not use this work except in compliance with the License, which is
 * available at www.apache.org/licenses/LICENSE-2.0
 *
 * This software is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
 * either express or implied, as more fully set forth in the License.
 *
 * See the NOTICE file distributed with this work for information regarding copyright ownership.
 */

package alluxio.shell.command;

import alluxio.AlluxioURI;
import alluxio.client.FileSystemTestUtils;
import alluxio.client.WriteType;
import alluxio.shell.AbstractAlluxioShellTest;
import alluxio.underfs.UnderFileSystem;
import org.junit.Assert;
import org.junit.Test;

public class CheckConsistencyCommandTest extends AbstractAlluxioShellTest {
  /**
   * Tests the check consistency shell command correctly identifies a consistent subtree.
   */
  @Test
  public void consistent() throws Exception {
    FileSystemTestUtils
        .createByteFile(mFileSystem, "/testRoot/testFileA", WriteType.CACHE_THROUGH, 10);
    FileSystemTestUtils.createByteFile(mFileSystem, "/testRoot/testDir/testFileB",
        WriteType.CACHE_THROUGH, 20);
    mFsShell.run("checkConsistency", "/testRoot");
    String expected = "/testRoot is consistent with the under storage system.\n";
    Assert.assertEquals(expected, mOutput.toString());
  }

  /**
   * Tests the check consistency shell command correctly identifies inconsistent files in a subtree.
   */
  @Test
  public void inconsistent() throws Exception {
    FileSystemTestUtils
        .createByteFile(mFileSystem, "/testRoot/testFileA", WriteType.CACHE_THROUGH, 10);
    FileSystemTestUtils.createByteFile(mFileSystem, "/testRoot/testDir/testFileB",
        WriteType.CACHE_THROUGH, 20);
    String ufsPath = mFileSystem.getStatus(new AlluxioURI("/testRoot/testDir")).getUfsPath();
    UnderFileSystem ufs = UnderFileSystem.get(ufsPath);
    ufs.delete(ufsPath, true);
    mFsShell.run("checkConsistency", "/testRoot");
    StringBuilder expected = new StringBuilder();
    expected.append("The following files are inconsistent:\n");
    expected.append("/testRoot/testDir\n");
    expected.append("/testRoot/testDir/testFileB\n");
    Assert.assertEquals(expected.toString(), mOutput.toString());
  }
}

Add a unit test for the shell command.

Add a unit test for the shell command.


package org.app.material.widget;

import android.support.annotation.StringRes;
import android.support.v4.app.Fragment;

public class FragmentSet {

    private Fragment fragment;
    private CharSequence title;
    private @StringRes int resId;

    public FragmentSet(Fragment fragment, CharSequence title) {
        this.fragment = fragment;
        this.title = title;
    }

    public FragmentSet(Fragment fragment, @StringRes int resId) {
        this.fragment = fragment;
        this.resId = resId;
    }

    public Fragment getFragment() {
        return fragment;
    }

    public CharSequence getTitle() {
        return title;
    }

    public int getResId() {
        return resId;
    }
}

Add set to fragment pager adapter

Add set to fragment pager adapter


package nl.hsac.fitnesse.junit;

import org.junit.runner.Description;
import org.junit.runner.Result;
import org.junit.runner.notification.Failure;
import org.junit.runner.notification.RunListener;

import java.io.PrintStream;

/**
 * JUnit RunListener so that TeamCity is updated with progress info while tests run.
 */
public class JUnitTeamcityReporter extends RunListener {
    private final PrintStream out;
    private String currentTestClassName = null;

    public JUnitTeamcityReporter() {
        this(System.out);
    }

    public JUnitTeamcityReporter(final PrintStream out) {
        this.out = out;
        this.currentTestClassName = null;
    }

    @Override
    public void testStarted(Description description) {
        final String testClassName = getTestClassName(description);
        final String testName = getTestName(description);

        if (currentTestClassName == null || !currentTestClassName.equals(testClassName)) {
            testRunFinished(null);
            this.out.println(String.format("##teamcity[testSuiteStarted name='%s']", testClassName));
            currentTestClassName = testClassName;
        }

        out.println(String.format("##teamcity[testStarted name='%s' captureStandardOutput='true']", testName));
    }

    @Override
    public void testFinished(Description description) {
        final String testName = getTestName(description);

        out.println(String.format("##teamcity[testFinished name='%s']", testName));
    }

    @Override
    public void testFailure(Failure failure) {
        if (failure.getTrace() != null && !failure.getTrace().isEmpty())
            out.print(failure.getTrace());
        out.println(String.format("##teamcity[testFailed name='%s' message='%s' details='%s']",
                getTestName(failure.getDescription()),
                "failed",
                ""));
        testFinished(failure.getDescription());
    }

    @Override
    public void testIgnored(Description description) {
        out.println(String.format("##teamcity[testIgnored name='%s' message='%s']",
                getTestName(description),
                ""));
    }

    @Override
    public void testRunFinished(Result result) {
        if (currentTestClassName != null) {
            out.println(String.format("##teamcity[testSuiteFinished name='%s']", currentTestClassName));
        }
    }

    protected String getTestClassName(final Description description) {
        return description.getTestClass().getName();
    }

    protected String getTestName(final Description description) {
        return description.getMethodName();
    }
}

Add RunListener to be used in combination with TeamCity so that start and end time of each page is recorded in the build log in a format that TeamCity can interpret. (Can be used as listener instead of JUnitXMLPerPageListener.)


/*
 * 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.logging.log4j.core.config.plugins;

/**
 * Identifies a default string value for a given plugin attribute or value. This value should be used as a fallback
 * where either the given value is invalid, or when there is no given value.
 */
public @interface PluginDefault {
    /**
     * The default value to use.
     */
    String value();
}

Add annotation for default plugin values.

  - Use this to specify the string value you'd want as the default fallback value for a @PluginAttribute, @PluginValue, or @SensitivePluginValue.
  - Part of LOG4J2-652.

git-svn-id: de5ce936019686f47409c93bcc5e202a9739563b@1597360 13f79535-47bb-0310-9956-ffa450edef68


package br.inpe.cap.evolution.processor;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Collection;
import java.util.stream.Stream;

import org.apache.commons.io.FileUtils;
import org.repodriller.persistence.csv.CSVFile;

public class RemoveUnchangedArtifactsStandAlonePostProcessor {

	public static void main(String[] args) {

		System.out.println("Starting...");

		final File pathToLook = new File("C:\\Users\\LuizWagner\\Desktop\\evolutions_joined\\unchanged");
		final String outputPath = pathToLook + File.separator + "output";
		new File(outputPath).mkdirs();
		Collection<File> arquivos = FileUtils.listFiles(pathToLook, null, false);

		arquivos.parallelStream().forEach((csvInput)-> {

			final RemoveUnchangedArtifactsPostProcessor postProcessor = new RemoveUnchangedArtifactsPostProcessor(false);
			final String name = csvInput.getName();
			System.out.println("Processing "+name);
			final CSVFile csvOutput = new CSVFile(outputPath + File.separator + name);

			try {
				final Stream<String> listCsvLines = Files.lines(Paths.get(csvInput.toURI()));
				postProcessor.processCsvLines(csvOutput, listCsvLines);
			} catch (RuntimeException | IOException e) {
				e.printStackTrace();
			}

			System.gc();
			System.out.println("Done "+name);

		});

		System.out.println("Finish!");

	}

}

Change way of processing lines from List<String> to Stream<String> in order to process the 15 billion lines csv file!


package com.nucleus.vecmath;

/**
 * 3 Component vector utilities
 *
 * @author Richard Sahlin
 *
 */
public class Vector3D extends VecMath {

    /**
     * Returns the cross product vector from vector1 and vector2
     * cx = ay * bz − az * by
     * cy = az * bx − ax * bz
     * cz = ax * by − ay * bx
     *
     * @param vector1
     * @param vector2
     * @return New 3 component vector that is the cross product of vector1 and vector2
     */
    public final static float[] cross3(float[] vector1, float[] vector2) {
        float[] cross = new float[3];
        cross[0] = vector1[Y] * vector2[Z] - vector1[Z] * vector2[Y];
        cross[1] = vector1[Z] * vector2[X] - vector1[X] * vector2[Z];
        cross[2] = vector1[X] * vector2[Y] - vector1[Y] * vector2[X];
        return cross;
    }

    /**
     * Sets a 3 component vector at the specified index
     *
     * @param src
     * @param srcIndex
     * @param dest
     * @param destIndex
     */
    public final static void set(float[] src, int srcIndex, float[] dest, int destIndex) {
        dest[destIndex++] = src[srcIndex++];
        dest[destIndex++] = src[srcIndex++];
        dest[destIndex++] = src[srcIndex++];
    }

    public final static float[] subtract(float[] v1, int v1Index, float[] v2, int v2Index) {
        float[] result = new float[3];
        result[0] = v2[v1Index++] - v1[v2Index++];
        result[1] = v2[v1Index++] - v1[v2Index++];
        result[2] = v2[v1Index] - v1[v2Index];
        return result;
    }

    /**
     * Returns the cross product vector from vector1 and vector2
     * cx = ay * bz − az * by
     * cy = az * bx − ax * bz
     * cz = ax * by − ay * bx
     *
     * @param data Array containing vector1 and vector2 and the destination
     * @param v1 index into array where vertex 1 is
     * @param v2 index into array where vertex 2 is
     * @param dest index to result
     */
    public final static void cross3(float[] data, int v1, int v2, int dest) {
        data[dest + X] = data[v1 + Y] * data[v2 + Z] - data[v1 + Z] * data[v2 + Y];
        data[dest + Y] = data[v1 + Z] * data[v2 + X] - data[v1 + X] * data[v2 + Z];
        data[dest + Z] = data[v1 + X] * data[v2 + Y] - data[v1 + Y] * data[v2 + X];
    }

}

Add class for 3 component vector functionality


/*
8.6.2 The Random Class
page 309
*/

package epfc.cours3449;

import java.util.Random;

public class TestRandom {
    public static void main(String[] args) {
        Random r1 = new Random(3);
        for(int i=0; i<10; i++) {
            System.out.print(r1.nextInt(1000) + " ");
        }
        System.out.println("");
        Random r2 = new Random(3);
        for(int i=0; i<10; i++) {
            System.out.print(r2.nextInt(1000) + " ");
        }
        System.out.println("");
    }
}

Test Random Class, comme dans le livre pg 310


/*
 * Copyright 2018 EPAM Systems
 *
 * 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.epam.ta.reportportal.ws.model.launch;

import com.epam.ta.reportportal.ws.model.ErrorRS;
import com.fasterxml.jackson.annotation.JsonProperty;

import java.util.List;

/**
 * @author Ihar Kahadouski
 */
public class DeleteLaunchesRS {

	@JsonProperty("successfullyDeleted")
	private List<Long> deleted;

	@JsonProperty("notFound")
	private List<Long> notFound;

	@JsonProperty("noPermissions")
	private List<Long> noPermissions;

	@JsonProperty("errors")
	private List<ErrorRS> errors;

	public DeleteLaunchesRS() {
	}

	public DeleteLaunchesRS(List<Long> deleted, List<Long> notFound, List<Long> noPermissions, List<ErrorRS> errors) {
		this.deleted = deleted;
		this.notFound = notFound;
		this.noPermissions = noPermissions;
		this.errors = errors;
	}

	public List<Long> getDeleted() {
		return deleted;
	}

	public void setDeleted(List<Long> deleted) {
		this.deleted = deleted;
	}

	public List<Long> getNotFound() {
		return notFound;
	}

	public void setNotFound(List<Long> notFound) {
		this.notFound = notFound;
	}

	public List<Long> getNoPermissions() {
		return noPermissions;
	}

	public void setNoPermissions(List<Long> noPermissions) {
		this.noPermissions = noPermissions;
	}

	public List<ErrorRS> getErrors() {
		return errors;
	}

	public void setErrors(List<ErrorRS> errors) {
		this.errors = errors;
	}

	@Override
	public String toString() {
		final StringBuilder sb = new StringBuilder("DeleteLaunchesRS{");
		sb.append("deleted=").append(deleted);
		sb.append(", notFound=").append(notFound);
		sb.append(", noPermissions=").append(noPermissions);
		sb.append(", errors=").append(errors);
		sb.append('}');
		return sb.toString();
	}
}

Add delete launches response entity

Add delete launches response entity


package leetcode.roman_to_integer;

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

public class Solution {
	public int romanToInt(String s) {
		Map<String, Integer> map = new HashMap<String, Integer>();
    	String[] romans = new String[]{
    		"", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX",
    		"X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC",
    		"C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM",
    		"M", "MM", "MMM",
    	};
    	for(int i = 0; i <= 9; i++){
    		map.put(romans[i], i);
    	}
    	for(int i = 10; i <= 90; i += 10){
    		map.put(romans[i / 10 + 9], i);
    	}
    	for(int i = 100; i <= 900; i += 100){
    		map.put(romans[i / 100 + 18], i);
    	}
    	for(int i = 1000; i <= 3000; i += 1000){
    		map.put(romans[i / 1000 + 27], i);
    	}
    	int offset = 0;
    	int ans = 0;
    	while(offset < s.length()){
    		for(int digits = Math.min(4, s.length() - offset); digits >= 1; digits--){
    			Integer val = map.get(s.substring(offset, offset + digits));
    			if(val != null){
    				ans += val;
    				offset += digits;
    				break;
    			}
    		}
    	}
    	return ans;
	}

	public static void main(String[] args){
		for(int i = 1; i <= 3999; i++){
			if(new Solution().romanToInt(new leetcode.integer_to_roman.Solution().intToRoman(i)) != i){
				System.err.println("failed at " + i);
			}else{
				System.err.println(new leetcode.integer_to_roman.Solution().intToRoman(i) + " " + i);
			}
		}
	}
}

Add java solution for 13. Roman to Integer

13. Roman to Integer: https://leetcode.com/problems/roman-to-integer/


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

package gerrit;

import com.google.gerrit.server.rules.StoredValues;
import com.googlecode.prolog_cafe.exceptions.PrologException;
import com.googlecode.prolog_cafe.lang.IntegerTerm;
import com.googlecode.prolog_cafe.lang.Operation;
import com.googlecode.prolog_cafe.lang.Predicate;
import com.googlecode.prolog_cafe.lang.Prolog;
import com.googlecode.prolog_cafe.lang.Term;
import org.eclipse.jgit.revwalk.RevCommit;

/**
 * Prolog fact for the number of parents of a given commit
 *
 * <pre>
 *   'commit_parent_count'(-Count)
 * </pre>
 */
public class PRED_commit_parent_count_1 extends Predicate.P1 {
  public PRED_commit_parent_count_1(Term a1, Operation n) {
    arg1 = a1;
    cont = n;
  }

  @Override
  public Operation exec(Prolog engine) throws PrologException {
    engine.setB0();
    Term a1 = arg1.dereference();

    RevCommit commit = StoredValues.COMMIT.get(engine);

    if (!a1.unify(new IntegerTerm(commit.getParentCount()), engine.trail)) {
      return engine.fail();
    }
    return cont;
  }
}

Add prolog predicate to determine number of parents

This change introduces a new prolog predicate for the
number of parents of a given patch set. This can be used to determine
from within the "rules.pl" file whether a change
is a merge commit or not.

This can be useful in order to evaluate a different set of
submit rules for merge commits.

Example usage:
submit_rule(submit(Parents)) :-
    Parents = label('Is-Merge', need(_)).
submit_rule(submit(Parents)) :-
    gerrit:commit_parent_count(A),
    A > 1,
    Parents = label('Is-Merge', ok(user(ID))).

Change-Id: I306163510e201606e936d95caea5ffa0bb957236


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

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

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

/**
 * @author Pedro Vicente Gómez Sánchez.
 */
public class IsRotationUsingIsSubstringTest {

  private IsRotationUsingIsSubstring isRotation;

  @Before public void setUp() {
    isRotation = new IsRotationUsingIsSubstring();
  }

  @Test(expected = IllegalArgumentException.class)
  public void shouldNotAcceptNullInstancesAsFirstParameter() {
    isRotation.check(null, "");
  }

  @Test(expected = IllegalArgumentException.class)
  public void shouldNotAcceptNullInstancesAsSecondParameter() {
    isRotation.check("", null);
  }

  @Test public void shouldReturnFalseIfS2IsNotRotationOfS1() {
    String s1 = "waterbottle";
    String s2 = "pedro";

    boolean result = isRotation.check(s1, s2);

    assertFalse(result);
  }

  @Test public void shouldReturnTrueIfS2IsNotRotationOfS1() {
    String s1 = "waterbottle";
    String s2 = "erbottlewat";

    boolean result = isRotation.check(s1, s2);

    assertTrue(result);
  }
}

Add some tests to problem 56

Add some tests to problem 56


package org.codehaus.xfire.aegis.type.basic;

import org.codehaus.xfire.aegis.AbstractXFireAegisTest;
import org.codehaus.xfire.client.XFireProxyFactory;
import org.codehaus.xfire.service.Service;
import org.codehaus.xfire.service.invoker.BeanInvoker;

public class InterfaceImplTest
    extends AbstractXFireAegisTest
{
    public void testInterface() throws Exception
    {
        Service service = getServiceFactory().create(IMyService.class);
        service.setInvoker(new BeanInvoker(new MyService()));
        getServiceRegistry().register(service);
        service.setProperty(IMyObject.class.getName() + ".implementation", MyObject.class.getName());

        IMyService client = (IMyService)
            new XFireProxyFactory(getXFire()).create(service, "xfire.local://IMyService");
        MyObject o = new MyObject();
        o.setName("foo");
        client.receive(o);
    }

    public static interface IMyService
    {
        public void receive(IMyObject o);
    }

    public static class MyService implements IMyService
    {
        public void receive(IMyObject o)
        {
            assertTrue(o instanceof MyObject);
        }
    }

    public interface IMyObject
    {
        public String getName();
    }

    public static class MyObject implements IMyObject
    {
        private String name;

        public String getName()
        {
            return name;
        }

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

}

Add unit test for interface impl feature

git-svn-id: 9326b53cbc4a8f4c3d02979b62b178127d5150fe@1445 c7d0bf07-ec0d-0410-b2cc-d48fa9be22ba


/*
 * Copyright (c) Facebook, Inc. and its affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */

package com.facebook.imagepipeline.core;

/** Setter and getter for option about using native code. */
public class NativeCodeSetup {

  private static boolean sUseNativeCode = true;

  private NativeCodeSetup() {}

  /**
   * Setter for useNativeCode option
   *
   * @param useNativeCode true, if you want to use native code
   */
  public static void setUseNativeCode(boolean useNativeCode) {
    sUseNativeCode = useNativeCode;
  }

  /**
   * Getter for useNativeCode option
   *
   * @return true, if you going to use Native code
   */
  public static boolean getUseNativeCode() {
    return sUseNativeCode;
  }
}

Add option to use native code in Fresco

Add option to use native code in Fresco

Summary: Add class with setter and getter for option to use native code in Fresco

Reviewed By: oprisnik

Differential Revision: D17602042

fbshipit-source-id: e098360cd79afa934a6691ea385b22877eb57eb0


/*
 * Copyright © 2014 <code@io7m.com> http://io7m.com
 *
 * Permission to use, copy, modify, and/or distribute this software for any
 * purpose with or without fee is hereby granted, provided that the above
 * copyright notice and this permission notice appear in all copies.
 *
 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
 * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR
 * IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 */

/**
 * Unit tests.
 */

@com.io7m.jnull.NonNullByDefault
package com.io7m.jfunctional.tests;

Add missing package info file

Add missing package info file


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

public class Main {
    public static void main(String args[]) throws IOException {
        InputStreamReader ir = new InputStreamReader(System.in);
        BufferedReader in = new BufferedReader(ir);

        int a, b, x;

        a = Integer.parseInt(in.readLine());
        b = Integer.parseInt(in.readLine());

        x = a + b;

        System.out.printf("SOMA = %d\n", x);
    }
}

Solve Simple Sum in java

Solve Simple Sum in java


package absyn;

import env.Env;
import parse.Loc;
import types.Type;

public abstract class Var extends AST {

   // Type of the expression, calculated by the semantic analyser
   public Type type;

   public Var(Loc loc) {
      super(loc);
   }

   // Obtain the type of the expression as a string prefixed by the given text.
   protected String annotateType(String text) {
      final String theType = type == null ? "" : "\n<" + type + ">";
      return text + theType;
   }

   // Do semantic analysis of the expression
   public Type semantic(Env env) {
      type = semantic_(env);
      return type;
   }

   // Type check the expression. Should be defined in the concrete subclasses.
   protected abstract Type semantic_(Env env);
}

Add abstract class for variables

Add abstract class for variables


/*
 * Copyright 2005-2014 Red Hat, Inc.
 *
 * Red Hat 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 io.fabric8.maven;

import io.fabric8.kubernetes.client.KubernetesClient;
import io.fabric8.openshift.client.OpenShiftClient;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.apache.maven.plugins.annotations.Mojo;
import org.apache.maven.plugins.annotations.Parameter;
import org.apache.maven.plugins.annotations.ResolutionScope;

/**
 * Cleans up namespace resources.
 * The default behavior is to clean app specific resources, replication controllers, pods, services, routes etc.
 * The command also supports deep cleaning. When enabled deep cleaning will delete everything including secrets, service accounts etc.
 */
@Mojo(name = "clean", requiresDependencyResolution = ResolutionScope.RUNTIME)
public class CleanMojo extends ApplyMojo {

    @Parameter(property = "fabric8.deep.clean", defaultValue = "false")
    private Boolean deep;

    @Override
    public void execute() throws MojoExecutionException, MojoFailureException {
        KubernetesClient client = getKubernetes().inNamespace(getNamespace());

        client.services().delete();
        client.replicationControllers().delete();
        client.pods().delete();

        client.endpoints().delete();
        client.events().delete();

        if (deep) {
            client.secrets().delete();
            client.serviceAccounts().delete();
            client.securityContextConstraints().delete();
        }

        if (client.isAdaptable(OpenShiftClient.class)) {
            OpenShiftClient openShiftClient = client.adapt(OpenShiftClient.class);

            openShiftClient.routes().delete();
            openShiftClient.builds().delete();
            openShiftClient.imageStreams().delete();
            openShiftClient.buildConfigs().delete();
            openShiftClient.deploymentConfigs().delete();
            openShiftClient.templates().delete();

            if (deep) {
                openShiftClient.users().delete();
                openShiftClient.groups().delete();
                openShiftClient.policies().delete();
                openShiftClient.policyBindings().delete();
            }
        }
    }
}

[OSFUSE-34] Introduce clean mojo for cleaning up namespaces.


import org.junit.Test;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.WebDriverWait;

import java.util.List;

import static org.junit.Assert.assertTrue;

/**
 * Created by mikas on 12.11.2015.
 */
public class LogInTest {
    private String baseUrl = "http://localhost:3000/";

    @Test
    public void checkTitle(){
        FirefoxDriver driver = new FirefoxDriver();
        driver.get(baseUrl);

        assertTrue(driver.getTitle().equals("Projekt Grupowy 2015 - aplikacja demo"));

        driver.quit();
    }

    @Test
    public void checkIfThereAreFields(){
        FirefoxDriver driver = new FirefoxDriver();
        driver.get(baseUrl);

        int numberOfInputs = 2;

        List<WebElement> inputs = driver.findElementsByCssSelector("input");
        WebElement button = driver.findElementByCssSelector("button");

        assertTrue(inputs.size() == numberOfInputs && button != null);
        driver.quit();
    }

    @Test
    public void testLoginAction(){
        FirefoxDriver driver = new FirefoxDriver();
        driver.get(baseUrl);

        List<WebElement> inputs = driver.findElementsByCssSelector("input");

        WebElement roomInput = inputs.get(0);
        roomInput.sendKeys("13");
        WebElement loginInput = inputs.get(1);
        loginInput.sendKeys("test");

        driver.findElementByCssSelector("button").click();

        String url = driver.getCurrentUrl();

        assertTrue(url != baseUrl);
        driver.quit();
    }
}

Add UI tests for Login page.

Add UI tests for Login page.


package apostov;

import static apostov.Suit.CLUBS;
import static apostov.Suit.DIAMONDS;
import static apostov.Suit.HEARTS;
import static apostov.Suit.SPADES;
import static apostov.Value.FIVE;
import static apostov.Value.FOUR;
import static apostov.Value.KING;
import static apostov.Value.QUEEN;
import static apostov.Value.SEVEN;
import static apostov.Value.SIX;
import static com.google.common.collect.ImmutableSet.copyOf;
import static com.google.common.collect.Iterables.concat;
import static org.junit.Assert.*;
import static strength.PokerHandKind.PAIR;

import org.junit.Test;

import com.google.common.collect.ImmutableCollection;
import com.google.common.collect.ImmutableSet;

import strength.PairRanking;
import strength.PokerHandRanking;

public class ShowdownEvaluatorTest {

	@Test
	public void selectBestCombinationWithTwoKings() {
		final Card seven = new Card(SEVEN, SPADES);
		final ImmutableCollection<Card> holeCards = ImmutableSet.of(
				seven,
				new Card(KING, CLUBS));

		final Card queen = new Card(QUEEN, CLUBS);
		final Card six = new Card(SIX, DIAMONDS);
		final ImmutableCollection<Card> board = ImmutableSet.of(
				new Card(FIVE, CLUBS),
				new Card(KING, DIAMONDS),
				new Card(FOUR, HEARTS),
				queen,
				six);

		final ShowdownEvaluator evaluator = new ShowdownEvaluator();
		final PokerHandRanking handStrength = evaluator.selectBestCombination(copyOf(concat(holeCards, board)));
		assertSame(PAIR, handStrength.handKind);
		final PairRanking pairRanking = (PairRanking) handStrength;
		assertSame(KING, pairRanking.pairValue);
		assertEquals(
				ImmutableSet.of(CLUBS, DIAMONDS),
				ImmutableSet.of(pairRanking.firstSuit, pairRanking.secondSuit));
		assertEquals(queen, pairRanking.firstKicker);
		assertEquals(seven, pairRanking.secondKicker);
		assertEquals(six, pairRanking.thirdKicker);
	}
}

Add a JUnit test for the selectBestCombination() method


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

package org.cyanogenmod.hardware;

import org.cyanogenmod.hardware.util.FileUtils;

import java.io.File;

public class VibratorHW {

    private static String LEVEL_PATH = "/sys/class/timed_output/vibrator/intensity";

    public static boolean isSupported() {
        File f = new File(LEVEL_PATH);
        return f.exists();
    }

    public static int getMaxIntensity()  {
        return 10000;
    }

    public static int getMinIntensity()  {
        return 0;
    }

    public static int getWarningThreshold()  {
        return 9000;
    }

    public static int getCurIntensity()  {
        File f = new File(LEVEL_PATH);
        String actualIntensity = FileUtils.readOneLine(LEVEL_PATH).replace("intensity: ", "");

        return f.exists() ? Integer.parseInt(actualIntensity) : 0;
    }

    public static int getDefaultIntensity()  {
        return 7500;
    }

    public static boolean setIntensity(int intensity)  {
        File f = new File(LEVEL_PATH);

        return f.exists() && FileUtils.writeLine(LEVEL_PATH, String.valueOf(intensity));
    }
}

zero: Allow for vibration intensity to be configured

Change-Id: I46d63e101a69fcd07815853ed685ae93271ed102
Signed-off-by: Brandon McAnsh <b221b0128acc8543b2071d143ea6dbc7b1554a73@gmail.com>


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

package com.hazelcast.jet;

import com.hazelcast.jet.core.JetTestSupport;
import com.hazelcast.jet.pipeline.Pipeline;
import com.hazelcast.jet.pipeline.Sinks;
import com.hazelcast.jet.pipeline.test.TestSources;
import com.hazelcast.jet.test.SerialTest;
import java.util.List;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.experimental.categories.Category;

import static org.junit.Assert.assertEquals;

@Category(SerialTest.class)
public class JetBootstrappedStandaloneTest extends JetTestSupport {

    private static JetInstance bootstrappedInstance;

    @BeforeClass
    public static void initializeBootstrappedInstance() {
        bootstrappedInstance = Jet.bootstrappedInstance();
    }

    @AfterClass
    public static void shutdownBootstrappedInstance() {
        if (bootstrappedInstance != null) {
            bootstrappedInstance.shutdown();
        }
    }

    @Test
    public void bootstrappedInstanceIsStartedAsStandalone() {
        // start different cluster
        createJetMember();

        int size = bootstrappedInstance.getHazelcastInstance().getCluster().getMembers().size();
        assertEquals(1, size);
    }

    @Test
    public void bootstrappedInstanceCanExecuteJob() {
        Pipeline p = Pipeline.create();
        p.readFrom(TestSources.items(0, 1, 2, 3, 4))
                .writeTo(Sinks.list("sinkList"));

        bootstrappedInstance.newJob(p).join();

        List<Integer> sinkList = bootstrappedInstance.getList("sinkList");
        assertEquals(5, sinkList.size());
    }

    @Test
    public void moreBootstrappedInstanceCallReturnsTheSameInstance() {
        JetInstance bootstrappedInstance2 = Jet.bootstrappedInstance();
        assertEquals(bootstrappedInstance, bootstrappedInstance2);
    }
}

Add smoke test for standalone bootstrappedInstance


/*
 * 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.facebook.presto.ml;

import com.facebook.presto.metadata.MetadataManager;
import com.facebook.presto.metadata.Signature;
import com.facebook.presto.operator.Page;
import com.facebook.presto.operator.RowPageBuilder;
import com.facebook.presto.operator.aggregation.Accumulator;
import com.facebook.presto.operator.aggregation.AggregationFunction;
import com.facebook.presto.spi.block.Block;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.google.common.base.Optional;
import com.google.common.base.Splitter;
import com.google.common.collect.ImmutableList;
import org.testng.annotations.Test;

import java.util.List;

import static com.facebook.presto.spi.type.BigintType.BIGINT;
import static com.facebook.presto.spi.type.VarcharType.VARCHAR;
import static org.testng.Assert.assertEquals;

public class TestEvaluateClassifierPredictions
{
    @Test
    public void testEvaluateClassifierPredictions()
            throws Exception
    {
        MetadataManager metadata = new MetadataManager();
        metadata.addFunctions(new MLFunctionFactory().listFunctions());
        AggregationFunction aggregation = metadata.getExactFunction(new Signature("evaluate_classifier_predictions", VARCHAR, BIGINT, BIGINT)).getAggregationFunction();
        Accumulator accumulator = aggregation.createAggregation(Optional.<Integer>absent(), Optional.<Integer>absent(), 1.0, 0, 1);
        accumulator.addInput(getPage());
        Block block = accumulator.evaluateFinal();

        String output = block.getSlice(0).toStringUtf8();
        List<String> parts = ImmutableList.copyOf(Splitter.on('\n').split(output));
        assertEquals(parts.size(), 3);
        assertEquals(parts.get(0), "Accuracy: 1/2 (50.00%)");
        assertEquals(parts.get(1), "Precision: 1/1 (100.00%)");
        assertEquals(parts.get(2), "Recall: 1/2 (50.00%)");
    }

    private static Page getPage()
            throws JsonProcessingException
    {
        return RowPageBuilder.rowPageBuilder(BIGINT, BIGINT)
                .row(1, 1)
                .row(1, 0)
                .build();
    }
}

Add unit test for evaluate_classifier_predictions


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

import org.hamcrest.MatcherAssert;
import org.hamcrest.Matchers;
import org.junit.Test;

/**
 * Test case for {@link True}.
 *
 * @author Vseslav Sekorin (vssekorin@gmail.com)
 * @version $Id$
 * @since 0.5
 * @checkstyle JavadocMethodCheck (500 lines)
 */
public final class TrueTest {

    @Test
    public void asValue() throws Exception {
        MatcherAssert.assertThat(
            new True().asValue(),
            Matchers.equalTo(true)
        );
    }
}

Add test case for True

Add test case for True


/**
 * This source file is subject to the license that is bundled with this package in the file LICENSE.
 */
package com.codeup.console;

import com.codeup.validation.Validator;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;

import java.io.ByteArrayInputStream;
import java.io.PrintStream;
import java.util.Scanner;

import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.*;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;

@RunWith(MockitoJUnitRunner.class)
public class ConsoleTest {
    @Test
    public void it_accepts_a_valid_text() {
        when(validator.isValid(text)).thenReturn(true);
        console = new Console(getInput(text), output);

        assertThat(console.promptForText(message, validator), is(text));
    }

    @Test
    public void it_prompts_a_second_time_if_invalid_text_is_given() {
        when(validator.isValid(invalidText)).thenReturn(false);
        when(validator.isValid(text)).thenReturn(true);
        console = new Console(
            getInput(String.format("%s\n%s", invalidText, text)),
            output
        );

        assertThat(console.promptForText(message, validator), is(text));
        verify(validator).errorMessage();
    }

    private Scanner getInput(String text) {
        return new Scanner(new ByteArrayInputStream(text.getBytes()))
            .useDelimiter("\n")
        ;
    }

    private Console console;
    private String message = "Message";
    private String invalidText = "invalid";
    private String text = "text";

    @Mock
    private PrintStream output;

    @Mock
    private Validator validator;
}

Create first tests for Console class.

Create first tests for Console class.


package io.github.aquerr.eaglefactions;

public abstract class PluginPermissions
{
    public static final String AllPermissions = "eaglefactions";
    public static final String AllCommands = "eaglefactions.command";

    public static final String AllyCommands = "eaglefactions.command.ally";
    public static final String AddAllyCommand = "eaglefactions.command.ally.add";
    public static final String RemoveAllyCommand = "eaglefactions.command.ally.remove";

    public static final String EnemyCommands = "eaglefactions.command.enemy";
    public static final String AddEnemyCommand = "eaglefactions.command.enemy.add";
    public static final String RemoveEnemyCommand = "eaglefactions.command.enemy.remove";

    public static final String CreateCommand = "eaglefactions.command.create";
    public static final String DisbandCommand = "eaglefactions.command.disband";
    public static final String InviteCommand = "eaglefactions.command.invite";
    public static final String JoinCommand = "eaglefactions.command.join";
    public static final String LeaveCommand = "eaglefactions.command.leave";
    public static final String ListCommand = "eaglefactions.command.list";
    public static final String KickCommand = "eaglefactions.command.kick";
    public static final String FriendlyFireCommand = "eaglefactions.command.friendlyfire";

    public static final String HelpCommand = "eaglefactions.command.help";
    public static final String PlayerCommand = "eaglefactions.command.player";
    public static final String InfoCommand = "eaglefactions.command.info";
    public static final String VersionCommand = "eaglefactions.command.version";

    public static final String ClaimCommand = "eaglefactions.command.claim";
    public static final String AutoClaimCommand = "eaglefactions.command.autoclaim";
    public static final String UnclaimCommand = "eaglefactions.command.unclaim";
    public static final String UnclaimAllCommand = "eaglefactions.command.unclaimall";

    public static final String OfficerCommand = "eaglefactions.command.officer";
    public static final String SetHomeCommand = "eaglefactions.command.sethome";
    public static final String HomeCommand = "eaglefactions.command.home";

    public static final String MapCommand = "eaglefactions.command.map";
    public static final String AutoMapCommand = "eaglefactions.command.automap";

    public static final String AdminCommand = "eaglefactions.command.admin";

    public static final String SetPowerCommand = "eaglefactions.command.setpower";
    public static final String MaxPowerCommand = "eaglefactions.command.maxpower";
}

Add file that contains all plugin permissions


package org.squiddev.plethora.integration;

import com.google.common.collect.Sets;
import dan200.computercraft.api.lua.LuaException;
import net.minecraft.util.ResourceLocation;
import org.squiddev.plethora.api.method.BasicObjectMethod;
import org.squiddev.plethora.api.method.IContext;
import org.squiddev.plethora.api.method.IUnbakedContext;
import org.squiddev.plethora.api.module.IModuleContainer;
import org.squiddev.plethora.api.reference.Reference;

import javax.annotation.Nonnull;
import java.util.Set;

import static org.squiddev.plethora.api.method.ArgumentHelper.getString;

public class MethodsModules {
	@BasicObjectMethod.Inject(
		value = IModuleContainer.class, worldThread = true,
		doc = "function():table -- Lists all modules available"
	)
	public static Object[] listModules(@Nonnull IContext<IModuleContainer> context, @Nonnull Object[] args) throws LuaException {
		return new Object[]{context.getModules().toArray()};
	}

	@BasicObjectMethod.Inject(
		value = IModuleContainer.class, worldThread = true,
		doc = "function():boolean -- Checks whether a module is available"
	)
	public static Object[] hasModules(@Nonnull IContext<IModuleContainer> context, @Nonnull Object[] args) throws LuaException {
		ResourceLocation module = new ResourceLocation(getString(args, 0));
		return new Object[]{context.hasModule(module)};
	}

	/*@BasicObjectMethod.Inject(
		value = IModuleContainer.class, worldThread = true,
		doc = "function(names:string...):table -- Gets the methods which require these modules"
	)*/
	public static Object[] filterModules(@Nonnull IContext<IModuleContainer> context, @Nonnull Object[] args) throws LuaException {
		final ResourceLocation[] modules = new ResourceLocation[args.length];
		for (int i = 0; i < args.length; i++) {
			modules[i] = new ResourceLocation(getString(args, i));
		}

		final IModuleContainer container = context.getTarget();
		IModuleContainer filteredContainer = new IModuleContainer() {
			@Nonnull
			@Override
			public Set<ResourceLocation> get() throws LuaException {
				Set<ResourceLocation> existing = container.get();
				Set<ResourceLocation> out = Sets.newHashSetWithExpectedSize(modules.length);
				for (ResourceLocation module : modules) {
					if (existing.contains(module)) out.add(module);
				}
				return out;
			}
		};

		// FIXME: This doesn't actually work, we need to pass it to the primary module reference too.
		IUnbakedContext<IModuleContainer> selected = context.makeChild(Reference.id(filteredContainer));

		return new Object[]{selected.getObject()};
	}
}

Add some basic methods to list modules

Add some basic methods to list modules


package com.github.fge.grappa.examples.recursiveparens;

import com.github.parboiled1.grappa.parsers.EventBusParser;
import org.parboiled.Parboiled;
import org.parboiled.Rule;
import org.parboiled.parserunners.BasicParseRunner;
import org.parboiled.parserunners.ParseRunner;

public class RecursiveParensParser
    extends EventBusParser<Void>
{
    Rule exprContent()
    {
        return oneOrMore(noneOf("()"));
    }

    Rule expression()
    {
        return sequence(
            '(',
            exprContent(),
            zeroOrMore(expression()),
            optional(exprContent()),
            ')'
        );
    }

    public static void main(final String... args)
    {
        final RecursiveParensParser parser
            = Parboiled.createParser(RecursiveParensParser.class);
        final ParseRunner<Void> runner =
            new BasicParseRunner<>(parser.expression());
        System.out.println(runner.run("(a(b(c))d)").isSuccess());
    }
}

Add a parser for recursive parens plus contents

Answer to this question on parboiled-users:

http://users.parboiled.org/Recursion-grouping-question-tp4024358p4024360.html


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

package com.google.gerrit.acceptance.git;

import com.google.gerrit.acceptance.AbstractDaemonTest;
import org.eclipse.jgit.api.errors.TransportException;
import org.eclipse.jgit.junit.TestRepository;
import org.eclipse.jgit.lib.Config;
import org.eclipse.jgit.transport.RefSpec;
import org.junit.Test;

public class GitmodulesIT extends AbstractDaemonTest {
  @Test
  public void invalidSubmoduleURLIsRejected() throws Exception {
    pushGitmodules("name", "-invalid-url", "path", "Invalid submodule URL");
  }

  @Test
  public void invalidSubmodulePathIsRejected() throws Exception {
    pushGitmodules("name", "http://somewhere", "-invalid-path", "Invalid submodule path");
  }

  @Test
  public void invalidSubmoduleNameIsRejected() throws Exception {
    pushGitmodules("-invalid-name", "http://somewhere", "path", "Invalid submodule name");
  }

  private void pushGitmodules(String name, String url, String path, String expectedErrorMessage)
      throws Exception {
    Config config = new Config();
    config.setString("submodule", name, "url", url);
    config.setString("submodule", name, "path", path);
    TestRepository<?> repo = cloneProject(project);
    repo.branch("HEAD")
        .commit()
        .insertChangeId()
        .message("subject: adding new subscription")
        .add(".gitmodules", config.toText().toString())
        .create();

    exception.expectMessage(expectedErrorMessage);
    exception.expect(TransportException.class);
    repo.git().push().setRemote("origin").setRefSpecs(new RefSpec("HEAD:refs/for/master")).call();
  }
}

Add tests for .gitmodules validation

Add tests for .gitmodules validation

Add tests to ensure that pushes containing invalid .gitmodules
content are rejected. Without the previous commit that updates
JGit to fix CVE-2018-17456 [1], these tests fail.

[1] https://nvd.nist.gov/vuln/detail/CVE-2018-17456

Change-Id: Id07a9560ff224ce4971f3e848656b987ac9357c2


package de.philipphager.disclosure.database.version.mapper;

import android.content.pm.PackageInfo;
import de.philipphager.disclosure.database.version.model.Version;
import de.philipphager.disclosure.util.Mapper;
import org.threeten.bp.LocalDateTime;

public class ToVersionMapper implements Mapper<PackageInfo, Version> {
  private final long appId;

  public ToVersionMapper(long appId) {
    this.appId = appId;
  }

  @Override public Version map(PackageInfo from) {
    return Version.create(appId, from.versionCode, from.versionName, LocalDateTime.now());
  }
}

Add mapper for Version model

Add mapper for Version model

Filters out an apps version from android.PackageInfo


package de.tudresden.inf.lat.born.owlapi.example;

import java.util.List;

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

/**
 *
 * @author Julian Mendez
 *
 */
public class ExampleLoaderTest {

	@Test
	public void testGetExampleConfigurations() {
		ExampleLoader loader = new ExampleLoader();
		List<ExampleConfiguration> list = loader.getExampleConfigurations();
		Assert.assertEquals(2, list.size());

		{
			ExampleConfiguration conf0 = list.get(0);
			Assert.assertEquals("example-0", conf0.getOntologyName());
			Assert.assertTrue(conf0.getOntologyFileName().endsWith("/examples/example-0.owl"));
			Assert.assertEquals(
					"query(sub('http://lat.inf.tu-dresden.de/systems/born/born-example#a', 'http://lat.inf.tu-dresden.de/systems/born/born-example#e')).\n\n",
					conf0.getQuery());
		}

		{
			ExampleConfiguration conf1 = list.get(1);
			Assert.assertEquals("example-1", conf1.getOntologyName());
			Assert.assertTrue(conf1.getOntologyFileName().endsWith("/examples/example-1.owl"));
			Assert.assertEquals(
					"query(sub('http://lat.inf.tu-dresden.de/systems/born/born-example#a', 'http://lat.inf.tu-dresden.de/systems/born/born-example#e')).\n\n",
					conf1.getQuery());
		}

	}

}

Create test for example loader

Create test for example loader


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

package org.eclipse.birt.report.tests.model.regression;

import java.util.List;

import org.eclipse.birt.report.model.api.DesignFileException;
import org.eclipse.birt.report.model.api.ScriptDataSetHandle;
import org.eclipse.birt.report.tests.model.BaseTestCase;

/**
 * Regression description:
 *

 * BIRT 2.0 Scripted Data Set converted incorrectly in 2.1
 *

 * First attachment in this file is a report design created in 2.0.1, which
 * defines a Scripted Data Set. Open the design in 2.1RC5, the BIRT designer
 * converts the design to 2.1 format. (Attachment 2 [edit] is the converted
 * design file). However visual inspection of the XML source reveals that the
 * data set definition contains both a "resultSet" structure and an identical
 * "resultSetHints" structure. The "resultSet" structure here is wrong - it
 * should have been removed during the conversion.
 *

 * As it stands the extranueous "resultSet" does not stop the data set from
 * working so this is not a critical issue. But it should be removed.
 *

 * Test description:
 *

 * Open the 2.1 report, make sure that the resultSet list property is removed
 * after convertion.
 *

 */
public class Regression_148548 extends BaseTestCase
{

	private final static String REPORT = "ScriptTest2.0.1.rptdesign"; //$NON-NLS-1$

	/**
	 * @throws DesignFileException
	 */

	public void test_regression_148548( ) throws DesignFileException
	{
		openDesign( REPORT );
		ScriptDataSetHandle ds = (ScriptDataSetHandle) designHandle
				.findDataSet( "Data Set" ); //$NON-NLS-1$
		List resultSets = ds
				.getListProperty( ScriptDataSetHandle.RESULT_SET_PROP );

		assertNull( resultSets );
	}
}

Add one regression test case

Add one regression test case


package seedu.address.model;

import static org.junit.Assert.*;

import org.junit.Test;

import seedu.address.commons.exceptions.IllegalValueException;
import seedu.address.model.person.Person;
import seedu.address.testutil.PersonBuilder;
import seedu.address.testutil.TestPerson;

/**
 * Test classes for Person
 */
public class PersonTest {
    @Test
    public void person_hashCodeShouldMatch_returnTrue() {
        TestPerson pb;
        try {
            pb = (new PersonBuilder()).withAddress("Singapore").withLabels("testLabel").withName("Name").withPhone("12345678").withEmail("email@email.com").build();
            Person p = new Person(pb);
            int hashcode = 1027801006;
            assert(p.hashCode() == hashcode);
        } catch (IllegalValueException e) {
            e.printStackTrace();
            fail("Person fail Illegal value");
        }

    }
}

Add Testcase for Person's hashcode

Add Testcase for Person's hashcode


package io.quarkus.smallrye.graphql.deployment;

import static io.restassured.RestAssured.get;
import static org.hamcrest.Matchers.containsString;

import javax.validation.Valid;
import javax.validation.constraints.Size;

import org.eclipse.microprofile.graphql.GraphQLApi;
import org.eclipse.microprofile.graphql.Query;
import org.jboss.shrinkwrap.api.asset.EmptyAsset;
import org.jboss.shrinkwrap.api.asset.StringAsset;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;

import io.quarkus.test.QuarkusUnitTest;

/**
 * Basic test to verify that bean validation constraints on input fields are transformed into GraphQL directives when
 * the option to include directives in the schema is enabled.
 */
public class BeanValidationGraphQLDirectivesTest extends AbstractGraphQLTest {

    @RegisterExtension
    static QuarkusUnitTest test = new QuarkusUnitTest()
            .withApplicationRoot((jar) -> jar
                    .addClasses(Person.class)
                    .addAsResource(new StringAsset("quarkus.smallrye-graphql.schema-include-directives=true"),
                            "application.properties")
                    .addAsManifestResource(EmptyAsset.INSTANCE, "beans.xml"));

    @Test
    public void validateDirectivesPresentInSchema() {
        get("/graphql/schema.graphql")
                .then()
                .body(containsString("input PersonInput {\n" +
                        "  name: String @constraint(maxLength : 20, minLength : 5)\n" +
                        "}\n"))
                .body(containsString(
                        "queryWithConstrainedArgument(constrained: String @constraint(maxLength : 123)): String"));
    }

    @GraphQLApi
    public static class ValidationApi {

        @Query
        public String query(@Valid Person person) {
            return null;
        }

        @Query
        public String queryWithConstrainedArgument(@Size(max = 123) String constrained) {
            return null;
        }

    }

    public static class Person {

        @Size(min = 5, max = 20)
        private String name;

        public String getName() {
            return name;
        }

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

}

Test for bean validation directives

Test for bean validation directives


package swing;

import java.awt.BorderLayout;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JSplitPane;

public class TestJSplitPane {
  private void init() {
    JFrame frame = new JFrame();
    frame.setLayout(new BorderLayout());
    JSplitPane splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT);
    splitPane.setRightComponent(new JButton("Here I Am"));
    splitPane.setLeftComponent(new JButton("Me Too"));
    splitPane.setResizeWeight(0.8);
    frame.add(splitPane, BorderLayout.CENTER);
    frame.pack();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setVisible(true);
  }

  public static void main(String[] args) {
    new TestJSplitPane().init();
  }
}

Add example about usage of the JSplitPane used by buttons.


package edu.java.cosc111.samples;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Scanner;

/**
 *
 * @author russel
 */
public class PathTest {

    private static final Scanner cin = new Scanner(System.in);

    public static void main(String[] args) throws IOException {
        manageFile();
    }

    private static void getFileInformationFromPath(Path p) throws IOException{

        System.out.println("\n---------------File Information------------------");
        System.out.printf("Is absolute path? %s%n",p.isAbsolute());
        System.out.printf("Absolute Path: %s%n",p.toAbsolutePath());
        System.out.printf("Filename: %s%n",p.getFileName());
        System.out.printf("Parent: %s%n",p.getParent());

        System.out.printf("Kind: %s%n",Files.isDirectory(p)?"Directory":"File");
        System.out.printf("Size (in bytes): %d%n",Files.size(p));

        System.out.printf("Existing: %b%n",Files.exists(p));
        System.out.printf("Readable: %b%n",Files.isReadable(p));
        System.out.printf("Writable: %b%n",Files.isWritable(p));
        System.out.printf("Executable: %b%n",Files.isExecutable(p));
        System.out.printf("Hidden: %b%n",Files.isHidden(p));
        System.out.println("-------------------------------------------------\n");
    }

    private static void manageFile() throws IOException{

        while(true){
            System.out.print("Enter file path: ");
            String path = cin.nextLine();
            Path p = Paths.get(path);
            System.out.println("What do you want to do:");
            System.out.println("   [0] Exit");
            System.out.println("   [1] Create File");
            System.out.println("   [2] Create Directory");
            System.out.println("   [3] Delete File/Directory");
            System.out.println("   [4] Get File/Directory Information");
            System.out.print("Choice: ");
            int choice;
            switch((choice = cin.nextInt())){
                case 0:return;
                case 1:
                case 2:
                    if(Files.exists(p)){
                        System.out.printf("%s already exists.%n",p.toAbsolutePath());
                    }else{
                        if(choice == 1){
                            Files.createFile(p);
                        }else{
                            Files.createDirectories(p);
                        }
                        System.out.printf("%s is created successfully.%n",p.toAbsolutePath());
                    }
                    break;
                case 3:
                    if(Files.deleteIfExists(p)){
                        System.out.printf("%s is deleted successfully.%n",p.toAbsolutePath());
                    }else{
                        System.out.printf("%s does not exists.%n",p.toAbsolutePath());
                    }
                    break;
                case 4:
                    getFileInformationFromPath(p);
                default:
                    break;
            }
            cin.nextLine();
            System.out.println();
        }
    }
}

Add sample to test basic Path and Files methods


package com.millross.blog.async;

import org.junit.Test;

import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionException;
import java.util.concurrent.atomic.AtomicReference;

/**
 *
 */
public class ExceptionalThenComposeTest extends CompletableFutureTestBase {

    @Test(expected = IntentionalException.class)
    public void exceptionCallingThenApplyAsSeenFromNextStage() throws Throwable {
        final AtomicReference<Throwable> thrownException = new AtomicReference<>(null);
        final CompletableFuture<Object> future = CompletableFuture.supplyAsync(delayedValueSupplier(1), executor)
                .thenCompose(i -> {
                    throw new IntentionalException();
                })
                .whenComplete((v, t) -> {
                    if (t != null) {
                        thrownException.set(t);
                    }
                });
        try {
            future.join();
        } catch (CompletionException ex) {
            throw (Optional.ofNullable(thrownException.get().getCause()).orElse(new RuntimeException("No thrown exception")));
        }
    }

}

Add exception propagation demo for thenCompose


package org.opennms.netmgt.dao;

import java.util.Collection;

import org.hibernate.criterion.Restrictions;
import org.opennms.netmgt.model.OnmsCriteria;
import org.opennms.netmgt.model.OnmsNode;

public class CriteriaTestCase extends AbstractDaoTestCase {

    public void testSimple() {
        OnmsCriteria crit = new OnmsCriteria(OnmsNode.class);
        crit.add(Restrictions.eq("label", "node1"));

        Collection<OnmsNode> matching = getNodeDao().findMatching(crit);

        assertEquals("Expect a single node with label node1", 1, matching.size());

        OnmsNode node = matching.iterator().next();
        assertEquals("node1", node.getLabel());
        assertEquals(3, node.getIpInterfaces().size());
    }

    public void testComplicated() {
        OnmsCriteria crit =
            new OnmsCriteria(OnmsNode.class)
            .createAlias("ipInterfaces", "iface")
            .add(Restrictions.eq("iface.ipAddress", "192.168.2.1"));

        Collection<OnmsNode> matching = getNodeDao().findMatching(crit);

        assertEquals("Expect a single node with an interface 192.168.2.1", 1, matching.size());

        OnmsNode node = matching.iterator().next();
        assertEquals("node2", node.getLabel());
        assertEquals(3, node.getIpInterfaces().size());

    }
}

Test case for new OnmsCriteria

Test case for new OnmsCriteria


package leetcode101_110;

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

/**Given a singly linked list where elements are sorted in ascending order,
 convert it to a height balanced BST.
 * Created by eugene on 16/1/28.
 */
public class ConvertSortedListToBinarySearchTree {

    //Definition for a binary tree node.
    public static class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;
        TreeNode(int x) { val = x; }
    }

    // Definition for singly-linked list.
    public static class ListNode {
        int val;
        ListNode next;
        ListNode(int x) { val = x; }
    }

    //获取链表长度后,自底向上(中序顺序)递归建树
    private ListNode node = null;
    public TreeNode sortedListToBST(ListNode head) {
        if (head==null) return null;
        node = head;
        int len = 0;
        while (node!=null){
            len++;
            node = node.next;
        }
        node = head;
        return sortedListToBST(0, len-1);
    }
    private TreeNode sortedListToBST(int l, int r){
        if (l>r) return null;
        int m = (l+r)/2;
        TreeNode left = sortedListToBST(l, m-1);
        TreeNode root = new TreeNode(node.val);
        node = node.next;
        TreeNode right = sortedListToBST(m+1, r);
        root.left = left;
        root.right = right;
        return root;
    }

    //先将链表转为数组,再自顶向下(先根再左右子树)递归建树
    public TreeNode sortedListToBST1(ListNode head) {
        if (head==null) return null;
        ListNode node = head;
        List<Integer> list = new ArrayList<>();
        while (node!=null){
            list.add(node.val);
            node = node.next;
        }
        return sortedArrayToBST(list, 0, list.size()-1);
    }
    private TreeNode sortedArrayToBST(List<Integer> nums, int l, int r){
        if (l>r) return null;
        int m = (l+r)/2;
        TreeNode root = new TreeNode(nums.get(m));
        root.left = sortedArrayToBST(nums, l, m-1);
        root.right = sortedArrayToBST(nums, m+1, r);
        return root;
    }

}

Convert Sorted List to Binary Search Tree


package com.test.graphs;

import com.graphs.DetectCycle;
import com.graphs.GraphAdjacencyListRepresentation;

import junit.framework.TestCase;

public class TestDetectCycle extends TestCase {

    public void testConnectedComponentsInDirectedGraph() {
        GraphAdjacencyListRepresentation graph = new GraphAdjacencyListRepresentation(13, true);

        graph.addEdge(0, 5);
        graph.addEdge(0, 1);

        graph.addEdge(2, 0);
        graph.addEdge(2, 3);

        graph.addEdge(3, 5);
        graph.addEdge(3, 2);

        graph.addEdge(4, 3);
        graph.addEdge(4, 2);

        graph.addEdge(5, 4);

        graph.addEdge(6, 9);
        graph.addEdge(6, 4);
        graph.addEdge(6, 8);
        graph.addEdge(6, 0);

        graph.addEdge(7, 6);
        graph.addEdge(7, 9);

        graph.addEdge(8, 6);

        graph.addEdge(9, 11);
        graph.addEdge(9, 10);

        graph.addEdge(10, 12);

        graph.addEdge(11, 4);
        graph.addEdge(11, 12);

        graph.addEdge(12, 9);

        assertEquals(true, DetectCycle.haveCycle(graph));

        graph = new GraphAdjacencyListRepresentation(13, true);

        graph.addEdge(0, 5);
        graph.addEdge(0, 1);
        graph.addEdge(0, 6);

        graph.addEdge(2, 0);
        graph.addEdge(2, 3);

        graph.addEdge(3, 5);

        graph.addEdge(5, 4);

        graph.addEdge(6, 9);
        graph.addEdge(6, 4);

        graph.addEdge(7, 6);

        graph.addEdge(8, 7);

        graph.addEdge(9, 11);
        graph.addEdge(9, 10);
        graph.addEdge(9, 12);

        graph.addEdge(11, 12);

        assertEquals(false, DetectCycle.haveCycle(graph));

    }

}

Add JUnit test for DetectCycle

Add JUnit test for DetectCycle


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

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

import static java.lang.annotation.ElementType.PARAMETER;
import static java.lang.annotation.RetentionPolicy.RUNTIME;

/**
 * Filters events delivered to the {@linkplain Subscribe subscriber method} the first
 * parameter of which has this annotation.
 *
 *
For example, the following method would be invoked only if the owner of the created
 * project is {@code mary@ackme.net}:
 *
{@code
 * \@Subscribe
 * void on(@Where(field = "owner.email" equals = "mary@ackme.net") ProjectCreated e) { ... }
 * }

 *
 *
NOTE: This syntax applies only to events. Filtering state subscriptions
 * is not supported.
 */
@Retention(RUNTIME)
@Target(PARAMETER)
@Documented
public @interface Where {

    /**
     * The {@linkplain io.spine.base.FieldPath path to the field} of the event message to filter by.
     */
    String field();

    /**
     * The expected value of the field.
     *
     *
The value converted with help of {@link io.spine.string.Stringifier Stringifier}s into
     * the type of the actual value of the message field.
     */
    String equals();
}

Introduce new argument filter annotation


package org.jetbrains.plugins.javaFX.sceneBuilder;

import com.intellij.openapi.fileEditor.FileEditor;
import com.intellij.openapi.fileEditor.FileEditorPolicy;
import com.intellij.openapi.fileEditor.FileEditorProvider;
import com.intellij.openapi.project.DumbAware;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.SystemInfo;
import com.intellij.openapi.util.registry.Registry;
import com.intellij.openapi.vfs.VirtualFile;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.plugins.javaFX.fxml.JavaFxFileTypeFactory;

/**
 * @author Alexander Lobas
 */
public class SceneBuilderEditorProvider implements FileEditorProvider, DumbAware{
  @Override
  public boolean accept(@NotNull Project project, @NotNull VirtualFile file) {
    return JavaFxFileTypeFactory.FXML_EXTENSION.equalsIgnoreCase(file.getExtension()) &&
           SystemInfo.isJavaVersionAtLeast("1.8") &&
           Registry.is("embed.scene.builder");
  }

  @NotNull
  @Override
  public FileEditor createEditor(@NotNull Project project, @NotNull VirtualFile file) {
    return new SceneBuilderEditor(project, file);
  }

  @NotNull
  @Override
  public String getEditorTypeId() {
    return "JavaFX-Scene-Builder";
  }

  @NotNull
  @Override
  public FileEditorPolicy getPolicy() {
    return FileEditorPolicy.PLACE_AFTER_DEFAULT_EDITOR;
  }
}

package org.jetbrains.plugins.javaFX.sceneBuilder;

import com.intellij.openapi.fileEditor.FileEditor;
import com.intellij.openapi.fileEditor.FileEditorPolicy;
import com.intellij.openapi.fileEditor.FileEditorProvider;
import com.intellij.openapi.project.DumbAware;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.SystemInfo;
import com.intellij.openapi.util.registry.Registry;
import com.intellij.openapi.vfs.VirtualFile;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.plugins.javaFX.fxml.JavaFxFileTypeFactory;

/**
 * @author Alexander Lobas
 */
public class SceneBuilderEditorProvider implements FileEditorProvider, DumbAware{
  static {
    ClassLoader pluginClassLoader = SceneBuilderEditorProvider.class.getClassLoader();
    pluginClassLoader.setPackageAssertionStatus("com.oracle.javafx.scenebuilder.kit", false);
  }

  @Override
  public boolean accept(@NotNull Project project, @NotNull VirtualFile file) {
    return JavaFxFileTypeFactory.FXML_EXTENSION.equalsIgnoreCase(file.getExtension()) &&
           SystemInfo.isJavaVersionAtLeast("1.8") &&
           Registry.is("embed.scene.builder");
  }

  @NotNull
  @Override
  public FileEditor createEditor(@NotNull Project project, @NotNull VirtualFile file) {
    return new SceneBuilderEditor(project, file);
  }

  @NotNull
  @Override
  public String getEditorTypeId() {
    return "JavaFX-Scene-Builder";
  }

  @NotNull
  @Override
  public FileEditorPolicy getPolicy() {
    return FileEditorPolicy.PLACE_AFTER_DEFAULT_EDITOR;
  }
}

Javafx: Disable assertions in Scene Builder because of false positives (IDEA-162542)


package com.alexstyl.specialdates.events;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.runners.MockitoJUnitRunner;

import static org.fest.assertions.api.Assertions.assertThat;

@RunWith(MockitoJUnitRunner.class)
public class EventTypeTest {

    @Test
    public void mapsTypeBirthdayIdToBirthdayEvent() {
        EventType eventType = EventType.fromId(EventColumns.TYPE_BIRTHDAY);
        assertThat(eventType).isEqualTo(EventType.BIRTHDAY);
    }

    @Test
    public void mapsTypeNamedayIdToNamedayEvent() {
        EventType eventType = EventType.fromId(EventColumns.TYPE_NAMEDAY);
        assertThat(eventType).isEqualTo(EventType.NAMEDAY);
    }

    @Test(expected = IllegalArgumentException.class)
    public void throwExceptionOnInvalidId() {
        EventType.fromId(3);
    }
}

Add test to ensure correct creation of EventType


package net.glowstone.block;

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

import org.junit.jupiter.api.Test;

class MaterialUtilTest {
    @Test
    public void testSanityChecks() {
        assertTrue(MaterialUtil.SLABS.containsAll(MaterialUtil.WOODEN_SLABS));
        assertTrue(MaterialUtil.STAIRS.containsAll(MaterialUtil.WOODEN_STAIRS));
        assertTrue(MaterialUtil.BUTTONS.containsAll(MaterialUtil.WOODEN_BUTTONS));
    }
}

Add sanity checks for reflectively-generated sets in MaterialUtil


package com.stripe.model;

import com.stripe.BaseStripeTest;
import com.stripe.model.Event;

import java.io.IOException;

import org.junit.Test;

import static org.junit.Assert.assertEquals;

public class EventTest extends BaseStripeTest {
	@Test
	public void nestedObjectDeserializesToModel() throws IOException {
		String json = resource("account_event.json");
		Event event = StripeObject.PRETTY_PRINT_GSON.fromJson(json, Event.class);

		// Thanks to some GSON magic, the object nested within the event can be
		// typecast to its expected type.
		Account account = (com.stripe.model.Account)event.getData().getObject();

		assertEquals(account.getEmail(), "test@stripe.com");
	}
}

Add test to demonstrate event deserialization

Adds a basic test to demonstrate how to deserialize an event and then
typecast the `StripeObject` nested in it to a model that's appropriate
based on the type of event.

Not a true fix for #297, but at least produces some sample code for this
operation, even if not particularly discoverable.


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

package org.springframework.session.data.mongo;

import org.junit.Test;

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

/**
 * @author Rob Winch
 */
public class MongoExpiringSessionTests {

	@Test
	public void isExpiredWhenIntervalNegativeThenFalse() {
		MongoExpiringSession session = new MongoExpiringSession();
		session.setMaxInactiveIntervalInSeconds(-1);
		session.setLastAccessedTime(0L);

		assertThat(session.isExpired()).isFalse();
	}
}

Add MongoSession.isExpired interval < 0 Test

Issue gh-629


package leetcode.invert_binary_tree;

import common.TreeNode;

public class Solution {
    public TreeNode invertTree(TreeNode root) {
        if(root != null){
            TreeNode tmp = root.left;
            root.left = root.right;
            root.right = tmp;
            invertTree(root.left);
            invertTree(root.right);
        }
        return root;
    }
}

Add java solution for 226. Invert Binary Tree

226. Invert Binary Tree: https://leetcode.com/problems/invert-binary-tree/


package net.vexelon.bgrates.ui;

import java.util.Map;

import com.google.common.collect.Maps;

import net.vexelon.bgrates.R;

public class UIFlags {

	private static final Map<String, Integer> flagsMap = Maps.newHashMap();

	static {
		flagsMap.put("au", R.drawable.au);
		flagsMap.put("bg", R.drawable.bg);
		flagsMap.put("br", R.drawable.br);
		flagsMap.put("ca", R.drawable.ca);
		flagsMap.put("ch", R.drawable.ch);
		flagsMap.put("ca", R.drawable.ca);
		flagsMap.put("cn", R.drawable.cn);
		flagsMap.put("cz", R.drawable.cz);
		flagsMap.put("dk", R.drawable.dk);
		flagsMap.put("ee", R.drawable.ee);
		flagsMap.put("gb", R.drawable.gb);
		flagsMap.put("hk", R.drawable.hk);
		flagsMap.put("hr", R.drawable.hr);
		flagsMap.put("hu", R.drawable.hu);
		flagsMap.put("id", R.drawable.id);
		flagsMap.put("in", R.drawable.in);
		flagsMap.put("is", R.drawable.is);
		flagsMap.put("jp", R.drawable.jp);
		flagsMap.put("kr", R.drawable.kr);
		flagsMap.put("lt", R.drawable.lt);
		flagsMap.put("lv", R.drawable.lv);
		flagsMap.put("mx", R.drawable.mx);
		flagsMap.put("my", R.drawable.my);
		flagsMap.put("no", R.drawable.no);
		flagsMap.put("nz", R.drawable.nz);
		flagsMap.put("ph", R.drawable.ph);
		flagsMap.put("pl", R.drawable.pl);
		flagsMap.put("ro", R.drawable.ro);
		flagsMap.put("ru", R.drawable.ru);
		flagsMap.put("se", R.drawable.se);
		flagsMap.put("sg", R.drawable.sg);
		flagsMap.put("th", R.drawable.th);
		flagsMap.put("tr", R.drawable.tr);
		flagsMap.put("us", R.drawable.us);
		flagsMap.put("xa", R.drawable.xa);
		flagsMap.put("za", R.drawable.za);
		flagsMap.put("eu", R.drawable.eu);
	}

	public static int getResourceFromCode(String code) {
		Integer resId = R.drawable.unknown;
		if (!code.isEmpty()) {
			String lower = code.substring(0, 2).toLowerCase();
			if (flagsMap.containsKey(lower)) {
				resId = flagsMap.get(lower);
			}
		}
		return resId;
	}
}

Add currency flags UI handler

Add currency flags UI handler


package guitests;

import static org.junit.Assert.assertTrue;

import java.io.File;

import org.junit.Test;

//@@author A0164440M
public class PathCommandTest extends TaskBookGuiTest {

    @Test
    public void saveToCorrectPath() {
        assertCorrectPathResult("path", "a.xml");
        assertCorrectPathResult("path", "a.txt");
    }

    @Test
    public void saveToInvalidPath() {
        assertWrongPathResult("path", "data/C:");

        commandBox.runCommand("path");
        assertResultMessage("Invalid command format! \npath: Change save path. "
                + "Parameters: path [filename] \nExample: path taskbook.xml");
    }

    private void assertCorrectPathResult(String command, String path) {
        commandBox.runCommand(command + " " + path);
        assertTrue(fileExist(path));
        assertResultMessage("Save path has been successfully updated \n");
    }

    private void assertWrongPathResult(String command, String path) {
        commandBox.runCommand(command + " " + path);
        assertTrue(!fileExist(path));
        assertResultMessage("This path is invalid");
    }

    private boolean fileExist(String path) {
        File f = new File(path);
        if (f.exists() && !f.isDirectory()) {
            return true;
        }
        return false;
    }
}

Add test case for path command

Add test case for path command


package com.consol.citrus.simulator.http;

import java.io.IOException;
import java.nio.charset.Charset;

import com.consol.citrus.http.controller.HttpMessageController;
import org.springframework.http.MediaType;
import org.springframework.mock.http.MockHttpInputMessage;
import org.springframework.mock.http.MockHttpOutputMessage;
import org.testng.Assert;
import org.testng.annotations.Test;

/**
 * @author Christoph Deppisch
 */
public class SimulatorHttpMessageConverterTest {

    private SimulatorHttpMessageConverter converter = new SimulatorHttpMessageConverter();

    @Test
    public void testSimulatorMessageConverter() throws IOException {
        Assert.assertFalse(converter.canRead(Object.class, Object.class, MediaType.ALL));
        Assert.assertFalse(converter.canRead(Object.class, MediaType.ALL));
        Assert.assertFalse(converter.canWrite(Object.class, Object.class, MediaType.ALL));
        Assert.assertFalse(converter.canWrite(Object.class, MediaType.ALL));

        Assert.assertEquals(converter.read(String.class, HttpMessageController.class, new MockHttpInputMessage("Hello".getBytes(Charset.forName("UTF-8")))), "Hello");
    }

    @Test(expectedExceptions = IllegalStateException.class)
    public void testUnsupportedRead() throws IOException {
        converter.read(Object.class, new MockHttpInputMessage("Hello".getBytes(Charset.forName("UTF-8"))));
    }

    @Test(expectedExceptions = IllegalStateException.class)
    public void testUnsupportedWrite() {
        converter.write("Hello", MediaType.TEXT_PLAIN, new MockHttpOutputMessage());
    }

    @Test(expectedExceptions = IllegalStateException.class)
    public void testUnsupportedGenericWrite() {
        converter.write("Hello", String.class, MediaType.TEXT_PLAIN, new MockHttpOutputMessage());
    }

}

Add unit test for new classes

fix: Add unit test for new classes


package de.fu_berlin.cdv.chasingpictures.api;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.test.AndroidTestCase;
import android.util.Log;

import org.springframework.http.ResponseEntity;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

import de.fu_berlin.cdv.chasingpictures.R;

/**
 * @author Simon Kalt
 */
public class PhotoUploadRequestTest extends AndroidTestCase {

    private static final String TAG = "PhotoUploadRequestTest";

    public void setUp() throws Exception {
        super.setUp();
    }

    public void testPhotoUpload() throws Exception {
        // Register user so we have a valid access token
        LoginRequestTest.registerUser(
                getContext(),
                "Tom",
                LoginRequestTest.getUniqueEmail(),
                "12345678"
        );

        Place place = new Place();
        place.setId(6);

        //region Save picture
        Bitmap bitmap = BitmapFactory.decodeResource(getContext().getResources(), R.drawable.upload_image);
        File tempFile = null;
        try {
            tempFile = File.createTempFile("UPLOAD_TEST", ".jpg", getContext().getCacheDir());
            FileOutputStream out = new FileOutputStream(tempFile);
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);
            out.close();
        } catch (IOException e) {
            Log.e(TAG, "Image file could not be written.", e);
        }
        //endregion

        PhotoUploadRequest request = new PhotoUploadRequest(getContext(), place, tempFile);
        ResponseEntity<Picture> pictureResponseEntity = request.sendRequest();
        assertNotNull("No response entity received", pictureResponseEntity);
        Picture picture = pictureResponseEntity.getBody();
        assertNotNull("Response entity has empty body", picture);
    }
}

Add test for photo upload

Add test for photo upload


package gov.nih.nci.calab.dto.common;

/**
 * This class includes properties for User Authentication and Authorization .
 *
 *
 * @author doswellj
 *
 */

public class UserBean
{

	private String loginId;
	private String fullName;
	private String firstName;
	private String lastName;

	public UserBean() {}

	public UserBean(String strLoginId, String firstName, String lastName)
	{
		this.loginId = strLoginId;
		this.firstName= firstName;
		this.lastName= lastName;
		this.fullName = firstName + " " + lastName;
	}

	public String getLoginId()
	{
		return loginId;
	}
	public void setLoginId(String loginId)
	{
		this.loginId = loginId;
	}

	public String getFirstName()
	{
		return firstName;
	}
	public void setFirstName(String firstName)
	{
		this.firstName = firstName;
	}

	public String getLastName()
	{
		return lastName;
	}
	public void setLastName(String lastName)
	{
		this.lastName = lastName;
	}

	public String getFullName() {
		return fullName;
	}

	public void setFullName(String fullName) {
		this.fullName =fullName;
	}
}

Move the package. Container user info

Move the package.  Container user info

SVN-Revision: 1077