package org.openlmis.core.upload;

import org.openlmis.core.domain.BaseModel;
import org.openlmis.core.domain.Budget;
import org.openlmis.core.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class BudgetHandler extends AbstractModelPersistenceHandler {

  @Autowired
  private BudgetService service;

  @Autowired
  private FacilityService facilityService;

  @Autowired
  private ProgramService programService;

  @Autowired
  private ProcessingPeriodService processingPeriodService;

  @Override
  protected BaseModel getExisting(BaseModel record) {
    Budget budget = ((Budget) record);
    return service.getByCodes(budget.getProgram().getCode(), budget.getPeriod().getName(), budget.getFacility().getCode() );
  }

  @Override
  protected void save(BaseModel record) {
    fillReferenceData((Budget) record);
    validateBudget((Budget) record);
    service.save((Budget) record);
  }

  private void fillReferenceData(Budget budget){
      // set the id's of all reference data
      // this is to make sure that the save routine will be able to save this budget information
      budget.setFacility( facilityService.getByCode(budget.getFacility() ) );
      budget.setProgram( programService.getByCode(budget.getProgram().getCode()));
      budget.getPeriod().setId(processingPeriodService.getIdByName(budget.getPeriod().getName()));
  }

  private void validateBudget(Budget budget){
     facilityService.is
  }

  @Override
  protected String getDuplicateMessageKey() {
    return "error.duplicate.Budget";
  }
}

package org.openlmis.core.upload;

import org.openlmis.core.domain.BaseModel;
import org.openlmis.core.domain.Budget;
import org.openlmis.core.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class BudgetHandler extends AbstractModelPersistenceHandler {

  @Autowired
  private BudgetService service;

  @Autowired
  private FacilityService facilityService;

  @Autowired
  private ProgramService programService;

  @Autowired
  private ProcessingPeriodService processingPeriodService;

  @Override
  protected BaseModel getExisting(BaseModel record) {
    Budget budget = ((Budget) record);
    return service.getByCodes(budget.getProgram().getCode(), budget.getPeriod().getName(), budget.getFacility().getCode() );
  }

  @Override
  protected void save(BaseModel record) {
    fillReferenceData((Budget) record);
    validateBudget((Budget) record);
    service.save((Budget) record);
  }

  private void fillReferenceData(Budget budget){
      // set the id's of all reference data
      // this is to make sure that the save routine will be able to save this budget information
      budget.setFacility( facilityService.getByCode(budget.getFacility() ) );
      budget.setProgram( programService.getByCode(budget.getProgram().getCode()));
      budget.getPeriod().setId(processingPeriodService.getIdByName(budget.getPeriod().getName()));
  }

  private void validateBudget(Budget budget){

  }

  @Override
  protected String getDuplicateMessageKey() {
    return "error.duplicate.Budget";
  }
}

Fix compiler error on validate budget handler


/**
 * Copyright 2005-2011 The Kuali Foundation
 *
 * Licensed under the Educational Community 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.opensource.org/licenses/ecl2.php
 *
 * 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 edu.samplu.mainmenu.test;

import org.junit.Test;

import edu.samplu.common.MainMenuLookupLegacyITBase;

/**
 * tests that user 'admin' can display the Term lookup screen, search,
 * initiate an Term maintenance document via an edit action on the search results and
 * finally cancel the maintenance document
 *
 * @author Kuali Rice Team (rice.collab@kuali.org)
 */
public class TermLookUpLegacyIT extends MainMenuLookupLegacyITBase {
    @Override
    public String getLinkLocator() {
        return "Term Lookup";
    }

    @Test
    public void lookupAssertions() throws Exception{
        gotoMenuLinkLocator();
        super.testTermLookUp();
    }
}

/**
 * Copyright 2005-2011 The Kuali Foundation
 *
 * Licensed under the Educational Community 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.opensource.org/licenses/ecl2.php
 *
 * 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 edu.samplu.mainmenu.test;

import org.junit.Test;

import edu.samplu.common.MainMenuLookupLegacyITBase;

/**
 * tests that user 'admin' can display the Term lookup screen, search,
 * initiate an Term maintenance document via an edit action on the search results and
 * finally cancel the maintenance document
 *
 * @author Kuali Rice Team (rice.collab@kuali.org)
 */
public class TermLookUpLegacyIT extends MainMenuLookupLegacyITBase {
    @Override
    public void testLookUp() {} // no-op to avoid https://jira.kuali.org/browse/KULRICE-9047 messing up the server state

    @Override
    public String getLinkLocator() {
        return "Term Lookup";
    }

    @Test
    public void lookupAssertions() throws Exception{
        gotoMenuLinkLocator();
        super.testTermLookUp();
    }
}

Disable term lookup smoke test to avoid any server impact till fixed.


package com.github.aureliano.verbum_domini.helper;

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

import org.apache.commons.lang.StringUtils;

public final class UrlHelper {

	private UrlHelper() {
		super();
	}

	public static String join(Object...tokens) {
		return "/" + StringUtils.join(tokens, '/');
	}

	public static String buildWebAppUrl(ServletRequest request, String path) {
		String contextPath = ((HttpServletRequest) request).getContextPath();
		if (contextPath.startsWith("/")) {
			contextPath = contextPath.substring(1);
		}
		return join(contextPath, path);
	}

	public static String buildWebAppUrl(String path) {
		return buildWebAppUrl(WebHelper.getRequest(), path);
	}
}

package com.github.aureliano.verbum_domini.helper;

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

import org.apache.commons.lang.StringUtils;

public final class UrlHelper {

	private UrlHelper() {
		super();
	}

	public static String join(Object...tokens) {
		return "/" + StringUtils.join(tokens, '/');
	}

	public static String buildWebAppUrl(ServletRequest request, String path) {
		String contextPath = ((HttpServletRequest) request).getContextPath();
		if (contextPath.startsWith("/")) {
			contextPath = contextPath.substring(1);
		}

		return (StringUtils.isEmpty(contextPath)) ? path : join(contextPath, path);
	}

	public static String buildWebAppUrl(String path) {
		return buildWebAppUrl(WebHelper.getRequest(), path);
	}
}

Build URL with server context path.


package net.openright.infrastructure.rest;

import java.io.IOException;
import java.io.Writer;

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

import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class JsonGetController implements GetController {

	private static final Logger log = LoggerFactory.getLogger(JsonGetController.class);

	private JsonController jsonController;

	public JsonGetController(JsonController jsonController) {
		this.jsonController = jsonController;
	}

	@Override
	public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		String[] parts = req.getPathInfo().split("\\/");

		try {
			JSONObject json = parts.length > 2 ? jsonController.getJSON(parts[2]) : jsonController.listJSON(req);
			log.info("JSON response: {}", json);
			sendResponse(resp, json);
		} catch (RequestException e) {
			log.warn("Invalid request {}: {}", req.getRequestURL(), e.toString());
			resp.sendError(e.getStatusCode(), e.toString());
		}
	}

	private void sendResponse(HttpServletResponse resp, JSONObject response) throws IOException {
		resp.setHeader("Expires", "-1");

		if (response == null) {
			resp.setStatus(204);
			return;
		}

		resp.setContentType("application/json");
		try (Writer writer = resp.getWriter()) {
			writer.write(response.toString());
		}
	}
}

package net.openright.infrastructure.rest;

import java.io.IOException;
import java.io.Writer;

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

import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class JsonGetController implements GetController {

	private static final Logger log = LoggerFactory.getLogger(JsonGetController.class);

	private JsonController jsonController;

	public JsonGetController(JsonController jsonController) {
		this.jsonController = jsonController;
	}

	@Override
	public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		String[] parts = req.getPathInfo().split("\\/");

		try {
			JSONObject json = parts.length > 2 ? jsonController.getJSON(parts[2]) : jsonController.listJSON(req);
			log.info("JSON response: {}", json.toString());
			sendResponse(resp, json);
		} catch (RequestException e) {
			log.warn("Invalid request {}: {}", req.getRequestURL(), e.toString());
			resp.sendError(e.getStatusCode(), e.toString());
		}
	}

	private void sendResponse(HttpServletResponse resp, JSONObject response) throws IOException {
		resp.setHeader("Expires", "-1");

		if (response == null) {
			resp.setStatus(204);
			return;
		}

		resp.setContentType("application/json");
		try (Writer writer = resp.getWriter()) {
			writer.write(response.toString());
		}
	}
}

Use json.toString instead of json when printing object.


/*
 * Copyright 2021, Yurii Serhiichuk
 *
 * 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.openweathermap.api.query;

import lombok.Data;

@Data
public abstract class AbstractQuery implements Query {
    private UnitFormat unitFormat;
    private Language language;
    private final String baseUrl = BASE_URL;

    @Override
    public String toStringRepresentation(String apiKey) {
        StringBuilder stringBuilder = new StringBuilder(baseUrl);
        stringBuilder.append(getSearchPath());
        stringBuilder.append(QUESTION_MARK);
        if (getLanguage() != null) {
            stringBuilder.append("lang=").append(getLanguage().getStringRepresentation()).append(AND);
        }
        if (getUnitFormat() != null) {
            stringBuilder.append("units=").append(getUnitFormat().getStringRepresentation()).append(AND);
        }
        stringBuilder.append(getRequestPart());
        stringBuilder.append(AND).append("appid=").append(apiKey);
        return stringBuilder.toString();
    }

    protected abstract String getSearchPath();

    protected abstract String getRequestPart();
}

/*
 * Copyright 2021, Yurii Serhiichuk
 *
 * 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.openweathermap.api.query;

import lombok.Data;

@Data
public abstract class AbstractQuery implements Query {

    @SuppressWarnings({"FieldCanBeLocal", "FieldMayBeFinal"}) /* We'd like to be able to override the base URL. */
    private String baseUrl = BASE_URL;
    private UnitFormat unitFormat;
    private Language language;

    @Override
    public String toStringRepresentation(String apiKey) {
        StringBuilder stringBuilder = new StringBuilder(baseUrl);
        stringBuilder.append(getSearchPath());
        stringBuilder.append(QUESTION_MARK);
        if (getLanguage() != null) {
            stringBuilder.append("lang=").append(getLanguage().getStringRepresentation()).append(AND);
        }
        if (getUnitFormat() != null) {
            stringBuilder.append("units=").append(getUnitFormat().getStringRepresentation()).append(AND);
        }
        stringBuilder.append(getRequestPart());
        stringBuilder.append(AND).append("appid=").append(apiKey);
        return stringBuilder.toString();
    }

    protected abstract String getSearchPath();

    protected abstract String getRequestPart();
}

