package com.semperos.screwdriver.js;

import java.util.HashMap;

/**
 * @todo Steps needed:
 *   * Create generic {@link org.mozilla.javascript.ScriptableObject} class to handle
 *     properties used for RequireJS optimizer's config (see hardcoded-build.js).
 *   * For each needed build (determined by user-provided list of main JS modules to target),
 *     create unique instance of that object and set it's data accordingly (i.e., change values
 *     based on the config needs for each main JS module)
 *   * Add those objects to an array, say of __Screwdriver.rjsMainModules, which can then
 *     be iterated through in the evaluated JavaScript and passed to requirejs.optimize
 */
public class RequireJsConfigCompiler extends RhinoCompiler {
    private RhinoCompiler rhinoCompiler;

    public RequireJsConfigCompiler() {
        rhinoCompiler = new RhinoCompiler();
        HashMap<String,String> deps = new HashMap<String,String>();
        deps.put("r.js", "com/semperos/screwdriver/js/vendor/r-2.1.4.js");
        rhinoCompiler.addDependencies(deps);
    }

}

Add initial code for r.js via Rhino, include comments for next steps


package de.otto.jlineup.report;

import de.otto.jlineup.file.FileService;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.Mockito;

import static java.util.Collections.singletonList;
import static org.mockito.MockitoAnnotations.initMocks;

public class JSONReportWriterV2Test {

    private JSONReportWriter_V2 testee;

    @Mock
    private FileService fileServiceMock;

    @Before
    public void setup() {
        initMocks(this);
        testee = new JSONReportWriter_V2(fileServiceMock);
    }

    @Test
    public void shouldWriteComparisonReportAsJson() throws Exception {

        ScreenshotComparisonResult screenshotComparisonResult =
                new ScreenshotComparisonResult("url", 1337, 1338, 0d, "before", "after", "differenceSum");
        Report report = new Report(new Summary(false, 0d, 0d), singletonList(screenshotComparisonResult));

        String expectedString = "{\n" +
                "  \"summary\": {\n" +
                "    \"error\": false,\n" +
                "    \"differenceSum\": 0.0,\n" +
                "    \"differenceMax\": 0.0\n" +
                "  },\n" +
                "  \"screenshotComparisons\": [\n" +
                "    {\n" +
                "      \"url\": \"url\",\n" +
                "      \"width\": 1337,\n" +
                "      \"verticalScrollPosition\": 1338,\n" +
                "      \"difference\": 0.0,\n" +
                "      \"screenshotBeforeFileName\": \"before\",\n" +
                "      \"screenshotAfterFileName\": \"after\",\n" +
                "      \"differenceImageFileName\": \"differenceSum\"\n" +
                "    }\n" +
                "  ]\n" +
                "}";

        testee.writeComparisonReportAsJson(report);

        Mockito.verify(fileServiceMock).writeJsonReport(expectedString);
    }
}

Test for report format v2

Test for report format v2


/*
 * This file is part of whereisthat-android
 *
 * Unless otherwise stated in a separate LICENSE file for this project
 * or agreed via contract, all rights reserved by the author.
 */

package com.michael_kuck.android.mkcommons;

public class Version {

    final public static int MAJOR = 1;
    final public static int MINOR = 0;
    final public static int PATCH = 0;

}

Add class for tracking library version

Add class for tracking library version


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

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

import org.junit.Test;
import org.onosproject.vtnrsc.PhysicalNetwork;

import com.google.common.testing.EqualsTester;

/**
 * Unit tests for PhysicalNetwork class.
 */
public class PhysicalNetworkTest {

    final PhysicalNetwork physicalNetwork1 = PhysicalNetwork.physicalNetwork("1");
    final PhysicalNetwork sameAsPhysicalNetwork1 = PhysicalNetwork.physicalNetwork("1");
    final PhysicalNetwork physicalNetwork2 = PhysicalNetwork.physicalNetwork("2");

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

    /**
     * Checks the operation of equals() methods.
     */
    @Test
    public void testEquals() {
        new EqualsTester().addEqualityGroup(physicalNetwork1, sameAsPhysicalNetwork1)
                .addEqualityGroup(physicalNetwork2).testEquals();
    }

    /**
     * Checks the construction of a PhysicalNetwork object.
     */
    @Test
    public void testConstruction() {
        final String physicalNetworkValue = "s";
        final PhysicalNetwork physicalNetwork = PhysicalNetwork
                .physicalNetwork(physicalNetworkValue);
        assertThat(physicalNetwork, is(notNullValue()));
        assertThat(physicalNetwork.physicalNetwork(), is(physicalNetworkValue));
    }
}

[ONOS-3231] Add the junit test code of PhysicalNetwork

Change-Id: I14a88859593739cbe7cb7ed480cdcad63437d915


package ru.ifmo.nds;

import java.util.Arrays;
import java.util.Locale;
import java.util.Scanner;

public class RunGivenTest {
    public static void main(String[] args) {
        Locale.setDefault(Locale.US);
        try (Scanner in = new Scanner(System.in)) {
            int n = in.nextInt();
            int d = in.nextInt();
            double[][] data = new double[n][d];
            for (int i = 0; i < n; ++i) {
                for (int j = 0; j < d; ++j) {
                    data[i][j] = in.nextDouble();
                }
            }
            int[] ranks = new int[n];
            int[] referenceRanks = new int[n];
            boolean set = false;
            String referenceAlgo = null;
            for (String s : IdCollection.getAllNonDominatedSortingIDs()) {
                Arrays.fill(ranks, -1);
                NonDominatedSorting sorting = IdCollection.getNonDominatedSortingFactory(s).getInstance(n, d);
                sorting.sort(data, ranks);
                if (set) {
                    if (!Arrays.equals(referenceRanks, ranks)) {
                        System.out.println("Ranks different for " + s + " and " + referenceAlgo);
                    }
                } else {
                    set = true;
                    referenceAlgo = s;
                    System.arraycopy(ranks, 0, referenceRanks, 0, n);
                }
                System.out.println(s + " seems to be OK, rank[0] = " + ranks[0]);
            }
        }
    }
}

Add a main class that runs a test given from the console on all algos.


package ru.stqa.selenium.example;

import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.pagefactory.ByAll;

public class correctProduct extends TestBase {
    @Test
    public void correctProduct() {
        driver.get("http://localhost/litecart/en/");

        WebElement campaignsBlock = driver.findElement(By.id("box-campaigns"));
        String nameOfProduct1 = campaignsBlock.findElement(By.className("name")).getText();

        WebElement prices = campaignsBlock.findElement(By.className("price-wrapper"));
        String regularPrice1 = prices.findElement(By.className("regular-price")).getText();
        String campaignPrice1 = prices.findElement(By.className("campaign-price")).getText();

        campaignsBlock.findElement(By.className("link")).click();

        campaignsBlock = driver.findElement(By.id("box-product"));
        String nameOfProduct2 = campaignsBlock.findElement(By.className("title")).getText();

        prices = campaignsBlock.findElement(By.className("price-wrapper"));
        String regularPrice2 = prices.findElement(By.className("regular-price")).getText();
        String campaignPrice2 = prices.findElement(By.className("campaign-price")).getText();

        System.out.println(nameOfProduct1 + " = " + nameOfProduct2);
        System.out.println(regularPrice1 + " = " + regularPrice2);
        System.out.println(campaignPrice1 + " = " + campaignPrice2);
    }
}

Create file for the task №10. Done the task №10 (a,b)


package com.ezardlabs.dethsquare.multiplayer;

import java.nio.ByteBuffer;

public class NetworkAnimator extends NetworkBehaviour {

	@Override
	protected ByteBuffer onSend() {
		data.putInt(0, gameObject.animator.getCurrentAnimationId()); // 0 - 3
		data.putInt(4, gameObject.animator.getCurrentAnimationFrame()); // 4 - 7
		return data;
	}

	@Override
	protected void onReceive(ByteBuffer data, int index) {
		gameObject.animator.setCurrentAnimationId(data.getInt(index));
		gameObject.animator.setCurrentAnimationFrame(data.getInt(index + 4));
	}

	@Override
	public int getSize() {
		return 8;
	}
}

Add component for automatically synchronising an Animator component between multiplayer clients


/*
 *  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.tomcat.util.http;

import org.junit.Test;

public class TestFastHttpDateFormatPerformance {

    @Test
    public void testGetCurrentDateConcurrent() throws InterruptedException {
        int threadCount = 8;
        int callCount = 100000000;
        Thread[] threads = new Thread[threadCount];

        for (int i = 0; i < threadCount; i++) {
            threads[i] = new GetCurrentDateThread(callCount);
        }

        long startTime = System.nanoTime();

        for (int i = 0; i < threadCount; i++) {
            threads[i].start();
        }

        for (int i = 0; i < threadCount; i++) {
            threads[i].join();
        }

        long endTime = System.nanoTime();

        System.out.println("Duration: " + (endTime - startTime));
    }

    private static class GetCurrentDateThread extends Thread {

        private final int callCount;

        public GetCurrentDateThread(int callCount) {
            this.callCount = callCount;
        }

        @Override
        public void run() {
            for (int i = 0; i < callCount; i++) {
                FastHttpDateFormat.getCurrentDate();
            }
        }
    }
}

Add a test to use to check for performance changes during refactoring of data formatting.

git-svn-id: 79cef5a5a257cc9dbe40a45ac190115b4780e2d0@1834044 13f79535-47bb-0310-9956-ffa450edef68


package org.hollowcraft.model;
/*
 * HollowCraft License
 *  Copyright (c) 2010 Caleb Champlin.
 *  All rights reserved
 *  This license must be include in all copied, cloned and derived works
 */

/**
 * A class which holds block id constants.
 * @author Caleb Champlin
 */
public class BlockActions {
	private BlockActions() { }
	public static final int DESTROY = 0;
	public static final int BUILD = 1;
}

Add a constants class for block actions (atm only two: destory and build)


/*
 * Licensed to the University of California, Berkeley 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 tachyon.master.block;

import org.powermock.reflect.Whitebox;

import tachyon.collections.IndexedSet;
import tachyon.master.block.meta.MasterWorkerInfo;

/**
 * Class which provides access to private state of {@link BlockMaster}.
 */
