package org.imos.ddb;

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

import net.ucanaccess.jdbc.JackcessOpenerInterface;
//imports from Jackcess Encrypt
import com.healthmarketscience.jackcess.CryptCodecProvider;
import com.healthmarketscience.jackcess.Database;
import com.healthmarketscience.jackcess.DatabaseBuilder;

public class CryptCodecOpener implements JackcessOpenerInterface {
  public Database open(File fl,String pwd) throws IOException {
   DatabaseBuilder dbd =new DatabaseBuilder(fl);
   dbd.setAutoSync(true);
   dbd.setCodecProvider(new CryptCodecProvider(pwd));
   dbd.setReadOnly(false);
   return dbd.open();

  }
  //Notice that the parameter setting autosync =true is recommended with UCanAccess for performance reasons.
  //UCanAccess flushes the updates to disk at transaction end.
  //For more details about autosync parameter (and related tradeoff), see the Jackcess documentation.
}

package org.imos.ddb;

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

import net.ucanaccess.jdbc.JackcessOpenerInterface;
//imports from Jackcess Encrypt
import com.healthmarketscience.jackcess.CryptCodecProvider;
import com.healthmarketscience.jackcess.Database;
import com.healthmarketscience.jackcess.DatabaseBuilder;

public class CryptCodecOpener implements JackcessOpenerInterface {
  public Database open(File fl,String pwd) throws IOException {
   DatabaseBuilder dbd =new DatabaseBuilder(fl);
   dbd.setAutoSync(true);
   dbd.setCodecProvider(new CryptCodecProvider(pwd));
   dbd.setReadOnly(true);
   return dbd.open();

  }
  //Notice that the parameter setting autosync =true is recommended with UCanAccess for performance reasons.
  //UCanAccess flushes the updates to disk at transaction end.
  //For more details about autosync parameter (and related tradeoff), see the Jackcess documentation.
}

Set ddb connection to readonly to get rid of the warning message


package test;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Consumer;

public class TypeParameterBoundExample {
    // extends Runnable produces T::List signature, so
    // @Nullable targets index=1 (optional class bound always counts)
    public static class ListConsumer<T extends @Nullable List<?>>
            implements Consumer<T> {
        @Override
        public void accept(T t) {
        }
    }

    // extends Runnable produces T:ArrayList signature since ArrayList is class
    public static class ArrayListConsumer<T extends @Nullable ArrayList<?>>
            implements Consumer<T> {
        @Override
        public void accept(T t) {
        }
    }

    // extends Runnable produces T:ArrayList signature since ArrayList is class
    public static class SerializableListConsumer<T extends @Nullable List<?> & @Untainted Serializable>
            implements Consumer<T> {
        @Override
        public void accept(T t) {
        }
    }

    // extends Runnable produces T:ArrayList signature since ArrayList is class
    public static class SerializableListConsumerDoubleA<T extends @Nullable @Untainted List<?> & @Untainted Serializable>
            implements Consumer<T> {
        @Override
        public void accept(T t) {
        }
    }
}

package test;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Consumer;
import java.util.function.Supplier;

public class TypeParameterBoundExample {
    // extends Runnable produces T::List signature, so
    // @Nullable targets index=1 (optional class bound always counts)
    public static class ListConsumer<T extends @Nullable List<?>>
            implements Consumer<T> {
        @Override
        public void accept(T t) {
        }
    }

    // extends Runnable produces T:ArrayList signature since ArrayList is class
    public static class ArrayListConsumer<T extends @Nullable ArrayList<?>>
            implements Consumer<T> {
        @Override
        public void accept(T t) {
        }
    }

    // extends Runnable produces T:ArrayList signature since ArrayList is class
    public static class SerializableListConsumer<T extends @Nullable List<?> & @Untainted Serializable>
            implements Consumer<T> {
        @Override
        public void accept(T t) {
        }
    }

    // extends Runnable produces T:ArrayList signature since ArrayList is class
    public static class SerializableListConsumerDoubleA<T extends @Nullable @Untainted List<?> & @Untainted Serializable>
            implements Consumer<T> {
        @Override
        public void accept(T t) {
        }
    }

    public static class IteratorSupplier implements Supplier<Consumer<@Nullable Object[]>> {
        @Override
        public Consumer<@Nullable Object[]> get() {
            return new Consumer<@Nullable Object[]>() {
                @Override
                public void accept(@Nullable Object[] objects) {
                }
            };
        }
    }
}

Add cless extends type param example


/*
 * Copyright (C) 2009-2011 Mathias Doenitz
 *
 * 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.parboiled.errors;

/**
 * Exception that is thrown for any problem during the parsing run that cannot be overcome automatically.
 */
public class ParserRuntimeException extends RuntimeException {

    public ParserRuntimeException() {
    }

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

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

    public ParserRuntimeException(String message, Object... messageArgs) {
        super(String.format(message, messageArgs));
    }

    public ParserRuntimeException(Throwable cause, String message, Object... messageArgs) {
        super(String.format(message, messageArgs), cause);
    }

    public ParserRuntimeException(Throwable cause) {
        super(cause);
    }

}

/*
 * Copyright (C) 2009-2011 Mathias Doenitz
 *
 * 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.parboiled.errors;

/**
 * Exception that is thrown for any problem during the parsing run that cannot be overcome automatically.
 */
public class ParserRuntimeException extends RuntimeException {

    public ParserRuntimeException() {
    }

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

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

    public ParserRuntimeException(String message, Object... messageArgs) {
        super(String.format(message, messageArgs));
    }

    public ParserRuntimeException(Throwable cause, String message, Object... messageArgs) {
        super(messageArgs.length > 0 ? String.format(message, messageArgs) : message, cause);
    }

    public ParserRuntimeException(Throwable cause) {
        super(cause);
    }

}

Fix MissingFormatArgumentException in ParseRuntimeException when args array is empty


package net.md_5.specialsource;

import com.google.common.base.Joiner;

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

public class InheritanceMap {

    private final Map<String, ArrayList<String>> inheritanceMap = new HashMap<String, ArrayList<String>>();

    public void generate(List<IInheritanceProvider> inheritanceProviders, Collection<String> classes) {
        for (String className : classes) {
            ArrayList<String> parents = getParents(inheritanceProviders, className);

            if (parents == null) {
                System.out.println("No inheritance information found for "+className);
            } else {
                inheritanceMap.put(className, parents);
            }
        }
    }

    private ArrayList<String> getParents(List<IInheritanceProvider> inheritanceProviders, String className) {
        for (IInheritanceProvider inheritanceProvider : inheritanceProviders) {
            // // ask each provider for inheritance information on the class, until one responds
            // TODO: refactor with JarRemapper tryClimb?
            List<String> parents = inheritanceProvider.getParents(className);

            if (parents != null) {
                return (ArrayList<String>) parents;
            }
        }

        return null;
    }

    public void save(PrintWriter writer) {
        for (String className : inheritanceMap.keySet()) {
            writer.print(className);
            writer.print(' ');

            List<String> parents = inheritanceMap.get(className);
            writer.println(Joiner.on(' ').join(parents));
        }
    }
}

package net.md_5.specialsource;

import com.google.common.base.Joiner;

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

public class InheritanceMap {

    private final Map<String, ArrayList<String>> inheritanceMap = new HashMap<String, ArrayList<String>>();

    public void generate(List<IInheritanceProvider> inheritanceProviders, Collection<String> classes) {
        for (String className : classes) {
            ArrayList<String> parents = getParents(inheritanceProviders, className);

            if (parents == null) {
                System.out.println("No inheritance information found for "+className);
            } else {
                inheritanceMap.put(className, parents);
            }
        }
    }

    private ArrayList<String> getParents(List<IInheritanceProvider> inheritanceProviders, String className) {
        for (IInheritanceProvider inheritanceProvider : inheritanceProviders) {
            // // ask each provider for inheritance information on the class, until one responds
            // TODO: refactor with JarRemapper tryClimb?
            List<String> parents = inheritanceProvider.getParents(className);

            if (parents != null) {
                return (ArrayList<String>) parents;
            }
        }

        return null;
    }

    public void save(PrintWriter writer) {
        List<String> classes = new ArrayList<String>(inheritanceMap.keySet());
        Collections.sort(classes);

        for (String className : classes) {
            writer.print(className);
            writer.print(' ');

            List<String> parents = inheritanceMap.get(className);
            writer.println(Joiner.on(' ').join(parents));
        }
    }
}

Sort inheritance map written to file


/*
 * Copyright (c) 2002-2003 by OpenSymphony
 * All rights reserved.
 */
package com.opensymphony.workflow;

import com.opensymphony.workflow.basic.BasicWorkflow;
import com.opensymphony.workflow.config.ConfigLoader;

import java.net.URL;

/**
 * @author Hani Suleiman (hani@formicary.net)
 * Date: May 10, 2003
 * Time: 1:36:21 PM
 */
public class TestWorkflow extends BasicWorkflow {
    //~ Static fields/initializers /////////////////////////////////////////////

    public static String configFile = "/osworkflow.xml";

    //~ Constructors ///////////////////////////////////////////////////////////

    public TestWorkflow(String caller) {
        super(caller);
    }

    //~ Methods ////////////////////////////////////////////////////////////////

    protected void loadConfig(URL url) throws FactoryException {
        if (url == null) {
            ConfigLoader.load(getClass().getResourceAsStream(configFile));
        }
    }
}

/*
 * Copyright (c) 2002-2003 by OpenSymphony
 * All rights reserved.
 */
package com.opensymphony.workflow;

import com.opensymphony.workflow.basic.BasicWorkflow;
import com.opensymphony.workflow.config.ConfigLoader;
import com.opensymphony.workflow.spi.StoreFactory;

import java.net.URL;

/**
 * @author Hani Suleiman (hani@formicary.net)
 * Date: May 10, 2003
 * Time: 1:36:21 PM
 */
public class TestWorkflow extends BasicWorkflow {
    //~ Static fields/initializers /////////////////////////////////////////////

    public static String configFile = "/osworkflow.xml";

    //~ Constructors ///////////////////////////////////////////////////////////

    public TestWorkflow(String caller) {
        super(caller);

        //lets clear out the old store
        StoreFactory.clearCache();
    }

    //~ Methods ////////////////////////////////////////////////////////////////

    protected void loadConfig(URL url) throws FactoryException {
        if (url == null) {
            ConfigLoader.load(getClass().getResourceAsStream(configFile));
        }
    }
}

Clear old store instance on ctor


package javalin.examples;

import org.eclipse.jetty.server.Connector;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.ServerConnector;
import org.eclipse.jetty.util.ssl.SslContextFactory;

import javalin.Javalin;
import javalin.embeddedserver.EmbeddedServer;
import javalin.embeddedserver.jetty.EmbeddedJettyFactory;