Make `baseUrl` non-final as we should be able to override it.


package com.msgilligan.bitcoinj.cli;

import com.msgilligan.bitcoinj.rpc.JsonRPCException;

import java.io.IOException;
import java.util.List;

/**
 * An attempt at cloning the bitcoin-cli tool, but using Java and bitcoinj
 *
 */
public class BitcoinJCli extends CliCommand {
    public final static String commandName = "bitcoinj-cli";

    public BitcoinJCli(String[] args) {
        super(commandName, new CliOptions(), args);
    }

    public static void main(String[] args) {
        BitcoinJCli command = new BitcoinJCli(args);
        Integer status = command.run();
        System.exit(status);
    }

    public Integer runImpl() throws IOException {
        // Hacked together parsing that barely supports the two RPC methods in the Spock test
        // TODO: Make this better and complete
        @SuppressWarnings("unchecked")
        List<Object> args = (List<Object>) line.getArgList();
        String method = (String) args.get(0);
        args.remove(0); // remove method from list
        if (args.size() > 0 && args.get(0) != null) {
            args.set(0, true);
        }
        Object result;
        try {
            result = client.cliSend(method, args.toArray());
        } catch (JsonRPCException e) {
            e.printStackTrace();
            return 1;
        }
        if (result != null) {
            pwout.println(result.toString());
        }
        return 0;
    }
}

package com.msgilligan.bitcoinj.cli;

import com.msgilligan.bitcoinj.rpc.JsonRPCException;

import java.io.IOException;
import java.util.List;

/**
 * An attempt at cloning the bitcoin-cli tool, but using Java and bitcoinj
 *
 */
public class BitcoinJCli extends CliCommand {
    public final static String commandName = "bitcoinj-cli";

    public BitcoinJCli(String[] args) {
        super(commandName, new CliOptions(), args);
    }

    public static void main(String[] args) {
        BitcoinJCli command = new BitcoinJCli(args);
        Integer status = command.run();
        System.exit(status);
    }

    public Integer runImpl() throws IOException {
        // Hacked together parsing that barely supports the two RPC methods in the Spock test
        // TODO: Make this better and complete
        @SuppressWarnings("unchecked")
        List<Object> args = (List<Object>) line.getArgList();
        if (args.size() == 0) {
            printError("rpc method required");
            printHelp();
            return(1);
        }
        String method = (String) args.get(0);
        args.remove(0); // remove method from list
        if (args.size() > 0 && args.get(0) != null) {
            args.set(0, true);
        }
        Object result;
        try {
            result = client.cliSend(method, args.toArray());
        } catch (JsonRPCException e) {
            e.printStackTrace();
            return 1;
        }
        if (result != null) {
            pwout.println(result.toString());
        }
        return 0;
    }
}

Handle zero-arguments case in bitcoinj-cli


/*
 * Copyright (c) 2014, Cloudera, Inc. All Rights Reserved.
 *
 * Cloudera, Inc. licenses this file to you under the Apache License,
 * Version 2.0 (the "License"). You may not use this file except in
 * compliance with the License. You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * This software is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
 * CONDITIONS OF ANY KIND, either express or implied. See the License for
 * the specific language governing permissions and limitations under the
 * License.
 */

package com.cloudera.oryx.common.random;

import org.apache.commons.math3.random.RandomGenerator;
import org.junit.Before;
import org.junit.Test;

import com.cloudera.oryx.common.OryxTest;

public final class RandomManagerRandomTest extends OryxTest {

  @Override
  @Before
  public void initRandom() {
    // specifically don't init random
  }

  @Test
  public void testRandomState() {
    RandomGenerator generator = RandomManager.getRandom();
    double unseededValue = generator.nextDouble();
    RandomManager.useTestSeed();
    double seededValue = generator.nextDouble();
    assertNotEquals(unseededValue, seededValue);
    assertEquals(seededValue, RandomManager.getRandom().nextDouble());
  }

}

/*
 * Copyright (c) 2014, Cloudera, Inc. All Rights Reserved.
 *
 * Cloudera, Inc. licenses this file to you under the Apache License,
 * Version 2.0 (the "License"). You may not use this file except in
 * compliance with the License. You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * This software is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
 * CONDITIONS OF ANY KIND, either express or implied. See the License for
 * the specific language governing permissions and limitations under the
 * License.
 */

package com.cloudera.oryx.common.random;

import org.apache.commons.math3.random.RandomGenerator;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;

import com.cloudera.oryx.common.OryxTest;

public final class RandomManagerRandomTest extends OryxTest {

  @Override
  @Before
  public void initRandom() {
    // specifically don't init random
  }

  // Not clear why this only fails on JenkinsDisable
  @Ignore
  @Test
  public void testRandomState() {
    RandomGenerator generator = RandomManager.getRandom();
    double unseededValue = generator.nextDouble();
    RandomManager.useTestSeed();
    double seededValue = generator.nextDouble();
    assertNotEquals(unseededValue, seededValue);
    assertEquals(seededValue, RandomManager.getRandom().nextDouble());
  }

}

Disable random test for Jenkins


package com.pinterest.secor.io.impl;

import com.pinterest.secor.common.SecorConfig;
import com.pinterest.secor.io.AdgearReader;
import com.pinterest.secor.io.KeyValue;

import net.minidev.json.JSONObject;
import net.minidev.json.JSONValue;

// Converts delivery JSON to Beh TSV
public class AdgearDeliveryJsonReader implements AdgearReader {
    private final String timestampFieldname;

    public AdgearDeliveryJsonReader(SecorConfig secorConfig) {
        timestampFieldname = secorConfig.getMessageTimestampName();
    }

    public String convert(KeyValue kv) {
        JSONObject jsonObject = null;
        Object value = JSONValue.parse(kv.getValue());
        if (value instanceof JSONObject) {
            jsonObject = (JSONObject) value;
        } else {
            return null;
        }

        Double timestamp = (Double) jsonObject.get(timestampFieldname);
        String cookieId = (String) jsonObject.get("uid");
        Integer segmentId = (Integer) jsonObject.get("segment_id");
        Boolean segmentIsNew = (Boolean) jsonObject.get("segment_new");

        if (timestamp == null || cookieId == null || segmentId == null
            || segmentIsNew == null || !segmentIsNew) {
            return null;
        }

        return String.format("%s\t%d\tseg:%d\n",
                             cookieId, Math.round(timestamp), segmentId);
    }
}

package com.pinterest.secor.io.impl;

import com.pinterest.secor.common.SecorConfig;
import com.pinterest.secor.io.AdgearReader;
import com.pinterest.secor.io.KeyValue;

import net.minidev.json.JSONObject;
import net.minidev.json.JSONValue;

// Converts delivery JSON to Beh TSV
public class AdgearDeliveryJsonReader implements AdgearReader {
    private final String timestampFieldname;

    public AdgearDeliveryJsonReader(SecorConfig secorConfig) {
        timestampFieldname = secorConfig.getMessageTimestampName();
    }

    public String convert(KeyValue kv) {
        JSONObject jsonObject = null;
        Object value = JSONValue.parse(kv.getValue());
        if (value instanceof JSONObject) {
            jsonObject = (JSONObject) value;
        } else {
            return null;
        }

        Double timestamp = (Double) jsonObject.get(timestampFieldname);
        String cookieId = (String) jsonObject.get("uid");
        Integer buyerId = (Integer) jsonObject.get("buyer_id");
        Integer segmentId = (Integer) jsonObject.get("segment_id");
        Boolean segmentIsNew = (Boolean) jsonObject.get("segment_new");

        if (timestamp == null || buyerId == null || cookieId == null || segmentId == null
            || segmentIsNew == null || !segmentIsNew) {
            return null;
        }

        return String.format("%s\t%d\t%d:seg:%d\n",
                             cookieId, Math.round(timestamp), buyerId, segmentId);
    }
}

Write buyer ID when converting delivery logs.


/*
  Write a recursive method that finds the number of occurrences of a specified
  letter in a string using the following method header:

  public static int count(String str, char a)

  For example, count("Welcome", 'e') returns 2. Write a test program that
  prompts the user to enter a string and a character, and displays the number
  of occurrences for the character in the string.
*/

import java.util.Scanner;

public class E18_10 {
  public static void main(String[] args) {
    Scanner input = new Scanner(System.in);
    System.out.print("Enter a string: ");
    String s = input.nextLine();
    System.out.print("Enter a character: ");
    char c = input.nextLine().charAt(0);

    System.out.println(count(s, c));
  }

  public static int count(String str, char a) {
    if (str.length() > 0) {
      int match =
        str.toLowerCase().charAt(0) == Character.toLowerCase(a) ? 1 : 0;
      return match + count(str.substring(1, str.length()), a);
    } else {
      return 0;
    }
  }
}

/*
  Write a recursive method that finds the number of occurrences of a specified
  letter in a string using the following method header:

  public static int count(String str, char a)

  For example, count("Welcome", 'e') returns 2. Write a test program that
  prompts the user to enter a string and a character, and displays the number
  of occurrences for the character in the string.
*/

import java.util.Scanner;

public class E18_10 {
  public static void main(String[] args) {
    Scanner input = new Scanner(System.in);
    System.out.print("Enter a string: ");
    String s = input.nextLine();
    System.out.print("Enter a character: ");
    char c = input.nextLine().charAt(0);

    System.out.println(count(s, c));
  }

