package api;

import java.util.List;

import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;

import dtos.UserDTO;
import services.UserService;

@RestController
@RequestMapping("/api/user")
public final class UserController {
    private final UserService service;

    @Autowired
    public UserController(UserService service) {
        this.service = service;
    }

    @RequestMapping(method = RequestMethod.POST)
    @ResponseStatus(HttpStatus.CREATED)
    UserDTO create(@RequestBody @Valid UserDTO userEntry) {
        return service.create(userEntry);
    }

    @RequestMapping(value = "{id}", method = RequestMethod.DELETE)
    UserDTO delete(@PathVariable("id") String id) {
        return service.delete(id);
    }

    @RequestMapping(value = "{id}", method = RequestMethod.GET)
    @ResponseStatus(HttpStatus.OK)
    UserDTO findById(@PathVariable("id") String id) {
        return service.findById(id);
    }

    @RequestMapping(value = "{id}", method = RequestMethod.PUT)
    UserDTO update(@RequestBody @Valid UserDTO userEntry) {
        return service.update(userEntry);
    }

    @RequestMapping(method = RequestMethod.GET)
    @ResponseStatus(HttpStatus.OK)
    List<UserDTO> findAll() {
        return service.findAll();
    }
}

Implement User resource API controller


package volley.core.utils;

import com.android.volley.Request;

import java.lang.reflect.Field;

/**
 * Created by Ismail Ceylan
 */
public class CoreVolleyUtil {

    /**
     * @param methodCode integer value of HTTP Methods
     * @return String value of HTTP Methods defined in {@link com.android.volley.Request.Method}
     */
    public static String getMethodName(int methodCode) throws IllegalAccessException {
        Field[] fields = Request.Method.class.getDeclaredFields();

        for (Field field : fields) {
            if (methodCode == field.getInt(null)) {
                return field.getName();
            }
        }

        return null;
    }
}

Revert "gson is outsourced for advantage/separate usage"


package leetcode.sudoku_solver;

public class Solution {
	public static final int N = 9;
	public boolean dfs(boolean[][] appearX, boolean[][] appearY, boolean[][] appearG, char[][] board, int x, int y){
		if(y == N){
			x++;
			y = 0;
		}
		if(x == N){
			return true;
		}
		int g = (x / 3) * 3 + (y / 3);
		if(board[x][y] != '.'){
			if(dfs(appearX, appearY, appearG, board, x, y + 1))
				return true;
		}else{
			for(int d = 0; d < N; d++){
				if(!appearX[x][d] && !appearY[y][d] && !appearG[g][d]){
					appearX[x][d] = appearY[y][d] = appearG[g][d] = true;
					board[x][y] = (char)('1' + d);
					if(dfs(appearX, appearY, appearG, board, x, y + 1))
						return true;
					board[x][y] = '.';
					appearX[x][d] = appearY[y][d] = appearG[g][d] = false;
				}
			}
		}
		return false;
	}

    public void solveSudoku(char[][] board) {
    	boolean[][] appearX = new boolean[N][N];
    	boolean[][] appearY = new boolean[N][N];
    	boolean[][] appearG = new boolean[N][N];
    	for(int x = 0; x < N; x++){
    		for(int y = 0; y < N; y++){
    			if(board[x][y] != '.'){
    				int d = board[x][y] - '1';
    				int g = (x / 3) * 3 + (y / 3);
    				appearX[x][d] = appearY[y][d] = appearG[g][d] = true;
    			}
    		}
    	}
    	dfs(appearX, appearY, appearG, board, 0, 0);
    }

    public static void main(String[] args){
    	String[] s = new String[]{"....4.9..","..21..3..",".........","........3","...2.....",".....7...","...61....","..9......",".......9."};
    	char[][] board = new char[N][N];
    	for(int i = 0; i < N; i++){
    		board[i] = s[i].toCharArray();
    	}
    	new Solution().solveSudoku(board);
    	for(char[] row : board){
    		System.err.println(new String(row));
    	}
    }
}

Add java solution for 37. Sudoku Solver


/**
 * Copyright © 2011-2012 EMBL - European Bioinformatics Institute
 *
 * 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 uk.ac.ebi.generic.util;

import org.apache.poi.xssf.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;

import java.util.Map;
import java.util.HashMap;
import java.io.FileOutputStream;

/**
* Creating spreadsheet using Apache POI.
* code modified from Apache POI timesheet example
*/

public class ExcelWorkBook {

	Workbook wb = null;
	private String[] titles = null;
	private Object[][] tableData = null;
	private String sheetTitle = null;

	public ExcelWorkBook(String[] titles, Object[][] tableData, String sheetTitle) throws Exception {

		this.titles = titles;
		this.tableData = tableData;
		this.sheetTitle = sheetTitle;

		// create new workbook
		this.wb = new HSSFWorkbook();

		// create new sheet
		Sheet sheet = wb.createSheet(sheetTitle); // do not exceed 31 characters
		PrintSetup printSetup = sheet.getPrintSetup();
		printSetup.setLandscape(true);
		sheet.setFitToPage(true);
		sheet.setHorizontallyCenter(true);

    	//header row
    	Row headerRow = sheet.createRow(0);
    	//headerRow.setHeightInPoints(40);
    	Cell headerCell;
    	for (int i = 0; i < titles.length; i++) {
    		headerCell = headerRow.createCell(i);
    		headerCell.setCellValue(titles[i]);
        	//headerCell.setCellStyle(styles.get("header"));
    	}

    	// data rows
    	// Create a row and put some cells in it. Rows are 0 based.
    	// Then set value for that created cell
    	for (int i=0; i<tableData.length; i++) {
    		Row row = sheet.createRow(i+1);  // data starts from row 1
    		for (int j = 0; j < tableData[i].length; j++) {
    			Cell cell = row.createCell(j);
    			cell.setCellValue((String)tableData[i][j]);
    			System.out.println((String)tableData[i][j]);
    		}
    	}
	}

	public Workbook fetchWorkBook() {
		return this.wb;
	}
}

Change the licence information export table as csv/excel stuff


/*
 * DownloadClient Geodateninfrastruktur Bayern
 *
 * (c) 2016 GSt. GDI-BY (gdi.bayern.de)
 *
 * 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 de.bayern.gdi.model;

import junit.framework.TestCase;
import org.junit.Test;

public class DownloadStepTest extends TestCase {

    /** Test the dataset getter/setter. */
    @Test
    public void testDataset() {
        DownloadStep dlst = new DownloadStep();
        dlst.setDataset("dataset");
        assertEquals("dataset", dlst.getDataset());
    }

//    /** Test the processingSteps getter/setter. */
//    @Test
//    public void testProcessingSteps() throws Exception {
//        DownloadStep dlst = new DownloadStep();
//        dlst.setProcessingSteps("dataset");
//        assertEquals("dataset", dlst.getDataset());
//    }
//
//    @Test
//    public void testParameters() throws Exception {
//        DownloadStep dlst = new DownloadStep();
//        dlst.setParameters("dataset");
//        assertEquals("dataset", dlst.getDataset());
//    }

    /** Test the ServiceType getters and setters. */
    @Test
    public void testServiceType() {
        DownloadStep dlst = new DownloadStep();
        dlst.setServiceType("service type");
        assertEquals("service type", dlst.getServiceType());
    }

    /** Test the serviceURL getter/setter. */
    @Test
    public void testServiceURL() {
        DownloadStep dlst = new DownloadStep();
        dlst.setServiceURL("service url");
        assertEquals("service url", dlst.getServiceURL());
    }

    /** Test the path getter/setter. */
    @Test
    public void testPath() {
        DownloadStep dlst = new DownloadStep();
        dlst.setPath("path");
        assertEquals("path", dlst.getPath());
    }

}

Add Unit Tests for getter and setter methods


package com.bubbletastic.android.ping;

import android.app.Application;
import android.app.job.JobInfo;
import android.app.job.JobScheduler;
import android.content.ComponentName;
import android.content.Context;

import com.squareup.otto.Bus;
import com.squareup.otto.ThreadEnforcer;

/**
 * Created by brendanmartens on 4/13/15.
 */
public class Ping extends Application {

    private Bus bus;
    private JobScheduler jobScheduler;
    private HostService hostService;

    @Override
    public void onCreate() {
        super.onCreate();

        bus = new Bus(ThreadEnforcer.ANY);
        hostService = HostService.getInstance(this);

        JobInfo updateHostsJob = new JobInfo.Builder(UpdateHostsService.JOB_ID, new ComponentName(this, UpdateHostsService.class))
                .setRequiredNetworkType(JobInfo.NETWORK_TYPE_ANY)
                        //update hosts once a minute
                .setPeriodic(60000)
                        //service scheduling should survive reboots
                .setPersisted(true)
                .build();

        //schedule the update hosts job
        jobScheduler = ((JobScheduler) getSystemService(Context.JOB_SCHEDULER_SERVICE));
        jobScheduler.schedule(updateHostsJob);
    }

    public Bus getBus() {
        return bus;
    }

    public HostService getHostService() {
        return hostService;
    }
}

package com.bubbletastic.android.ping;

import android.app.Application;
import android.app.job.JobInfo;
import android.app.job.JobScheduler;
import android.content.ComponentName;
import android.content.Context;

import com.squareup.otto.Bus;
import com.squareup.otto.ThreadEnforcer;

/**
 * Created by brendanmartens on 4/13/15.
 */
public class Ping extends Application {

    private Bus bus;
    private JobScheduler jobScheduler;
    private HostService hostService;

    @Override
    public void onCreate() {
        super.onCreate();

        bus = new Bus(ThreadEnforcer.ANY);
        hostService = HostService.getInstance(this);

        JobInfo updateHostsJob = new JobInfo.Builder(UpdateHostsService.JOB_ID, new ComponentName(this, UpdateHostsService.class))
                .setRequiredNetworkType(JobInfo.NETWORK_TYPE_ANY)
                        //update hosts once every 4 minutes
                .setPeriodic(240000)
                        //service scheduling should survive reboots
                .setPersisted(true)
                .build();

        //schedule the update hosts job
        jobScheduler = ((JobScheduler) getSystemService(Context.JOB_SCHEDULER_SERVICE));
        jobScheduler.schedule(updateHostsJob);
    }