public final class BlockMasterPrivateAccess {
  public static boolean isWorkerRegistered(BlockMaster master, long workerId) {
    IndexedSet<MasterWorkerInfo> workers = Whitebox.getInternalState(master, "mWorkers");
    IndexedSet.FieldIndex<MasterWorkerInfo> idIndex = Whitebox.getInternalState(master, "mIdIndex");
    if (workers == null || idIndex == null) {
      return false;
    }
    synchronized (workers) {
      MasterWorkerInfo workerInfo = workers.getFirstByField(idIndex, workerId);
      return workerInfo != null && workerInfo.isRegistered();
    }
  }
}

Add private access for BlockMaster

Add private access for BlockMaster


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

package com.google.gerrit.acceptance.rest.group;

import static com.google.gerrit.acceptance.rest.group.GroupAssert.assertGroupInfo;

import com.google.common.reflect.TypeToken;
import com.google.gerrit.acceptance.AbstractDaemonTest;
import com.google.gerrit.acceptance.AccountCreator;
import com.google.gerrit.acceptance.RestResponse;
import com.google.gerrit.acceptance.RestSession;
import com.google.gerrit.acceptance.TestAccount;
import com.google.gerrit.reviewdb.client.AccountGroup;
import com.google.gerrit.server.account.GroupCache;
import com.google.gson.Gson;
import com.google.inject.Inject;

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

import java.io.IOException;

public class GetGroupIT extends AbstractDaemonTest {

  @Inject
  private AccountCreator accounts;

  @Inject
  private GroupCache groupCache;

  private TestAccount admin;
  private RestSession session;

  @Before
  public void setUp() throws Exception {
    admin = accounts.create("admin", "admin@example.com", "Administrator",
            "Administrators");
    session = new RestSession(admin);
  }

  @Test
  public void testGetGroup() throws IOException {
    AccountGroup adminGroup = groupCache.get(new AccountGroup.NameKey("Administrators"));

    // by UUID
    testGetGroup("/groups/" + adminGroup.getGroupUUID().get(), adminGroup);

    // by name
    testGetGroup("/groups/" + adminGroup.getName(), adminGroup);

    // by legacy numeric ID
    testGetGroup("/groups/" + adminGroup.getId().get(), adminGroup);
  }

  private void testGetGroup(String url, AccountGroup expectedGroup) throws IOException {
    RestResponse r = session.get(url);
    @SuppressWarnings("serial")
    GroupInfo group = (new Gson()).fromJson(r.getReader(), new TypeToken<GroupInfo>() {}.getType());
    assertGroupInfo(expectedGroup, group);
  }
}

Add acceptance test to retrieve group via REST

Change-Id: Ib48016b695bd7707821fc4e1da2e5a1a97923f06
Signed-off-by: Edwin Kempin <b444e279ad95fdef4fbdd82c813b624595df204a@sap.com>


package de.philipphager.disclosure.database;

import com.squareup.sqlbrite.BriteDatabase;
import com.squareup.sqlbrite.SqlBrite;
import javax.inject.Inject;
import rx.schedulers.Schedulers;

public class DatabaseManager {
  private final DatabaseOpenHelper openHelper;
  private final SqlBrite sqlBrite;
  private BriteDatabase database;

  @Inject public DatabaseManager(DatabaseOpenHelper openHelper, SqlBrite sqlBrite) {
    this.openHelper = openHelper;
    this.sqlBrite = sqlBrite;
  }

  public synchronized BriteDatabase open() {
    ensureDatabase();
    return database;
  }

  public synchronized void close() {
    if (database != null) {
      database.close();
      database = null;
    }
  }

  private void ensureDatabase() {
    if (database == null) {
      database = sqlBrite.wrapDatabaseHelper(openHelper, Schedulers.io());
      ;
    }
  }
}

Add a database manager to manage database instances.


//
// BackReferenceTest.java
//

/*
OME Bio-Formats package for reading and converting biological file formats.
Copyright (C) 2005-@year@ UW-Madison LOCI and Glencoe Software, Inc.

This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 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., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
*/

package loci.formats.utests.xml;

import static org.testng.AssertJUnit.assertEquals;
import static org.testng.AssertJUnit.assertNotNull;

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

import loci.common.services.DependencyException;
import loci.common.services.ServiceException;
import loci.common.services.ServiceFactory;
import loci.formats.ome.OMEXMLMetadata;
import loci.formats.services.OMEXMLService;

import ome.xml.model.OME;
import ome.xml.model.Plate;
import ome.xml.model.Well;

import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;

/**
 *

Source code:

 *
Trac,
 * Gitweb

 *
 * @author Melissa Linkert melissa at glencoesoftware.com
 */
public class BackReferenceTest {

  private OMEXMLService service;
  private OMEXMLMetadata metadata;

  @BeforeMethod
  public void setUp() throws DependencyException, ServiceException, IOException
  {
    ServiceFactory sf = new ServiceFactory();
    service = sf.getInstance(OMEXMLService.class);
    metadata = service.createOMEXMLMetadata();
  }

  @Test
  public void testPlateWellReferences() {
    metadata.setPlateID("Plate:0", 0);
    metadata.setWellID("Well:0:0", 0, 0);

    OME root = (OME) metadata.getRoot();

    Plate plate = root.getPlate(0);
    Well well = plate.getWell(0);

    assertNotNull(plate);
    assertNotNull(well);
    assertEquals(plate, well.getPlate());
  }

}

Add one back reference test

Add one back reference test

More to come later.


package org.slc.sli.modeling.rest;

import static org.junit.Assert.*;

import java.util.ArrayList;

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

/**
 * JUnit test for Request class.
 *
 * @author wscott
 *
 */
public class RequestTest {

    private Request request;

    private static final ArrayList<Documentation> DOC = new ArrayList<Documentation>(0);
    private static final ArrayList<Param> PARAMS = new ArrayList<Param>(0);
    private static final ArrayList<Representation> REPRESENTATIONS = new ArrayList<Representation>(0);

    @Before
    public void setup() throws Exception {
        request = new Request(DOC, PARAMS, REPRESENTATIONS);
    }

    @Test
    public void testNullParams() {
        new Request(DOC, null, REPRESENTATIONS);
    }

    @Test
    public void testNullRepresentations() {
        new Request(DOC, PARAMS, null);
    }

    @Test
    public void testGetParams() {
        assertEquals(PARAMS, request.getParams());
    }

    @Test
    public void testGetRepresentations() {
        assertEquals(REPRESENTATIONS, request.getRepresentations());
    }

    @Test
    public void testToString() {
        assertTrue(!"".equals(request.toString()));
    }
}

Add JUnit test for Request class in rest modeling module.


/*
 * 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.jmeter.report.processor;

import junit.framework.TestCase;

import org.apache.jmeter.report.core.Sample;
import org.apache.jmeter.report.core.SampleMetadata;
import org.junit.Test;

public class FieldSampleComparatorTest extends TestCase {

    private SampleMetadata sampleMetadata;
    private FieldSampleComparator comparator;

    @Override
    protected void setUp() throws Exception {
        super.setUp();
        sampleMetadata = new SampleMetadata(',', "test");
        comparator = new FieldSampleComparator("test");
        comparator.initialize(sampleMetadata);
    }

    @Test
    public void testCompare() {
        Sample s1 = new Sample(0, sampleMetadata, "1");
        Sample s2 = new Sample(1, sampleMetadata, "2");
        assertTrue(comparator.compare(s1, s2) < 0);
        assertTrue(comparator.compare(s2, s1) > 0);
        assertTrue(comparator.compare(s2, s2) == 0);
        assertTrue(comparator.compare(s1, s1) == 0);
    }

}

Use simple test case for FieldSampleComparator.

git-svn-id: 5ccfe34f605a6c2f9041ff2965ab60012c62539a@1719686 13f79535-47bb-0310-9956-ffa450edef68


package edu.iastate.cs.design.spec.export;

import boa.types.Spec;

import java.util.List;

public class JmlToBoa {

    public static List<Spec.Specification> JmlToBoaProtobuf(String jml) {
        // TODO
        return null;
    }

}

Add skeleton class for exporting Boa specs


/**
 * Twist in the Tale 4.3 from the OCA Java SE 7 book by Mala Gupta (Manning Publications)
 * Created by Josef on 1/3/14.
 */
public class TwistInTheTale4_3 {
    public static void main(String[] args) {
        String multiStrArr[][] = new String[][] {
                {"A", "B"},
                null,
                {"Jan", "Feb", null}
        };

        System.out.println(multiStrArr[2][2]);
//        System.out.println(multiStrArr[1][1]);

        for (int i = 0; i < multiStrArr.length; i++) {
            if (multiStrArr[i] == null) { System.out.println("length:null\tnull"); continue; }

            System.out.print("length:" + multiStrArr[i].length + "\t");
            for (int j = 0; j < multiStrArr[i].length; j++) {
                System.out.print(multiStrArr[i][j] + " ");
            }
            System.out.println();
        }
    }
}

Add code for Twist In The Tale 4.3

Add code for Twist In The Tale 4.3


/*
 * Copyright 2016 Philip Cohn-Cort
 *
 * 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.fuzz.indicator.text;

import android.support.annotation.NonNull;

/**
 * These are designed to be translated (in a 2-dimensional plane) above
 * their associated {@link android.text.Spannable Spannables}.
 *
 * @author Philip Cohn-Cort (Fuzz)
 */
public interface MigratorySpan {

    /**
     * Consider a Spannable sequence has a lower bound at 0% of its length
     * and upper bound at 100% of that length. The MigratoryRange returned
     * by this method represents some portion of indices within that sequence.
     *

     *     Sample caller code may be as follows:
     *

     *         MigratorySpan ms;
     *         //...
     *         Range<Float> bounds = ms.getCoverage();
     *         String percentLower = String.format("%0.2f", bounds.getLower()/100);
     *         String percentUpper = String.format("%0.2f", bounds.getUpper()/100);
     *

     *

     *
     * @return a range which can be used to figure out what
     * percentages of the Spannable is covered.
     */
    @NonNull
    MigratoryRange<Float> getCoverage();

