package cpw.mods.fml.common.event;

import net.minecraft.server.MinecraftServer;
import cpw.mods.fml.common.LoaderState.ModState;

public class FMLServerStartingEvent extends FMLStateEvent
{

    private MinecraftServer server;

    public FMLServerStartingEvent(Object... data)
    {
        super(data);
        this.server = (MinecraftServer) data[0];
    }
    @Override
    public ModState getModState()
    {
        return ModState.AVAILABLE;
    }

    public MinecraftServer getServer()
    {
        return server;
    }
}

package cpw.mods.fml.common.event;

import net.minecraft.server.MinecraftServer;
import net.minecraft.src.CommandHandler;
import net.minecraft.src.ICommand;
import cpw.mods.fml.common.LoaderState.ModState;

public class FMLServerStartingEvent extends FMLStateEvent
{

    private MinecraftServer server;

    public FMLServerStartingEvent(Object... data)
    {
        super(data);
        this.server = (MinecraftServer) data[0];
    }
    @Override
    public ModState getModState()
    {
        return ModState.AVAILABLE;
    }

    public MinecraftServer getServer()
    {
        return server;
    }

    public void registerServerCommand(ICommand command)
    {
        CommandHandler ch = (CommandHandler) getServer().func_71187_D();
        ch.func_71560_a(command);
    }
}

Add in a helper on the server start event for adding commands to the server.


package org.udg.pds.simpleapp_javaee.rest;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.ws.rs.container.ContainerRequestContext;
import javax.ws.rs.container.ContainerResponseContext;
import javax.ws.rs.container.ContainerResponseFilter;
import javax.ws.rs.ext.Provider;
import java.io.IOException;

@Provider
public class LoggingFilter implements ContainerResponseFilter {

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

  public void filter(ContainerRequestContext requestContext,
                     ContainerResponseContext responseContext) throws IOException {
    String method = requestContext.getMethod();

    logger.info("Requesting " + method + " for path " + requestContext.getUriInfo().getPath() + " with MIME type " + requestContext.getMediaType());
    // String json = IOUtils.toString(requestContext.getEntityStream());
    Object entity = responseContext.getEntity();
    if (entity != null) {
      logger.info("Response " + new ObjectMapper().writerWithDefaultPrettyPrinter().writeValueAsString(entity));
    }

  }
}

package org.udg.pds.simpleapp_javaee.rest;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.ws.rs.container.ContainerRequestContext;
import javax.ws.rs.container.ContainerResponseContext;
import javax.ws.rs.container.ContainerResponseFilter;
import javax.ws.rs.ext.Provider;
import java.io.IOException;

@Provider
public class LoggingFilter implements ContainerResponseFilter {

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

  public void filter(ContainerRequestContext requestContext,
                     ContainerResponseContext responseContext) throws IOException {
    String method = requestContext.getMethod();

    logger.info("Requesting " + method + " for path " + requestContext.getUriInfo().getPath() + " with MIME type " + requestContext.getMediaType());
    // String json = IOUtils.toString(requestContext.getEntityStream());
    Object entity = responseContext.getEntity();
    if (entity != null) {
      String response = new ObjectMapper().writeValueAsString(entity).replace("\\\"", "\"");
      logger.info("Response: " + response);
    }

  }
}

Remove escape from double quotes


package bamboo;

import bamboo.app.Bamboo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;

import java.io.IOException;

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

    @Bean
    public Bamboo getBamboo() throws IOException {
        return new Bamboo(false);
    }
}

package bamboo;

import bamboo.app.Bamboo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;

import java.io.IOException;

@SpringBootApplication
public class Application {
    public static void main(String[] args) {
        for (int i = 0; i < args.length; i++) {
            switch (args[i]) {
                case "-h":
                case "--help":
                    System.out.println("Options:\n" +
                            "  -p port  Web server port\n" +
                            "  -b addr  Web server bind address\n" +
                            "  -c path  Web server context path");
                    return;
                case "-c":
                    System.setProperty("server.servlet.context-path", args[++i]);
                    break;
                case "-p":
                    System.setProperty("server.port", args[++i]);
                    break;
                case "-b":
                    System.setProperty("server.address", args[++i]);
                    break;
                default:
                    System.err.println("Ignoring unknown option: " + args[i]);
                    break;
            }
        }
        SpringApplication.run(Application.class, args);
    }

    @Bean
    public Bamboo getBamboo() throws IOException {
        return new Bamboo(false);
    }
}

Add command-line options compatible with old main()


package org.logtalk.intellij;

import org.jetbrains.annotations.NotNull;

import com.intellij.openapi.fileTypes.FileTypeConsumer;
import com.intellij.openapi.fileTypes.FileTypeFactory;

public class LogtalkFileTypeFactory extends FileTypeFactory {

    @Override
    public void createFileTypes(@NotNull FileTypeConsumer fileTypeConsumer) {
        fileTypeConsumer.consume(LogtalkFileType.INSTANCE, "lgt");
        fileTypeConsumer.consume(LogtalkFileType.INSTANCE, "pl");
        //fileTypeConsumer.consume(PrologFileType.INSTANCE, "pl");
    }

}

package org.logtalk.intellij;

import org.jetbrains.annotations.NotNull;

import com.intellij.openapi.fileTypes.FileTypeConsumer;
import com.intellij.openapi.fileTypes.FileTypeFactory;

public class LogtalkFileTypeFactory extends FileTypeFactory {

    @Override
    public void createFileTypes(@NotNull FileTypeConsumer fileTypeConsumer) {
        fileTypeConsumer.consume(LogtalkFileType.INSTANCE, "logtalk");
        fileTypeConsumer.consume(LogtalkFileType.INSTANCE, "lgt");
        fileTypeConsumer.consume(LogtalkFileType.INSTANCE, "prolog");
        fileTypeConsumer.consume(LogtalkFileType.INSTANCE, "pl");
        //fileTypeConsumer.consume(PrologFileType.INSTANCE, "pl");
    }

}

Update IntelliJ IDEA support to also recognize `*.logtalk` and `*.prolog` file extensions


package edu.ntnu.idi.goldfish;

import java.util.HashMap;
import java.util.concurrent.TimeUnit;

public class StopWatch {

	protected static HashMap<String, Long> starts = new HashMap<String,Long>();
	protected static HashMap<String, Long> timings = new HashMap<String,Long>();

	public static void start(String name) {
		timings.remove(name);
		starts.put(name, System.currentTimeMillis());
	}

	public static void stop(String name) {
		if(!starts.containsKey(name)) {
			System.err.format("have no start timing for %s\n", name);
			return;
		}
		if(!timings.containsKey(name)) {
			timings.put(name, System.currentTimeMillis() - starts.get(name));
		}
	}

	public static String str(String name) {
		stop(name);
		long time = timings.get(name);
		return String.format("%d min, %d sec",
			    TimeUnit.MILLISECONDS.toMinutes(time),
			    TimeUnit.MILLISECONDS.toSeconds(time) -
			    TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(time))
		);
	}

	public static void print(String name) {
		System.out.format("%s: %s\n", name, str(name));
	}

	public static long get(String name) {
		stop(name);
		return timings.get(name);
	}
}

package edu.ntnu.idi.goldfish;

import java.util.HashMap;
import java.util.concurrent.TimeUnit;

public class StopWatch {

	protected static HashMap<String, Long> starts = new HashMap<String,Long>();
	protected static HashMap<String, Long> timings = new HashMap<String,Long>();

	public static void start(String name) {
		timings.remove(name);
		starts.put(name, System.currentTimeMillis());
	}

	public static void stop(String name) {
		if(!starts.containsKey(name)) {
			System.err.format("have no start timing for %s\n", name);
			return;
		}
		if(!timings.containsKey(name)) {
			timings.put(name, System.currentTimeMillis() - starts.get(name));
		}
	}

	public static String str(String name) {
		stop(name);
		long time = timings.get(name);
		return String.format("%d min, %d sec, (%d ms)",
			    TimeUnit.MILLISECONDS.toMinutes(time),
			    TimeUnit.MILLISECONDS.toSeconds(time) -
			    TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(time)),
			    time
		);
	}

	public static void print(String name) {
		System.out.format("%s: %s\n", name, str(name));
	}

	public static long get(String name) {
		stop(name);
		return timings.get(name);
	}
}

Include ms in stopwatch output.


package org.oblodiff.token.text;

import org.oblodiff.token.BasicToken;

/**
 * A textual token is a token representing a text.
 *
 * @since 1.0.0
 * @param <T> the type of the content this token represents
 * @author Christian Rösch <christianroesch@gmx.net>
 */
public abstract class TextualToken<T> extends BasicToken<T> {

    public TextualToken(T ct) {
        super(ct);
    }
}

package org.oblodiff.token.text;

import org.oblodiff.token.BasicToken;

/**
 * A textual token is a token representing a text.
 *
 * XXX For what is this class good? It does not add any behavior/property to BasicToken.
 * @since 1.0.0
 * @param <T> the type of the content this token represents
 * @author Christian Rösch <christianroesch@gmx.net>
 */
public abstract class TextualToken<T> extends BasicToken<T> {

    /**
     * Dedicated constructor.
     *
     * @param content must not be {@code null}
     */
    public TextualToken(final T content) {
        super(content);
    }
}

Add XXX marker to class.


package se.kits.gakusei.content.model;

import com.fasterxml.jackson.annotation.JsonManagedReference;

import javax.persistence.*;
import java.io.Serializable;
import java.util.List;

@Entity
@Table(name = "lessons", schema = "contentschema")
public class Lesson implements Serializable {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column(nullable = false)
    private String name;

    private String description;

    @ManyToMany
    @JsonManagedReference
    @JoinTable(
            name = "lessons_nuggets",
            joinColumns = @JoinColumn(name = "lesson_id", referencedColumnName = "id"),
            inverseJoinColumns = @JoinColumn(name = "nugget_id", referencedColumnName = "id"))
    private List<Nugget> nuggets;

    public Lesson() {
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

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

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public List<Nugget> getNuggets() {
        return nuggets;
    }

    public void setNuggets(List<Nugget> nuggets) {
        this.nuggets = nuggets;
    }
}

package se.kits.gakusei.content.model;

import com.fasterxml.jackson.annotation.JsonManagedReference;

import javax.persistence.*;
import java.io.Serializable;
import java.util.List;

@Entity
@Table(name = "lessons", schema = "contentschema")
public class Lesson implements Serializable {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column(nullable = false)
    private String name;

    private String description;

