package com.avairebot.orion.ai.intents;

import ai.api.model.AIResponse;
import com.avairebot.orion.Orion;
import com.avairebot.orion.commands.Category;
import com.avairebot.orion.commands.CategoryHandler;
import com.avairebot.orion.contracts.ai.Intent;
import com.avairebot.orion.factories.MessageFactory;
import net.dv8tion.jda.core.entities.Message;

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

public class RequestCommandPrefix extends Intent {

    public RequestCommandPrefix(Orion orion) {
        super(orion);
    }

    @Override
    public String getAction() {
        return "command.prefix";
    }

    @Override
    public void onIntent(Message message, AIResponse response) {
        List<String> prefixes = new ArrayList<>();
        for (Category category : CategoryHandler.getValues()) {
            prefixes.add(
                String.format("`%s` %s", category.getPrefix(message), category.getName())
            );
        }

        MessageFactory.makeSuccess(message,
            "Here is all my prefixes for this server.\n\n" +
                String.join("\n", prefixes)
        ).queue();
    }
}

Create request command prefix AI intent

Create request command prefix AI intent


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

// tag::snippet-in-doc[]
import static org.junit.jupiter.api.Assertions.assertTrue;

import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;

import io.github.bonigarcia.SeleniumExtension;

@ExtendWith(SeleniumExtension.class)
public class SeleniumJupiterTest {

    @Test
    public void testWithChrome(ChromeDriver chrome) {
        chrome.get("https://bonigarcia.github.io/selenium-jupiter/");

        assertTrue(chrome.getTitle().startsWith("selenium-jupiter"));
    }

    @Test
    public void testWithChromeAndFirefix(ChromeDriver chrome,
            FirefoxDriver firefox) {
        chrome.get("http://www.seleniumhq.org/");
        firefox.get("http://junit.org/junit5/");

        assertTrue(chrome.getTitle().startsWith("Selenium"));
        assertTrue(firefox.getTitle().equals("JUnit 5"));
    }

}
// end::snippet-in-doc[]

Include simple test example ("Hello World" kinda)


package org.realityforge.arez.integration;

import java.util.List;
import javax.annotation.Nonnull;
import org.realityforge.arez.Arez;
import org.realityforge.arez.ArezContext;
import org.realityforge.arez.annotations.ArezComponent;
import org.realityforge.arez.annotations.Observable;
import org.realityforge.arez.annotations.Repository;
import org.testng.annotations.Test;
import static org.testng.Assert.*;

public class RepositoryExtensionTest
  extends AbstractIntegrationTest
{
  interface TestComponentRepositoryExtension
    extends RepositoryExtensionTest$TestComponentBaseRepositoryExtension
  {
    @Nonnull
    default List<TestComponent> findAllLike( @Nonnull final String pattern )
    {
      return self().findAllByQuery( c -> c.getValue().contains( pattern ) );
    }
  }

  @ArezComponent
  @Repository( extensions = TestComponentRepositoryExtension.class )
  static class TestComponent
  {
    private String _value;

    TestComponent( final String value )
    {
      _value = value;
    }

    @Observable
    String getValue()
    {
      return _value;
    }

    void setValue( final String value )
    {
      _value = value;
    }
  }

  @Test
  public void integrationTest()
    throws Throwable
  {
    final ArezContext context = Arez.context();

    final RepositoryExtensionTest$TestComponentRepository repository =
      RepositoryExtensionTest$TestComponentRepository.newRepository();
    final TestComponent component1 = repository.create( "ABCDEF" );
    final TestComponent component2 = repository.create( "CDEFGH" );
    final TestComponent component3 = repository.create( "EFGHIJ" );

    context.action( false, () -> assertEquals( repository.findAllLike( "AB" ).size(), 1 ) );
    context.action( false, () -> assertEquals( repository.findAllLike( "AB" ).contains( component1 ), true ) );
    context.action( false, () -> assertEquals( repository.findAllLike( "CD" ).size(), 2 ) );
    context.action( false, () -> assertEquals( repository.findAllLike( "CD" ).contains( component1 ), true ) );
    context.action( false, () -> assertEquals( repository.findAllLike( "CD" ).contains( component2 ), true ) );
    context.action( false, () -> assertEquals( repository.findAllLike( "EF" ).size(), 3 ) );
    context.action( false, () -> assertEquals( repository.findAllLike( "EF" ).contains( component1 ), true ) );
    context.action( false, () -> assertEquals( repository.findAllLike( "EF" ).contains( component2 ), true ) );
    context.action( false, () -> assertEquals( repository.findAllLike( "EF" ).contains( component3 ), true ) );
  }
}

Add some basic integration tests that use repository extensions


package org.pdxfinder.commands.postload;

import joptsimple.OptionParser;
import joptsimple.OptionSet;
import org.pdxfinder.graph.dao.ModelCreation;
import org.pdxfinder.services.DataImportService;
import org.pdxfinder.services.UtilityService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.stream.Stream;

/*
 * Created by csaba on 23/03/2019.
 */

@Component
public class CheckPDXPages implements CommandLineRunner{

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

    private String errorHtml = "err_body";
    private String successHtml = "level2";

    @Autowired
    DataImportService dataImportService;

    @Autowired
    UtilityService utilityService;

    @Override
    public void run(String... args) throws Exception {

        OptionParser parser = new OptionParser();
        parser.allowsUnrecognizedOptions();
        parser.accepts("checkPDXPages", "Testing PDX details page urls");
        OptionSet options = parser.parse(args);

        if (options.has("checkPDXPages")) {

            testDetailsPageUrls();
        }

    }

    private void testDetailsPageUrls(){

        Collection<ModelCreation> models = dataImportService.findAllModels();

        String html = "";
        for(ModelCreation model : models){

            long startTime = System.currentTimeMillis();
            String url = "http://localhost:8080/data/pdx/"+model.getDataSource()+"/"+model.getSourcePdxId();

            html = parseURL(url);
            long endTime = System.currentTimeMillis();
            long totalTime = endTime - startTime;
            checkPageContent(html, url, Long.toString(totalTime));

        }

        //log.info(html);

    }

    private void checkPageContent(String html, String url, String responseTime){

        if(html == null || html.isEmpty() || html.contains(errorHtml)){
            log.error("Page is not available "+url);
        }
        else if(html.contains(successHtml)){
            log.info("Details page is up: "+url+" Response time: "+responseTime+"ms");
        }
        else{
            log.warn("What has just happened??? "+url);
        }
    }

    public String parseURL(String urlStr) {

        StringBuilder sb = new StringBuilder();

        try {
            URL url = new URL(urlStr);
            BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
            String inputLine;
            while ((inputLine = in.readLine()) != null) {
                sb.append(inputLine);
            }
            in.close();
        } catch (Exception e) {
            return "";
        }
        return sb.toString();
    }
}

Add details page checking command

Add details page checking command


/*
 * Zed Attack Proxy (ZAP) and its related class files.
 *
 * ZAP is an HTTP/HTTPS proxy for assessing web application security.
 *
 * Copyright 2019 The ZAP Development Team
 *
 * 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.zaproxy.zap.extension.websocket;

import java.io.IOException;
import org.parosproxy.paros.network.HttpMessage;
import org.zaproxy.zap.extension.websocket.client.HandshakeConfig;
import org.zaproxy.zap.extension.websocket.client.HttpHandshakeBuilder;
import org.zaproxy.zap.extension.websocket.client.ServerConnectionEstablisher;
import org.zaproxy.zap.testutils.WebSocketTestUtils;

public abstract class WebSocketAddonTestUtils extends WebSocketTestUtils {

    public WebSocketProxy setupWebSocketProxy() {
        ServerConnectionEstablisher establisher = new ServerConnectionEstablisher();
        try {
            HttpMessage handshakeRequest =
                    new HttpMessage(
                            HttpHandshakeBuilder.getHttpHandshakeRequestHeader(
                                    super.getServerUrl()));
            return establisher.send(new HandshakeConfig(handshakeRequest, false, false));
        } catch (Exception e) {
            return null;
        }
    }

    public WebSocketMessageDTO sendOutgoingMessage(WebSocketProxy webSocketProxy, String message) {
        WebSocketMessageDTO webSocketMessage = new WebSocketMessageDTO(webSocketProxy.getDTO());
        webSocketMessage.payload = message;
        webSocketMessage.opcode = WebSocketMessage.OPCODE_TEXT;

        try {
            return webSocketProxy.send(webSocketMessage, WebSocketProxy.Initiator.MANUAL_REQUEST)
                    ? webSocketMessage
                    : null;
        } catch (IOException e) {
            return null;
        }
    }
}

Add Base Class for WebSocket Unit testing

* addOns/websocket/src/test/java/org/zaproxy/zap/extension/websocket/WebSocketAddonTestUtils.java:


package de.terrestris.shogun2.util.json;

import static org.hamcrest.CoreMatchers.instanceOf;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertThat;

import java.text.DateFormat;
import java.util.List;
import java.util.TimeZone;

import org.junit.Test;

import com.fasterxml.jackson.databind.DeserializationConfig;
import com.fasterxml.jackson.databind.Module;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationConfig;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.databind.util.ISO8601DateFormat;
import com.fasterxml.jackson.datatype.joda.JodaModule;

/**
 * @author Nils Bühner
 *
 */
public class Shogun2JsonObjectMapperTest {

	/**
	 * The object mapper to test.
	 */
	private final ObjectMapper objectMapper = new Shogun2JsonObjectMapper();

	/**
	 * Tests whether the JodaModule is registered.
	 */
	@Test
	public void testModules() {

		List<Module> modules = Shogun2JsonObjectMapper.findModules();

		assertEquals(1, modules.size());
		assertThat(modules.get(0), instanceOf(JodaModule.class));
	}