public class HelloWorldSecure {

    public static void main(String[] args) {
        Javalin.create()
            .embeddedServer(new EmbeddedJettyFactory(() -> {
                Server server = new Server();
                ServerConnector sslConnector = new ServerConnector(server, getSslContextFactory());
                sslConnector.setPort(443);
                ServerConnector connector = new ServerConnector(server);
                connector.setPort(80);
                server.setConnectors(new Connector[] {sslConnector, connector});
                return server;
            }))
            .get("/", (req, res) -> res.body("Hello World")); // valid endpoint for both connectors
    }

    private static SslContextFactory getSslContextFactory() {
        SslContextFactory sslContextFactory = new SslContextFactory();
        sslContextFactory.setKeyStorePath(EmbeddedServer.class.getResource("/keystore.jks").toExternalForm());
        sslContextFactory.setKeyStorePassword("password");
        return sslContextFactory;
    }

}

package javalin.examples;

import org.eclipse.jetty.server.Connector;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.ServerConnector;
import org.eclipse.jetty.util.ssl.SslContextFactory;

import javalin.Javalin;
import javalin.embeddedserver.EmbeddedServer;
import javalin.embeddedserver.jetty.EmbeddedJettyFactory;

public class HelloWorldSecure {

    // This is a very basic example, a better one can be found at:
    // https://github.com/eclipse/jetty.project/blob/jetty-9.4.x/examples/embedded/src/main/java/org/eclipse/jetty/embedded/LikeJettyXml.java#L139-L163
    public static void main(String[] args) {
        Javalin.create()
            .embeddedServer(new EmbeddedJettyFactory(() -> {
                Server server = new Server();
                ServerConnector sslConnector = new ServerConnector(server, getSslContextFactory());
                sslConnector.setPort(443);
                ServerConnector connector = new ServerConnector(server);
                connector.setPort(80);
                server.setConnectors(new Connector[] {sslConnector, connector});
                return server;
            }))
            .get("/", (req, res) -> res.body("Hello World")); // valid endpoint for both connectors
    }

    private static SslContextFactory getSslContextFactory() {
        SslContextFactory sslContextFactory = new SslContextFactory();
        sslContextFactory.setKeyStorePath(EmbeddedServer.class.getResource("/keystore.jks").toExternalForm());
        sslContextFactory.setKeyStorePassword("password");
        return sslContextFactory;
    }

}

Add link to jetty ssl example


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

public final class KotlinConstants {

	// '^' is prepended to the regex in LICENSE_HEADER_DELIMITER later in FormatExtension.licenseHeader(String, String)
	public static final String LICENSE_HEADER_DELIMITER = "(package |@file)";

	private KotlinConstants() {}
}

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

public final class KotlinConstants {

	// '^' is prepended to the regex in LICENSE_HEADER_DELIMITER later in FormatExtension.licenseHeader(String, String)
	public static final String LICENSE_HEADER_DELIMITER = "(package |@file|import )";

	private KotlinConstants() {}
}

Support adding license header for classes without package name


package leetcode;

public class Problem55 {
    public boolean canJump(int[] nums) {
        if (nums.length == 1) {
            return true;
        }
        for (int i = 0; i < nums.length; i++) {
            if (canJump(nums, i)) {
                return true;
            }
        }
        return false;
    }

    private boolean canJump(int[] nums, int idx) {
        int i = idx;
        while (i < nums.length) {
            if (nums[i] == 0) {
                return false;
            }
            int val = (nums.length-1) - i - nums[i];
            if (val == 0) {
                return true;
            }
            i += nums[i];
        }
        return false;
    }

    public static void main(String[] args) {
        Problem55 prob = new Problem55();
        System.out.println(prob.canJump(new int[]{2,3,1,1,4}));
        System.out.println(prob.canJump(new int[]{3,2,1,0,4}));
        System.out.println(prob.canJump(new int[]{2,0}));
        System.out.println(prob.canJump(new int[]{0}));
    }
}

package leetcode;

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

public class Problem55 {
    public boolean canJump(int[] nums) {
        Stack<Integer> stack = new Stack<>();
        Set<Integer> set = new HashSet<>();
        stack.add(0);
        while (!stack.isEmpty()) {
            int idx = stack.pop();
            if (idx == nums.length-1) {
                return true;
            }
            int val = nums[idx];
            for (int i = idx+1; i <= idx+val; i++) {
                if (i == nums.length-1) {
                    return true;
                }
                if (set.contains(i)) {
                    continue;
                }
                set.add(i);
                stack.push(i);
            }
        }
        return false;
    }

    public static void main(String[] args) {
        Problem55 prob = new Problem55();
        System.out.println(prob.canJump(new int[]{2,3,1,1,4})); // true
        System.out.println(prob.canJump(new int[]{3,2,1,0,4})); // false
        System.out.println(prob.canJump(new int[]{2,0})); // true
        System.out.println(prob.canJump(new int[]{0})); // true
        System.out.println(prob.canJump(new int[]{0,2,3})); // false
        System.out.println(prob.canJump(new int[]{1,0,1,0})); // false
    }
}

Update problem 55 (stil TLE)


package com.litle.sdk.samples;
import com.litle.sdk.*;
import com.litle.sdk.generate.AccountUpdateFileRequestData;
import com.litle.sdk.generate.RFRRequest;
import java.util.Calendar;
public class RfrLitleExample {
    public static void main(String[] args) {
        String merchantId = "0180";
        String requestFileName = "litleSdk-testRFRFile-fileConfigSFTP.xml";
        RFRRequest rfrRequest = new RFRRequest();
        AccountUpdateFileRequestData data = new AccountUpdateFileRequestData();
        data.setMerchantId(merchantId);
        data.setPostDay(Calendar.getInstance());
        rfrRequest.setAccountUpdateFileRequestData(data);

        LitleRFRFileRequest request = new LitleRFRFileRequest(requestFileName, rfrRequest);
        try{
            LitleRFRFileResponse response = request.sendToLitleSFTP();
            String message=response.getLitleRFRResponse().getRFRResponseMessage();
        }
        catch(Exception e){
        }
    }
}

package com.litle.sdk.samples;
import com.litle.sdk.*;
import com.litle.sdk.generate.AccountUpdateFileRequestData;
import com.litle.sdk.generate.RFRRequest;
import java.util.Calendar;
public class RfrLitleExample {
    public static void main(String[] args) {
        String preliveStatus = System.getenv("preliveStatus");

        if(preliveStatus != null && preliveStatus.equalsIgnoreCase("down")){
            return;
        }

        String merchantId = "0180";
        String requestFileName = "litleSdk-testRFRFile-fileConfigSFTP.xml";
        RFRRequest rfrRequest = new RFRRequest();
        AccountUpdateFileRequestData data = new AccountUpdateFileRequestData();
        data.setMerchantId(merchantId);
        data.setPostDay(Calendar.getInstance());
        rfrRequest.setAccountUpdateFileRequestData(data);

        LitleRFRFileRequest request = new LitleRFRFileRequest(requestFileName, rfrRequest);
        try{
            LitleRFRFileResponse response = request.sendToLitleSFTP();
            String message=response.getLitleRFRResponse().getRFRResponseMessage();
        }
        catch(Exception e){
        }
    }
}

Change sample using sftp to not run if prelive is down


package com.saintsrobotics.frc.commands.autonomous;

import com.saintsrobotics.frc.commands.ResetShootBall;
import com.saintsrobotics.frc.commands.ShootBall;
import edu.wpi.first.wpilibj.command.CommandGroup;

/**
 * The basic autonomous command.
 * @author Saints Robotics
 */
public class BasicAutonomous extends CommandGroup {
    private static final double DRIVE_SECONDS = 1.0;

    public BasicAutonomous() {
        // Move forward to lower pickup
        addSequential(new MoveIntoZone(DRIVE_SECONDS));

        // Shoot the preloaded ball!
        addSequential(new ShootBall());

        // Reset the shooter
        addSequential(new ResetShootBall());
    }
}

package com.saintsrobotics.frc.commands.autonomous;

import com.saintsrobotics.frc.commands.ResetShootBall;
import com.saintsrobotics.frc.commands.ShootBall;
import edu.wpi.first.wpilibj.command.CommandGroup;

/**
 * The basic autonomous command.
 * @author Saints Robotics
 */
public class BasicAutonomous extends CommandGroup {
    private static final double DRIVE_SECONDS = 2.0;

    public BasicAutonomous() {
        // Move forward to lower pickup
        addSequential(new MoveIntoZone(DRIVE_SECONDS));

        // Shoot the preloaded ball!
        addSequential(new ShootBall());

        // Reset the shooter
        addSequential(new ResetShootBall());
    }
}

Increase driving time during autonomous


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

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import at.ac.tuwien.inso.entity.Course;
import at.ac.tuwien.inso.service.CourseService;
import at.ac.tuwien.inso.service.StudentService;

@Controller
@RequestMapping("/student/register")
public class StudentRegisterForCourseController {

    @Autowired
    private CourseService courseService;

    @GetMapping
    private String registerStudent(@RequestParam Long courseId,
                                   RedirectAttributes redirectAttributes) {
        Course course = courseService.findCourseWithId(courseId);
        if (courseService.registerStudentForCourse(course)) {
            redirectAttributes.addFlashAttribute("registeredForCourse", course.getSubject().getName());
            return "redirect:/student/courses";
        } else {
            redirectAttributes.addFlashAttribute("notRegisteredForCourse", course.getSubject().getName());
            return "redirect:/student/courses";
        }

    }

}

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

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import at.ac.tuwien.inso.entity.Course;
import at.ac.tuwien.inso.service.CourseService;

@Controller
@RequestMapping("/student/register")
public class StudentRegisterForCourseController {

    @Autowired
    private CourseService courseService;

    @GetMapping
    private String registerStudent(@RequestParam Long courseId,
                                   RedirectAttributes redirectAttributes) {
        Course course = courseService.findCourseWithId(courseId);
        if (courseService.registerStudentForCourse(course)) {
            redirectAttributes.addFlashAttribute("registeredForCourse", course.getSubject().getName());
            return "redirect:/student/courses";
        } else {
            redirectAttributes.addFlashAttribute("notRegisteredForCourse", course.getSubject().getName());
            return "redirect:/student/courses";
        }

    }

}

Refactor - remove unused imports


package io.fotoapparat.parameter.selector;

import io.fotoapparat.parameter.range.Range;

/**
 * Selector functions for sensor sensitivity (ISO).
 */
public class SensorSensitivitySelectors {

    /**
     * @param iso the specified ISO value
     * @return {@link SelectorFunction} which selects the specified ISO value.
     *         If there is no specified value - selects default ISO value.
     */
    public static SelectorFunction<Range<Integer>, Integer> manualSensorSensitivity(final int iso) {
        return new SelectorFunction<Range<Integer>, Integer>() {
            @Override
            public Integer select(Range<Integer> sensorSensitivityCapability) {
                if(sensorSensitivityCapability.contains(iso)) {
                    return iso;
                } else {
                    return null;
                }
            }
        };
    }