    public Bus getBus() {
        return bus;
    }

    public HostService getHostService() {
        return hostService;
    }
}

Increase time between host refreshing to four minutes.


package io.quarkus.runtime.util;

import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;

import io.quarkus.runtime.StartupContext;

public class StepTiming {

    public static final String PRINT_STARTUP_TIMES = "quarkus.debug.print-startup-times";

    private static boolean stepTimingEnabled;
    private static long stepTimingStart;

    public static void configureEnabled() {
        stepTimingEnabled = System.getProperty(PRINT_STARTUP_TIMES, "false").equalsIgnoreCase("true");
    }

    public static void configureStart() {
        stepTimingStart = System.currentTimeMillis();
    }

    public static void printStepTime(StartupContext startupContext) {
        if (!stepTimingEnabled) {
            return;
        }
        long stepTimingStop = System.currentTimeMillis();
        String currentBuildStepName = startupContext.getCurrentBuildStepName();
        System.out.printf("%1$tF %1$tT,%1$tL Build step %2$s completed in: %3$sms%n",
                LocalDateTime.ofInstant(Instant.ofEpochMilli(stepTimingStop), ZoneId.systemDefault()),
                currentBuildStepName,
                stepTimingStop - stepTimingStart);
        stepTimingStart = System.currentTimeMillis();
    }
}

package io.quarkus.runtime.util;

import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.concurrent.TimeUnit;

import io.quarkus.runtime.StartupContext;

public class StepTiming {

    public static final String PRINT_STARTUP_TIMES = "quarkus.debug.print-startup-times";

    private static boolean stepTimingEnabled;
    private static long stepTimingStart;

    public static void configureEnabled() {
        stepTimingEnabled = System.getProperty(PRINT_STARTUP_TIMES, "false").equalsIgnoreCase("true");
    }

    public static void configureStart() {
        stepTimingStart = System.nanoTime();
    }

    public static void printStepTime(StartupContext startupContext) {
        if (!stepTimingEnabled) {
            return;
        }
        String currentBuildStepName = startupContext.getCurrentBuildStepName();
        System.out.printf("%1$tF %1$tT,%1$tL Build step %2$s completed in: %3$sms%n",
                LocalDateTime.ofInstant(Instant.ofEpochMilli(System.currentTimeMillis()), ZoneId.systemDefault()),
                currentBuildStepName,
                duration(System.nanoTime(), stepTimingStart));
        stepTimingStart = System.nanoTime();
    }

    private static long duration(long ended, long started) {
        return TimeUnit.MILLISECONDS.convert(ended - started, TimeUnit.NANOSECONDS);
    }
}

Use proper timing method in step timing


package no.javazone;

import io.vertx.core.Vertx;
import io.vertx.core.json.Json;
import io.vertx.ext.web.Router;
import io.vertx.ext.web.RoutingContext;

public class VertxHttpServer {

    public static void main(String[] args) {
        Vertx vertx = Vertx.vertx();
        Router router = Router.router(vertx);
        router.get("/person/:id").handler(VertxHttpServer::returnPerson);
        router.get("/address/:id").handler(VertxHttpServer::returnAddress);
        router.get("/").handler(ctx -> ctx.response().end("Hello world"));
        vertx.createHttpServer().requestHandler(router::accept).listen(8080);
    }

    private static void returnPerson(RoutingContext ctx) {
        String id = ctx.request().getParam("id");
        ctx.response()
                .setStatusCode(200)
                .end(Json.encode(new TypicalExamples.Person(id, "Me", 29)));
        System.out.println("requested person " + id);
    }

    private static void returnAddress(RoutingContext ctx) {
        String id = ctx.request().getParam("id");
        ctx.response()
                .setStatusCode(200)
                .end(Json.encode(new TypicalExamples.Address(id, "House 1", "Street 2", "1337", "Sandvika")));
        System.out.println("requested address " + id);
    }
}

package no.javazone;

import io.vertx.core.Vertx;
import io.vertx.core.json.Json;
import io.vertx.ext.web.Router;
import io.vertx.ext.web.RoutingContext;

public class VertxHttpServer {

    public static void main(String[] args) {
        Vertx vertx = Vertx.vertx();
        Router router = Router.router(vertx);
        router.get("/person/:id").handler(VertxHttpServer::returnPerson);
        router.get("/address/:id").handler(VertxHttpServer::returnAddress);
        router.get("/").handler(ctx -> ctx.response().end("Hello world"));
        vertx.createHttpServer().requestHandler(router::accept).listen(8080);
        System.out.println("Server started on port 8080");
    }

    private static void returnPerson(RoutingContext ctx) {
        String id = ctx.request().getParam("id");
        ctx.response()
                .setStatusCode(200)
                .end(Json.encode(new TypicalExamples.Person(id, "Me", 29)));
        System.out.println("requested person " + id);
    }

    private static void returnAddress(RoutingContext ctx) {
        String id = ctx.request().getParam("id");
        ctx.response()
                .setStatusCode(200)
                .end(Json.encode(new TypicalExamples.Address(id, "House 1", "Street 2", "1337", "Sandvika")));
        System.out.println("requested address " + id);
    }
}

Add output when server has started.


/**
 * Decoding structure data to a compressed form.
 * @author Anthony Bradley
 *
 */
package org.rcsb.mmtf.decoder;

/**
 * Decoding structure data from a compressed form.
 * @author Anthony Bradley
 *
 */
package org.rcsb.mmtf.decoder;

Update to the package info


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

import com.github.aureliano.achmed.command.CommandResponse;

public interface IService {

	public abstract CommandResponse start();

	public abstract CommandResponse stop();

	public abstract CommandResponse restart();

	public abstract boolean isRunning();

	public abstract CommandResponse enableBootstrap();

	public abstract CommandResponse disableBootstrap();
}

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

import com.github.aureliano.achmed.command.CommandResponse;
import com.github.aureliano.achmed.resources.properties.ServiceProperties;

public interface IService {

	public abstract CommandResponse start();

	public abstract CommandResponse stop();

	public abstract CommandResponse restart();

	public abstract boolean isRunning();

	public abstract CommandResponse enableBootstrap();

	public abstract CommandResponse disableBootstrap();

	public abstract void setServiceProperties(ServiceProperties properties);

	public abstract ServiceProperties getServiceProperties();
}

Add methods to set and get properties.


/**
 *
 */
package com.grayben.riskExtractor.htmlScorer;

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

/**
 * A class implementing this interface is able to process HTML from a number of sources
 * and output a representation of the readable text in that HTML, with scores attached to
 * elements of this text.
 * <p>
 * Created by Ben Gray, 2015.
 */
public interface HtmlScorer {

    /**
     * Score HTML stored locally.
     *
     * @param htmlStream the stream containing the HTML to score
     * @param charsetName the name of the charset used to encode the file
     * @param baseUri the baseURI of the HTML document
     * @return the scored text
     *
     */
	ScoredText scoreHtml(InputStream htmlStream, String charsetName, String baseUri) throws IOException;

    /**
     * Score HTML stored remotely.
     *
     * @param url the URL of the file containing the HTML to score
     * @return the scored text
     * @throws IOException
     */
	ScoredText scoreHtml(String url) throws IOException;
}

/**
 *
 */
package com.grayben.riskExtractor.htmlScorer;

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

/**
 * A class implementing this interface is able to process HTML from a number of sources
 * and output a representation of the readable text in that HTML, with scores attached to
 * elements of this text.
 * <p>
 * Created by Ben Gray, 2015.
 */
public interface HtmlScorer {

    /**
     * Score HTML stored locally.
     *
     * @param htmlStream the stream containing the HTML to score
     * @param charsetName the name of the charset used to encode the file
     * @param baseUri the baseURI of the HTML document
     * @return the scored text
     *
     */
	ScoredText scoreHtml(InputStream htmlStream, String charsetName, String baseUri) throws IOException;

    /**
     * Score HTML stored remotely.
     *
     * @param url the URL of the file containing the HTML to score
     * @return the scored text
     * @throws IOException if unable to connect to url
     */
	ScoredText scoreHtml(String url) throws IOException;
}

Add documentation for IOException thrown


package com.choudhury.logger;

import org.apache.log4j.BasicConfigurator;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.logging.Level;
import java.util.logging.Logger;

public class LoggerInterceptor extends HandlerInterceptorAdapter {

    static Logger logger = Logger.getLogger(LoggerInterceptor.class.getName());

    static {
        BasicConfigurator.configure();
        logger.setLevel((Level) Level.INFO);
    }

    @Override
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response, Object handler) throws Exception {
        logger.info("Before handling the request");
        return super.preHandle(request, response, handler);
    }

    @Override
    public void postHandle(HttpServletRequest request,
                           HttpServletResponse response, Object handler,
                           ModelAndView modelAndView) throws Exception {
        logger.info("After handling the request");
        super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request,
                                HttpServletResponse response, Object handler, Exception ex)
            throws Exception {
        logger.info("After rendering the view");
        super.afterCompletion(request, response, handler, ex);
    }
}

package com.choudhury.logger;

import org.apache.log4j.BasicConfigurator;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.logging.Level;
import java.util.logging.Logger;

public class LoggerInterceptor extends HandlerInterceptorAdapter {

    static Logger logger = Logger.getLogger(LoggerInterceptor.class.getName());

    static {
        BasicConfigurator.configure();
        logger.setLevel(Level.INFO);
    }

    @Override
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response, Object handler) throws Exception {
        logger.info("Before handling the request");
        return super.preHandle(request, response, handler);
    }

    @Override
    public void postHandle(HttpServletRequest request,
                           HttpServletResponse response, Object handler,
                           ModelAndView modelAndView) throws Exception {
        logger.info("After handling the request");
        super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request,
                                HttpServletResponse response, Object handler, Exception ex)
            throws Exception {
        logger.info("After rendering the view");
        super.afterCompletion(request, response, handler, ex);
    }
}

Remove used full path attribute


package werkbook.task.commons.util;

import static org.junit.Assert.assertNotNull;

import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;

public class AppUtilTest {

    @Rule
    public ExpectedException thrown = ExpectedException.none();