	/**
	 * Tests whether the dateFormat is ISO8601
	 */
	@Test
	public void testDateFormat() {

		SerializationConfig serializationConfig = objectMapper.getSerializationConfig();
		DeserializationConfig deserializationConfig = objectMapper.getDeserializationConfig();

		DateFormat serializationDateFormat = serializationConfig.getDateFormat();
		DateFormat deserializationDateFormat = deserializationConfig.getDateFormat();

		assertThat(serializationDateFormat, instanceOf(ISO8601DateFormat.class));
		assertThat(deserializationDateFormat, instanceOf(ISO8601DateFormat.class));
	}

	/**
	 * Tests whether the correct TimeZone is set.
	 */
	@Test
	public void testTimezone() {

		TimeZone expectedTimeZone = TimeZone.getDefault();

		SerializationConfig serializationConfig = objectMapper.getSerializationConfig();
		DeserializationConfig deserializationConfig = objectMapper.getDeserializationConfig();

		TimeZone serializationTimeZone = serializationConfig.getTimeZone();
		TimeZone deserializationTimeZone = deserializationConfig.getTimeZone();

		assertEquals(expectedTimeZone, serializationTimeZone);
		assertEquals(expectedTimeZone, deserializationTimeZone);
	}

	/**
	 * Tests whether the dates are not serialized as timestamps, but as
	 * their textual representation.
	 */
	@Test
	public void testDateSerialization() {

		SerializationConfig serializationConfig = objectMapper.getSerializationConfig();

		boolean writesDatesAsTimestamps = serializationConfig.isEnabled(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);

		assertFalse(writesDatesAsTimestamps);
	}

}

Add tests for the Shogun2JsonObjectMapper


package com.btk5h.skriptmirror.skript;

import ch.njol.skript.Skript;
import ch.njol.skript.lang.Effect;
import ch.njol.skript.lang.Expression;
import ch.njol.skript.lang.SkriptParser;
import ch.njol.skript.lang.TriggerItem;
import ch.njol.util.Kleenean;
import com.btk5h.skriptmirror.SkriptMirror;
import com.btk5h.skriptmirror.skript.reflect.ExprJavaCall;
import com.btk5h.skriptmirror.skript.reflect.ExprTry;
import com.btk5h.skriptmirror.util.SkriptUtil;
import org.bukkit.Bukkit;
import org.bukkit.event.Event;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class EffExpressionStatement extends Effect {
  static {
    Skript.registerEffect(EffExpressionStatement.class, "[(1¦await)] %~javaobject%");
  }

  private static final ExecutorService threadPool =
      Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());

  private Expression<Object> arg;
  private boolean isAsynchronous;

  @Override
  protected void execute(Event e) {
    arg.getAll(e);
  }

  @Override
  protected TriggerItem walk(Event e) {
    if (isAsynchronous) {
      CompletableFuture.runAsync(() -> execute(e), threadPool)
          .thenAccept(res -> Bukkit.getScheduler().runTask(SkriptMirror.getInstance(), () -> {
            if (getNext() != null) {
              TriggerItem.walk(getNext(), e);
            }
          }));
      return null;
    }
    return super.walk(e);
  }

  @Override
  public String toString(Event e, boolean debug) {
    return arg.toString(e, debug);
  }

  @SuppressWarnings("unchecked")
  @Override
  public boolean init(Expression<?>[] exprs, int matchedPattern, Kleenean isDelayed,
                      SkriptParser.ParseResult parseResult) {
    arg = SkriptUtil.defendExpression(exprs[0]);

    if (!(arg instanceof ExprJavaCall || arg instanceof ExprTry)) {
      return false;
    }

    isAsynchronous = (parseResult.mark & 1) == 1;
    return SkriptUtil.canInitSafely(arg);
  }
}

Add expression statement effect for effect commands


package com.seaglasslookandfeel.demo;

import javax.swing.SwingUtilities;
import javax.swing.JPanel;
import javax.swing.JFrame;
import javax.swing.JComboBox;
import javax.swing.UIManager;

import java.awt.Rectangle;

/**
 * DOCUMENT ME!
 */
public class TestComboBoxes extends JFrame {

    private static final long serialVersionUID = 1L;
    private JPanel            jContentPane     = null;
    private JComboBox         jComboBox        = null;

    /**
     * This is the default constructor
     */
    public TestComboBoxes() {
        super();
        initialize();
    }

    /**
     * This method initializes jComboBox
     *
     * @return javax.swing.JComboBox
     */
    private JComboBox getJComboBox() {
        if (jComboBox == null) {
            jComboBox = new JComboBox();
            jComboBox.setBounds(new Rectangle(87, 61, 122, 25));
        }

        return jComboBox;
    }

    /**
     * Main method.
     *
     * @param args
     *            command line args.
     */
    public static void main(String[] args) {
        try {
            UIManager.setLookAndFeel("com.seaglasslookandfeel.SeaGlassLookAndFeel");
        } catch (Exception e) {
            e.printStackTrace();
        }

        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                TestComboBoxes thisClass = new TestComboBoxes();

                thisClass.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                thisClass.setVisible(true);
            }
        });
    }

    /**
     * This method initializes this
     */
    private void initialize() {
        this.setSize(300, 200);
        this.setContentPane(getJContentPane());
        this.setTitle("JFrame");
        for (int i = 0; i < 50; i++) {
            jComboBox.addItem(i);
        }
    }

    /**
     * This method initializes jContentPane
     *
     * @return javax.swing.JPanel
     */
    private JPanel getJContentPane() {
        if (jContentPane == null) {
            jContentPane = new JPanel();
            jContentPane.setLayout(null);
            jContentPane.add(getJComboBox(), null);
        }

        return jContentPane;
    }

}

Add test for long combo box.

Add test for long combo box.


/*
 * See the NOTICE file distributed with this work for additional
 * information regarding copyright ownership.
 *
 * This is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License as
 * published by the Free Software Foundation; either version 2.1 of
 * the License, or (at your option) any later version.
 *
 * This software is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this software; if not, write to the Free
 * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
 * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
 *
 */
package com.xpn.xwiki.web;

import java.util.List;

import javax.servlet.http.HttpServletResponse;

import com.xpn.xwiki.XWiki;
import com.xpn.xwiki.XWikiContext;
import com.xpn.xwiki.XWikiException;
import com.xpn.xwiki.doc.XWikiDocument;
import com.xpn.xwiki.objects.BaseObject;
import com.xpn.xwiki.objects.BaseProperty;

/**
 * Synchronizes the objects in a document with their current classes, by removing any deprecated properties.
 *
 * @version $Id$
 */
public class ObjectsSynchronizeAction extends XWikiAction
{
    /**
     * {@inheritDoc}
     *
     * @see XWikiAction#action(XWikiContext)
     */
    @Override
    public boolean action(XWikiContext context) throws XWikiException
    {
        XWiki xwiki = context.getWiki();
        XWikiResponse response = context.getResponse();
        XWikiDocument doc = context.getDoc();

        for (List<BaseObject> classObjects : doc.getXObjects().values()) {
            for (BaseObject object : classObjects) {
                for (BaseProperty property : object.getXClass(context).getDeprecatedObjectProperties(object)) {
                    object.removeField(property.getName());
                }
            }
        }

        xwiki.saveDocument(doc, context.getMessageTool().get("core.model.xobject.synchronizeObjects.versionSummary"),
            true, context);

        if (Utils.isAjaxRequest(context)) {
            response.setStatus(HttpServletResponse.SC_NO_CONTENT);
            response.setContentLength(0);
        } else {
            // forward to edit
            String redirect = Utils.getRedirect("edit", context);
            sendRedirect(response, redirect);
        }
        return false;
    }
}

XWIKI-99: Add support for removing class properties
Added Struts action for synchronizing document objects with their current classes.

git-svn-id: d23d7a6431d93e1bdd218a46658458610974b053@29590 f329d543-caf0-0310-9063-dda96c69346f


/*
 */
package org.datadryad.rest.responses;

import javax.ws.rs.core.UriInfo;

/**
 *
 * @author Dan Leehr <dan.leehr@nescent.org>
 */
public class ResponseFactory {
    public static ErrorsResponse makeError(String detail, String title, UriInfo uriInfo, Integer statusCode) {
        ErrorObject error = new ErrorObject();
        error.path = uriInfo.getPath();
        error.status = String.valueOf(statusCode);
        error.detail = detail;
        error.title = title;
        ErrorsResponse errorsResponse = new ErrorsResponse(error);
        return errorsResponse;
    }
}

/*
 */
package org.datadryad.rest.responses;

import javax.ws.rs.core.UriInfo;

/**
 *
 * @author Dan Leehr <dan.leehr@nescent.org>
 */
public class ResponseFactory {
    public static ErrorsResponse makeError(String detail, String title, UriInfo uriInfo, Integer statusCode) {
        ErrorObject error = new ErrorObject();
        error.path = uriInfo.getAbsolutePathBuilder().build().toString();
        error.status = String.valueOf(statusCode);
        error.detail = detail;
        error.title = title;
        ErrorsResponse errorsResponse = new ErrorsResponse(error);
        return errorsResponse;
    }
}

Include absolute paths in error

Include absolute paths in error


package com.satsumasoftware.timetable.db;

import android.provider.BaseColumns;

import com.satsumasoftware.timetable.db.util.SchemaUtilsKt;

public final class TimetablesSchema implements BaseColumns {

    public static final String TABLE_NAME = "timetables";
    public static final String COL_NAME = "name";
    public static final String COL_START_DATE_DAY_OF_MONTH = "start_date_day_of_month";
    public static final String COL_START_DATE_MONTH = "start_date_month";
    public static final String COL_START_DATE_YEAR = "start_date_year";
    public static final String COL_END_DATE_DAY_OF_MONTH = "end_date_day_of_month";
    public static final String COL_END_DATE_MONTH = "end_date_month";
    public static final String COL_END_DATE_YEAR = "end_date_year";