    @ManyToMany
    @JsonManagedReference
    @JoinTable(
            name = "lessons_nuggets",
            schema = "contentschema",
            joinColumns = @JoinColumn(name = "lesson_id", referencedColumnName = "id"),
            inverseJoinColumns = @JoinColumn(name = "nugget_id", referencedColumnName = "id"))
    private List<Nugget> nuggets;

    public Lesson() {
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

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

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public List<Nugget> getNuggets() {
        return nuggets;
    }

    public void setNuggets(List<Nugget> nuggets) {
        this.nuggets = nuggets;
    }
}

Add missing schema declaration to lesson/nugget relation


package com.example.beer.dao;

import javax.ejb.Singleton;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;

import com.example.beer.model.Project;

@Singleton
public class ProjectDAO {

	@PersistenceContext
	private EntityManager em;

	public boolean addProject(Project project) {
		Project foundProject = findProjectByName(project.getName());

		if (foundProject != null) {
			em.persist(project);
			return true;
		} else {
			// TODO: Maybe update project title or users, or tasks?
			return false;
		}
	}

	public Project findProjectByName(String name) {
		String idQueryText = "SELECT p FROM Project p WHERE p.name= :projectName";
		TypedQuery<Project> idQuery = em.createQuery(idQueryText, Project.class);
		idQuery.setParameter("projectName", name);

		try {
			return idQuery.getSingleResult();
		} catch (NoResultException e) {
			return null;
		}
	}

	public Project findProjectById(int projectId) {
		String idQueryText = "SELECT p FROM Project p WHERE p.id= :projectId";
		TypedQuery<Project> idQuery = em.createQuery(idQueryText, Project.class);
		idQuery.setParameter("projectId", projectId);

		try {
			return idQuery.getSingleResult();
		} catch (NoResultException e) {
			return null;
		}
	}
}

package com.example.beer.dao;

import javax.ejb.Singleton;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;

import com.example.beer.model.Project;

@Singleton
public class ProjectDAO {

	@PersistenceContext
	private EntityManager em;

	public boolean addProject(Project project) {
		Project foundProject = findProjectByName(project.getName());

		if (foundProject == null) {
			em.persist(project);
			return true;
		} else {
			// TODO: Maybe update project title or users, or tasks?
			return false;
		}
	}

	public Project findProjectByName(String name) {
		String idQueryText = "SELECT p FROM Project p WHERE p.name= :projectName";
		TypedQuery<Project> idQuery = em.createQuery(idQueryText, Project.class);
		idQuery.setParameter("projectName", name);

		try {
			return idQuery.getSingleResult();
		} catch (NoResultException e) {
			return null;
		}
	}

	public Project findProjectById(int projectId) {
		String idQueryText = "SELECT p FROM Project p WHERE p.id= :projectId";
		TypedQuery<Project> idQuery = em.createQuery(idQueryText, Project.class);
		idQuery.setParameter("projectId", projectId);

		try {
			return idQuery.getSingleResult();
		} catch (NoResultException e) {
			return null;
		}
	}
}

Fix a logical error. A new project was persisted if it was already found found in the database. It should be the opposite


import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public final class Benchmark {

    private static final String PATTERN_EMAIL = "[\\w.+-]+@[\\w.-]+\\.[\\w.-]+";
    private static final String PATTERN_URI = "[\\w]+://[^/\\s?#]+[^\\s?#]+(?:\\?[^\\s#]*)?(?:#[^\\s]*)?";
    private static final String PATTERN_IP = "(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9])\\.){3}" +
                                             "(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9])";

    public static void main(String... args) throws IOException {
        if (args.length != 1) {
            System.out.println("Usage: java Benchmark <filename>");
            System.exit(1);
        }

        final String data = Files.readString(Paths.get(args[0]));

        measure(data, PATTERN_EMAIL);
        measure(data, PATTERN_URI);
        measure(data, PATTERN_IP);
    }

    private static void measure(String data, String pattern) {
        long startTime = System.nanoTime();

        final Matcher matcher = Pattern.compile(pattern).matcher(data);
        int count = 0;
        while (matcher.find()) {
            ++count;
        }

        long elapsed = System.nanoTime() - startTime;

        System.out.println(elapsed / 1e6 + " - " + count);
    }
}

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public final class Benchmark {
    public static void main(String... args) throws IOException {
        if (args.length != 1) {
            System.out.println("Usage: java Benchmark <filename>");
            System.exit(1);
        }

        final String data = Files.readString(Paths.get(args[0]));

        measure(data, "[\\w.+-]+@[\\w.-]+\\.[\\w.-]+");
        measure(data, "[\\w]+://[^/\\s?#]+[^\\s?#]+(?:\\?[^\\s#]*)?(?:#[^\\s]*)?");
        measure(data, "(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9])\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9])");
    }

    private static void measure(String data, String pattern) {
        long startTime = System.nanoTime();

        final Matcher matcher = Pattern.compile(pattern).matcher(data);
        int count = 0;
        while (matcher.find()) {
            ++count;
        }

        long elapsed = System.nanoTime() - startTime;

        System.out.println(elapsed / 1e6 + " - " + count);
    }
}

Put patterns directly in function call to follow style of the rest of benchmarks


package org.gbif.nameparser;

import org.gbif.nameparser.api.ParsedAuthorship;
import org.gbif.nameparser.api.ParsedName;

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

public class ParserConfigs {

  private final Map<String, ParsedName> names = new HashMap<>();
  private final Map<String, ParsedAuthorship> authorships = new HashMap<>();

  public ParsedName forName(String name) {
    name = ParsingJob.preClean(name, null);
    return names.get(name);
  }

  public ParsedAuthorship forAuthorship(String authorship) {
    authorship = ParsingJob.preClean(authorship, null);
    return authorships.get(authorship);
  }
}

package org.gbif.nameparser;

import org.gbif.nameparser.api.ParsedAuthorship;
import org.gbif.nameparser.api.ParsedName;

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

public class ParserConfigs {

  private final Map<String, ParsedName> names = new HashMap<>();
  private final Map<String, ParsedAuthorship> authorships = new HashMap<>();

  public ParsedName forName(String name) {
    name = ParsingJob.preClean(name, null);
    return names.get(name);
  }

  public ParsedAuthorship forAuthorship(String authorship) {
    authorship = ParsingJob.preClean(authorship, null);
    return authorships.get(authorship);
  }

  public void setName(String sciname, ParsedName pn) {
    names.put(ParsingJob.preClean(sciname, null), pn);
  }

  public ParsedName deleteName(String name) {
    return names.remove(ParsingJob.preClean(name, null));
  }

  public void setAuthorship(String authorship, ParsedAuthorship pn) {
    authorships.put(ParsingJob.preClean(authorship, null), pn);
  }

  public ParsedAuthorship deleteAuthorship(String authorship) {
    return authorships.remove(ParsingJob.preClean(authorship, null));
  }
}

Add methods to change parser override configs


package com.amebame.triton.server;

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

import javax.inject.Inject;
import javax.inject.Singleton;

import com.amebame.triton.config.TritonServerConfiguration;
import com.amebame.triton.util.NamedThreadFactory;

@Singleton
public class TritonServerContext {

	private TritonServerMethodMap methodMap;

	private ExecutorService executor;

	@Inject
	public TritonServerContext(TritonServerConfiguration config) {
		methodMap = new TritonServerMethodMap();
		executor = Executors.newFixedThreadPool(
				config.getNetty().getWorker(),
				new NamedThreadFactory("triton-worker-"));
	}

	/**
	 * Add server methods from the target object
	 * @param target
	 */
	public void addServerMethod(Object target) {
		methodMap.register(target);
	}

	/**
	 * Get server method by name
	 * @param name
	 * @return
	 */
	public TritonServerMethod getServerMethod(String name) {
		return methodMap.getMethod(name);
	}

	/**
	 * Get worker executor
	 * @return
	 */
	public ExecutorService getWorkerExecutor() {
		return executor;
	}
}

package com.amebame.triton.server;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

import javax.inject.Inject;
import javax.inject.Singleton;

import com.amebame.triton.config.TritonServerConfiguration;
import com.amebame.triton.util.NamedThreadFactory;

@Singleton
public class TritonServerContext {

	private TritonServerMethodMap methodMap;

	private ExecutorService executor;

	@Inject
	public TritonServerContext(TritonServerConfiguration config) {
		methodMap = new TritonServerMethodMap();
		executor = new ThreadPoolExecutor(
				1,
				config.getNetty().getWorker(),
				60L,
				TimeUnit.SECONDS,
				new SynchronousQueue<Runnable>(),
				new NamedThreadFactory("triton-worker-"));
	}

	/**
	 * Add server methods from the target object
	 * @param target
	 */
	public void addServerMethod(Object target) {
		methodMap.register(target);
	}

	/**
	 * Get server method by name
	 * @param name
	 * @return
	 */
	public TritonServerMethod getServerMethod(String name) {
		return methodMap.getMethod(name);
	}

	/**
	 * Get worker executor
	 * @return
	 */
	public ExecutorService getWorkerExecutor() {
		return executor;
	}
}

Use SynchronousQueue as executor queue to enable expanding pools.


package at.ac.tuwien.inso.service;

import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.security.access.prepost.PreAuthorize;

import at.ac.tuwien.inso.entity.*;

import java.util.*;

public interface SubjectService {

    @PreAuthorize("isAuthenticated()")
    Page<Subject> findAll(Pageable pageable);

    @PreAuthorize("isAuthenticated()")
    Subject findOne(long id);

    @PreAuthorize("isAuthenticated()")
    List<Subject> searchForSubjects(String word);

    @PreAuthorize("hasRole('ADMIN')")
    Subject create(Subject subject);

    @PreAuthorize("hasRole('ADMIN')")
    Subject addLecturerToSubject(Long subjectId, Long lecturerUisUserId);

    @PreAuthorize("hasRole('ADMIN')")
    List<Lecturer> getAvailableLecturersForSubject(Long subjectId);

    @PreAuthorize("hasRole('ADMIN')")
    void removeLecturerFromSubject(Long subjectId, Long lecturerId);
}

package at.ac.tuwien.inso.service;

import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.security.access.prepost.PreAuthorize;

import at.ac.tuwien.inso.entity.*;

import java.util.*;

public interface SubjectService {

    @PreAuthorize("isAuthenticated()")
    Page<Subject> findAll(Pageable pageable);

    @PreAuthorize("isAuthenticated()")
    Subject findOne(long id);

    @PreAuthorize("isAuthenticated()")
    List<Subject> searchForSubjects(String word);

