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

package io.vertx.ext.web.templ;

import io.vertx.lang.js.ClasspathFileResolver;
import io.vertx.test.lang.js.JSTestBase;
import org.junit.Test;

/**
 * @author Thomas Segismont
 */
public class FreeMarkerJavascriptTemplateTest extends JSTestBase {

  static {
    ClasspathFileResolver.init();
  }

  @Override
  protected String getTestFile() {
    return "freemarker_javascript_template_test.js";
  }

  @Test
  public void testTemplate() throws Exception {
    runTest();
  }
}

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

package io.vertx.ext.web.templ;

import io.vertx.lang.js.ClasspathFileResolver;
import io.vertx.test.lang.js.JSTestBase;
import org.junit.Ignore;
import org.junit.Test;

/**
 * @author Thomas Segismont
 */
public class FreeMarkerJavascriptTemplateTest extends JSTestBase {

//  static {
//    ClasspathFileResolver.init();
//  }

  @Override
  protected String getTestFile() {
    return "freemarker_javascript_template_test.js";
  }

  @Test
  @Ignore
  public void testTemplate() throws Exception {
    runTest();
  }
}

Disable JS test for a while since the CP hack breaks things


package dr.inference.model;

import dr.xml.*;
import sun.awt.X11.XLayerProtocol;

/**
 * @author Joseph Heled
 *         Date: 4/09/2009
 */
public class ValuesPoolParser extends dr.xml.AbstractXMLObjectParser {
    public static String VALUES_POOL = "valuesPool";
    public static String VALUES = "values";
     public static String SELECTOR = "selector";

    public Object parseXMLObject(XMLObject xo) throws XMLParseException {
        final Variable pool = (Variable)xo.getElementFirstChild(VALUES);
        final Variable selector = (Variable)xo.getElementFirstChild(SELECTOR);

        if( pool.getSize() != selector.getSize() ) {
            throw new XMLParseException("variable Pool and selector must have equal length.");
        }
        return new ValuesPool(pool, selector);
    }

    public XMLSyntaxRule[] getSyntaxRules() {
          return new XMLSyntaxRule[] {
                  new ElementRule(VALUES, new XMLSyntaxRule[]{
                        new ElementRule(Variable.class,1,1) }),
                   new ElementRule(SELECTOR, new XMLSyntaxRule[]{
                        new ElementRule(Variable.class,1,1) })

          };
      }

    public String getParserDescription() {
        return "";
    }

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

    public String getParserName() {
        return VALUES_POOL;
    }
}

package dr.inference.model;

import dr.xml.*;
//import sun.awt.X11.XLayerProtocol;

/**
 * @author Joseph Heled
 *         Date: 4/09/2009
 */
public class ValuesPoolParser extends dr.xml.AbstractXMLObjectParser {
    public static String VALUES_POOL = "valuesPool";
    public static String VALUES = "values";
     public static String SELECTOR = "selector";

    public Object parseXMLObject(XMLObject xo) throws XMLParseException {
        final Variable pool = (Variable)xo.getElementFirstChild(VALUES);
        final Variable selector = (Variable)xo.getElementFirstChild(SELECTOR);

        if( pool.getSize() != selector.getSize() ) {
            throw new XMLParseException("variable Pool and selector must have equal length.");
        }
        return new ValuesPool(pool, selector);
    }

    public XMLSyntaxRule[] getSyntaxRules() {
          return new XMLSyntaxRule[] {
                  new ElementRule(VALUES, new XMLSyntaxRule[]{
                        new ElementRule(Variable.class,1,1) }),
                   new ElementRule(SELECTOR, new XMLSyntaxRule[]{
                        new ElementRule(Variable.class,1,1) })

          };
      }

    public String getParserDescription() {
        return "";
    }

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

    public String getParserName() {
        return VALUES_POOL;
    }
}

Fix broken code, comment out sun.awt.X11.XLayerProtocol


package plugins.CENO;

import plugins.CENO.FreenetInterface.FreemailAPI.Freemail;

public class CENORequest extends Freemail {

	private CENOReqFlags[] reqFlags;

	public CENORequest(Freemail freemail) {
		super(freemail.getFreemailFrom(), freemail.getFreemailTo(), freemail.getSubject(), freemail.getBody());
	}

	public CENORequest(Freemail freemail, CENOReqFlags[] reqFlags) {
		this(freemail);
		this.reqFlags = reqFlags;
	}

	public CENORequest(String freemailFrom, String[] freemailTo, String subject, String body) {
		super(freemailFrom, freemailTo, subject, body);
	}

	public CENORequest(String freemailFrom, String[] freemailTo, String subject, String body, CENOReqFlags[] reqFlags) {
		this(freemailFrom, freemailTo, subject, body);
		this.reqFlags = reqFlags;
	}

	public CENOReqFlags[] getReqFlags() {
		return reqFlags;
	}

	public enum CENOReqFlags {
		X_Ceno_Rewritten
	}
}

package plugins.CENO;

import java.util.EnumSet;

import plugins.CENO.FreenetInterface.FreemailAPI.Freemail;

public class CENORequest extends Freemail {

	public enum CENOReqFlags {
		X_Ceno_Rewritten
	}

	private EnumSet<CENOReqFlags> reqFlags;

	public CENORequest(Freemail freemail) {
		super(freemail.getFreemailFrom(), freemail.getFreemailTo(), freemail.getSubject(), freemail.getBody());
	}

	public CENORequest(Freemail freemail, EnumSet<CENOReqFlags> reqFlags) {
		this(freemail);
		this.reqFlags = reqFlags;
	}

	public CENORequest(String freemailFrom, String[] freemailTo, String subject, String body) {
		super(freemailFrom, freemailTo, subject, body);
	}

	public CENORequest(String freemailFrom, String[] freemailTo, String subject, String body, EnumSet<CENOReqFlags> reqFlags) {
		this(freemailFrom, freemailTo, subject, body);
		this.reqFlags = reqFlags;
	}

	public EnumSet<CENOReqFlags> getReqFlags() {
		return reqFlags;
	}
}

Replace CENOReqFlags array with an EnumSet


/**
 * @file EnumDemo.java
 * @author Valery Samovich
 * @version 1.0.0
 * @date 10/15/2014
 */

package com.valerysamovich.java.enums;

public class EnumDemo {

    public static void main(String[] args) {

        /**
         * The java.lang.Enum.compareTo() method compares this enum with the
         * specified object for order.Enum constants are only comparable to
         * other enum constants of the same enum type.
         *
         * public final int compareTo(E o)
         *
         * o - This is object to be compared
         */

    }

}

/**
 * @file EnumDemo.java
 * @author Valery Samovich
 * @version 1.0.0
 * @date 10/15/2014
 */

package com.valerysamovich.java.enums;

/**
 * Enum showing topics covered under Tutorials
 */
enum Tutorials {
    topic1, topic2, topic3;
}

public class EnumDemo {

    public static void main(String[] args) {

        /**
         * The java.lang.Enum.compareTo() method compares this enum with the
         * specified object for order.Enum constants are only comparable to
         * other enum constants of the same enum type.
         *
         * public final int compareTo(E o)
         *
         * o - This is object to be compared
         */

        Tutorials t1, t2,t3;

        t1 = Tutorials.topic1;
        t2 = Tutorials.topic2;
        t3 = Tutorials.topic3;
    }

}

Add Enum class and create objects


package guitests;

public class RedoCommandTest extends TaskManagerGuiTest {

}

package guitests;

import org.junit.Test;

import seedu.address.logic.commands.UndoCommand;
import seedu.address.testutil.TestTask;
import seedu.address.testutil.TestUtil;

public class RedoCommandTest extends TaskManagerGuiTest {

    TestTask[] expectedList = td.getTypicalTasks();
    TestTask[] currentList = expectedList;

    public void redo() {
        redoAdd();
    }

    /**
     * Tries to redo an add command
     */
    @Test
    public void redoAdd() {
        TestTask taskToAdd = td.alice;
        commandBox.runCommand(taskToAdd.getAddCommand());
        commandBox.runCommand(UndoCommand.COMMAND_WORD);
        expectedList = TestUtil.addTasksToList(expectedList, taskToAdd);
        assertRedoSuccess(currentList, expectedList);
    }

}

Test case for redo add command


package patterns.document;

import java.util.HashMap;
import java.util.Map;
import java.util.OptionalDouble;
import java.util.OptionalInt;

import org.junit.Test;

import org.junit.Assert;

public class CarTest {

	private static final double PRICE = 100.0;
	private static final String MODEL = "Audi";
	private static final String COLOR = "red";
	private static final int WHEELS_COUNT = 4;

	@Test
	public void testCreateCar() throws Exception {
		Map<String, Object> entries = new HashMap<>();
		Car car = new Car(entries);

		car.put(ColorTrait.KEY, COLOR);
		car.put(ModelTrait.KEY, MODEL);
		car.put(PriceTrait.KEY, PRICE);
		car.put(WheelsTrait.KEY, WHEELS_COUNT);

		String color = car.getColor();
		Assert.assertEquals(COLOR, color);
		String model = car.getModel();
		Assert.assertEquals(MODEL, model);
		OptionalDouble price = car.getPrice();
		Assert.assertEquals(PRICE, price.getAsDouble());
		OptionalInt wheels = car.getWheels();
		Assert.assertEquals(WHEELS_COUNT, wheels.getAsInt());
	}
}

package patterns.document;

import java.util.HashMap;
import java.util.Map;
import java.util.OptionalDouble;
import java.util.OptionalInt;

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

public class CarTest {

	private static final double DELTA = 0.000001;
	private static final double PRICE = 100.0;
	private static final String MODEL = "Audi";
	private static final String COLOR = "red";
	private static final int WHEELS_COUNT = 4;

	@Test
	public void testCreateCar() throws Exception {
		Map<String, Object> entries = new HashMap<>();
		Car car = new Car(entries);

		car.put(ColorTrait.KEY, COLOR);
		car.put(ModelTrait.KEY, MODEL);
		car.put(PriceTrait.KEY, PRICE);
		car.put(WheelsTrait.KEY, WHEELS_COUNT);

		String color = car.getColor();
		Assert.assertEquals(COLOR, color);
		String model = car.getModel();
		Assert.assertEquals(MODEL, model);
		OptionalDouble price = car.getPrice();
		Assert.assertEquals(PRICE, price.getAsDouble(), DELTA);
		OptionalInt wheels = car.getWheels();
		Assert.assertEquals(WHEELS_COUNT, wheels.getAsInt());
	}
}