    protected static final String SQL_CREATE = "CREATE TABLE " + TABLE_NAME + "( " +
            _ID + SchemaUtilsKt.INTEGER_TYPE + SchemaUtilsKt.PRIMARY_KEY_AUTOINCREMENT + SchemaUtilsKt.COMMA_SEP +
            COL_NAME + SchemaUtilsKt.TEXT_TYPE + SchemaUtilsKt.COMMA_SEP +
            COL_START_DATE_DAY_OF_MONTH + SchemaUtilsKt.INTEGER_TYPE + SchemaUtilsKt.COMMA_SEP +
            COL_START_DATE_MONTH + SchemaUtilsKt.INTEGER_TYPE + SchemaUtilsKt.COMMA_SEP +
            COL_START_DATE_YEAR + SchemaUtilsKt.INTEGER_TYPE + SchemaUtilsKt.COMMA_SEP +
            COL_END_DATE_DAY_OF_MONTH + SchemaUtilsKt.INTEGER_TYPE + SchemaUtilsKt.COMMA_SEP +
            COL_END_DATE_MONTH + SchemaUtilsKt.INTEGER_TYPE + SchemaUtilsKt.COMMA_SEP +
            COL_END_DATE_YEAR + SchemaUtilsKt.INTEGER_TYPE +
            " )";

    protected static final String SQL_DELETE =
            "DROP TABLE IF EXISTS " + TABLE_NAME;
}

Create a db schema class for timetables

Create a db schema class for timetables


package com.skcraft.smes.item;

import net.minecraft.item.Item;

public class SMESItems {
    public static Item itemYttriumDust;

    public static void preInit() {
        itemYttriumDust = new ItemPurifiable().setUnlocalizedName("yttriumDust");
    }
}

Set up an item loader class which should load all items on preInit


/*
 * Copyright (c) 2012 Mateusz Parzonka, Eric Bodden
 * 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:
 * Eric Bodden - initial API
 * Mateusz Parzonka - adapted API
 */
package prm4j.indexing;

/**
 * An indexing strategy has the single purpose of dispatching a parametric event, represented by instances of the type
 * {@link Event}, to all monitors corresponding to compatible variable bindings.
 *
 * For example, consider an event with a binding {a=a1,b=b1} where a1 and b1 are concrete objects. Also assume that
 * there are monitor instances for the bindings {}, {a=a1}, and {a=a1,b=b2}. The indexing algorithm will dispatch the
 * event to both {}, {a=a1} but not to {a=a1,b=b2} because the latter binding conflicts on variable b: the event binds b
 * to b1 while the monitor binds it to b2. When the event is dispatched to {} and {a=a1}, this will progress these
 * monitors' states and the new states will be stored for the binding {a=a1,b=b1}.
 *
 * Indexing is tricky to get both correct and efficient. Therefore there can be multiple different indexing strategies.
 * However, they all should be equivalent with respect to their externally visible behavior.
 *
 * @param <A>
 *            the type of the auxiliary data usable by base monitors
 */
public interface IndexingStrategy<A> {

    /**
     * Update the internal state of all related monitors by sending the parameter event to the respective monitors.
     *
     * @param symbol
     *            The symbol of the event.
     * @param binding
     *            The variable binding at this event.
     */
    void processEvent(Event<A> event);

}

Add interface for indexing strategies

Add interface for indexing strategies


/*
 * LensKit, an open source recommender systems toolkit.
 * Copyright 2010-2014 LensKit Contributors.  See CONTRIBUTORS.md.
 * Work on LensKit has been funded by the National Science Foundation under
 * grants IIS 05-34939, 08-08692, 08-12148, and 10-17697.
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as
 * published by the Free Software Foundation; either version 2.1 of the
 * License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
 * details.
 *
 * You should have received a copy of the GNU General Public License along with
 * this program; if not, write to the Free Software Foundation, Inc., 51
 * Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
 */
package org.lenskit.eval.crossfold;

import org.junit.Test;
import org.lenskit.data.events.Event;
import org.lenskit.data.ratings.Rating;

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

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

public class SortOrderTest {
    @Test
    public void testRandom() {
        List<Event> events = new ArrayList<>();
        events.add(Rating.create(42, 1, 3.5, 100));
        events.add(Rating.create(42, 2, 4.0, 105));
        events.add(Rating.create(42, 3, 2.5, 98));

        List<Event> copy = new ArrayList<>(events);

        SortOrder.RANDOM.apply(copy, new Random());

        assertThat(copy, hasSize(3));
        for (Event e: events) {
            assertThat(copy, hasItem(e));
        }
    }

    @Test
    public void testTimestamp() {
        List<Rating> events = new ArrayList<>();
        events.add(Rating.create(42, 1, 3.5, 100));
        events.add(Rating.create(42, 2, 4.0, 105));
        events.add(Rating.create(42, 3, 2.5, 98));

        List<Rating> copy = new ArrayList<>(events);

        SortOrder.TIMESTAMP.apply(copy, new Random());

        assertThat(copy, hasSize(3));
        assertThat(copy, contains(Rating.create(42, 3, 2.5, 98),
                                  Rating.create(42, 1, 3.5, 100),
                                  Rating.create(42, 2, 4.0, 105)));
    }
}

Add tests for crossfold sort order

Add tests for crossfold sort order

This adds unit tests for the crossfolder's SortOrder code.


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

package com.google.sps.servlets;

import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;
import com.google.gson.JsonObject;
import com.google.gson.Gson;
import java.util.ArrayList;
import java.io.IOException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/userapi")
public class UserApiServlet extends HttpServlet {

    @Override
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException{

        JsonObject loginInfo = new JsonObject();
        UserService userService = UserServiceFactory.getUserService();

        // Store whether user is logged in.
        Boolean isLoggedIn = userService.isUserLoggedIn();
        String url,
            email;

        // If user is logged in send logout is index.html, else home.html is login
        if(isLoggedIn) {
            url = userService.createLogoutURL("../index.html");
            email = userService.getCurrentUser().getEmail();
        }
        else {
            url =userService.createLoginURL("../Home/home.html");
            email = "";
        }

        // Store info in Json object.
        loginInfo.addProperty("Url", url);
        loginInfo.addProperty("Bool", isLoggedIn);
        loginInfo.addProperty("Email", email);

        // Send info back as response.
        response.setContentType("application/json;");
        response.getWriter().println(loginInfo.toString());
    }
}

Add servlet for retrieving userdata when loggging in


/**
 * 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.camel.itest.karaf;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.ops4j.pax.exam.junit.PaxExam;

@RunWith(PaxExam.class)
public class CamelAwsEc2Test extends BaseKarafTest {

    public static final String COMPONENT = extractName(CamelAwsEc2Test.class);

    @Test
    public void test() throws Exception {
    	testComponent(COMPONENT);
    }

}

Camel-AWS: Create single Karaf feature tests for single components, Aws-ec2 test


package to.etc.puzzler;

import java.lang.annotation.*;

/**
 * This annotation sets options for the Puzzler's JUnit test runner for those tests
 * that are in trouble when running parallel.
 *
 * @author Frits Jalvingh
 * Created on Apr 16, 2014
 */
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface TestConfig {
	/**
	 * Define one or more group names that this test class belongs to. These group names
	 * @return
	 */
	String[] groups() default {};

	/**
	 * Define a set of test class names and/or "parallel" group names that this test cannot run
	 * in parallel with. For test class names the mechanism is simple: this test will not run
	 * in parallel with that other test class. Alternatively you add just names here which are
	 * "group" names of tests that should not run together, like "database". For such a name, if
	 * any other test is running also with that "name" this test will wait.
	 * @return
	 */
	String[] notParallelWith() default {};

	/**
	 * When T this test class runs strictly standalone, with not a single other JUnit test in
	 * parallel.
	 * @return
	 */
	boolean serial() default false;

	/**
	 * Can be used to set test IDs.
	 * @return
	 */
	String id() default "";
}

Add a Puzzler-specific annotation to control/manipulate test execution when running inside the Puzzler.


package ru.ifmo.jmh;

import ru.ifmo.DominanceTree;
import ru.ifmo.NonDominatedSortingFactory;

@SuppressWarnings("unused")
public class JMH_DominanceTree_NoDelayedInsertion extends AbstractBenchmark {
    @Override
    protected NonDominatedSortingFactory getFactory() {
        return DominanceTree.getNoDelayedInsertion();
    }
}

Add benchmark entity to DominanceTree/NoDelayedInsertion.


package org.slc.sli.api.resources.config;

import java.io.IOException;
import java.io.OutputStream;
import java.io.Writer;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;
import java.io.OutputStreamWriter;
import javax.ws.rs.Produces;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.ext.MessageBodyWriter;
import javax.ws.rs.ext.Provider;

import com.fasterxml.jackson.xml.XmlMapper;

import org.codehaus.jackson.map.SerializationConfig;
import org.springframework.stereotype.Component;

/**
 * Custom JAXB Context Resolver that will generate XML
 *
 * */
@SuppressWarnings("rawtypes")
@Provider
@Component
@Produces(MediaType.APPLICATION_XML)
public class JacksonXMLMsgBodyWriter implements MessageBodyWriter {

    @Override
    public boolean isWriteable(Class type, Type genericType, Annotation[] annotations, MediaType mediaType) {
        return true;
    }

    @Override
    public long getSize(Object t, Class type, Type genericType, Annotation[] annotations, MediaType mediaType) {
        return -1;
    }

    @Override
    public void writeTo(Object t, Class type, Type genericType, Annotation[] annotations, MediaType mediaType,
                        MultivaluedMap httpHeaders, OutputStream entityStream) throws IOException, WebApplicationException {
        XmlMapper xmlMapper = new XmlMapper();
        xmlMapper.configure(SerializationConfig.Feature.WRITE_DATES_AS_TIMESTAMPS, false);
        xmlMapper.configure(SerializationConfig.Feature.FAIL_ON_EMPTY_BEANS, false);
        xmlMapper.writeValue(entityStream, t);
    }

}

Implement Jackson XML message body writer


package com.cossacklabs.themis.test;

import java.util.Random;

import com.cossacklabs.themis.SecureCompare;
import com.cossacklabs.themis.SecureCompareException;

import android.test.AndroidTestCase;

public class SecureCompareTest extends AndroidTestCase {

	static final int MAX_TEST_DATA = 1024;
	Random rand = new Random();