    @PreAuthorize("hasRole('ADMIN')")
    Subject create(Subject subject);

    @PreAuthorize("hasRole('ADMIN')")
    Subject addLecturerToSubject(Long subjectId, Long lecturerUisUserId);

    @PreAuthorize("hasRole('ADMIN')")
    List<Lecturer> getAvailableLecturersForSubject(Long subjectId);

    @PreAuthorize("hasRole('ADMIN')")
    Lecturer removeLecturerFromSubject(Long subjectId, Long lecturerUisUserId);
}

Add return value to removeLecturerFromSubject


package seedu.address.logic.commands;

import java.util.Set;

/**
 * Finds and lists all persons in address book whose name contains any of the argument keywords.
 * Keyword matching is case sensitive.
 */
public class FindCommand extends Command {

    public static final String COMMAND_WORD = "find";

    public static final String MESSAGE_USAGE = COMMAND_WORD + ": Finds all tasks whose names contain any of "
            + "the specified keywords (case-sensitive) and displays them as a list with index numbers.\n"
            + "Parameters: KEYWORD [MORE_KEYWORDS]...\n"
            + "Example: " + COMMAND_WORD + " CS2103";

    private final Set<String> keywords;

    public FindCommand(Set<String> keywords) {
        this.keywords = keywords;
    }

    @Override
    public CommandResult execute() {
        model.updateFilteredPersonList(keywords);
        return new CommandResult(getMessageForPersonListShownSummary(model.getFilteredPersonList().size()));
    }

}

package seedu.address.logic.commands;

import java.util.Set;

/**
 * Finds and lists all persons in address book whose name contains any of the argument keywords.
 * Keyword matching is case sensitive.
 */
public class FindCommand extends Command {

    public static final String COMMAND_WORD = "find";

    public static final String MESSAGE_USAGE = COMMAND_WORD + ": Finds all tasks whose names contain any of "
            + "the specified keywords (case-sensitive) and displays them as a list with index numbers.\n"
            + "Parameters: KEYWORD [MORE_KEYWORDS]...\n"
            + "Example: " + COMMAND_WORD + " CS2103";

    private final Set<String> keywords;

    public FindCommand(Set<String> keywords) {
        this.keywords = keywords;
    }

    @Override
    public CommandResult execute() {
        model.updateFilteredPersonList(keywords);
        return new CommandResult(getMessageForPersonListShownSummary(model.getFilteredPersonList().size()+model.getFilteredUndatedTaskList().size()));
    }

}

Update Number of tasks listed in Find command


package com.kurento.kmf.media.repository;

import java.io.IOException;

public abstract class MediaRepository {

	/**
	 *
	 * @return the created media id
	 * @throws IOException
	 *             if the media resource cannot be created
	 */
	public abstract String create() throws IOException;

	/**
	 *
	 * @param mediaId
	 * @throws IOException
	 *             it the media resource cannot be removed
	 */
	public abstract void remove(String mediaId) throws IOException;

	/**
	 *
	 * @param mediaId
	 * @return the path of the media resource with this id
	 * @throws IOException
	 *             if the media resource does not exist
	 */
	public abstract String getPath(String mediaId) throws IOException;

}

package com.kurento.kmf.media.repository;

import java.io.IOException;

public abstract class MediaRepository {

	/**
	 *
	 * @return the created media id
	 * @throws IOException
	 *             if the media resource cannot be created
	 */
	public abstract String create() throws IOException;

	/**
	 *
	 * @param mediaId
	 * @throws IOException
	 *             it the media resource cannot be removed
	 */
	public abstract void remove(String mediaId) throws IOException;

	/**
	 *
	 * @param mediaId
	 * @return the URI of the media resource with this id
	 * @throws IOException
	 *             if the media resource does not exist
	 */
	public abstract String getUri(String mediaId) throws IOException;

}

Replace getPath method by getUri


package com.codingchili.core.logging;

import io.vertx.core.Vertx;
import io.vertx.ext.unit.Async;
import io.vertx.ext.unit.TestContext;
import io.vertx.ext.unit.junit.VertxUnitRunner;
import org.junit.*;
import org.junit.runner.RunWith;

import com.codingchili.core.context.SystemContext;
import com.codingchili.core.testing.ContextMock;

import static com.codingchili.core.configuration.CoreStrings.NODE_LOGGING;

/**
 * @author Robin Duda
 *
 * Verify that the remote logger is pushing events to a remote.
 */
@RunWith(VertxUnitRunner.class)
public class RemoteLoggerTest {
    private SystemContext context;

    @Before
    public void setUp() {
        context = new ContextMock(Vertx.vertx());
    }

    @After
    public void tearDown(TestContext test) {
        context.vertx().close(test.asyncAssertSuccess());
    }

    @Test
    public void testLogRemote(TestContext test) {
        mockNode(test.async());

        new RemoteLogger(context).log("text");
    }

    private void mockNode(Async async) {
        context.bus().consumer(NODE_LOGGING).handler(message -> {
            async.complete();
        });
    }
}

package com.codingchili.core.logging;

import io.vertx.core.Vertx;
import io.vertx.ext.unit.Async;
import io.vertx.ext.unit.TestContext;
import io.vertx.ext.unit.junit.VertxUnitRunner;
import org.junit.*;
import org.junit.runner.RunWith;

import com.codingchili.core.context.ServiceContext;
import com.codingchili.core.testing.ContextMock;

import static com.codingchili.core.configuration.CoreStrings.NODE_LOGGING;

/**
 * @author Robin Duda
 *
 * Verify that the remote logger is pushing events to a remote.
 */
@RunWith(VertxUnitRunner.class)
public class RemoteLoggerTest {
    private ServiceContext context;

    @Before
    public void setUp() {
        context = new ContextMock(Vertx.vertx());
    }

    @After
    public void tearDown(TestContext test) {
        context.vertx().close(test.asyncAssertSuccess());
    }

    @Test
    public void testLogRemote(TestContext test) {
        mockNode(test.async());

        new RemoteLogger(context).log("text");
    }

    private void mockNode(Async async) {
        context.bus().consumer(NODE_LOGGING).handler(message -> {
            async.complete();
        });
    }
}

Fix compile error in tests.


package com.cloud.flyway;

import com.cloud.legacymodel.exceptions.CloudRuntimeException;
import org.flywaydb.core.Flyway;
import org.flywaydb.core.api.FlywayException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;

public class FlywayDB {

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

    public void check() {
        logger.info("Start database migration");

        final InitialContext cxt;
        final DataSource dataSource;

        try {
            cxt = new InitialContext();
            dataSource = (DataSource) cxt.lookup("java:/comp/env/jdbc/cosmic");
        } catch (final NamingException e) {
            logger.error(e.getMessage(), e);
            throw new CloudRuntimeException(e.getMessage(), e);
        }

        final Flyway flyway = new Flyway();
        flyway.setDataSource(dataSource);
        flyway.setTable("schema_version");
        flyway.setEncoding("UTF-8");

        try {
            flyway.migrate();
        } catch (final FlywayException e) {
            logger.error(e.getMessage(), e);
            throw new CloudRuntimeException(e.getMessage(), e);
        }

        logger.info("Database migration successful");
    }
}

package com.cloud.flyway;

import com.cloud.legacymodel.exceptions.CloudRuntimeException;

import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;

import org.flywaydb.core.Flyway;
import org.flywaydb.core.api.FlywayException;
import org.flywaydb.core.api.configuration.FluentConfiguration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class FlywayDB {

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

    public void check() {
        logger.info("Start database migration");

        final InitialContext cxt;
        final DataSource dataSource;

        try {
            cxt = new InitialContext();
            dataSource = (DataSource) cxt.lookup("java:/comp/env/jdbc/cosmic");
        } catch (final NamingException e) {
            logger.error(e.getMessage(), e);
            throw new CloudRuntimeException(e.getMessage(), e);
        }

        final FluentConfiguration flywayConfig = new FluentConfiguration()
                .encoding("UTF-8")
                .dataSource(dataSource)
                .table("schema_version");
        final Flyway flyway = new Flyway(flywayConfig);

        try {
            flyway.migrate();
        } catch (final FlywayException e) {
            logger.error(e.getMessage(), e);
            throw new CloudRuntimeException(e.getMessage(), e);
        }

        logger.info("Database migration successful");
    }
}

Change deprecated flyway methods to new FluentConfiguration


package nakadi;

/**
 * Can be called by the {@link StreamObserver} to indicate a batch has been processed.
 *
 * Typically this is used to implement a checkpointer that can store the position of the
 * client in the stream to track their progress.
 */
public interface StreamOffsetObserver {

  /**
   * Receives a {@link StreamCursorContext} that can be used to checkpoint (or more generally,
   * observe) progress in the stream.
   *

   * The default observer for a subscription based {@link StreamProcessor} (one which has been
   * given a subscription id via {@link StreamConfiguration#subscriptionId} is
   * {@link SubscriptionOffsetObserver}. This will checkpoint back to the server each time
   * it's called. This behaviour can be replaced by supplying a different checkpointer via
   * {@link StreamProcessor.Builder#streamOffsetObserver}.
   *
   * @param streamCursorContext the batch's {@link StreamCursorContext}.
   *
   * todo: see if we need to declare checked exceptions here to force the observer to handle.
   */
  void onNext(StreamCursorContext streamCursorContext) throws NakadiException;
}

package nakadi;

/**
 * Can be called by the {@link StreamObserver} to indicate a batch has been processed.
 *
 * Typically this is used to implement a checkpointer that can store the position of the
 * client in the stream to track their progress.
 */
public interface StreamOffsetObserver {

  /**
   * Receives a {@link StreamCursorContext} that can be used to checkpoint (or more generally,
   * observe) progress in the stream.
   *

   * The default observer for a subscription based {@link StreamProcessor} (one which has been
   * given a subscription id via {@link StreamConfiguration#subscriptionId} is
   * {@link SubscriptionOffsetObserver}. This will checkpoint back to the server each time
   * it's called. This behaviour can be replaced by supplying a different checkpointer via
   * {@link StreamProcessor.Builder#streamOffsetObserver}.
   *
   * @param streamCursorContext the batch's {@link StreamCursorContext}.
   *
   */
  void onNext(StreamCursorContext streamCursorContext) throws NakadiException;
}

Remove comment, offset observer will throw runtime exceptions


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

/**
 * Workers allow running pieces of work in the background, either
 * in-process in isolated classloaders or out-of-process in reausable
 * daemons.
 *
 * @since 3.5
 */
@org.gradle.api.Incubating
package org.gradle.workers;

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

/**
 * Workers allow running pieces of work in the background, either
 * in-process in isolated classloaders or out-of-process in reusable
 * daemons.
 *
 * @since 3.5
 */
@org.gradle.api.Incubating
package org.gradle.workers;

Fix a typo in some Javadoc.


/*
 * Copyright (c) 2015 Ushahidi.
 * This program is free software: you can redistribute it and/or modify it under
 * the terms of the GNU Affero General Public License as published by the Free
 * Software Foundation, either version 3 of the License, or (at your option)
 * any later version.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program in the file LICENSE-AGPL. If not, see
 * https://www.gnu.org/licenses/agpl-3.0.html
 */

package com.ushahidi.android.domain.entity;

import com.addhen.android.raiburari.domain.entity.Entity;

/**
 * GeoJson Entity
 *
 * @author Ushahidi Team <team@ushahidi.com>
 */
public class GeoJson extends Entity {