  public static int count(String str, char a) {
    return count(str, a, 0);
  }

  private static int count(String str, char a, int index) {
    if (index < str.length()) {
      int match =
        str.toLowerCase().charAt(index) == Character.toLowerCase(a) ? 1 : 0;
      return match + count(str, a, index + 1);
    } else {
      return 0;
    }
  }
}

Use auxilliary recursive method to eliminate need to create new strings via substring method


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

package bisq.desktop.util.validation;

public final class RevolutValidator extends LengthValidator {
    public RevolutValidator() {
        // Not sure what are requirements for Revolut user names
        // Please keep in mind that even we force users to set user name at startup we should handle also the case
        // that the old accountID as phone number or email is displayed at the username text field and we do not
        // want to break validation in those cases. So being too strict on the validators might cause more troubles
        // as its worth...
        super(5, 100);
    }

    public ValidationResult validate(String input) {
        return super.validate(input);
    }

}

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

package bisq.desktop.util.validation;

public final class RevolutValidator extends LengthValidator {
    public RevolutValidator() {
        // Not sure what are requirements for Revolut user names
        // Please keep in mind that even we force users to set user name at startup we should handle also the case
        // that the old accountID as phone number or email is displayed at the username text field and we do not
        // want to break validation in those cases. So being too strict on the validators might cause more troubles
        // as its worth...
        // UPDATE 04/2021: Revolut usernames could be edited (3-16 characters, lowercase a-z and numbers only)
        super(3, 100);
    }

    public ValidationResult validate(String input) {
        return super.validate(input);
    }

}

Allow Revolut username to be minimum 3 characters


package com.marcospassos.phpserializer.adapter;

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

import com.marcospassos.phpserializer.Context;
import com.marcospassos.phpserializer.Writer;
import java.util.HashMap;
import java.util.Map;
import org.junit.Test;
import org.mockito.InOrder;

/**
 * @author Marcos Passos
 * @since 1.0
 */
public class MapAdapterTest
{
    @Test
    public void write() throws Exception
    {
        MapAdapter<Object, Object> adapter = new MapAdapter<>();
        Writer writer = mock(Writer.class);
        Context context = mock(Context.class);
        Map<Object, Object> map = new HashMap<>();
        map.put(1, "a");
        map.put("2", "b");
        map.put(3, "c");

        adapter.write(map, writer, context);

        InOrder order = inOrder(writer, context);

        order.verify(writer).writeArrayStart(3);
        order.verify(writer).writeKey(1);
        order.verify(context).write("a", writer);
        order.verify(writer).writeKey("2");
        order.verify(context).write("b", writer);
        order.verify(writer).writeKey(3);
        order.verify(context).write("c", writer);
        order.verify(writer).writeArrayEnd();
    }
}

package com.marcospassos.phpserializer.adapter;

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

import com.marcospassos.phpserializer.Context;
import com.marcospassos.phpserializer.Writer;
import java.util.HashMap;
import java.util.Map;
import org.junit.Test;
import org.mockito.InOrder;

/**
 * @author Marcos Passos
 * @since 1.0
 */
public class MapAdapterTest
{
    @Test
    public void write() throws Exception
    {
        MapAdapter<Object, Object> adapter = new MapAdapter<>();
        Writer writer = mock(Writer.class);
        Context context = mock(Context.class);
        Map<Object, Object> map = new HashMap<>();
        map.put(1, "a");
        map.put("2", "b");
        map.put(3, "c");

        // The verify check is split by entries once HashMap is an unordered map

        adapter.write(map, writer, context);

        InOrder order = inOrder(writer, context);

        order.verify(writer).writeArrayStart(3);

        InOrder first = inOrder(writer, context);

        first.verify(writer).writeKey(1);
        first.verify(context).write("a", writer);

        InOrder second = inOrder(writer, context);

        second.verify(writer).writeKey("2");
        second.verify(context).write("b", writer);

        InOrder third = inOrder(writer, context);

        third.verify(writer).writeKey(3);
        third.verify(context).write("c", writer);

        order.verify(writer).writeArrayEnd();

        order.verifyNoMoreInteractions();
    }
}

Fix test for unordered map making it order-insensitive


package com.novoda.downloadmanager;

import com.novoda.notils.logger.simple.Log;

class WaitForLockRunnable {

    interface Action {
        void performAction();
    }

    static WaitForLockAndThenPerformActionRunnable waitFor(Object lock) {
        return new WaitForLockAndThenPerformActionRunnable(lock);
    }

    static class WaitForLockAndThenPerformActionRunnable {

        private final Object lock;

        WaitForLockAndThenPerformActionRunnable(Object lock) {
            this.lock = lock;
        }

        Runnable thenPerform(final Action action) {
            return new Runnable() {
                @Override
                public void run() {
                    waitOnLock();
                    action.performAction();
                }
            };
        }

        private void waitOnLock() {
            try {
                synchronized (lock) {
                    lock.wait();
                }
            } catch (InterruptedException e) {
                Log.e(e, "Interruped waiting for download service.");
            }
        }
    }

}

package com.novoda.downloadmanager;

import com.novoda.notils.logger.simple.Log;

class WaitForLockRunnable {

    interface Action {
        void performAction();
    }

    private WaitForLockRunnable() {
        // Uses static factory method.
    }

    static WaitForLockAndThenPerformActionRunnable waitFor(Object lock) {
        return new WaitForLockAndThenPerformActionRunnable(lock);
    }

    static class WaitForLockAndThenPerformActionRunnable {

        private final Object lock;

        WaitForLockAndThenPerformActionRunnable(Object lock) {
            this.lock = lock;
        }

        Runnable thenPerform(final Action action) {
            return new Runnable() {
                @Override
                public void run() {
                    waitOnLock();
                    action.performAction();
                }
            };
        }

        private void waitOnLock() {
            try {
                synchronized (lock) {
                    lock.wait();
                }
            } catch (InterruptedException e) {
                Log.e(e, "Interruped waiting for download service.");
            }
        }
    }

}

Add private constructor for factory.


package thredds.catalog2;

import junit.framework.*;
import thredds.catalog2.simpleImpl.*;
import thredds.catalog2.xml.parser.TestCatalogParser;

/**
 * _more_
 *
 * @author edavis
 * @since 4.0
 */
public class TestAll extends TestCase
{
  public TestAll( String name )
  {
    super( name );
  }

  public static Test suite()
  {
    TestSuite suite = new TestSuite();
    // Tests in thredds.catalog2.simpleImpl
    suite.addTestSuite( TestPropertyImpl.class );
    suite.addTestSuite( TestPropertyContainer.class );
    suite.addTestSuite( TestServiceImpl.class );
    suite.addTestSuite( TestServiceContainer.class );
    suite.addTestSuite( TestAccessImpl.class );
    suite.addTestSuite( TestCatalogImpl.class );

    // Tests in thredds.catalog2.xml
    suite.addTestSuite( TestCatalogParser.class );

    return suite;
  }
}

package thredds.catalog2;

import junit.framework.*;
import thredds.catalog2.simpleImpl.*;
import thredds.catalog2.xml.parser.TestCatalogParser;

/**
 * _more_
 *
 * @author edavis
 * @since 4.0
 */
public class TestAll extends TestCase
{
  public TestAll( String name )
  {
    super( name );
  }

  public static Test suite()
  {
    TestSuite suite = new TestSuite();
    // Tests in thredds.catalog2.simpleImpl
    suite.addTestSuite( TestPropertyImpl.class );
    suite.addTestSuite( TestPropertyContainer.class );
    suite.addTestSuite( TestServiceImpl.class );
    suite.addTestSuite( TestServiceContainer.class );
    suite.addTestSuite( TestDatasetNodeImpl.class );
    suite.addTestSuite( TestAccessImpl.class );
    //suite.addTestSuite( TestCatalogRefImpl.class );
    suite.addTestSuite( TestCatalogImpl.class );

    // Tests in thredds.catalog2.xml
    suite.addTestSuite( TestCatalogParser.class );

    return suite;
  }
}

Work on thredds.catalog2: working on unit tests.


package de.philipphager.disclosure.database.app;

import android.content.pm.PackageInfo;

public final class MockPackage {
  @SuppressWarnings("PMD.UnnecessaryConstructor") private MockPackage() {
    //No instances of helper classes.
  }

  public static final PackageInfo TEST = new PackageInfo() {{
    packageName = MockApp.TEST.packageName();
    versionCode = MockApp.TEST_INFO.versionCode();
  }};

  public static PackageInfo TEST2 = new PackageInfo() {{
    packageName = MockApp.TEST2.packageName();
    versionCode = MockApp.TEST2_INFO.versionCode();
  }};
}

package de.philipphager.disclosure.database.app;

import android.content.pm.PackageInfo;

public final class MockPackage {
  @SuppressWarnings("PMD.UnnecessaryConstructor") private MockPackage() {
    //No instances of helper classes.
  }

  public static final PackageInfo TEST = new PackageInfo() {{
    packageName = MockApp.TEST.packageName();
    versionCode = MockApp.TEST_INFO.versionCode();
  }};

  public static final PackageInfo TEST2 = new PackageInfo() {{
    packageName = MockApp.TEST2.packageName();
    versionCode = MockApp.TEST2_INFO.versionCode();
  }};
}

Fix helper field not being final


package controller;

import boundary.PlayerApplication;
import model.PlayerModel;
import model.PlayerState;
import model.Point;
import model.Move;

/**
 * @author Eli Skeggs, Nick Chaput
 */
public class PlayerStartMoveCtrl {
  PlayerApplication app;
  PlayerModel model;

  public PlayerStartMoveCtrl(PlayerApplication app, PlayerModel model) {
    this.app = app;
    this.model = model;
  }

  /**
   * TODO: is there anything in the boundary that needs to get updated?
   */
  public void startMove(Point point) {
    model.playerState = PlayerState.SELECT;
   // System.out.println(model.playerState.toString());
    model.move = new Move();
    model.move.expand(model.level.currentBoard, point);
  }
}