	private byte[] generateTestData() {
		int dataLength = 0;

		do {
			dataLength = rand.nextInt(MAX_TEST_DATA);
		} while (0 == dataLength);

		byte[] data = new byte[dataLength];
		rand.nextBytes(data);

		return data;
	}

	private void performCompare(boolean shouldMatch) throws SecureCompareException {

		byte[] compareData = generateTestData();
		SecureCompare.CompareResult expectedResult;

		if (shouldMatch) {
			expectedResult = SecureCompare.CompareResult.MATCH;
		} else {
			expectedResult = SecureCompare.CompareResult.NO_MATCH;
		}

		SecureCompare alice = new SecureCompare(compareData);

		if (!shouldMatch) {
			compareData[0]++;
		}

		SecureCompare bob = new SecureCompare(compareData);

		// Initiating secure compare (alice, step1)
		byte[] peerData = alice.begin();

		assertNotNull(peerData);
		assertTrue(SecureCompare.CompareResult.NOT_READY == alice.getResult());
		assertTrue(SecureCompare.CompareResult.NOT_READY == bob.getResult());

		// alice --> peerData --> bob

		// Accepting secure compare (bob, step2)
		peerData = bob.proceed(peerData);
		assertNotNull(peerData);
		assertTrue(SecureCompare.CompareResult.NOT_READY == alice.getResult());
		assertTrue(SecureCompare.CompareResult.NOT_READY == bob.getResult());

		// bob --> peerData --> alice

		// ALice, step3
		peerData = alice.proceed(peerData);
		assertNotNull(peerData);
		assertTrue(SecureCompare.CompareResult.NOT_READY == alice.getResult());
		assertTrue(SecureCompare.CompareResult.NOT_READY == bob.getResult());

		// alice --> peerData --> bob

		// Bob, step4, should be ready after
		peerData = bob.proceed(peerData);
		assertNotNull(peerData);
		assertTrue(SecureCompare.CompareResult.NOT_READY == alice.getResult());
		assertTrue(expectedResult == bob.getResult());

		// bob --> peerData --> alice

		// Alice, step5, should be ready after
		peerData = alice.proceed(peerData);
		assertNull(peerData);
		assertTrue(expectedResult == alice.getResult());
		assertTrue(expectedResult == bob.getResult());
	}

	@Override
	public void runTest() {

		try {

			performCompare(true);
			performCompare(false);

		} catch (Exception e) {
			String failMessage = e.getClass().getCanonicalName();

			if (null != e.getMessage()) {
				failMessage += ": " + e.getMessage();
			}

			fail(failMessage);
		}

	}
}

Add Android secure compare tests

Add Android secure compare tests


package lucene.hurricanc.com.wjlucene_android;

/**
 * Created by Hurricanc on 11/4/15.
 */

import android.app.ActionBar;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

public class ResultActivity extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.result_main);

        Button backButton = (Button) findViewById(R.id.backButton);
        backButton.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                onBackPressed();
            }
        });

        Intent intent = getIntent();
        String value = intent.getExtras().getString("key");

        JSONObject obj = null;
        try {
            obj = new JSONObject(value);
            JSONArray newsArray = new JSONArray();
            newsArray = obj.getJSONArray("News");

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

                JSONObject News = newsArray.getJSONObject(i);
                String title = News.getString("Title");
                String number = News.getString("Number");
                String URL = News.getString("URL");

                Log.v("WOOJNUM", number);

                this.setFirstBlock(number, URL);
            }

        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    private void setFirstBlock(String number, final String url) {
        TableLayout tableView = (TableLayout) findViewById(R.id.tableLayout1);
        Button btn = new Button(this);
        btn.setText("NEWS NUMBER: " + number);
        btn.setBackgroundColor(0xE6FAFF);
        btn.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
                startActivity(browserIntent);
            }
        });
        //TableLayout.LayoutParams lp = new TableLayout.LayoutParams(tableView.getLayoutParams());
        tableView.addView(btn);
    }

    private View tableChild(String number, final String URL) {

        TableRow tr = new TableRow(this);
        View v = LayoutInflater.from(this).inflate(R.layout.custom_tablerow, tr, true);
        TextView tv = (TextView) v.findViewById(R.id.title);
        tv.setText("NEWS NUMBER: " + number);
        Button btn = (Button) v.findViewById(R.id.openURL);
        btn.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(URL));
                startActivity(browserIntent);
            }
        });
        return v;
    }

}

Handle JSON Result Object in TableLayout


/**
 * Copyright 2011 OpenEngSB Division, Vienna University of Technology
 *
 * 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.openengsb.opencit.core.projectmanager.model;

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

import java.util.Map;

import org.junit.Before;
import org.junit.Test;
import org.openengsb.core.common.Domain;
import org.openengsb.domain.notification.NotificationDomain;
import org.openengsb.domain.report.ReportDomain;
import org.openengsb.domain.scm.ScmDomain;

public class ProjectModelTest {

    private Project p;

    @Before
    public void setUp() {
        p = new Project();
    }

    @Test
    public void addService_shouldWork() {
        p.addService(ScmDomain.class, "Scm1234");
        p.addService(ReportDomain.class, "Report9876");

        Map<Class<? extends Domain>, String> services = p.getServices();
        assertEquals(2, services.size());
        assertTrue(services.containsKey(ScmDomain.class));
        assertEquals(services.get(ScmDomain.class), "Scm1234");
        assertTrue(services.containsKey(ReportDomain.class));
        assertEquals(services.get(ReportDomain.class), "Report9876");
        assertFalse(services.containsKey(NotificationDomain.class));
    }

    @Test
    public void getServices_shouldWork() {
        Map<Class<? extends Domain>, String> services = p.getServices();
        assertEquals(0, services.size());
    }

    @Test
    public void addService_overwrite_shouldWork() {
        p.addService(ScmDomain.class, "Scm1234");
        p.addService(ScmDomain.class, "Scm0000");
        Map<Class<? extends Domain>, String> services = p.getServices();
        assertEquals(1, services.size());
        assertTrue(services.containsKey(ScmDomain.class));
        assertEquals(services.get(ScmDomain.class), "Scm0000");
    }
}

Add a test for Project::addService and Project::getServices


/*
 * Key point:
 *      1.common solution: insert a copy after each
 *        original node(ignore random pointer now), then copy random pointer,
 *        finally, split the original list and copied list
 *
 *      2.HashMap Solution: use a HashMap<RandomListNode,RandomListNode> to
 *        construct a key value pair between original node and new copied node,
 *        then, copy the next and random pointer accordingly
 */

/**
 * Definition for singly-linked list with a random pointer.
 * class RandomListNode {
 *     int label;
 *     RandomListNode next, random;
 *     RandomListNode(int x) { this.label = x; }
 * };
 */
public class Solution {
    public RandomListNode copyRandomList(RandomListNode head) {
        if(head == null)
            return head;

        //insert a copy after each original node (ignore random pointer now)
        RandomListNode current = head;
        while(current != null){
            RandomListNode copy = new RandomListNode(current.label);
            copy.next = current.next;
            current.next = copy;
            current = current.next.next;
        }

        //copy random pointer
        current = head;
        while(current != null){

            if(current.random != null) //take care, random pointer may be null
                current.next.random = current.random.next;
            else
                current.next.random = null;

            current = current.next.next;
        }

        //split original list and copy list
        current = head;
        RandomListNode newHead = current.next;
        RandomListNode newCurrent = newHead;
        while(newCurrent != null){
            current.next = newCurrent.next;

            if(newCurrent.next != null)
                newCurrent.next = newCurrent.next.next;

            current = current.next;
            newCurrent = newCurrent.next;
        }

        return newHead;
    }
}

/*
 * HashMap Solution
 */

/**
 * Definition for singly-linked list with a random pointer.
 * class RandomListNode {
 *     int label;
 *     RandomListNode next, random;
 *     RandomListNode(int x) { this.label = x; }
 * };
 */
public class Solution {
    public RandomListNode copyRandomList(RandomListNode head) {
        if(head == null)
            return head;

        HashMap<RandomListNode, RandomListNode> hm = new HashMap<RandomListNode, RandomListNode>();
        RandomListNode current = head;
        while(current != null){
            hm.put(current, new RandomListNode(current.label));
            current = current.next;
        }

        current = head;
        while(current != null){
            hm.get(current).next = hm.get(current.next);
            hm.get(current).random = hm.get(current.random);
            current = current.next;
        }

        return hm.get(head);
    }
}

Copy List with Random Pointer

Copy List with Random Pointer


package org.eclipse.cmf.occi.core.gen.alloy.services;

import java.util.Date;

import org.eclipse.cmf.occi.core.Attribute;
import org.eclipse.cmf.occi.core.Category;
import org.eclipse.cmf.occi.core.DataType;
import org.eclipse.cmf.occi.core.Extension;
import org.eclipse.cmf.occi.core.Kind;

public class GenUtils
{
	/**
	 * Get the current date.
	 * @return the current date.
	 */
	public String getNow() {
		return new Date().toString();
	}

	/**
	 * Get the file path of an extension.
	 * @param extension the given extension.
	 * @return the file path of the given extension.
	 */
	public String getFilePath(Extension extension) {
		return extension.eResource().getURI().toString();
	}

	/**
	 *
	 * @param category
	 * @param context
	 * @return
	 */
	public String getScope(Category category, Category context)
	{
		StringBuffer sb = new StringBuffer();
		if((Extension)category.eContainer() != (Extension)context.eContainer()) {
			sb.append(((Extension)category.eContainer()).getName()).append('/');
		}
		return sb.toString();
	}

	/**
	 *
	 * @param kind
	 * @return
	 */
	public String getScope4KindParent(Kind kind)
	{
		return getScope(kind.getParent(), kind);
	}

	/**
	 *
	 * @param attribute
	 * @param suffix
	 * @return
	 */
	public String getSigAttributeType(Attribute attribute, String suffix)
	{
		StringBuffer sb = new StringBuffer();
		DataType type = attribute.getType();
		Extension typeExtension = (Extension)type.eContainer();
		Extension attributeExtension = (Extension)attribute.eResource().getContents().get(0);
		if(typeExtension != attributeExtension) {
			if(! (suffix == null && type.getName().equals("String"))) {
				sb.append(typeExtension.getName()).append('/');
			}
		}
		sb.append(type.getName());
		if(suffix != null) {
			sb.append(suffix);
		}
		return sb.toString();
	}
}