    @Test
    public void getImage_exitingImage() {
        assertNotNull(AppUtil.getImage("/images/address_book_32.png"));
    }

    @Test
    public void getImage_nullGiven_assertionError() {
        thrown.expect(AssertionError.class);
        AppUtil.getImage(null);
    }

}

package werkbook.task.commons.util;

import static org.junit.Assert.assertNotNull;

import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;

public class AppUtilTest {

    @Rule
    public ExpectedException thrown = ExpectedException.none();

    @Test
    public void getImage_exitingImage() {
        assertNotNull(AppUtil.getImage("/images/app_icon_32.png"));
    }

    @Test
    public void getImage_nullGiven_assertionError() {
        thrown.expect(AssertionError.class);
        AppUtil.getImage(null);
    }

}

Change app icon file path


/**
 * Package contains all the views required by budgetreporter
 */
package com.budgetreporter.View;

import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.GridLayout;

import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;

/**
 * @author jacky
 *
 */
public class MenuView extends JPanel{

	public MenuView(){
		super();
		initUI();
	}

	public void initUI(){
		GridLayout gLayout = new GridLayout(0,1);
		this.setLayout(gLayout);

        //Add the "View Report" button
        JButton viewReportButton = new JButton("View Report");

        //Add the "New Expense" button
        JButton newExpenseButton = new JButton("New Expense");

        //Add the "New Income" button
        JButton newIncomeButton = new JButton("New Income");

        //Add the "Profile" button
        JButton profileButton = new JButton("Profile");

        //Add the "Quit" button
        JButton quitButton = new JButton("Quit");

        this.add(profileButton);
        this.add(viewReportButton);
        this.add(newExpenseButton);
        this.add(newIncomeButton);
        this.add(quitButton);

        System.out.println("Menu page created");
	}

}

/**
 * Package contains all the views required by budgetreporter
 */
package com.budgetreporter.View;

import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;

/**
 * @author jacky
 *
 */
public class MenuView extends JPanel{

	public MenuView(){
		super();
		initUI();
	}

	public void initUI(){
		GridLayout gLayout = new GridLayout(0,1);
		this.setLayout(gLayout);

        //Add the "View Report" button
        JButton viewReportButton = new JButton("View Report");

        //Add the "New Expense" button
        JButton newExpenseButton = new JButton("New Expense");

        //Add the "New Income" button
        JButton newIncomeButton = new JButton("New Income");

        //Add the "Profile" button
        JButton profileButton = new JButton("Profile");

        //Add the "Quit" button
        JButton quitButton = new JButton("Quit");
        quitButton.addActionListener(new QuitButtonListener());

        this.add(profileButton);
        this.add(viewReportButton);
        this.add(newExpenseButton);
        this.add(newIncomeButton);
        this.add(quitButton);

        System.out.println("Menu page created");
	}

	private class QuitButtonListener implements ActionListener{
		@Override
		public void actionPerformed(ActionEvent e) {
		    System.exit(0);
		}
	}

}

Add quit button functionality in menuView


/**
 * A HTTP plugin for Cordova / Phonegap
 */
package com.synconset.cordovahttp;

import java.net.SocketTimeoutException;
import java.net.UnknownHostException;

import javax.net.ssl.SSLHandshakeException;

import org.apache.cordova.CallbackContext;
import org.json.JSONException;
import org.json.JSONObject;

import com.github.kevinsawicki.http.HttpRequest;
import com.github.kevinsawicki.http.HttpRequest.HttpRequestException;

class CordovaHttpHead extends CordovaHttp implements Runnable {
    public CordovaHttpHead(String urlString, Object params, JSONObject headers, int timeout, CallbackContext callbackContext) {
        super(urlString, params, headers, timeout, callbackContext);
    }

    @Override
    public void run() {
        try {
            HttpRequest request = HttpRequest.head(this.getUrlString(), this.getParamsMap(), true);

            this.prepareRequest(request);
            this.returnResponseObject(request);
        } catch (HttpRequestException e) {
            this.handleHttpRequestException(e);
        } catch (Exception e) {
            this.respondWithError(e.getMessage());
        }
    }
}

/**
 * A HTTP plugin for Cordova / Phonegap
 */
package com.synconset.cordovahttp;

import java.net.SocketTimeoutException;
import java.net.UnknownHostException;

import javax.net.ssl.SSLHandshakeException;

import org.apache.cordova.CallbackContext;
import org.json.JSONException;
import org.json.JSONObject;

import com.github.kevinsawicki.http.HttpRequest;
import com.github.kevinsawicki.http.HttpRequest.HttpRequestException;

class CordovaHttpHead extends CordovaHttp implements Runnable {
    public CordovaHttpHead(String urlString, Object params, JSONObject headers, int timeout, CallbackContext callbackContext) {
        super(urlString, params, headers, timeout, callbackContext);
    }

    @Override
    public void run() {
        try {
            HttpRequest request = HttpRequest.head(this.getUrlString(), this.getParamsMap(), false);

            this.prepareRequest(request);
            this.returnResponseObject(request);
        } catch (HttpRequestException e) {
            this.handleHttpRequestException(e);
        } catch (Exception e) {
            this.respondWithError(e.getMessage());
        }
    }
}

Fix argument double encoding for HttpHead


package net.qbar.common.block;

import net.minecraft.block.material.Material;
import net.minecraft.block.state.IBlockState;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.EnumHand;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;
import net.qbar.common.tile.TileTank;
import net.qbar.common.util.FluidUtils;

public class BlockTank extends BlockMachineBase
{
    public BlockTank()
    {
        super("tank", Material.IRON);
    }

    @Override
    public boolean onBlockActivated(final World w, final BlockPos pos, final IBlockState state,
            final EntityPlayer player, final EnumHand hand, final EnumFacing facing, final float hitX, final float hitY,
            final float hitZ)
    {
        if (player.isSneaking())
            return false;
        if (!w.isRemote)
        {
            final TileTank tank = (TileTank) w.getTileEntity(pos);

            if (tank != null)
            {
                if (FluidUtils.drainPlayerHand(tank.getTank(), player)
                        || FluidUtils.fillPlayerHand(tank.getTank(), player))
                    return true;
            }
        }
        return false;
    }

    @Override
    public TileEntity createNewTileEntity(final World worldIn, final int meta)
    {
        return new TileTank();
    }
}

package net.qbar.common.block;

import net.minecraft.block.material.Material;
import net.minecraft.block.state.IBlockState;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.EnumHand;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;
import net.qbar.common.tile.TileTank;
import net.qbar.common.util.FluidUtils;

public class BlockTank extends BlockMachineBase
{
    public BlockTank()
    {
        super("tank", Material.IRON);
    }

    @Override
    public boolean onBlockActivated(final World w, final BlockPos pos, final IBlockState state,
            final EntityPlayer player, final EnumHand hand, final EnumFacing facing, final float hitX, final float hitY,
            final float hitZ)
    {
        if (player.isSneaking())
            return false;

        final TileTank tank = (TileTank) w.getTileEntity(pos);

        if (tank != null)
        {
            if (FluidUtils.drainPlayerHand(tank.getTank(), player) || FluidUtils.fillPlayerHand(tank.getTank(), player))
                return true;
        }
        return false;
    }

    @Override
    public TileEntity createNewTileEntity(final World worldIn, final int meta)
    {
        return new TileTank();
    }
}

Fix side check in tank filling


/**
 * @license
 * Copyright 2019 The FOAM Authors. All Rights Reserved.
 * http://www.apache.org/licenses/LICENSE-2.0
 */

package foam.util.concurrent;

import foam.core.Agency;
import foam.core.ContextAgent;
import foam.core.X;

/**
* An Aynchronous implementation of the AssemblyLine interface.
* Uses the threadpool to avoid blocking the caller.
**/
public class AsyncAssemblyLine
  extends SyncAssemblyLine
{
 protected Agency pool_;
 protected X      x_;

 public AsyncAssemblyLine(X x) {
   x_    = x;
   pool_ = (Agency) x.get("threadPool");
 }

 public void enqueue(Assembly job) {
   final Assembly previous;

   synchronized ( startLock_ ) {
     try {
       previous = q_;
       q_ = job;
       job.executeUnderLock();
       job.startJob();
     } catch (Throwable t) {
       q_ = null;
       throw t;
     }
   }

   pool_.submit(x_, new ContextAgent() { public void execute(X x) {
     try {
       job.executeJob();

       if ( previous != null ) previous.waitToComplete();

       synchronized ( endLock_ ) {
         job.endJob();
         job.complete();
       }
     } finally {
       // Isn't required, but helps GC last entry.
       synchronized ( startLock_ ) {
         // If I'm still the only job in the queue, then remove me
         if ( q_ == job ) q_ = null;
       }
     }
   }}, "SyncAssemblyLine");
 }
}

/**
 * @license
 * Copyright 2019 The FOAM Authors. All Rights Reserved.
 * http://www.apache.org/licenses/LICENSE-2.0
 */

package foam.util.concurrent;

import foam.core.Agency;
import foam.core.ContextAgent;
import foam.core.X;

/**
* An Aynchronous implementation of the AssemblyLine interface.
* Uses the threadpool to avoid blocking the caller.
**/
public class AsyncAssemblyLine
  extends SyncAssemblyLine
{
 protected Agency pool_;
 protected X      x_;

 public AsyncAssemblyLine(X x) {
   x_    = x;
   pool_ = (Agency) x.get("threadPool");
 }

 public void enqueue(Assembly job) {
   final Assembly previous;

   synchronized ( startLock_ ) {
     try {
       previous = q_;
       q_ = job;
       job.executeUnderLock();
       job.startJob();
     } catch (Throwable t) {
       q_ = previous;
       throw t;
     }
   }

   pool_.submit(x_, new ContextAgent() { public void execute(X x) {
     try {
       job.executeJob();

       if ( previous != null ) previous.waitToComplete();

       synchronized ( endLock_ ) {
         job.endJob();
         job.complete();
       }
     } finally {
       // Isn't required, but helps GC last entry.
       synchronized ( startLock_ ) {
         // If I'm still the only job in the queue, then remove me
         if ( q_ == job ) q_ = null;
       }
     }
   }}, "SyncAssemblyLine");
 }
}