    /**
     * Whatever is returned here should be a valid argument into
     * {@link android.text.Spannable#setSpan(Object, int, int, int)}'s
     * {@code flags} argument. Feel free to return the parameter directly
     * if they don't need to change.
     *
     * @return a combination of valid span-laying-out flags
     * @param previousFlags    flags used for the previous layout - will
     *                         be 0 if not currently attached to a
     *                         {@link android.text.Spannable Spannable}
     */
    int preferredFlags(int previousFlags);
}

Create dedicated interface for Migratory spans

(it's got an imaginative name)


package arithlang;

public interface Value {
	public String toString();
	static class NumVal implements Value {
		private double _val;
	    public NumVal(double v) { _val = v; }
	    public double v() { return _val; }
	    public String toString() {
	    	int tmp = (int) _val;
	    	if(tmp == _val) return "" + tmp;
	    	return "" + _val;
	    }
	}
}

Set of values for Arithlang

Set of values for Arithlang


package com.googlecode.gentyref;

import java.lang.reflect.Method;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

import junit.framework.TestCase;

/**
 * Sample in the form of a JUnit test, to show gentyref solves the problem on
 * http://stackoverflow.com/questions/182872/
 *
 * @author Wouter Coekaerts <wouter@coekaerts.be>
 */
public class StackoverflowQ182872Test extends TestCase {
	private static Type LIST_OF_STRING = new TypeToken<List<String>>(){}.getType();

	public static class StringList extends ArrayList<String> {}

	public List<String> method1() {return null;}
	public ArrayList<String> method2() {return null;}
	public StringList method3() {return null;}
	interface Parameterized<T extends StringList> {
		T method4();
	}
	interface Parameterized2<T> {
		T method5();
	}
	interface Parameterized2ListString extends Parameterized2<List<String>> {
	}

	public boolean returnTypeExtendsListOfString(Class<?> clazz, String methodName) throws NoSuchMethodException {
		Method method = clazz.getMethod(methodName);
		Type returnType = GenericTypeReflector.getExactReturnType(method, clazz); // needed for method5, else the return type is just "T"
		return GenericTypeReflector.isSuperType(LIST_OF_STRING, returnType);
	}

	public void testIt() throws NoSuchMethodException {
		assertTrue(returnTypeExtendsListOfString(StackoverflowQ182872Test.class, "method1"));
		assertTrue(returnTypeExtendsListOfString(StackoverflowQ182872Test.class, "method2"));
		assertTrue(returnTypeExtendsListOfString(StackoverflowQ182872Test.class, "method3"));
		assertTrue(returnTypeExtendsListOfString(Parameterized.class, "method4"));
		assertTrue(returnTypeExtendsListOfString(Parameterized2ListString.class, "method5"));
	}
}

Add test sample for question 182872 on stackoverflow.com

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


import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.PreparedQuery;
import com.google.appengine.api.datastore.Query;
import com.google.gson.Gson;
package com.google.sps;
import com.google.sps.data.Fields;
import com.google.sps.data.Video;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.File;
import java.nio.file.Files;
import java.nio.file.Paths;

// Servlet for testing queries.
@WebServlet("/data")
public class DataServlet extends HttpServlet {

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

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

        Video video = requestToVideoObject(request);
        Entity videoEntity = videoToEntity(video);

        DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
        datastore.put(videoEntity);
        response.sendRedirect("/");
    }

    public Video requestToVideoObject(HttpServletRequest request){
        // Get the input from the form.
        String videoId = request.getParameter(Fields.VIDEO_ID);
        // Extra fields in form for metadata until we can fetch them.
        String title = request.getParameter(Fields.TITLE);
        String description = request.getParameter(Fields.DESCRIPTION);
        String captions = request.getParameter(Fields.CAPTIONS);
        Video video = new Video(videoId, title, description, captions);
        return video;
    }

    public Entity videoToEntity(Video video){
        Entity videoEntity = new Entity("Video");
        videoEntity.setProperty("videoId", video.getVideoId());
        videoEntity.setProperty("videoObjectAsJSON", new Gson().toJson(video));
        return videoEntity;
    }
}

Add Data Servlet, handles putting video data into DataStore


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

package io.spine.testing.logging;

import com.google.common.truth.ObjectArraySubject;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.junit.jupiter.api.extension.Extension;

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

@DisplayName("@MuteLogging should")
class MuteLoggingTest {

    @Test
    @DisplayName("be marked as an extension")
    void annotated() {
        Class<MuteLogging> annotation = MuteLogging.class;
        ExtendWith extendsWith = annotation.getAnnotation(ExtendWith.class);
        Class<? extends Extension>[] extensions = extendsWith.value();
        ObjectArraySubject<Class<? extends Extension>> assertExtensions = assertThat(extensions);
        assertExtensions.hasLength(1);
        assertExtensions.asList().contains(MuteLoggingExtension.class);
    }
}

Add a test for `MuteLogging`.

Add a test for `MuteLogging`.


/*
 * $Log: JmsRealmsFactory.java,v $
 * Revision 1.1  2007-10-23 09:18:28  europe\M00035F
 * Add Digester-Factory for the JmsRealmFactory object to retrieve it from spring beans factory instead of old helper-bean-object.
 *
 * Created on 23-okt-07
 *
 */
package nl.nn.adapterframework.configuration;

/**
 * Factory for the JMS Realms instance, which holds all JMS Realm definitions
 * found in the Configuration File.
 *
 * This bean is a singleton, not a prototype, which is why the GenericFactory
 * can not be used.
 *
 * @author Tim van der Leeuw
 * @version Id
 *
 */
public class JmsRealmsFactory extends AbstractSpringPoweredDigesterFactory {

    /* (non-Javadoc)
     * @see nl.nn.adapterframework.configuration.AbstractSpringPoweredDigesterFactory#getBeanName()
     */
    public String getBeanName() {
        return "jmsRealmsFactory";
    }

    /* (non-Javadoc)
     * @see nl.nn.adapterframework.configuration.AbstractSpringPoweredDigesterFactory#isPrototypesOnly()
     */
    public boolean isPrototypesOnly() {
        return false;
    }

}


/******************************************************************************
 *                                                                            *
 *                    Copyright 2018 Subterranean Security                    *
 *                                                                            *
 *  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.sandpolis.core.instance.storage.converter;

import javax.persistence.AttributeConverter;
import javax.persistence.Converter;

import com.sandpolis.core.proto.util.Platform.Instance;

/**
 * When used on a persistent {@link Instance} field, this converter makes
 * database operations much more efficient by replacing {@link Instance}s with
 * their numeric identifier.
 *
 * @author cilki
 * @since 5.0.0
 */
@Converter
public class InstanceConverter implements AttributeConverter<Instance, Integer> {

	@Override
	public Integer convertToDatabaseColumn(Instance instance) {
		return instance.getNumber();
	}

	@Override
	public Instance convertToEntityAttribute(Integer dbData) {
		return Instance.forNumber(dbData);
	}

}

Add JPA Converter so Instance types can be persisted cleanly


/*
 * 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 org.xwiki.test.escaping.framework;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;

import org.apache.http.entity.ContentType;

public class URLContent
{
    private ContentType type;

    private byte[] content;

    public URLContent(String typeHeader, byte[] content)
    {
        this.type = typeHeader != null ? ContentType.parse(typeHeader) : null;
        this.content = content;
    }

    public ContentType getType()
    {
        return this.type;
    }

    public byte[] getContent()
    {
        return this.content;
    }

    public Reader getContentReader()
    {
        Charset charset;
        if (this.type != null && this.type.getCharset() != null) {
            charset = this.type.getCharset();
        } else {
            charset = StandardCharsets.UTF_8;
        }

        return new BufferedReader(new InputStreamReader(new ByteArrayInputStream(getContent()), charset));
    }
}

Add class missing in previous commit

[misc] Add class missing in previous commit


package com.twu.biblioteca;

import java.util.Scanner;

public class InputReader {

    String readFromConsole() {
        Scanner scanner = new Scanner(System.in);
        String inputString = scanner.next();
        return inputString;
    }
}

Implement an Input Reader which takes input from user


package ca.antonious.viewcelladapter;

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

import static org.junit.Assert.*;

/**
 * Created by George on 2016-12-18.
 */

public class ListenerCollectionTests {
    private RegisteredListener registeredListener;
    private ListenerCollection listenerCollection;

    @Before
    public void set_up() {
        registeredListener = new RegisteredListener() {
            @Override
            public void listen() {

            }
        };

        listenerCollection = new ListenerCollection();
        listenerCollection.addListener(registeredListener);
    }

    @Test
    public void test_getListener_ifListenerIsRegistered_returnsInstanceOfListener() {
        Object expectedListener = registeredListener;
        Object actualListener = listenerCollection.getListener(RegisteredListener.class);

        assertEquals(expectedListener, actualListener);
    }

    @Test
    public void test_getListener_ifListenerIsNotRegistered_returnsNull() {
        Object expectedListener = null;
        Object actualListener = listenerCollection.getListener(NotRegisteredListener.class);

        assertEquals(expectedListener, actualListener);
    }

    @Test
    public void test_removeListener_removesListener() {
        listenerCollection.removeListener(registeredListener);

        Object expectedListener = null;
        Object actualListener = listenerCollection.getListener(RegisteredListener.class);

        assertEquals(expectedListener, actualListener);
    }

    public interface RegisteredListener {
        void listen();
    }

    public interface NotRegisteredListener {
        void listen();
    }
}

Add tests for the ListenerCollection

Add tests for the ListenerCollection


package org.sagebionetworks.profiler;

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

import java.io.IOException;

import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.map.JsonMappingException;
import org.json.JSONException;
import org.junit.Before;
import org.junit.Test;

/**
 * Test for Frame.
 *
 */
public class FrameTest {

	Frame root = null;

	@Before
	public void before(){
		// Create a frame that is a few levels deep
		root = new Frame(0, "root");
		root.setEnd(12);
		// Add some children
		for(int i=0; i<4; i++){
			Frame child = new Frame(i, "child"+1);
			child.setEnd(i+1);
			root.addChild(child);
			// Add one more level
			for(int j=0; j<2; j++){
				Frame grand = new Frame(i, "grand"+j);
				grand.setEnd(i);
				child.addChild(grand);
			}
		}
	}