Add genUtils for the Alloy Generator.

Add genUtils for the Alloy Generator.


package fuzion24.device.vulnerability.vulnerabilities.framework.graphics;

import android.content.Context;

import fuzion24.device.vulnerability.vulnerabilities.VulnerabilityTest;

/**
 * Created by fuzion24 on 9/15/15.
 */
public class GraphicBufferTest implements VulnerabilityTest {
    static {
        System.loadLibrary("graphicsbufferoverflow");
    }

    @Override
    public String getName() {
        return "CVE-2015-1528/GraphicsBuffer Unflatten";
    }

    private native int checkGraphicsBuffer();

    @Override
    public boolean isVulnerable(Context context) throws Exception {
        int checkVal = checkGraphicsBuffer();

        //TODO: If we declare a different type of socket do we still need internet permission?
        if(checkVal == 0) {
            return false;
        }else if(checkVal == 1) {
            return true;
        }else {
            //TODO: grab more information about failure, errno and error string
            throw new Exception("Error running test");
        }
    }
}

Add java class to run checker

Add java class to run checker


package com.bitmonlab.osiris.api.map.swagger;

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

import io.github.robwin.markup.builder.MarkupLanguage;
import io.github.robwin.swagger2markup.Swagger2MarkupConverter;

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

import static org.junit.Assert.assertTrue;

@RunWith(MockitoJUnitRunner.class)
public class Swagger2MarkupTest {

    @Test
    @Ignore public void convertRemoteSwaggerToAsciiDoc() throws IOException {
        // Remote Swagger source
        // Default is AsciiDoc
        Swagger2MarkupConverter.from("http://localhost:4024/api-docs").build().intoFolder("src/docs/asciidoc/generated");

        // Then validate that three AsciiDoc files have been created
        String[] files = new File("src/docs/asciidoc/generated").list();

        assertTrue(Arrays.asList(files).contains("definitions.adoc"));
        assertTrue(Arrays.asList(files).contains("overview.adoc"));
        assertTrue(Arrays.asList(files).contains("paths.adoc"));

    }

    @Test
    @Ignore public void convertRemoteSwaggerToMarkdown() throws IOException {
        // Remote Swagger source
        // Markdown
        Swagger2MarkupConverter.from("http://localhost:4024/api-docs").withMarkupLanguage(MarkupLanguage.MARKDOWN).build().intoFolder("src/docs/markdown/generated");

        // Then validate that three Markdown files have been created
        String[] files = new File("src/docs/markdown/generated").list();

        assertTrue(Arrays.asList(files).contains("definitions.md"));
        assertTrue(Arrays.asList(files).contains("overview.md"));
        assertTrue(Arrays.asList(files).contains("paths.md"));

    }
}

Test to create static documentation

Test to create static documentation


package com.lintcode;

/**
 * @author : Joshua
 * Date:     1/25/16
 * @see A + B 问题
 */
public class APlusB {
    public int aplusb(int a, int b) {
        // write your code here, try to do it without arithmetic operators.
        int carry = a & b;
        int result = a ^ b;

        while (carry != 0) {
            int tmpCarry = carry << 1;
            carry = result & tmpCarry;
            result = result ^ tmpCarry;
        }

        return result;
    }
}

Add a + b problem solution

Add a + b problem solution


/*
 * ExperimentalControllerTest.java
 *
 * Copyright (C) 2018 [ A Legge Up ]
 *
 * This software may be modified and distributed under the terms
 * of the MIT license.  See the LICENSE file for details.
 */

package com.aleggeup.confagrid.controller;

import static org.junit.Assert.assertNotNull;

import java.io.UnsupportedEncodingException;

import javax.xml.transform.TransformerException;

import org.apache.batik.svggen.SVGGraphics2DIOException;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.junit.MockitoJUnitRunner;

import com.aleggeup.confagrid.service.WordGridGenerationService;

@RunWith(MockitoJUnitRunner.class)
public class ExperimentalControllerTest {

    @Mock
    private WordGridGenerationService mockWordGridGenerationService;

    private ExperimentalController experimentalController;

    @Before
    public void setUp() {
        experimentalController = new ExperimentalController(mockWordGridGenerationService);
    }

    @After
    public void tearDown() {
        Mockito.verifyNoMoreInteractions(mockWordGridGenerationService);
    }

    @Test
    public void test() throws SVGGraphics2DIOException, UnsupportedEncodingException, TransformerException {
        Mockito.when(mockWordGridGenerationService.svgTest()).thenReturn("");
        assertNotNull(experimentalController.svgTest());
        Mockito.verify(mockWordGridGenerationService).svgTest();
    }
}

:white_check_mark: Add simple test for ExperimentalController for coverage


package org.ow2.chameleon.fuchsia.upnp.examples.config;

import org.apache.felix.ipojo.configuration.Configuration;
import org.apache.felix.ipojo.configuration.Instance;
import org.ow2.chameleon.fuchsia.core.FuchsiaConstants;

import static org.apache.felix.ipojo.configuration.Instance.instance;
import static org.ow2.chameleon.fuchsia.core.ImportationLinker.FILTER_IMPORTERSERVICE_PROPERTY;

@Configuration
public class DiscoveryInitializer {

    Instance upnpDiscovery = instance()
            .of("Fuchsia-UPnPDiscovery-Factory")
            .named("Fuchsia-UPnPDiscovery")
            .with(FILTER_IMPORTERSERVICE_PROPERTY).setto("(instance.name=FuchsiaUPnPImporter)")
            .with("target").setto("(id=*)");

}

[example] Add an instance of upnp-discovery in upnp-config bundle


package ch.hevs.aislab.magpie.broker.model;

/**
 * Object sent by the publisher to notify
 * the decision for a subscription request
 */
public class SubscriptionResult {

	private long subscriberId;
	private boolean decision;

	public SubscriptionResult() {

	}

	public SubscriptionResult(long subscriberId, boolean decision) {
		this.subscriberId = subscriberId;
		this.decision = decision;
	}

	public long getSubscriberId() {
		return subscriberId;
	}

	public void setSubscriberId(long subscriberId) {
		this.subscriberId = subscriberId;
	}

	public boolean isDecision() {
		return decision;
	}

	public void setDecision(boolean decision) {
		this.decision = decision;
	}

}

Add new data model class

Add new data model class


package com.opcoach.training.e4.codesamples;

import org.eclipse.e4.core.contexts.ContextInjectionFactory;
import org.eclipse.e4.core.contexts.IEclipseContext;
import org.eclipse.e4.core.di.annotations.Execute;
import org.eclipse.jface.wizard.Wizard;
import org.eclipse.jface.wizard.WizardDialog;
import org.eclipse.swt.widgets.Shell;

public class OpenSampleWizard
{
	@Execute
	public void execute(IEclipseContext ctx, Shell s)
	{
		Wizard w = ContextInjectionFactory.make(SampleWizard.class, ctx);
		WizardDialog wd = new WizardDialog(s, w);
		wd.open();
	}
}

Add the open wizard sample

Add the open wizard sample


package net.devrieze.chatterbox.client;

import net.devrieze.chatterbox.client.StatusEvent.StatusLevel;

import com.google.gwt.event.shared.EventHandler;
import com.google.gwt.event.shared.GwtEvent;

public class StatusEvent extends GwtEvent<StatusEvent.Handler> {

  public enum StatusLevel {
    WARNING,
    INFO,
    DEBUG;
  }

  public interface Handler extends EventHandler{
    public void onStatusUpdate(StatusEvent e);
  }

  public static final Type<Handler> TYPE = new Type<StatusEvent.Handler>();
  private final StatusLevel statusLevel;
  private final String message;
  private final Throwable exception;

  public StatusEvent(StatusLevel statusLevel, String message) {
    this(statusLevel, message, null);
  }

  public StatusEvent(StatusLevel statusLevel, String message, Throwable exception) {
    this.statusLevel = statusLevel;
    this.message = message;
    this.exception = exception;
  }

  @Override
  public com.google.gwt.event.shared.GwtEvent.Type<Handler> getAssociatedType() {
    return TYPE;
  }

  @Override
  protected void dispatch(Handler handler) {
    handler.onStatusUpdate(this);
  }

  public StatusLevel getStatusLevel() {
    return statusLevel;
  }

  public String getMessage() {
    return message;
  }

  public Throwable getException() {
    return exception;
  }

}

Create an event type for status updates.


/*
 * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
 * or more contributor license agreements. Licensed under the Elastic License;
 * you may not use this file except in compliance with the Elastic License.
 */

package org.elasticsearch.xpack.security.cli;

import org.elasticsearch.test.ESTestCase;

public class TestSuiteCannotBeEmptyTests extends ESTestCase {

    public void testIsHereSoThisSuiteIsNonEmpty() {
        // This is needed on a FIPS JVM as the rest of the suite is skipped
    }
}

Add empty test case for FIPS

[TEST] Add empty test case for FIPS

All other tests in security:cli are skipped on FIPS JVMs


package org.skyscreamer.yoga.demo.test.controller;

import org.skyscreamer.yoga.metadata.MetaDataService;
import org.skyscreamer.yoga.metadata.TypeMetaData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;

@Controller
@RequestMapping("/metadata")
public class MetaDataController
{
   @Autowired
   MetaDataService metaDataService;

   @RequestMapping("/{type}")
   public TypeMetaData getTypeMetaData(@PathVariable("type") String type,
         HttpServletRequest request)
   {
      String uri = request.getRequestURI();
      String parts[] = uri.split( "\\." );
      return metaDataService.getMetaData( type, parts[parts.length - 1] );
   }

}

Enable metadata for Spring MVC.

Enable metadata for Spring MVC.