    private String mGeoJson;

    public String getGeoJson() {
        return mGeoJson;
    }

    public void setGeoJson(String geoJson) {
        mGeoJson = geoJson;
    }

    @Override
    public String toString() {
        return "GeoJson{" +
                "mID='" + _id + '\'' +
                ", geojson='" + mGeoJson + '\'' +
                '}';
    }
}

/*
 * Copyright (c) 2015 Ushahidi.
 * This program is free software: you can redistribute it and/or modify it under
 * the terms of the GNU Affero General Public License as published by the Free
 * Software Foundation, either version 3 of the License, or (at your option)
 * any later version.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program in the file LICENSE-AGPL. If not, see
 * https://www.gnu.org/licenses/agpl-3.0.html
 */

package com.ushahidi.android.domain.entity;

import com.addhen.android.raiburari.domain.entity.Entity;

/**
 * GeoJson Entity
 *
 * @author Ushahidi Team <team@ushahidi.com>
 */
public class GeoJson extends Entity {

    private String mGeoJson;

    private Long mDeploymentId;

    public String getGeoJson() {
        return mGeoJson;
    }

    public void setGeoJson(String geoJson) {
        mGeoJson = geoJson;
    }

    @Override
    public String toString() {
        return "GeoJson{" +
                "mID='" + _id + '\'' +
                "mDeploymentId='" + mDeploymentId + '\'' +
                ", geojson='" + mGeoJson + '\'' +
                '}';
    }
}

Add deployment Id as all entities have to be associated with a deployment


package com.antonjohansson.geotest.docker;

import com.spotify.docker.client.DockerClient;
import com.spotify.docker.client.exceptions.DockerException;
import com.spotify.docker.client.messages.ContainerInfo;

/**
 * Defines a single docker container.
 */
public class DockerContainer implements AutoCloseable
{
    private final DockerClient client;
    private final String containerId;

    /**
     * Constructs a new {@link DockerContainer}.
     *
     * @param client The docker client. Used to close the container.
     * @param containerId The identifier of the container.
     */
    DockerContainer(DockerClient client, String containerId)
    {
        this.client = client;
        this.containerId = containerId;
    }

    public String getContainerId()
    {
        return containerId;
    }

    @Override
    public void close()
    {
        try
        {
            ContainerInfo info = client.inspectContainer(containerId);
            if (info.state().running())
            {
                client.killContainer(containerId);
            }
            client.removeContainer(containerId);
        }
        catch (DockerException | InterruptedException e)
        {
            throw new RuntimeException(e);
        }
    }
}

package com.antonjohansson.geotest.docker;

import static com.spotify.docker.client.DockerClient.RemoveContainerParam.removeVolumes;

import com.spotify.docker.client.DockerClient;
import com.spotify.docker.client.exceptions.DockerException;
import com.spotify.docker.client.messages.ContainerInfo;

/**
 * Defines a single docker container.
 */
public class DockerContainer implements AutoCloseable
{
    private final DockerClient client;
    private final String containerId;

    /**
     * Constructs a new {@link DockerContainer}.
     *
     * @param client The docker client. Used to close the container.
     * @param containerId The identifier of the container.
     */
    DockerContainer(DockerClient client, String containerId)
    {
        this.client = client;
        this.containerId = containerId;
    }

    public String getContainerId()
    {
        return containerId;
    }

    @Override
    public void close()
    {
        try
        {
            ContainerInfo info = client.inspectContainer(containerId);
            if (info.state().running())
            {
                client.killContainer(containerId);
            }
            client.removeContainer(containerId, removeVolumes());
        }
        catch (DockerException | InterruptedException e)
        {
            throw new RuntimeException(e);
        }
    }
}

Remove volumes when removing the container This to avoid leaving dangling volumes


package uk.org.cinquin.mutinack.misc_util;

import java.util.concurrent.ThreadFactory;

public class NamedPoolThreadFactory implements ThreadFactory {
	private int counter = 0;
	final String name;
	public NamedPoolThreadFactory(String name) {
		this.name = name;
	}

	@Override
	public Thread newThread(Runnable r) {
		Thread t = new Thread(r);
		t.setName(name + counter++);
		return t;
	}

}

package uk.org.cinquin.mutinack.misc_util;

import java.util.concurrent.ThreadFactory;

public class NamedPoolThreadFactory implements ThreadFactory {
	private int counter = 0;
	final String name;
	public NamedPoolThreadFactory(String name) {
		this.name = name;
	}

	@Override
	public Thread newThread(Runnable r) {
		Thread t = new Thread(r);
		t.setName(name + counter++);
		t.setDaemon(true);
		return t;
	}

}

Mark pool threads as daemon.


/*
 * Copyright 2014 Patrik Karlsson.
 *
 * 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 se.trixon.toolbox.core.base;

import java.util.ResourceBundle;
import org.openide.windows.TopComponent;

/**
 *
 * @author Patrik Karlsson <patrik@trixon.se>
 */
public abstract class ToolTopComponent extends TopComponent {

    protected static final int TOOLBAR_ICON_SIZE = 24;
    protected ResourceBundle mBundle;
    protected String mToolName;
}

/*
 * Copyright 2014 Patrik Karlsson.
 *
 * 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 se.trixon.toolbox.core.base;

import java.util.ResourceBundle;
import org.openide.awt.StatusDisplayer;
import org.openide.windows.TopComponent;
import se.trixon.toolbox.core.Toolbox;

/**
 *
 * @author Patrik Karlsson <patrik@trixon.se>
 */
public abstract class ToolTopComponent extends TopComponent {

    protected static final int TOOLBAR_ICON_SIZE = 24;
    protected ResourceBundle mBundle;
    protected String mToolName;
    private String mStatus = "";

    @Override
    protected void componentDeactivated() {
        super.componentDeactivated();
        mStatus = StatusDisplayer.getDefault().getStatusText();
        Toolbox.setStatusText("");
    }

    @Override
    protected void componentActivated() {
        super.componentActivated();
        Toolbox.setStatusText(mStatus);
    }
}

Clear and reset status text.


package net.machinemuse.numina.recipe;

import net.minecraft.block.Block;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;

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

/**
 * Author: MachineMuse (Claire Semple)
 * Created: 5:06 PM, 11/4/13
 */
public class ItemNameMappings {
    private static Map<String, ItemStack> itemMap;

    private static Map<String, ItemStack> getItemMap() {
        if (itemMap == null) {
            itemMap = new HashMap<String, ItemStack>();
            for (Object obj : Block.blockRegistry) {
                Block block = (Block)obj;
                if (block != null && block.getUnlocalizedName() != null) {
                    itemMap.put(block.getUnlocalizedName(), new ItemStack(block));
                }
            }
            for (Object obj : Item.itemRegistry) {
                Item item = (Item)obj;
                if (item != null) {
                    if(item.getHasSubtypes()) {
                        List<ItemStack> stacklist = new ArrayList<ItemStack>();
                        for(CreativeTabs tab : item.getCreativeTabs()) {
                            item.getSubItems(item, tab, stacklist);
                        }
                        for(ItemStack stack : stacklist) {
                            itemMap.put(stack.getUnlocalizedName(), stack.copy());
                        }
                    } else {
                        itemMap.put(item.getUnlocalizedName(), new ItemStack(item));
                    }
                }
            }
        }
        return itemMap;
    }

    public static ItemStack getItem(String name) {
        if (getItemMap().containsKey(name))
            return getItemMap().get(name);
        else
            return null;
    }
}

package net.machinemuse.numina.recipe;

import net.minecraft.block.Block;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;

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

/**
 * Author: MachineMuse (Claire Semple)
 * Created: 5:06 PM, 11/4/13
 */
public class ItemNameMappings {
    private static Map<String, ItemStack> itemMap;

    private static Map<String, ItemStack> getItemMap() {
        if (itemMap == null) {
            itemMap = new HashMap<String, ItemStack>();
            for (Object obj : Block.blockRegistry) {
                Block block = (Block)obj;
                if (block != null && block.getUnlocalizedName() != null) {
                    itemMap.put(block.getUnlocalizedName(), new ItemStack(block));
                }
            }
            for (Object obj : Item.itemRegistry) {
                Item item = (Item)obj;
                if (item != null && item.getUnlocalizedName() != null) {
                    itemMap.put(item.getUnlocalizedName(), new ItemStack(item));
                }
            }
        }
        return itemMap;
    }

    public static ItemStack getItem(String name) {
        if (getItemMap().containsKey(name))
            return getItemMap().get(name);
        else
            return null;
    }
}

Undo change that makes client-side issue. Will need another way to get sub-items


/*
 * Copyright (C) 2008 XStream Committers.
 * All rights reserved.
 *
 * The software in this package is published under the terms of the BSD
 * style license a copy of which has been included with this distribution in
 * the LICENSE.txt file.
 *
 * Created on 13. October 2008 by Joerg Schaible
 */
package com.thoughtworks.xstream.core.util;

public final class FastField {
    private final String name;
    private final Class declaringClass;

    public FastField(Class definedIn, String name) {
        this.name = name;
        this.declaringClass = definedIn;
    }

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

    public Class getDeclaringClass() {
        return this.declaringClass;
    }

    public boolean equals(Object obj) {
        if (this == obj) {
            return true;
        }
        if (this == null) {
            return false;
        }
        if (obj.getClass() == FastField.class) {
            final FastField field = (FastField)obj;
            return name.equals(field.getName())
                && declaringClass.equals(field.getDeclaringClass());
        }
        return false;
    }

    public int hashCode() {
        return name.hashCode() ^ declaringClass.hashCode();
    }