Fix test after JUnit upgrade


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

package org.apache.spf.mechanismn;

import org.apache.spf.IPAddr;
import org.apache.spf.SPF1Data;

public interface GenericMechanismn {

    /**
     * Run the mechanismn
     * @return result
     */
    public int checkMechanismn(IPAddr checkAddress, String domainName, int maskLenght);

    /**
     * Init the SPF1Data
     * @param spfData The current SPF1Data container
     */
    public void initSPF1Data(SPF1Data spfData);
}

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

package org.apache.spf.mechanismn;

import org.apache.spf.IPAddr;
import org.apache.spf.SPF1Data;

public interface GenericMechanismn {

    /**
     * Run the mechanismn
     * @return result
     */
    public int run();

    /**
     *
     * @param spfData The SPF1Data
     * @param mechanismPrefix The mechanismPrefix
     * @param checkAddress The ipAddress to check
     * @param domainName The domainName
     * @param maskLenght The maskLength
     */
    public void init(SPF1Data spfData,String mechanismPrefix,IPAddr checkAddress, String domainName, int maskLenght);
}

Change the interface layout to reflect the changes we spoke about in icq


package org.kefirsf.tk;

import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;
import twitter4j.auth.RequestToken;

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

/**
 * Signin servlet
 *
 * @author Vitalii Samolovskikh aka Kefir
 */
public class SigninServlet extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Twitter twitter = new TwitterFactory().getInstance();
        request.getSession().setAttribute("twitter", twitter);
        try {
            String callbackUrl = new StringBuilder()
                    .append(ConfigurationHolder.getInstance().get("server.url"))
                    .append("/callback")
                    .toString();

            RequestToken requestToken = twitter.getOAuthRequestToken(callbackUrl);
            request.getSession().setAttribute("requestToken", requestToken);
            response.sendRedirect(requestToken.getAuthenticationURL());
        } catch (TwitterException e) {
            throw new ServletException(e);
        }
    }
}

package org.kefirsf.tk;

import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;
import twitter4j.auth.RequestToken;

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

/**
 * Signin servlet
 *
 * @author Vitalii Samolovskikh aka Kefir
 */
public class SigninServlet extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Twitter twitter = new TwitterFactory().getInstance();
        request.getSession().setAttribute("twitter", twitter);
        try {
/*
            String callbackUrl = new StringBuilder()
                    .append(ConfigurationHolder.getInstance().get("server.url"))
                    .append("/callback")
                    .toString();

            RequestToken requestToken = twitter.getOAuthRequestToken(callbackUrl);
*/
            RequestToken requestToken = twitter.getOAuthRequestToken();
            request.getSession().setAttribute("requestToken", requestToken);
            response.sendRedirect(requestToken.getAuthenticationURL());
        } catch (TwitterException e) {
            throw new ServletException(e);
        }
    }
}

Prepare for deploy to production.


package org.junit.experimental.theories.internal;

import java.util.Arrays;
import java.util.Collection;
import java.util.Iterator;

public class ParameterizedAssertionError extends RuntimeException {
    private static final long serialVersionUID = 1L;

    public ParameterizedAssertionError(Throwable targetException,
            String methodName, Object... params) {
        super(String.format("%s(%s)", methodName, join(", ", params)),
                targetException);
    }

    @Override
    public boolean equals(Object obj) {
        return toString().equals(obj.toString());
    }

    public static String join(String delimiter, Object... params) {
        return join(delimiter, Arrays.asList(params));
    }

    public static String join(String delimiter,
            Collection<Object> values) {
        StringBuffer buffer = new StringBuffer();
        Iterator<Object> iter = values.iterator();
        while (iter.hasNext()) {
            Object next = iter.next();
            buffer.append(stringValueOf(next));
            if (iter.hasNext()) {
                buffer.append(delimiter);
            }
        }
        return buffer.toString();
    }

    private static String stringValueOf(Object next) {
        try {
            return String.valueOf(next);
        } catch (Throwable e) {
            return "[toString failed]";
        }
    }
}

package org.junit.experimental.theories.internal;

import java.util.Arrays;
import java.util.Collection;
import java.util.Iterator;

public class ParameterizedAssertionError extends AssertionError {
    private static final long serialVersionUID = 1L;

    public ParameterizedAssertionError(Throwable targetException,
            String methodName, Object... params) {
        super(String.format("%s(%s)", methodName, join(", ", params)));
        this.initCause(targetException);
    }

    @Override
    public boolean equals(Object obj) {
        return toString().equals(obj.toString());
    }

    public static String join(String delimiter, Object... params) {
        return join(delimiter, Arrays.asList(params));
    }

    public static String join(String delimiter,
            Collection<Object> values) {
        StringBuffer buffer = new StringBuffer();
        Iterator<Object> iter = values.iterator();
        while (iter.hasNext()) {
            Object next = iter.next();
            buffer.append(stringValueOf(next));
            if (iter.hasNext()) {
                buffer.append(delimiter);
            }
        }
        return buffer.toString();
    }

    private static String stringValueOf(Object next) {
        try {
            return String.valueOf(next);
        } catch (Throwable e) {
            return "[toString failed]";
        }
    }
}

Make parameterized assertion error extend assertion error


package org.jvirtanen.nassau.util;

public class SystemClock implements Clock {

    public static final SystemClock INSTANCE = new SystemClock();

    @Override
    public long currentTimeMillis() {
        return System.currentTimeMillis();
    }

}

package org.jvirtanen.nassau.util;

public class SystemClock implements Clock {

    public static final SystemClock INSTANCE = new SystemClock();

    private SystemClock() {
    }

    @Override
    public long currentTimeMillis() {
        return System.currentTimeMillis();
    }

}

Clean up interface for system clock


package org.jsoftware.tjconsole.local;

import com.sun.tools.attach.VirtualMachine;

/**
 * Check if tools.jar is available
 * Receive local java PIDs
 * Try to load agent for JMX
 * @author szalik
 */
public class ProcessListManagerLoader {
    public static final String LOCAL_PREFIX = "LOCAL ";
    private static ProcessListManager processListManager;

    public static boolean isToolsJarAvailable() {
        try {
            Class.forName("com.sun.tools.attach.VirtualMachine");
            return true;
        } catch (ClassNotFoundException e) {
            return false;
        }
    }

    public static ProcessListManager getProcessListManager() throws ToolsNotAvailableException {
        if (! isToolsJarAvailable()) {
            throw new ToolsNotAvailableException();
        }
        synchronized (ProcessListManagerLoader.class) {
            if (processListManager == null) {
                processListManager = new ProcessListManager();
            }
            return processListManager;
        }
    }

    /**
     * @param url url to check
     * @return true if url string is local process url
     */
    public static boolean isLocalProcess(String url) {
        return url.startsWith(LOCAL_PREFIX);
    }

}

package org.jsoftware.tjconsole.local;

import com.sun.tools.attach.VirtualMachine;

/**
 * Check if tools.jar is available
 * Receive local java PIDs
 * Try to load agent for JMX
 * @author szalik
 */
public class ProcessListManagerLoader {
    public static final String LOCAL_PREFIX = "LOCAL:";
    private static ProcessListManager processListManager;

    public static boolean isToolsJarAvailable() {
        try {
            Class.forName("com.sun.tools.attach.VirtualMachine");
            return true;
        } catch (ClassNotFoundException e) {
            return false;
        }
    }

    public static ProcessListManager getProcessListManager() throws ToolsNotAvailableException {
        if (! isToolsJarAvailable()) {
            throw new ToolsNotAvailableException();
        }
        synchronized (ProcessListManagerLoader.class) {
            if (processListManager == null) {
                processListManager = new ProcessListManager();
            }
            return processListManager;
        }
    }

    /**
     * @param url url to check
     * @return true if url string is local process url
     */
    public static boolean isLocalProcess(String url) {
        return url.startsWith(LOCAL_PREFIX);
    }

}

Change for local pid prefix


/**
 * Copyright 2009 Joe LaPenna
 */
package com.joelapenna.foursquared.test;

import com.joelapenna.foursquare.Foursquare;
import com.joelapenna.foursquared.Foursquared;

import android.test.ApplicationTestCase;
import android.test.suitebuilder.annotation.MediumTest;
import android.test.suitebuilder.annotation.SmallTest;

/**
 * @author Joe LaPenna (joe@joelapenna.com)
 *
 */
public class FoursquaredAppTestCase extends ApplicationTestCase<Foursquared> {

    public FoursquaredAppTestCase() {
        super(Foursquared.class);
    }

    @MediumTest
    public void testLocationMethods() {
        createApplication();
        getApplication().getLastKnownLocation();
        getApplication().getLocationListener();
    }

    @SmallTest
    public void testPreferences() {
        createApplication();
        Foursquared foursquared = getApplication();
        Foursquare foursquare = foursquared.getFoursquare();
        // ... to be continued.
    }
}

/**
 * Copyright 2009 Joe LaPenna
 */

package com.joelapenna.foursquared.test;

import com.joelapenna.foursquare.Foursquare;
import com.joelapenna.foursquared.Foursquared;

import android.test.ApplicationTestCase;
import android.test.suitebuilder.annotation.MediumTest;
import android.test.suitebuilder.annotation.SmallTest;

/**
 * @author Joe LaPenna (joe@joelapenna.com)
 */
public class FoursquaredAppTestCase extends ApplicationTestCase<Foursquared> {

    public FoursquaredAppTestCase() {
        super(Foursquared.class);
    }

    @MediumTest
    public void testLocationMethods() {
        createApplication();
        getApplication().getLastKnownLocation();
        getApplication().getLocationListener();
    }

    @SmallTest
    public void testPreferences() {
        createApplication();
        Foursquared foursquared = getApplication();
        foursquared.getFoursquare();
        // ... to be continued.
    }
}

Fix formatting and a warning for FoursqauredAppTestCase.


package guice;

import play.Application;
import services.AuthenticationService;
import services.StubConfigurationImplTest;
import services.ConfigurationService;
import services.ESConstantImpl;
import services.ESConstantService;
import services.ESSearchImpl;
import services.ESSearchService;
import stub.StubAuthenticationImplTest;
import utils.EncodeUtils;
import utils.IEncodeUtils;
import utils.eslasticsearch.ESServerEmbedded;
import utils.eslasticsearch.IESServerEmbedded;