/*
 * Copyright 2012-2014 Institut National des Sciences Appliquees de Lyon (INSA-Lyon)
 *
 * 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 fr.insalyon.citi.golo.compiler.parser;

public class ASTNamedAugmentationDeclaration extends GoloASTNode implements NamedNode {

  private String name;

  public ASTNamedAugmentationDeclaration(int id) {
    super(id);
  }

  public ASTNamedAugmentationDeclaration(GoloParser p, int id) {
    super(p, id);
  }

  @Override
  public String getName() {
    return name;
  }

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

  @Override
  public Object jjtAccept(GoloParserVisitor visitor, Object data) {
    return visitor.visit(this, data);
  }

  @Override
  public String toString() {
    return "ASTNamedAugmentationDeclaration{" +
        "name='" + name + '\'' +
        '}';
  }
}

Add AST node for NamedAugmentationDeclaration

ooops... should have done this earlier...


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

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

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

import javax.inject.Inject;

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

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

    @Inject
    private FeaturesService featuresService;

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

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

}

Add itest to prove fixes

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

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

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


package com.google.ase;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;

public class UsageTrackingConfirmation {
  private UsageTrackingConfirmation() {
    // Utility class.
  }

  public static void show(Activity activity) {
    final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(activity);
    if (prefs.getBoolean("present_usagetracking", true)) {
      final AlertDialog.Builder builder = new AlertDialog.Builder(activity);
      builder.setTitle("Usage Tracking");
      builder.setCancelable(true);
      builder.setPositiveButton("Accept", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int which) {
          prefs.edit().putBoolean("present_usagetracking", false).commit();
          prefs.edit().putBoolean("usagetracking", true).commit();
        }
      });
      builder.setNegativeButton("Refuse", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int which) {
          prefs.edit().putBoolean("present_usagetracking", false).commit();
          prefs.edit().putBoolean("usagetracking", false).commit();
        }
      });
      builder.setOnCancelListener(new DialogInterface.OnCancelListener() {
        public void onCancel(DialogInterface dialog) {
          prefs.edit().putBoolean("present_usagetracking", true).commit();
          prefs.edit().putBoolean("usagetracking", false).commit();
        }
      });
      builder.setMessage("Allow collection of anonymous usage information?\n\nThis can be "
          + "changed later under preferences.");
      builder.create().show();
    }
  }
}

Add usage tracking confirmation class that was missing from the last commit.


/*
 * Copyright 2012-2020 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
 *
 *      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 org.springframework.boot.autoconfigure.kafka;

import org.junit.jupiter.api.Test;

import org.springframework.boot.autoconfigure.kafka.KafkaProperties.IsolationLevel;
import org.springframework.boot.testsupport.classpath.ClassPathOverrides;
import org.springframework.test.util.ReflectionTestUtils;

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

/**
 * Tests for {@link KafkaProperties} with Kafka 2.4.
 *
 * @author Stephane Nicoll
 */
@ClassPathOverrides("org.apache.kafka:kafka-clients:2.4.1")
class KafkaPropertiesKafka24Tests {

	@Test
	void isolationLevelEnumConsistentWithKafkaVersion() throws ClassNotFoundException {
		Class<?> isolationLevelClass = Class.forName("org.apache.kafka.common.requests.IsolationLevel");
		Object[] original = ReflectionTestUtils.invokeMethod(isolationLevelClass, "values");
		assertThat(original).extracting("name").containsExactly(IsolationLevel.READ_UNCOMMITTED.name(),
				IsolationLevel.READ_COMMITTED.name());
		assertThat(original).extracting("id").containsExactly(IsolationLevel.READ_UNCOMMITTED.id(),
				IsolationLevel.READ_COMMITTED.id());
		assertThat(original).hasSize(IsolationLevel.values().length);
	}

}

Add IsolationLevel regression test with Kafka 2.4

This commit makes sure that our copy of the IsolationLevel enum is
consistent with what Kafka 2.4 provides

Closes gh-20822


package seedu.tasklist.commons.events.storage;

import seedu.tasklist.commons.events.BaseEvent;

//@@author A0141993X
/**
 * Indicates a changed in the file storage location
 */
public class TaskListFilePathChangedEvent extends BaseEvent {

    public String filePath;

    public TaskListFilePathChangedEvent(String filePath) {
        this.filePath = filePath;
    }

    @Override
    public String toString() {
        return "File is saved at: " + filePath;
    }

}

Add file path changed event

Add file path changed event


package net.kencochrane.raven.getsentry;

import net.kencochrane.raven.RavenFactory;
import org.hamcrest.Matchers;
import org.testng.annotations.Test;

import java.util.ServiceLoader;

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.instanceOf;

public class GetSentryRavenFactoryTest {
    @Test
    public void checkServiceLoaderProvidesFactory() {
        ServiceLoader<RavenFactory> ravenFactories = ServiceLoader.load(RavenFactory.class);

        assertThat(ravenFactories, Matchers.<RavenFactory>hasItem(instanceOf(GetSentryRavenFactory.class)));
    }
}

Add test to ensure getSentry provided by ServiceLoader


/*******************************************************************************
 * Copyright (c) 2014 Codenvy, S.A.
 * 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:
 *   Codenvy, S.A. - initial API and implementation
 *******************************************************************************/
package com.codenvy.ide.editor.orion.client.jso;

import com.google.gwt.core.client.JavaScriptObject;

/** Overlay on the orion JS Annotation model objects. */
public class OrionAnnotationModelOverlay extends JavaScriptObject {

    /** JSO mandated protected constructor. */
    protected OrionAnnotationModelOverlay() {
    }

    /**
     * Adds an annotation to the annotation model.
     *
     * @param annotation the annotation to add
     */
    public final native void addAnnotation(OrionAnnotationOverlay annotation) /*-{
        this.addAnnotation(annotation);
    }-*/;

    /**
     * Removes an annotation from the annotation model.
     *
     * @param annotation the annotation to remove
     */
    public final native void removeAnnotation(OrionAnnotationOverlay annotation) /*-{
        this.removeAnnotation(annotation);
    }-*/;

    /**
     * Removes all annotations of the given type.
     *
     * @param annotationType the type of annotations to remove
     */
    public final native void removeAnnotations(String annotationType) /*-{
        this.removeAnnotations(annotationType);
    }-*/;

    /**
     * Removes all annotations.
     */
    public final native void removeAnnotations() /*-{
        this.removeAnnotations();
    }-*/;

    /**
     * Notifies the annotation model that the given annotation has been modified.
     *
     * @param annotation the modified annotation
     */
    public final native void modifyAnnotation(OrionAnnotationOverlay annotation) /*-{
        this.modifyAnnotation(annotation);
    }-*/;

    /**
     * Removes and adds the specifed annotations to the annotation model.
     *
     * @param removedAnnotation the annotation that is removed
     * @param addedAnnotation the annotation that is added
     */
    public final native void replaceAnnotation(OrionAnnotationOverlay removedAnnotation, OrionAnnotationOverlay addedAnnotation) /*-{
        this.replaceAnnotation(removedAnnotation, addedAnnotation);
    }-*/;

    /**
     * Returns an iterator of annotations for the given range of text.
     *
     * @return annotations iterator
     */
    public final native OrionAnnotationIteratorOverlay getAnnotations(int startOffset, int endOffset) /*-{
        this.getAnnotations(startOffset, endOffset);
    }-*/;

    /**
     * Returns an iterator of all annotations.
     *
     * @return annotations iterator
     */
    public final native OrionAnnotationIteratorOverlay getAnnotations() /*-{
        this.getAnnotations();
    }-*/;
}

Add an annotation model overlay

Add an annotation model overlay


package com.thoughtworks.selenium;

import org.openqa.selenium.server.RemoteControlConfiguration;
import org.openqa.selenium.server.SeleniumServer;
import org.testng.annotations.AfterSuite;
import org.testng.annotations.BeforeSuite;
import org.testng.annotations.Optional;
import org.testng.annotations.Parameters;

public class TestSeleniumServerLauncher {
    SeleniumServer server;
    @BeforeSuite
    @Parameters({"selenium.host", "selenium.port"})
    public void startServer(@Optional("localhost") String host, @Optional("4444") String port) throws Exception {
        if (!"localhost".equals(host)) return;
        RemoteControlConfiguration config = new RemoteControlConfiguration();
        config.setPort(Integer.parseInt(port));
        server = new SeleniumServer(config);
        server.start();
    }

    @AfterSuite(alwaysRun=true)
    public void stopServer() {
        if (server == null) return;
        server.stop();
    }
}

Add a launcher that TestNG can run (or exclude, if necessary)

r5646