    public String toString() {
        return declaringClass.getName() + "[" + name + "]";
    }
}

/*
 * Copyright (C) 2008, 2010 XStream Committers.
 * All rights reserved.
 *
 * The software in this package is published under the terms of the BSD
 * style license a copy of which has been included with this distribution in
 * the LICENSE.txt file.
 *
 * Created on 13. October 2008 by Joerg Schaible
 */
package com.thoughtworks.xstream.core.util;

public final class FastField {
    private final String name;
    private final Class declaringClass;

    public FastField(Class definedIn, String name) {
        this.name = name;
        this.declaringClass = definedIn;
    }

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

    public Class getDeclaringClass() {
        return this.declaringClass;
    }

    public boolean equals(Object obj) {
        if (this == obj) {
            return true;
        }
        if (this == null) {
            return false;
        }
        if (obj.getClass() == FastField.class) {
            final FastField field = (FastField)obj;
            if ((declaringClass == null && field.declaringClass != null)
                || (declaringClass != null && field.declaringClass == null)) {
                return false;
            }
            return name.equals(field.getName())
                && (declaringClass == null || declaringClass.equals(field.getDeclaringClass()));
        }
        return false;
    }

    public int hashCode() {
        return name.hashCode() ^ (declaringClass == null ? 0 : declaringClass.hashCode());
    }

    public String toString() {
        return (declaringClass == null ? "" : declaringClass.getName() + ".") + name;
    }
}

Allow null as defining class.


package net.honeybadgerlabs.adventurequest;

import android.app.Activity;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.GridView;
import android.widget.TextView;

public class ProfileFragment extends Fragment {
  private GridView listView;
  private TextView button;
  private StatAdapter adapter;

  @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.profile, container, false);

    listView = (GridView) view.findViewById(R.id.attribute_list);
    button = (TextView) view.findViewById(R.id.spend_points);

    return view;
  }

  @Override public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    adapter = ((TitleActivity) getActivity()).getStatAdapter();
    listView.setAdapter(adapter);
    updateButton();
  }

  public void updateButton() {
    try {
      int points = ((TitleActivity) getActivity()).getCharLevel() - adapter.totalPoints() - 1;

      if (points > 0) {
        String message = getResources().getQuantityString(R.plurals.points, points, points);
        button.setText(message);
        button.setVisibility(View.VISIBLE);
      } else {
        button.setVisibility(View.GONE);
      }
    } catch (NullPointerException e) {
    }
  }
}

package net.honeybadgerlabs.adventurequest;

import android.app.Activity;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.GridView;
import android.widget.TextView;

public class ProfileFragment extends Fragment {
  private GridView listView;
  private TextView button;
  private StatAdapter adapter;

  @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.profile, container, false);

    listView = (GridView) view.findViewById(R.id.attribute_list);
    button = (TextView) view.findViewById(R.id.spend_points);

    return view;
  }

  @Override public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    adapter = ((TitleActivity) getActivity()).getStatAdapter();
    listView.setAdapter(adapter);
    updateButton();
  }

  public void updateButton() {
    TitleActivity activity = (TitleActivity) getActivity();

    if (activity != null) {
      int points = ((TitleActivity) getActivity()).getCharLevel() - adapter.totalPoints() - 1;

      if (points > 0) {
        String message = getResources().getQuantityString(R.plurals.points, points, points);
        button.setText(message);
        button.setVisibility(View.VISIBLE);
      } else {
        button.setVisibility(View.GONE);
      }
    }
  }
}

Fix issue with updating button before activity loaded


package com.hubspot.jinjava.lib.tag;

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

import com.hubspot.jinjava.BaseInterpretingTest;
import org.junit.Test;

public class CycleTagTest extends BaseInterpretingTest {

  @Test
  public void itDefaultsNullToImage() {
    String template = "{% for item in [0,1] %}{% cycle {{item}} %}{% endfor %}";
    assertThat(interpreter.render(template)).isEqualTo("{{item}}{{item}}");
  }
}

package com.hubspot.jinjava.lib.tag;

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

import com.hubspot.jinjava.BaseInterpretingTest;
import org.junit.Test;

public class CycleTagTest extends BaseInterpretingTest {

  @Test
  public void itDefaultsNullToImage() {
    String template = "{% for item in [0,1] %}{% cycle {{item}} %}{% endfor %}";
    assertThat(interpreter.render(template)).isEqualTo("{{item}}{{item}}");
  }

  @Test
  public void itDefaultsMultipleNullToImage() {
    String template = "{% for item in [0,1] %}{% cycle {{foo}},{{bar}} %}{% endfor %}";
    assertThat(interpreter.render(template)).isEqualTo("{{foo}}{{bar}}");
  }

  @Test
  public void itDefaultsNullToImageUsingAs() {
    String template =
      "{% for item in [0,1] %}{% cycle {{item}} as var %}{% cycle var %}{% endfor %}";
    assertThat(interpreter.render(template)).isEqualTo("{{item}}{{item}}");
  }

  @Test
  public void itDefaultsMultipleNullToImageUsingAs() {
    String template =
      "{% for item in [0,1] %}{% cycle {{foo}},{{bar}} as var %}{% cycle var %}{% endfor %}";
    assertThat(interpreter.render(template)).isEqualTo("{{foo}}{{bar}}");
  }
}

Add more null handling cycle tag tests


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

//
// This source code implements specifications defined by the Java
// Community Process. In order to remain compliant with the specification
// DO NOT add / change / or delete method signatures!
//

package javax.persistence;

public interface TupleElement<X> {
    Class<X> getJavaType();

    String getAlias();
}

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

//
// This source code implements specifications defined by the Java
// Community Process. In order to remain compliant with the specification
// DO NOT add / change / or delete method signatures!
//

package javax.persistence;

public interface TupleElement<X> {
    Class<? extends X> getJavaType();

    String getAlias();
}

Update Geronimo JPA 2.0 specs EA7


package fr.neamar.kiss.db;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

class DB extends SQLiteOpenHelper {

    private final static int DB_VERSION = 1;
    private final static String DB_NAME = "summon.s3db";

    public DB(Context context) {
        super(context, DB_NAME, null, DB_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase database) {
        database.execSQL("CREATE TABLE history ( _id INTEGER PRIMARY KEY AUTOINCREMENT, query TEXT NOT NULL, record TEXT NOT NULL)");
    }

    @Override
    public void onUpgrade(SQLiteDatabase arg0, int arg1, int arg2) {
        // See
        // http://www.drdobbs.com/database/using-sqlite-on-android/232900584
    }
}

package fr.neamar.kiss.db;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

class DB extends SQLiteOpenHelper {

    private final static int DB_VERSION = 1;
    private final static String DB_NAME = "kiss.s3db";

    public DB(Context context) {
        super(context, DB_NAME, null, DB_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase database) {
        database.execSQL("CREATE TABLE history ( _id INTEGER PRIMARY KEY AUTOINCREMENT, query TEXT, record TEXT NOT NULL)");
    }

    @Override
    public void onUpgrade(SQLiteDatabase arg0, int arg1, int arg2) {
        // See
        // http://www.drdobbs.com/database/using-sqlite-on-android/232900584
    }
}

Store empty queries in history


package at.ac.tuwien.inso.service;

import at.ac.tuwien.inso.entity.Semester;
import at.ac.tuwien.inso.repository.SemesterRepository;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class SemesterService {

    @Autowired
    private SemesterRepository semesterRepository;

    public Semester getCurrentSemester() {
        return semesterRepository.findFirstByOrderByIdDesc();
    }

    public Iterable<Semester> getAllSemesters() {
        return semesterRepository.findAllByOrderByIdDesc();
    }
}

package at.ac.tuwien.inso.service;

import at.ac.tuwien.inso.entity.Semester;
import at.ac.tuwien.inso.repository.SemesterRepository;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class SemesterService {

    @Autowired
    private SemesterRepository semesterRepository;

    public Semester create(Semester semester) {
        return semesterRepository.save(semester);
    }

    public Semester getCurrentSemester() {
        return semesterRepository.findFirstByOrderByIdDesc();
    }

    public Iterable<Semester> getAllSemesters() {
        return semesterRepository.findAllByOrderByIdDesc();
    }
}

Add create() to semeser service


/*
       Licensed to the Apache Software Foundation (ASF) under one
       or more contributor license agreements.  See the NOTICE file
       distributed with this work for additional information
       regarding copyright ownership.  The ASF licenses this file
       to you under the Apache License, Version 2.0 (the
       "License"); you may not use this file except in compliance
       with the License.  You may obtain a copy of the License at

         http://www.apache.org/licenses/LICENSE-2.0

       Unless required by applicable law or agreed to in writing,
       software distributed under the License is distributed on an
       "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
       KIND, either express or implied.  See the License for the
       specific language governing permissions and limitations
       under the License.
 */

package __ID__;

import android.os.Bundle;
import org.apache.cordova.*;

public class __ACTIVITY__ extends DroidGap
{
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        Config.init(this);
        super.loadUrl("file:///android_asset/www/index.html");
    }
}

/*
       Licensed to the Apache Software Foundation (ASF) under one
       or more contributor license agreements.  See the NOTICE file
       distributed with this work for additional information
       regarding copyright ownership.  The ASF licenses this file
       to you under the Apache License, Version 2.0 (the
       "License"); you may not use this file except in compliance
       with the License.  You may obtain a copy of the License at

         http://www.apache.org/licenses/LICENSE-2.0

       Unless required by applicable law or agreed to in writing,
       software distributed under the License is distributed on an
       "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
       KIND, either express or implied.  See the License for the
       specific language governing permissions and limitations
       under the License.
 */

package __ID__;

import android.os.Bundle;
import org.apache.cordova.*;

public class __ACTIVITY__ extends DroidGap
{
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        Config.init(this);
        super.loadUrl(Config.getStartUrl());
        //super.loadUrl("file:///android_asset/www/index.html")
    }
}

Add configurable start location to config.xml and template


package com.conveyal.geom2gtfs;

import org.onebusaway.gtfs.model.AgencyAndId;
import org.onebusaway.gtfs.model.Stop;

import com.vividsolutions.jts.geom.Coordinate;

import java.util.concurrent.atomic.AtomicInteger;

public class ProtoRouteStop {
        // TODO: this is kind of hacky, we should really be using a separate ID space for each feed.
        private AtomicInteger createdStopId = new AtomicInteger();