import com.google.inject.AbstractModule;
import com.google.inject.Guice;

import configuration.GlobalConfiguration;
import controllers.AuthenticationController;

public class GlobalTest extends GlobalConfiguration {

    @Override
    protected AbstractModule buildAbstractModule() {
        return new AbstractModule() {
            @Override
            protected void configure() {
                bind(IESServerEmbedded.class).to(ESServerEmbedded.class);
                bind(IEncodeUtils.class).to(EncodeUtils.class);

                bind(ESSearchService.class).to(ESSearchImpl.class);
                bind(ESConstantService.class).to(ESConstantImpl.class);

                bind(ConfigurationService.class).to(StubConfigurationImplTest.class);
                bind(AuthenticationService.class).to(StubAuthenticationImplTest.class);

                bind(AuthenticationController.class).asEagerSingleton();
            }
        };
    }

    @Override
    public void onStart(Application application) {
        this.injector = Guice.createInjector(buildAbstractModule());
    }

    @Override
    public void onStop(Application arg0) {
        // do nothing
    }
}

package guice;

import play.Application;
import services.AuthenticationService;
import services.StubConfigurationImplTest;
import services.ConfigurationService;
import services.ESConstantImpl;
import services.ESConstantService;
import services.ESSearchImpl;
import services.ESSearchService;
import stub.StubAuthenticationImplTest;
import utils.EncodeUtils;
import utils.FileUtils;
import utils.IEncodeUtils;
import utils.IFileUtils;
import utils.eslasticsearch.ESServerEmbedded;
import utils.eslasticsearch.IESServerEmbedded;

import com.google.inject.AbstractModule;
import com.google.inject.Guice;

import configuration.GlobalConfiguration;
import controllers.AuthenticationController;

public class GlobalTest extends GlobalConfiguration {

    @Override
    protected AbstractModule buildAbstractModule() {
        return new AbstractModule() {
            @Override
            protected void configure() {
                bind(IESServerEmbedded.class).to(ESServerEmbedded.class);
                bind(IEncodeUtils.class).to(EncodeUtils.class);
                bind(IFileUtils.class).to(FileUtils.class);

                bind(ESSearchService.class).to(ESSearchImpl.class);
                bind(ESConstantService.class).to(ESConstantImpl.class);

                bind(ConfigurationService.class).to(StubConfigurationImplTest.class);
                bind(AuthenticationService.class).to(StubAuthenticationImplTest.class);

                bind(AuthenticationController.class).asEagerSingleton();
            }
        };
    }

    @Override
    public void onStart(Application application) {
        this.injector = Guice.createInjector(buildAbstractModule());
    }

    @Override
    public void onStop(Application arg0) {
        // do nothing
    }
}

Fix test: Missing Guice dependency


package co.inventorsoft.oop.basic.demo;

import co.inventorsoft.oop.basic.model.Passport;
import co.inventorsoft.oop.basic.model.Person;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.Month;

public class Main {

    public static void main(String[] args) {
        final Person martynBorodavka = new Person("Martyn", "Borodavka",
                LocalDateTime.of(LocalDate.of(1736, Month.JULY, 10), LocalTime.now()));
        /*
         * age calculation is reflective to current date but we don't care because of encapsulation
         */
        printAge(martynBorodavka);

        martynBorodavka.setAge(-2); //we cannot change created person's age which is makes sense
        martynBorodavka.setPassport(new Passport()); //we can create objects we are not responsible to create

        /*
        * we can omit birth date for newborns but age is calculation right. But again we don't care. thanks for encapsulation
        */
        final Person newBorn = new Person("Ivan", "Ivanenko");
        printAge(newBorn);
    }

    private static String printAge(final Person person) {
        System.out.println(String.format("Martyn Borodavka is %d years old", person.getAge()));
    }
}

package co.inventorsoft.oop.basic.demo;

import co.inventorsoft.oop.basic.model.Passport;
import co.inventorsoft.oop.basic.model.Person;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.Month;

public class Main {

    public static void main(String[] args) {
        final Person martynBorodavka = new Person("Martyn", "Borodavka",
                LocalDateTime.of(LocalDate.of(1736, Month.JULY, 10), LocalTime.now()));
        /*
         * age calculation is reflective to current date but we don't care because of encapsulation
         */
        printAge(martynBorodavka);

        martynBorodavka.setAge(-2); //we cannot change created person's age which is makes sense
        martynBorodavka.setPassport(new Passport()); //we cannot create passport object without required info

        /*
        * we can omit birth date for newborns but age is calculation right. But again we don't care. thanks for encapsulation
        */
        final Person newBorn = new Person("Ivan", "Ivanenko");
        printAge(newBorn);
    }

    private static String printAge(final Person person) {
        System.out.println(String.format("Martyn Borodavka is %d years old", person.getAge()));
    }
}

Update comment for passport creation


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

// --main-class de.sormuras.bach.Bach
open /*test*/ module de.sormuras.bach /*extends "main" module*/ {
  requires org.junit.jupiter;

  // ---

  requires java.compiler;
  requires java.net.http;

  // exports de.sormuras.bach;
  // exports de.sormuras.bach.project;
  // exports de.sormuras.bach.project;

  uses java.util.spi.ToolProvider;
}

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

// --main-class de.sormuras.bach.Bach
open /*test*/ module de.sormuras.bach /*extends "main" module*/ {

  // "test"

  requires org.junit.jupiter;

  // "main"

  requires java.compiler;
  requires java.net.http;

  exports de.sormuras.bach;
  exports de.sormuras.bach.project;

  uses java.util.spi.ToolProvider;
}

Copy main module descriptor 1:1


package org.rmatil.sync.event.aggregator.core.modifier;

import org.rmatil.sync.event.aggregator.core.events.IEvent;
import org.rmatil.sync.event.aggregator.core.events.ModifyEvent;

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

/**
 * Modifies the list of events in such a way, that notifications
 * about a change in a directory do not get propagated further.
 */
public class IgnoreDirectoryModifier implements IModifier {

    @Override
    public List<IEvent> modify(List<IEvent> events) {
        List<IEvent> modifiedEvents = new ArrayList<>();

        for (IEvent event : events) {
            if (! (event instanceof ModifyEvent && event.getPath().toFile().isDirectory())) {
                modifiedEvents.add(event);
            }
        }

        return modifiedEvents;
    }
}

package org.rmatil.sync.event.aggregator.core.modifier;

import org.rmatil.sync.event.aggregator.core.events.IEvent;
import org.rmatil.sync.event.aggregator.core.events.ModifyEvent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

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

/**
 * Modifies the list of events in such a way, that notifications
 * about a change in a directory do not get propagated further.
 */
public class IgnoreDirectoryModifier implements IModifier {

    final static Logger logger = LoggerFactory.getLogger(IgnoreDirectoryModifier.class);

    @Override
    public List<IEvent> modify(List<IEvent> events) {
        List<IEvent> modifiedEvents = new ArrayList<>();

        for (IEvent event : events) {
            if (! (event instanceof ModifyEvent && event.getPath().toFile().isDirectory())) {
                modifiedEvents.add(event);
            } else {
                logger.trace("Ignoring modify event for directory " + event.getPath());
            }
        }

        return modifiedEvents;
    }
}

Add log statement on ignore


package com.github.aureliano.achmed.server.service;

import com.github.aureliano.achmed.common.exception.AchmedException;

public final class ServiceFactory {

	private ServiceFactory() {}

	public static IService createService(ServiceType type) {
		switch (type) {
		case READ_FILE:
			return null;
		default:
			throw new AchmedException("Unsupported service type: " + type);
		}
	}
}

package com.github.aureliano.achmed.server.service;

import com.github.aureliano.achmed.common.exception.AchmedException;

public final class ServiceFactory {

	private ServiceFactory() {}

	public static IService createService(ServiceType type) {
		switch (type) {
		case READ_FILE:
			return new ReadFileService();
		default:
			throw new AchmedException("Unsupported service type: " + type);
		}
	}
}

Create service for reading file.


package org.testng.internal;

public class Version {

    public static final String VERSION = "7.1.1-SNAPSHOT";

    public static String getVersionString() {
        return VERSION;
    }

    public static void displayBanner() {
        System.out.println("...\n... TestNG " + getVersionString() + " by Cédric Beust (cedric@beust.com)\n...\n");
    }
}

package org.testng.internal;

public class Version {

    public static final String VERSION = "7.0.1";

    public static String getVersionString() {
        return VERSION;
    }

    public static void displayBanner() {
        System.out.println("...\n... TestNG " + getVersionString() + " by Cédric Beust (cedric@beust.com)\n...\n");
    }
}

Undo alteration of generated file


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

package com.google.sps;

import static org.junit.Assert.assertEquals;

import java.io.IOException;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;

@RunWith(JUnit4.class)
public final class FirebaseTest {

  @Test
  public void userLoggedIn() throws IOException {
    boolean result = Firebase.isUserLoggedIn("test");
    assertEquals(true, result);
  }

  @Test
  public void userLoggedInEmpty() throws IOException {
    boolean result = Firebase.isUserLoggedIn("");
    assertEquals(false, result);
  }
}

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

package com.google.sps;

import static org.junit.Assert.assertEquals;

import java.io.IOException;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import org.powermock.core.classloader.annotations.SuppressStaticInitializationFor;

@RunWith(JUnit4.class)
@SuppressStaticInitializationFor({"com.google.sps.Firebase"})
public final class FirebaseTest {

  @Test
  public void userLoggedIn() throws IOException {
    boolean result = Firebase.isUserLoggedIn("test");
    assertEquals(true, result);
  }

  @Test
  public void userLoggedInEmpty() throws IOException {
    boolean result = Firebase.isUserLoggedIn("");
    assertEquals(false, result);
  }
}

Add suppression to try and fix test errors


package org.deeplearning4j.ui.exception;

import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.ext.ExceptionMapper;
import javax.ws.rs.ext.Provider;

@Provider
public class GenericExceptionMapper implements ExceptionMapper<Throwable> {

    @Override
    public Response toResponse(Throwable ex) {
        return Response.status(500)
                .entity("Error occurred")
                .type(MediaType.APPLICATION_JSON)
                .build();
    }

}

package org.deeplearning4j.ui.exception;

import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.ext.ExceptionMapper;
import javax.ws.rs.ext.Provider;