	/**
	 * @throws JSONException
	 * @throws IOException
	 * @throws JsonMappingException
	 * @throws JsonGenerationException
	 *
	 */
	@Test
	public void testJSONRoundTrip() throws JSONException {
		// Write it to json
		String json = Frame.writeFrameJSON(root);
		assertNotNull(json);
		System.out.println(json);
		// Now convert back to Frames
		Frame cloneRoot = Frame.readFrameFromJSON(json);
		assertNotNull(cloneRoot);
		assertEquals(root, cloneRoot);
	}
}

Move the unit tests of the profiler package to logging


/*
 * Copyright (c) 2006-2014 DMDirc Developers
 *
 * 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 com.dmdirc.util.validators;

public class OptionalEmailAddressValidator extends EmailAddressValidator {

    @Override
    public ValidationResponse validate(final String object) {
        if (object == null || object.isEmpty()) {
            return new ValidationResponse();
        }
        return super.validate(object);
    }

}

Add Optional email address validator.

Add Optional email address validator.

Change-Id: Ifc8ca757700db2dd19db89715e95f6c1df15e999
Reviewed-on: http://gerrit.dmdirc.com/3613
Automatic-Compile: DMDirc Build Manager
Reviewed-by: Chris Smith <711c73f64afdce07b7e38039a96d2224209e9a6c@dmdirc.com>


package com.nexmo.quickstart.voice;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.nexmo.client.NexmoClient;
import com.nexmo.client.auth.JWTAuthMethod;
import com.nexmo.client.voice.CallInfoPage;
import com.nexmo.client.voice.CallsFilter;

import java.nio.file.FileSystems;
import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;

import static com.nexmo.quickstart.Util.configureLogging;
import static com.nexmo.quickstart.Util.envVar;

public class RetrieveInfoForAllCalls {
    public static void main(String... args) throws Exception {
        configureLogging();

        String APPLICATION_ID = envVar("APPLICATION_ID");
        String PRIVATE_KEY = envVar("PRIVATE_KEY");

        NexmoClient nexmo = new NexmoClient(
                new JWTAuthMethod(APPLICATION_ID, FileSystems.getDefault().getPath(PRIVATE_KEY))
        );

        CallsFilter filter = new CallsFilter();
        filter.setDateStart(getYesterdaysDate());
        filter.setDateEnd(getTodaysDate());

        CallInfoPage calls = nexmo.getVoiceClient().listCalls(filter);
        System.out.println(
                new ObjectMapper().writer().writeValueAsString(calls)
        );
    }

    private static Date getTodaysDate() {
        return Calendar.getInstance(TimeZone.getTimeZone("UTC")).getTime();
    }

    private static Date getYesterdaysDate() {
        Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
        calendar.add(Calendar.DATE, -1);
        return calendar.getTime();
    }
}

Add retrieve info for all calls example.


/*
 * Copyright 2016 The Closure Compiler 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 com.google.javascript.jscomp;

/**
 * A warnings guard that suppresses warnings for a particular diagnostic group for a file that
 * contains the specified substring.
 * @author nicksantos@google.com (Nick Santos)
 */
public class DiagnosticGroupPathSuppressingWarningsGuard extends DiagnosticGroupWarningsGuard {
  private final String part;

  public DiagnosticGroupPathSuppressingWarningsGuard(DiagnosticGroup type, String part) {
    super(type, CheckLevel.OFF);
    this.part = part;
  }

  /** Does not suppress all warnings of any type. */
  @Override public boolean disables(DiagnosticGroup type) {
    return false;
  }

  /** Does not touch warnings in other paths. */
  @Override public CheckLevel level(JSError error) {
    return error.sourceName != null && error.sourceName.contains(part)
        ? super.level(error) /** suppress */
        : null /** proceed */;
  }

  @Override public String toString() {
    return super.toString() + "(" + part + ")";
  }
}

Make the warnings guard that allow suppressing specific groups by path public

-------------
Created by MOE: https://github.com/google/moe
MOE_MIGRATED_REVID=132504067


package de.cinovo.cloudconductor.api.interfaces;

import java.util.Set;

import javax.annotation.security.RolesAllowed;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;

import de.cinovo.cloudconductor.api.MediaType;
import de.cinovo.cloudconductor.api.enums.UserPermissions;

/**
 * Copyright 2017 Cinovo AG

 *

 *
 * @author mweise
 */
@Path("/permission")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public interface IPermission {

	/**
	 * @return set of all possible permissions
	 */
	@GET
	@RolesAllowed({"VIEW_USERS", "EDIT_USERS"})
	Set<UserPermissions> getPermissions();

}

Add interface to get the names of all possible permissions.


package leveledit;

import java.util.ArrayList;

public class ArbitraryCode {
	/**
	 * You can write your own code here to generate patterns programmatically.
	 * Just return an array of patterns and the runtime will allow you to add
	 * it to the contents of the level patterns by typing r! */
	public static ArrayList<Pattern> runCode() {
		ArrayList<Pattern> patterns = new ArrayList<>();

		//Write code here

		return patterns;
	}
}

Allow the execution of arbitrary code in runtime.

Former-commit-id: e6094929d2c3b8f96f1f30667bc6904dd0856259


package cucumber.demo;

public class Hello {
    public String greet(String who, String from) {
        return "Hi, " + who + ". I'm " + from;
    }

    public boolean isFriend(String who) {
        return true;
    }

    public String getPhoneNumber(String who) {
        return "99999";
    }
}

package cucumber.demo;

public class Hello {
    public String greet(String who, String from) {
        return "Hi, " + who + ". I'm " + from;
    }

    public boolean isFriend(String who) {
        return true;
    }

    public String getPhoneNumber(String who) {
        throw new RuntimeException("My phone is secret!");
    }
}

Make java example fail. More fun.

Make java example fail. More fun.


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

import java.util.logging.Level;

/**
 * Custom JUL Level for unit tests.
 */
public class CustomJdkLevel extends Level {

    private static final long serialVersionUID = 4681718777617726164L;

    protected CustomJdkLevel(final String name, final int value) {
        super(name, value);
    }

    // inside CONFIG range; should map to INFO
    public static final Level TEST = new CustomJdkLevel("TEST", 600);

    // just 1 below Level.SEVERE; should map to ERROR
    public static final Level DEFCON_2 = new CustomJdkLevel("DEFCON_2", 999);

    // above Level.SEVERE; should map to FATAL
    public static final Level DEFCON_1 = new CustomJdkLevel("DEFCON_1", 10000);
}

Add custom jul.Level for unit tests.

Add custom jul.Level for unit tests.


/*
 * Grapht, an open source dependency injector.
 * Copyright 2010-2012 Regents of the University of Minnesota and contributors
 *
 * 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.grouplens.grapht;

import javax.inject.Named;

import org.grouplens.grapht.util.AnnotationBuilder;

/**
 * Names is a utility class to create {@link Named} annotation instances when
 * configuring an injector that relies on named qualifiers. Qualifiers with
 * other attributes can by instantiated using the {@link AnnotationBuilder}.
 *
 * @author Michael Ludwig <mludwig@cs.umn.edu>
 */
public class Names {
    /**
     * Get a Named annotation instance whose value equals the provided String.
     * The returned annotation is equal to annotations created by a declaration
     * matching: <code>@Named(name)</code>, where name is the input String.
     *
     * @param name The name value for the returned annotation
     * @return A Named instance wrapping the given name
     */
    public static Named named(String name) {
        return new AnnotationBuilder<Named>(Named.class)
            .set("value", name)
            .build();
    }
}

Add @Named utility class that wraps AnnotationBuilder.


package net.kencochrane.raven.servlet;

import mockit.Injectable;
import mockit.NonStrictExpectations;
import mockit.Tested;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.Test;

import javax.servlet.ServletRequest;
import javax.servlet.ServletRequestEvent;
import javax.servlet.http.HttpServletRequest;

import static mockit.Deencapsulation.getField;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.nullValue;

public class RavenServletRequestListenerTest {
    @Tested
    private RavenServletRequestListener ravenServletRequestListener = null;
    @Injectable
    private ServletRequestEvent mockServletRequestEvent = null;

    @AfterMethod
    public void tearDown() throws Exception {
        // Reset the threadLocal value
        ((ThreadLocal) getField(RavenServletRequestListener.class, "THREAD_REQUEST")).remove();
    }

    @Test
    public void requestListenerEmptyByDefault() throws Exception {
        assertThat(RavenServletRequestListener.getServletRequest(), is(nullValue()));
    }

    @Test
    public void requestListenerContainsTheCurrentRequest(@Injectable final HttpServletRequest mockHttpServletRequest)
            throws Exception {
        new NonStrictExpectations() {{
            mockServletRequestEvent.getServletRequest();
            result = mockHttpServletRequest;
        }};

        ravenServletRequestListener.requestInitialized(mockServletRequestEvent);

        assertThat(RavenServletRequestListener.getServletRequest(), is(mockHttpServletRequest));
    }

    @Test
    public void requestListenerDoesntWorkWithNonHttpRequests(@Injectable final ServletRequest mockServletRequest)
            throws Exception {
        new NonStrictExpectations() {{
            mockServletRequestEvent.getServletRequest();
            result = mockServletRequest;
        }};

        ravenServletRequestListener.requestInitialized(mockServletRequestEvent);

        assertThat(RavenServletRequestListener.getServletRequest(), is(nullValue()));
    }

    @Test
    public void requestListenerDestroyRemovesTheCurrentRequest(@Injectable final HttpServletRequest mockHttpServletRequest)
            throws Exception {
        new NonStrictExpectations() {{
            mockServletRequestEvent.getServletRequest();
            result = mockHttpServletRequest;
        }};
        ravenServletRequestListener.requestInitialized(mockServletRequestEvent);

        ravenServletRequestListener.requestDestroyed(mockServletRequestEvent);

        assertThat(RavenServletRequestListener.getServletRequest(), is(nullValue()));
    }