    /**
     * @return {@link SelectorFunction} which selects highest ISO value.
     */
    public static SelectorFunction<Range<Integer>, Integer> highestSensorSensitivity() {
        return new SelectorFunction<Range<Integer>, Integer>() {
            @Override
            public Integer select(Range<Integer> sensorSensitivityCapability) {
                return sensorSensitivityCapability.highest();
            }
        };
    }

    /**
     * @return {@link SelectorFunction} which selects lowest ISO value.
     */
    public static SelectorFunction<Range<Integer>, Integer> lowestSensorSensitivity() {
        return new SelectorFunction<Range<Integer>, Integer>() {
            @Override
            public Integer select(Range<Integer> sensorSensitivityCapability) {
                return sensorSensitivityCapability.lowest();
            }
        };
    }

    /**
     * @return {@link SelectorFunction} which selects default ISO value.
     */
    public static SelectorFunction<Range<Integer>,Integer> automaticSensorSensitivity() {
        return new SelectorFunction<Range<Integer>, Integer>() {
            @Override
            public Integer select(Range<Integer> integerRange) {
                return null;
            }
        };
    }
}

package io.fotoapparat.parameter.selector;

import io.fotoapparat.parameter.range.Range;

/**
 * Selector functions for sensor sensitivity (ISO).
 */
public class SensorSensitivitySelectors {

    /**
     * @param iso the specified ISO value
     * @return {@link SelectorFunction} which selects the specified ISO value.
     *         If there is no specified value - selects default ISO value.
     */
    public static SelectorFunction<Range<Integer>, Integer> manualSensorSensitivity(final int iso) {
        return new SelectorFunction<Range<Integer>, Integer>() {
            @Override
            public Integer select(Range<Integer> sensorSensitivityCapability) {
                if(sensorSensitivityCapability.contains(iso)) {
                    return iso;
                } else {
                    return null;
                }
            }
        };
    }

    /**
     * @return {@link SelectorFunction} which selects highest ISO value.
     */
    public static SelectorFunction<Range<Integer>, Integer> highestSensorSensitivity() {
        return new SelectorFunction<Range<Integer>, Integer>() {
            @Override
            public Integer select(Range<Integer> sensorSensitivityCapability) {
                return sensorSensitivityCapability.highest();
            }
        };
    }

    /**
     * @return {@link SelectorFunction} which selects lowest ISO value.
     */
    public static SelectorFunction<Range<Integer>, Integer> lowestSensorSensitivity() {
        return new SelectorFunction<Range<Integer>, Integer>() {
            @Override
            public Integer select(Range<Integer> sensorSensitivityCapability) {
                return sensorSensitivityCapability.lowest();
            }
        };
    }
}

Remove useless SelectorFunction for ISO


package org.bouncycastle.asn1;

import java.util.Vector;

/**
 * a general class for building up a vector of DER encodable objects -
 * this will eventually be superceded by ASN1EncodableVector so you should
 * use that class in preference.
 */
public class DEREncodableVector
{
    private Vector  v = new Vector();

    /**
     * @deprecated use ASN1EncodableVector instead.
     */
    public DEREncodableVector()
    {

    }

    public void add(
        DEREncodable   obj)
    {
        v.addElement(obj);
    }

    public DEREncodable get(
        int i)
    {
        return (DEREncodable)v.elementAt(i);
    }

    public int size()
    {
        return v.size();
    }
}

package org.bouncycastle.asn1;

import java.util.Vector;

/**
 * a general class for building up a vector of DER encodable objects -
 * this will eventually be superceded by ASN1EncodableVector so you should
 * use that class in preference.
 */
public class DEREncodableVector
{
    Vector v = new Vector();

    /**
     * @deprecated use ASN1EncodableVector instead.
     */
    public DEREncodableVector()
    {

    }

    public void add(
        DEREncodable   obj)
    {
        v.addElement(obj);
    }

    public DEREncodable get(
        int i)
    {
        return (DEREncodable)v.elementAt(i);
    }

    public int size()
    {
        return v.size();
    }
}

Allow package access to the internal vector


package org.usfirst.frc.team2503.r2016;

import edu.wpi.first.wpilibj.DigitalInput;
import edu.wpi.first.wpilibj.Spark;
import edu.wpi.first.wpilibj.SpeedController;
import edu.wpi.first.wpilibj.Talon;

public class Constants {

	public static final SpeedController leftTrackSpeedController = new Talon(0);
	public static final SpeedController rightTrackSpeedController = new Talon(1);
	public static final SpeedController shooterSpeedController = new Spark(2);
	public static final SpeedController winchSpeedController = new Spark(3);
	public static final SpeedController hookerSpeedController = new Talon(4);

	public static final DigitalInput leftTrackEncoderAChannel = new DigitalInput(0);
	public static final DigitalInput leftTrackEncoderBChannel = new DigitalInput(1);
	public static final DigitalInput rightTrackEncoderAChannel = new DigitalInput(2);
	public static final DigitalInput rightTrackEncoderBChannel = new DigitalInput(3);
	public static final DigitalInput intakeDigitalInput = new DigitalInput(4);

}

package org.usfirst.frc.team2503.r2016;

import edu.wpi.first.wpilibj.DigitalInput;
import edu.wpi.first.wpilibj.Spark;
import edu.wpi.first.wpilibj.SpeedController;
import edu.wpi.first.wpilibj.Talon;

public class Constants {

	public static final SpeedController leftTrackSpeedController = new Talon(0);
	public static final SpeedController rightTrackSpeedController = new Talon(1);
	public static final SpeedController shooterSpeedController = new Spark(2);
	public static final SpeedController winchSpeedController = new Talon(3);
	public static final SpeedController hookerSpeedController = new Talon(4);

	public static final DigitalInput leftTrackEncoderAChannel = new DigitalInput(0);
	public static final DigitalInput leftTrackEncoderBChannel = new DigitalInput(1);
	public static final DigitalInput rightTrackEncoderAChannel = new DigitalInput(2);
	public static final DigitalInput rightTrackEncoderBChannel = new DigitalInput(3);
	public static final DigitalInput intakeDigitalInput = new DigitalInput(4);

}

Switch Winch speed controller from Spark to Talon


package ca.uhnresearch.pughlab.tracker.restlets;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.restlet.Component;
import org.restlet.Request;
import org.restlet.Response;
import org.restlet.Restlet;
import org.restlet.data.ChallengeResponse;
import org.restlet.data.ChallengeScheme;
import org.restlet.security.Authenticator;
import org.restlet.security.User;

public class CustomSpringSessionAuthenticator extends Authenticator {

	public CustomSpringSessionAuthenticator(Component component) {
		super(component.getContext());
	}

    public CustomSpringSessionAuthenticator(Restlet parent) {
        super(parent.getContext());
    }

	@Override
	protected boolean authenticate(Request request, Response response) {

		Subject currentUser = SecurityUtils.getSubject();

		if (currentUser == null) {
			throw new IllegalStateException("Invalid subject: SecurityUtils.getSubject returned null");
		}

		Object principal = currentUser.getPrincipals().getPrimaryPrincipal();
		if (principal != null) {
			User user = new User(principal.toString());
			request.getClientInfo().setUser(user);

			ChallengeResponse challenge = new ChallengeResponse(ChallengeScheme.CUSTOM);
			challenge.setIdentifier(user.getIdentifier());
			request.setChallengeResponse(challenge);
			return true;

		} else {
			return false;
		}
	}
}

package ca.uhnresearch.pughlab.tracker.restlets;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.restlet.Component;
import org.restlet.Request;
import org.restlet.Response;
import org.restlet.Restlet;
import org.restlet.data.ChallengeResponse;
import org.restlet.data.ChallengeScheme;
import org.restlet.security.Authenticator;
import org.restlet.security.User;

public class CustomSpringSessionAuthenticator extends Authenticator {

	public CustomSpringSessionAuthenticator(Component component) {
		super(component.getContext());
	}

    public CustomSpringSessionAuthenticator(Restlet parent) {
        super(parent.getContext());
    }

	@Override
	protected boolean authenticate(Request request, Response response) {

		Subject currentUser = SecurityUtils.getSubject();

		if (currentUser == null) {
			throw new IllegalStateException("Invalid subject: SecurityUtils.getSubject() returned null");
		}

		// If we have no principals, we're not authenticated
		PrincipalCollection principals = currentUser.getPrincipals();
		if (principals == null) {
			return false;
		}

		Object principal = principals.getPrimaryPrincipal();
		if (principal != null) {
			User user = new User(principal.toString());
			request.getClientInfo().setUser(user);

			ChallengeResponse challenge = new ChallengeResponse(ChallengeScheme.CUSTOM);
			challenge.setIdentifier(user.getIdentifier());
			request.setChallengeResponse(challenge);
			return true;

		} else {
			return false;
		}
	}
}

Handle absence of authentication more sensibly, without an NPE


package net.minecraftforge.common;

public enum Orientation
{
    /** -Y */
    DOWN,

    /** +Y */
    UP,

    /** -Z */
    NORTH,

    /** +Z */
    SOUTH,

    /** -X */
    WEST,

    /** +X */
    EAST,

    /**
     * Used only by getOrientation, for invalid inputs
     */
    UNKNOWN;

    public static Orientation getOrientation(int id)
    {
        if (Orientation.values().length < id)
        {
            return Orientation.values()[id];
        }
        return UNKNOWN;
    }
}

package net.minecraftforge.common;

public enum Orientation
{
    /** -Y */
    DOWN,

    /** +Y */
    UP,

    /** -Z */
    NORTH,

    /** +Z */
    SOUTH,

    /** -X */
    WEST,

    /** +X */
    EAST,

    /**
     * Used only by getOrientation, for invalid inputs
     */
    UNKNOWN;

    public static Orientation getOrientation(int id)
    {
        if (id < Orientation.values().length)
        {
            return Orientation.values()[id];
        }
        return UNKNOWN;
    }
}

Fix oreientation bug causing levers not being able to place.


/* Class : JarOutputStream

  Implementation of the 1.2 Java class JarOutputStream.

  Copyright : Moses DeJong, dejong@cs.umn.edu, 1998.
  Source code licensed under the GPL.
  You can get a copy of the license from www.gnu.org.

  This code is intended for use in the Kaffe project but you can use
  it in other projects as long as you follow the license rules.
*/

package java.util.jar;

import java.io.*;
import java.util.zip.*;