import org.apache.commons.lang.exception.ExceptionUtils;

@Provider
public class GenericExceptionMapper implements ExceptionMapper<Throwable> {

    @Override
    public Response toResponse(Throwable ex) {
        return Response.status(500)
                .entity("Error occurred\n\n" + (ex != null ? ExceptionUtils.getStackTrace(ex) : ""))
                .type(MediaType.APPLICATION_JSON)
                .build();
    }

}

Print exception details for UI


package de.itemis.mosig.ringbuffer;

import org.junit.Test;

public class CircularBufferTest {

	@Test
	public void constructorShouldSetProvidedSize() {
		new CircularBuffer(3);
	}
}

package de.itemis.mosig.ringbuffer;

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

public class CircularBufferTest {

	@Test
	public void constructorShouldSetProvidedSize() {
		CircularBuffer underTest = new CircularBuffer(3);
		Assert.assertEquals(3, underTest.size());
	}
}

Test uses non existing size method.


package info.u_team.u_team_core.intern.asm;

import info.u_team.u_team_core.menu.UAbstractContainerMenu;
import net.minecraft.server.level.ServerPlayer;
import net.minecraft.world.inventory.AbstractContainerMenu;

public class ASMUContainerMenuHook {

	/**
	 * Called from asm core mod (ucontainermenu-init-menu.js)
	 */
	public static void hook(AbstractContainerMenu menu, ServerPlayer player) {
		if (menu instanceof UAbstractContainerMenu uContainerMenu) {
			uContainerMenu.setSynchronizerPlayer(player);
			uContainerMenu.initMenu(player);
		}
	}

}

package info.u_team.u_team_core.intern.asm;

import info.u_team.u_team_core.menu.UAbstractContainerMenu;
import net.minecraft.server.level.ServerPlayer;
import net.minecraft.world.inventory.AbstractContainerMenu;

public class ASMUContainerMenuHook {

	/**
	 * Called from asm core mod (ucontainermenu-init-menu.js) from {@link ServerPlayer#initMenu(AbstractContainerMenu)}
	 * method.
	 */
	public static void hook(AbstractContainerMenu menu, ServerPlayer player) {
		if (menu instanceof UAbstractContainerMenu uContainerMenu) {
			uContainerMenu.setSynchronizerPlayer(player);
			uContainerMenu.initMenu(player);
		}
	}

}

Make coremod description a bit more enhanced


package info.u_team.u_team_test.screen;

import com.mojang.blaze3d.matrix.MatrixStack;

import info.u_team.u_team_core.screen.UContainerScreen;
import info.u_team.u_team_test.TestMod;
import info.u_team.u_team_test.container.BasicFluidInventoryContainer;
import net.minecraft.entity.player.PlayerInventory;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.text.ITextComponent;

public class BasicFluidInventoryScreen extends UContainerScreen<BasicFluidInventoryContainer> {

	public BasicFluidInventoryScreen(BasicFluidInventoryContainer container, PlayerInventory playerInventory, ITextComponent title) {
		super(container, playerInventory, title, new ResourceLocation(TestMod.MODID, "textures/gui/fluid_inventory.png"));
	}

	@Override
	public void func_230430_a_(MatrixStack matrixStack, int mouseX, int mouseY, float partialTicks) {
		func_230446_a_(matrixStack);
		super.func_230430_a_(matrixStack, mouseX, mouseY, partialTicks);
		field_230710_m_.forEach(widget -> widget.func_230443_a_(matrixStack, mouseX, mouseY));
		func_230459_a_(matrixStack, mouseX, mouseY);
	}
}

package info.u_team.u_team_test.screen;

import info.u_team.u_team_core.screen.UBasicContainerScreen;
import info.u_team.u_team_test.TestMod;
import info.u_team.u_team_test.container.BasicFluidInventoryContainer;
import net.minecraft.entity.player.PlayerInventory;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.text.ITextComponent;

public class BasicFluidInventoryScreen extends UBasicContainerScreen<BasicFluidInventoryContainer> {

	public BasicFluidInventoryScreen(BasicFluidInventoryContainer container, PlayerInventory playerInventory, ITextComponent title) {
		super(container, playerInventory, title, new ResourceLocation(TestMod.MODID, "textures/gui/fluid_inventory.png"));
	}
}

Update basic fluid inventory screen to UBasicContainerScreen and reduce code


package com.saintdan.framework.annotation;