    @Test
    public void requestListenerSpecificToLocalThread(@Injectable final HttpServletRequest mockHttpServletRequest)
            throws Exception {
        new NonStrictExpectations() {{
            mockServletRequestEvent.getServletRequest();
            result = mockHttpServletRequest;
        }};

        new Thread(){
            @Override
            public void run() {
                ravenServletRequestListener.requestInitialized(mockServletRequestEvent);
            }
        }.start();

        assertThat(RavenServletRequestListener.getServletRequest(), is(nullValue()));
    }
}

Add test coverage for the ServletRequestListener


package io.github.xxyy.quietcord.filter;

import org.junit.Test;

import java.util.logging.Filter;
import java.util.logging.Level;
import java.util.logging.LogRecord;
import java.util.logging.Logger;

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

public class PropagatingFilterTest {

    public static final String ARBITRARY_TEXT = "arbitrary text";
    public static final String IGNORED_BY_A = "ignored by A";
    public static final String IGNORED_BY_B = "ignored by B";

    @Test
    public void testInject__alone() throws Exception {
        Logger logger = Logger.getLogger("testing");

        new PropagatingFilterA(logger).inject();

        Filter injected = logger.getFilter();

        assertThat("filter wrongly matched arbitrary message alone",
                injected.isLoggable(rec(ARBITRARY_TEXT)), is(true));

        assertThat("filter A didn't match ignored message alone",
                injected.isLoggable(rec(IGNORED_BY_A)), is(false));
    }

    @Test
    public void testInject__multiple() throws Exception {
        Logger logger = Logger.getLogger("testing");

        new PropagatingFilterA(logger).inject();
        new PropagatingFilterB(logger).inject();

        Filter injected = logger.getFilter();

        assertThat("filter wrongly matched arbitrary message multiple",
                injected.isLoggable(rec(ARBITRARY_TEXT)), is(true));

        assertThat("filter didn't match ignored message A multiple",
                injected.isLoggable(rec(IGNORED_BY_A)), is(false));

        assertThat("filter didn't match ignored message B multiple",
                injected.isLoggable(rec(IGNORED_BY_B)), is(false));
    }

    private LogRecord rec(String message) {
        return new LogRecord(Level.INFO, message);
    }

    private class PropagatingFilterA extends PropagatingFilter {
        protected PropagatingFilterA(Logger logger) {
            super(logger);
        }

        @Override
        public boolean isLoggable(LogRecord record) {
            return !record.getMessage().equals(IGNORED_BY_A);
        }
    }

    private class PropagatingFilterB extends PropagatingFilter {
        protected PropagatingFilterB(Logger logger) {
            super(logger);
        }

        @Override
        public boolean isLoggable(LogRecord record) {
            return !record.getMessage().equals(IGNORED_BY_B);
        }
    }
}

Add some tests for compound filter mechanics


package com.github.aureliano.achmed.resources;

import com.github.aureliano.achmed.resources.properties.IResourceProperties;

public interface IResource {

	public abstract void make(IResourceProperties properties);
}

Create interface to resource types.

Create interface to resource types.


package com.maraudersapp.android;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.text.InputType;
import android.util.Log;
import android.widget.EditText;

/**
 * Created by Michael on 10/28/2015.
 */
public class InputDialog extends AlertDialog.Builder {

    public interface OnTextEntered {
        public void onTextEntered(String text);
    }

    public InputDialog(Context ctx, String title, final OnTextEntered callback) {
        super(ctx);
        setTitle(title);
        final EditText input = new EditText(ctx);
        input.setInputType(InputType.TYPE_CLASS_TEXT);
        setView(input);
        setPositiveButton("Send", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                Log.i("Input dialog", "Text entered: " + input.getText().toString());
                callback.onTextEntered(input.getText().toString());
            }
        });
    }

}

Add create friends and groups

Add create friends and groups


package nl.hsac.fitnesse.fixture.slim;

import fitnesse.testsystems.slim.results.SlimExceptionResult;
import org.junit.Test;

import static org.junit.Assert.*;

public class SlimFixtureExceptionTest {

    @Test
    public void testNoStackTrace() {
        SlimFixtureException e = new SlimFixtureException(false, "Hallo");
        SlimExceptionResult exceptionResult = new SlimExceptionResult("key", e.getMessage());
        assertTrue(exceptionResult.hasMessage());
        assertEquals("Hallo", exceptionResult.getMessage());
    }

    @Test
    public void testStackTrace() {
        SlimFixtureException e = new SlimFixtureException("Hallo");
        SlimExceptionResult exceptionResult = new SlimExceptionResult("key", e.getMessage());
        assertFalse(exceptionResult.hasMessage());
    }
}

Add test for exception escaping

Add test for exception escaping


/*
 * Copyright (c) 2016 Instituto Atlântico Development Company, L.P. and others. 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
 */

package org.opendaylight.nic.of.renderer.strategy;

import static org.mockito.Mockito.when;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.opendaylight.controller.md.sal.binding.api.DataBroker;
import org.opendaylight.nic.of.renderer.impl.QosConstraintManager;
import org.opendaylight.nic.of.renderer.utils.TopologyUtils;
import org.opendaylight.nic.utils.FlowAction;
import org.opendaylight.yang.gen.v1.urn.opendaylight.intent.rev150122.intents.Intent;
import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeId;
import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.node.NodeConnector;
import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.Node;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;

/**
 * @author victor. Created on 17/11/16.
 */
@PrepareForTest({ TopologyUtils.class })
@RunWith(PowerMockRunner.class)
public class QoSExecutorTest {

    @InjectMocks
    private QoSExecutor qoSExecutorMock;

    @Mock
    private QosConstraintManager qosConstraintManagerMock;

    @Mock
    private DataBroker dataBroker;

    @Mock
    private Intent intentMock;

    @Mock
    private Node node;

    @Mock
    private NodeConnector nodeConnector;

    @Mock
    private NodeId nodeIdDeprecatedMock;

    private Map<Node, List<NodeConnector>> nodeMap;

    private List<NodeConnector> nodeConnectorList;

    @Before
    public void setUp() throws Exception {
        nodeConnectorList = Arrays.asList(nodeConnector);

        when(node.getId()).thenReturn(nodeIdDeprecatedMock);

        nodeMap = new HashMap<>();
        nodeMap.put(node, nodeConnectorList);

        PowerMockito.mockStatic(TopologyUtils.class);

        when(TopologyUtils.getNodes(dataBroker)).thenReturn(nodeMap);

        qoSExecutorMock = new QoSExecutor(qosConstraintManagerMock, dataBroker);
    }

    @Test
    public void testExecuteIntentAddFlow() throws Exception {
        qoSExecutorMock.execute(intentMock, FlowAction.ADD_FLOW);
    }
}

Increase of-renderer coverage on QoSExecutor.

    QoSExecutor.java

Change-Id: Ia047885e122d70dc95e5a76813b6d510d6d13f5b
Signed-off-by: Victor Mota <a399842758ce81a1b2704ada69a36369cee4aa4d@atlantico.com.br>


package eu.europa.esig.dss.token;

import java.util.List;

import org.apache.commons.codec.binary.Base64;

import eu.europa.esig.dss.DigestAlgorithm;
import eu.europa.esig.dss.SignatureValue;
import eu.europa.esig.dss.ToBeSigned;

public class MSCAPISignatureTokenApp {

	public static void main(String[] args){

		MSCAPISignatureToken token = new MSCAPISignatureToken();

		List<DSSPrivateKeyEntry> keys = token.getKeys();
		for (DSSPrivateKeyEntry entry : keys) {
			System.out.println(entry.getCertificate().getCertificate());
		}

		ToBeSigned toBeSigned = new ToBeSigned("Hello world".getBytes());
		SignatureValue signatureValue = token.sign(toBeSigned, DigestAlgorithm.SHA256, keys.get(0));

		System.out.println("Signature value : " + Base64.encodeBase64String(signatureValue.getValue()));
	}

}

Add simple application test to interact with MSCAPI


/*
 * Copyright (C) 2015 Archie L. Cobbs. All rights reserved.
 */

package org.jsimpledb.kv.spanner;

import com.google.cloud.spanner.SpannerOptions;

import org.jsimpledb.kv.KVDatabase;
import org.jsimpledb.kv.KVTransaction;
import org.jsimpledb.kv.test.KVTestSupport;
import org.jsimpledb.util.ByteUtil;
import org.testng.Assert;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Optional;
import org.testng.annotations.Parameters;
import org.testng.annotations.Test;

public class DeleteTest extends KVTestSupport {

    private SpannerKVDatabase db;

    @BeforeClass(groups = "configure")
    @Parameters({ "spannerProject", "spannerInstance" })
    public void setSpannerConfig(@Optional String project, String instance) throws Exception {
        if (instance != null) {
            this.db = new SpannerKVDatabase();
            final SpannerOptions.Builder builder = SpannerOptions.newBuilder();
            if (project != null)
                builder.setProjectId(project);
            this.db.setSpannerOptions(builder.build());
            this.db.setInstanceId(instance);
        }
    }

    @Test
    protected void testDeleteToInfinity() throws Exception {
        this.db.start();
        try {

            final byte[] key1 = new byte[] { (byte)0x11 };
            final byte[] val1 = new byte[] { (byte)0xaa };
            final byte[] key2 = new byte[] { (byte)0x22 };
            final byte[] val2 = new byte[] { (byte)0xbb };

            // Populate DB
            KVTransaction tx = this.db.createTransaction();
            try {
                tx.removeRange(new byte[0], null);
                tx.put(key1, val1);
                tx.put(key2, val2);
                tx.commit();
            } finally {
                tx.rollback();
            }

            // Display db
            this.show("initial content");

            // Delete to infinity
            tx = this.db.createTransaction();
            try {
                tx.removeRange(ByteUtil.getNextKey(key1), null);
                tx.commit();
            } finally {
                tx.rollback();
            }

            // Verify second key is gone
            tx = this.db.createTransaction();
            try {
                this.show("after remove");
                Assert.assertNull(tx.get(key2));
                tx.commit();
            } finally {
                tx.rollback();
            }

        } finally {
            this.db.stop();
        }
    }

    private void show(String label) throws Exception {
        this.log.info("Spanner content (" + label + "):");
        KVTransaction tx = this.db.createTransaction();
        try {
            this.show(tx, label);
            tx.commit();
        } finally {
            tx.rollback();
        }
    }