public class JarOutputStream extends ZipOutputStream
{
    public JarOutputStream(OutputStream out, Manifest man) throws IOException
    {
	super(out);
	if (man != null) {
	    ZipEntry ze = new ZipEntry(JarFile.MANIFEST_NAME);
	    ze.setMethod(ZipEntry.DEFLATED); // compressed entry
	    putNextEntry(ze);
	    man.write(out);
	    closeEntry();
	}
    }

    public JarOutputStream(OutputStream out) throws IOException
    {
	super(out);
    }

    public void putNextEntry(ZipEntry ze) throws IOException
    {
	// FIXME : this method must be overridden for some reason.
	// It must do something extra that super.putNextEntry() does not.

	// so far I have been able to figure out that JarOutputStream
	// will use the ZipEntry.setExtra() method to add 4 bytes
	// of data. I have no idea what this data is but it seems to
	// be the same for both uncompressed and compressed archives.

	byte[] data = {-2,-54,0,0};
	ze.setExtra(data);

	super.putNextEntry(ze);
    }
}

/* Class : JarOutputStream

  Implementation of the 1.2 Java class JarOutputStream.

  Copyright : Moses DeJong, dejong@cs.umn.edu, 1998.
  Source code licensed under the GPL.
  You can get a copy of the license from www.gnu.org.

  This code is intended for use in the Kaffe project but you can use
  it in other projects as long as you follow the license rules.
*/

package java.util.jar;

import java.io.*;
import java.util.zip.*;

public class JarOutputStream extends ZipOutputStream {

    	public JarOutputStream(OutputStream out, Manifest manifest)
			throws IOException {
		super(out);
		if (manifest == null) {
			return;
		}
		JarEntry ent = new JarEntry(JarFile.MANIFEST_NAME);
		putNextEntry(ent);
		manifest.write(new OutputStream() {
			public void write(int b) throws IOException {
				JarOutputStream.this.write(b);
			}
			public void write(byte[] buf, int off, int len)
					throws IOException {
				JarOutputStream.this.write(buf, off, len);
			}
			public void flush() throws IOException {
				JarOutputStream.this.flush();
			}
		});
		closeEntry();
	}

	public JarOutputStream(OutputStream out) throws IOException {
		super(out);
	}

	// Why is this method here?
	public void putNextEntry(ZipEntry ze) throws IOException {
		super.putNextEntry(ze);
	}
}

Fix bug in writing out the Manifest to the JAR file.


/* -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- vim:set ts=4 sw=4 sts=4 et: */
package jp.oist.flint.rpc;

import com.sun.net.httpserver.HttpServer;
import java.io.IOException;
import java.net.BindException;
import java.net.InetSocketAddress;

public class Server {

    static final int PORT = 20465;

    private final HttpServer mHttpServer;

    public Server(ICallee callee) throws BindException, IOException {
        InetSocketAddress isa = new InetSocketAddress(PORT);
        mHttpServer = HttpServer.create(isa, 0); // use the default value for the socket backlog
        mHttpServer.createContext("/open-model", new OpenModelRequestHandler(callee));
        mHttpServer.createContext("/run", new RunRequestHandler(callee));
    }

    public void start() {
        mHttpServer.setExecutor(null); // create a default executor
        mHttpServer.start();

        Runtime.getRuntime().addShutdownHook(new Thread() {
             @Override
             public void run() {
                 mHttpServer.stop(0);
             }
        });
    }
}

/* -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- vim:set ts=4 sw=4 sts=4 et: */
package jp.oist.flint.rpc;

import com.sun.net.httpserver.HttpServer;
import java.io.IOException;
import java.net.BindException;
import java.net.InetAddress;
import java.net.InetSocketAddress;

public class Server {

    static final int PORT = 20465;

    private final HttpServer mHttpServer;

    public Server(ICallee callee) throws BindException, IOException {
        InetSocketAddress isa = new InetSocketAddress(InetAddress.getLoopbackAddress(), PORT);
        mHttpServer = HttpServer.create(isa, 0); // use the default value for the socket backlog
        mHttpServer.createContext("/open-model", new OpenModelRequestHandler(callee));
        mHttpServer.createContext("/run", new RunRequestHandler(callee));
    }

    public void start() {
        mHttpServer.setExecutor(null); // create a default executor
        mHttpServer.start();

        Runtime.getRuntime().addShutdownHook(new Thread() {
             @Override
             public void run() {
                 mHttpServer.stop(0);
             }
        });
    }
}

Allow connection from localhost only


package heufybot.core;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

import heufybot.utils.FileUtils;

public class Logger
{
	public static void log(String line, String target)
	{
		//Timestamp line
		DateFormat dateFormat = new SimpleDateFormat("[HH:mm]");
		Date date = new Date();
		line = dateFormat.format(date) + " " + line;

		//Output to console
		if(target.equals(""))
		{
			System.out.println(line);
		}
		else
		{
			System.out.println(target + " - " + line);
		}

		//Output to logfile
		FileUtils.writeFileAppend("test.log", line + "\n");
	}

	public static void log(String line)
	{
		log(line, "");
	}

	public static void error(String errorSource, String line)
	{
		System.err.println(errorSource + " - ERROR: " + line);
	}
}

package heufybot.core;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

import heufybot.utils.FileUtils;

public class Logger
{
	public static void log(String line, String target)
	{
		//Timestamp line
		DateFormat dateFormat = new SimpleDateFormat("[HH:mm]");
		Date date = new Date();

		//Output to console
		if(target.equals(""))
		{
			System.out.println(dateFormat.format(date) + " " + line);
		}
		else
		{
			System.out.println(dateFormat.format(date) + " " + target + " - " + line);
		}

		//Output to logfile
		FileUtils.writeFileAppend("test.log", line + "\n");
	}

	public static void log(String line)
	{
		log(line, "");
	}

	public static void error(String errorSource, String line)
	{
		System.err.println(errorSource + " - ERROR: " + line);
	}
}

Fix timestamps that got messed up by a change in the logging


/* Copyright 2017 Telstra Open Source
 *
 *   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.openkilda.northbound.messaging;

public interface MessageConsumer<T> {
    /**
     * Kafka message queue poll timeout.
     */
    int POLL_TIMEOUT = 10 * 1000;

    /**
     * Kafka message queue poll pause.
     */
    int POLL_PAUSE = 100;

    /**
     * Polls Kafka message queue.
     *
     * @param correlationId correlation id
     * @return received message
     */
    T poll(final String correlationId);

    /**
     * Clears message queue.
     */
    void clear();
}

/* Copyright 2017 Telstra Open Source
 *
 *   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.openkilda.northbound.messaging;

public interface MessageConsumer<T> {
    /**
     * Kafka message queue poll timeout.
     */
    int POLL_TIMEOUT = 120 * 1000;

    /**
     * Kafka message queue poll pause.
     */
    int POLL_PAUSE = 100;

    /**
     * Polls Kafka message queue.
     *
     * @param correlationId correlation id
     * @return received message
     */
    T poll(final String correlationId);

    /**
     * Clears message queue.
     */
    void clear();
}

Change NB timeout to 2 minutes, was 10 seconds


package com.phonegap.demo;

import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import android.content.Context;
import android.net.*;
import android.webkit.WebView;

public class NetworkManager {

	Context mCtx;
	WebView mView;
	ConnectivityManager sockMan;

	NetworkManager(Context ctx, WebView view)
	{
		mCtx = ctx;
		mView = view;
		sockMan = (ConnectivityManager) mCtx.getSystemService(Context.CONNECTIVITY_SERVICE);
	}

	public boolean isAvailable()
	{
		NetworkInfo info = sockMan.getActiveNetworkInfo();
		return info.isConnected();
	}

	public boolean isReachable(String uri)
	{
		boolean reached = true;
		try {
			DefaultHttpClient httpclient = new DefaultHttpClient();
			HttpGet httpget = new HttpGet(uri);
			httpclient.execute(httpget);
		} catch (Exception e) { reached = false;}
		return reached;
	}

}

package com.phonegap.demo;

import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import android.content.Context;
import android.net.*;
import android.webkit.WebView;

public class NetworkManager {

	Context mCtx;
	WebView mView;
	ConnectivityManager sockMan;

	NetworkManager(Context ctx, WebView view)
	{
		mCtx = ctx;
		mView = view;
		sockMan = (ConnectivityManager) mCtx.getSystemService(Context.CONNECTIVITY_SERVICE);
	}

	public boolean isAvailable()
	{
		NetworkInfo info = sockMan.getActiveNetworkInfo();
		return info.isConnected();
	}

	public boolean isReachable(String uri)
	{
		boolean reached = isAvailable();
		try {
			DefaultHttpClient httpclient = new DefaultHttpClient();
			HttpGet httpget = new HttpGet(uri);
			httpclient.execute(httpget);
		} catch (Exception e) { reached = false;}
		return reached;
	}

}

Make reachable depend on availability


package spark;

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

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

import static spark.Service.ignite;

public class InitExceptionHandlerTest {

    @Test
    public void testInitExceptionHandler() throws Exception {
        ExecutorService executorService = Executors.newSingleThreadExecutor();
        CompletableFuture<String> future = new CompletableFuture<>();
        executorService.submit(() -> {
            Service service1 = ignite().port(1122);
            service1.init();
            nap();
            Service service2 = ignite().port(1122);
            service2.initExceptionHandler((e) -> future.complete("Custom init error"));
            service2.init();
            service1.stop();
            service2.stop();
        });
        Assert.assertEquals("Custom init error", future.get());
    }

    private void nap() {
        try {
            Thread.sleep(100);
        } catch (InterruptedException ignored) {
        }
    }

}

package spark;

import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;

import static spark.Service.ignite;

public class InitExceptionHandlerTest {

    private static Service service1;
    private static Service service2;
    private static String errorMessage = "";

    @BeforeClass
    public static void setUpClass() throws Exception {

        service1 = ignite();
        service1.port(1122);
        service1.init();
        service1.awaitInitialization();

        service2 = ignite();
        service2.port(1122);
        service2.initExceptionHandler((e) -> errorMessage = "Custom init error");
        service2.init();
        service2.awaitInitialization();

    }

    @Test
    public void testGetPort_withRandomPort() throws Exception {
        Assert.assertEquals("Custom init error", errorMessage);
    }

    @AfterClass
    public static void tearDown() throws Exception {
        service1.stop();
        service2.stop();
    }

}

Rewrite initExceptionTest to be less stupid


package com.staticbloc.jobs;

import android.content.Context;

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

public abstract class BasicPersistentJobQueue extends BasicJobQueue {
    private ExecutorService executor = Executors.newSingleThreadExecutor();

    BasicPersistentJobQueue(Context context, JobQueueInitializer initializer) {
        super(context, initializer);
    }

    protected ExecutorService getPersistenceExecutor() {
        return executor;
    }

    @Override
    protected abstract void onLoadPersistedData();

    @Override
    protected abstract void onPersistJobAdded(JobQueueItem job);