package controller;

import boundary.PlayerApplication;
import model.PlayerModel;
import model.PlayerState;
import model.Point;
import model.Move;

/**
 * @author Eli Skeggs, Nick Chaput
 */
public class PlayerStartMoveCtrl {
  PlayerApplication app;
  PlayerModel model;

  public PlayerStartMoveCtrl(PlayerApplication app, PlayerModel model) {
    this.app = app;
    this.model = model;
  }

  /**
   * TODO: is there anything in the boundary that needs to get updated?
   */
  public void startMove(Point point) {
    model.playerState = PlayerState.SELECT;
    model.move = new Move();
    model.move.expand(model.level.currentBoard, point);
  }
}

Fix errors with mouse leaving boardview during a move and remove error-finding messages


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

import org.apache.camel.Exchange;
import org.apache.camel.Message;

public final class AwsExchangeUtil {

    private AwsExchangeUtil() {
    }

    public static Message getMessageForResponse(final Exchange exchange) {
        if (exchange.getPattern().isOutCapable()) {
            Message out = exchange.getOut();
            out.copyFrom(exchange.getIn());
            return out;
        }
        return exchange.getIn();
    }
}

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

import org.apache.camel.Exchange;
import org.apache.camel.Message;

public final class AwsExchangeUtil {

    private AwsExchangeUtil() {
    }

    public static Message getMessageForResponse(final Exchange exchange) {
        if (exchange.getPattern().isOutCapable()) {
            return exchange.getOut();
        }
        return exchange.getIn();
    }
}

Fix over writing previous addToResult calls


import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.nio.file.Files;
import java.util.*;
import machine.learning.ARL;

public class Programme {

    public static void main(String[] args) throws FileNotFoundException {

        ArrayList array = new ArrayList<Double>();
        Scanner lineReader = new Scanner(new File("data/EURUSD.dat"));

        while(lineReader.hasNext()){
            String line = lineReader.nextLine();
            String[] tmp = line.split("/")[0].split(" ");
            array.add(Double.parseDouble(tmp[tmp.length - 1]));
        }

        ARL arl = new ARL(13);
        // arl.loop(array.subList(200000,260000), 1000);
        // arl.loop(array.subList(260000,270000), 1000);

        System.out.println(arl.toString());
    }
}

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.nio.file.Files;
import java.util.*;
import machine.learning.ARL;

public class Programme {

    //TODO fixe the exemple in java
    public static void main(String[] args) throws FileNotFoundException {

        ArrayList array = new ArrayList<Double>();
        Scanner lineReader = new Scanner(new File("data/EURUSD.dat"));

        while(lineReader.hasNext()){
            String line = lineReader.nextLine();
            String[] tmp = line.split("/")[0].split(" ");
            array.add(Double.parseDouble(tmp[tmp.length - 1]));
        }

        ARL arl = new ARL(13);
        // arl.loop(array.subList(200000,260000), 1000);
        // arl.loop(array.subList(260000,270000), 1000);

        System.out.println(arl.toString());
    }
}

Add a todo in the file.


package se.kits.gakusei.content.repository;

import org.springframework.data.repository.CrudRepository;
import se.kits.gakusei.content.model.GrammarText;

public interface GrammarTextRepository extends CrudRepository<GrammarText, String> {
}

package se.kits.gakusei.content.repository;

import org.springframework.data.repository.CrudRepository;
import se.kits.gakusei.content.model.GrammarText;

import java.util.List;

public interface GrammarTextRepository extends CrudRepository<GrammarText, String> {

    List<GrammarText> findByInflectionMethod(String inflectionMethod);
}

Add method for finding grammarText using inflectionMethod


package x2x.translator.xcodeml.transformation;

import java.util.ArrayList;

import x2x.translator.xcodeml.xelement.XcodeProg;
import x2x.translator.xcodeml.transformer.Transformer;

/**
 * An dependent transformation group check wether it can be transformed with
 * another pending transformation in the pipeline. Each transformation are
 * applied only once.
 */

public class DependentTransformationGroup<T extends Transformation<? super T>> extends TransformationGroup<T> {

  public DependentTransformationGroup(String name) {
    super(name);
  }

  public void applyTranslations(XcodeProg xcodeml, Transformer transformer){
    for(int i = 0; i < _translations.size(); ++i){
      T base = _translations.get(i);
      for(int j = i + 1; j < _translations.size(); ++j){
        T candidate = _translations.get(j);
        if(candidate.isTransformed()){
          continue;
        }
        if(base.canBeTransformedWith(candidate)){
          base.transform(xcodeml, transformer, candidate);
        }
      }
    }
  }
}

package x2x.translator.xcodeml.transformation;

import java.util.ArrayList;

import x2x.translator.xcodeml.xelement.XcodeProg;
import x2x.translator.xcodeml.transformer.Transformer;

/**
 * An dependent transformation group check wether it can be transformed with
 * another pending transformation in the pipeline. Each transformation are
 * applied only once.
 */

public class DependentTransformationGroup<T extends Transformation<? super T>> extends TransformationGroup<T> {

  public DependentTransformationGroup(String name) {
    super(name);
  }

  public void applyTranslations(XcodeProg xcodeml, Transformer transformer){
    for(int i = 0; i < _translations.size(); ++i){
      T base = _translations.get(i);
      for(int j = i + 1; j < _translations.size(); ++j){
        T candidate = _translations.get(j);
        if(candidate.isTransformed()){
          continue;
        }
        if(base.canBeTransformedWith(candidate)){
          base.transform(xcodeml, transformer, candidate);
        }
      }
    }
  }

  // In the dependent transformation group, the order in which transformation
  // appears is important
  public void add(T translation){
    int linePosition = translation.getStartLine();
    int insertIndex = 0;
    for(Transformation t : _translations){
      if(t.getStartLine() > linePosition){
        break;
      }
      ++insertIndex;
    }
    _translations.add(insertIndex, translation);
  }
}

Add transformation in the pipeline according to their position


package com.novadart.reactnativenfc;

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.ArrayList;
import java.util.Collections;
import java.util.List;

public class ReactNativeNFCPackage implements ReactPackage {
    @Override
    public List<NativeModule> createNativeModules(ReactApplicationContext reactContext) {
        List<NativeModule> modules = new ArrayList<>(1);
        modules.add(new ReactNativeNFCModule(reactContext));
        return modules;
    }

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

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

package com.novadart.reactnativenfc;

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.ArrayList;
import java.util.Collections;
import java.util.List;

public class ReactNativeNFCPackage implements ReactPackage {
    @Override
    public List<NativeModule> createNativeModules(ReactApplicationContext reactContext) {
        List<NativeModule> modules = new ArrayList<>(1);
        modules.add(new ReactNativeNFCModule(reactContext));
        return modules;
    }

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

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

Handle Android RN 0.47 breaking change


/*
 * Copyright 2014-2015 Hewlett-Packard Development Company, L.P.
 * Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License.
 */

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

import org.springframework.context.annotation.Condition;
import org.springframework.context.annotation.ConditionContext;

public abstract class AbstractPersistentStateCondition implements Condition {

    private static final String DEFAULT_VALUE = "INMEMORY";

    protected PersistentStateConfig getProperty(final ConditionContext context) {
        return PersistentStateConfig.valueOf(context.getEnvironment().getProperty("hp.find.redis", DEFAULT_VALUE));
    }

}

/*
 * Copyright 2014-2015 Hewlett-Packard Development Company, L.P.
 * Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License.
 */

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

import org.springframework.context.annotation.Condition;
import org.springframework.context.annotation.ConditionContext;

public abstract class AbstractPersistentStateCondition implements Condition {

    private static final String DEFAULT_VALUE = "INMEMORY";

    protected PersistentStateConfig getProperty(final ConditionContext context) {
        return PersistentStateConfig.valueOf(context.getEnvironment().getProperty("hp.find.persistentState", DEFAULT_VALUE));
    }

}

Rename property in case it ever becomes more general than Redis


package com.uxxu.konashi.lib;

import info.izumin.android.bletia.BletiaErrorType;

/**
 * Created by izumin on 9/16/15.
 */
public enum KonashiErrorType implements BletiaErrorType{
    INVALID_PARAMETER,
    NOT_ENABLED_UART,
    NOT_ENABLED_I2C;

    @Override
    public int getCode() {
        return -1;
    }

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

package com.uxxu.konashi.lib;

import info.izumin.android.bletia.BletiaErrorType;

/**
 * Created by izumin on 9/16/15.
 */
public enum KonashiErrorType implements BletiaErrorType{
    INVALID_PARAMETER,
    NOT_ENABLED_UART,
    NOT_ENABLED_I2C,
    INVALID_PIN_NUMBER,
    INVALID_MODE,
    INVALID_PULLUP_PARAM,
    INVALID_OUTPUT_PARAM,
    DATA_SIZE_TOO_LONG,
    INVALID_BAUDRATE,
    NO_ERROR;

    @Override
    public int getCode() {
        return -1;
    }

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

Add ErrorType refer to issue


package website.automate.jwebrobot.loader;

import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import website.automate.jwebrobot.AbstractTest;
import website.automate.jwebrobot.ConfigurationProperties;
import website.automate.jwebrobot.exceptions.NonReadableFileException;

import java.util.List;

import static java.util.Arrays.asList;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertThat;

public class PatternScenarioLoaderIT extends AbstractTest {

    @Autowired
    private ScenarioLoader scenarioLoader;

    @Test
    public void loadScenariosFromTheBaseDirectoryRecursively(){
        List<ScenarioFile> scenarioFiles = scenarioLoader.load(asList("./src/test/resources/loader"),
                ConfigurationProperties.DEFAULT_REPORT_PATH);

        assertThat(scenarioFiles.size(), is(3));
    }