    private void show(KVTransaction tx, String label) throws Exception {
        final Exception e = this.showKV(tx, label);
        if (e != null)
            throw e;
    }
}

Add Google Spanner unit test.

Add Google Spanner unit test.


package com.jetbrains.python.actions;

import com.intellij.ide.actions.CreateFileFromTemplateDialog;
import com.intellij.ide.actions.CreateFromTemplateAction;
import com.intellij.openapi.project.DumbAware;
import com.intellij.openapi.project.Project;
import com.intellij.psi.PsiDirectory;
import com.intellij.psi.PsiFile;
import com.jetbrains.python.PythonFileType;

/**
 * @author yole
 */
public class CreatePythonFileAction extends CreateFromTemplateAction<PsiFile> implements DumbAware {
  public CreatePythonFileAction() {
    super("Python File", "Creates a Python file from the specified template", PythonFileType.INSTANCE.getIcon());
  }

  @Override
  protected PsiFile createFile(String name, String templateName, PsiDirectory dir) {
    return createFileFromTemplate(name, templateName, dir);
  }

  @Override
  protected void checkBeforeCreate(String name, String templateName, PsiDirectory dir) {
    dir.checkCreateFile(name);
  }

  @Override
  protected void buildDialog(Project project, PsiDirectory directory, CreateFileFromTemplateDialog.Builder builder) {
    builder
      .setTitle("New Python file")
      .addKind("Python file", PythonFileType.INSTANCE.getIcon(), "Python Script")
      .addKind("Python unit test", PythonFileType.INSTANCE.getIcon(), "Python Unit Test");
  }

  @Override
  protected String getActionName(PsiDirectory directory, String newName, String templateName) {
    return "Create Python script " + newName;
  }
}

package com.jetbrains.python.actions;

import com.intellij.ide.actions.CreateFileFromTemplateAction;
import com.intellij.ide.actions.CreateFileFromTemplateDialog;
import com.intellij.openapi.project.DumbAware;
import com.intellij.openapi.project.Project;
import com.intellij.psi.PsiDirectory;
import com.jetbrains.python.PythonFileType;

/**
 * @author yole
 */
public class CreatePythonFileAction extends CreateFileFromTemplateAction implements DumbAware {
  public CreatePythonFileAction() {
    super("Python File", "Creates a Python file from the specified template", PythonFileType.INSTANCE.getIcon());
  }

  @Override
  protected void buildDialog(Project project, PsiDirectory directory, CreateFileFromTemplateDialog.Builder builder) {
    builder
      .setTitle("New Python file")
      .addKind("Python file", PythonFileType.INSTANCE.getIcon(), "Python Script")
      .addKind("Python unit test", PythonFileType.INSTANCE.getIcon(), "Python Unit Test");
  }

  @Override
  protected String getActionName(PsiDirectory directory, String newName, String templateName) {
    return "Create Python script " + newName;
  }
}

Create JavaEE Web Page action

Create JavaEE Web Page action


package org.slc.sli.modeling.rest;

import static org.junit.Assert.*;

import java.util.ArrayList;

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

/**
 * JUnit test for Grammars class.
 *
 * @author wscott
 *
 */
public class GrammarsTest {

    private Grammars grammars;

    private static final ArrayList<Include> INCLUDES = new ArrayList<Include>(0);
    private static final ArrayList<Documentation> DOC = new ArrayList<Documentation>(0);

    @Before
    public void setup() throws Exception {
        grammars = new Grammars(DOC, INCLUDES);
    }

    @Test
    public void testNullIncludes() {
        new Grammars(DOC, null);
    }

    @Test
    public void testGetIncludes() {
        assertEquals(INCLUDES, grammars.getIncludes());
    }

    @Test
    public void testToString() {
        assertTrue(!"".equals(grammars.toString()));
    }

}

Add JUnit test for Grammars class in rest modeling module.


package edu.grinnell.tranchri.cohnhan.deweytyl.hardtmad;

/**
 * JSONParser Class
 *
 * @author Hannah Cohn
 * @author Ty Dewey
 * @author Madeleine Hardt
 * @author Christine Tran
 */

public class JSONParser
{
  // +--------+----------------------------------------------
  // | Fields |
  // +--------+

  String jString;
  JSONValue jValue;

  // +--------------+----------------------------------------
  // | Constructors |
  // +--------------+

  public JSONParser(String input)
  {
    jString = input;
  } // JSONParser (String)

  public JSONParser(JSONValue obj)
  {
    jValue = obj;
  } // JSONParser (JSONValue)

  // +---------------+---------------------------------------
  // | Class Methods |
  // +---------------+

  public Object JSONToJavaObject()
    throws Exception
  {
    this.jValue = JSONUtils.parseValue(jString);
    char type = jValue.type();
    switch (type)
      {
        case 'n':
          return JSONUtils.getNumber(jValue);
        case 's':
          return JSONUtils.getString(jValue);
        case 'c':
          {
            String str = JSONUtils.getString(jValue);
            if (str.equals("true"))
              return true;
            else if (str.equals("false"))
              return false;
            else
              return null;
          } // case 'c'
        case 'a':
          return JSONUtils.getArray(jValue);
        case 'o':
          return JSONUtils.getObject(jValue);
      } // switch

    throw new Exception("Unsupported String" + jString);

  } // JSONToJavaObject()

  public String JavaObjectToStringOfJSON()
    throws Exception
  {

    return jString;
  } // JavaObjectToStringOfJSON()

}

Add framework for parser object and String to Object method


package de.xn__ho_hia.quality.null_analysis;

import java.math.BigInteger;

import org.eclipse.jdt.annotation.NonNull;

/**
 * Utility class to work with @NonNull match operations.
 */
public final class NullsafeMath {

    /**
     * @param value
     *            The value to wrap
     * @return A @NonNull {@link BigInteger}
     */
    public static @NonNull BigInteger asBigInteger(final long value) {
        return Nullsafe.nonNull(BigInteger.valueOf(value));
    }

    /**
     * @param value
     *            The value to wrap
     * @return A @NonNull {@link Long}
     */
    public static @NonNull Long asLong(final long value) {
        return Nullsafe.nonNull(Long.valueOf(value));
    }

    /**
     * @param first
     *            The first value to add
     * @param second
     *            The second value to add
     * @return The sum of both values as a @NonNull {@link BigInteger}
     */
    public static @NonNull BigInteger addNullsafe(final BigInteger first, final BigInteger second) {
        return Nullsafe.nonNull(first.add(second));
    }

    /**
     * @param first
     *            The first value to subtract
     * @param second
     *            The second value to subtract
     * @return The difference of both values as a @NonNull {@link BigInteger}
     */
    public static @NonNull BigInteger subtractNullsafe(final BigInteger first, final BigInteger second) {
        return Nullsafe.nonNull(first.subtract(second));
    }

    /**
     * @param first
     *            The first value to divide
     * @param second
     *            The second value to divide
     * @return The division of both values as a @NonNull {@link BigInteger}
     */
    public static @NonNull BigInteger divideNullsafe(final BigInteger first, final BigInteger second) {
        return Nullsafe.nonNull(first.divide(second));
    }

    /**
     * @param first
     *            The first value to multiply
     * @param second
     *            The second value to multiply
     * @return The multiplication of both values as a @NonNull {@link BigInteger}
     */
    public static @NonNull BigInteger multiplyNullsafe(final BigInteger first, final BigInteger second) {
        return Nullsafe.nonNull(first.multiply(second));
    }

}

Add null safe math operations

Add null safe math operations

Signed-off-by: Sebastian Hoß <1d6e1cf70ec6f9ab28d3ea4b27a49a77654d370e@shoss.de>


/*******************************************************************************
 * Copyright (C) 2017 Push Technology Ltd.
 *
 * 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.pushtechnology.adapters.rest.metrics;

import com.pushtechnology.adapters.rest.model.latest.EndpointConfig;
import com.pushtechnology.adapters.rest.model.latest.ServiceConfig;
import com.pushtechnology.diffusion.client.features.control.topics.TopicAddFailReason;
import com.pushtechnology.diffusion.datatype.Bytes;

/**
 * Listener for Diffusion topic creation events.
 *
 * @author Push Technology Limited
 */
public interface TopicCreationListener {
    /**
     * Notified when an attempt to create a Diffusion topic is made and there is no initial value.
     *
     * @param serviceConfig the service
     * @param endpointConfig the endpoint
     */
    void onTopicCreationRequest(ServiceConfig serviceConfig, EndpointConfig endpointConfig);

    /**
     * Notified when an attempt to create a Diffusion topic is made and there is an initial value.
     *
     * @param serviceConfig the service
     * @param endpointConfig the endpoint
     * @param value the initial value
     */
    void onTopicCreationRequest(ServiceConfig serviceConfig, EndpointConfig endpointConfig, Bytes value);

    /**
     * Notified when a Diffusion topic is created and there is no initial value.
     *
     * @param serviceConfig the service
     * @param endpointConfig the endpoint
     */
    void onTopicCreated(ServiceConfig serviceConfig, EndpointConfig endpointConfig);

    /**
     * Notified when a Diffusion topic is created and there is an initial value.
     *
     * @param serviceConfig the service
     * @param endpointConfig the endpoint
     * @param value the initial value
     */
    void onTopicCreated(ServiceConfig serviceConfig, EndpointConfig endpointConfig, Bytes value);

    /**
     * Notified when a Diffusion topic cannot be created and there is no initial value.
     *
     * @param serviceConfig the service
     * @param endpointConfig the endpoint
     * @param reason the cause of failure
     */
    void onTopicCreationFailed(
        ServiceConfig serviceConfig,
        EndpointConfig endpointConfig,
        TopicAddFailReason reason);

    /**
     * Notified when a Diffusion topic cannot be created and there is an initial value.
     *
     * @param serviceConfig the service
     * @param endpointConfig the endpoint
     * @param value the initial value
     * @param reason the cause of failure
     */
    void onTopicCreationFailed(
        ServiceConfig serviceConfig,
        EndpointConfig endpointConfig,
        Bytes value,
        TopicAddFailReason reason);
}