    @Override
    protected abstract void onPersistJobRemoved(JobQueueItem job);

    @Override
    protected abstract void onPersistAllJobsCanceled();

    @Override
    protected abstract void onPersistJobModified(JobQueueItem job);
}

package com.staticbloc.jobs;

import android.content.Context;

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

public abstract class BasicPersistentJobQueue extends BasicJobQueue {
    private ExecutorService executor;

    BasicPersistentJobQueue(Context context, JobQueueInitializer initializer) {
        super(context, initializer);
    }

    protected ExecutorService getPersistenceExecutor() {
        if(executor == null) {
            executor = Executors.newSingleThreadExecutor();
        }
        return executor;
    }

    @Override
    protected abstract void onLoadPersistedData();

    @Override
    protected abstract void onPersistJobAdded(JobQueueItem job);

    @Override
    protected abstract void onPersistJobRemoved(JobQueueItem job);

    @Override
    protected abstract void onPersistAllJobsCanceled();

    @Override
    protected abstract void onPersistJobModified(JobQueueItem job);
}

Fix an NPE with the persistence executor.


package com.cedricziel.idea.typo3.util;

import com.intellij.psi.PsiElement;

import java.util.Arrays;

import static com.cedricziel.idea.typo3.psi.PhpElementsUtil.extractArrayIndexFromValue;

public class TCAUtil {

    public static final String[] TCA_TABLE_FIELDS = {
            "foreign_table",
            "allowed",
    };

    public static boolean arrayIndexIsTCATableNameField(PsiElement element) {
        String arrayIndex = extractArrayIndexFromValue(element);

        return Arrays.asList(TCA_TABLE_FIELDS).contains(arrayIndex);
    }
}

package com.cedricziel.idea.typo3.util;

import com.intellij.psi.PsiElement;

import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

import static com.cedricziel.idea.typo3.psi.PhpElementsUtil.extractArrayIndexFromValue;

public class TCAUtil {

    public static final String[] TCA_TABLE_FIELDS = {
            "foreign_table",
            "allowed",
    };

    public static final String[] TCA_CORE_TYPES = {
            "flex",
            "group",
            "imageManipulation",
            "input",
            "inline",
            "none",
            "passthrough",
            "radio",
            "select",
            "text",
            "user",
    };

    public static final String[] TCA_CORE_RENDER_TYPES = {
            "selectSingle",
            "selectSingleBox",
            "selectCheckBox",
            "selectMultipleSideBySide",
            "selectTree",
            "colorpicker",
            "inputDateTime",
            "inputLink",
            "rsaInput",
            "belayoutwizard",
            "t3editor",
            "textTable",
    };

    public static boolean arrayIndexIsTCATableNameField(PsiElement element) {
        String arrayIndex = extractArrayIndexFromValue(element);

        return Arrays.asList(TCA_TABLE_FIELDS).contains(arrayIndex);
    }

    public static Set<String> getAvailableRenderTypes(PsiElement element) {

        return new HashSet<>(Arrays.asList(TCA_CORE_RENDER_TYPES));
    }

    public static Set<String> getAvailableColumnTypes(PsiElement element) {

        return new HashSet<>(Arrays.asList(TCA_CORE_TYPES));
    }
}

Add core column types and renderTypes to TCA Util


package seedu.tache.logic.commands;

import seedu.tache.commons.core.EventsCenter;
import seedu.tache.commons.events.ui.ExitAppRequestEvent;

/**
 * Terminates the program.
 */
public class ExitCommand extends Command {

    public static final String COMMAND_WORD = "exit";

    public static final String MESSAGE_EXIT_ACKNOWLEDGEMENT = "Exiting Tache as requested ...";

    @Override
    public CommandResult execute() {
        EventsCenter.getInstance().post(new ExitAppRequestEvent());
        return new CommandResult(MESSAGE_EXIT_ACKNOWLEDGEMENT);
    }

}

package seedu.tache.logic.commands;

import seedu.tache.commons.core.EventsCenter;
import seedu.tache.commons.events.ui.ExitAppRequestEvent;

/**
 * Terminates the program.
 */
public class ExitCommand extends Command {

    public static final String COMMAND_WORD = "exit";
    //@@author A0150120H
    public static final String MESSAGE_USAGE = COMMAND_WORD + ": Exits Tache\n"
            + "All changes will be saved but undo history will be discarded\n"
            + "Example: " + COMMAND_WORD;
    //@@author
    public static final String MESSAGE_EXIT_ACKNOWLEDGEMENT = "Exiting Tache as requested ...";

    @Override
    public CommandResult execute() {
        EventsCenter.getInstance().post(new ExitAppRequestEvent());
        return new CommandResult(MESSAGE_EXIT_ACKNOWLEDGEMENT);
    }

}

Add usage string for exit command


package org.apollo.net.release.r377;

import org.apollo.game.message.impl.OpenDialogueOverlayMessage;
import org.apollo.net.codec.game.DataOrder;
import org.apollo.net.codec.game.DataType;
import org.apollo.net.codec.game.GamePacket;
import org.apollo.net.codec.game.GamePacketBuilder;
import org.apollo.net.release.MessageEncoder;

/**
 * A {@link MessageEncoder} for the {@link OpenDialogueOverlayMessage}.
 *
 * @author Major
 */
public final class OpenDialogueOverlayMessageEncoder extends MessageEncoder<OpenDialogueOverlayMessage> {

	@Override
	public GamePacket encode(OpenDialogueOverlayMessage message) {
		GamePacketBuilder builder = new GamePacketBuilder(154);
		builder.put(DataType.SHORT, DataOrder.LITTLE, message.getInterfaceId());
		return builder.toGamePacket();
	}

}

package org.apollo.net.release.r377;

import org.apollo.game.message.impl.OpenDialogueOverlayMessage;
import org.apollo.net.codec.game.DataOrder;
import org.apollo.net.codec.game.DataType;
import org.apollo.net.codec.game.GamePacket;
import org.apollo.net.codec.game.GamePacketBuilder;
import org.apollo.net.release.MessageEncoder;

/**
 * A {@link MessageEncoder} for the {@link OpenDialogueOverlayMessage}.
 *
 * @author Major
 */
public final class OpenDialogueOverlayMessageEncoder extends MessageEncoder<OpenDialogueOverlayMessage> {

	@Override
	public GamePacket encode(OpenDialogueOverlayMessage message) {
		GamePacketBuilder builder = new GamePacketBuilder(158);
		builder.put(DataType.SHORT, DataOrder.LITTLE, message.getInterfaceId());
		return builder.toGamePacket();
	}

}

Correct opcode of the 377 OpenDialogueOverlayMessage.


package router;

import javax.servlet.http.HttpServletRequest;

import org.skyve.impl.web.UserAgent.UserAgentType;
import org.skyve.metadata.router.UxUi;
import org.skyve.metadata.router.UxUiSelector;

public class DefaultUxUiSelector implements UxUiSelector {
	private static final UxUi PHONE = new UxUi("phone", "water");
	private static final UxUi TABLET = new UxUi("tablet", "omega");
	private static final UxUi DESKTOP = new UxUi("desktop", "omega");
	private static final UxUi EXTERNAL = new UxUi("external", "casablanca");

	@Override
	public UxUi select(UserAgentType userAgentType, HttpServletRequest request) {
		switch (userAgentType) {
			case phone:
				return PHONE;
			case tablet:
				return TABLET;
			case desktop:
				return DESKTOP;
			default:
				return EXTERNAL;
		}
	}
}

package router;

import javax.servlet.http.HttpServletRequest;

import org.skyve.impl.web.UserAgent.UserAgentType;
import org.skyve.metadata.router.UxUi;
import org.skyve.metadata.router.UxUiSelector;

public class DefaultUxUiSelector implements UxUiSelector {
	private static final UxUi PHONE = new UxUi("phone", "water");
	private static final UxUi TABLET = new UxUi("tablet", "omega");
	private static final UxUi DESKTOP = new UxUi("desktop", "casablanca");
	private static final UxUi EXTERNAL = new UxUi("external", "omega");

	@Override
	public UxUi select(UserAgentType userAgentType, HttpServletRequest request) {
		switch (userAgentType) {
			case phone:
				return PHONE;
			case tablet:
				return TABLET;
			case desktop:
				return DESKTOP;
			default:
				return EXTERNAL;
		}
	}
}

Fix the PF themes used in the default UX/UI selection.


package cz.muni.fi.rtsystems.robojagr.enums;

public enum Color {
    WHITE;

    public static Color getColor(int number) {
        return Color.WHITE;
    }
}

package cz.muni.fi.rtsystems.robojagr.enums;

public enum Color {
    WHITE, NOTWHITE;

    public static Color getColor(int number) {
        if (number == -1) {
            return Color.WHITE;
        }
        return NOTWHITE;
    }
}

Add "NOTWHITE" color and simple conversion rule.


package uk.ac.ebi.quickgo.solr.query.model.ontology.enums;

/**
 * Solr Term fields. Must have the same names as in the schema.xml solR file
 * @author cbonill
 *
 */
public enum TermField {

	ID("id"),
	NAME("name"),
	TYPE("docType"),
	CHILD("child"),
	PARENT("parent"),
	OBSOLETE_ID("obsoleteId"),
	SECONDARYID("secondaryId"),
	HISTORYTIMESTAMP("historyTimeStamp");
	// TODO Add the rest

	String value;

	private TermField(String value) {
		this.value = value;
	}

	public String getValue() {
		return value;
	}

	public void setValue(String value) {
		this.value = value;
	}
}

package uk.ac.ebi.quickgo.solr.query.model.ontology.enums;

/**
 * Solr Term fields. Must have the same names as in the schema.xml solR file
 * @author cbonill
 *
 */
public enum TermField {

	ID("id"),
	NAME("name"),
	TYPE("docType"),
	CHILD("child"),
	PARENT("parent"),
	OBSOLETE_ID("obsoleteId"),
	SECONDARYID("secondaryId"),
	HISTORYTIMESTAMP("historyTimeStamp"),
	DOCTYPE("docType");
	// TODO Add the rest

	String value;

	TermField(String value) {
		this.value = value;
	}

	public String getValue() {
		return value;
	}

	public void setValue(String value) {
		this.value = value;
	}
}

Add field necessary for querying specific field within data source.


//
// $Id: BootstrapData.java,v 1.1 2001/07/19 07:09:16 mdb Exp $

package com.threerings.cocktail.cher.net;

import com.threerings.cocktail.cher.dobj.DObject;

/**
 * An BootstrapData object is communicated back to the client
 * after authentication has succeeded and after the server is fully
 * prepared to deal with the client. It contains information the client
 * will need to interact with the server.
 */
public class BootstrapData extends DObject
{
    /** The oid of this client's associated distributed object. */
    public int clientOid;