import org.springframework.security.core.annotation.AuthenticationPrincipal;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 * Get current user.{@link AuthenticationPrincipal}
 *
 *

 * @Controller
 * public class MyController {
 *     @RequestMapping("/user/current/show")
 *     public String show(@CurrentUser CustomUser customUser) {
 *         // do something with CustomUser
 *         return "view";
 *     }
 *

 *
 * @author Liao Yifan
 * @date 10/29/15
 * @since JDK1.8
 */
@Target({ ElementType.PARAMETER })
@Retention(RetentionPolicy.RUNTIME)
@AuthenticationPrincipal
public @interface CurrentUser {

}

Change code style to google code style.


package org.knowm.xchange.binance.dto.trade;

import com.fasterxml.jackson.annotation.JsonProperty;

public final class BinanceCancelledOrder {

  public final String symbol;
  public final String origClientOrderId;
  public final long orderId;
  public final String clientOrderId;

  public BinanceCancelledOrder(
      @JsonProperty("symbol") String symbol,
      @JsonProperty("origClientOrderId") String origClientOrderId,
      @JsonProperty("orderId") long orderId,
      @JsonProperty("clientOrderId") String clientOrderId) {
    super();
    this.symbol = symbol;
    this.origClientOrderId = origClientOrderId;
    this.orderId = orderId;
    this.clientOrderId = clientOrderId;
  }
}

package org.knowm.xchange.binance.dto.trade;

import com.fasterxml.jackson.annotation.JsonProperty;

public final class BinanceCancelledOrder {

    public final String symbol;
    public final String origClientOrderId;
    public final long orderId;
    public final String clientOrderId;
    public String price;
    public String origQty;
    public String executedQty;
    public String cummulativeQuoteQty;
    public String status;
    public String timeInForce;
    public String type;
    public String side;

    public BinanceCancelledOrder(
            @JsonProperty("symbol") String symbol,
            @JsonProperty("origClientOrderId") String origClientOrderId,
            @JsonProperty("orderId") long orderId,
            @JsonProperty("clientOrderId") String clientOrderId,
            @JsonProperty("price") String price,
            @JsonProperty("origQty") String origQty,
            @JsonProperty("executedQty") String executedQty,
            @JsonProperty("cummulativeQuoteQty") String cummulativeQuoteQty,
            @JsonProperty("status") String status,
            @JsonProperty("timeInForce") String timeInForce,
            @JsonProperty("type") String type,
            @JsonProperty("side") String side) {
        super();
        this.symbol = symbol;
        this.origClientOrderId = origClientOrderId;
        this.orderId = orderId;
        this.clientOrderId = clientOrderId;
        this.price = price;
        this.origQty = origQty;
        this.executedQty = executedQty;
        this.cummulativeQuoteQty = cummulativeQuoteQty;
        this.status = status;
        this.timeInForce = timeInForce;
        this.type = type;
        this.side = side;
    }
}

Add all response CancelOrder fields


package com.gh4a.loader;

import java.io.IOException;

import org.eclipse.egit.github.core.RepositoryId;
import org.eclipse.egit.github.core.client.RequestException;
import org.eclipse.egit.github.core.service.CollaboratorService;

import android.content.Context;

import com.gh4a.Gh4Application;

public class IsCollaboratorLoader extends BaseLoader<Boolean> {

    private String mRepoOwner;
    private String mRepoName;

    public IsCollaboratorLoader(Context context, String repoOwner, String repoName) {
        super(context);
        mRepoOwner = repoOwner;
        mRepoName = repoName;
    }

    @Override
    public Boolean doLoadInBackground() throws IOException {
        Gh4Application app = Gh4Application.get();
        CollaboratorService collabService =
                (CollaboratorService) app.getService(Gh4Application.COLLAB_SERVICE);
        try {
            RepositoryId repoId = new RepositoryId(mRepoOwner, mRepoName);
            return collabService.isCollaborator(repoId, app.getAuthLogin());
        } catch (RequestException e) {
            if (e.getStatus() == 403) {
                // the API returns 403 if the user doesn't have push access,
                // which in turn means he isn't a collaborator
                return false;
            }
            throw e;
        }
    }
}

package com.gh4a.loader;

import java.io.IOException;

import org.eclipse.egit.github.core.RepositoryId;
import org.eclipse.egit.github.core.client.RequestException;
import org.eclipse.egit.github.core.service.CollaboratorService;

import android.content.Context;

import com.gh4a.Gh4Application;

public class IsCollaboratorLoader extends BaseLoader<Boolean> {

    private String mRepoOwner;
    private String mRepoName;

    public IsCollaboratorLoader(Context context, String repoOwner, String repoName) {
        super(context);
        mRepoOwner = repoOwner;
        mRepoName = repoName;
    }

    @Override
    public Boolean doLoadInBackground() throws IOException {
        Gh4Application app = Gh4Application.get();
        String login = app.getAuthLogin();
        if (login == null) {
            return false;
        }

        CollaboratorService collabService =
                (CollaboratorService) app.getService(Gh4Application.COLLAB_SERVICE);
        try {
            RepositoryId repoId = new RepositoryId(mRepoOwner, mRepoName);
            return collabService.isCollaborator(repoId, login);
        } catch (RequestException e) {
            if (e.getStatus() == 403) {
                // the API returns 403 if the user doesn't have push access,
                // which in turn means he isn't a collaborator
                return false;
            }
            throw e;
        }
    }
}

Fix load failure if not logged in.


/*++

NASM Assembly Language Plugin
Copyright (c) 2017-2018 Aidan Khoury. All rights reserved.

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 3 of the License, or
(at your option) any later version.

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

You should have received a copy of the GNU General Public License
along with this program.  If not, see <http://www.gnu.org/licenses/>.

--*/

package com.nasmlanguage;

import com.intellij.openapi.fileTypes.FileTypeConsumer;
import com.intellij.openapi.fileTypes.FileTypeFactory;
import org.jetbrains.annotations.NotNull;

public class NASMFileTypeFactory extends FileTypeFactory {
    @Override
    public void createFileTypes(@NotNull FileTypeConsumer fileTypeConsumer) {
        fileTypeConsumer.consume(NASMFileType.INSTANCE, NASMFileType.FILE_EXTENSION);
    }
}

/*++

NASM Assembly Language Plugin
Copyright (c) 2017-2018 Aidan Khoury

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.nasmlanguage;

import com.intellij.openapi.fileTypes.FileTypeConsumer;
import com.intellij.openapi.fileTypes.FileTypeFactory;
import org.jetbrains.annotations.NotNull;

public class NASMFileTypeFactory extends FileTypeFactory {
    @Override
    public void createFileTypes(@NotNull FileTypeConsumer fileTypeConsumer) {
        fileTypeConsumer.consume(NASMFileType.INSTANCE, NASMFileType.FILE_EXTENSION);
    }
}

Update copyright notice with MIT license


package org.apache.camel.groovy.converter;

import groovy.util.XmlSlurper;
import groovy.util.slurpersupport.GPathResult;
import groovy.xml.StreamingMarkupBuilder;
import org.apache.camel.Converter;
import org.apache.camel.StringSource;
import org.w3c.dom.Node;
import org.xml.sax.SAXException;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.IOException;
import java.io.StringWriter;

@Converter
public class GPathResultConverter {

    @Converter
    public static GPathResult fromString(String input) throws ParserConfigurationException, SAXException, IOException {
        return new XmlSlurper().parseText(input);
    }

    @Converter
    public static GPathResult fromStringSource(StringSource input) throws IOException, SAXException, ParserConfigurationException {
        return fromString(input.getText());
    }

    @Converter
    public static GPathResult fromNode(Node input) throws IOException, SAXException, ParserConfigurationException, TransformerException {
        StringWriter writer = new StringWriter();
        Transformer t = TransformerFactory.newInstance().newTransformer();
        t.transform(new DOMSource(input), new StreamResult(writer));
        return fromString(writer.toString());
    }
}

package org.apache.camel.groovy.converter;

import groovy.util.XmlSlurper;
import groovy.util.slurpersupport.GPathResult;
import groovy.xml.StreamingMarkupBuilder;
import org.apache.camel.Converter;
import org.apache.camel.Exchange;
import org.apache.camel.StringSource;
import org.apache.camel.converter.jaxp.XmlConverter;
import org.w3c.dom.Node;
import org.xml.sax.SAXException;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.IOException;
import java.io.StringWriter;

@Converter
public class GPathResultConverter {

    private final XmlConverter xmlConverter = new XmlConverter();

    @Converter
    public GPathResult fromString(String input) throws ParserConfigurationException, SAXException, IOException {
        return new XmlSlurper().parseText(input);
    }

    @Converter
    public GPathResult fromStringSource(StringSource input) throws IOException, SAXException, ParserConfigurationException {
        return fromString(input.getText());
    }

    @Converter
    public GPathResult fromNode(Node input, Exchange exchange) throws IOException, SAXException, ParserConfigurationException, TransformerException {
        return fromString(xmlConverter.toString(input, exchange));
    }
}

Rewrite converting Node to GPathResult


package com.laytonsmith.abstraction.bukkit;

import com.laytonsmith.abstraction.blocks.MCBlockState;
import com.laytonsmith.abstraction.MCBlockStateMeta;
import org.bukkit.block.BlockState;
import org.bukkit.inventory.meta.BlockStateMeta;

public class BukkitMCBlockStateMeta extends BukkitMCItemMeta implements MCBlockStateMeta {

	BlockStateMeta bsm;

	public BukkitMCBlockStateMeta(BlockStateMeta meta) {
		super(meta);
		this.bsm = meta;
	}

	@Override
	public MCBlockState getBlockState() {
		try {
			return BukkitConvertor.BukkitGetCorrectBlockState(bsm.getBlockState());
		} catch (IllegalStateException | NullPointerException ex) {
			// BlockStateMeta that cannot get a BlockState
			// or a broken implementation
			return null;
		}
	}

	@Override
	public void setBlockState(MCBlockState state) {
		bsm.setBlockState((BlockState) state.getHandle());
	}
}

package com.laytonsmith.abstraction.bukkit;

import com.laytonsmith.abstraction.blocks.MCBlockState;
import com.laytonsmith.abstraction.MCBlockStateMeta;
import com.laytonsmith.core.Static;
import org.bukkit.block.BlockState;
import org.bukkit.inventory.meta.BlockStateMeta;

import java.util.logging.Level;

public class BukkitMCBlockStateMeta extends BukkitMCItemMeta implements MCBlockStateMeta {

	BlockStateMeta bsm;

	public BukkitMCBlockStateMeta(BlockStateMeta meta) {
		super(meta);
		this.bsm = meta;
	}

	@Override
	public MCBlockState getBlockState() {
		BlockState bs;
		try {
			bs = bsm.getBlockState();
		} catch (Exception ex) {
			// Broken server implementation.
			Static.getLogger().log(Level.WARNING, ex.getMessage() + " when"
					+ " trying to get the BlockState from " + bsm.toString());
			return null;
		}
		return BukkitConvertor.BukkitGetCorrectBlockState(bs);
	}

	@Override
	public void setBlockState(MCBlockState state) {
		bsm.setBlockState((BlockState) state.getHandle());
	}
}

Add better logging when getting a broken BlockState from item meta


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

import com.fasterxml.jackson.databind.Module;

/**
 * A service exposed by the content manager to let applications register custom JSON serializer and deserializer.
 */
public interface JacksonModuleRepository {

    public void register(Module module);

    public void unregister(Module module);

}

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

import com.fasterxml.jackson.databind.Module;

/**
 * A service exposed by the content manager to let applications register custom JSON serializer and deserializer
 * (also call module).
 * <p/>
 * Users must not forget to call {@link #unregister(com.fasterxml.jackson.databind.Module)} for each module they
 * registered.
 */
public interface JacksonModuleRepository {

    /**
     * Registers a module.
     * Don't forget to unregister the module when leaving.
     *
     * @param module the module
     */
    public void register(Module module);

    /**
     * Un-registers a module
     *
     * @param module the module
     */
    public void unregister(Module module);

}

Add javadoc to the Jackson Module Repository


package hackerrank;

import java.util.Scanner;

/**
 * https://www.hackerrank.com/challenges/red-john-is-back
 */
public class RedJohnIsBack {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        // TODO
    }
}

package hackerrank;

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

/**
 * https://www.hackerrank.com/challenges/red-john-is-back
 */
public class RedJohnIsBack {
    private static int redJohnIsBack(int n) {
        int x = redJohnIsBack(n, new HashMap<>());
        return primes(x);
    }

    private static int primes(int n) {
        boolean[] primes = new boolean[n + 1];
        int count = 0;
        for (int i = 2; i <= n; i++) {
            if (primes[i]) {
                continue;
            }
            count++;
            int j = i;
            while (j <= n) {
                primes[j] = true;
                j += i;
            }
        }
        return count;
    }

    private static int redJohnIsBack(int n, Map<Integer, Integer> memo) {
        if (n < 0) {
            return 0;
        }
        if (n == 0) {
            return 1;
        }
        if (memo.containsKey(n)) {
            return memo.get(n);
        }
        int a = redJohnIsBack(n - 1, memo);
        int b = redJohnIsBack(n - 4, memo);
        int total = a + b;
        memo.put(n, total);
        return total;
    }

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

Solve Red John Is Back


package org.jenkinsci.plugins.workflow.cps.global;

import groovy.lang.GroovyClassLoader;
import groovy.lang.GroovyShell;
import hudson.Extension;
import org.jenkinsci.plugins.workflow.cps.CpsFlowExecution;
import org.jenkinsci.plugins.workflow.cps.GroovyShellDecorator;

import javax.inject.Inject;
import java.net.MalformedURLException;

/**
 * Adds the global shared library space into {@link GroovyClassLoader} classpath.
 *
 * @author Kohsuke Kawaguchi
 */
@Extension
public class GroovyShellDecoratorImpl extends GroovyShellDecorator {
    @Inject
    WorkflowLibRepository repo;

    @Override
    public void configureShell(CpsFlowExecution context, GroovyShell shell) {
        try {
            shell.getClassLoader().addURL(repo.workspace.toURL());
        } catch (MalformedURLException e) {
            throw new AssertionError(e);
        }
    }
}

package org.jenkinsci.plugins.workflow.cps.global;

import groovy.lang.GroovyClassLoader;
import groovy.lang.GroovyShell;
import hudson.Extension;
import org.jenkinsci.plugins.workflow.cps.CpsFlowExecution;
import org.jenkinsci.plugins.workflow.cps.GroovyShellDecorator;

import javax.inject.Inject;
import java.io.File;
import java.net.MalformedURLException;

/**
 * Adds the global shared library space into {@link GroovyClassLoader} classpath.
 *
 * @author Kohsuke Kawaguchi
 */
@Extension
public class GroovyShellDecoratorImpl extends GroovyShellDecorator {
    @Inject
    WorkflowLibRepository repo;

    @Override
    public void configureShell(CpsFlowExecution context, GroovyShell shell) {
        try {
            shell.getClassLoader().addURL(new File(repo.workspace,"src").toURL());
        } catch (MalformedURLException e) {
            throw new AssertionError(e);
        }
    }
}

Use a sub-directory so that in the future we can have other directories for jar files, custom functions, etc.


public class Wift {

  /**
   *  Wift - The BASIC Programming Language
   *
   *        BASIC FUNCTIONALITY:
   *            - STRINGS []
   *            - INTEGERS []
   *            - ARITHMETIC []
   *            - VARIABLES []
   *
   *        FUNCTIONS:
   *            - PRINT []
   *            - INPUT []
   *            - IF []
   *            - FOR []
   *
   *
   */

  //        #readFile() -> char content
  //        #tokenize() -> list
  //        #parse()    -> symbol table

}

public class Wift {

  /**
   *  Wift - The BASIC Programming Language
   *
   *        BASIC FUNCTIONALITY:
   *            - STRINGS []
   *            - INTEGERS []
   *            - ARITHMETIC []
   *            - VARIABLES []
   *
   *        FUNCTIONS:
   *            - PRINT []
   *            - INPUT []
   *            - IF []
   *            - FOR []
   *
   *
   */

  public static void main(){}