Set q_ back to previous on exception in pre-pool block


package io.miti.beetle.model;

public enum ContentType {
  SQL(1), SQL_FILE(2), HADOOP(3), CSV(4), JSON(5), YAML(6), TEXT(7);

  private int id = -1;

  ContentType(final int nId) {
    id = nId;
  }

  public int getId() {
    return id;
  }

  public static ContentType getById(final int pId) {
    ContentType result = null;
    for (ContentType ct : values()) {
      if (ct.id == pId) {
        result = ct;
        break;
      }
    }

    return result;
  }
}

package io.miti.beetle.model;

public enum ContentType {
  SQL(1), SQL_FILE(2), HADOOP(3), CSV(4), JSON(5), YAML(6), TEXT(7), TOML(8), XML(9);

  private int id = -1;

  ContentType(final int nId) {
    id = nId;
  }

  public int getId() {
    return id;
  }

  public static ContentType getById(final int pId) {
    ContentType result = null;
    for (ContentType ct : values()) {
      if (ct.id == pId) {
        result = ct;
        break;
      }
    }

    return result;
  }
}

Support for exporting to TOML and XML.


package net.ihiroky.niotty.sample;

import net.ihiroky.niotty.LoadStage;
import net.ihiroky.niotty.LoadStageContext;
import net.ihiroky.niotty.buffer.CodecBuffer;
import net.ihiroky.niotty.TransportStateEvent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.nio.charset.CharacterCodingException;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;
import java.nio.charset.CodingErrorAction;

/**
 * Created on 13/01/18, 14:12
 *
 * @author Hiroki Itoh
 */
public class StringDecoder implements LoadStage<CodecBuffer, String> {

    private Logger logger_ = LoggerFactory.getLogger(StringDecoder.class);

    private static final Charset CHARSET = Charset.forName("UTF-8");

    private CharsetDecoder decoder_ = CHARSET.newDecoder()
            .onMalformedInput(CodingErrorAction.IGNORE)
            .onUnmappableCharacter(CodingErrorAction.IGNORE);

    @Override
    public void load(LoadStageContext<CodecBuffer, String> context, CodecBuffer input) {
        try {
            String s = decoder_.decode(input.toByteBuffer()).toString();
            context.proceed(s);
        } catch (CharacterCodingException cce) {
            cce.printStackTrace();
        }
    }

    @Override
    public void load(LoadStageContext<CodecBuffer, String> context, TransportStateEvent event) {
        logger_.info(event.toString());
        context.proceed(event);
    }
}

package net.ihiroky.niotty.sample;

import net.ihiroky.niotty.LoadStage;
import net.ihiroky.niotty.LoadStageContext;
import net.ihiroky.niotty.TransportStateEvent;
import net.ihiroky.niotty.buffer.CodecBuffer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.nio.charset.Charset;

/**
 * Created on 13/01/18, 14:12
 *
 * @author Hiroki Itoh
 */
public class StringDecoder implements LoadStage<CodecBuffer, String> {

    private Logger logger_ = LoggerFactory.getLogger(StringDecoder.class);

    private static final Charset CHARSET = Charset.forName("UTF-8");

    @Override
    public void load(LoadStageContext<CodecBuffer, String> context, CodecBuffer input) {
        String s = input.readString(CHARSET.newDecoder());
        context.proceed(s);
    }

    @Override
    public void load(LoadStageContext<CodecBuffer, String> context, TransportStateEvent event) {
        logger_.info(event.toString());
        context.proceed(event);
    }
}

Fix invalid decoder in sample


package seedu.address.testutil;

import seedu.address.model.tag.UniqueTagList;
import seedu.address.model.task.Name;
import seedu.address.model.task.ReadOnlyTask;

/**
 * A mutable person object. For testing only.
 */
public class TestTask implements ReadOnlyTask {

    private Name name;
    private UniqueTagList tags;

    public TestTask() {
        tags = new UniqueTagList();
    }

    /**
     * Creates a copy of {@code personToCopy}.
     */
    public TestTask(TestTask personToCopy) {
        this.name = personToCopy.getName();
        this.tags = personToCopy.getTags();
    }

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

    public void setTags(UniqueTagList tags) {
        this.tags = tags;
    }

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

    @Override
    public UniqueTagList getTags() {
        return tags;
    }

    @Override
    public String toString() {
        return getAsText();
    }

    public String getAddCommand() {
        StringBuilder sb = new StringBuilder();
        sb.append("add " + this.getName().fullName + " ");
        this.getTags().asObservableList().stream().forEach(s -> sb.append("t/" + s.tagName + " "));
        return sb.toString();
    }
}

package seedu.address.testutil;

import seedu.address.model.tag.UniqueTagList;
import seedu.address.model.task.Name;
import seedu.address.model.task.ReadOnlyTask;

/**
 * A mutable task object. For testing only.
 */
public class TestTask implements ReadOnlyTask {

    private Name name;
    private UniqueTagList tags;

    public TestTask() {
        tags = new UniqueTagList();
    }

    /**
     * Creates a copy of {@code taskToCopy}.
     */
    public TestTask(TestTask taskToCopy) {
        this.name = taskToCopy.getName();
        this.tags = taskToCopy.getTags();
    }

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

    public void setTags(UniqueTagList tags) {
        this.tags = tags;
    }

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

    @Override
    public UniqueTagList getTags() {
        return tags;
    }

    @Override
    public String toString() {
        return getAsText();
    }

    public String getAddCommand() {
        StringBuilder sb = new StringBuilder();
        sb.append("add " + this.getName().fullName + " ");
        this.getTags().asObservableList().stream().forEach(s -> sb.append("t/" + s.tagName + " "));
        return sb.toString();
    }
}

Fix some wrong references to person


package rs.emulate.lynx.net;

/**
 * Contains constants used as part of the js5 protocol.
 *
 * @author Major
 */
public final class Js5Constants {

	/**
	 * The amount of times to attempt a connection to the server (incrementing the major version each unsuccessful
	 * connection) before stopping.
	 */
	public static final int DEFAULT_ATTEMPT_COUNT = 100;

	/**
	 * The port the js5 worker should connect to.
	 */
	public static final int DEFAULT_PORT = 43594;

	/**
	 * The major version (i.e. client version).
	 */
	public static final int MAJOR_VERSION = 814;

	/**
	 * The minor version.
	 */
	public static final int MINOR_VERSION = 1;

	/**
	 * The host to connect to.
	 */
	public static final String HOST = "world1.runescape.com";

	/**
	 * Default private constructor to prevent instantiation.
	 */
	private Js5Constants() {
	}

}

package rs.emulate.lynx.net;

/**
 * Contains constants used as part of the js5 protocol.
 *
 * @author Major
 */
public final class Js5Constants {

	/**
	 * The amount of times to attempt a connection to the server (incrementing the major version each unsuccessful
	 * connection) before stopping.
	 */
	public static final int DEFAULT_ATTEMPT_COUNT = 100;

	/**
	 * The port the js5 worker should connect to.
	 */
	public static final int DEFAULT_PORT = 43594;

	/**
	 * The major version (i.e. client version).
	 */
	public static final int MAJOR_VERSION = 816;

	/**
	 * The minor version.
	 */
	public static final int MINOR_VERSION = 1;

	/**
	 * The host to connect to.
	 */
	public static final String HOST = "world1.runescape.com";

	/**
	 * Default private constructor to prevent instantiation.
	 */
	private Js5Constants() {
	}

}

Update the default version to the current one.


// HeadArray.java

package ed.appserver;

import ed.js.*;

public class HeadArray extends JSArray {

    public void addCSS( String css ){
        add( "<link rel=\"stylesheet\" type=\"text/css\" href=\"" + css + "\" >" );
    }

    public void addScript( String script ){
        add( "<script src=\"" + script + "\" ></script>" );
    }

    public void addRSS( String link ){
	add("<link rel=\"alternate\" type=\"application/rss+xml\" title=\"RSS\" href=\"" + link + "\" />" );
    }
}

// HeadArray.java

package ed.appserver;

import ed.js.*;

public class HeadArray extends JSArray {

    protected int getIndex( Object index ){
        int idx;
        if( index == null ) idx = size();
        else {
            if( ! (index instanceof Number) ) throw new JSException( "index must be number, not " + index.toString() );
            idx = ((Number)index).intValue();
        }
        return idx;
    }

    public void addCSS( String css , Object index ){
        add( getIndex( index ) ,
             "<link rel=\"stylesheet\" type=\"text/css\" href=\"" + css + "\" >" );
    }

    public void addScript( String script , Object index ){
        add( getIndex( index ) ,
             "<script src=\"" + script + "\" ></script>" );
    }

    public void addRSS( String link ){
	add("<link rel=\"alternate\" type=\"application/rss+xml\" title=\"RSS\" href=\"" + link + "\" />" );
    }
}

Allow indexes on scripts and CSS files (so you can add them at the beginning).


package seedu.bulletjournal.logic.parser;

/**
 * Provides variations of commands Note: hard-coded for v0.2, will implement nlp
 * for future versions
 * @author Tu An - arishuynhvan
 */

public class FlexibleCommand {
    private String commandFromUser = "";
    private String[] commandGroups = new String[] { "add a adds create creates new", "clear clr c clears empty empties",
        "delete d deletes del remove removes rm", "edit edits e change changes",
        "exit exits close closes logout logouts", "find finds f search searches lookup",
        "help helps h manual instruction instructions", "list lists l ls show shows display displays showall",
        "select selects s choose chooses" };

    /**
     * Constructor must take in a valid string input
     * @param cfu
     */
    public FlexibleCommand(String cfu) {
        commandFromUser = cfu;
    }

    /**
     * @return the correct command string that matches COMMAND_WORD of command
     *         classes
     */
    public String getCommandWord() {
        for (String commandGroup : commandGroups) {
            for (String command : commandGroup.split(" ")) {
                if (commandFromUser.equals(command))
                    return commandGroup.split(" ")[0];
            }
        }
        return commandFromUser;
    }

    public boolean isValidCommand() {
        for (String commandGroup : commandGroups) {
            for (String command : commandGroup.split(" ")) {
                if (commandFromUser.equals(command))
                    return true;
            }
        }
        return false;
    }
}