    /** The oid to which to send invocation requests. */
    public int invOid;

    public String toString ()
    {
        return "[clientOid=" + clientOid + ", invOid=" + invOid + "]";
    }
}

//
// $Id: BootstrapData.java,v 1.2 2001/10/09 18:17:52 mdb Exp $

package com.threerings.cocktail.cher.net;

import com.threerings.cocktail.cher.dobj.DObject;

/**
 * A BootstrapData object is communicated back to the client
 * after authentication has succeeded and after the server is fully
 * prepared to deal with the client. It contains information the client
 * will need to interact with the server.
 */
public class BootstrapData extends DObject
{
    /** The oid of this client's associated distributed object. */
    public int clientOid;

    /** The oid to which to send invocation requests. */
    public int invOid;

    // documentation inherited
    public void toString (StringBuffer buf)
    {
        super.toString(buf);
        buf.append(", clientOid=").append(clientOid);
        buf.append(", invOid=").append(invOid);
    }
}

Use the proper toString() method.


package com.capitalistlepton.model;

import java.util.Random;

/**
 * Created by zanelittrell on 2/5/17.
 */
public class Bacterium {

    private static final Random rand = new Random();

    private int x;
    private int y;
    private String genotype;

    public Bacterium(String parentGenotype, int x, int y) {
        float mutation = rand.nextFloat();
        if (mutation > 0.99f) {
            genotype = "AABBCc";
        } else {
            genotype = parentGenotype;
        }
        this.x = x;
        this.y = y;
    }

    public int getX() { return x; }
    public int getY() { return y; }
    public String getGenotype() { return genotype; }
}

package com.capitalistlepton.model;

import java.util.Random;

/**
 * Created by zanelittrell on 2/5/17.
 */
public class Bacterium {

    private static final Random rand = new Random();
    private static final float mutationRate = 0.99f;

    private int x;
    private int y;
    private String genotype;

    public Bacterium(String parentGenotype, int x, int y) {
        this.genotype = generateGenotype(parentGenotype);
        this.x = x;
        this.y = y;
    }

    public int getX() { return x; }
    public int getY() { return y; }
    public String getGenotype() { return genotype; }

    private static String generateGenotype(String parentGenotype) {
        StringBuilder gen = new StringBuilder(parentGenotype);
        for (int i = 0; i < parentGenotype.length(); i += 2) {
            if (rand.nextFloat() > mutationRate) {
                if (rand.nextFloat() > 0.75f) {
                    gen.setCharAt(i, Character.toLowerCase(gen.charAt(i)));
                    gen.setCharAt(i+1, Character.toLowerCase(gen.charAt(i+1)));
                } else if(rand.nextFloat() > 0.5f) {
                    gen.setCharAt(i, Character.toTitleCase(gen.charAt(i)));
                    gen.setCharAt(i+1, Character.toLowerCase(gen.charAt(i+1)));
                } else {
                    gen.setCharAt(i, Character.toUpperCase(gen.charAt(i)));
                    gen.setCharAt(i+1, Character.toUpperCase(gen.charAt(i+1)));
                }
            }
        }
        return gen.toString();
    }
}

Add random mutation method for when bacteria are created.


package nl.rug.search.cpptool.api;

import com.google.common.collect.ImmutableList;
import nl.rug.search.cpptool.api.util.ContextTools;

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

public interface SourceFile {
    Iterable<Declaration> MISSING_DECLARATIONS_DUMMY = ImmutableList.of();

    /**
     * @return
     */
    @Nonnull
    String path();

    /**
     * @return
     */
    @Nonnull
    Iterable<SourceFile> includes();

    /**
     * @return
     */
    @Nonnull
    Iterable<SourceFile> includedBy();

    /**
     * @return
     */
    @Nonnull
    Optional<DeclContext> localContext();

    /**
     * @return
     */
    @Nonnull
    default Iterable<Declaration> declarations() {
        return localContext().map(ContextTools::traverseDecls).orElse(MISSING_DECLARATIONS_DUMMY);
    }
}

package nl.rug.search.cpptool.api;

import com.google.common.collect.ImmutableList;
import nl.rug.search.cpptool.api.util.ContextTools;

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

public interface SourceFile {
    Iterable<Declaration> MISSING_DECLARATIONS_DUMMY = ImmutableList.of();

    /**
     * @return
     */
    @Nonnull
    String path();

    /**
     * @return
     */
    @Nonnull
    Iterable<SourceFile> includes();

    /**
     * @return
     */
    @Nonnull
    Iterable<SourceFile> includedBy();

    /**
     * @return
     */
    @Nonnull
    Optional<DeclContext> localContext();

    /**
     * @return
     */
    @Nonnull
    default Iterable<Declaration> declarations() {
        return localContext().map(ContextTools::traverseDeclarations).orElse(MISSING_DECLARATIONS_DUMMY);
    }
}

Make sure the public repository remains compilable


package net.minecraftforge.event;

import net.minecraft.src.EntityPlayerMP;

@Cancelable
public class ServerChatEvent extends Event {
        public final String message, username;
        public final EntityPlayerMP player;
        public String line;
        public ServerChatEvent(EntityPlayerMP player, String message, String line)
        {
            super();
            this.message = message;
            this.player = player;
            this.username = player.username;
            this.line = "<" + username + "> " + message;
        }
}

Add event to cancel or change chat messages sent from server


/* 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.activiti.examples.bpmn.servicetask;

import org.activiti.engine.delegate.JavaDelegate;
import org.activiti.engine.delegate.DelegateExecution;
import org.activiti.engine.impl.el.Expression;
import org.junit.Assert;

/**
 * @author Frederik Heremans
 */
public class ToUpperCaseSetterInjected implements JavaDelegate {

  private Expression text;
  private boolean setterInvoked = false;

  public void execute(DelegateExecution execution) {

    if(!setterInvoked) {
      Assert.fail("Setter was not invoked");
    }
    execution.setVariable("setterVar", ((String)text.getValue(execution)).toUpperCase());
  }

  public void setText(Expression text) {
    setterInvoked = true;
    this.text = text;
  }

}

/* 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.activiti.examples.bpmn.servicetask;

import org.activiti.engine.delegate.DelegateExecution;
import org.activiti.engine.delegate.JavaDelegate;
import org.activiti.engine.impl.el.Expression;

/**
 * @author Frederik Heremans
 */
public class ToUpperCaseSetterInjected implements JavaDelegate {

  private Expression text;
  private boolean setterInvoked = false;

  public void execute(DelegateExecution execution) {

    if(!setterInvoked) {
      throw new RuntimeException("Setter was not invoked");
    }
    execution.setVariable("setterVar", ((String)text.getValue(execution)).toUpperCase());
  }

  public void setText(Expression text) {
    setterInvoked = true;
    this.text = text;
  }

}

Fix for failing demo setup


package com.yuyakaido.android.cardstackview.internal;

import android.support.annotation.Nullable;
import android.support.v7.widget.RecyclerView;

import com.yuyakaido.android.cardstackview.CardStackLayoutManager;

public class CardStackDataObserver extends RecyclerView.AdapterDataObserver {

    private final RecyclerView recyclerView;

    public CardStackDataObserver(RecyclerView recyclerView) {
        this.recyclerView = recyclerView;
    }

    @Override
    public void onChanged() {
        CardStackLayoutManager manager = getCardStackLayoutManager();
        manager.setTopPosition(0);
    }

    @Override
    public void onItemRangeChanged(int positionStart, int itemCount) {
        // Do nothing
    }

    @Override
    public void onItemRangeChanged(int positionStart, int itemCount, @Nullable Object payload) {
        // Do nothing
    }

    @Override
    public void onItemRangeInserted(int positionStart, int itemCount) {
        // Do nothing
    }

    @Override
    public void onItemRangeRemoved(int positionStart, int itemCount) {
        CardStackLayoutManager manager = getCardStackLayoutManager();
        if (positionStart == 0) {
            manager.setTopPosition(0);
        }
        manager.removeAllViews();
    }

    @Override
    public void onItemRangeMoved(int fromPosition, int toPosition, int itemCount) {
        CardStackLayoutManager manager = getCardStackLayoutManager();
        manager.removeAllViews();
    }

    private CardStackLayoutManager getCardStackLayoutManager() {
        RecyclerView.LayoutManager manager = recyclerView.getLayoutManager();
        if (manager instanceof CardStackLayoutManager) {
            return (CardStackLayoutManager) manager;
        }
        throw new IllegalStateException("CardStackView must be set CardStackLayoutManager.");
    }

}

package com.yuyakaido.android.cardstackview.internal;

import android.support.annotation.Nullable;
import android.support.v7.widget.RecyclerView;

import com.yuyakaido.android.cardstackview.CardStackLayoutManager;

public class CardStackDataObserver extends RecyclerView.AdapterDataObserver {

    private final RecyclerView recyclerView;

    public CardStackDataObserver(RecyclerView recyclerView) {
        this.recyclerView = recyclerView;
    }

    @Override
    public void onChanged() {
        CardStackLayoutManager manager = getCardStackLayoutManager();
        manager.setTopPosition(0);
    }

    @Override
    public void onItemRangeChanged(int positionStart, int itemCount) {
        // Do nothing
    }

    @Override
    public void onItemRangeChanged(int positionStart, int itemCount, @Nullable Object payload) {
        // Do nothing
    }

    @Override
    public void onItemRangeInserted(int positionStart, int itemCount) {
        // Do nothing
    }

    @Override
    public void onItemRangeRemoved(int positionStart, int itemCount) {
        CardStackLayoutManager manager = getCardStackLayoutManager();
        if (positionStart == 0) {
            manager.setTopPosition(0);
        }
        manager.removeAllViews();
    }

    @Override
    public void onItemRangeMoved(int fromPosition, int toPosition, int itemCount) {
        // Do nothing
    }

    private CardStackLayoutManager getCardStackLayoutManager() {
        RecyclerView.LayoutManager manager = recyclerView.getLayoutManager();
        if (manager instanceof CardStackLayoutManager) {
            return (CardStackLayoutManager) manager;
        }
        throw new IllegalStateException("CardStackView must be set CardStackLayoutManager.");
    }

}

Revert "Refresh all views when invoking move action"


package org.jvirtanen.parity.net.poe;

import org.jvirtanen.parity.net.ProtocolException;

public class POEException extends ProtocolException {

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

}

package org.jvirtanen.parity.net.poe;

import org.jvirtanen.parity.net.ProtocolException;

/**
 * Indicates a protocol error while handling the POE protocol.
 */
public class POEException extends ProtocolException {

    /**
     * Construct an instance with the specified detail message.
     *
     * @param message the detail message
     */
    public POEException(String message) {
        super(message);
    }

}

Add documentation for POE exception in network protocols


package io.syndesis.qe;