Add listener interface for topic creation events.


/*
 *
 *
 * Copyright (C) 2005 SIPfoundry Inc.
 * Licensed by SIPfoundry under the LGPL license.
 *
 * Copyright (C) 2005 Pingtel Corp.
 * Licensed to SIPfoundry under a Contributor Agreement.
 *
 * $
 */
package org.sipfoundry.sipxconfig.security;

import junit.framework.TestCase;
import net.sf.acegisecurity.UserDetails;

import org.easymock.MockControl;
import org.easymock.classextension.MockClassControl;
import org.sipfoundry.sipxconfig.common.CoreContext;
import org.sipfoundry.sipxconfig.common.Permission;
import org.sipfoundry.sipxconfig.common.User;

public class AuthenticationDaoImplTest extends TestCase {
    private static final String USER_NAME = "Hjelje";
    private static User s_user = null;

    private MockControl m_coreControl;
    private CoreContext m_coreContext;
    private AuthenticationDaoImpl m_authenticationDaoImpl;

    protected void setUp() throws Exception {
        m_coreControl = MockClassControl.createStrictControl(CoreContext.class);
        m_coreContext = (CoreContext) m_coreControl.getMock();
        m_authenticationDaoImpl = new AuthenticationDaoImpl();
        m_authenticationDaoImpl.setCoreContext(m_coreContext);
        s_user = new User() {
            public boolean hasPermission(Permission permission) {
                return true;
            }
        };
        s_user.setUserName(USER_NAME);
    }

    public void testLoadUserByUsername() {
        // prep the mock core context
        m_coreContext.loadUserByUserNameOrAlias(USER_NAME);
        m_coreControl.setReturnValue(s_user);
        m_coreControl.replay();

        // load the user details
        UserDetails details = m_authenticationDaoImpl.loadUserByUsername(USER_NAME);
        assertEquals(USER_NAME, details.getUsername());
        assertEquals(AuthenticationDaoImpl.AUTH_USER_AND_ADMIN_ARRAY, details.getAuthorities());
        m_coreControl.verify();
    }
}

Add unit test for AuthenticationDaoImpl

Add unit test for AuthenticationDaoImpl

git-svn-id: f26ccc5efe72c2bd8e1c40f599fe313f2692e4de@5685 a612230a-c5fa-0310-af8b-88eea846685b


package com.github.conradoqg.studydsa.hackerrank.challenges.ctci;

import java.util.HashMap;
import java.util.Scanner;

public class DavisStaircase {
    private static HashMap<Integer, Integer> cache = new HashMap<Integer, Integer>();

    private static int calculateCombinatoryFor(int n) {
        int ways = 0;
        if (n == 1)
            ways = 1;
        if (n == 2)
            ways = 2;
        if (n == 3)
            ways = 4;

        if (n > 3) {
            for (int i = 1; i <= 3; i++) {
                if (cache.containsKey(n - i))
                    ways += cache.get(n - i);
                else {
                    int result = calculateCombinatoryFor(n - i);
                    ways += result;
                    cache.put(n - i, result);
                }
            }
        }

        return ways;
    }

    public static void main(String[] args) {
        try (Scanner in = new Scanner(System.in)) {
            int s = in.nextInt();
            for (int a0 = 0; a0 < s; a0++) {
                int n = in.nextInt();
                System.out.println(calculateCombinatoryFor(n));
            }
        }
    }
}

Add Davis' staircase CTCI challenge

Add Davis' staircase CTCI challenge


package org.usfirst.frc4915.MecanumDrive.commands;

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

public class GenericTestCommand extends Command {

	int count = 0;
	int i;
	String message;

    public GenericTestCommand(int count, String message) {
        // Use requires() here to declare subsystem dependencies
        // eg. requires(chassis);
    	this.count = count;
    	this.message = message;
    }

    // Called just before this Command runs the first time
    protected void initialize() {
    	System.out.printf("Saying \"%s\" %i times.%n", message, count);
    }

    // Called repeatedly when this Command is scheduled to run
    protected void execute() {
    	System.out.printf("%s (%i/%i)", message, i, count);
    	i++;
    }

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

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

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

Create a simple command to use in testing things


package javaStringCompare;

import java.util.Arrays;
import java.util.Scanner;

public class Solution {

	public static String[] readAndSplitString(Scanner scanner) {
		String line = scanner.next();
		int windowLength = scanner.nextInt();
		String[] lines = new String[line.length() - windowLength + 1];
		for(int i = 0; i < line.length() - windowLength + 1; ++i) {
			lines[i] = line.substring(i, windowLength + i);
		}
		return lines;
	}

	public static void main(String ...args) {
		Scanner scanner = new Scanner(System.in);
		String[] lines = readAndSplitString(scanner);
		Arrays.sort(lines);
		System.out.println(lines[0]);
		System.out.println(lines[lines.length - 1]);
		scanner.close();
	}
}

Add solution for problem Java String Compare

Java String Compare from HackerRank/Strings/Java String Compare


package leetcode.climbing_stairs;

public class Solution {
    public int climbStairs(int n) {
        int a = 1, b = 1;
        while(n > 0){
        	int tmp = a;
        	a = a + b;
        	b = tmp;
        	n--;
        }
        return b;
    }
}

Add java solution for 70. Climbing Stairs

70. Climbing Stairs: https://leetcode.com/problems/climbing-stairs/


package leetcode.merge_intervals;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;

import common.Interval;

public class Solution {
    public ArrayList<Interval> merge(ArrayList<Interval> intervals) {
    	ArrayList<Interval> ans = new ArrayList<Interval>();
    	for(int i = intervals.size() - 1; i >= 0; i--){
    		Interval iv = intervals.get(i);
    		if(iv.start > iv.end){
    			int tmp = iv.start;
    			iv.start = iv.end;
    			iv.end = tmp;
    		}
    	}
    	int size = intervals.size();
    	if(intervals.size() == 0) return ans;
    	Collections.sort(intervals, new Comparator<Interval>(){
			@Override
			public int compare(Interval iv1, Interval iv2) {
				if(iv1.start < iv2.start) return -1;
				if(iv1.start > iv2.start) return 1;
				return 0;
			}
    	});
    	Interval cur = intervals.get(0);
    	int index = 1;
    	while(true){
    		while(index < size && intervals.get(index).start <= cur.end){
    			cur.end = Math.max(cur.end, intervals.get(index).end);
    			index++;
    		}
    		ans.add(cur);
    		if(index < size)
    			cur = intervals.get(index);
    		else
    			break;
    	}
    	return ans;
    }

    public static void main(String[] args){
    	ArrayList<Interval> input = new ArrayList<Interval>();
    	//[1,3],[2,6],[8,10],[15,18]
    	input.add(new Interval(0, 4));
    	input.add(new Interval(0, 0));
    	for(Interval iv : new Solution().merge(input)){
    		System.err.println(iv.start + "," + iv.end);
    	}
    }
}

Add java solution for 56. Merge Intervals

56. Merge Intervals: https://leetcode.com/problems/merge-intervals/


package experimentalcode.erich.data.images;

import java.awt.Color;
import java.util.List;

import de.lmu.ifi.dbs.elki.utilities.optionhandling.IntParameter;
import de.lmu.ifi.dbs.elki.utilities.optionhandling.OptionID;
import de.lmu.ifi.dbs.elki.utilities.optionhandling.ParameterException;
import de.lmu.ifi.dbs.elki.utilities.optionhandling.constraints.IntervalConstraint;
import de.lmu.ifi.dbs.elki.utilities.optionhandling.constraints.IntervalConstraint.IntervalBoundary;

public class ComputeHSBColorHistogram extends AbstractComputeColorHistogram {
  int quant;

  /**
   * OptionID for {@link #BINSPERPLANE_PARAM}
   */
  public static final OptionID BINSPERPLANE_ID = OptionID.getOrCreateOptionID("hsbhist.bpp", "Bins per plane for HSV/HSB histogram. This will result in bpp ** 3 bins.");

  /**
   * Parameter that specifies the number of bins (per plane) to use.
   *
   * <p>
   * Key: {@code -rgbhist.bpp}
   * </p>
   */
  private final IntParameter BINSPERPLANE_PARAM = new IntParameter(BINSPERPLANE_ID, new IntervalConstraint(2, IntervalBoundary.CLOSE, 256, IntervalBoundary.CLOSE));

  public ComputeHSBColorHistogram() {
    super();
    addOption(BINSPERPLANE_PARAM);
  }

  @Override
  public List<String> setParameters(List<String> args) throws ParameterException {
    List<String> remainingParameters = super.setParameters(args);

    quant = BINSPERPLANE_PARAM.getValue();

    return remainingParameters;
  }

  private final static float[] hsbbuf = new float[3];

  @Override
  protected int getBinForColor(int rgb) {
    int r = (rgb & 0xFF0000) >> 16;
    int g = (rgb & 0x00FF00) >> 8;
    int b = (rgb & 0x0000FF);

    synchronized(hsbbuf) {
      float[] hsbvals = Color.RGBtoHSB(r, g, b, hsbbuf);
      // The values returned by RGBtoHSB are all in [0:1]
      int h = (int) Math.floor(quant * hsbvals[0]);
      int s = (int) Math.floor(quant * hsbvals[1]);
      int v = (int) Math.floor(quant * hsbvals[2]);
      // Guard against the value of 1.0
      if(h >= quant) {
        h = quant - 1;
      }
      if(s >= quant) {
        s = quant - 1;
      }
      if(v >= quant) {
        v = quant - 1;
      }
      return h * quant * quant + s * quant + v;
    }
  }