  //        #readFile() -> char content
  //        #tokenize() -> list
  //        #parse()    -> symbol table

}

Set "public static void" for "main" :thumbsup:


/*******************************************************************************
 * Copyright (c) 2016 Sebastian Stenzel and others.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the accompanying LICENSE.txt.
 *
 * Contributors:
 *     Sebastian Stenzel - initial API and implementation
 *******************************************************************************/
package org.cryptomator.cryptolib.api;

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

import javax.inject.Qualifier;

@Qualifier
@Documented
@Retention(RetentionPolicy.RUNTIME)
public @interface CryptoLibVersion {
	Version value() default Version.ONE;

	public enum Version {
		ONE
	}
}

/*******************************************************************************
 * Copyright (c) 2016 Sebastian Stenzel and others.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the accompanying LICENSE.txt.
 *
 * Contributors:
 *     Sebastian Stenzel - initial API and implementation
 *******************************************************************************/
package org.cryptomator.cryptolib.api;

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

import javax.inject.Qualifier;

@Qualifier
@Documented
@Retention(RetentionPolicy.RUNTIME)
public @interface CryptoLibVersion {
	Version value();

	public enum Version {
		ONE
	}
}

Enforce explicit declaration of required CryptorProvider version


package com.cjburkey.cubulus;

public final class Info {

	public static final int GAME_MAJOR = 0;
	public static final int GAME_MINOR = 0;
	public static final int GAME_PATCH = 1;

	public static String getGameVersion() {
		StringBuilder b = new StringBuilder();
		b.append(GAME_MAJOR);
		b.append('.');
		b.append(GAME_MINOR);
		b.append('.');
		b.append(GAME_PATCH);
		return b.toString();
	}

}

Fix whitespace in info file


package jsx3.xml;

import org.junit.Test;

import static org.junit.Assert.*;

/**
 * Unit test for simple App.
 */
public class CdfDocumentTest
{
    /**
     * Rigorous Test :-)
     */
    @Test
    public void testApp()
    {
        CdfDocument document = new CdfDocument("root");

        Record record = new Record("US").setAttribute("index", "1");
        document.appendRecord(record);

        String xml = document.toXml();

        assertEquals(xml, "");
    }
}
/*
<data jsxid="jsxroot">
<record index="1" jsxid="US" jsxtext="United States"/>
<record index="2" jsxid="UK" jsxtext="United Kingdom"/>
<record index="3" jsxid="AG" jsxtext="Afghanistan"/>
<record index="4" jsxid="AL" jsxtext="Albania"/>
<record index="5" jsxid="AR" jsxtext="Algeria"/>
<record index="6" jsxid="AS" jsxtext="American Samoa"/>
<record index="7" jsxid="AD" jsxtext="Andorra"/>
<record index="8" jsxid="AO" jsxtext="Angola"/>
<record index="9" jsxid="AU" jsxtext="Anguilla"/>
</data>
*/

package jsx3.xml;

import org.junit.Test;

import static org.junit.Assert.*;

/**
 * Unit test for simple App.
 */
public class CdfDocumentTest
{
    /**
     * Rigorous Test :-)
     */
    @Test
    public void testApp()
    {
        CdfDocument document = new CdfDocument("root");

        Record record = new Record("US").setAttribute("index", "1");
        document.appendRecord(record);

        String xml = document.toXml();

        assertTrue(xml.startsWith("<data jsxid=\"jsxroot\">"));
        assertTrue(xml.contains("<record jsxid=\"US\" index=\"1\"/>"));
        assertTrue(xml.contains("</data>"));
    }
}

Fix to the GI CDF test, so now all tests from SVN pass


package GeeksforGeeksPractice;

public class _0017CheckSumTree {
	public static class TreeNode {
		int val;
		TreeNode left;
		TreeNode right;
		TreeNode(int x) { val = x; }
	}
	public static void main(String args[]){
		TreeNode tn=new TreeNode(10);
		tn.left=new TreeNode(8);
		tn.right=new TreeNode(2);
		tn.left.left=new TreeNode(3);
		tn.left.right=new TreeNode(5);
		tn.right.left=new TreeNode(1);
		tn.right.right=new TreeNode(1);
		System.out.println(checkSumTree(tn));
	}
	public static boolean checkSumTree(TreeNode tn) {

		return true;
	}

}

package GeeksforGeeksPractice;

public class _0017CheckSumTree {
	public static class TreeNode {
		int val;
		TreeNode left;
		TreeNode right;
		TreeNode(int x) { val = x; }
	}
	public static void main(String args[]){
		TreeNode tn=new TreeNode(26);
		tn.left=new TreeNode(10);
		tn.right=new TreeNode(3);
		tn.left.left=new TreeNode(6);
		tn.left.right=new TreeNode(4);
		tn.right.left=new TreeNode(1);
		tn.right.right=new TreeNode(2);
		System.out.println(checkSumTree(tn));
	}
	public static boolean checkSumTree(TreeNode tn) {
		if(tn!=null)
		{
			if(tn.left==null && tn.right==null)
				return true;
			if (tn.val==(sum(tn.left)+sum(tn.right)) && checkSumTree(tn.left) && checkSumTree(tn.right))
				return true;
			return false;
		}
		return true;
	}
	private static int sum(TreeNode tn) {
		if(tn!=null)
		{
			return tn.val+sum(tn.left)+sum(tn.right);
		}
		return 0;
	}

}

Check sum tree redo completed


package com.adaptionsoft.games.uglytrivia;

import org.junit.Test;

import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;

public class GamePlayTest {

    @Test
    public void playerShouldAdvanceByEyesOfDice() {
        int eyesOfDice = 3;

        Players players = mock(Players.class);
        Questions questions = mock(Questions.class);
        Game game = GameBuilder.createGameWith(players, questions);

        game.playCurrentPlayer(eyesOfDice);

        verify(players).advanceBy(eyesOfDice);
    }

}

package com.adaptionsoft.games.uglytrivia;

import org.junit.Test;

import java.util.Arrays;
import java.util.List;

import static org.hamcrest.CoreMatchers.hasItems;
import static org.junit.Assert.assertThat;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;

public class GamePlayTest {

    @Test
    public void playerShouldAdvanceByEyesOfDice() {
        int eyesOfDice = 3;

        Players players = mock(Players.class);
        Questions questions = mock(Questions.class);
        Game game = GameBuilder.createGameWith(players, questions);

        game.playCurrentPlayer(eyesOfDice);

        verify(players).advanceBy(eyesOfDice);
    }

    @Test
    public void playerShouldBeAskedQuestion() {
        new SystemOutCapture() {
            {

                Players players = mock(Players.class);
                Questions questions = mock(Questions.class);
                when(questions.nextFor(any(Category.class))).thenReturn("Pop Question 1");
                Game game = GameBuilder.createGameWith(players, questions);

                int anyEye = 0;
                game.playCurrentPlayer(anyEye);

                assertThat(capturedSystemOutLines(), hasItems("Pop Question 1" ));

            }

            private List<String> capturedSystemOutLines() {
                return Arrays.asList(capturedSystemOut().split(cr()));
            }
        }.resetSystemOut();
    }

    @Test
    public void playerShouldBeAskedQuestionBelongingToCategoryOfPlace() {
        Players players = mock(Players.class);
        when(players.currentCategory()).thenReturn(Category.POP);
        Questions questions = mock(Questions.class);
        Game game = GameBuilder.createGameWith(players, questions);

        int anyEye = 7;
        game.playCurrentPlayer(anyEye);

        verify(questions).nextFor(Category.POP);
    }

}

Test that player is asked a question and that question is of proper category


package org.obda.query.domain.imp;

import java.net.URI;

import org.obda.query.domain.Predicate;

public class PredicateImp implements Predicate{

	private int arity = -1;
	private URI name = null;
	private int identfier = -1;

	//TODO PredicateImp remove identifier
	protected PredicateImp (URI name, int identifier, int arity){
		this.name = name;
		this.identfier = name.toString().hashCode();
		this.arity = arity;
	}

	public int getArity() {
		return arity;
	}

	public URI getName() {
		return name;
	}

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

	@Override
	public boolean equals(Object obj){

		if(obj == null|| !(obj instanceof PredicateImp)){
			return false;
		}else{
			PredicateImp pred2 =(PredicateImp)obj;
			if (pred2.arity != arity)
				return false;
			return this.identfier == pred2.identfier;
		}
	}

	@Override
	public int hashCode(){
		return identfier;
	}

	public Predicate copy() {
		return new PredicateImp(this.name, this.identfier, this.arity);
	}

	public String toString() {
		return this.name.toString();
	}
}

package org.obda.query.domain.imp;

import java.net.URI;

import org.obda.query.domain.Predicate;

public class PredicateImp implements Predicate{

	private int arity = -1;
	private URI name = null;
	private int identfier = -1;

	protected PredicateImp (URI name, int arity){
		this.name = name;
		this.identfier = name.toString().hashCode();
		this.arity = arity;
	}

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

	@Override
	public int getArity() {
		return arity;
	}

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

	@Override
	public boolean equals(Object obj) {

		if (obj == null|| !(obj instanceof PredicateImp))
			return false;

		PredicateImp pred2 = (PredicateImp) obj;
		if (pred2.arity != arity)
			return false;

		return this.identfier == pred2.identfier;
	}

	@Override
	public int hashCode(){
		return identfier;
	}

	@Override
	public Predicate copy() {
		return new PredicateImp(this.name, this.arity);
	}

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

Remove the identifier parameter in the object constructor.


package ulcrs.scheduler;

import ulcrs.models.schedule.Schedule;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

public class Scheduler {
    private static List<Schedule> generatedSchedules;
    private static boolean isScheduling = false;
    private static LocalDateTime schedulingStart;

    public static boolean generateSchedule() {
        // TODO implement
        // This is where the algorithm's entry point will be. This will call the scheduling algorithm with the
        // specified tutors, courses, and shifts from DataStore, and return the list of schedules generated from
        // those constraints

        // TODO we want to spin off a thread here to do our scheduling likely.
        // The scheduling should not be done on the same thread as the thread handling the HTTP request, as we need
        // to return data for the request to avoid a timeout

        isScheduling = true;
        schedulingStart = LocalDateTime.now();

        // Start scheduling algorithm

        isScheduling = false;
        generatedSchedules = new ArrayList<>();
        return true;
    }

    public static List<Schedule> fetchGeneratedSchedules() {
        if (!isComplete()) {
            return null;
        }

        return generatedSchedules;
    }

    private static boolean isComplete() {
        return schedulingStart != null && !isScheduling;
    }