import com.codeborne.selenide.Configuration;
import cucumber.api.CucumberOptions;
import cucumber.api.junit.Cucumber;
import org.junit.BeforeClass;
import org.junit.runner.RunWith;

@RunWith(Cucumber.class)
@CucumberOptions(
        features = "classpath:features",
        tags = "not @wip, @manual, @deprecated",
        format = {"pretty", "html:target/cucumber/cucumber-html", "junit:target/cucumber/cucumber-junit.xml", "json:target/cucumber/cucumber-report.json"}
)
public class CucumberTest extends TestSuiteParent {

    @BeforeClass
    public static void setupCucumber() {
        //set up Selenide
        Configuration.timeout = TestConfiguration.getConfigTimeout() * 1000;
        //We will now use custom web driver
        //Configuration.browser = TestConfiguration.syndesisBrowser();
        Configuration.browser = "io.syndesis.qe.CustomWebDriverProvider";
        Configuration.browserSize= "1920x1080";
    }

}

package io.syndesis.qe;

import com.codeborne.selenide.Configuration;
import cucumber.api.CucumberOptions;
import cucumber.api.junit.Cucumber;
import org.junit.BeforeClass;
import org.junit.runner.RunWith;

@RunWith(Cucumber.class)
@CucumberOptions(
        features = "classpath:features",
        tags = {"not @wip", "not @manual", "not @deprecated"},
        format = {"pretty", "html:target/cucumber/cucumber-html", "junit:target/cucumber/cucumber-junit.xml", "json:target/cucumber/cucumber-report.json"}
)
public class CucumberTest extends TestSuiteParent {

    @BeforeClass
    public static void setupCucumber() {
        //set up Selenide
        Configuration.timeout = TestConfiguration.getConfigTimeout() * 1000;
        //We will now use custom web driver
        //Configuration.browser = TestConfiguration.syndesisBrowser();
        Configuration.browser = "io.syndesis.qe.CustomWebDriverProvider";
        Configuration.browserSize= "1920x1080";
    }

}

Update cucumber options to new format


package specs;

import static com.greghaskins.spectrum.Spectrum.describe;
import static com.greghaskins.spectrum.Spectrum.it;
import static com.greghaskins.spectrum.Spectrum.value;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.nullValue;

import com.greghaskins.spectrum.Spectrum;
import com.greghaskins.spectrum.Spectrum.Value;

import org.junit.runner.RunWith;

@RunWith(Spectrum.class)
public class MutableWrapperSpec {
  {

    describe("The Value convenience type", () -> {

      it("allows you to set the value of a 'final' variable", () -> {
        final Value<Integer> counter = value();
        counter.value = 0;
        counter.value = 1;
        assertThat(counter.value, is(1));
      });

      it("can be given a starting value", () -> {
        final Value<Double> pi = value(3.14);
        assertThat(pi.value, is(3.14));
      });

      it("has a default value of null if not specified", () -> {
        final Value<String> name = value();
        assertThat(name.value, is(nullValue()));
      });

    });
  }
}

package specs;

import static com.greghaskins.spectrum.Spectrum.describe;
import static com.greghaskins.spectrum.Spectrum.it;
import static com.greghaskins.spectrum.Spectrum.value;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.nullValue;

import com.greghaskins.spectrum.Spectrum;
import com.greghaskins.spectrum.Spectrum.Value;

import org.junit.runner.RunWith;

@RunWith(Spectrum.class)
@SuppressWarnings("deprecation")
public class MutableWrapperSpec {
  {

    describe("The Value convenience type", () -> {

      it("allows you to set the value of a 'final' variable", () -> {
        final Value<Integer> counter = value();
        counter.value = 0;
        counter.value = 1;
        assertThat(counter.value, is(1));
      });

      it("can be given a starting value", () -> {
        final Value<Double> pi = value(3.14);
        assertThat(pi.value, is(3.14));
      });

      it("has a default value of null if not specified", () -> {
        final Value<String> name = value();
        assertThat(name.value, is(nullValue()));
      });

      it("can take an explicit class parameter, for backward compatibility with ~0.6.1", () -> {
        final Value<String> stringValue = value(String.class);
        assertThat(stringValue.value, is(nullValue()));
      });

    });
  }
}

Make sure tests cover deprecated value(Class<T>) method


package com.nopcommerce.domain;

import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import com.nopcommerce.jackson.FlexDateDeserializer;
import com.nopcommerce.jackson.FlexDateSerializer;
import com.nopcommerce.json.JsonConstants;
import lombok.Data;

import java.util.Date;
import java.util.List;

@Data
public class Customer
{
    @JsonProperty(value = JsonConstants.ID)
    private int id;

    @JsonProperty(value = JsonConstants.EMAIL)
    private String email;

    @JsonProperty(value = JsonConstants.FIRST_NAME)
    private String firstName;

    @JsonProperty(value = JsonConstants.LAST_NAME)
    private String lastName;

    @JsonProperty(value = JsonConstants.GENDER)
    private String gender;

    @JsonProperty(value = JsonConstants.DATE_OF_BIRTH)
    private String dateOfBirth;

    @JsonProperty(value = JsonConstants.CREATED_ON_UTC)
    @JsonDeserialize(using = FlexDateDeserializer.class)
    @JsonSerialize(using = FlexDateSerializer.class)
    private Date registeredDate;

    @JsonProperty(value = JsonConstants.ADDRESSES)
    private List<Address> addresses;

}

package com.nopcommerce.domain;

import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import com.nopcommerce.jackson.FlexDateDeserializer;
import com.nopcommerce.jackson.FlexDateSerializer;
import com.nopcommerce.json.JsonConstants;
import lombok.Data;

import java.util.Date;
import java.util.List;

@Data
public class Customer
{
    @JsonProperty(value = JsonConstants.ID)
    private int id;

    @JsonProperty(value = JsonConstants.EMAIL)
    private String email;

    @JsonProperty(value = JsonConstants.FIRST_NAME)
    private String firstName;

    @JsonProperty(value = JsonConstants.LAST_NAME)
    private String lastName;

    @JsonProperty(value = JsonConstants.GENDER)
    private String gender;

    @JsonProperty(value = JsonConstants.DATE_OF_BIRTH)
    private String dateOfBirth;

    @JsonProperty(value = JsonConstants.LANGUAGE_ID)
    private Integer languageId;

    @JsonProperty(value = JsonConstants.REGISTERED_IN_STORE_ID)
    private Integer registeredInStoreId;

    @JsonProperty(value = JsonConstants.CREATED_ON_UTC)
    @JsonDeserialize(using = FlexDateDeserializer.class)
    @JsonSerialize(using = FlexDateSerializer.class)
    private Date registeredDate;

    @JsonProperty(value = JsonConstants.ADDRESSES)
    private List<Address> addresses;

}

Add the languageId and registeredInStore properties to the customer.


package com.google.sps;

import com.google.appengine.api.datastore.Entity;
import com.google.appengine.tools.development.testing.LocalDatastoreServiceTestConfig;
import com.google.appengine.tools.development.testing.LocalServiceTestHelper;
import com.google.sps.data.Trip;
import com.google.sps.servlets.TripsServlet;
import com.google.sps.util.TripDataConverter;

import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;

@RunWith(JUnit4.class)
public class TripsServletTest {

}

package com.google.sps;

import static org.mockito.Mockito.*;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;

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

import com.google.appengine.api.datastore.Entity;
import com.google.appengine.tools.development.testing.LocalDatastoreServiceTestConfig;
import com.google.appengine.tools.development.testing.LocalServiceTestHelper;
import com.google.sps.data.Trip;
import com.google.sps.servlets.TripsServlet;
import com.google.sps.util.TripDataConverter;

import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;

@RunWith(JUnit4.class)
public class TripsServletTest {
  private LocalServiceTestHelper helper;

  @Before
  public void setUp() {
    helper = new LocalServiceTestHelper(new LocalDatastoreServiceTestConfig());
  }

  @After
  public void tearDown() {
    helper.tearDown();
  }

  @Test
  public void testUnauthenticatedUser() throws IOException {
    helper.setEnvIsLoggedIn(false);
    helper.setUp();

    HttpServletRequest request = mock(HttpServletRequest.class);
    HttpServletResponse response = mock(HttpServletResponse.class);
    PrintWriter pw = new PrintWriter(new StringWriter());
    when(response.getWriter()).thenReturn(pw);

    TripsServlet servlet = new TripsServlet();
    servlet.doGet(request, response);
    servlet.doPost(request, response);
    servlet.doPut(request, response);
    servlet.doDelete(request, response);
    verify(response, times(4)).setStatus(HttpServletResponse.SC_UNAUTHORIZED);
  }

  @Test
  public void testDoGet() {
    helper.setEnvIsLoggedIn(true);
    helper.setEnvEmail("peter@google.com");
    helper.setEnvAuthDomain("google.com");
    helper.setUp();
  }
}

Add test for unauthenticated user all 4 HTTP methods in TripsServlet


/**
 * Tests some evaluation order / side effects with && and ||.
 *
 * @author Elvis Stansvik <elvstone@gmail.com>
 */

//EXT:BDJ

class SideEffects {
    public static void main(String[] args) {
        IncredibleMachine m;
        m = new IncredibleMachine();
        System.out.println(m.run()); // Should print 329.
    }
}

class IncredibleMachine {
    int result;
    public int run() {
        result = 2;
        if (a(3, false) && a(5, true)                        /* r = 2 + 3 */
            || (m(7, false) || s(11, true) && m(13, false))  /* r = ((2 + 3) * 7 - 11) * 13 */
            || a(17, true) || m(19, true))                   /* r = ((2 + 3) * 7 - 11) * 13 + 17 = 329 */
            result = result;
        else
            result = 42;
        return result;
    }
    public boolean m(int value, boolean ret) {
        result = result * value;
        return ret;
    }
    public boolean a(int value, boolean ret) {
        result = result + value;
        return ret;
    }
    public boolean s(int value, boolean ret) {
        result = result - value;
        return ret;
    }
}

/**
 * Tests some evaluation order / side effects with && and ||.
 *
 * @author Elvis Stansvik <elvstone@gmail.com>
 */

//EXT:BDJ
//EXT:IWE

class SideEffects {
    public static void main(String[] args) {
        IncredibleMachine m;
        m = new IncredibleMachine();
        System.out.println(m.run()); // Should print 329.
    }
}

class IncredibleMachine {
    int result;
    public int run() {
        result = 2;
        if (this.a(3, false) && this.a(5, true)                             /* r = 2 + 3 */
            || (this.m(7, false) || this.s(11, true) && this.m(13, false))  /* r = ((2 + 3) * 7 - 11) * 13 */
            || this.a(17, true) || this.m(19, true))                        /* r = ((2 + 3) * 7 - 11) * 13 + 17 = 329 */
            result = result;
        return result;
    }
    public boolean m(int value, boolean ret) {
        result = result * value;
        return ret;
    }
    public boolean a(int value, boolean ret) {
        result = result + value;
        return ret;
    }
    public boolean s(int value, boolean ret) {
        result = result - value;
        return ret;
    }
}