        public ProtoRouteStop (Coordinate coord, double dist) {
            this.coord = coord;
            this.dist = dist;
            this.stop = new Stop();
            stop.setLat(coord.y);
            stop.setLon(coord.x);
            int stopId = createdStopId.incrementAndGet();
            stop.setName("Stop " + stopId);
            stop.setId(new AgencyAndId(Main.DEFAULT_AGENCY_ID, "created_stop_" + stopId));
        }

        public ProtoRouteStop (Stop stop, double dist) {
            this.stop = stop;
            this.coord = new Coordinate(stop.getLon(), stop.getLat());
            this.dist = dist;
        }

	public Coordinate coord;
	public double dist;
	public Stop stop;
}

package com.conveyal.geom2gtfs;

import org.onebusaway.gtfs.model.AgencyAndId;
import org.onebusaway.gtfs.model.Stop;

import com.vividsolutions.jts.geom.Coordinate;

import java.util.concurrent.atomic.AtomicInteger;

public class ProtoRouteStop {
        // TODO: this is kind of hacky, we should really be using a separate ID space for each feed.
        private static AtomicInteger createdStopId = new AtomicInteger();

        public ProtoRouteStop (Coordinate coord, double dist) {
            this.coord = coord;
            this.dist = dist;
            this.stop = new Stop();
            stop.setLat(coord.y);
            stop.setLon(coord.x);
            int stopId = createdStopId.incrementAndGet();
            stop.setName("Stop " + stopId);
            stop.setId(new AgencyAndId(Main.DEFAULT_AGENCY_ID, "created_stop_" + stopId));
        }

        public ProtoRouteStop (Stop stop, double dist) {
            this.stop = stop;
            this.coord = new Coordinate(stop.getLon(), stop.getLat());
            this.dist = dist;
        }

	public Coordinate coord;
	public double dist;
	public Stop stop;
}

Make sure stops get unique IDs.


package com.decentralizeddatabase.reno;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.SecretKeySpec;
import java.security.InvalidKeyException;
import java.security.Key;
import java.security.NoSuchAlgorithmException;

/*Initialize and use this class to deal with block encryption and decryption*/
public class CryptoBlock {

    private Cipher cipher;

    public CryptoBlock() throws NoSuchPaddingException, NoSuchAlgorithmException {
        this.cipher = Cipher.getInstance("AES");
    }

    /*
        Inputs: String (data block), String (16 byte secret key)
        Outputs: byte[] (encrypted data block)
     */
    public byte[] encrypt(String block, String key) throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException {
        Key aesKey = new SecretKeySpec(key.getBytes(), "AES");
        cipher.init(Cipher.ENCRYPT_MODE, aesKey);
        byte[] encrypted = cipher.doFinal(block.getBytes());
        return encrypted;
    }

    /*
        Inputs: byte[] (encrypted data block), String (16 byte secret key)
        Outputs: String (decrypted data block)
     */
    public String decrypt(byte[] block, String key) throws InvalidKeyException, BadPaddingException, IllegalBlockSizeException {
        Key aesKey = new SecretKeySpec(key.getBytes(), "AES");
        cipher.init(Cipher.DECRYPT_MODE, aesKey);
        String decrypted = new String(cipher.doFinal(block));
        return decrypted;
    }
}

package com.decentralizeddatabase.reno;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.SecretKeySpec;
import java.security.InvalidKeyException;
import java.security.Key;
import java.security.NoSuchAlgorithmException;

public class CryptoBlock {

    private final Cipher cipher;

    public CryptoBlock() throws NoSuchPaddingException, NoSuchAlgorithmException {
        this.cipher = Cipher.getInstance("AES");
    }

    /**
     *  Inputs: String (data block), String (16 byte secret key)
     *  Outputs: byte[] (encrypted data block)
     */
    public byte[] encrypt(final byte[] block, final String key) throws NoSuchPaddingException,
							   NoSuchAlgorithmException,
							   InvalidKeyException,
							   BadPaddingException,
							   IllegalBlockSizeException {
        final Key aesKey = new SecretKeySpec(key.getBytes(), "AES");
        cipher.init(Cipher.ENCRYPT_MODE, aesKey);
        final byte[] encrypted = cipher.doFinal(block);
        return encrypted;
    }

    /**
     *   Inputs: byte[] (encrypted data block), String (16 byte secret key)
     *   Outputs: String (decrypted data block)
     */
    public String decrypt(final byte[] block, final String key) throws InvalidKeyException,
							   BadPaddingException,
							   IllegalBlockSizeException {
        Key aesKey = new SecretKeySpec(key.getBytes(), "AES");
        cipher.init(Cipher.DECRYPT_MODE, aesKey);
        String decrypted = new String(cipher.doFinal(block));
        return decrypted;
    }
}

Change encrypt to use byte array


package pl.com.chodera.myweather.common;

/**
 * Created by Adam Chodera on 2016-03-15.
 */
public class Commons {

    public static final String BASE_URL = "http://api.openweathermap.org/data/2.5/";

    public static final String OPEN_WEATHER_APP_ID = "6fc006e6b8cbdd1bc3fa490b467a1692";

    public static final int CHART_NUMBER_OF_X_VALUES = 8;

    public static final String PASCAL_UNIT = "hPa";

    public interface Chars {

        char SPACE = ' ';
        char COLON = ':';
        String NEW_LINE = System.getProperty("line.separator");
        char PLUS = '+';
        char H = 'h';
        char CELSIUS_UNIT = 'C';
        char PERCENT = '%';
    }

    public interface IntentKeys {

        String LOCATION_NAME = "key_ADVERTISEMENT";
    }

    public interface Animations {

        int DRAW_CHART_DATA = 1800;
    }
}

package pl.com.chodera.myweather.common;

/**
 * Created by Adam Chodera on 2016-03-15.
 */
public interface Commons {

    String BASE_URL = "http://api.openweathermap.org/data/2.5/";

    String OPEN_WEATHER_APP_ID = "6fc006e6b8cbdd1bc3fa490b467a1692";

    int CHART_NUMBER_OF_X_VALUES = 8;

    String PASCAL_UNIT = "hPa";

    interface Chars {

        char SPACE = ' ';
        char COLON = ':';
        String NEW_LINE = System.getProperty("line.separator");
        char PLUS = '+';
        char H = 'h';
        char CELSIUS_UNIT = 'C';
        char PERCENT = '%';
    }

    interface IntentKeys {

        String LOCATION_NAME = "key_ADVERTISEMENT";
    }

    interface Animations {

        int DRAW_CHART_DATA = 1800;
    }
}

Change class with static variables into interface


import java.lang.System;

public class Test {
        static {
                System.loadLibrary("react_render");
        }

        public static void main(String[] args) {
                System.out.println("Hello, Java!");

                react_render.set_debug(1);
                react_render.initialize("../bundle.js");
                react_render.render_path("Homepage");
        }
}

import java.lang.System;

public class Test {
        static {
                System.loadLibrary("react_render");
        }

        public static void main(String[] args) {
                System.out.println("Hello, Java!");

                react_render.set_debug(1);
                react_render.initialize("../bundle.js");
                react_render.render_path("/");
        }
}

Fix Java testcase to work


package beaform.gui.main;

import java.awt.BorderLayout;
import java.awt.Component;

import javax.swing.JPanel;
import javax.swing.JScrollPane;

import beaform.gui.debug.DebugUtilities;

/**
 * This class represents the main panel where all views will work in.
 *
 * @author Steven Post
 *
 */
public final class MainPanel extends JPanel {

	private static final long serialVersionUID = 1207348877338520359L;

	/** An inner panel for the actual content */
	private final JPanel panel = new JPanel(new BorderLayout());
	private final JScrollPane scrollPane = new JScrollPane(this.panel);

	public MainPanel() {
		super(new BorderLayout());
		this.add(this.scrollPane);
	}

	public void replaceActiveWindow(final Component comp) {
		if (this.panel.getComponentCount() > 0) {
			this.panel.remove(0);
		}
		this.panel.add(comp);
		this.panel.revalidate();
	}

	public void enableDebugBorders() {
		DebugUtilities.drawBorders(this.panel);
	}

}

package beaform.gui.main;

import java.awt.BorderLayout;
import java.awt.Component;

import javax.swing.JPanel;
import javax.swing.JScrollPane;

import beaform.gui.InterchangableWindowDisplayer;
import beaform.gui.debug.DebugUtilities;

/**
 * This class represents the main panel where all views will work in.
 *
 * @author Steven Post
 *
 */
public final class MainPanel extends JPanel implements InterchangableWindowDisplayer {

	private static final long serialVersionUID = 1207348877338520359L;

	/** An inner panel for the actual content */
	private final JPanel panel = new JPanel(new BorderLayout());
	private final JScrollPane scrollPane = new JScrollPane(this.panel);

	public MainPanel() {
		super(new BorderLayout());
		this.add(this.scrollPane);
	}

	@Override
	public void replaceActiveWindow(final Component comp) {
		if (this.panel.getComponentCount() > 0) {
			this.panel.remove(0);
		}
		this.panel.add(comp);
		this.panel.revalidate();
	}

	public void enableDebugBorders() {
		DebugUtilities.drawBorders(this.panel);
	}

}

Implement the ICWD interface in the main panel


package de.centerdevice.classcleaner.core.model;

public class CodeReference {

	private CodeElement src;
	private CodeElement dst;

	public CodeReference(CodeElement src, CodeElement dst) {
		this.src = src;
		this.dst = dst;
	}

	public CodeElement getDestination() {
		return dst;
	}

	public CodeElement getSource() {
		return src;
	}

	@Override
	public String toString() {
		return getClassNameWithFallback(src) + " -> " + getClassNameWithFallback(dst);
	}

	protected String getClassNameWithFallback(CodeElement element) {
		if (element == null) {
			return "none";
		}
		return element.getClassName();
	}
}

package de.centerdevice.classcleaner.core.model;

public class CodeReference {

	private final CodeElement src;
	private final CodeElement dst;

	public CodeReference(CodeElement src, CodeElement dst) {
		this.src = src;
		this.dst = dst;
	}

	public CodeElement getDestination() {
		return dst;
	}

	public CodeElement getSource() {
		return src;
	}

	@Override
	public String toString() {
		return getClassNameWithFallback(src) + " -> " + getClassNameWithFallback(dst);
	}

	protected String getClassNameWithFallback(CodeElement element) {
		if (element == null) {
			return "none";
		}
		return element.toString();
	}
}

Return full names of references in toString


package test.ccn.security.access;

import java.util.SortedSet;

import junit.framework.Assert;

import org.junit.BeforeClass;
import org.junit.Test;