    @Test
    public void loadSingleScenarioFromPath(){
        List<ScenarioFile> scenarioFiles = scenarioLoader.load(asList("./src/test/resources/loader/multi.yaml"),
                ConfigurationProperties.DEFAULT_REPORT_PATH);

        assertThat(scenarioFiles.size(), is(1));
    }

    @Test(expected=NonReadableFileException.class)
    public void failLoadingNonExistingFile(){
        scenarioLoader.load(asList("./src/test/resources/loader/non-existent.yaml"),
                ConfigurationProperties.DEFAULT_REPORT_PATH);
    }
}

package website.automate.jwebrobot.loader;

import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import website.automate.jwebrobot.AbstractTest;
import website.automate.jwebrobot.ConfigurationProperties;
import website.automate.jwebrobot.exceptions.NonReadableFileException;

import java.util.List;

import static java.util.Arrays.asList;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertThat;

public class PatternScenarioLoaderIT extends AbstractTest {

    @Autowired
    private ScenarioLoader scenarioLoader;

    @Test
    public void loadScenariosFromTheBaseDirectoryRecursively(){
        List<ScenarioFile> scenarioFiles = scenarioLoader.load(asList("./src/test/resources/loader"),
                ConfigurationProperties.DEFAULT_REPORT_PATH);

        assertThat(scenarioFiles.size(), is(2));
    }

    @Test
    public void loadSingleScenarioFromPath(){
        List<ScenarioFile> scenarioFiles = scenarioLoader.load(asList("./src/test/resources/loader/multi.yaml"),
                ConfigurationProperties.DEFAULT_REPORT_PATH);

        assertThat(scenarioFiles.size(), is(1));
    }

    @Test(expected=NonReadableFileException.class)
    public void failLoadingNonExistingFile(){
        scenarioLoader.load(asList("./src/test/resources/loader/non-existent.yaml"),
                ConfigurationProperties.DEFAULT_REPORT_PATH);
    }
}

Fix pattern scenario loader test


package io.macintosh.scratch.params;

public class MyMath {

	public int sum(int[] vals) {
		int sum = 0;
		for(int val : vals) {
			sum += val;
		}
		return sum;
	}

	public int avg(int[] vals) {
		int sum = sum(vals);
		int avg = sum / vals.length; // simple; no rounding
		return avg;
	}

}

package io.macintosh.scratch.params;

public class MyMath {

	public int sum(int[] vals) {
		int sum = 0;
		for(int val : vals) {
			sum += val;
		}
		return sum;
	}

	public int avg(int[] vals) {
		int avg = 0;
		if(vals.length > 0) {
			avg = sum(vals) / vals.length; // simple; no rounding
		}
		return avg;
	}

}

Add protection for zero-length array.


package sorting;

import java.util.Comparator;

public class StupidSort {
    public static void main(String[] args) {
	Comparator<Integer> ascending = new Comparator<Integer>() {
	    @Override
	    public int compare(Integer foo, Integer bar) {
		return foo - bar;
	    }
	};

	int[] array = {5, 4, 3, 2, 1};
	stupidSort(array, ascending);
	for (int x : array) {
	    System.out.println(x);
	}
    }

    public static void swap(int[] array, int foo, int bar) {
	int temp = array[foo];
	array[foo] = array[bar];
	array[bar] = temp;
    }

    public static void stupidSort(int[] array, Comparator<Integer> comparator) {
	for (int i = 0; i < array.length; i++) {
	    for (int j = i + 1; j < array.length; j++) {
		if (comparator.compare(array[i], array[j]) > 0) {
		    swap(array, i, j);
		}
	    }
	}
    }
}

package sorting;

import java.util.Comparator;

public class StupidSort {
    public static void swap(int[] array, int foo, int bar) {
	int temp = array[foo];
	array[foo] = array[bar];
	array[bar] = temp;
    }

    public static void stupidSort(int[] array, Comparator<Integer> comparator) {
	for (int i = 0; i < array.length; i++) {
	    for (int j = i + 1; j < array.length; j++) {
		if (comparator.compare(array[i], array[j]) > 0) {
		    swap(array, i, j);
		}
	    }
	}
    }
}

Drop main function as we are moving to Junit.


/*
 * Copyright 2015 Anton Tananaev (anton.tananaev@gmail.com)
 *
 * 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.traccar.api;

import javax.ws.rs.core.SecurityContext;

public class BaseResource {

    @javax.ws.rs.core.Context
    private SecurityContext securityContext;

    protected long getUserId() {
        UserPrincipal principal = (UserPrincipal) securityContext.getUserPrincipal();
        if (principal != null) {
            return principal.getUserId();
        }
        return 0;
    }

}

/*
 * Copyright 2015 - 2016 Anton Tananaev (anton.tananaev@gmail.com)
 *
 * 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.traccar.api;

import javax.annotation.security.PermitAll;
import javax.ws.rs.OPTIONS;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.SecurityContext;

public class BaseResource {

    @javax.ws.rs.core.Context
    private SecurityContext securityContext;

    protected long getUserId() {
        UserPrincipal principal = (UserPrincipal) securityContext.getUserPrincipal();
        if (principal != null) {
            return principal.getUserId();
        }
        return 0;
    }

    @PermitAll
    @OPTIONS
    public Response options() {
        return Response.noContent().build();
    }

}

Implement OPTIONS verb API handler


/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.parallax.server.common.cloudsession.service.impl;

import com.google.inject.Inject;
import com.parallax.server.common.cloudsession.db.dao.UserDao;
import com.parallax.server.common.cloudsession.service.DatabaseMaintenanceService;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;

/**
 *
 * @author Michel
 */
public class DatabaseMaintenanceServiceImpl implements DatabaseMaintenanceService, Runnable {

    private ScheduledExecutorService service;

    private UserDao userDao;

    @Inject
    public void setUserDao(UserDao userDao) {
        this.userDao = userDao;
        setup();
    }

    public void setup() {
        this.service = Executors.newSingleThreadScheduledExecutor(new ThreadFactory() {
            public Thread newThread(Runnable r) {
                Thread thread = new Thread(r);
                thread.setDaemon(true);
                return thread;
            }
        });
        this.service.scheduleAtFixedRate(this, 5, 5, TimeUnit.MINUTES);
    }

    @Override
    public void run() {
        userDao.count();
    }

}

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.parallax.server.common.cloudsession.service.impl;

import com.google.inject.Inject;
import com.parallax.server.common.cloudsession.db.dao.UserDao;
import com.parallax.server.common.cloudsession.service.DatabaseMaintenanceService;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 *
 * @author Michel
 */
public class DatabaseMaintenanceServiceImpl implements DatabaseMaintenanceService, Runnable {

    private Logger log = LoggerFactory.getLogger(DatabaseMaintenanceServiceImpl.class);

    private ScheduledExecutorService service;

    private UserDao userDao;

    @Inject
    public void setUserDao(UserDao userDao) {
        this.userDao = userDao;
        setup();
    }

    public void setup() {
        this.service = Executors.newSingleThreadScheduledExecutor(new ThreadFactory() {
            public Thread newThread(Runnable r) {
                Thread thread = new Thread(r);
                thread.setDaemon(true);
                return thread;
            }
        });
        this.service.scheduleAtFixedRate(this, 5, 5, TimeUnit.MINUTES);
    }

    @Override
    public void run() {
        log.info("Keep db active: {}", userDao.count());
    }

}

Fix sleeping database connection bug


package uk.org.sappho.code.change.management.data;

import net.sf.oval.constraint.NotEmpty;
import net.sf.oval.constraint.NotNull;

public class ChangedFile {

    @NotNull
    @NotEmpty
    private final String filename;
    @NotNull
    @NotEmpty
    private final Boolean isCreate;

    public ChangedFile(String filename, Boolean isCreate) {

        this.filename = filename;
        this.isCreate = isCreate;
    }

    public String getFilename() {

        return filename;
    }

    public boolean isCreate() {

        return isCreate;
    }
}

package uk.org.sappho.code.change.management.data;

import net.sf.oval.constraint.NotEmpty;
import net.sf.oval.constraint.NotNull;

public class ChangedFile {

    @NotNull
    @NotEmpty
    private String filename;
    @NotNull
    @NotEmpty
    private Boolean isCreate;

    public ChangedFile() {
    }

    public ChangedFile(String filename, Boolean isCreate) {

        this.filename = filename;
        this.isCreate = isCreate;
    }

    public String getFilename() {

        return filename;
    }

    public boolean isCreate() {

        return isCreate;
    }
}

Add no-params constructor to fix data file read issue.


/*
 * The Alluxio Open Foundation licenses this work under the Apache License, version 2.0
 * (the "License"). You may not use this work except in compliance with the License, which is
 * available at www.apache.org/licenses/LICENSE-2.0
 *
 * This software is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
 * either express or implied, as more fully set forth in the License.
 *
 * See the NOTICE file distributed with this work for information regarding copyright ownership.
 */

package alluxio.underfs.cosn;

import alluxio.Constants;
import alluxio.underfs.hdfs.HdfsUnderFileSystemFactory;
import alluxio.underfs.UnderFileSystemConfiguration;

import javax.annotation.concurrent.ThreadSafe;

/**
 * Factory for creating {@link HdfsUnderFileSystem}.
 *
 * It caches created {@link HdfsUnderFileSystem}s, using the scheme and authority pair as the key.
 */
@ThreadSafe
public class CosNUnderFileSystemFactory extends HdfsUnderFileSystemFactory {

  @Override
  public boolean supportsPath(String path) {
    return path != null && path.startsWith(Constants.HEADER_COSN);
  }