/*
 * 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.teradata.prestomanager.common;

import org.glassfish.jersey.client.JerseyClient;

import javax.ws.rs.client.Entity;
import javax.ws.rs.client.Invocation;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.MediaType;

import java.net.URI;

import static java.util.Objects.requireNonNull;
import static org.glassfish.jersey.client.JerseyClientBuilder.createClient;

public class RequestBuilder
{
    private final URI path;
    private Entity body;
    private String headerName;
    private Object headerValue;
    private static JerseyClient jerseyClient = createClient();

    private RequestBuilder(URI path) {
        this.path = path;
    }

    public static RequestBuilder newRequestBuilder(URI path)
    {
        return new RequestBuilder(path);
    }

    public RequestBuilder withBody(Entity body)
    {
        this.body = body;
        return this;
    }

    public RequestBuilder withHeader(String headerName, Object headerValue)
    {
        this.headerName = headerName;
        this.headerValue = headerValue;
        return this;
    }

    public Invocation buildGet()
    {
        return build().buildGet();
    }

    public Invocation buildPut()
    {
        requireNonNull(body, "body is null");

        return build().buildPut(body);
    }

    public Invocation buildPost()
    {
        requireNonNull(body, "body is null");

        return build().buildPost(body);
    }

    public Invocation buildDelete()
    {
        return build().buildDelete();
    }

    private Invocation.Builder build()
    {
        WebTarget webTarget = jerseyClient.target(path);
        Invocation.Builder invocationBuilder = webTarget.request(MediaType.TEXT_PLAIN);
        if (headerValue != null && headerName != null) {
            invocationBuilder.header(headerName, headerValue);
        }
        return invocationBuilder;
    }
}

Add builder for http request

Add builder for http request


package se.christianjensen.maintenance.sigar;

import org.hyperic.sigar.Sigar;
import org.hyperic.sigar.SigarException;
import org.junit.Before;
import org.junit.Test;
import se.christianjensen.maintenance.representation.processes.*;
import se.christianjensen.maintenance.representation.processes.Process;

import java.util.List;

import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.*;
import static org.mockito.Matchers.anyLong;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

public class ProcessMetricsTest {

    private Sigar sigar;
    private ProcessMetrics processMetrics;
    private Process process1;

    @Before
    public void setUp() throws Exception {
        sigar = mock(Sigar.class);
        processMetrics = new ProcessMetrics(sigar);
        process1 = new Process(123L, new String[0], new ProcessExecutable(), new ProcessCreator(), new ProcessCpu(), new ProcessMemory());

    }

    @Test
    public void getProcessListHappyPath() throws Exception {
        setupProcessMock();
        List<se.christianjensen.maintenance.representation.processes.Process> processes = processMetrics.getProcesses();
        assertThat(processes.get(0).getPid(), is(123L));
    }

    private void setupProcessMock() throws SigarException {
        long[] pidArray = {process1.getPid()};
        when(sigar.getProcList()).thenReturn(pidArray);
        when(sigar.getProcArgs(anyLong())).thenReturn(new String[0]);
        when(sigar.getProcExe(anyLong())).thenThrow(new SigarException());
        when(sigar.getProcCredName(anyLong())).thenThrow(new SigarException());
        when(sigar.getProcCpu(anyLong())).thenThrow(new SigarException());
        when(sigar.getProcMem(anyLong())).thenThrow(new SigarException());
    }
}

Create simple test for ProcessMetrics

Create simple test for ProcessMetrics


package tools.vitruv.framework.util;

import java.util.Map;

import org.eclipse.emf.ecore.resource.Resource;
import org.eclipse.emf.ecore.resource.ResourceSet;
import org.eclipse.emf.ecore.xmi.impl.XMIResourceFactoryImpl;

public class ResourceSetUtil {
	public static void addExistingFactoriesToResourceSet(ResourceSet resourceSet) {
        Map<String, Object> globalExtensionToFactoryMap = Resource.Factory.Registry.INSTANCE.getExtensionToFactoryMap();
        for (String extension : globalExtensionToFactoryMap.keySet()) {
            resourceSet.getResourceFactoryRegistry().getExtensionToFactoryMap().put(extension,
                    globalExtensionToFactoryMap.get(extension));
        }
        if (resourceSet.getResourceFactoryRegistry().getExtensionToFactoryMap().isEmpty()) {
        	resourceSet.getResourceFactoryRegistry().getExtensionToFactoryMap().put("*", new XMIResourceFactoryImpl());
        }
	}
}

Add utilities class for resource sets

Add utilities class for resource sets


package Sorting;

import java.util.Arrays;

/**
 * Created by matao on 8/14/16.
 */
public class InsertionSort extends BaseSort {

    @Override
    public void sort(Comparable[] a) {
        for (int i = 0; i < a.length; i++) {
            for (int j = i; j > 0 && lessThan(a[j], a[j - 1]); j--) {
                exchange(a, j, j-1);
            }
        }
    }

    public static void main(String[] args) {
        InsertionSort insertionSort = new InsertionSort();

        Integer[] a = {2, 1, 5, 7, 0, 10};
        insertionSort.sort(a);
        System.out.println(Arrays.toString(a));

        Integer[] b = {1, 1, 0, 3, -1};
        insertionSort.sort(b);
        System.out.println(Arrays.toString(b));
    }
}

Add insertion sort and test case

[ADD] Add insertion sort and test case


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

import org.apache.tika.language.translate.MicrosoftTranslator;

public class TranslatingExample {
    public static void main(String[] args) {
        String textToTranslate = "This is some text that will be used for an example.";
        MicrosoftTranslator translator = new MicrosoftTranslator();
        // Change the id and secret! See http://msdn.microsoft.com/en-us/library/hh454950.aspx.
        translator.setId("dummy-id");
        translator.setSecret("dummy-secret");
        if (translator.isAvailable()) {
            try {
                String translatedText = translator.translate(textToTranslate, "en", "fr");
                System.out.println("Original: " + textToTranslate);
                System.out.println("Translated: " + translatedText);
            } catch (Exception e) {
                System.err.println("Error while translating.");
            }
        }
        else {
            throw new AssertionError("You must set the ID and secret for the MicrosoftTranslator.");
        }
    }
}

Add in a translating example.

Add in a translating example.


package org.genericsystem.cv.application;

import org.genericsystem.cv.AbstractApp;
import org.genericsystem.cv.Img;
import org.genericsystem.cv.utils.NativeLibraryLoader;
import org.opencv.core.Scalar;
import org.opencv.imgcodecs.Imgcodecs;

import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.GridPane;

public class MeshgridRadonTest extends AbstractApp {

	public static void main(String[] args) {
		launch(args);
	}

	static {
		NativeLibraryLoader.load();
	}
	private Img image = new Img(Imgcodecs.imread("1_in.png"), false);
	private int cols = 3;
	private int rows = 2;

	@Override
	protected void fillGrid(GridPane mainGrid) {
		Image[] images = new Image[6];
		images[0] = image.toJfxImage();

		MeshGridRadon meshGrid = new MeshGridRadon(20, 40, 40, image.getSrc());
		meshGrid.build(-5000, -45, 45);
		try (Img vertDirs = new Img(meshGrid.drawVerticalDirs(new Scalar(255, 0, 255)), false);
				Img baseLines = new Img(meshGrid.drawBaselines(new Scalar(255, 0, 0)), false);
				Img grid = new Img(meshGrid.drawOnCopy(new Scalar(0, 0, 255)), false);
				Img surface = new Img(meshGrid.draw3Dsurface(new Scalar(0, 255, 0), new Scalar(0, 0, 255)), false);
				Img dewarped = new Img(meshGrid.dewarp(), false))  {
			images[1] = baseLines.toJfxImage();
			images[2] = vertDirs.toJfxImage();
			images[3] = grid.toJfxImage();
			images[4] = surface.toJfxImage();
			images[5] = dewarped.toJfxImage();
			for (int col = 0; col < cols; col++)
				for (int row = 0; row < rows; row++) {
					int i = row * cols + col;
					if (i < images.length) {
						ImageView imageView = new ImageView(images[i]);
						mainGrid.add(imageView, col, row);
						imageView.setPreserveRatio(true);
						imageView.setFitWidth(image.width());
						imageView.setFitHeight(image.height());
					}
				}
		}
	}
}

Add test program for MeshgridRadon

gs-cv: Add test program for MeshgridRadon


package com.cloudycrew.cloudycar.utils;

import com.cloudycrew.cloudycar.models.requests.AcceptedRequest;
import com.cloudycrew.cloudycar.models.requests.CompletedRequest;
import com.cloudycrew.cloudycar.models.requests.ConfirmedRequest;
import com.cloudycrew.cloudycar.models.requests.PendingRequest;
import com.cloudycrew.cloudycar.models.requests.Request;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonDeserializer;

/**
 * Created by George on 2016-10-25.
 */

public class RequestUtils {
    private static JsonDeserializer<Request> getRequestDeserializer() {
        return new SubclassDeserializer.Builder<Request>()
                .setTypeFieldName("requestType")
                .registerRequestType(PendingRequest.TYPE_NAME, PendingRequest.class)
                .registerRequestType(AcceptedRequest.TYPE_NAME, AcceptedRequest.class)
                .registerRequestType(ConfirmedRequest.TYPE_NAME, ConfirmedRequest.class)
                .registerRequestType(CompletedRequest.TYPE_NAME, CompletedRequest.class)
                .build();
    }

    public static Gson getGson() {
        return new GsonBuilder().registerTypeAdapter(Request.class, getRequestDeserializer()).create();
    }
}

Add request utils for getting a gson instance that can handle deserializing requests


package nom.bdezonia.zorbage.type.data.float64.complex;

import static org.junit.Assert.assertTrue;

import org.junit.Test;

import nom.bdezonia.zorbage.algorithm.MatrixMaximumAbsoluteColumnSumNorm;
import nom.bdezonia.zorbage.algorithm.MatrixMaximumAbsoluteRowSumNorm;
import nom.bdezonia.zorbage.groups.G;
import nom.bdezonia.zorbage.type.data.float64.real.Float64Member;

public class TestNorms {

	@Test
	public void test1() {
		Float64Member norm = new Float64Member();
		ComplexFloat64MatrixMember matrix = new ComplexFloat64MatrixMember();
		MatrixMaximumAbsoluteColumnSumNorm.compute(G.CDBL, matrix, norm);
		assertTrue(true);
	}

	@Test
	public void test2() {
		Float64Member norm = new Float64Member();
		ComplexFloat64MatrixMember matrix = new ComplexFloat64MatrixMember();
		MatrixMaximumAbsoluteRowSumNorm.compute(G.CDBL, matrix, norm);
		assertTrue(true);
	}
}

Define a fake test that makes sure api code can compile correctly


package com.InfinityRaider.AgriCraft.renderers.items;

import net.minecraft.client.renderer.RenderBlocks;
import net.minecraft.client.renderer.Tessellator;
import net.minecraft.entity.item.EntityItem;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;

public class RenderItemMagnifyingGlass extends RenderItemBase {
    protected RenderItemMagnifyingGlass(Item item) {
        super(item);
    }

    @Override
    protected void renderItemEntity(ItemStack stack, Tessellator tessellator, RenderBlocks renderBlocks, EntityItem entityItem) {

    }

    @Override
    protected void renderItemEquipped(ItemStack stack, Tessellator tessellator, RenderBlocks renderBlocks, EntityPlayer player) {

    }

    @Override
    protected void renderItemEquippedFirstPerson(ItemStack stack, Tessellator tessellator, RenderBlocks renderBlocks, EntityPlayer player) {

    }