import com.parc.ccn.data.ContentName;
import com.parc.ccn.library.CCNLibrary;
import com.parc.ccn.library.EnumeratedNameList;
import com.parc.ccn.library.io.repo.RepositoryOutputStream;

public class SampleTestRepo {
	static final String base = "/parc.com/csl/ccn/repositories";
	static final String file_name = "simon.txt";
	static final String txt =  "Sample text file from Simon.";
	static final String UTF8 = "UTF-8";

	@BeforeClass
	public static void setUpBeforeClass() throws Exception {
		ContentName name = ContentName.fromNative(base + "/" + file_name);
		RepositoryOutputStream os = new RepositoryOutputStream(name, CCNLibrary.getLibrary());

		os.write(txt.getBytes(UTF8));
		os.close();
	}

	@Test
	public void readWrite() throws Exception {
		EnumeratedNameList l = new EnumeratedNameList(ContentName.fromNative(base), null);
		SortedSet<ContentName> r = l.getNewData();
		Assert.assertNotNull(r);
		Assert.assertEquals(1, r.size());
		Assert.assertEquals(file_name.getBytes(UTF8), r.first().lastComponent());
	}
}

package test.ccn.security.access;

import java.util.SortedSet;

import junit.framework.Assert;

import org.junit.BeforeClass;
import org.junit.Test;

import com.parc.ccn.data.ContentName;
import com.parc.ccn.library.CCNLibrary;
import com.parc.ccn.library.EnumeratedNameList;
import com.parc.ccn.library.io.repo.RepositoryOutputStream;

public class SampleTestRepo {
	static final String base = "/parc.com/csl/ccn/repositories/SampleTestRepo";
	static final String file_name = "simon.txt";
	static final String txt =  "Sample text file from Simon.";
	static final String UTF8 = "UTF-8";

	@BeforeClass
	public static void setUpBeforeClass() throws Exception {
		ContentName name = ContentName.fromNative(base + "/" + file_name);
		RepositoryOutputStream os = new RepositoryOutputStream(name, CCNLibrary.getLibrary());

		os.write(txt.getBytes(UTF8));
		os.close();
	}

	@Test
	public void readWrite() throws Exception {
		EnumeratedNameList l = new EnumeratedNameList(ContentName.fromNative(base), null);
		SortedSet<ContentName> r = l.getNewData();
		Assert.assertNotNull(r);
		Assert.assertEquals(1, r.size());
		Assert.assertEquals(file_name.getBytes(UTF8), r.first().lastComponent());
	}
}

Make name more specific to avoid clash in repo


package net.openhft.chronicle.wire;

import net.openhft.chronicle.bytes.Bytes;
import net.openhft.chronicle.bytes.BytesUtil;
import org.junit.Test;

import java.io.IOException;

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

interface MockMethods {
    void method1(MockDto dto);

    void method2(MockDto dto);
}

/**
 * Created by peter on 17/05/2017.
 */
public class MethodReaderTest {
    @Test
    public void readMethods() throws IOException {
        Wire wire = new TextWire(BytesUtil.readFile("methods-in.yaml"));
        Wire wire2 = new TextWire(Bytes.allocateElasticDirect());
        // expected
        Bytes expected = BytesUtil.readFile("methods-in.yaml");
        MockMethods writer = wire2.methodWriter(MockMethods.class);
        MethodReader reader = wire.methodReader(writer);
        for (int i = 0; i < 2; i++) {
            assertTrue(reader.readOne());
            while (wire2.bytes().peekUnsignedByte(wire2.bytes().writePosition() - 1) == ' ')
                wire2.bytes().writeSkip(-1);
            wire2.bytes().append("---\n");
        }
        assertFalse(reader.readOne());
        assertEquals(expected.toString().trim().replace("\r", ""), wire2.toString().trim());
    }
}

class MockDto extends AbstractMarshallable {
    String field1;
    double field2;
}

package net.openhft.chronicle.wire;

import net.openhft.chronicle.bytes.Bytes;
import net.openhft.chronicle.bytes.BytesUtil;
import org.junit.Test;

import java.io.IOException;

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

interface MockMethods {
    void method1(MockDto dto);

    void method2(MockDto dto);
}

/**
 * Created by peter on 17/05/2017.
 */
public class MethodReaderTest {
    @Test
    public void readMethods() throws IOException {
        Wire wire = new TextWire(BytesUtil.readFile("methods-in.yaml")).useTextDocuments();
        Wire wire2 = new TextWire(Bytes.allocateElasticDirect());
        // expected
        Bytes expected = BytesUtil.readFile("methods-in.yaml");
        MockMethods writer = wire2.methodWriter(MockMethods.class);
        MethodReader reader = wire.methodReader(writer);
        for (int i = 0; i < 2; i++) {
            assertTrue(reader.readOne());
            while (wire2.bytes().peekUnsignedByte(wire2.bytes().writePosition() - 1) == ' ')
                wire2.bytes().writeSkip(-1);
            wire2.bytes().append("---\n");
        }
        assertFalse(reader.readOne());
        assertEquals(expected.toString().trim().replace("\r", ""), wire2.toString().trim());
    }
}

class MockDto extends AbstractMarshallable {
    String field1;
    double field2;
}

Allow TextWire to write binary headers as well as plain text.


package io.vertx.example.core.http.simple;

import io.vertx.core.AbstractVerticle;
import io.vertx.example.util.Runner;

/*
 * @author Tim Fox
 */
public class Server extends AbstractVerticle {

  // Convenience method so you can run it in your IDE
  public static void main(String[] args) {
    Runner.runExample(Server.class);
  }

  @Override
  public void start() throws Exception {
    vertx.createHttpServer().requestHandler(req -> {
      req.response().putHeader("content-type", "text/html").end("
Hello from vert.x!
");
    }).listen(8081);
  }
}

package io.vertx.example.core.http.simple;

import io.vertx.core.AbstractVerticle;
import io.vertx.example.util.Runner;

/*
 * @author Tim Fox
 */
public class Server extends AbstractVerticle {

  // Convenience method so you can run it in your IDE
  public static void main(String[] args) {
    Runner.runExample(Server.class);
  }

  @Override
  public void start() throws Exception {
    vertx.createHttpServer().requestHandler(req -> {
      req.response().putHeader("content-type", "text/html").end("
Hello from vert.x!
");
    }).listen(8080);
  }
}

Fix simple http server example wrong port


package com.github.games647.flexiblelogin.tasks;

import com.github.games647.flexiblelogin.FlexibleLogin;

import java.util.UUID;

import org.spongepowered.api.text.Texts;
import org.spongepowered.api.text.format.TextColors;
import org.spongepowered.api.util.command.CommandSource;

public class UnregisterTask implements Runnable {

    private final FlexibleLogin plugin;
    private final CommandSource src;

    private final Object accountIndentifer;

    public UnregisterTask(FlexibleLogin plugin, CommandSource src, UUID uuid) {
        this.plugin = plugin;
        this.src = src;

        this.accountIndentifer = uuid;
    }

    public UnregisterTask(FlexibleLogin plugin, CommandSource src, String playerName) {
        this.plugin = plugin;
        this.src = src;

        this.accountIndentifer = playerName;
    }

    @Override
    public void run() {
        boolean accountFound;
        if (accountIndentifer instanceof String) {
            accountFound = plugin.getDatabase().deleteAccount((String) accountIndentifer);
        } else {
            accountFound = plugin.getDatabase().deleteAccount((UUID) accountIndentifer);
        }

        if (accountFound) {
            src.sendMessage(Texts.of(TextColors.DARK_GREEN, "Deleted account of: " + accountIndentifer));
        } else {
            src.sendMessage(Texts.of(TextColors.DARK_RED, "Error executing command. See console"));
        }
    }
}

package com.github.games647.flexiblelogin.tasks;

import com.github.games647.flexiblelogin.FlexibleLogin;

import java.util.UUID;

import org.spongepowered.api.text.Texts;
import org.spongepowered.api.text.format.TextColors;
import org.spongepowered.api.util.command.CommandSource;

public class UnregisterTask implements Runnable {

    private final FlexibleLogin plugin;
    private final CommandSource src;

    private final Object accountIndentifer;

    public UnregisterTask(FlexibleLogin plugin, CommandSource src, UUID uuid) {
        this.plugin = plugin;
        this.src = src;

        this.accountIndentifer = uuid;
    }

    public UnregisterTask(FlexibleLogin plugin, CommandSource src, String playerName) {
        this.plugin = plugin;
        this.src = src;

        this.accountIndentifer = playerName;
    }

    @Override
    public void run() {
        boolean accountFound;
        if (accountIndentifer instanceof String) {
            accountFound = plugin.getDatabase().deleteAccount((String) accountIndentifer);
        } else {
            accountFound = plugin.getDatabase().deleteAccount((UUID) accountIndentifer);
        }

        if (accountFound) {
            src.sendMessage(Texts.of(TextColors.DARK_GREEN, "Deleted account of: " + accountIndentifer));
        } else {
            src.sendMessage(Texts.of(TextColors.DARK_RED, "User account not found"));
        }
    }
}

Fix command message if the account wasn't found on deleting.


package jp.satorufujiwara.binder.recycler;

import android.content.Context;
import android.support.annotation.LayoutRes;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.ViewGroup;

import jp.satorufujiwara.binder.Binder;
import jp.satorufujiwara.binder.ViewType;

public abstract class RecyclerBinder<V extends ViewType>
        implements Binder<V, RecyclerView.ViewHolder> {

    private final V mViewType;
    private Context mContext;

    protected RecyclerBinder(final Context context, final V viewType) {
        mContext = context;
        mViewType = viewType;
    }

    @LayoutRes
    public abstract int layoutResId();

    public abstract RecyclerView.ViewHolder onCreateViewHolder(final View v);

    @Override
    public final RecyclerView.ViewHolder onCreateViewHolder(final ViewGroup parent) {
        return onCreateViewHolder(View.inflate(mContext, layoutResId(), null));
    }

    @Override
    public void onViewRecycled(RecyclerView.ViewHolder holder) {
        // no op
    }

    @Override
    public void onRemoved() {
        mContext = null;
    }

    @Override
    public V getViewType() {
        return mViewType;
    }

    public final Context getContext() {
        return mContext;
    }

}

package jp.satorufujiwara.binder.recycler;

import android.content.Context;
import android.support.annotation.LayoutRes;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import jp.satorufujiwara.binder.Binder;
import jp.satorufujiwara.binder.ViewType;

public abstract class RecyclerBinder<V extends ViewType>
        implements Binder<V, RecyclerView.ViewHolder> {

    private final V mViewType;
    private Context mContext;

    protected RecyclerBinder(final Context context, final V viewType) {
        mContext = context;
        mViewType = viewType;
    }

    @LayoutRes
    public abstract int layoutResId();

    public abstract RecyclerView.ViewHolder onCreateViewHolder(final View v);

    @Override
    public final RecyclerView.ViewHolder onCreateViewHolder(final ViewGroup parent) {
        return onCreateViewHolder(LayoutInflater.from(mContext).inflate(layoutResId(), parent, false));
    }

    @Override
    public void onViewRecycled(RecyclerView.ViewHolder holder) {
        // no op
    }

    @Override
    public void onRemoved() {
        mContext = null;
    }

    @Override
    public V getViewType() {
        return mViewType;
    }

    public final Context getContext() {
        return mContext;
    }

}

Fix inflated view using parent view.


package com.connect_group.urlshortener;

import org.junit.Test;

import java.net.MalformedURLException;
import java.net.URL;

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.core.IsEqual.equalTo;

public class ShortenerServiceImplTest {