    public static boolean verifySchedule(Schedule schedule) {
        // TODO implement
        return false;
    }

}

package ulcrs.scheduler;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.google.gson.stream.JsonReader;
import ulcrs.data.DataStore;
import ulcrs.models.schedule.Schedule;

import java.io.InputStream;
import java.io.InputStreamReader;
import java.time.LocalDateTime;
import java.util.List;

public class Scheduler {
    private static List<Schedule> generatedSchedules;
    private static boolean isScheduling = false;
    private static LocalDateTime schedulingStart;

    public static boolean generateSchedule() {
        // TODO implement
        // This is where the algorithm's entry point will be. This will call the scheduling algorithm with the
        // specified tutors, courses, and shifts from DataStore, and return the list of schedules generated from
        // those constraints

        // TODO we want to spin off a thread here to do our scheduling likely.
        // The scheduling should not be done on the same thread as the thread handling the HTTP request, as we need
        // to return data for the request to avoid a timeout

        isScheduling = true;
        schedulingStart = LocalDateTime.now();

        // Start scheduling algorithm

        // For now, return mock data
        InputStream is = DataStore.class.getClassLoader().getResourceAsStream("mockSchedule_FrontendExpects.json");
        JsonReader reader = new JsonReader(new InputStreamReader(is));
        generatedSchedules = new Gson().fromJson(reader, new TypeToken<List<Schedule>>() {}.getType());

        isScheduling = false;
        return true;
    }

    public static List<Schedule> fetchGeneratedSchedules() {
        if (!isComplete()) {
            return null;
        }

        return generatedSchedules;
    }

    private static boolean isComplete() {
        return schedulingStart != null && !isScheduling;
    }

    public static boolean verifySchedule(Schedule schedule) {
        // TODO implement
        return false;
    }

}

Update Schedule endpoints to use mock data


package net.kencochrane.raven.event.interfaces;

import java.util.Map;

public interface SentryInterface {
    /**
     * Gets the unique name of the interface.
     *
     * @return name of the interface.
     */
    String getInterfaceName();

    /**
     * Gets the content of the interface as a Map.
     *

     * The values contained in the Map can only be:
     *

     *
A {@code String}

     *
A wrapped primitive

     *
A {@code Collection<String>}

     *
A {@code Map<String, V>} where {@code V} is one of the types currently listed

     *

     *

     *
     * @return the content of the interface.
     */
    Map<String, Object> getInterfaceContent();
}

package net.kencochrane.raven.event.interfaces;

import java.util.Map;

//TODO: Change interfaces so they do not behave like pre-made JSON objects
//Instead the encoder should take care of interpreting each interface in a specific way (more code, but more sensible).
public interface SentryInterface {
    /**
     * Gets the unique name of the interface.
     *
     * @return name of the interface.
     */
    String getInterfaceName();

    /**
     * Gets the content of the interface as a Map.
     *

     * The values contained in the Map can only be:
     *

     *
A {@code String}

     *
A wrapped primitive

     *
A {@code Collection<String>}

     *
A {@code Map<String, V>} where {@code V} is one of the types currently listed

     *

     *

     *
     * @return the content of the interface.
     */
    Map<String, Object> getInterfaceContent();
}

Add a todo for interfaces


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

/* Implements an adjacency list using linked lists. */

class GraphAdjacencyList<T> {

  private List<Node<T>> adjacencyList;

  public GraphAdjacencyList(int size) {
    this.adjacencyList = new ArrayList<Node<T>>(size);
  }

  /* Return true if firstNode points to secondNode. */
  protected boolean hasDirectedEdge(T firstNode, T secondNode) {
    return true;
  }

  /* Return true if both firstNode and secondNode point to each other. */
  protected boolean hasUndirectedEdge(T firstNode, T secondNode) {
    return true;
  }

  /* Add an edge from firstNode to secondNode. */
  protected void addDirectedEdge(T firstNode, T secondNode) {
    return;
  }

  /* Finds the linked list starting with node value findData. */
  private Node getNode(T findData) {
    Node current = this;

    while(current.data != findData) {
      current = current.next;
    }

    return current;
  }
}

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

/* Implements an adjacency list using linked lists. */

class GraphAdjacencyList<T> {

  private List<Node<T>> adjacencyList;

  public GraphAdjacencyList(int size) {
    this.adjacencyList = new ArrayList<Node<T>>(size);
  }

  /* Return true if firstNode points to secondNode. */
  protected boolean hasDirectedEdge(T firstNode, T secondNode) {
    return true;
  }

  /* Return true if both firstNode and secondNode point to each other. */
  protected boolean hasUndirectedEdge(T firstNode, T secondNode) {
    return true;
  }

  /* Add an edge from firstNode to secondNode. */
  protected void addDirectedEdge(T firstNode, T secondNode) {
    return;
  }

  /* Remove the edge from firstNode to secondNode. */
  protected void removeDirectedEdge(T firstNode, T secondNode) {
    return;
  }

  /* Remove the edge between both firstNode and secondNode. */
  protected void removeUndirectedEdge(T firstNode, T secondNode) {
    return;
  }

  /* Finds the linked list starting with node value findData. */
  private Node getNode(T findData) {
    Node current = this;

    while(current.data != findData) {
      current = current.next;
    }

    return current;
  }
}

Add stubs for addEdge methods for graph adjacency list.


package com.lloydtorres.stately.dto;

/**
 * Created by Lloyd on 2016-07-24.
 * A holder for freedom score data in the nation overview tab.
 */
public class NationFreedomCardData {
    public String civDesc;
    public int civScore;
    public String econDesc;
    public int econScore;
    public String poliDesc;
    public int poliScore;

    public NationFreedomCardData() { super(); }
}

package com.lloydtorres.stately.dto;

/**
 * Created by Lloyd on 2016-07-24.
 * A holder for freedom score data in the nation overview tab.
 */
public class NationFreedomCardData {
    public String nationTarget;
    public String civDesc;
    public int civScore;
    public String econDesc;
    public int econScore;
    public String poliDesc;
    public int poliScore;

    public NationFreedomCardData() { super(); }
}

Add target nation for census data


package com.hp.autonomy.frontend.find.core.configuration;

import org.springframework.stereotype.Service;

import java.io.IOException;

@Service
public class TemplatesConfigService extends CustomisationConfigService<TemplatesConfig> {
    public TemplatesConfigService() throws IOException {
        super(
                "templates.json",
                "defaultTemplatesConfigFile.json",
                TemplatesConfig.class,
                TemplatesConfig.builder().build()
        );
    }
}

package com.hp.autonomy.frontend.find.core.configuration;

import org.springframework.stereotype.Service;

@Service
public class TemplatesConfigService extends CustomizationConfigService<TemplatesConfig> {
    public TemplatesConfigService() {
        super(
                "templates.json",
                "defaultTemplatesConfigFile.json",
                TemplatesConfig.class,
                TemplatesConfig.builder().build()
        );
    }
}

Use correct name for CustomizationConfigService.


// Copyright 2019 Oath Inc. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.config.server.rpc.security;

import com.google.inject.Inject;
import com.google.inject.Provider;
import com.yahoo.cloud.config.ConfigserverConfig;
import com.yahoo.config.provision.security.NodeIdentifier;
import com.yahoo.security.tls.TransportSecurityUtils;
import com.yahoo.vespa.config.server.host.HostRegistries;
import com.yahoo.vespa.config.server.rpc.RequestHandlerProvider;

/**
 * A provider for {@link RpcAuthorizer}. The instance provided is dependent on the configuration of the configserver.
 *
 * @author bjorncs
 */
public class DefaultRpcAuthorizerProvider implements Provider<RpcAuthorizer> {

    private final RpcAuthorizer rpcAuthorizer;

    @Inject
    public DefaultRpcAuthorizerProvider(ConfigserverConfig config,
                                        NodeIdentifier nodeIdentifier,
                                        HostRegistries hostRegistries,
                                        RequestHandlerProvider handlerProvider) {
        this.rpcAuthorizer =
                TransportSecurityUtils.isTransportSecurityEnabled() && config.multitenant()
                        ? new MultiTenantRpcAuthorizer(nodeIdentifier, hostRegistries, handlerProvider)
                        : new NoopRpcAuthorizer();
    }

    @Override
    public RpcAuthorizer get() {
        return rpcAuthorizer;
    }
}

// Copyright 2019 Oath Inc. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.config.server.rpc.security;

import com.google.inject.Inject;
import com.yahoo.cloud.config.ConfigserverConfig;
import com.yahoo.config.provision.security.NodeIdentifier;
import com.yahoo.container.di.componentgraph.Provider;
import com.yahoo.security.tls.TransportSecurityUtils;
import com.yahoo.vespa.config.server.host.HostRegistries;
import com.yahoo.vespa.config.server.rpc.RequestHandlerProvider;

/**
 * A provider for {@link RpcAuthorizer}. The instance provided is dependent on the configuration of the configserver.
 *
 * @author bjorncs
 */
public class DefaultRpcAuthorizerProvider implements Provider<RpcAuthorizer> {

    private final RpcAuthorizer rpcAuthorizer;

    @Inject
    public DefaultRpcAuthorizerProvider(ConfigserverConfig config,
                                        NodeIdentifier nodeIdentifier,
                                        HostRegistries hostRegistries,
                                        RequestHandlerProvider handlerProvider) {
        this.rpcAuthorizer =
                TransportSecurityUtils.isTransportSecurityEnabled() && config.multitenant()
                        ? new MultiTenantRpcAuthorizer(nodeIdentifier, hostRegistries, handlerProvider)
                        : new NoopRpcAuthorizer();
    }

    @Override
    public RpcAuthorizer get() {
        return rpcAuthorizer;
    }

    @Override
    public void deconstruct() {}
}

Use correct Provider interface for global components


package com.github.grundlefleck;

import static org.junit.Assert.assertEquals;
import static org.mutabilitydetector.unittesting.MutabilityAssert.assertImmutable;

import org.junit.Test;

public class CarTest {

	@Test
	public void testRecompilationWithNewProperties() {
		// Not the kind of tests you would normally write,
		// included here just to see how the IDE handles changes.
		Car instanceOfCar = Car.create("Ford Focus");
		assertEquals(instanceOfCar.model(), "Ford Focus");
		assertEquals(instanceOfCar.numWheels(), 4);
	}