    @Override
    protected void renderItemInventory(ItemStack stack, Tessellator tessellator, RenderBlocks renderBlocks) {

    }

    @Override
    protected void renderItemMap(ItemStack stack, Tessellator tessellator) {

    }
}

Create render class for magnifying glass


package org.ethereum.jsontestsuite;

import org.ethereum.core.BlockHeader;
import org.json.simple.parser.ParseException;
import org.junit.FixMethodOrder;
import org.junit.Test;
import org.junit.runners.MethodSorters;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;

import static org.junit.Assert.*;

/**
 * @author Mikhail Kalinin
 * @since 02.09.2015
 */
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class GitHubBasicTest {

    private static final Logger logger = LoggerFactory.getLogger("TCK-Test");

    @Test
    public void runDifficultyTest() throws IOException, ParseException {

        String shacommit = "b814f9fb484889bda407f2b9349983f211b77753";
        String json = JSONReader.loadJSONFromCommit("BasicTests/difficulty.json", shacommit);

        DifficultyTestSuite testSuite = new DifficultyTestSuite(json);

        for (DifficultyTestCase testCase : testSuite.getTestCases()) {

            logger.info("Running {}\n", testCase.getName());

            BlockHeader current = testCase.getCurrent();
            BlockHeader parent = testCase.getParent();

            assertEquals(testCase.getExpectedDifficulty(), current.calcDifficulty(parent));
        }
    }
}

package org.ethereum.jsontestsuite;

import org.ethereum.config.SystemProperties;
import org.ethereum.core.BlockHeader;
import org.json.simple.parser.ParseException;
import org.junit.Before;
import org.junit.FixMethodOrder;
import org.junit.Test;
import org.junit.runners.MethodSorters;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;

import static org.junit.Assert.*;
import static org.ethereum.config.SystemProperties.CONFIG;

/**
 * @author Mikhail Kalinin
 * @since 02.09.2015
 */
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class GitHubBasicTest {

    private static final Logger logger = LoggerFactory.getLogger("TCK-Test");

    @Before
    public void setup() {

        // if not set explicitly
        // this test fails being run by Gradle
        CONFIG.setGenesisInfo("frontier.json");
    }

    @Test
    public void runDifficultyTest() throws IOException, ParseException {

        String shacommit = "b814f9fb484889bda407f2b9349983f211b77753";
        String json = JSONReader.loadJSONFromCommit("BasicTests/difficulty.json", shacommit);

        DifficultyTestSuite testSuite = new DifficultyTestSuite(json);

        for (DifficultyTestCase testCase : testSuite.getTestCases()) {

            logger.info("Running {}\n", testCase.getName());

            BlockHeader current = testCase.getCurrent();
            BlockHeader parent = testCase.getParent();

            assertEquals(testCase.getExpectedDifficulty(), current.calcDifficulty(parent));
        }
    }
}

Fix difficulty test to run correctly via Gradle


/*
 * Bach - Java Shell Builder
 * Copyright (C) 2020 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 de.sormuras.bach;

/** Unchecked exception thrown when a module is not mapped. */
public /*static*/ class UnmappedModuleException extends RuntimeException {
  private static final long serialVersionUID = 0L;

  public UnmappedModuleException(String module) {
    super("Module " + module + " is not mapped");
  }
}

Introduce exception for unmapped modules


/*
 * Copyright (c) 2009 Kathryn Huxtable and Kenneth Orr.
 *
 * This file is part of the SeaGlass Pluggable Look and Feel.
 *
 * 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.
 *
 * $Id$
 */
package com.seaglass.state;

import java.awt.Component;

import javax.swing.JComponent;
import javax.swing.JFrame;

/**
 */
public class TitlePaneCloseButtonWindowModifiedState extends State {
    public TitlePaneCloseButtonWindowModifiedState() {
        super("WindowModified");
    }

    private static final String WINDOW_DOCUMENT_MODIFIED = "Window.documentModified";

    protected boolean isInState(JComponent c) {
        Component parent = c;
        while (parent.getParent() != null) {
            if (parent instanceof JFrame) {
                break;
            }
            parent = parent.getParent();
        }
        if (parent instanceof JFrame) {
            return ((JFrame) parent).getRootPane().getClientProperty(WINDOW_DOCUMENT_MODIFIED) == Boolean.TRUE;
        }
        return false;
    }
}

Test for "window modifed" state.

Test for "window modifed" state.


/*
 * Copyright (C) 2015 Atanas Gegov
 *
 * 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.atanasg.fileprocessingapp;

import com.atanasg.fileprocessingapp.mvc.controller.FileProcessingAppController;
import com.atanasg.fileprocessingapp.mvc.controller.FileProcessingAppControllerImpl;
import com.atanasg.fileprocessingapp.mvc.model.FileContentModel;
import com.atanasg.fileprocessingapp.mvc.model.FileContentModelImpl;
import com.atanasg.fileprocessingapp.mvc.view.FileProcessingAppCommandLineUI;
import com.atanasg.fileprocessingapp.mvc.view.FileProcessingAppView;
import com.atanasg.fileprocessingapp.rules.RuleFileFormat;

/**
 * The launcher class of the File Processing Application.
 * Initializes and connects the relevant components (Model,
 * View and Controller) and asks for the first user input.
 *
 * @author Atanas Gegov
 */
public class FileProcessingAppLauncher {

	private static final String USER_FILE_PROMPT_MESSAGE = "Please provide a path to some %s file";

	public static void main(String[] args) {
		// create MVC components
		FileContentModel fileContentModel = new FileContentModelImpl();
		FileProcessingAppView appUI = new FileProcessingAppCommandLineUI();
		FileProcessingAppController appController = new FileProcessingAppControllerImpl();

		// connect MVC components
		appUI.setController(appController);
		appController.setModel(fileContentModel);
		appController.setView(appUI);

		// Ask the user for a file
		appUI.askUserForCommand(String.format(USER_FILE_PROMPT_MESSAGE,
				RuleFileFormat.getValidFileFormatAsString()));
	}
}

Add application Launcher with a main method

It constructs and connects the MVC components and
ask the user for providing a file.


package us.codecraft.webmagic.utils;

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

public class NumberUtilsTest {

	@Test
	public void testCompareLong() {
		Assert.assertEquals(0, NumberUtils.compareLong(0L, 0L));
		Assert.assertEquals(1, NumberUtils.compareLong(9L, 0L));
		Assert.assertEquals(-1, NumberUtils.compareLong(0L, 9L));
		Assert.assertEquals(-1, NumberUtils.compareLong(-9L, 0L));
		Assert.assertEquals(1, NumberUtils.compareLong(0L, -9L));
	}
}

Add unit tests for us.codecraft.webmagic.utils.NumberUtils

These tests were written using Diffblue Cover.


/*
 * Copyright 2012 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.broadleafcommerce.core.web.interceptor;

import org.springframework.web.servlet.mvc.WebContentInterceptor;
import org.springframework.web.servlet.resource.ResourceHttpRequestHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * This class is used to control the cache seconds for all things that are not resources. The default Spring
 * WebContentInterceptor will apply the cacheSeconds and associated variables to everything that goes through Spring
 * MVC. We really only want to apply that to Controllers, not our static resources.
 *
 * This interceptor facilitates that functionality.
 *
 * @author Andre Azzolini (apazzolini)
 */
public class NonResourceWebContentInterceptor extends WebContentInterceptor {

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws ServletException {

		if (ResourceHttpRequestHandler.class.isAssignableFrom(handler.getClass())) {
		    return true;
		} else {
			return super.preHandle(request, response, handler);
		}
	}

}

[BLC-631] Add a content interceptor that will respect a cache control
policy


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

package org.jeeventstore.core.notifier;

import org.jeeventstore.core.ChangeSet;

/**
 * Default implementation for a commit notification.
 *
 * @author Alexander Langer
 */
class DefaultCommitNotification implements EventStoreCommitNotification {

    private ChangeSet changes;

    public DefaultCommitNotification(ChangeSet changes) {
        this.changes = changes;
    }

    @Override
    public ChangeSet changes() {
        return this.changes;
    }

}

Add default implementation for commit notifications.


package com.udacity.gradle.testing;

import android.test.AndroidTestCase;

import com.udacity.gradle.testing.paid.PaidEcho;

import java.util.Collection;

public class PaidEchoAndroidTest extends AndroidTestCase {
    public void testVerifyEchoResponse() {
        assertEquals("hello", Echo.echo("hello"));
    }

    public void testVerifyLoggingEchoResponse() {
        Collection<String> strings = PaidEcho.echo("hello", 10, true);
        assertEquals(strings.size(), 10);
        for (String string : strings) {
            assertEquals(string, "hello");
        }

        assertEquals("hello", Echo.echo("hello", true));
    }
}

Add paid android test to 4.09

Add paid android test to 4.09


package com.orientechnologies.orient.distributed.impl.coordinator.network;

import com.orientechnologies.orient.distributed.impl.coordinator.ONodeResponse;
import com.orientechnologies.orient.distributed.impl.coordinator.ddl.ODDLQueryOperationResponse;
import com.orientechnologies.orient.distributed.impl.log.OLogId;
import org.junit.Assert;
import org.junit.Test;

import java.io.*;

public class ONetworkAckTest {

  @Test
  public void testSerialize() throws IOException {
    OLogId oplogId = new OLogId(10, 20, 19);
    ONetworkAck ack = new ONetworkAck(oplogId);

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    DataOutputStream out = new DataOutputStream(baos);
    ack.write(out);
    byte[] serialized = baos.toByteArray();
    out.close();
    baos.close();
    ByteArrayInputStream bais = new ByteArrayInputStream(serialized);
    DataInputStream in = new DataInputStream(bais);

    ONetworkAck ack2 = new ONetworkAck();
    ack2.read(in);
    in.close();
    bais.close();

    Assert.assertEquals(ack.getCommand(), ack2.getCommand());
    Assert.assertEquals(ack.getLogId(), ack2.getLogId());
  }
}

Add serialization tests for ONetworkAck

Add serialization tests for ONetworkAck