  @Override
  public boolean supportsPath(String path, UnderFileSystemConfiguration conf) {
    return supportsPath(path);
  }
}

/*
 * The Alluxio Open Foundation licenses this work under the Apache License, version 2.0
 * (the "License"). You may not use this work except in compliance with the License, which is
 * available at www.apache.org/licenses/LICENSE-2.0
 *
 * This software is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
 * either express or implied, as more fully set forth in the License.
 *
 * See the NOTICE file distributed with this work for information regarding copyright ownership.
 */

package alluxio.underfs.cosn;

import alluxio.Constants;
import alluxio.underfs.hdfs.HdfsUnderFileSystem;
import alluxio.underfs.hdfs.HdfsUnderFileSystemFactory;
import alluxio.underfs.UnderFileSystemConfiguration;

import javax.annotation.concurrent.ThreadSafe;

/**
 * Factory for creating {@link HdfsUnderFileSystem}.
 *
 * It caches created {@link HdfsUnderFileSystem}s, using the scheme and authority pair as the key.
 */
@ThreadSafe
public class CosNUnderFileSystemFactory extends HdfsUnderFileSystemFactory {

  @Override
  public boolean supportsPath(String path) {
    return path != null && path.startsWith(Constants.HEADER_COSN);
  }

  @Override
  public boolean supportsPath(String path, UnderFileSystemConfiguration conf) {
    return supportsPath(path);
  }
}

Add import statement to make link in Java doc workable


import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;

public class Logger {
	private String filename;

	Logger(String filename) {
		this.filename = filename;
	}

	public void append(String line) {
		try(PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(filename, true)))) {
		    out.println(line);
		}
		catch (IOException e) {
			// fail
		}
	}
}

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;

public class Logger {
	private PrintWriter out;