Make test case valid MiniJava.


package org.tomighty.plugin;

import com.google.inject.AbstractModule;
import com.google.inject.Guice;
import com.google.inject.Injector;
import org.junit.Test;

import static org.junit.Assert.assertSame;

public class DefaultPluginTest {

    //TODO test getPluginName
    //TODO test getPluginVersion
    //TODO test getMenuItem

    @Test
    public void testInjectorIsTheSameUsedToCreateThePlugin() {
        Injector injector = Guice.createInjector(new AbstractModule() {
            @Override
            protected void configure() {
                bind(Plugin.class).to(DefaultPlugin.class);
            }
        });

        Plugin plugin = injector.getInstance(Plugin.class);

        assertSame(injector, plugin.getInjector());
    }

}

package org.tomighty.plugin;

import com.google.inject.AbstractModule;
import com.google.inject.Guice;
import com.google.inject.Injector;
import org.junit.Before;
import org.junit.Test;

import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertSame;

public class DefaultPluginTest {

    private Plugin plugin;
    private Injector injector;

    @Before
    public void setUp() {
        injector = Guice.createInjector(new AbstractModule() {
            @Override
            protected void configure() {
                bind(Plugin.class).to(DefaultPlugin.class);
            }
        });

        plugin = injector.getInstance(Plugin.class);
    }

    //TODO test getPluginName
    //TODO test getPluginVersion

    @Test
    public void testHasNoMenuItem() {
        assertNull(plugin.getMenuItem());
    }

    @Test
    public void testInjectorIsTheSameUsedToCreateThePlugin() {
        assertSame(injector, plugin.getInjector());
    }

}

Test menu item returned by the default plugin.


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

package com.facebook.react.common;

/**
 * Lifecycle state for an Activity. The state right after pause and right before resume are the
 * basically the same so this enum is in terms of the forward lifecycle progression (onResume, etc).
 * Eventually, if necessary, it could contain something like:
 *
 * <p>BEFORE_CREATE, CREATED, VIEW_CREATED, STARTED, RESUMED
 */
public enum LifecycleState {
  BEFORE_CREATE,
  BEFORE_RESUME,
  RESUMED,
}

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

package com.facebook.react.common;

/**
 * Lifecycle state for an Activity. The state right after pause and right before resume are the
 * basically the same so this enum is in terms of the forward lifecycle progression (onResume, etc).
 *
 *
BEFORE_CREATE is used before a ReactRootView is attached to ReactInstanceManager, or after all
 * the ReactRootView has been detached from the ReactInstanceManager.
 *
 *
BEFORE_RESUME is used after a ReactRootView is attached to ReactInstanceManager but before
 * it's activity is resumed, or after its activity has been paused and before the ReactRootView has
 * been detached from the ReactInstanceManager.
 *
 *
RESUMED is used when a ReactRootView is rendered on the screen and the user can interact with
 * it.
 */
public enum LifecycleState {
  BEFORE_CREATE,
  BEFORE_RESUME,
  RESUMED,
}

Update InitialLifeCycleState used when initializing RN in FB4A


package com.untamedears.citadel.entity;

import com.untamedears.citadel.Citadel;

import javax.persistence.Entity;
import javax.persistence.Id;

/**
 * Created by IntelliJ IDEA.
 * User: chrisrico
 * Date: 3/21/12
 * Time: 1:14 AM
 */
@Entity
public class Faction {

    @Id private String name;
    private String founder;

    public Faction() {
    }

    public Faction(String name, String founder) {
        this.name = name;
        this.founder = founder;
    }

    public String getName() {
        return name;
    }

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

    public String getFounder() {
        return founder;
    }

    public void setFounder(String founder) {
        this.founder = founder;
    }

    public boolean hasMember(String memberName) {
        return Citadel.getInstance().dao.hasGroupMember(name, memberName);
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (!(o instanceof Faction)) return false;

        Faction faction = (Faction) o;

        return name.equals(faction.name);
    }

    @Override
    public int hashCode() {
        return name.hashCode();
    }
}

Fix critical upgrade/repair bug. Initial changes to allow multiple player groups.


package arez.component;

import arez.AbstractArezTest;
import arez.ArezTestUtil;
import org.testng.annotations.Test;
import static org.testng.Assert.*;

public class VerifiableTest
  extends AbstractArezTest
{
  static class TestElement
    implements Verifiable
  {
    boolean _verified;

    @Override
    public void verify()
    {
      _verified = true;
    }
  }

  @Test
  public void verifiableElement()
    throws Exception
  {
    final TestElement element = new TestElement();
    assertFalse( element._verified );
    Verifiable.verify( element );
    assertTrue( element._verified );
  }

  @Test
  public void verifiableElement_verifyDisabled()
    throws Exception
  {
    ArezTestUtil.disableVerify();
    final TestElement element = new TestElement();
    assertFalse( element._verified );
    Verifiable.verify( element );
    assertFalse( element._verified );
  }

  @Test
  public void nonLinkableElement()
    throws Exception
  {
    // Should produce no exceptions
    Verifiable.verify( new Object() );
  }
}

package arez.component;

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

public class VerifiableTest
  extends AbstractArezTest
{
  static class TestElement
    implements Verifiable
  {
    boolean _verified;

    @Override
    public void verify()
    {
      _verified = true;
    }
  }

  static class TestBadElement
    implements Verifiable
  {
    boolean _verified;

    @Override
    public void verify()
      throws Exception
    {
      _verified = true;
      throw new IOException();
    }
  }

  @Test
  public void verifiableElement()
    throws Exception
  {
    final TestElement element = new TestElement();
    assertFalse( element._verified );
    Verifiable.verify( element );
    assertTrue( element._verified );
  }

  @Test
  public void verifiableElement_verifyDisabled()
    throws Exception
  {
    ArezTestUtil.disableVerify();
    final TestElement element = new TestElement();
    assertFalse( element._verified );
    Verifiable.verify( element );
    assertFalse( element._verified );
  }

  @Test
  public void nonLinkableElement()
    throws Exception
  {
    // Should produce no exceptions
    Verifiable.verify( new Object() );
  }

  @Test
  public void verifiableBadElement()
  {
    final TestBadElement element = new TestBadElement();
    assertFalse( element._verified );
    assertThrows( IOException.class, () -> Verifiable.verify( element ) );
    assertTrue( element._verified );
  }
}

Add aditional test to make sure a failed verify is possible


/*
 * test that caught null pointers exceptions in finalizers work correctly
 * and that local variables are accessible in null pointer exception handlers.
 */
import java.io.*;

public class NullPointerTest {

    static String s;

    public static void main(String[] args) {
	  System.out.println(tryfinally() + s);
    }

    public static String tryfinally() {
	String yuck = null;
	String local_s = null;

	try {
	    return "This is ";
	} finally {
	    try {
		local_s = "Perfect";
		/* trigger null pointer exception */
		String x = yuck.toLowerCase();
	    } catch (Exception _) {
		/*
		 * when the null pointer exception is caught, we must still
		 * be able to access local_s.
		 * Our return address for the finally clause must also still
		 * be intact.
		 */
		s = local_s;
	    }
	}
    }
}

/* Expected Output:
This is Perfect
*/

/*
 * test that caught null pointers exceptions in finalizers work correctly
 * and that local variables are accessible in null pointer exception handlers.
 */
import java.io.*;

public class NullPointerTest {

    static String s;

    public static void main(String[] args) {
	  System.out.println(tryfinally() + s);
	  try {
		// Note: String.concat("") will not dereference 'this'
		((String)null).concat("");
	  	System.out.println("FAILED!");
	  } catch (NullPointerException e) {
	  	System.out.println("This is good too");
	  }
    }

    public static String tryfinally() {
	String yuck = null;
	String local_s = null;

	try {
	    return "This is ";
	} finally {
	    try {
		local_s = "Perfect";
		/* trigger null pointer exception */
		String x = yuck.toLowerCase();
	    } catch (Exception _) {
		/*
		 * when the null pointer exception is caught, we must still
		 * be able to access local_s.
		 * Our return address for the finally clause must also still
		 * be intact.
		 */
		s = local_s;
	    }
	}
    }
}

/* Expected Output:
This is Perfect
This is good too
*/

Check that kaffe doesn't allow invocation of a null pointer.


package org.mozilla.webmaker.util;

import android.app.Activity;
import android.content.Intent;
import org.mozilla.webmaker.R;

public class Share {

    /**
     * Launches a share intent using a specified subject and body.
     *
     * @param url URL to be appended to the share body
     * @param activity Base activity
     */
    public static void launchShareIntent(final String url, final Activity activity) {
        final Intent shareIntent = new Intent(android.content.Intent.ACTION_SEND);
        final String shareSubject = activity.getString(R.string.share_subject);
        final String shareBody = activity.getString(R.string.share_body).concat(" " + url);

        shareIntent.setType("text/plain");
        shareIntent.putExtra(Intent.EXTRA_SUBJECT, shareSubject);
        shareIntent.putExtra(Intent.EXTRA_TEXT, shareBody);

        activity.startActivity(Intent.createChooser(shareIntent, "Share"));
    }
}

package org.mozilla.webmaker.util;

import android.app.Activity;
import android.content.Intent;
import org.mozilla.webmaker.R;

public class Share {

    /**
     * Launches a share intent.
     *
     * @param url URL to be appended to the share body
     * @param activity Base activity
     */
    public static void launchShareIntent(final String url, final Activity activity) {
        final Intent shareIntent = new Intent(android.content.Intent.ACTION_SEND);
        final String shareSubject = activity.getString(R.string.share_subject);
        final String shareBody = activity.getString(R.string.share_body).concat(" " + url);

        shareIntent.setType("text/plain");
        shareIntent.putExtra(Intent.EXTRA_SUBJECT, shareSubject);
        shareIntent.putExtra(Intent.EXTRA_TEXT, shareBody);

        activity.startActivity(Intent.createChooser(shareIntent, "Share"));
    }
}

Clarify static method description for sharing


package org.bouncycastle.util;

public class Integers
{
    public static Integer valueOf(int value)
    {
        return Integer.valueOf(value);
    }
}

package org.bouncycastle.util;

public class Integers
{
    public static int rotateLeft(int i, int distance)
    {
        return Integer.rotateLeft(i, distance);
    }

    public static int rotateRight(int i, int distance)
    {
        return Integer.rotateRight(i, distance);
    }

    public static Integer valueOf(int value)
    {
        return Integer.valueOf(value);
    }
}

Make rotate methods from Integer available