	@Test
	public void isImmutable() {
		assertImmutable(Car.create("Ferrari").getClass());
	}
}

package com.github.grundlefleck;

import static org.junit.Assert.assertEquals;
import static org.mutabilitydetector.unittesting.AllowedReason.provided;
import static org.mutabilitydetector.unittesting.MutabilityAssert.assertImmutable;
import static org.mutabilitydetector.unittesting.MutabilityAssert.assertInstancesOf;
import static org.mutabilitydetector.unittesting.MutabilityMatchers.areImmutable;

import org.junit.Test;
import org.mutabilitydetector.unittesting.AllowedReason;
import org.mutabilitydetector.unittesting.MutabilityAssert;
import org.mutabilitydetector.unittesting.MutabilityMatchers;

public class CarTest {

	@Test
	public void testRecompilationWithNewProperties() {
		// Not the kind of tests you would normally write,
		// included here just to see how the IDE handles changes.
		Car instanceOfCar = Car.create("Ford Focus");
		assertEquals(instanceOfCar.model(), "Ford Focus");
		assertEquals(instanceOfCar.numWheels(), 4);
	}

	@Test
	public void isImmutable() {
        assertInstancesOf(Car.create("Ferrari").getClass(), areImmutable(), provided(Registration.class).isAlsoImmutable());
	}
}

Make tests pass by assuming Registration class is also immutable.


package net.greghaines.arithmeticparser.js;

import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;

import net.greghaines.arithmeticparser.ArithmeticParser;

/**
 * An implementation that uses Java's built-in JavaScript parser to evaluate the expression.
 *
 * @author Greg Haines
 */
public class JavaScriptArithmeticParser implements ArithmeticParser {

    /**
     * {@inheritDoc}
     */
    @Override
    public double evaluate(final String expression) {
        final double result;
        try {
            final ScriptEngineManager factory = new ScriptEngineManager();
            final ScriptEngine engine = factory.getEngineByName("JavaScript");
            final Object resultObj = engine.eval(expression);
            if (resultObj instanceof Number) {
                result = ((Number) resultObj).doubleValue();
            } else if (resultObj instanceof String) {
                result = Double.parseDouble((String) resultObj);
            } else {
                throw new IllegalStateException("Unknown return type: " + resultObj);
            }
        } catch (ScriptException se) {
            throw new RuntimeException(se);
        }
        return result;
    }
}

package net.greghaines.arithmeticparser.js;

import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;

import net.greghaines.arithmeticparser.ArithmeticParser;

/**
 * An implementation that uses Java's built-in JavaScript parser to evaluate the expression.
 *
 * @author Greg Haines
 */
public class JavaScriptArithmeticParser implements ArithmeticParser {

    private final ScriptEngine engine;

    public JavaScriptArithmeticParser() {
        this("JavaScript");
    }

    public JavaScriptArithmeticParser(final String engineName) {
        this.engine = new ScriptEngineManager().getEngineByName(engineName);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public double evaluate(final String expression) {
        final double result;
        try {
            final Object resultObj = this.engine.eval(expression);
            if (resultObj instanceof Number) {
                result = ((Number) resultObj).doubleValue();
            } else if (resultObj instanceof String) {
                result = Double.parseDouble((String) resultObj);
            } else {
                throw new IllegalStateException("Unknown return type: " + resultObj);
            }
        } catch (ScriptException se) {
            throw new RuntimeException(se);
        }
        return result;
    }
}

Tweak the JavaScript implementation for ~4x faster execution.


//@@author A0142255M
package guitests;

import org.junit.Test;

import seedu.tache.commons.core.Messages;

public class ResultDisplayTest extends TaskManagerGuiTest {

    @Test
    public void resultDisplay_blankOnStartup_success() {
        assertResultMessage("");
    }

    @Test
    public void resultDisplay_unknownCommand_failure() {
        commandBox.runCommand("yutyfcydvchui");
        assertResultMessage(Messages.MESSAGE_UNKNOWN_COMMAND);

        commandBox.runCommand("");
        assertResultMessage(Messages.MESSAGE_INVALID_COMMAND_FORMAT);
    }

}

//@@author A0142255M
package guitests;

import static seedu.tache.commons.core.Messages.MESSAGE_INVALID_COMMAND_FORMAT;

import org.junit.Test;

import seedu.tache.commons.core.Messages;
import seedu.tache.logic.commands.HelpCommand;

public class ResultDisplayTest extends TaskManagerGuiTest {

    @Test
    public void resultDisplay_blankOnStartup_success() {
        assertResultMessage("");
    }

    @Test
    public void resultDisplay_unknownCommand_failure() {
        commandBox.runCommand("yutyfcydvchui");
        assertResultMessage(Messages.MESSAGE_UNKNOWN_COMMAND);

        commandBox.runCommand("");
        assertResultMessage(String.format(MESSAGE_INVALID_COMMAND_FORMAT, HelpCommand.MESSAGE_USAGE));
    }

}

Fix JUnit result display test


package org.jongo;

import org.bson.types.ObjectId;
import org.jongo.model.Friend;
import org.jongo.util.JongoTestCase;
import org.jongo.util.MongoInMemoryRule;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;

import java.util.Iterator;

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

public class FindWithHintTest extends JongoTestCase {

    @Rule
    public static final MongoInMemoryRule mongo = new MongoInMemoryRule();

    private MongoCollection collection;

    @Before
    public void setUp() throws Exception {
        collection = createEmptyCollection("friends");
    }

    @After
    public void tearDown() throws Exception {
        dropCollection("friends");
    }

    @Test
    public void canFindWithHint() throws Exception {
        /* given */
        Friend john = new Friend(new ObjectId(), "John");
        collection.save(john);

        Friend noName = new Friend(new ObjectId(), null);
        collection.save(noName);

        collection.ensureIndex("{name: 1}", "{sparse: true}");

        /* when */
        Iterator<Friend> friends = collection.find("{name: null}").hint("{name: 1}").as(Friend.class).iterator();

        /* then */
        assertThat(friends.hasNext()).isFalse();
    }

}

package org.jongo;

import org.bson.types.ObjectId;
import org.jongo.model.Friend;
import org.jongo.util.JongoTestCase;
import org.jongo.util.MongoInMemoryRule;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;

import java.util.Iterator;

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

public class FindWithHintTest extends JongoTestCase {

    @Rule
    public static final MongoInMemoryRule mongo = new MongoInMemoryRule();

    private MongoCollection collection;

    @Before
    public void setUp() throws Exception {
        collection = createEmptyCollection("friends");
    }

    @After
    public void tearDown() throws Exception {
        dropCollection("friends");
    }

    @Test
    public void canFindWithHint() throws Exception {
        /* given */
        Friend noName = new Friend(new ObjectId(), null);
        collection.save(noName);

        collection.ensureIndex("{name: 1}", "{sparse: true}");

        /* when */
        // force to use _id index instead of name index which is sparsed
        Iterator<Friend> friends = collection.find().hint("{$natural: 1}").sort("{name: 1}").as(Friend.class).iterator();

        /* then */
        assertThat(friends.hasNext()).isTrue();
    }

}

Update of a test to really show an use of hint method.


/**
 *
 */
package gov.nih.nci.security.acegi.csm.authorization;

/**
 * @author Joshua Phillips
 *
 */
public class AuthorizationSwitch {

	private boolean on = true;

	public boolean isOn() {
		return on;
	}

	public void setOn(boolean on) {
		this.on = on;
	}

}

/**
 *
 */
package gov.nih.nci.security.acegi.csm.authorization;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * @author Joshua Phillips
 * @author Rhett Sutphin
 */
public class AuthorizationSwitch {
    private static final Log log = LogFactory.getLog(AuthorizationSwitch.class);

    private boolean on = true;

    public AuthorizationSwitch() {
        if (log.isDebugEnabled()) log.debug(this + " created");
    }

    public boolean isOn() {
        return on;
    }

    public void setOn(boolean on) {
        if (log.isDebugEnabled()) log.debug(this + " turned " + (on ? "on" : "off"));
        this.on = on;
    }

    @Override
    public String toString() {
        return new StringBuilder(getClass().getSimpleName()).append("[0x")
            .append(System.identityHashCode(this)).append(']').toString();
    }
}

Add debug output for tracking state changes


package com.clearspring.thetan.metricCatcher;

import com.yammer.metrics.core.CounterMetric;
import com.yammer.metrics.core.GaugeMetric;
import com.yammer.metrics.core.HistogramMetric;
import com.yammer.metrics.core.MeterMetric;
import com.yammer.metrics.core.TimerMetric;

public enum MetricType {
    GAUGE ("gauge", GaugeMetric.class),
    COUNTER ("counter", CounterMetric.class),
    METER ("meter", MeterMetric.class),
    HISTOGRAM ("histogram", HistogramMetric.class),
    TIMER ("timer", TimerMetric.class);

    private String name;
    private Class<?> klass;

    MetricType(String name, Class<?> className) {
        this.name = name;
        this.klass = className;
    }

    public String getName() {
        return name;
    }

    public Class<?> getKlass() {
        return klass;
    }

    public static MetricType fromName(String name) {
        if (name != null) {
            for (MetricType t : MetricType.values()) {
                if (t.name.equalsIgnoreCase(name))
                    return t;
            }
        }

        return null;
    }
}

package com.clearspring.thetan.metricCatcher;

import com.yammer.metrics.core.CounterMetric;
import com.yammer.metrics.core.GaugeMetric;
import com.yammer.metrics.core.HistogramMetric;
import com.yammer.metrics.core.MeterMetric;
import com.yammer.metrics.core.TimerMetric;

public enum MetricType {
    GAUGE ("gauge", GaugeMetric.class),
    COUNTER ("counter", CounterMetric.class),
    METER ("meter", MeterMetric.class),
    HISTOGRAM_BIASED ("biased", HistogramMetric.class),
    HISTOGRAM_UNIFORM ("uniform", HistogramMetric.class),
    TIMER ("timer", TimerMetric.class);

    private String name;
    private Class<?> klass;

    MetricType(String name, Class<?> className) {
        this.name = name;
        this.klass = className;
    }

    public String getName() {
        return name;
    }

    public Class<?> getKlass() {
        return klass;
    }

    public static MetricType fromName(String name) {
        if (name != null) {
            for (MetricType t : MetricType.values()) {
                if (t.name.equalsIgnoreCase(name))
                    return t;
            }
        }

        return null;
    }
}

Use proper names for histograms