package seedu.bulletjournal.logic.parser;

/**
 * Provides variations of commands Note: hard-coded for v0.2, will implement nlp
 * for future versions
 * @author Tu An - arishuynhvan
 */

public class FlexibleCommand {
    private String commandFromUser = "";
    private String[] commandGroups = new String[] { "add a adds create creates new", "clear clr c clears empty empties",
        "delete d deletes del remove removes rm", "edit edits e change changes",
        "exit exits close closes logout logouts", "find finds f search searches lookup",
        "help helps h manual instruction instructions", "list lists l ls show shows display displays showall",
        "select selects s choose chooses" };

    /**
     * Constructor must take in a valid string input
     * @param cfu
     */
    public FlexibleCommand(String cfu) {
        commandFromUser = cfu;
    }

    /**
     * @return the correct command string that matches COMMAND_WORD of command
     *         classes
     */
    public String getCommandWord() {
        for (String commandGroup : commandGroups) {
            for (String command : commandGroup.split(" ")) {
                if (commandFromUser.equals(command)) {
                    return commandGroup.split(" ")[0];
                }
            }
        }
        return commandFromUser;
    }

    public boolean isValidCommand() {
        for (String commandGroup : commandGroups) {
            for (String command : commandGroup.split(" ")) {
                if (commandFromUser.equals(command))
                    return true;
            }
        }
        return false;
    }
}

Fix one more style error


package com.AlexanderZaytsev.RNI18n;

import com.facebook.react.ReactPackage;
import com.facebook.react.bridge.JavaScriptModule;
import com.facebook.react.bridge.NativeModule;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.uimanager.ViewManager;

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

public class RNI18nPackage implements ReactPackage {

  @Override
  public List<NativeModule> createNativeModules(ReactApplicationContext reactContext) {
    return Arrays.<NativeModule>asList(new RNI18nModule(reactContext));
  }

  @Override
  public List<Class<? extends JavaScriptModule>> createJSModules() {
    return Collections.emptyList();
  }

  @Override
  public List<ViewManager> createViewManagers(ReactApplicationContext reactContext) {
    return Collections.emptyList();
  }
}

package com.AlexanderZaytsev.RNI18n;

import com.facebook.react.ReactPackage;
import com.facebook.react.bridge.JavaScriptModule;
import com.facebook.react.bridge.NativeModule;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.uimanager.ViewManager;

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

public class RNI18nPackage implements ReactPackage {

  @Override
  public List<NativeModule> createNativeModules(ReactApplicationContext reactContext) {
    return Arrays.<NativeModule>asList(new RNI18nModule(reactContext));
  }

  // Deprecated in React Native 0.47
  public List<Class<? extends JavaScriptModule>> createJSModules() {
    return Collections.emptyList();
  }

  @Override
  public List<ViewManager> createViewManagers(ReactApplicationContext reactContext) {
    return Collections.emptyList();
  }
}

Fix unexistant createJSModules on rn 0.47+


package dk.kleistsvendsen;

import com.google.inject.Inject;

public class GameTimer implements IGameTimer {
    private ITicSource ticSource_;
    private long startTic_;
    private long pauseTic_;
    private boolean running_;

    @Inject
    public GameTimer(ITicSource ticSource) {
        running_ = false;
        ticSource_ = ticSource;
        startTic_ = 0;
        pauseTic_ = 0;
    }

    @Override
    public long timePlayed() {
        if (running_) {
            return ticSource_.tic() -startTic_;
        }
        else {
            return pauseTic_ - startTic_;
        }
    }

    @Override
    public void pauseTimer() {
        pauseTic_ = ticSource_.tic();
        running_ = false;
    }

    @Override
    public void startTimer() {
        running_ = true;
        ticSource_.tic();
    }

    @Override
    public void resetTimer() {

    }
}

package dk.kleistsvendsen;

import com.google.inject.Inject;

public class GameTimer implements IGameTimer {
    private ITicSource ticSource_;
    private long startTic_;
    private long pauseTic_;
    private enum State {
        IDLE,
        PAUSED,
        RUNNING
    }

    private State running_;

    @Inject
    public GameTimer(ITicSource ticSource) {
        running_ = State.IDLE;
        ticSource_ = ticSource;
        startTic_ = 0;
        pauseTic_ = 0;
    }

    @Override
    public long timePlayed() {
        if (running_ == State.RUNNING) {
            return ticSource_.tic() -startTic_;
        }
        else {
            return pauseTic_ - startTic_;
        }
    }

    @Override
    public void pauseTimer() {
        pauseTic_ = ticSource_.tic();
        running_ = State.PAUSED;
    }

    @Override
    public void startTimer() {
        running_ = State.RUNNING;
        ticSource_.tic();
    }

    @Override
    public void resetTimer() {

    }
}