  @Override
  protected int getNumBins() {
    return quant * quant * quant;
  }
}

Add histogram class for HSB/HSV colors.

Add histogram class for HSB/HSV colors.


package com.haxademic.sketch.test;

import com.haxademic.core.app.AppSettings;
import com.haxademic.core.app.PAppletHax;
import com.haxademic.core.draw.image.ImageCyclerBuffer;
import com.haxademic.core.file.FileUtil;

import processing.core.PImage;

public class ImageSwapperBufferTest
extends PAppletHax {
	public static void main(String args[]) { PAppletHax.main(Thread.currentThread().getStackTrace()[1].getClassName()); }

	protected ImageCyclerBuffer imageCycler;

	protected void overridePropsFile() {
		p.appConfig.setProperty( AppSettings.WIDTH, 720 );
		p.appConfig.setProperty( AppSettings.HEIGHT, 720 );
		p.appConfig.setProperty( AppSettings.FULLSCREEN, false );
		p.appConfig.setProperty( AppSettings.SMOOTHING, AppSettings.SMOOTH_HIGH );
		p.appConfig.setProperty( AppSettings.RETINA, false );
	}

	public void setup() {
		super.setup();

		PImage[] images = new PImage[] {
				p.loadImage(FileUtil.getFile("images/justin-home.jpg")),
				p.loadImage(FileUtil.getFile("images/justin-home.png")),
		};

		imageCycler = new ImageCyclerBuffer(640, 280, images, 300, 0.5f);
	}

	public void drawApp() {
		p.background(0);

		imageCycler.update();
		p.image(imageCycler.image(), 20, 20);
	}

}

Add image cycler (w/glsl transitions) test


package de.evorepair.analysis.solver.eclipse;

import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.PlatformUI;

public class EclipseUtil {
	public static IWorkbenchPage getActivePage() {
		return PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage();
	}

	public static IEditorPart getActiveEditor(){
		return getActivePage().getActiveEditor();
	}
}

Add missing eclipse util class

Add missing eclipse util class


package org.commonmark.ext.headerids;

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

/**
 * Provider of unique strings to be used as an identifier
 */
public class UniqueIdentifierProvider
{
    private String defaultIdentifier;
    private final Map<String, Integer> identityMap;

    /**
     * Create a provider with the default identifier of "id"
     */
    public UniqueIdentifierProvider() {
        this("id");
    }

    /**
     * @param defaultIdentifier default identifier to use if given a null, or empty {@code providedIdentity}
     *                          in {@link #getUniqueIdentifier(String)}
     */
    public UniqueIdentifierProvider(String defaultIdentifier)
    {
        this.defaultIdentifier = defaultIdentifier;
        this.identityMap = new HashMap<>();
    }

    public String getDefaultIdentifier()
    {
        return defaultIdentifier;
    }

    public void setDefaultIdentifier(String defaultIdentifier)
    {
        this.defaultIdentifier = defaultIdentifier;
    }

    /**
     *

     * Provides unique strings over the lifetime of the instance
     *

     *

     * This method is not thread safe, concurrent calls can end up
     * with non-unique identifiers
     *

     *

     * Note that collision can occur in the case that
     *

     *
String 'X' provided to getUniqueIdentifier

     *
String 'X' provided again to getUniqueIdentifier

     *
String 'X-1' provided to getUniqueIdentifier

     *

     *

     *

     * In that case, the three ids provided will be
     *

     *
X

     *
X-1

     *
X-1

     *

     *

     *

     * Therefore if collisions are unnacceptable you should ensure that
     * numbers are stripped from end of {@code providedIdentity}
     *

     *
     * @param providedIdentity tentative identifier to be used. Will be used to check if this is unique. Will be the
     *                         basis for the returned identifier
     *
     * @return {@code providedIdentity} if this is the first instance that the {@code providedIdentity} has been passed
     * to the method. Otherwise, {@code providedIdentity + "-" + X} will be returned, where X is the number of times
     * that {@code providedIdentity} has previously been passed in. If {@code providedIdentity} is empty, the default
     * identifier given in the constructor (or "id" if none given) will be used.
     */
    public String getUniqueIdentifier(String providedIdentity) {
        if (providedIdentity == null || providedIdentity.trim().length() == 0) {
            providedIdentity = defaultIdentifier;
        }

        if (!identityMap.containsKey(providedIdentity)) {
            identityMap.put(providedIdentity, 1);
            return providedIdentity;
        } else {
            int currentCount = identityMap.get(providedIdentity);
            identityMap.put(providedIdentity, currentCount + 1);
            return providedIdentity + "-" +currentCount;
        }
    }
}

Add UniqueID Provider as public class

Add UniqueID Provider as public class

Previously this functionality existed internally in the
HeaderIdAttributeProvider. This has been stripped out into its own
functional class that can be used by other packages. The language
attempts to divorce it from its original heading implementation to a
more general identity provider


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

import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import org.graylog2.gelfclient.GelfConfiguration;
import org.testng.annotations.Test;

import static org.testng.Assert.assertEquals;

public class AbstractGelfTransportTest {

    @Test
    public void testThreads() throws Exception {
        final int threads = 23;
        final GelfConfiguration configuration = new GelfConfiguration().threads(threads);
        final AbstractGelfTransport transport = new AbstractGelfTransport(configuration) {
            @Override
            protected void createBootstrap(EventLoopGroup workerGroup) {
                final NioEventLoopGroup eventLoopGroup = (NioEventLoopGroup) workerGroup;
                assertEquals(threads, eventLoopGroup.executorCount());
            }
        };
        transport.stop();
    }
}

Add test for number of threads used by AbstractGelfTransport

Refs #35


package com.opentable.jaxrs;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.PropertyResolver;

import com.opentable.spring.SpecializedConfigFactory;

@Configuration
public class JaxRsClientConfiguration {

    @Bean
    SpecializedConfigFactory<JaxRsClientConfig> jaxRsConfigFactory(PropertyResolver pr) {
        return SpecializedConfigFactory.create(pr, JaxRsClientConfig.class, "jaxrs.client.${name}");
    }

    @Bean
    JaxRsClientFactory jaxrsClientFactory(SpecializedConfigFactory<JaxRsClientConfig> config) {
        return new JaxRsClientFactory(config);
    }

    @Bean
    JaxRsFeatureBinding dataUriHandler() {
        return JaxRsFeatureBinding.bindToAllGroups(new DataUriFeature());
    }
}

package com.opentable.jaxrs;

import com.fasterxml.jackson.databind.ObjectMapper;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.PropertyResolver;

import com.opentable.spring.SpecializedConfigFactory;

@Configuration
public class JaxRsClientConfiguration {

    @Bean
    SpecializedConfigFactory<JaxRsClientConfig> jaxRsConfigFactory(PropertyResolver pr) {
        return SpecializedConfigFactory.create(pr, JaxRsClientConfig.class, "jaxrs.client.${name}");
    }

    @Bean
    JaxRsClientFactory jaxrsClientFactory(SpecializedConfigFactory<JaxRsClientConfig> config) {
        return new JaxRsClientFactory(config);
    }

    @Bean
    JaxRsFeatureBinding dataUriHandler() {
        return JaxRsFeatureBinding.bindToAllGroups(new DataUriFeature());
    }

    @Bean
    JaxRsFeatureBinding jsonFeature(ObjectMapper mapper) {
        return JaxRsFeatureBinding.bindToAllGroups(JsonClientFeature.forMapper(mapper));
    }
}

Enable Jackson on jaxrs clients

Enable Jackson on jaxrs clients


/**
 *
 */
package org.corpus_tools.atomic.api.events;

import org.eclipse.core.runtime.IConfigurationElement;
import org.eclipse.core.runtime.Platform;
import org.eclipse.ui.IPartListener2;
import org.eclipse.ui.IWorkbenchPartReference;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.contexts.IContextActivation;
import org.eclipse.ui.contexts.IContextService;

/**
 * TODO Description
 *
 * @author Stephan Druskat <mail@sdruskat.net>
 *
 */
public class PartContextListener implements IPartListener2 {

	private final String partId;
	private IContextActivation contextActivation = null;
	private final String pluginId;
	private String contextId = null;

	/**
	 * @param partId
	 *
	 */
	public PartContextListener(String partId, String pluginId) {
		this.partId = partId;
		this.pluginId = pluginId;
		IConfigurationElement[] elements = Platform.getExtensionRegistry().getConfigurationElementsFor("org.eclipse.ui.contexts");

		for (IConfigurationElement element : elements) {
			if (element.getContributor().getName().equals(pluginId)) {
				this.contextId = element.getAttribute("id");
				break;
			}
		}
	}

	/* (non-Javadoc)
	 * @see org.eclipse.ui.IPartListener2#partActivated(org.eclipse.ui.IWorkbenchPartReference)
	 */
	@Override
	public void partActivated(IWorkbenchPartReference partRef) {
		if (contextId != null) {
			if (partRef.getId().equals(partId)) {
				PlatformUI.getWorkbench().getDisplay().syncExec(new Runnable() {
					@Override
					public void run() {
						contextActivation = PlatformUI.getWorkbench().getService(IContextService.class).activateContext(contextId);
					}
				});
			}
		}
	}

	/* (non-Javadoc)
	 * @see org.eclipse.ui.IPartListener2#partDeactivated(org.eclipse.ui.IWorkbenchPartReference)
	 */
	@Override
	public void partDeactivated(IWorkbenchPartReference partRef) {
		if (contextId != null && contextActivation != null) {
			if (partRef.getId().equals(partId)) {
				PlatformUI.getWorkbench().getDisplay().syncExec(new Runnable() {
					@Override
					public void run() {
						PlatformUI.getWorkbench().getService(IContextService.class).deactivateContext(contextActivation);
					}
				});
			}
		}

	}

	// Unimplemented methods
	@Override public void partBroughtToTop(IWorkbenchPartReference partRef) {}
	@Override public void partClosed(IWorkbenchPartReference partRef) {}
	@Override public void partOpened(IWorkbenchPartReference partRef) {}
	@Override public void partHidden(IWorkbenchPartReference partRef) {}
	@Override public void partVisible(IWorkbenchPartReference partRef) {}
	@Override public void partInputChanged(IWorkbenchPartReference partRef) {}

}

Implement a part listener that sets contexts automatically


package com.github.gabrielruiu.spring.cloud.config.redis;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

/**
 * @author Gabriel Mihai Ruiu (gabriel.ruiu@mail.com)
 */
@EnableConfigServerRedis
@SpringBootApplication
public class SpringConfigServerRedisTestConfiguration {

    public static void main(String[] args) {
        SpringApplication.run(SpringConfigServerRedisTestConfiguration.class, args);
    }
}

Add main configuration class that tests will use to build the application context