    @Test
    public void shouldConvertUrlToToken() throws MalformedURLException {
        ShortenerServiceImpl service = new ShortenerServiceImpl();
        String shortUrl = service.shorten(new URL("http://test.com/url?param=value"));
        assertThat(shortUrl, equalTo("-"));
    }

    @Test
    public void shouldConvertTokenToUrl() throws UnrecognisedTokenException, MalformedURLException {
        String url = "http://test.com/url?param=value";
        ShortenerServiceImpl service = new ShortenerServiceImpl();
        String token = service.shorten(new URL(url));
        assertThat(service.expand(token), equalTo(url));
    }

}

package com.connect_group.urlshortener;

import org.junit.Test;

import java.net.MalformedURLException;
import java.net.URL;

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.core.IsEqual.equalTo;

public class ShortenerServiceImplTest {

    @Test
    public void shouldConvertUrlToToken() throws MalformedURLException {
        ShortenerServiceImpl service = new ShortenerServiceImpl();
        String shortUrl = service.shorten(new URL("http://test.com/url?param=value"));
        assertThat(shortUrl, equalTo("-"));
    }

    @Test
    public void shouldConvertTokenToUrl() throws UnrecognisedTokenException, MalformedURLException {
        String url = "http://test.com/url?param=value";
        ShortenerServiceImpl service = new ShortenerServiceImpl();
        String token = service.shorten(new URL(url));
        assertThat(service.expand(token), equalTo(url));
    }

    @Test(expected=UnrecognisedTokenException.class)
    public void shouldThrowException_WhenNullToken() throws UnrecognisedTokenException {
        new ShortenerServiceImpl().expand(null);
    }

}

Test for invalid token when expanding token


package seedu.tasklist.logic.commands;

//@@author A0141993X
public class SortCommand extends Command {

    public static final String COMMAND_WORD = "sort";
    private final String parameter;

    public static final String MESSAGE_USAGE = COMMAND_WORD
            + ":Sorts task according to the parameter specified. "
            + "Only 1 of the 5. "
            + "Name:n"
            + "Priority:p or StartDate: sd or EndDate:ed or Deadline:d\n"
            + "Parameters: n, p, sd, ed\n"
            + "Example: " + COMMAND_WORD + " n";
    public static final String MESSAGE_FAILURE = "Invalid sorting parameter used!" + MESSAGE_USAGE;
    public static final String MESSAGE_SUCCESS = "Task sorted according to given parameter.";

    public SortCommand(String parameter) {
        switch (parameter) {
        case "d":
            this.parameter = "Date";
            break;
        case "n":
            this.parameter = "Name";
            break;
        case "p":
            this.parameter = "Priority";
            break;
        default:
            this.parameter = null;
            break;
        }
    }

    @Override
    public CommandResult execute() {

        if (parameter == null) {
            return new CommandResult(MESSAGE_FAILURE);
        }
        model.sortTaskList(parameter);
        return new CommandResult(MESSAGE_SUCCESS);
    }

}

package seedu.tasklist.logic.commands;

//@@author A0141993X
public class SortCommand extends Command {

    public static final String COMMAND_WORD = "sort";
    private final String parameter;

    public static final String MESSAGE_USAGE = COMMAND_WORD
            + ":Sorts task according to the parameter specified. "
            + "Only 1 of the 5. "
            + "Name:n "
            + "Priority:p or StartDate: sd or EndDate:ed or Deadline:d\n"
            + "Parameters: n, p, sd, ed\n"
            + "Example: " + COMMAND_WORD + " n";
    public static final String MESSAGE_FAILURE = "Invalid sorting parameter used!" + MESSAGE_USAGE;
    public static final String MESSAGE_SUCCESS = "Task sorted according to given parameter.";

    public SortCommand(String parameter) {
        switch (parameter) {
        case "d":
            this.parameter = "Date";
            break;
        case "n":
            this.parameter = "Name";
            break;
        case "p":
            this.parameter = "Priority";
            break;
        default:
            this.parameter = null;
            break;
        }
    }

    @Override
    public CommandResult execute() {

        if (parameter == null) {
            return new CommandResult(MESSAGE_FAILURE);
        }
        model.sortTaskList(parameter);
        return new CommandResult(MESSAGE_SUCCESS);
    }

}

Edit format of sort command


package com.haxademic.core.system;

import processing.core.PApplet;
import processing.opengl.PGL;

import com.haxademic.core.app.P;

public class SystemUtil {

	public static String getJavaVersion() {
		return System.getProperty("java.version");
	}

	public static String getTimestamp( PApplet p ) {
		// use P.nf to pad date components to 2 digits for more consistent ordering across systems
		return  String.valueOf( P.year() ) + "-" +
				P.nf( P.month(), 2 ) + "-" +
				P.nf( P.day(), 2 ) + "-" +
				P.nf( P.hour(), 2 ) + "-" +
				P.nf( P.minute(), 2 ) + "-" +
				P.nf( P.second(), 2 );
	}

	public static String getTimestampFine( PApplet p ) {
		return SystemUtil.getTimestamp(p) + "-" + P.nf( p.frameCount, 8 );
	}

	// Patch TAB capture ability - Processing 2.0 broke this in 3D rendering contexts
	public static void p2TabKeyInputPatch() {
		if(PGL.canvas != null) { PGL.canvas.setFocusTraversalKeysEnabled(false); }
	}
}

package com.haxademic.core.system;

import processing.core.PApplet;

import com.haxademic.core.app.P;

public class SystemUtil {

	public static String getJavaVersion() {
		return System.getProperty("java.version");
	}

	public static String getTimestamp( PApplet p ) {
		// use P.nf to pad date components to 2 digits for more consistent ordering across systems
		return  String.valueOf( P.year() ) + "-" +
				P.nf( P.month(), 2 ) + "-" +
				P.nf( P.day(), 2 ) + "-" +
				P.nf( P.hour(), 2 ) + "-" +
				P.nf( P.minute(), 2 ) + "-" +
				P.nf( P.second(), 2 );
	}

	public static String getTimestampFine( PApplet p ) {
		return SystemUtil.getTimestamp(p) + "-" + P.nf( p.frameCount, 8 );
	}

	// Patch TAB capture ability - Processing 2.0 broke this in 3D rendering contexts
	public static void p2TabKeyInputPatch() {
//		if(PJOGL.canvas != null) { PJOGL.canvas.setFocusTraversalKeysEnabled(false); }
	}
}

Remove hack for tab-key handling in Processing 2.0 - This is now fixed in Processing 2.1


package dmax.words.domain;

/**
 * Created by Maxim Dybarsky | maxim.dybarskyy@gmail.com
 * on 10.12.14 at 13:46
 */
public enum Language {
    POLISH,
    UKRAINIAN
}

package dmax.words.domain;

/**
 * Created by Maxim Dybarsky | maxim.dybarskyy@gmail.com
 * on 10.12.14 at 13:46
 */
public enum Language {
    POLISH("Polish"),
    UKRAINIAN("Ukrainian");

    private String codeName;

    Language(String codeName) {
        this.codeName = codeName;
    }

    public String getCodeName() {
        return codeName;
    }
}

Add method setWord(word) into Link class


package br.com.bloder.blormlib.validation;

import br.com.bloder.blormlib.validation.validations.Checked;
import br.com.bloder.blormlib.validation.validations.Email;
import br.com.bloder.blormlib.validation.validations.Filled;
import br.com.bloder.blormlib.validation.validations.Number;

/**
 * Created by bloder on 05/06/16.
 */
public class Validations {

  public static Validation filled = new Filled();
  public static Validation checked = new Checked();
  public static Validation email = new Email();
  public static Validation number = new Number();
}

package br.com.bloder.blormlib.validation;

import br.com.bloder.blormlib.validation.validations.Checked;
import br.com.bloder.blormlib.validation.validations.Email;
import br.com.bloder.blormlib.validation.validations.Filled;
import br.com.bloder.blormlib.validation.validations.Number;

/**
 * Created by bloder on 05/06/16.
 */
public class Validations {

  public static Validation filled = new Filled();
  public static Validation checked = new Checked();
  public static Validation email = new Email();
  public static Number number = new Number();
}

Change number validation field type


package mb.nabl2.spoofax.analysis;

import java.io.Serializable;
import java.util.Optional;
import java.util.Set;

import mb.nabl2.constraints.IConstraint;
import mb.nabl2.solver.Fresh;
import mb.nabl2.solver.ISolution;

public interface IScopeGraphUnit extends Serializable {

    String resource();

    Set<IConstraint> constraints();

    Optional<ISolution> solution();

    Optional<CustomSolution> customSolution();

    Fresh fresh();

    /**
     * Check if the solution returned is for this resource exactly,
     * or if this unit is just a part of it.
     */
    boolean isPrimary();

}

package mb.nabl2.spoofax.analysis;

import java.io.Serializable;
import java.util.Optional;
import java.util.Set;

import mb.nabl2.constraints.IConstraint;
import mb.nabl2.solver.Fresh;
import mb.nabl2.solver.ISolution;

public interface IScopeGraphUnit extends Serializable {

    String resource();

    Set<IConstraint> constraints();

    Optional<ISolution> solution();

    Optional<CustomSolution> customSolution();

    Fresh fresh();

    /**
     * Check if the solution returned is for this resource exactly,
     * or if this unit is just a part of it.
     */
    boolean isPrimary();

    IScopeGraphUnit withSolution(ISolution solution);

}

Add helper for FlowSpec to add the CFG at a later time