	Logger(String filename) {
		try {
			out = new PrintWriter(new BufferedWriter(new FileWriter(filename, true)));
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public void append(String line) {
		out.println(line);
		out.flush();
	}
}

Fix logger for java 1.6


package de.fau.amos.virtualledger.server.auth;

import org.keycloak.KeycloakPrincipal;
import org.keycloak.KeycloakSecurityContext;
import org.keycloak.representations.AccessToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;

@Component
public class KeycloakUtilizer {

    /**
     * extracts the email adress from the keycloak context.
     * returns null if not successful.
     */
    public String getEmail() {
        return getAccessToken().getEmail();
    }

    /**
     * extracts the first name from the keycloak context.
     * returns null if not successful.
     */
    public String getFirstName() {
        return getAccessToken().getGivenName();
    }

    /**
     * extracts the last name from the keycloak context.
     * returns null if not successful.
     */
    public String getLastName() {
        return getAccessToken().getFamilyName();
    }

    private AccessToken getAccessToken() {
        return getKeycloakSecurityContext().getToken();
    }

    public String getTokenString() {
        return getKeycloakSecurityContext().getTokenString();
    }

    private KeycloakSecurityContext getKeycloakSecurityContext() {
        try {
            //noinspection unchecked
            return ((KeycloakPrincipal<KeycloakSecurityContext>) SecurityContextHolder.getContext().getAuthentication().getPrincipal()).getKeycloakSecurityContext();
        } catch (final Exception e) {
            throw new KeycloakException("Failure at getting data about the user by the identity token!");
        }
    }
}

package de.fau.amos.virtualledger.server.auth;

import org.keycloak.KeycloakPrincipal;
import org.keycloak.KeycloakSecurityContext;
import org.keycloak.representations.AccessToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;

@Component
public class KeycloakUtilizer {

    /**
     * extracts the email adress from the keycloak context.
     * returns null if not successful.
     */
    public String getEmail() {
        return getAccessToken().getEmail();
    }

    /**
     * extracts the first name from the keycloak context.
     * returns null if not successful.
     */
    public String getFirstName() {
        return getAccessToken().getGivenName();
    }

    /**
     * extracts the last name from the keycloak context.
     * returns null if not successful.
     */
    public String getLastName() {
        return getAccessToken().getFamilyName();
    }

    private AccessToken getAccessToken() {
        return getKeycloakSecurityContext().getToken();
    }

    public String getAuthorizationHeader() {
        return "Bearer: " + getTokenString();
    }

    public String getTokenString() {
        return getKeycloakSecurityContext().getTokenString();
    }

    private KeycloakSecurityContext getKeycloakSecurityContext() {
        try {
            //noinspection unchecked
            return ((KeycloakPrincipal<KeycloakSecurityContext>) SecurityContextHolder.getContext().getAuthentication().getPrincipal()).getKeycloakSecurityContext();
        } catch (final Exception e) {
            throw new KeycloakException("Failure at getting data about the user by the identity token!");
        }
    }
}

Add method to get complete Authorization Header for adorsys


// vim:shiftwidth=4:tabstop=4:expandtab

import sun.security.krb5.PrincipalName;
import sun.security.krb5.internal.ccache.FileCredentialsCache;

public class kwho {
    public static void main(String[] args) {

        String cache = System.getenv("KRB5CCNAME");
        if (cache == null) {
            return;
        }

        // The FileCredentialsCache does not want to see the "FILE:" prefix
        cache = cache.replaceAll("^FILE:", cache);

        //assumes credendials cache of type "FILE:"
        FileCredentialsCache fcc = FileCredentialsCache.acquireInstance(null, cache);
        if (fcc == null) {
            return;
        }
        PrincipalName princ = fcc.getPrimaryPrincipal();
        String[] nameStrings = princ.getNameStrings();
        StringBuffer temp = new StringBuffer(nameStrings[0]);
        for (int i=1; i<nameStrings.length; i++) {
            temp.append("/");
            temp.append(nameStrings[i]);
        }
        System.out.println(temp);
    }
}

// vim:shiftwidth=4:tabstop=4:expandtab

import sun.security.krb5.PrincipalName;
import sun.security.krb5.internal.ccache.FileCredentialsCache;

public class kwho {
    public static void main(String[] args) {

        String cache = System.getenv("KRB5CCNAME");
        if (cache == null) {
            return;
        }

        // The FileCredentialsCache does not want to see the "FILE:" prefix
        cache = cache.replaceAll("^FILE:", "");

        //assumes credendials cache of type "FILE:"
        FileCredentialsCache fcc = FileCredentialsCache.acquireInstance(null, cache);
        if (fcc == null) {
            return;
        }
        PrincipalName princ = fcc.getPrimaryPrincipal();
        String[] nameStrings = princ.getNameStrings();
        StringBuffer temp = new StringBuffer(nameStrings[0]);
        for (int i=1; i<nameStrings.length; i++) {
            temp.append("/");
            temp.append(nameStrings[i]);
        }
        System.out.println(temp);
    }
}

Fix bug removing FILE: from ccache name.


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

package com.netflix.spinnaker.orca.pipeline.expressions.whitelisting;

import java.text.SimpleDateFormat;
import java.time.Instant;
import java.time.LocalDate;
import java.time.temporal.ChronoUnit;
import java.util.*;

public interface InstantiationTypeRestrictor {
  Set<Class<?>> allowedTypes =
      Collections.unmodifiableSet(
          new HashSet<>(
              Arrays.asList(
                  String.class,
                  Date.class,
                  Integer.class,
                  Long.class,
                  Double.class,
                  Byte.class,
                  SimpleDateFormat.class,
                  Math.class,
                  Random.class,
                  UUID.class,
                  Boolean.class,
                  LocalDate.class,
                  Instant.class,
                  ChronoUnit.class)));

  static boolean supports(Class<?> type) {
    return allowedTypes.contains(type);
  }
}

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

package com.netflix.spinnaker.orca.pipeline.expressions.whitelisting;

import java.text.SimpleDateFormat;
import java.time.DayOfWeek;
import java.time.Instant;
import java.time.LocalDate;
import java.time.temporal.ChronoUnit;
import java.util.*;

public interface InstantiationTypeRestrictor {
  Set<Class<?>> allowedTypes =
      Collections.unmodifiableSet(
          new HashSet<>(
              Arrays.asList(
                  String.class,
                  Date.class,
                  Integer.class,
                  Long.class,
                  Double.class,
                  Byte.class,
                  SimpleDateFormat.class,
                  Math.class,
                  Random.class,
                  UUID.class,
                  Boolean.class,
                  LocalDate.class,
                  DayOfWeek.class,
                  Instant.class,
                  ChronoUnit.class)));

  static boolean supports(Class<?> type) {
    return allowedTypes.contains(type);
  }
}

Whitelist `DayOfWeek` enum for expressions


package uk.co.littlemike.jextend.impl.jdk;

import org.junit.Test;

public class MethodLookupTest {

    private void privateMethod() {
    }

    @Test(expected = MethodLookupException.class)
    public void throwsExceptionWhenAttemptingToLookupPrivateMethod() throws Exception {
        MethodLookup lookup = new MethodLookup(Object.class);

        lookup.lookup(MethodLookupTest.class.getDeclaredMethod("privateMethod"));
    }
}

package uk.co.littlemike.jextend.impl.jdk;

import org.junit.Test;

public class MethodLookupTest {

    private void privateMethod() {
    }

    @Test(expected = MethodLookupException.class)
    public void throwsExceptionWhenAttemptingToLookupPrivateMethodOnDifferentClass() throws Exception {
        MethodLookup lookup = new MethodLookup(Object.class);

        lookup.lookup(MethodLookupTest.class.getDeclaredMethod("privateMethod"));
    }

    @Test(expected = MethodLookupException.class)
    public void throwsExceptionWhenAttemptingToLookupPrivateMethodOnDifferentClass_EvenIfPrivileged() throws Exception {
        PrivilegedMethodLookup lookup = new PrivilegedMethodLookup(Object.class);

        lookup.lookupDefault(MethodLookupTest.class.getDeclaredMethod("privateMethod"));
    }
}

Add test for privileged private method lookup failure


package edu.berkeley.eecs.emission.cordova.launchnative;

import org.apache.cordova.*;
import org.json.JSONArray;
import org.json.JSONException;
import android.content.Intent;

public class LaunchNative extends CordovaPlugin {

    @Override
    public boolean execute(String action, JSONArray data, CallbackContext callbackContext) throws JSONException {
        if (action.equals("launch")) {
            java.lang.Package pkg = cordova.getClass().getPackage();
            System.out.println("cordova has package name "+pkg);
            String activityName = data.getString(0);
            String fqcn = pkg.getName()+"."+activityName;
            System.out.println("FQCN = "+pkg.getName() + fqcn);
            try {
                Class fqClass = Class.forName(fqcn);
                Intent startIntent = new Intent(cordova.getActivity(), fqClass);
                cordova.getActivity().startActivity(startIntent);
                callbackContext.success("Launched activity " + activityName);
            } catch (ClassNotFoundException e) {
                callbackContext.error("Class "+fqcn+" not found, unable to launch");
            }
            return true;
        } else {
            return false;
        }
    }
}

package edu.berkeley.eecs.emission.cordova.launchnative;

import org.apache.cordova.*;
import org.json.JSONArray;
import org.json.JSONException;
import android.content.Intent;

public class LaunchNative extends CordovaPlugin {

    @Override
    public boolean execute(String action, JSONArray data, CallbackContext callbackContext) throws JSONException {
        if (action.equals("launch")) {
            String pkgName = cordova.getActivity().getPackageName();
            System.out.println("cordova has package name "+pkgName);
            String activityName = data.getString(0);
            String fqcn = pkgName+"."+activityName;
            System.out.println("FQCN = "+ fqcn);
            try {
                Class fqClass = Class.forName(fqcn);
                Intent startIntent = new Intent(cordova.getActivity(), fqClass);
                cordova.getActivity().startActivity(startIntent);
                callbackContext.success("Launched activity " + activityName);
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
                callbackContext.error("Class "+fqcn+" not found, unable to launch");
            }
            return true;
        } else {
            return false;
        }
    }
}

Read the correct package name


package com.brysonm.uconomy;

import org.apache.commons.lang.StringUtils;
import org.bukkit.Material;

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

public class ItemUtils {

    public static String toFriendlyName(Material material) {

        String materialName = material.name().toLowerCase();

        if(!materialName.contains("_")) {

            return StringUtils.capitalize(materialName);

        }

        List<String> words = new ArrayList<String>();

        for(String word : materialName.split("_")) {

            StringUtils.capitalize(word);

        }

        return StringUtils.join(words, " ");

    }

}

package com.brysonm.uconomy;

import org.apache.commons.lang.StringUtils;
import org.bukkit.Material;

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

public class ItemUtils {

    public static String toFriendlyName(Material material) {

        String materialName = material.name().toLowerCase();

        if(!materialName.contains("_")) {

            return StringUtils.capitalize(materialName);

        }

        List<String> words = new ArrayList<String>();

        for(String word : materialName.split("_")) {

            StringUtils.capitalize(word);
            words.add(word);

        }

        return StringUtils.join(words, " ");

    }

}

Fix name with '_' in them being blank.


package com.alexrnl.jbetaseries;

import java.util.logging.Logger;

/**
 * Entry point of the interface to the BetaSeries API.<br />
 * @author Alex
 */
public class JBetaSeries {
	/** Logger */
	private static Logger	lg	= Logger.getLogger(JBetaSeries.class.getName());

	/** The key to use for the API */
	private String key;
	/** The preferred data type format */
	private Format preferredFormat;
	/** The token for the user */
	private String token;
}

package com.alexrnl.jbetaseries;

import java.util.logging.Logger;

/**
 * Entry point of the interface to the BetaSeries API.

 * @author Alex
 */
public final class JBetaSeries {
	/** Logger */
	private static Logger	lg	= Logger.getLogger(JBetaSeries.class.getName());

	/** The key to use for the API */
	private final String	key;
	/** The preferred data type format */
	private final Format	format;
	/** The token for the user, null if no user is logged. */
	private final String	token;

	/**
	 * Constructor #1.

	 * This will use the {@link Format#XML XML} format of the API.
	 * @param key
	 *        the API key to use.
	 */
	public JBetaSeries (final String key) {
		this(key, Format.XML);
	}

	/**
	 * Constructor #2.

	 * @param key
	 *        the API key to use.
	 * @param format
	 *        the data type required for the API.
	 */
	public JBetaSeries (final String key, final Format format) {
		super();
		this.key = key;
		this.format = format;
		this.token = null;
	}

}

Add constructors to main class


import java.util.Arrays;

public class ConvertArray {

	public int getOriginalIndex(int currentIndex, int length) {
		return (currentIndex % 3) * length + currentIndex/3;
	}

	public int[] convert(int[] input) {
		for (int i = 0; i < input.length; ++i) {
			int originalIndex = getOriginalIndex(i, input.length/3);
			while (originalIndex < i) {
				originalIndex = getOriginalIndex(originalIndex, input.length/3);
			}
			int temp = input[i];
			input[i] = input[originalIndex];
			input[originalIndex] = temp;
		}
		return input;
	}

	public static void main(String[] args) {
		ConvertArray c = new ConvertArray();
		int[] test1 = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
		System.out.println(Arrays.toString(c.convert(test1)));

	}
}

import java.util.Arrays;

public class ConvertArray {

	public int getOriginalIndex(int currentIndex, int length) {
		return (currentIndex % 3) * length + currentIndex/3;
	}

	public int[] convert(int[] input) {
	  // When array size is less than 3, returns an error.
	  if (input.length % 3 != 0 ) {
			System.out.println("Error! Array cannot be divided into three equal parts");
			return;
		}
		for (int i = 0; i < input.length; ++i) {
			int originalIndex = getOriginalIndex(i, input.length/3);
			while (originalIndex < i) {
				originalIndex = getOriginalIndex(originalIndex, input.length/3);
			}
			int temp = input[i];
			input[i] = input[originalIndex];
			input[originalIndex] = temp;
		}
		return input;
	}

	public static void main(String[] args) {
		ConvertArray c = new ConvertArray();
		int[] test1 = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
		System.out.println(Arrays.toString(c.convert(test1)));

	}
}

Update to handle an edge case


/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package jxfdl.utils;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.zip.GZIPInputStream;
import sun.misc.BASE64Decoder;

/**
 *
 * @author unamanic
 */
public class Base64GZip {

  public static InputStream B64GzipToInputStream(InputStream is) {
    ByteArrayInputStream decoded = null;
    try {
      BASE64Decoder b64 = new BASE64Decoder();
      decoded = new ByteArrayInputStream(b64.decodeBuffer(is));
      GZIPInputStream gzip = new GZIPInputStream(decoded);
      return gzip;
    } catch (IOException ex) {
      Logger.getLogger(Base64GZip.class.getName()).log(Level.SEVERE, null, ex);
    }
    return null;
  }

}

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package jxfdl.utils;

import java.io.IOException;
import java.io.InputStream;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.zip.GZIPInputStream;
import org.apache.commons.codec.binary.Base64InputStream;

/**
 *
 * @author unamanic
 */
public class Base64GZip {

  public static InputStream B64GzipToInputStream(InputStream is) {
    try {
      //BASE64Decoder b64 = new BASE64Decoder();
      //decoded = new ByteArrayInputStream(b64.decodeBuffer(is));

      InputStream decoded = new Base64InputStream(is);

      InputStream gzip = new GZIPInputStream(decoded);
      return gzip;
    } catch (IOException ex) {
      Logger.getLogger(Base64GZip.class.getName()).log(Level.SEVERE, null, ex);
    }
    return null;
  }

}

Use Apache Commons Base64 library instead of sun.misc.BASE64


package water.fvec;

import java.io.File;

import org.apache.hadoop.fs.FileStatus;

import water.*;
import water.persist.PersistHdfs;
import water.persist.PersistNFS;

// A distributed file-backed Vector
//
public class NFSFileVec extends FileVec {

  // Make a new NFSFileVec key which holds the filename implicitly.
  // This name is used by the DVecs to load data on-demand.
  public static Key make(File f) {
    Futures fs = new Futures();
    Key key = make(f, fs);
    fs.blockForPending();
    return key;
  }

  public static Key make(File f, Futures fs) {
    long size = f.length();
    Key k = Vec.newKey(PersistNFS.decodeFile(f));
    // Insert the top-level FileVec key into the store
    DKV.put(k,new NFSFileVec(k,size), fs);
    return k;
  }

  public static Key make(FileStatus f, Futures fs) {
    long size = f.getLen();
    Key k = Vec.newKey(Key.make(f.getPath().toString()));
    // Insert the top-level FileVec key into the store
    DKV.put(k,new NFSFileVec(k,size), fs);
    return k;
  }

  private NFSFileVec(Key key, long len) {super(key,len,Value.NFS);}
}

package water.fvec;

import java.io.File;

import water.*;
import water.persist.PersistNFS;

// A distributed file-backed Vector
//
public class NFSFileVec extends FileVec {

  // Make a new NFSFileVec key which holds the filename implicitly.
  // This name is used by the DVecs to load data on-demand.
  public static Key make(File f) {
    Futures fs = new Futures();
    Key key = make(f, fs);
    fs.blockForPending();
    return key;
  }

  public static Key make(File f, Futures fs) {
    long size = f.length();
    Key k = Vec.newKey(PersistNFS.decodeFile(f));
    // Insert the top-level FileVec key into the store
    DKV.put(k,new NFSFileVec(k,size), fs);
    return k;
  }

  private NFSFileVec(Key key, long len) {super(key,len,Value.NFS);}
}

Remove unused Key.make for Hadoop FileStatus.


package Entities;

import org.jsfml.graphics.Sprite;

/**
 * Created by steven on 10/10/14.
 */
public abstract class GameBaseEntity extends Sprite{

    // Angle of the entity relative to origin
    private int angle;
    // Radius of the entity relative to origin
    private int radius;

    public GameBaseEntity() {
        this.setPosition(0,0);
        this.angle = 0;
        this.radius = 0;
    }
}

package Entities;

import org.jsfml.graphics.Sprite;

/**
 * Created by steven on 10/10/14.
 */
public abstract class GameBaseEntity extends Sprite{

    // Angle of the entity relative to origin
    private int angle;
    // Radius of the entity relative to origin
    private int radius;
    // Allow to know if the entity is alive or not
    private boolean isAlive;
    // Allow to know if the entity is displayable or not
    private boolean isVisible;

    /**
     * Default constructor of the GameBaseEntity
     */
    public GameBaseEntity() {
        super();
        this.setPosition(0,0);
        this.angle = 0;
        this.radius = 0;
        this.isAlive = true;
        this.isVisible = false;
    }

    //  Accessors   //
    public int getRadius() {
        return radius;
    }

    public void setRadius(int radius) {
        this.radius = radius;
    }

    public int getAngle() {

        return angle;
    }

    public void setAngle(int angle) {
        this.angle = angle;
    }

    public boolean isAlive() {
        return isAlive;
    }

    public void setAlive(boolean isAlive) {
        this.isAlive = isAlive;
    }

    public boolean isVisible() {
        return isVisible;
    }

    public void setVisible(boolean isVisible) {
        this.isVisible = isVisible;
    }
}

Add isVisible and isAlive attributs with getters and setters.


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

import com.fasterxml.jackson.databind.ObjectMapper;
import com.hp.autonomy.frontend.configuration.AbstractAuthenticatingConfigFileService;
import com.hp.autonomy.frontend.configuration.Authentication;

public class FindConfigFileService extends AbstractAuthenticatingConfigFileService<FindConfig> {

    @Override
    protected void addPreReadMixins(final ObjectMapper mapper) {
        mapper.addMixInAnnotations(Authentication.class, AuthenticationMixins.class);
    }

    @Override
    public FindConfig preUpdate(final FindConfig config) {
        return config;
    }

    @Override
    public void postUpdate(final FindConfig config) throws Exception {

    }

    @Override
    public void postInitialise(final FindConfig config) throws Exception {
        postUpdate(config);
    }

    @Override
    public Class<FindConfig> getConfigClass() {
        return FindConfig.class;
    }

    @Override
    public FindConfig getEmptyConfig() {
        return new FindConfig.Builder().build();
    }

}

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

import com.hp.autonomy.frontend.configuration.AbstractAuthenticatingConfigFileService;

public class FindConfigFileService extends AbstractAuthenticatingConfigFileService<FindConfig> {

    @Override
    public FindConfig preUpdate(final FindConfig config) {
        return config;
    }

    @Override
    public void postUpdate(final FindConfig config) throws Exception {

    }

    @Override
    public void postInitialise(final FindConfig config) throws Exception {
        postUpdate(config);
    }

    @Override
    public Class<FindConfig> getConfigClass() {
        return FindConfig.class;
    }

    @Override
    public FindConfig getEmptyConfig() {
        return new FindConfig.Builder().build();
    }

}

Remove method which went away.


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

import org.jetbrains.annotations.NotNull;

/**
 * @author Vitaliy.Bibaev
 */
public interface GenericType {
  @NotNull
  String getVariableTypeName();

  @NotNull
  String getGenericTypeName();

  GenericType BOOLEAN = new GenericTypeImpl("boolean", "java.lang.Boolean");
  GenericType INT = new GenericTypeImpl("int", "java.lang.Integer");
  GenericType DOUBLE = new GenericTypeImpl("double", "java.lang.Double");
  GenericType LONG = new GenericTypeImpl("long", "java.lang.Long");
  GenericType OBJECT = new ClassTypeImpl("java.lang.Object");
  GenericType VOID = new GenericTypeImpl("void", "java.lang.Void");
}

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

import com.intellij.psi.CommonClassNames;
import org.jetbrains.annotations.NotNull;

/**
 * @author Vitaliy.Bibaev
 */
public interface GenericType {
  @NotNull
  String getVariableTypeName();

  @NotNull
  String getGenericTypeName();

  GenericType BOOLEAN = new GenericTypeImpl("boolean", "java.lang.Boolean");
  GenericType INT = new GenericTypeImpl("int", "java.lang.Integer");
  GenericType DOUBLE = new GenericTypeImpl("double", "java.lang.Double");
  GenericType LONG = new GenericTypeImpl("long", "java.lang.Long");
  GenericType OBJECT = new ClassTypeImpl("java.lang.Object");
  GenericType VOID = new GenericTypeImpl("void", "java.lang.Void");

  GenericType OPTIONAL = new ClassTypeImpl(CommonClassNames.JAVA_UTIL_OPTIONAL);
  GenericType OPTIONAL_INT = new ClassTypeImpl("java.lang.OptionalInt");
  GenericType OPTIONAL_LONG = new ClassTypeImpl("java.lang.OptionalLong");
  GenericType OPTIONAL_DOUBLE = new ClassTypeImpl("java.lang.OptionalDouble");
}

Add generic types for an optional


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

import com.yahoo.config.model.deploy.DeployState;
import com.yahoo.config.model.producer.AbstractConfigProducer;
import com.yahoo.container.handler.ThreadpoolConfig;
import com.yahoo.vespa.model.container.ContainerCluster;
import com.yahoo.vespa.model.container.component.Handler;

/**
 * @author hmusum
 */
public class LogserverContainerCluster extends ContainerCluster<LogserverContainer> implements ThreadpoolConfig.Producer {

    public LogserverContainerCluster(AbstractConfigProducer<?> parent, String name, DeployState deployState) {
        super(parent, name, name, deployState);

        addDefaultHandlersWithVip();
        addLogHandler();
    }

    @Override
    protected void doPrepare(DeployState deployState) { }

    @Override
    public void getConfig(ThreadpoolConfig.Builder builder) {
        builder.maxthreads(10);
    }

    protected boolean messageBusEnabled() { return false; }

    private void addLogHandler() {
        Handler<?> logHandler = Handler.fromClassName(ContainerCluster.LOG_HANDLER_CLASS);
        logHandler.addServerBindings("http://*/logs");
        addComponent(logHandler);
    }

}

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

import com.yahoo.config.model.deploy.DeployState;
import com.yahoo.config.model.producer.AbstractConfigProducer;
import com.yahoo.container.handler.ThreadpoolConfig;
import com.yahoo.search.config.QrStartConfig;
import com.yahoo.vespa.model.container.ContainerCluster;
import com.yahoo.vespa.model.container.component.Handler;

import java.util.Objects;

/**
 * @author hmusum
 */
public class LogserverContainerCluster extends ContainerCluster<LogserverContainer> implements ThreadpoolConfig.Producer {

    public LogserverContainerCluster(AbstractConfigProducer<?> parent, String name, DeployState deployState) {
        super(parent, name, name, deployState);

        addDefaultHandlersWithVip();
        addLogHandler();
    }

    @Override
    protected void doPrepare(DeployState deployState) { }

    @Override
    public void getConfig(ThreadpoolConfig.Builder builder) {
        builder.maxthreads(10);
    }

    @Override
    public void getConfig(QrStartConfig.Builder builder) {
        super.getConfig(builder);
        builder.jvm.heapsize(384);
    }

    protected boolean messageBusEnabled() { return false; }

    private void addLogHandler() {
        Handler<?> logHandler = Handler.fromClassName(ContainerCluster.LOG_HANDLER_CLASS);
        logHandler.addServerBindings("http://*/logs");
        addComponent(logHandler);
    }

}

Reduce max heap from 512m to 384m


package org.xcolab.view.pages.members.users.utils;

import org.xcolab.client.members.pojo.Member;
import org.xcolab.view.util.CsvResponseWriter;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.function.Function;

import javax.servlet.http.HttpServletResponse;

public class MemberListCsvWriter extends CsvResponseWriter {

    private static final List<String> COLUMN_NAMES = Arrays.asList("Screen name", "First name",
            "Last name", "Email address", "Country");
    private static final Function<Member, List<String>> COLUMN_EXTRACTION_FUNCTION
            = (member -> Arrays.asList(
                    member.getScreenName(),
                    member.getFirstName(),
                    member.getLastName(),
                    member.getEmailAddress(),
                    member.getCountry()
            ));

    public MemberListCsvWriter(HttpServletResponse response) throws IOException {
        super("membersList", COLUMN_NAMES, response);
    }

    public void writeMembers(List<Member> members) {
        members.stream()
                .map(COLUMN_EXTRACTION_FUNCTION)
                .forEach(this::writeRow);
    }
}

package org.xcolab.view.pages.members.users.utils;

import org.xcolab.client.members.pojo.Member;
import org.xcolab.view.util.CsvResponseWriter;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.function.Function;

import javax.servlet.http.HttpServletResponse;

public class MemberListCsvWriter extends CsvResponseWriter {

    private static final List<String> COLUMN_NAMES = Arrays.asList("Screen name", "First name",
            "Last name", "Email address", "Country", "Bio");
    private static final Function<Member, List<String>> COLUMN_EXTRACTION_FUNCTION
            = (member -> Arrays.asList(
                    member.getScreenName(),
                    member.getFirstName(),
                    member.getLastName(),
                    member.getEmailAddress(),
                    member.getCountry(),
                    member.getShortBio()
            ));

    public MemberListCsvWriter(HttpServletResponse response) throws IOException {
        super("membersList", COLUMN_NAMES, response);
    }

    public void writeMembers(List<Member> members) {
        members.stream()
                .map(COLUMN_EXTRACTION_FUNCTION)
                .forEach(this::writeRow);
    }
}

Add bio to member CSV export


/*
 * Copyright (C) 2013 ickStream GmbH
 * All rights reserved
 */

package com.ickstream.protocol.service.core;

public class ServiceResponse {
    private String id;
    private String name;
    private String type;
    private String url;

    public String getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

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

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }
}

/*
 * Copyright (C) 2013 ickStream GmbH
 * All rights reserved
 */

package com.ickstream.protocol.service.core;

public class ServiceResponse {
    private String id;
    private String name;
    private String type;
    private String url;
    private String addServiceUrl;

    public String getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

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

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    public String getAddServiceUrl() {
        return addServiceUrl;
    }

    public void setAddServiceUrl(String addServiceUrl) {
        this.addServiceUrl = addServiceUrl;
    }
}

Add addServiceUrl attribute to result from findServices and findAllServices