Use enum instead of boolean to hold state.


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 void addProject(Project project) {
		Project foundProject = findProjectByName(project.getName());

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

	public Project findProjectByName(String name) {
		TypedQuery<Project> query = em
				.createNamedQuery("findProjectByName", Project.class)
				.setParameter("name", name);

		try {
			return query.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 void addProject(Project project) {
		Project foundProject = findProjectByName(project.getName());

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

	public Project findProjectByName(String name) {
		TypedQuery<Project> query = em
				.createNamedQuery("findProjectByName", Project.class)
				.setParameter("name", name);

		try {
			return query.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;
		}
	}
}

Add searching for a project by id functionality


package cz.cuni.mff.d3s.spl.core.impl.formula;

import cz.cuni.mff.d3s.spl.core.Formula;
import cz.cuni.mff.d3s.spl.core.Result;

public class LogicOr extends LogicOp {

	public LogicOr(Formula left, Formula right) {
		super(left, right);
	}

	/*
	 * We are using Kleene three-value logic.
	 */
	@Override
	public Result evaluate() {
		Result leftResult = left.evaluate();

		/*
		 * If the left one is TRUE, we do not need
		 * to evaluate the right one.
		 */
		if (leftResult == Result.TRUE) {
			return Result.TRUE;
		}

		Result rightResult = right.evaluate();

		/*
		 * The same works other way round.
		 */
		if (rightResult == Result.TRUE) {
			return Result.TRUE;
		}

		/*
		 * FALSE is returned only if both are false, otherwise
		 * we return CANNOT_COMPUTE.
		 */
		if ((rightResult == Result.FALSE) || (leftResult == Result.FALSE)) {
			return Result.FALSE;
		} else {
			return Result.CANNOT_COMPUTE;
		}
	}

}

package cz.cuni.mff.d3s.spl.core.impl.formula;

import cz.cuni.mff.d3s.spl.core.Formula;
import cz.cuni.mff.d3s.spl.core.Result;

public class LogicOr extends LogicOp {

	public LogicOr(Formula left, Formula right) {
		super(left, right);
	}

	/*
	 * We are using Kleene three-value logic.
	 */
	@Override
	public Result evaluate() {
		Result leftResult = left.evaluate();

		/*
		 * If the left one is TRUE, we do not need
		 * to evaluate the right one.
		 */
		if (leftResult == Result.TRUE) {
			return Result.TRUE;
		}

		Result rightResult = right.evaluate();

		/*
		 * The same works other way round.
		 */
		if (rightResult == Result.TRUE) {
			return Result.TRUE;
		}

		/*
		 * FALSE is returned only if both are false, otherwise
		 * we return CANNOT_COMPUTE.
		 */
		if ((rightResult == Result.FALSE) && (leftResult == Result.FALSE)) {
			return Result.FALSE;
		} else {
			return Result.CANNOT_COMPUTE;
		}
	}

}

Fix bad evaluation of Kleene logic


package com.easternedgerobotics.rov.io;

/**
 * A MPX4250 is an absolute pressure (AP) sensor. See also: MPX4250.
 */
public final class MPX4250AP {
    /**
     * Scalar value for calculating pressure from voltage.
     */
    private static final float PRESSURE_SCALAR = 0.264909785f;

    /**
     * Offset value for calculating pressure from voltage.
     */
    private static final float PRESSURE_OFFSET = 54.20054200f;

    /**
     * The ADC this device uses.
     */
    private final ADC channel;

    /**
     * Constructs a new MPX4250AP sensor on the given channel.
     * @param channel the ADC this device uses
     */
    public MPX4250AP(final ADC channel) {
        this.channel = channel;
    }

    /**
     * Returns the pressure.
     * @return the pressure
     */
    public final float read() {
        return channel.voltage() * PRESSURE_OFFSET - PRESSURE_SCALAR;
    }
}

package com.easternedgerobotics.rov.io;

import rx.Observable;

/**
 * A MPX4250 is an absolute pressure (AP) sensor. See also: MPX4250.
 */
public final class MPX4250AP {
    /**
     * Scalar value for calculating pressure from voltage.
     */
    private static final float PRESSURE_SCALAR = 0.264909785f;

    /**
     * Offset value for calculating pressure from voltage.
     */
    private static final float PRESSURE_OFFSET = 54.20054200f;

    @SuppressWarnings("checkstyle:MagicNumber")
    public static final Observable.Transformer<Double, Double> CALIBRATION = source -> source.map(
        x -> 0.83060f * x + 10.0445f);

    /**
     * The ADC this device uses.
     */
    private final ADC channel;

    /**
     * Constructs a new MPX4250AP sensor on the given channel.
     * @param channel the ADC this device uses
     */
    public MPX4250AP(final ADC channel) {
        this.channel = channel;
    }

    /**
     * Returns the pressure.
     * @return the pressure
     */
    public final float read() {
        return channel.voltage() * PRESSURE_OFFSET - PRESSURE_SCALAR;
    }
}

Add pressure sensor calibration fn


package com.suse.saltstack.netapi.datatypes;

import java.util.HashMap;

/**
 * Parse events into objects.
 */
public class Event {

    private String tag;
    private HashMap<String, Object> data;

    /**
     * Return this event's tag.
     * @return the tag
     */
    public String getTag() {
        return tag;
    }

    /**
     * Return this event's data.
     * @return the data
     */
    public HashMap<String, Object> getData() {
        return data;
    }
}

package com.suse.saltstack.netapi.datatypes;

import java.util.Map;

/**
 * Parse events into objects.
 */
public class Event {

    private String tag;
    private Map<String, Object> data;

    /**
     * Return this event's tag.
     * @return the tag
     */
    public String getTag() {
        return tag;
    }

    /**
     * Return this event's data.
     * @return the data
     */
    public Map<String, Object> getData() {
        return data;
    }
}

Make data being a Map instead of HashMap


package it.uniroma2.ember;

/**
 * Created by odysseus on 09/03/17.
 */
public class EmberSensorsAggregation {
}

package it.uniroma2.ember;

import org.apache.flink.api.java.functions.KeySelector;
import org.apache.flink.api.java.tuple.Tuple2;

/**
 * This is a utility class for aggregate statistics in Project Ember
 */

public class EmberSensorsAggregation {

    /**
     * Implements a simple KeySelector to divide by key (address) the traffic data - window join
     */
    public static final class EmberTrafficMeanSelector implements KeySelector<Tuple2<String, Float>, String> {

        /**
         * @param trafficData the tuple <key, traffic_intensity>
         * @return address as a key
         * @throws Exception
         */
        @Override
        public String getKey(Tuple2<String, Float> trafficData) throws Exception {
            return trafficData.f0;
        }
    }

    /**
     * Implements a simple KeySelector to divide by key (address) the lumen data - window join
     */
    public static final class EmberLumenMeanSelector implements KeySelector<Tuple2<String, Float>, String> {

        /**
         * @param lumenData the tuple <key, light_level>
         * @return address as a key
         * @throws Exception
         */
        @Override
        public String getKey(Tuple2<String, Float> lumenData) throws Exception {
            return lumenData.f0;
        }
    }
}

Add key selectors for aggregation of traffic and lumen.


package ws.biotea.ld2rdf.rdf.model;

import ws.biotea.ld2rdf.util.OntologyPrefix;
import java.io.Serializable;

/**
 * OpenAnnotation: This class represents a general annotation on a Document.
 * @author leylajael
 */
public class BaseAnnotation implements Serializable {
	private static final long serialVersionUID = 1L;
	/* OWL Descriptors */
	public final static String ANNOTATION_DP_LABEL = OntologyPrefix.RDFS.getURL() + "label";
	public final static String RDFS_COMMENT = OntologyPrefix.RDFS.getURL() + "comment";
	public final static String BIOTEA_OCURRENCES = OntologyPrefix.BIOTEA.getURL() + "tf";
	public final static String BIOTEA_IDF = OntologyPrefix.BIOTEA.getURL() + "idf";
	public final static String RDFS_SEE_ALSO = OntologyPrefix.RDFS.getURL() + "seeAlso";
	public final static String OWL_SAME_AS = OntologyPrefix.OWL.getURL() + "sameAs";
    public final static String DC_IS_REFERENCED_BY = OntologyPrefix.DCTERMS.getURL() + "isReferencedBy";
    public final static String VOID_IN_DATASET = OntologyPrefix.VOID.getURL() + "inDataset";
    public final static String DP_SCORE = OntologyPrefix.BIOTEA.getURL() + "score";
}

package ws.biotea.ld2rdf.rdf.model;

import ws.biotea.ld2rdf.util.OntologyPrefix;
import java.io.Serializable;

/**
 * OpenAnnotation: This class represents a general annotation on a Document.
 * @author leylajael
 */
public class BaseAnnotation implements Serializable {
	private static final long serialVersionUID = 1L;
	/* OWL Descriptors */
	public final static String ANNOTATION_DP_LABEL = OntologyPrefix.RDFS.getURL() + "label";
	public final static String RDFS_COMMENT = OntologyPrefix.RDFS.getURL() + "comment";
	public final static String BIOTEA_OCURRENCES = OntologyPrefix.BIOTEA.getURL() + "tf";
	public final static String BIOTEA_IDF = OntologyPrefix.BIOTEA.getURL() + "idf";
	public final static String RDFS_SEE_ALSO = OntologyPrefix.RDFS.getURL() + "seeAlso";
	public final static String OWL_SAME_AS = OntologyPrefix.OWL.getURL() + "sameAs";
    public final static String DC_IS_REFERENCED_BY = OntologyPrefix.DCTERMS.getURL() + "isReferencedBy";
    public final static String SIO_IN_DATASET = OntologyPrefix.SIO.getURL() + "001278";
    public final static String DP_SCORE = OntologyPrefix.BIOTEA.getURL() + "score";
}

Use SIO:is_data _item in rather than void:inDataset


package info.tregmine.commands;

import static org.bukkit.ChatColor.*;
import org.bukkit.GameMode;

import info.tregmine.Tregmine;
import info.tregmine.api.TregminePlayer;

public class GameModeCommand extends AbstractCommand
{
    private GameMode mode;

    public GameModeCommand(Tregmine tregmine, String name, GameMode mode)
    {
        super(tregmine, name);

        this.mode = mode;
    }

    @Override
    public boolean handlePlayer(TregminePlayer player, String[] args)
    {
        if (!player.getRank().canUseCreative()) {
            return true;
        }

        player.setGameMode(mode);
        player.sendMessage(YELLOW + "You are now in "
                + mode.toString().toLowerCase() + " mode.");

        if (player.getRank().canFly()) {
            player.setAllowFlight(true);
        }

        return true;
    }
}

package info.tregmine.commands;

import static org.bukkit.ChatColor.*;

import info.tregmine.api.Rank;
import org.bukkit.GameMode;

import info.tregmine.Tregmine;
import info.tregmine.api.TregminePlayer;

public class GameModeCommand extends AbstractCommand
{
    private GameMode mode;
	private Tregmine tregmine;

    public GameModeCommand(Tregmine tregmine, String name, GameMode mode)
    {
        super(tregmine, name);

        this.mode = mode;
		this.tregmine = tregmine;
    }

    @Override
    public boolean handlePlayer(TregminePlayer player, String[] args)
    {
        if (!player.getRank().canUseCreative()) {
            return true;
        }

		if (	(player.getWorld().getName().equalsIgnoreCase(tregmine.getRulelessWorld().getName()) ||
				player.getWorld().getName().equalsIgnoreCase(tregmine.getRulelessEnd().getName()) ||
				player.getWorld().getName().equalsIgnoreCase(tregmine.getRulelessNether().getName())) &&
				player.getRank() == Rank.BUILDER) {

			player.sendMessage(RED + "Builders can not be in creative!" + DARK_RED + " Disabled.");
			player.setGameMode(GameMode.SURVIVAL);
			return false;
		}

        player.setGameMode(mode);
        player.sendMessage(YELLOW + "You are now in "
                + mode.toString().toLowerCase() + " mode.");

        if (player.getRank().canFly()) {
            player.setAllowFlight(true);
        }

        return true;
    }
}

Stop builders creative privledge in Anarchy


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

package io.requery.android;

import android.os.ParcelUuid;
import io.requery.sql.GenericMapping;
import io.requery.sql.Platform;

/**
 * Extended {@link io.requery.sql.Mapping} with useful {@link io.requery.Converter}s added
 * specifically for Android.
 */
public class DefaultMapping extends GenericMapping {
    public DefaultMapping(Platform platform) {
        super(platform);
        addConverter(new UriConverter());
        addConverter(new ParcelConverter<>(ParcelUuid.class, ParcelUuid.CREATOR));
    }
}

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

package io.requery.android;

import io.requery.sql.GenericMapping;
import io.requery.sql.Platform;

/**
 * Extended {@link io.requery.sql.Mapping} with useful {@link io.requery.Converter}s added
 * specifically for Android.
 */
public class DefaultMapping extends GenericMapping {
    public DefaultMapping(Platform platform) {
        super(platform);
        addConverter(new UriConverter());
    }
}

Remove ParcelConverter from default mapping


/*
 * 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 rx.android.plugins;

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

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;

public final class RxAndroidPluginsTest {
    @Before @After
    public void setUpAndTearDown() {
        RxAndroidPlugins.getInstance().reset();
    }

    @Test
    public void registeredSchedulersHookIsUsed() {
        RxAndroidPlugins plugins = new RxAndroidPlugins();
        RxAndroidSchedulersHook hook = new RxAndroidSchedulersHook();
        plugins.registerSchedulersHook(hook);
        assertSame(hook, plugins.getSchedulersHook());
    }

    @Test
    public void registerSchedulersHookTwiceFails() {
        RxAndroidPlugins plugins = new RxAndroidPlugins();
        RxAndroidSchedulersHook hook = new RxAndroidSchedulersHook();
        plugins.registerSchedulersHook(hook);
        try {
            plugins.registerSchedulersHook(hook);
            fail();
        } catch (IllegalStateException e) {
            assertTrue(e.getMessage().startsWith("Another strategy was already registered:"));
        }
    }
}

/*
 * 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 rx.android.plugins;

import org.junit.Test;

import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;

public final class RxAndroidPluginsTest {
    @Test
    public void registeredSchedulersHookIsUsed() {
        RxAndroidPlugins plugins = new RxAndroidPlugins();
        RxAndroidSchedulersHook hook = new RxAndroidSchedulersHook();
        plugins.registerSchedulersHook(hook);
        assertSame(hook, plugins.getSchedulersHook());
    }

    @Test
    public void registerSchedulersHookTwiceFails() {
        RxAndroidPlugins plugins = new RxAndroidPlugins();
        RxAndroidSchedulersHook hook = new RxAndroidSchedulersHook();
        plugins.registerSchedulersHook(hook);
        try {
            plugins.registerSchedulersHook(hook);
            fail();
        } catch (IllegalStateException e) {
            assertTrue(e.getMessage().startsWith("Another strategy was already registered:"));
        }
    }
}

Remove unnecessary reset. These tests don't use the global instance.


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

package it;

import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertThrows;

import de.sormuras.bach.Bach;
import java.lang.module.ModuleDescriptor;
import org.junit.jupiter.api.Test;

class BachTests {
  @Test
  void moduleDescriptorParsesVersion() {
    assertDoesNotThrow(() -> ModuleDescriptor.Version.parse("2.0-ea"));
    assertThrows(IllegalArgumentException.class, () -> ModuleDescriptor.Version.parse(""));
    assertThrows(IllegalArgumentException.class, () -> ModuleDescriptor.Version.parse("-"));
    assertThrows(IllegalArgumentException.class, () -> ModuleDescriptor.Version.parse("master"));
    assertThrows(IllegalArgumentException.class, () -> ModuleDescriptor.Version.parse("ea"));
  }
}

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

package it;

import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertThrows;

import java.lang.module.ModuleDescriptor;
import java.time.Instant;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import org.junit.jupiter.api.Test;

class BachTests {
  @Test
  void moduleDescriptorParsesVersion() {
    var pattern = DateTimeFormatter.ofPattern("yyyy.MM.dd.HHmmss").withZone(ZoneId.of("UTC"));
    assertDoesNotThrow(() -> ModuleDescriptor.Version.parse(pattern.format(Instant.now())));
    assertThrows(IllegalArgumentException.class, () -> ModuleDescriptor.Version.parse(""));
    assertThrows(IllegalArgumentException.class, () -> ModuleDescriptor.Version.parse("-"));
    assertThrows(IllegalArgumentException.class, () -> ModuleDescriptor.Version.parse("master"));
    assertThrows(IllegalArgumentException.class, () -> ModuleDescriptor.Version.parse("ea"));
  }
}

Check date time based pattern as module version


package editor.gui.ccp.handler;

import editor.gui.editor.EditorFrame;

@SuppressWarnings("serial")
public class EditorFrameTransferHandler extends EditorTransferHandler
{
    public EditorFrameTransferHandler(EditorFrame e, int i)
    {
        super(new EntryImportHandler(e, i), new CardImportHandler(e, i));
    }
}

package editor.gui.ccp.handler;

import editor.gui.editor.EditorFrame;

/**
 * Transfer handler for importing cards into decks via the editor frame
 * (rather than a table in the frame).  Mainly used for convenience for
 * drag-and-drop.
 *
 * @author Alec Roelke
 */
@SuppressWarnings("serial")
public class EditorFrameTransferHandler extends EditorTransferHandler
{
    /**
     * Create a new editor frame transfer handler.
     *
     * @param e editor frame to handle transfers for
     * @param i ID of the list in the frame to handle transfers for
     */
    public EditorFrameTransferHandler(EditorFrame e, int i)
    {
        super(new EntryImportHandler(e, i), new CardImportHandler(e, i));
    }
}

Add documentation to editor frame transfer handler


package io.collap.bryg;

import io.collap.bryg.exception.InvalidInputParameterException;
import io.collap.bryg.model.Model;

import javax.annotation.Nullable;
import java.io.Writer;

/**
 * Implementations of the template interface must be thread-safe, as only a single object is used to render all instances
 * of the template.
 */
public interface Template {

    /**
     * @param model May be null if no parameters are expected.
     * @throws InvalidInputParameterException Thrown when the Model does not contain a variable.
     * @throws java.lang.ClassCastException Thrown when the supplied variable in the Model has a type that can not be
     *                                      casted to the expected type.
     */
    public void render (Writer writer, @Nullable Model model) throws InvalidInputParameterException, ClassCastException;

}

package io.collap.bryg;

import io.collap.bryg.exception.InvalidInputParameterException;
import io.collap.bryg.model.Model;

import java.io.Writer;

/**
 * Implementations of the template interface must be thread-safe, as only a single object is used to render all instances
 * of the template.
 */
public interface Template {

    /**
     * @throws InvalidInputParameterException Thrown when the Model does not contain a variable.
     * @throws java.lang.ClassCastException Thrown when the supplied variable in the Model has a type that can not be
     *                                      casted to the expected type.
     */
    public void render (Writer writer, Model model) throws InvalidInputParameterException, ClassCastException;

}

Remove nullability of the Model when invoking a template, to reduce problems with global variables.


package ca.junctionbox.cljbuck.build;

import org.junit.Test;

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

public class TestIntegration {
    @Test
    public void Test_fail() {
        assertThat("tests written: you've been a very naughty boy...", 0, is(0));
    }
}

package ca.junctionbox.cljbuck.build;

import org.junit.Test;

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

public class TestIntegration {
    @Test
    public void Test_fail() {
        assertThat("tests written: you've been a very naughty boy...", 0, is(10));
    }
}

Test failing build with buck-out/cache on Travis.


package org.jctools.util;

import java.lang.reflect.Field;

import sun.misc.Unsafe;

public class UnsafeAccess {
    public static final Unsafe UNSAFE;
    static {
        try {
            // This is a bit of voodoo to force the unsafe object into
            // visibility and acquire it.
            // This is not playing nice, but as an established back door it is
            // not likely to be
            // taken away.
            final Field field = Unsafe.class.getDeclaredField("theUnsafe");
            field.setAccessible(true);
            UNSAFE = (Unsafe) field.get(null);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

}

package org.jctools.util;

import java.lang.reflect.Field;
import java.util.concurrent.atomic.AtomicReferenceArray;
import java.util.concurrent.atomic.AtomicReferenceFieldUpdater;

import sun.misc.Unsafe;

/**
 * Why should we resort to using Unsafe?

 *

 *
To construct class fields which allow volatile/ordered/plain access: This requirement is covered by
 * {@link AtomicReferenceFieldUpdater} and similar but their performance is arguably worse than the DIY approach
 * (depending on JVM version) while Unsafe intrinsification is a far lesser challenge for JIT compilers.
 *
To construct flavors of {@link AtomicReferenceArray}.
 *
Other use cases exist but are not present in this library yet.
 *

 *
 * @author nitsanw
 *
 */
public class UnsafeAccess {
    public static final Unsafe UNSAFE;
    static {
        try {
            /*
             * This is a bit of voodoo to force the unsafe object into visibility and acquire it. This is not playing
             * nice, but as an established back door it is not likely to be taken away.
             */
            final Field field = Unsafe.class.getDeclaredField("theUnsafe");
            field.setAccessible(true);
            UNSAFE = (Unsafe) field.get(null);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

}

Add comment justifying the use of UNSAFE.


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

import org.opennms.newts.api.Duration;

import io.dropwizard.jersey.params.AbstractParam;

/**
 * JAX-RS parameter that encapsulates creation of {@link Duration} instances from a string
 * specifier. Non-parseable values will result in a {@code 400 Bad Request} response.
 *
 * @author eevans
 */
public class DurationParam extends AbstractParam<Duration> {

    protected DurationParam(String input) {
        super(input);
    }

    @Override
    protected String errorMessage(String input, Exception e) {
        return String.format("Unable to parse '%s' as resolution", input);
    }

    @Override
    protected Duration parse(String input) throws Exception {
        if (input.matches("^[\\d]+$")) {
            return Duration.seconds(Integer.valueOf(input));
        }

        return Duration.parse(input);
    }

}

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

import org.opennms.newts.api.Duration;

import io.dropwizard.jersey.params.AbstractParam;

/**
 * JAX-RS parameter that encapsulates creation of {@link Duration} instances from a string
 * specifier. Non-parseable values will result in a {@code 400 Bad Request} response.
 *
 * @author eevans
 */
public class DurationParam extends AbstractParam<Duration> {

    public DurationParam(String input) {
        super(input);
    }

    @Override
    protected String errorMessage(String input, Exception e) {
        return String.format("Unable to parse '%s' as resolution", input);
    }

    @Override
    protected Duration parse(String input) throws Exception {
        if (input.matches("^[\\d]+$")) {
            return Duration.seconds(Integer.valueOf(input));
        }

        return Duration.parse(input);
    }

}

Make constructor public, needs to be accessible from org.glassfish.jersey.*


package me.coley.recaf;

import me.coley.recaf.decompile.fernflower.FernFlowerDecompiler;
import me.coley.recaf.workspace.*;
import org.junit.jupiter.api.*;

import java.io.IOException;

import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.fail;

public class DecompileTest extends Base {
	private Workspace workspace;

	@BeforeEach
	public void setup() {
		try {
			JavaResource resource = new JarResource(getClasspathFile("inherit.jar"));
			resource.getClasses();
			resource.getResources();
			workspace = new Workspace(resource);
		} catch(IOException ex) {
			fail(ex);
		}
	}

	@Nested
	public class FernFlower {
		@Test
		public void testFernFlower() {
			String className = "test/Yoda";
			FernFlowerDecompiler decompiler = new FernFlowerDecompiler();
			String decomp = decompiler.decompile(workspace, className);
			assertNotNull(decomp);
		}
	}
}

package me.coley.recaf;

import me.coley.recaf.decompile.fernflower.FernFlowerDecompiler;
import me.coley.recaf.workspace.*;
import org.junit.jupiter.api.*;

import java.io.IOException;

import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.fail;

public class DecompileTest extends Base {
	private Workspace workspace;

	@BeforeEach
	public void setup() {
		try {
			JavaResource resource = new JarResource(getClasspathFile("inherit.jar"));
			resource.getClasses();
			resource.getResources();
			workspace = new Workspace(resource);
		} catch(IOException ex) {
			fail(ex);
		}
	}

	@Nested
	public class FernFlower {
		@Test
		public void testFernFlower() {
			FernFlowerDecompiler decompiler = new FernFlowerDecompiler();
			for (String name : workspace.getPrimaryClassNames()) {
				String decomp = decompiler.decompile(workspace, name);
				assertNotNull(decomp);
			}
		}
	}
}

Test for decompile against all classes in the primary resource


package org.codeswarm.lipsum;

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

class AttributeRendererImpl implements Lipsum.AttributeRenderer {

  private final Map<String, Lipsum.ParagraphGenerator> registeredLipsums = new HashMap<String, Lipsum.ParagraphGenerator>();

  @Override
  public void register(String format, Lipsum.ParagraphGenerator paragraphGenerator) {
    registeredLipsums.put(format, paragraphGenerator);
  }

  @Override
  public String toString(Object o, String formatString, Locale locale) {
    if (registeredLipsums.containsKey(formatString)) {
      Lipsum.ParagraphGenerator paragraphGenerator = registeredLipsums.get(formatString);
      Long key = null;
      if (o instanceof Integer) {
        key = ((Integer) o).longValue();
      } else if (o instanceof Long) {
        key = (Long) o;
      }
      if (key != null) {
        return paragraphGenerator.paragraph(key);
      }
    }
    return o.toString();
  }

}

package org.codeswarm.lipsum;

import com.google.common.collect.Maps;

import java.util.Locale;
import java.util.Map;

class AttributeRendererImpl implements Lipsum.AttributeRenderer {

  private final Map<String, Lipsum.ParagraphGenerator> registeredLipsums =
    Maps.newHashMapWithExpectedSize(4);

  @Override
  public void register(String format, Lipsum.ParagraphGenerator paragraphGenerator) {
    registeredLipsums.put(format, paragraphGenerator);
  }

  @Override
  public String toString(Object o, String formatString, Locale locale) {
    if (registeredLipsums.containsKey(formatString)) {
      Lipsum.ParagraphGenerator paragraphGenerator = registeredLipsums.get(formatString);
      Long key = null;
      if (o instanceof Integer) {
        key = ((Integer) o).longValue();
      } else if (o instanceof Long) {
        key = (Long) o;
      }
      if (key != null) {
        return paragraphGenerator.paragraph(key);
      }
    }
    return o.toString();
  }

}

Use guava to construct the HashMap.


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

package com.uber.tchannel.api;

public interface RequestHandler<REQUEST_TYPE, RESPONSE_TYPE> {
    RESPONSE_TYPE handle(REQUEST_TYPE request);
}

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

package com.uber.tchannel.api;

public interface RequestHandler<RequestT, ResponseT> {
    ResponseT handle(RequestT request);
}

Address @truncs comment on Generic Type naming


package models.jbehave;

import play.test.TestServer;
import play.test.Helpers;

public class JBehaveRunnerAssistant extends JBehaveRunnerCommandLine {

    private TestServer server;

    public static void main(String[] args) throws Throwable {
        JBehaveRunnerAssistant cpRunner = new JBehaveRunnerAssistant();
        if (!cpRunner.isHelp(args)) {
            JBehaveRunner runner = cpRunner.getRunner(args);
            try {
                cpRunner.startFakeApp();
                runner.run();
                runner.cleanUp();
                cpRunner.stopFakeApp();
            } catch (Throwable e) {
                runner.cleanUp();
                cpRunner.stopFakeApp();
                throw e;
            }
        }
    }

    public void startFakeApp() {
        server = Helpers.testServer(1234, Helpers.fakeApplication());
        Helpers.start(server);
    }

    public void stopFakeApp() {
        Helpers.stop(server);
    }

}

package models.jbehave;

import play.test.TestServer;
import play.test.Helpers;

public class JBehaveRunnerAssistant extends JBehaveRunnerCommandLine {

    private TestServer server;

    public static void main(String[] args) throws Throwable {
        JBehaveRunnerAssistant cpRunner = new JBehaveRunnerAssistant();
        System.out.println("111");
        if (!cpRunner.isHelp(args)) {
            System.out.println("222");
            JBehaveRunner runner = cpRunner.getRunner(args);
            System.out.println("333");
            try {
                cpRunner.startFakeApp();
                System.out.println("444");
                runner.run();
                System.out.println("444");
                cpRunner.stopFakeApp();
                System.out.println("555");
                runner.cleanUp();
                System.out.println("666");
                System.exit(0);
            } catch (Throwable e) {
                System.out.println("777");
                cpRunner.stopFakeApp();
                System.out.println("888");
                runner.cleanUp();
                System.exit(1);
            }
        }
        System.out.println("000");
    }

    public void startFakeApp() {
        server = Helpers.testServer(1234, Helpers.fakeApplication());
        Helpers.start(server);
    }

    public void stopFakeApp() {
        Helpers.stop(server);
    }

}

Change the runner so that exit is forced within the main.


package haushaltsbuch.controllers;

import java.io.IOException;
import java.util.Locale;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;

@WebFilter("/*")
public class ContentTypeFilter implements Filter
{
  public void destroy()
  {
    // this space intentionally left blank
  }

  public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException
  {
    response.setContentType("text/html; charset=utf-8");
    response.setLocale(Locale.GERMANY);

    chain.doFilter(request, response);
  }

  public void init(FilterConfig fConfig) throws ServletException
  {
    // this space intentionally left blank
  }
}

package haushaltsbuch.controllers;

import java.io.IOException;
import java.util.Locale;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;

@WebFilter("/*")
public class ContentTypeFilter implements Filter
{
  public void destroy()
  {
    // this space intentionally left blank
  }

  public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException
  {
    request.setCharacterEncoding("UTF-8");

    response.setContentType("text/html; charset=utf-8");
    response.setLocale(Locale.GERMANY);

    chain.doFilter(request, response);
  }

  public void init(FilterConfig fConfig) throws ServletException
  {
    // this space intentionally left blank
  }
}

Fix weird character issues by hard-coding to UTF-8


package org.rnorth.dropwizard.markdown.demo;

import io.dropwizard.Application;
import io.dropwizard.Configuration;
import io.dropwizard.setup.Bootstrap;
import io.dropwizard.setup.Environment;
import org.rnorth.dropwizard.markdown.MarkdownAssetsBundle;
import org.rnorth.dropwizard.markdown.MarkdownAssetsConfiguration;
import org.rnorth.dropwizard.markdown.MarkdownBundleConfiguration;

/**
 * Created by rnorth on 29/09/2016.
 */
public class DemoApplication extends Application<DemoApplication.DemoConfiguration> {

    @Override
    public void initialize(Bootstrap<DemoConfiguration> bootstrap) {
        bootstrap.addBundle(new MarkdownAssetsBundle()
                .withResourcePath("/docs")
                .withUriPath("/docs"));
    }

    @Override
    public void run(DemoConfiguration configuration, Environment environment) throws Exception {
        // Nothing needed here for demo purposes
    }

    public static void main(String[] args) throws Exception {
        new DemoApplication().run(args);
    }

    public static class DemoConfiguration extends Configuration implements MarkdownBundleConfiguration {

        public MarkdownAssetsConfiguration assets = new MarkdownAssetsConfiguration();

        @Override
        public MarkdownAssetsConfiguration getMarkdownAssetsConfiguration() {
            return assets;
        }
    }
}

package org.rnorth.dropwizard.markdown.demo;

import io.dropwizard.Application;
import io.dropwizard.Configuration;
import io.dropwizard.setup.Bootstrap;
import io.dropwizard.setup.Environment;
import org.rnorth.dropwizard.markdown.MarkdownAssetsBundle;
import org.rnorth.dropwizard.markdown.MarkdownAssetsConfiguration;
import org.rnorth.dropwizard.markdown.MarkdownBundleConfiguration;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriBuilder;

/**
 * Created by rnorth on 29/09/2016.
 */
@Path("/")
public class DemoApplication extends Application<DemoApplication.DemoConfiguration> {

    @Override
    public void initialize(Bootstrap<DemoConfiguration> bootstrap) {
        bootstrap.addBundle(new MarkdownAssetsBundle()
                .withResourcePath("/docs")
                .withUriPath("/docs"));
    }

    @Override
    public void run(DemoConfiguration configuration, Environment environment) throws Exception {
        // Nothing needed here for demo purposes, but redirect the root path to /docs/
        environment.jersey().register(this);
    }

    public static void main(String[] args) throws Exception {
        new DemoApplication().run(args);
    }

    public static class DemoConfiguration extends Configuration implements MarkdownBundleConfiguration {

        public MarkdownAssetsConfiguration assets = new MarkdownAssetsConfiguration();

        @Override
        public MarkdownAssetsConfiguration getMarkdownAssetsConfiguration() {
            return assets;
        }
    }

    @GET
    public Response redirectRootToDocs() {
        return Response.temporaryRedirect(UriBuilder.fromPath("/docs/").build()).build();
    }
}

Add redirect from / to /docs/ for demo purposes


package se.kits.gakusei.content.repository;

import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;
import org.springframework.data.repository.query.Param;
import se.kits.gakusei.content.model.Lesson;
import se.kits.gakusei.content.model.Nugget;

import java.util.List;

public interface LessonRepository extends CrudRepository<Lesson, Long> {

    Lesson findByName(String name);

    List<Nugget> findNuggetsByTwoFactTypes(
            @Param("lessonName") String lessonName,
            @Param("factType1") String questionType,
            @Param("factType2") String answerType);

    List<Nugget> findNuggetsBySuccessrate(
            @Param("username") String username,
            @Param("lessonName") String lessonName,
            @Param("factType1") String questionType,
            @Param("factType2") String answerType);

    List<Nugget> findUnansweredNuggets(
            @Param("username") String username,
            @Param("lessonName") String lessonName,
            @Param("factType1") String questionType,
            @Param("factType2") String answerType);

    @Query("select l from Lesson l where not l.description = 'quiz'")
    List<Lesson> findVocabularyLessons();

    @Query("select l from Lesson l where l.description = 'quiz'")
    List<Lesson> findQuizLessons();
}

package se.kits.gakusei.content.repository;

import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;
import org.springframework.data.repository.query.Param;
import se.kits.gakusei.content.model.Lesson;
import se.kits.gakusei.content.model.Nugget;

import java.util.List;

public interface LessonRepository extends CrudRepository<Lesson, Long> {

    Lesson findByName(String name);

    List<Nugget> findNuggetsByTwoFactTypes(
            @Param("lessonName") String lessonName,
            @Param("factType1") String questionType,
            @Param("factType2") String answerType);

    List<Nugget> findNuggetsBySuccessrate(
            @Param("username") String username,
            @Param("lessonName") String lessonName,
            @Param("factType1") String questionType,
            @Param("factType2") String answerType);

    List<Nugget> findUnansweredNuggets(
            @Param("username") String username,
            @Param("lessonName") String lessonName,
            @Param("factType1") String questionType,
            @Param("factType2") String answerType);

    @Query("select l from Lesson l where not l.description = 'quiz' order by l.name")
    List<Lesson> findVocabularyLessons();

    @Query("select l from Lesson l where l.description = 'quiz' order by l.name")
    List<Lesson> findQuizLessons();
}

Sort lessons by name when retrieving from db