package seedu.address.logic.commands;

import seedu.address.commons.core.Messages;
import seedu.address.commons.core.UnmodifiableObservableList;
import seedu.address.model.person.ReadOnlyPerson;
import seedu.address.model.person.UniquePersonList.PersonNotFoundException;

/**
 * Deletes a person identified using it's last displayed index from the address book.
 */
public class DeleteCommand extends Command {

    public static final String COMMAND_WORD = "delete";

    public static final String MESSAGE_USAGE = COMMAND_WORD
            + ": Deletes the person identified by the index number used in the last person listing.\n"
            + "Parameters: INDEX (must be a positive integer)\n"
            + "Example: " + COMMAND_WORD + " 1";

    public static final String MESSAGE_DELETE_PERSON_SUCCESS = "Deleted Person: %1$s";

    public final int targetIndex;

    public DeleteCommand(int targetIndex) {
        this.targetIndex = targetIndex;
    }

    @Override
    public CommandResult execute() {

        UnmodifiableObservableList<ReadOnlyPerson> lastShownList = model.getFilteredPersonList();

        if (lastShownList.size() < targetIndex) {
            indicateAttemptToExecuteIncorrectCommand();
            return new CommandResult(Messages.MESSAGE_INVALID_PERSON_DISPLAYED_INDEX);
        }

        ReadOnlyPerson personToDelete = lastShownList.get(targetIndex - 1);

        try {
            model.deletePerson(personToDelete);
        } catch (PersonNotFoundException pnfe) {
            assert false : "The target person cannot be missing";
        }

        return new CommandResult(String.format(MESSAGE_DELETE_PERSON_SUCCESS, personToDelete));
    }

}

package seedu.address.logic.commands;

import seedu.address.commons.core.Messages;
import seedu.address.commons.core.UnmodifiableObservableList;
import seedu.address.model.person.ReadOnlyPerson;
import seedu.address.model.person.UniquePersonList.TaskNotFoundException;

/**
 * Deletes a task identified using it's last displayed index from the task manager.
 */
public class DeleteCommand extends Command {

    public static final String COMMAND_WORD = "delete";

    public static final String MESSAGE_USAGE = COMMAND_WORD
            + ": Deletes the task identified by the index number used in the last task listing.\n"
            + "Parameters: INDEX (must be a positive integer)\n"
            + "Example: " + COMMAND_WORD + " 1";

    public static final String MESSAGE_DELETE_TASK_SUCCESS = "Deleted Task: %1$s";

    public final int targetIndex;

    public DeleteCommand(int targetIndex) {
        this.targetIndex = targetIndex;
    }

    @Override
    public CommandResult execute() {

        UnmodifiableObservableList<ReadOnlyPerson> lastShownList = model.getFilteredPersonList();

        if (lastShownList.size() < targetIndex) {
            indicateAttemptToExecuteIncorrectCommand();
            return new CommandResult(Messages.MESSAGE_INVALID_TASK_DISPLAYED_INDEX);
        }

        ReadOnlyPerson taskToDelete = lastShownList.get(targetIndex - 1);

        try {
            model.deleteTask(taskToDelete);
        } catch (TaskNotFoundException pnfe) {
            assert false : "The target task cannot be missing";
        }

        return new CommandResult(String.format(MESSAGE_DELETE_TASK_SUCCESS, taskToDelete));
    }

}

Change occurrence of person to tasks in deleteCommand class


/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

package info.zamojski.soft.towercollector.utils;

import android.Manifest;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.provider.Settings;

public class NetworkUtils {
    public static String getNetworkType(Context context) {
        ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        if (manager == null)
            return "NO CONNECTIVITY";
        NetworkInfo netInfo = manager.getActiveNetworkInfo();
        if (netInfo == null)
            return "NO ACTIVE NETWORK";
        return netInfo.getTypeName().toUpperCase();
    }

    public static boolean isNetworkAvailable(Context context) {
        if (PermissionUtils.hasPermissions(context, Manifest.permission.ACCESS_NETWORK_STATE)) {
            ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo activeNetworkInfo = manager.getActiveNetworkInfo();
            return (activeNetworkInfo != null && activeNetworkInfo.isConnected());
        }
        return true; // assume there's one
    }

    public static boolean isInAirplaneMode(Context context) {
        return Settings.System.getInt(context.getContentResolver(), Settings.Global.AIRPLANE_MODE_ON, 0) != 0;
    }
}

/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

package info.zamojski.soft.towercollector.utils;

import android.Manifest;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.provider.Settings;

public class NetworkUtils {
    public static String getNetworkType(Context context) {
        ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        if (manager == null)
            return "NO CONNECTIVITY";
        NetworkInfo netInfo = manager.getActiveNetworkInfo();
        if (netInfo == null)
            return "NO ACTIVE NETWORK";
        return netInfo.getTypeName().toUpperCase();
    }

    public static boolean isNetworkAvailable(Context context) {
        if (PermissionUtils.hasPermissions(context, Manifest.permission.ACCESS_NETWORK_STATE)) {
            ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo activeNetworkInfo = manager.getActiveNetworkInfo();
            return (activeNetworkInfo != null && activeNetworkInfo.isConnected());
        }
        return true; // assume there's one
    }

    public static boolean isInAirplaneMode(Context context) {
        return Settings.Global.getInt(context.getContentResolver(), Settings.Global.AIRPLANE_MODE_ON, 0) != 0;
    }
}

Use global settings instead of system settings.


package net.folab.fo.runtime._fo._lang;

import static net.folab.fo.runtime._fo._lang.Boolean.*;
import static net.folab.fo.runtime._fo._lang.Integer.*;

import net.folab.fo.runtime.Evaluable;
import net.folab.fo.runtime.Function;

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

public class BooleanTest {

    @Before
    public void setUp() throws Exception {
    }

    @After
    public void tearDown() throws Exception {
    }

    @Test
    public void test() {

        Function<Evaluable<Boolean>, Function<Evaluable<Boolean>, Evaluable<Boolean>>> falseChoose = FALSE
                .choose();
        Function<Evaluable<Boolean>, Function<Evaluable<Boolean>, Evaluable<Boolean>>> trueChoose = TRUE
                .choose();

        System.out.println(falseChoose.apply(FALSE).apply(TRUE).evaluate()
                .getValue());
        System.out.println(trueChoose.apply(FALSE).apply(TRUE).evaluate()
                .getValue());

    }

    @Test
    public void testI() {

        Function<Evaluable<Integer>, Function<Evaluable<Integer>, Evaluable<Integer>>> falseChoose = FALSE
                .choose();
        Function<Evaluable<Integer>, Function<Evaluable<Integer>, Evaluable<Integer>>> trueChoose = TRUE
                .choose();

        System.out.println(falseChoose.apply(valueOf(1)).apply(valueOf(0))
                .evaluate().getValue());
        System.out.println(trueChoose.apply(valueOf(1)).apply(valueOf(0))
                .evaluate().getValue());

    }

}

package net.folab.fo.runtime._fo._lang;

import static net.folab.fo.runtime._fo._lang.Boolean.*;
import static net.folab.fo.runtime._fo._lang.Integer.*;
import static org.hamcrest.CoreMatchers.*;
import static org.junit.Assert.*;

import net.folab.fo.runtime._fo._lang._Boolean.choose;

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

public class BooleanTest {

    @Before
    public void setUp() throws Exception {
    }

    @After
    public void tearDown() throws Exception {
    }

    @Test
    public void test_Boolean() {

        choose<Boolean> f = FALSE.choose();
        choose<Boolean> t = TRUE.choose();

        assertTrue(f.apply(FALSE).apply(TRUE).evaluate().getValue());
        assertFalse(t.apply(FALSE).apply(TRUE).evaluate().getValue());

    }

    @Test
    public void test_Integer() {

        choose<Integer> f = FALSE.choose();
        choose<Integer> t = TRUE.choose();

        Integer one = valueOf(1);
        Integer zero = valueOf(0);

        assertThat(f.apply(one).apply(zero).evaluate().getValue(), is(0));
        assertThat(t.apply(one).apply(zero).evaluate().getValue(), is(1));

    }

}

Clean up codes as test case

Clean up codes as test case


// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.psi.impl.light;

import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiRecordComponent;
import org.jetbrains.annotations.NotNull;

public interface LightRecordMember extends PsiElement {
  @NotNull
  PsiRecordComponent getRecordComponent();
}

// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.psi.impl.light;

import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiRecordComponent;
import com.intellij.psi.SyntheticElement;
import org.jetbrains.annotations.NotNull;

public interface LightRecordMember extends PsiElement, SyntheticElement {
  @NotNull
  PsiRecordComponent getRecordComponent();
}

Mark fields and fields generated by record components as SyntheticElement

GitOrigin-RevId: 6edbb900a2e69b245fb86e474bf2eb74213f699c


package org.realityforge.arez.gwt.examples;

import elemental2.dom.DomGlobal;
import org.realityforge.arez.Arez;
import org.realityforge.arez.browser.extras.spy.ConsoleSpyEventProcessor;
import org.realityforge.arez.extras.WhyRun;

final class ExampleUtil
{
  private ExampleUtil()
  {
  }

  static void spyEvents()
  {
    Arez.context().getSpy().addSpyEventHandler( new ConsoleSpyEventProcessor() );
  }

  static void jsonLogSpyEvents()
  {
    Arez.context().getSpy().addSpyEventHandler( new JsonLogSpyEventProcessor() );
  }

  static void whyRun()
  {
    DomGlobal.console.log( new WhyRun( Arez.context() ).whyRun() );
  }

  static void logAllErrors()
  {
    Arez.context().addObserverErrorHandler( ( observer, error, throwable ) -> {
      DomGlobal.console.log( "Observer error: " + error + "\nobserver: " + observer );
      if ( null != throwable )
      {
        DomGlobal.console.log( throwable );
      }
    } );
  }
}

package org.realityforge.arez.gwt.examples;

import elemental2.dom.DomGlobal;
import org.realityforge.arez.Arez;
import org.realityforge.arez.extras.WhyRun;

final class ExampleUtil
{
  private ExampleUtil()
  {
  }

  static void jsonLogSpyEvents()
  {
    Arez.context().getSpy().addSpyEventHandler( new JsonLogSpyEventProcessor() );
  }

  static void whyRun()
  {
    DomGlobal.console.log( new WhyRun( Arez.context() ).whyRun() );
  }

  static void logAllErrors()
  {
    Arez.context().addObserverErrorHandler( ( observer, error, throwable ) -> {
      DomGlobal.console.log( "Observer error: " + error + "\nobserver: " + observer );
      if ( null != throwable )
      {
        DomGlobal.console.log( throwable );
      }
    } );
  }
}

Remove code no longer required

Remove code no longer required


package org.neuralnetwork.neuron;

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

import org.neuralnetwork.synapse.AbstractSynapse;

public abstract class AbstractNeuron<ValueType, SynapseType extends AbstractSynapse<?, ?>> {
	private ValueType value;
	private Set<SynapseType> inputs = new HashSet<SynapseType>();

	public AbstractNeuron(ValueType initialValue) {
		value = initialValue;
	}

	public ValueType getValue() {
		return value;
	}

	public void addSynapse(SynapseType synapse) {
		inputs.add(synapse);
	}

	public void removeSynapse(SynapseType synapse) {
		inputs.remove(synapse);
	}

	abstract protected ValueType computeValueFromInputs(
			Set<SynapseType> inputs);

	public void computeValue() {
		value = computeValueFromInputs(inputs);
	}
}

package org.neuralnetwork.neuron;

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

import org.neuralnetwork.synapse.AbstractSynapse;

public abstract class AbstractNeuron<ValueType, SynapseType extends AbstractSynapse<?, ?>> {
	private ValueType value;
	private final Set<SynapseType> inputs = new HashSet<SynapseType>();

	public AbstractNeuron(ValueType initialValue) {
		value = initialValue;
	}

	public ValueType getValue() {
		return value;
	}

	public void addSynapse(SynapseType synapse) {
		inputs.add(synapse);
	}

	public void removeSynapse(SynapseType synapse) {
		inputs.remove(synapse);
	}

	abstract protected ValueType computeValueFromInputs(
			Set<SynapseType> inputs);

	public void computeValue() {
		value = computeValueFromInputs(inputs);
	}
}

Make the set of synapses final.

Make the set of synapses final.


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

import org.apache.cordova.*;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import edu.berkeley.eecs.emission.cordova.comm.CommunicationHelper;
import edu.berkeley.eecs.emission.cordova.connectionsettings.ConnectionSettings;

public class CommunicationHelperPlugin extends CordovaPlugin {
    @Override
    public boolean execute(String action, JSONArray data, CallbackContext callbackContext) throws JSONException {
        if (action.equals("pushGetJSON")) {
            try {
                Context ctxt = cordova.getActivity();
                String relativeURL = data.getString(0);
                JSONObject filledMessage = data.getJSONObject(1);

                String commuteTrackerHost = ConnectionSettings.getConnectURL(ctxt);
                String fullURL = commuteTrackerHost + relativeURL;

                String resultString = CommunicationHelper.pushGetJSON(ctxt, fullURL, filledMessage);
                callbackContext.success(new JSONObject(resultString));
            } catch (Exception e) {
                callbackContext.error("While pushing/getting from server "+e.getMessage());
            }
            return true;
        } else {
            return false;
        }
    }
}

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

import org.apache.cordova.*;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import edu.berkeley.eecs.emission.cordova.comm.CommunicationHelper;
import edu.berkeley.eecs.emission.cordova.connectionsettings.ConnectionSettings;

public class CommunicationHelperPlugin extends CordovaPlugin {
    @Override
    public boolean execute(String action, JSONArray data, final CallbackContext callbackContext) throws JSONException {
        if (action.equals("pushGetJSON")) {
            try {
                final Context ctxt = cordova.getActivity();
                String relativeURL = data.getString(0);
                final JSONObject filledMessage = data.getJSONObject(1);

                String commuteTrackerHost = ConnectionSettings.getConnectURL(ctxt);
                final String fullURL = commuteTrackerHost + relativeURL;

                cordova.getThreadPool().execute(new Runnable() {
                    public void run() {
                        try {
                String resultString = CommunicationHelper.pushGetJSON(ctxt, fullURL, filledMessage);
                callbackContext.success(new JSONObject(resultString));
            } catch (Exception e) {
                callbackContext.error("While pushing/getting from server "+e.getMessage());
            }
                    }
                });
            } catch (Exception e) {
                callbackContext.error("While pushing/getting from server "+e.getMessage());
            }
            return true;
        } else {
            return false;
        }
    }
}

Move the call to the server into a separate thread

So that it does not block the webcore thread


/**
 * Copyright (C) 2014 Kasper Kronborg Isager and Sigrið Gyldenkærne Dalsgarð.
 */
package dk.itu.bookie.controller;

// General utilities
import java.util.ResourceBundle;

// Net utilities
import java.net.URL;

// FXML utilities
import javafx.fxml.Initializable;

/**
 * Application controller class.
 *
 * @version 1.0.0
 */
public final class ApplicationController implements Initializable {
  private static ApplicationController instance;

  public ApplicationController getInstance() {
    return ApplicationController.instance;
  }

  public void initialize(URL url, ResourceBundle resourceBundle) {
    ApplicationController.instance = this;
  }
}

/**
 * Copyright (C) 2014 Kasper Kronborg Isager and Sigrið Gyldenkærne Dalsgarð.
 */
package dk.itu.bookie.controller;

// General utilities
import java.util.ResourceBundle;

// Net utilities
import java.net.URL;

// SQL utilities
import java.sql.SQLException;

// JavaFX collections
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;

// FXML utilities
import javafx.fxml.FXML;

// Donkey utilities
import dk.itu.donkey.Model;

// Models
import dk.itu.bookie.model.Showtime;
import dk.itu.bookie.model.Reservation;

/**
 * Application controller class.
 *
 * @version 1.0.0
 */
public final class ApplicationController {
  private static ApplicationController instance;

  private static ObservableList<Showtime> showtimes;

  private static ObservableList<Reservation> reservations;

  public ApplicationController getInstance() {
    return ApplicationController.instance;
  }

  public void initialize() {
    ApplicationController.instance = this;
  }

  public static ObservableList<Showtime> showtimes() throws SQLException {
    if (ApplicationController.showtimes == null) {
      ApplicationController.showtimes = FXCollections.observableArrayList(
        Model
          .find(Showtime.class)
          .where("playingat", ">", System.currentTimeMillis())
          .orderBy("movies.name")
          .orderBy("playingat")
          .get()
      );
    }

    return ApplicationController.showtimes;
  }

  public static ObservableList<Reservation> reservations() throws SQLException {
    if (ApplicationController.reservations == null) {
      ApplicationController.reservations = FXCollections.observableArrayList(
        Model
          .find(Reservation.class)
          .where("showtimes.playingat", ">", System.currentTimeMillis())
          .orderBy("showtimes.playingat")
          .get()
      );
    }

    return ApplicationController.reservations;
  }
}

Handle data querying in Application controller.


package liquibase.change.core;

import liquibase.change.AbstractSQLChange;
import liquibase.change.ChangeMetaData;

/**
 * Allows execution of arbitrary SQL.  This change can be used when existing changes are either don't exist,
 * are not flexible enough, or buggy.
 */
public class RawSQLChange extends AbstractSQLChange {

    private String comments;
    public RawSQLChange() {
        super("sql", "Custom SQL", ChangeMetaData.PRIORITY_DEFAULT);
    }

    public RawSQLChange(String sql) {
        this();
        setSql(sql);
    }

    public String getComments() {
        return comments;
    }

    public void setComments(String comments) {
        this.comments = comments;
    }

    public String getConfirmationMessage() {
        return "Custom SQL executed";
    }
}

package liquibase.change.core;

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

import liquibase.change.AbstractSQLChange;
import liquibase.change.ChangeMetaData;
import liquibase.database.Database;
import liquibase.database.core.MSSQLDatabase;
import liquibase.exception.DatabaseException;
import liquibase.statement.SqlStatement;
import liquibase.statement.core.RawSqlStatement;
import liquibase.util.StringUtils;

/**
 * Allows execution of arbitrary SQL.  This change can be used when existing changes are either don't exist,
 * are not flexible enough, or buggy.
 */
public class RawSQLChange extends AbstractSQLChange {

    private String comments;
    public RawSQLChange() {
        super("sql", "Custom SQL", ChangeMetaData.PRIORITY_DEFAULT);
    }

    public RawSQLChange(String sql) {
        this();
        setSql(sql);
    }

    public String getComments() {
        return comments;
    }

    public void setComments(String comments) {
        this.comments = comments;
    }

    public String getConfirmationMessage() {
        return "Custom SQL executed";
    }

	public SqlStatement[] generateStatements(Database database) {
		List<SqlStatement> returnStatements = new ArrayList<SqlStatement>();

		if (StringUtils.trimToNull(getSql()) == null) {
			return new SqlStatement[0];
		}

		String processedSQL = getSql().replaceAll("\r\n", "\n").replaceAll("\r", "\n");
		for (String statement : StringUtils.processMutliLineSQL(processedSQL, isStrippingComments(),
				isSplittingStatements(), getEndDelimiter())) {
			if (database instanceof MSSQLDatabase) {
				statement = statement.replaceAll("\n", "\r\n");
			}

			String escapedStatement;
			try {
				escapedStatement = database.getConnection().nativeSQL(statement);
			} catch (DatabaseException e) {
				escapedStatement = statement;
			}

			returnStatements.add(new RawSqlStatement(escapedStatement, getEndDelimiter()));
		}

		return returnStatements.toArray(new SqlStatement[returnStatements.size()]);
	}
}

Convert raw query to native representation


package hudson.plugins.analysis.util;

import org.apache.xerces.parsers.SAXParser;

/**
 * Registers the correct SAX driver if the environment variable is set.
 */
public class SaxSetup {
    /** Property of SAX parser factory. */
    private static final String SAX_DRIVER_PROPERTY = "org.xml.sax.driver";

    private String oldProperty;

    public SaxSetup() {
        oldProperty = System.getProperty(SAX_DRIVER_PROPERTY);
        if (oldProperty != null) {
            System.setProperty(SAX_DRIVER_PROPERTY, SAXParser.class.getName());
        }
    }

    public void cleanup() {
        if (oldProperty != null) {
            System.setProperty(SAX_DRIVER_PROPERTY, oldProperty);
        }
        else {
            System.clearProperty(SAX_DRIVER_PROPERTY);
        }
    }
}

package hudson.plugins.analysis.util;

import org.apache.xerces.parsers.SAXParser;

/**
 * Registers the correct SAX driver if the environment variable is set.
 */
public class SaxSetup {
    /** Property of SAX parser factory. */
    public static final String SAX_DRIVER_PROPERTY = "org.xml.sax.driver";

    private String oldProperty;

    public SaxSetup() {
        oldProperty = System.getProperty(SAX_DRIVER_PROPERTY);
        if (oldProperty != null) {
            System.setProperty(SAX_DRIVER_PROPERTY, SAXParser.class.getName());
        }
    }

    public void cleanup() {
        if (oldProperty != null) {
            System.setProperty(SAX_DRIVER_PROPERTY, oldProperty);
        }
        else {
            System.clearProperty(SAX_DRIVER_PROPERTY);
        }
    }
}

Clear SAX system property afterwards.

[JENKINS-20070] Clear SAX system property afterwards.


package org.ngrinder.infra.config;

import org.springframework.boot.autoconfigure.web.servlet.DispatcherServletPath;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.support.HttpRequestHandlerServlet;
import org.springframework.web.servlet.DispatcherServlet;

@Configuration
public class ServletConfig {
	@Bean
	@SuppressWarnings("unchecked")
	public ServletRegistrationBean appServletRegisterBean() {
		ServletRegistrationBean appServletRegistrationBean = new ServletRegistrationBean(dispatcherServlet(), dispatcherServletPath().getPath());
		appServletRegistrationBean.setLoadOnStartup(1);
		appServletRegistrationBean.setName("appServlet");
		return appServletRegistrationBean;
	}

	@Bean
	public DispatcherServlet dispatcherServlet() {
		return new DispatcherServlet();
	}

	@Bean
	@SuppressWarnings("unchecked")
	public ServletRegistrationBean svnDavServletRegisterBean() {
		ServletRegistrationBean SvnDavServletRegistrationBean = new ServletRegistrationBean(new HttpRequestHandlerServlet(), "/svn/*");
		SvnDavServletRegistrationBean.setLoadOnStartup(1);
		SvnDavServletRegistrationBean.setName("svnDavServlet");
		return SvnDavServletRegistrationBean;
	}

	@Bean
	public DispatcherServletPath dispatcherServletPath() {
		return () -> "/*";
	}
}

package org.ngrinder.infra.config;

import org.springframework.boot.autoconfigure.web.servlet.DispatcherServletPath;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.support.HttpRequestHandlerServlet;
import org.springframework.web.servlet.DispatcherServlet;

@Configuration
public class ServletConfig {
	@Bean
	@SuppressWarnings("unchecked")
	public ServletRegistrationBean appServletRegisterBean() {
		ServletRegistrationBean appServletRegistrationBean = new ServletRegistrationBean(dispatcherServlet(), dispatcherServletPath().getPath());
		appServletRegistrationBean.setLoadOnStartup(1);
		appServletRegistrationBean.setName("appServlet");
		return appServletRegistrationBean;
	}

	@Bean
	public DispatcherServlet dispatcherServlet() {
		return new DispatcherServlet();
	}

	@Bean
	@SuppressWarnings("unchecked")
	public ServletRegistrationBean svnDavServletRegisterBean() {
		ServletRegistrationBean svnDavServletRegistrationBean = new ServletRegistrationBean(new HttpRequestHandlerServlet(), "/svn/*");
		svnDavServletRegistrationBean.setLoadOnStartup(1);
		svnDavServletRegistrationBean.setName("svnDavServlet");
		return svnDavServletRegistrationBean;
	}

	@Bean
	public DispatcherServletPath dispatcherServletPath() {
		return () -> "/*";
	}
}

Fix typo in variable name

Fix typo in variable name


package is.stanton.andy;

import com.google.inject.Guice;

import javax.naming.InitialContext;

public class EntryPoint {
    public static void main(String[] args) throws Exception {
        new InitialContext();
        Guice.createInjector();

        System.out.println("Running Camel + Guice example on http://127.0.0.1:8080/ping");
        System.out.println("Press Ctrl-C to quit");
    }
}

package is.stanton.andy;

import javax.naming.InitialContext;

public class EntryPoint {
    public static void main(String[] args) throws Exception {
        new InitialContext();

        System.out.println("Running Camel + Guice example on http://127.0.0.1:8080/ping");
        System.out.println("Press Ctrl-C to quit");
    }
}

Remove unnecessary Guice.createInjector() from main


package com.github.onsdigital.perkin.transform;

import org.junit.Test;

import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertThat;

public class NumberServiceTest {

    private NumberService classUnderTest;

    @Test
    public void shouldStartAtCorrectNumber() {
        //Given
        classUnderTest = new NumberService("test", 5L, 10L);

        //When
        long start = classUnderTest.getNext();

        //Then
        assertThat(start, is(5L));
    }

    @Test
    public void shouldWrapAroundToStart() {
        //Given
        long start = 5L;
        classUnderTest = new NumberService("test", start, 10L);
        classUnderTest.reset();

        //When / Then
        for (int i = 0; i < 6; i++) {
            long sequence = classUnderTest.getNext();
            assertThat(sequence, is(start + i));
        }

        //Then
        long sequence = classUnderTest.getNext();
        assertThat(sequence, is(start));
    }
}

package com.github.onsdigital.perkin.transform;

import org.junit.Test;

import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertThat;

public class NumberServiceTest {

    private NumberService classUnderTest;

    @Test
    public void shouldStartAtCorrectNumber() {
        //Given
        classUnderTest = new NumberService("test", 5L, 10L);

        //When
        long start = classUnderTest.getNext();

        //Then
        assertThat(start, is(5L));
    }

    @Test
    public void shouldWrapAroundToStart() {
        //Given
        long start = 5L;
        classUnderTest = new NumberService("test", start, 10L);
        classUnderTest.reset();

        //When / Then
        for (int i = 0; i < 6; i++) {
            long sequence = classUnderTest.getNext();
            assertThat(sequence, is(start + i));
        }

        //Then
        long sequence = classUnderTest.getNext();
        assertThat(sequence, is(start));
    }

    @Test
    public void shouldWrapAroundToStartWhenSaved() {
        //Given
        long start = 5L;
        classUnderTest = new NumberService("test", start, 10L);
        classUnderTest.reset();

        //When / Then
        for (int i = 0; i < 6; i++) {
            // Re-initialise (and re-load) on every increment:
            classUnderTest = new NumberService("test", start, 10L);
            long sequence = classUnderTest.getNext();
            assertThat(sequence, is(start + i));
        }

        //Then
        long sequence = new NumberService("test", start, 10L).getNext();
        assertThat(sequence, is(start));
    }
}

Test for looping a sequence when the value is saved on every increment.


package com.gitrekt.resort.controller;

import java.net.URL;
import java.util.ResourceBundle;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.stage.Stage;
import javafx.scene.control.button

/**
 * FXML Controller class for the leave feedback screen.
 */
public class LeaveFeedbackScreenController implements Initializable {

    @FXML
    private Button submitButton;

    @Override
    public void initialize(URL url, ResourceBundle rb) {
        // TODO
    }

    /**
     * Closes the window and saves the user's feedback to a database
     * @param event
     */
    @FXML
    private void onSubmitButtonClicked(ActionEvent event) {
        Stage stage = (Stage) submitButton.getScene().getWindow();
        //TODO Add feedback to database
        stage.close();
    }
}

Fix whitespace at end of file

Fix whitespace at end of file


package task.timer;

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.layout.AnchorPane;

import javafx.stage.Stage;

public class Main extends Application{

	public void start(Stage primaryStage){

			ViewLoader<AnchorPane, Object> viewLoader =
					new ViewLoader<AnchorPane, Object>("view/EmployeeData.fxml");

			AnchorPane anchorPane = viewLoader.getLayout();

		Scene scene = new Scene(anchorPane);
		primaryStage.setScene(scene);

		primaryStage.show();

	}

	public static void main(String[] args) {
		launch(args);

	}

}

package task.timer;

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.layout.AnchorPane;

import javafx.stage.Stage;

public class Main extends Application{

	public void start(Stage primaryStage){

			ViewLoader<AnchorPane, Object> viewLoader =
					//new ViewLoader<AnchorPane, Object>("view/EmployeeData.fxml");
					new ViewLoader<AnchorPane, Object>("view/MainManager.fxml");

			AnchorPane anchorPane = viewLoader.getLayout();

		Scene scene = new Scene(anchorPane);
		primaryStage.setScene(scene);

		primaryStage.show();

	}

	public static void main(String[] args) {
		launch(args);

	}

}

Change to show manager interface.

Change to show manager interface.


package at.ac.tuwien.inso.service;

import at.ac.tuwien.inso.entity.Course;
import at.ac.tuwien.inso.entity.Semester;
import at.ac.tuwien.inso.repository.CourseRepository;

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

import java.util.List;

@Service
public class CoursesService {

    @Autowired
    private SemesterService semesterService;

    @Autowired
    private CourseRepository courseRepository;

    public List<Course> findForCurrentSemester() {
        Semester semester = semesterService.getCurrentSemester();
        return courseRepository.findAllBySemester(semester);
    }

}

package at.ac.tuwien.inso.service;

import at.ac.tuwien.inso.entity.Course;
import at.ac.tuwien.inso.entity.Semester;
import at.ac.tuwien.inso.repository.CourseRepository;

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

import java.util.List;

import javax.validation.constraints.NotNull;

@Service
public class CoursesService {

    @Autowired
    private SemesterService semesterService;

    @Autowired
    private CourseRepository courseRepository;

    public List<Course> findCourseForCurrentSemesterWithName(@NotNull String name) {
        Semester semester = semesterService.getCurrentSemester();
        return courseRepository.findAllBySemesterAndSubjectNameLikeIgnoreCase(semester, "%" + name + "%");
    }

}

Add filter for name, combine with get all


package trantect.android_framework_demo.activity;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;

import trantect.android_framework_demo.R;

/**
 * Create by Trantect on 14-7-2.
 */
public class MainActivity extends Activity {

    private String getTag() {
        return getPackageName().toString() + getClass().toString();
    }

    @Override
    public void onCreate(Bundle savedInstance) {
        super.onCreate(savedInstance);
        Log.d(getTag(), "onCreate");
        setContentView(R.layout.welcome_main);
    }

    @Override
    public void onStart() {
        super.onStart();
    }
}

package trantect.android_framework_demo.activity;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import trantect.android_framework_demo.R;

/**
 * Create by Trantect on 14-7-2.
 */
public class MainActivity extends Activity {

    private Button bt_welcome;

    private TextView tv_welcome;

    @Override
    public void onCreate(Bundle savedInstance) {
        super.onCreate(savedInstance);
        Log.d(getTag(), "onCreate");
        setContentView(R.layout.welcome_main);
        initViews();
        onViewClick();
    }

    @Override
    public void onStart() {
        Log.d(getTag(), "onStart");
        super.onStart();
    }

    private String getTag() {
        return getPackageName().toString() + getClass().toString();
    }

    // init some views
    private void initViews(){
        bt_welcome = (Button)findViewById(R.id.bt_welcome);
        tv_welcome = (TextView)findViewById(R.id.tv_welcome);
        showBtView();
    }

    private void onViewClick(){
        MyListener myListener = new MyListener();
        bt_welcome.setOnClickListener(myListener);
        tv_welcome.setOnClickListener(myListener);
    }

    class MyListener implements View.OnClickListener{

        @Override
        public void onClick(View view) {
            int id = view.getId();
            switch (id){
                case R.id.bt_welcome:
                    showTvView();
                    break;
                case R.id.tv_welcome:
                    showBtView();
                    break;
            }
        }
    }

    // show Button
    private void showBtView(){
        bt_welcome.setVisibility(View.VISIBLE);
        tv_welcome.setVisibility(View.GONE);
    }

    // show TextView
    private void showTvView(){
        tv_welcome.setVisibility(View.VISIBLE);
        bt_welcome.setVisibility(View.GONE);
    }
}

Add some logic on main activity

Add some logic on main activity


package org.pdxfinder.repositories;

import org.pdxfinder.dao.OntologyTerm;
import org.springframework.data.neo4j.annotation.Query;
import org.springframework.data.repository.PagingAndSortingRepository;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import java.util.Collection;

/**
 * Created by csaba on 07/06/2017.
 */
@Repository
public interface OntologyTermRepository extends PagingAndSortingRepository<OntologyTerm, Long>
{

    OntologyTerm findById();

    @Query("MATCH (o:OntologyTerm) WHERE toLower(o.label) = toLower({label}) return o")
    OntologyTerm findByLabel(@Param("label") String label);

    OntologyTerm findByUrl(String url);

    @Query("match(o:OntologyTerm) return o limit 40")
    Collection<OntologyTerm>  findByOntologyTermLabel(@Param("label") String label);

    @Query("MATCH (oTerm:OntologyTerm)<-[SUBCLASS_OF]-(subNodes) where oTerm.label CONTAINS trim(toLower({searchParam})) WITH COLLECT(subNodes) AS subNodes " +
            "UNWIND subNodes AS subN " +
            "MATCH (oTerm:OntologyTerm)<-[SUBCLASS_OF]-(subNodes2) where oTerm.label=subN.label return subN,subNodes2 limit 8")
    Collection<OntologyTerm> findByDiseaseOntologyTerm(@Param("searchParam") String searchParam);

}

package org.pdxfinder.repositories;

import org.pdxfinder.dao.OntologyTerm;
import org.springframework.data.neo4j.annotation.Query;
import org.springframework.data.repository.PagingAndSortingRepository;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import java.util.Collection;

/**
 * Created by csaba on 07/06/2017.
 */
@Repository
public interface OntologyTermRepository extends PagingAndSortingRepository<OntologyTerm, Long>
{

    OntologyTerm findById();

    @Query("MATCH (o:OntologyTerm) WHERE toLower(o.label) = toLower({label}) return o")
    OntologyTerm findByLabel(@Param("label") String label);

    OntologyTerm findByUrl(String url);

    @Query("match(o:OntologyTerm) return o limit 40")
    Collection<OntologyTerm>  findByOntologyTermLabel(@Param("label") String label);

    @Query("MATCH (oTerm:OntologyTerm)<-[SUBCLASS_OF]-(subNodes) where oTerm.label CONTAINS trim(toLower({searchParam})) WITH COLLECT(subNodes) AS subNodes " +
            "UNWIND subNodes AS subN " +
            "MATCH (oTerm:OntologyTerm)<-[SUBCLASS_OF]-(subNodes2) where oTerm.label=subN.label return subN,subNodes2 limit 15")
    Collection<OntologyTerm> findByDiseaseOntologyTerm(@Param("searchParam") String searchParam);

}

Adjust search to make use of Disease Ontology terms


package info.u_team.u_team_test.init;

import info.u_team.u_team_core.util.registry.RegistryWorker;
import info.u_team.u_team_test.TestMod;
import info.u_team.u_team_test.screen.*;
import net.minecraft.client.gui.ScreenManager;
import net.minecraftforge.api.distmarker.Dist;
import net.minecraftforge.eventbus.api.SubscribeEvent;
import net.minecraftforge.fml.common.Mod.EventBusSubscriber;
import net.minecraftforge.fml.common.Mod.EventBusSubscriber.Bus;
import net.minecraftforge.fml.event.lifecycle.FMLClientSetupEvent;

@EventBusSubscriber(modid = TestMod.MODID, bus = Bus.MOD, value = Dist.CLIENT)
public class TestScreens {

	@SubscribeEvent
	public static void register(FMLClientSetupEvent event) {
		RegistryWorker.runOnMainThread(() -> {
			ScreenManager.registerFactory(TestContainers.BASIC, BasicTileEntityScreen::new);
			ScreenManager.registerFactory(TestContainers.BASIC_ENERGY_CREATOR, BasicEnergyCreatorScreen::new);
			ScreenManager.registerFactory(TestContainers.BASIC_FLUID_INVENTORY, BasicFluidInventoryScreen::new);
		});
	}

}

package info.u_team.u_team_test.init;

import info.u_team.u_team_core.util.registry.SyncedWorker;
import info.u_team.u_team_test.TestMod;
import info.u_team.u_team_test.screen.*;
import net.minecraft.client.gui.ScreenManager;
import net.minecraftforge.api.distmarker.Dist;
import net.minecraftforge.eventbus.api.SubscribeEvent;
import net.minecraftforge.fml.common.Mod.EventBusSubscriber;
import net.minecraftforge.fml.common.Mod.EventBusSubscriber.Bus;
import net.minecraftforge.fml.event.lifecycle.FMLClientSetupEvent;

@EventBusSubscriber(modid = TestMod.MODID, bus = Bus.MOD, value = Dist.CLIENT)
public class TestScreens {

	@SubscribeEvent
	public static void register(FMLClientSetupEvent event) {
		SyncedWorker.runOnMainThread(() -> {
			ScreenManager.registerFactory(TestContainers.BASIC, BasicTileEntityScreen::new);
			ScreenManager.registerFactory(TestContainers.BASIC_ENERGY_CREATOR, BasicEnergyCreatorScreen::new);
			ScreenManager.registerFactory(TestContainers.BASIC_FLUID_INVENTORY, BasicFluidInventoryScreen::new);
		});
	}

}

Fix class rename in caller class

Fix class rename in caller class


package org.javarosa.core.model.utils;

import org.javarosa.core.model.trace.EvaluationTrace;
import org.javarosa.core.model.trace.EvaluationTraceReporter;
import org.javarosa.core.model.trace.StringEvaluationTraceSerializer;

/**
 * Utility functions for instrumentation in the engine
 *
 * Created by ctsims on 7/6/2017.
 */

public class InstrumentationUtils {

    /**
     * Prints out traces (if any exist) from the provided reporter with a description into sysout
     */
    public static void printAndClearTraces(EvaluationTraceReporter reporter, String description) {
        if (reporter != null) {
            if (reporter.wereTracesReported()) {
                System.out.println(description);
            }

            StringEvaluationTraceSerializer serializer = new StringEvaluationTraceSerializer();

            for (EvaluationTrace trace : reporter.getCollectedTraces()) {
                System.out.println(trace.getExpression() + ": " + trace.getValue());
                System.out.print(serializer.serializeEvaluationLevels(trace));
            }

            reporter.reset();
        }
    }
}

package org.javarosa.core.model.utils;

import org.javarosa.core.model.trace.EvaluationTrace;
import org.javarosa.core.model.trace.EvaluationTraceReporter;
import org.javarosa.core.model.trace.StringEvaluationTraceSerializer;

/**
 * Utility functions for instrumentation in the engine
 *
 * Created by ctsims on 7/6/2017.
 */

public class InstrumentationUtils {

    /**
     * Prints out traces (if any exist) from the provided reporter with a description into sysout
     */
    public static void printAndClearTraces(EvaluationTraceReporter reporter, String description) {
        if (reporter != null) {
            if (reporter.wereTracesReported()) {
                System.out.println(description);
            }

            StringEvaluationTraceSerializer serializer = new StringEvaluationTraceSerializer();

            for (EvaluationTrace trace : reporter.getCollectedTraces()) {
                System.out.println(trace.getExpression() + ": " + trace.getValue());
                System.out.print(serializer.serializeEvaluationLevels(trace));
            }

            reporter.reset();
        }
    }

    /**
     * Prints out traces (if any exist) from the provided reporter with a description into sysout
     */
    public static String collectAndClearTraces(EvaluationTraceReporter reporter, String description) {
        String returnValue = "";
        if (reporter != null) {
            if (reporter.wereTracesReported()) {
                returnValue += description + "\n";
            }

            StringEvaluationTraceSerializer serializer = new StringEvaluationTraceSerializer();

            for (EvaluationTrace trace : reporter.getCollectedTraces()) {
                returnValue += trace.getExpression() + ": " + trace.getValue()  + "\n";
                returnValue += serializer.serializeEvaluationLevels(trace);
            }

            reporter.reset();
        }
        return returnValue;
    }

}

Add a way to evaluate traces into a single string output


package pl.touk.sputnik.processor.sonar;

import java.util.List;

import org.sonar.runner.api.EmbeddedRunner;

import pl.touk.sputnik.review.Review;
import pl.touk.sputnik.review.ReviewFile;

import com.google.common.collect.Lists;

class SonarRunnerBuilder {
    public SonarRunner prepareRunner(Review review) {
        List<String> files = Lists.newArrayList();
        for (ReviewFile file : review.getFiles()) {
            files.add(file.getReviewFilename());
        }
        SonarRunner sonarRunner = new SonarRunner(files, EmbeddedRunner.create());
        return sonarRunner;
    }
}

package pl.touk.sputnik.processor.sonar;

import java.io.File;
import java.util.List;

import org.sonar.runner.api.EmbeddedRunner;

import pl.touk.sputnik.review.Review;
import pl.touk.sputnik.review.ReviewFile;

import com.google.common.collect.Lists;

class SonarRunnerBuilder {
    public SonarRunner prepareRunner(Review review) {
        List<String> files = Lists.newArrayList();

        /*
         * Some sonar plugin do no include git path as the source file path (for
         * example, sonar-visual-studio plugin generates filenames that are relative
         * to the module csproj file).
         *
         * Using the file basename and a recursive match allows Sonar to match
         * modified files with their indexed names in Sonar.
         *
         * Although this can generate useless analysis (as some files that are not
         * included in a review may be analysed), this has a limited additional
         * cost considering that few files have the same basename inside a
         * repository.
         */
        for (ReviewFile file : review.getFiles()) {
            files.add("**/" + new File(file.getReviewFilename()).getName());
        }
        SonarRunner sonarRunner = new SonarRunner(files, EmbeddedRunner.create());
        return sonarRunner;
    }
}

Use file basename instead of fullname in sonar

Some sonar plugin do no include git path as the source file path (for
example, sonar-visual-studio plugin generates filenames that are
relative to the module csproj file).

Using the file basename and a recursive match allows Sonar to match
modified files with their indexed names in Sonar.

Although this can generate useless analysis (as some files that are not
included in a review may be analysed), this has a limited additional
cost considering that few files have the same basename inside a
repository.

Change-Id: Ib74289e201098d15c618791f47b2dd657c3a1744


package org.signaut.jetty.deploy.providers.couchdb;

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

import javax.servlet.http.HttpServletRequest;

import org.eclipse.jetty.server.handler.ErrorHandler;
/**
 * Display the error as a json object
 *
 */
class JsonErrorHandler extends ErrorHandler {

    @Override
    protected void writeErrorPage(HttpServletRequest request, Writer writer, int code, String message,
            boolean showStacks) throws IOException {
        // TODO Auto-generated method stub
        final Throwable exception = (Throwable) request.getAttribute("javax.servlet.error.exception");
        if (exception == null) {
            message = String.format("{\"status\": %d, \"uri\":\"%s\"," + "\"message\": %s}", code,
                                    request.getRequestURI(), jsonStr(message));
        } else {
            message = String.format("{\"status\": %d, \"uri\":\"%s\"," + "\"message\": %s, " + "\"exception\": { "
                                            + "\"exception\": \"%s\", \"message\": %s} }", code,
                                    request.getRequestURI(), jsonStr(message),
                                    exception.getClass().getCanonicalName(), jsonStr(exception.getMessage()));
        }
        writer.write(message);
    }

    private final String jsonStr(String string) {
        return string == null ? null : "\"" + string + "\"";
    }
}

package org.signaut.jetty.deploy.providers.couchdb;

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

import javax.servlet.http.HttpServletRequest;

import org.eclipse.jetty.server.handler.ErrorHandler;
/**
 * Display the error as a json object
 *
 */
class JsonErrorHandler extends ErrorHandler {

    @Override
    protected void writeErrorPage(HttpServletRequest request, Writer writer, int code, String message,
            boolean showStacks) throws IOException {
        // TODO Auto-generated method stub
        final Throwable exception = (Throwable) request.getAttribute("javax.servlet.error.exception");
        final String user = request.getUserPrincipal()==null?null:request.getUserPrincipal().getName();
        if (exception == null) {
            message = String.format("{\"status\": %d, \"uri\":\"%s\", \"user\": %s, \"message\": %s}", code,
                                    request.getRequestURI(), jsonStr(user), jsonStr(message));
        } else {
            message = String.format("{\"status\": %d, \"uri\":\"%s\", \"user\": %s, \"message\": %s, \"exception\": { "
                                            + "\"exception\": \"%s\", \"message\": %s} }", code,
                                    request.getRequestURI(), jsonStr(user), jsonStr(message),
                                    exception.getClass().getCanonicalName(), jsonStr(exception.getMessage()));
        }
        writer.write(message);
    }

    private final String jsonStr(String string) {
        return string == null ? null : "\"" + string + "\"";
    }
}

Add user to error messages

Add user to error messages


package org.eclipse.scanning.points;

import java.util.Iterator;

import org.eclipse.scanning.api.points.AbstractGenerator;
import org.eclipse.scanning.api.points.GeneratorException;
import org.eclipse.scanning.api.points.IPosition;
import org.eclipse.scanning.api.points.models.ArrayModel;

public class ArrayGenerator extends AbstractGenerator<ArrayModel, IPosition> {

	ArrayGenerator() {
		setLabel("Position List Scan");
		setDescription("Creates a scan from a list of positions");
	}

	@Override
	public int size() throws GeneratorException {
		if (containers!=null) throw new GeneratorException("Cannot deal with regions in a position list scan!");
		if (model.getPositions() == null) {
			return 0;
		}
		return model.getPositions().length;
	}

	@Override
	public Iterator<IPosition> iterator() {
		return new ArrayIterator(this);
	}

}

package org.eclipse.scanning.points;

import java.util.Iterator;

import org.eclipse.scanning.api.points.AbstractGenerator;
import org.eclipse.scanning.api.points.GeneratorException;
import org.eclipse.scanning.api.points.IPosition;
import org.eclipse.scanning.api.points.models.ArrayModel;

public class ArrayGenerator extends AbstractGenerator<ArrayModel, IPosition> {

	ArrayGenerator() {
		setLabel("Array Scan");
		setDescription("Creates a scan from an array of positions");
	}

	@Override
	public int size() throws GeneratorException {
		if (containers!=null) throw new GeneratorException("Cannot deal with regions in an array scan!");
		if (model.getPositions() == null) {
			return 0;
		}
		return model.getPositions().length;
	}

	@Override
	public Iterator<IPosition> iterator() {
		return new ArrayIterator(this);
	}

}

Adjust name and description for consistency

http://jira.diamond.ac.uk/browse/DATAACQTEAM-240


package fape.core.planning.preprocessing;

import planstack.anml.model.abs.AbstractAction;

/**
 * An action an might support an open goal.
 *
 * The action might be given a decomposition to apply
 */
public class SupportingAction {
    public int decID;
    public final AbstractAction absAct;

    public SupportingAction(AbstractAction aa, int decID) {
        this.absAct = aa;
        this.decID = decID;
    }
    public SupportingAction(AbstractAction aa) {
        this.absAct = aa;
        this.decID = -1;
    }

    public boolean mustBeDecomposed() { return decID != -1; }
    public int getDecID() { return decID; }
}

package fape.core.planning.preprocessing;

import planstack.anml.model.abs.AbstractAction;

/**
 * An action an might support an open goal.
 *
 * The action might be given a decomposition to apply
 */
public class SupportingAction {
    public int decID;
    public final AbstractAction absAct;

    public SupportingAction(AbstractAction aa, int decID) {
        this.absAct = aa;
        this.decID = decID;
    }
    public SupportingAction(AbstractAction aa) {
        this.absAct = aa;
        this.decID = -1;
    }

    public boolean mustBeDecomposed() { return decID != -1; }
    public int getDecID() { return decID; }

    @Override
    public boolean equals(Object o) {
        if(o instanceof SupportingAction) {
            return ((SupportingAction) o).absAct.equals(this.absAct) && ((SupportingAction) o).decID == this.decID;
        } else {
            return false;
        }
    }

    @Override
    public int hashCode() {
        return this.absAct.hashCode() + decID;
    }
}

Implement equals() and hashCode() for supporting actions.

This way we make sure we dont have to identical resolvers.


package org.cyclops.cyclopscore.config.extendedconfig;

import org.cyclops.cyclopscore.config.ConfigurableType;
import org.cyclops.cyclopscore.config.configurable.ConfigurableVillager;
import org.cyclops.cyclopscore.init.ModBase;

/**
 * Config for villagers.
 * @author rubensworks
 * @see ExtendedConfig
 */
public abstract class VillagerConfig extends ExtendedConfig<VillagerConfig> {

    private final int id;

    /**
     * Make a new instance.
     * @param mod     The mod instance.
     * @param defaultId The default ID for the configurable.
     * @param namedId The unique name ID for the configurable.
     * @param comment The comment to add in the config file for this configurable.
     * @param element The class of this configurable.
     */
    public VillagerConfig(ModBase mod, int defaultId, String namedId,
            String comment, Class<? extends ConfigurableVillager> element) {
        super(mod, defaultId != 0, namedId, comment, element);
        this.id = defaultId;
    }

    public int getId() {
        return this.id;
    }

    @Override
	public String getUnlocalizedName() {
		return "entity.villager." + getNamedId();
	}

    @Override
	public ConfigurableType getHolderType() {
		return ConfigurableType.VILLAGER;
	}

}

package org.cyclops.cyclopscore.config.extendedconfig;

import org.cyclops.cyclopscore.config.ConfigurableType;
import org.cyclops.cyclopscore.config.configurable.ConfigurableVillager;
import org.cyclops.cyclopscore.init.ModBase;

/**
 * Config for villagers.
 * @author rubensworks
 * @see ExtendedConfig
 */
public abstract class VillagerConfig extends ExtendedConfig<VillagerConfig> {

    private int id;

    /**
     * Make a new instance.
     * @param mod     The mod instance.
     * @param defaultId The default ID for the configurable.
     * @param namedId The unique name ID for the configurable.
     * @param comment The comment to add in the config file for this configurable.
     * @param element The class of this configurable.
     */
    public VillagerConfig(ModBase mod, int defaultId, String namedId,
            String comment, Class<? extends ConfigurableVillager> element) {
        super(mod, defaultId != 0, namedId, comment, element);
        this.id = defaultId;
    }

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

    public int getId() {
        return this.id;
    }

    @Override
	public String getUnlocalizedName() {
		return "entity.villager." + getNamedId();
	}

    @Override
	public ConfigurableType getHolderType() {
		return ConfigurableType.VILLAGER;
	}

}

Allow changing of villager id

Allow changing of villager id


package com.example.jersey_sample.gitlab;

import javax.ws.rs.POST;
import javax.ws.rs.Path;

import static com.example.jersey_sample.Log.GITLAB_LOG;

/**
 * @author manhnt
 */
@SuppressWarnings("ALL")
public class WebHook {

	@POST
	@Path("/push")
	public void pushEventHook(String body) {
		GITLAB_LOG.trace("Body: " + body);
	}
}

package com.example.jersey_sample.gitlab;

import javax.ws.rs.POST;
import javax.ws.rs.Path;

import static com.example.jersey_sample.Log.GITLAB_LOG;

/**
 * @author manhnt
 */
public class WebHook {

	@POST
	@Path("/push")
	public void pushEventHook(String body) {
		GITLAB_LOG.warn("Body: " + body);
	}
}

Change log level of trace message

Change log level of trace message


package com.puppycrawl.tools.checkstyle.checks.coding;
/* комментарий на русском */
public class InputReturnCount
{
    public boolean equals(Object obj) {
        int i = 1;
        switch (i) {
        case 1: return true;
        case 2: return true;
        case 3: return true;
        case 4: return true;
        case 5: return true;
        case 6: return true;
        }
        return false;
    }

    void foo(int i) {
        switch (i) {
        case 1: return;
        case 2: return;
        case 3: return;
        case 4: return;
        case 5: return;
        case 6: return;
        }
        return;
    }

    void foo1(int i) {
        if (i == 1) {
            return;
        }
        Object obj = new Object() {
                void method1(int i) {
                    switch (i) {
                    case 1: return;
                    case 2: return;
                    case 3: return;
                    case 4: return;
                    case 5: return;
                    }
                    return;
                }
            };
        return;
    }
}

class Test {

    public Test() {}
}

package com.puppycrawl.tools.checkstyle.coding;
/* комментарий на русском */
public class InputReturnCount
{
    public boolean equals(Object obj) {
        int i = 1;
        switch (i) {
        case 1: return true;
        case 2: return true;
        case 3: return true;
        case 4: return true;
        case 5: return true;
        case 6: return true;
        }
        return false;
    }

    void foo(int i) {
        switch (i) {
        case 1: return;
        case 2: return;
        case 3: return;
        case 4: return;
        case 5: return;
        case 6: return;
        }
        return;
    }

    void foo1(int i) {
        if (i == 1) {
            return;
        }
        Object obj = new Object() {
                void method1(int i) {
                    switch (i) {
                    case 1: return;
                    case 2: return;
                    case 3: return;
                    case 4: return;
                    case 5: return;
                    }
                    return;
                }
            };
        return;
    }
}

class Test {

    public Test() {}
}

Return Count Check compilable UT input

Return Count Check compilable UT input


package com.intellij.plugins.haxe.lang.parser.statements;

import com.intellij.plugins.haxe.lang.parser.HaxeParsingTestBase;

public class StatementTestBase extends HaxeParsingTestBase {
  public StatementTestBase(String subFolder) {
    super("parsing", "haxe", "statements", subFolder);
  }
}

package com.intellij.plugins.haxe.lang.parser.statements;

import com.intellij.plugins.haxe.lang.parser.HaxeParsingTestBase;

abstract public class StatementTestBase extends HaxeParsingTestBase {
  public StatementTestBase(String subFolder) {
    super("parsing", "haxe", "statements", subFolder);
  }
}

Make abstract to avoid inspection.

Make abstract to avoid inspection.


package net.cdahmedeh.ultimeter.ui.main;

import net.cdahmedeh.ultimeter.persistence.dao.TodoManager;
import net.cdahmedeh.ultimeter.persistence.manager.PersistenceManager;
import net.cdahmedeh.ultimeter.ui.controller.TodoController;
import net.cdahmedeh.ultimeter.ui.view.TodoView;

import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;

/**
 * This class starts the Ultimeter UI.
 *
 * @author Ahmed El-Hajjar
 *
 */
public class Ultimeter {
    public static void main(String[] args) throws Exception {
        // Prepare persistence utilities.
        final PersistenceManager persistenceManager = new PersistenceManager();
        final TodoManager todoManager = new TodoManager(persistenceManager);

        // Prepare controllers
        final TodoController todoController = new TodoController(todoManager);

        // Create the UI display
        final Display display = new Display();
        final Shell shell = new Shell(display);
        shell.setLayout(new FillLayout());

        // Create Views
        @SuppressWarnings("unused")
        final TodoView todoView = new TodoView(shell, todoController);

        // Display the UI
        shell.open();

        // Start event loop
        while (!shell.isDisposed()) {
            if (!display.readAndDispatch()) {
                display.sleep();
            }
        }

        // Clean up.
        display.dispose();
    }
}

package net.cdahmedeh.ultimeter.ui.main;

import net.cdahmedeh.ultimeter.persistence.dao.TodoManager;
import net.cdahmedeh.ultimeter.persistence.manager.PersistenceManager;
import net.cdahmedeh.ultimeter.ui.controller.TodoController;
import net.cdahmedeh.ultimeter.ui.view.TodoView;

import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;

/**
 * This class starts the Ultimeter UI.
 *
 * @author Ahmed El-Hajjar
 *
 */
public class Ultimeter {
    public static void main(String[] args) throws Exception {
        // Prepare persistence utilities.
        final PersistenceManager persistenceManager = new PersistenceManager();
        final TodoManager todoManager = new TodoManager(persistenceManager);

        // Prepare controllers
        final TodoController todoController = new TodoController(todoManager);

        // Create the UI display
        final Display display = new Display();
        final Shell shell = new Shell(display);
        shell.setText("Ultimeter - Time Management System");
        shell.setLayout(new FillLayout());

        // Create Views
        @SuppressWarnings("unused")
        final TodoView todoView = new TodoView(shell, todoController);

        // Display the UI
        shell.open();

        // Start event loop
        while (!shell.isDisposed()) {
            if (!display.readAndDispatch()) {
                display.sleep();
            }
        }

        // Clean up.
        display.dispose();
    }
}

Set application title in titlebar.

Set application title in titlebar.


package ru.yandex.qatools.allure.e2e;

import org.junit.Test;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.phantomjs.PhantomJSDriver;
import org.openqa.selenium.remote.DesiredCapabilities;

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

/**
 * @author Artem Eroshenko eroshenkoam@yandex-team.ru
 *         Date: 1/24/14
 */
public class AllureCommonPageTest {

    @Test
    public void sampleTitleTest() {
        WebDriver driver = new PhantomJSDriver(DesiredCapabilities.firefox());
        driver.get("http://0.0.0.0:8080/e2e");
        assertThat(driver.getTitle(), equalTo("Allure Dashboard"));
    }
}

package ru.yandex.qatools.allure.e2e;

import org.junit.Test;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.phantomjs.PhantomJSDriver;
import org.openqa.selenium.remote.DesiredCapabilities;

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

/**
 * @author Artem Eroshenko eroshenkoam@yandex-team.ru
 *         Date: 1/24/14
 */
public class AllureCommonPageTest {

    @Test
    public void sampleTitleTest() {
        WebDriver driver = new PhantomJSDriver(DesiredCapabilities.firefox());
        driver.get("http://0.0.0.0:8080/e2e/index.html");
        assertThat(driver.getTitle(), equalTo("Allure Dashboard"));
    }
}

Fix allure report path in test

Fix allure report path in test


package io.bootique.undertow.command;

import com.google.inject.Inject;
import com.google.inject.Provider;
import io.bootique.application.CommandMetadata;
import io.bootique.cli.Cli;
import io.bootique.command.CommandOutcome;
import io.bootique.command.CommandWithMetadata;
import io.bootique.undertow.UndertowServer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Command for running Undertow server.
 *
 * @since 0.1
 */
public class ServerCommand extends CommandWithMetadata {

    private static final Logger LOGGER = LoggerFactory.getLogger(ServerCommand.class);

    private final Provider<UndertowServer> serverProvider;

    @Inject
    public ServerCommand(Provider<UndertowServer> serverProvider) {
        super(createMetadata());
        this.serverProvider = serverProvider;
    }

    @Override
    public CommandOutcome run(Cli cli) {
        LOGGER.info("Will run Undertow Server...");

        UndertowServer server = serverProvider.get();

        try {
            server.start();
        } catch (Exception e) {
            return CommandOutcome.failed(1, e);
        }

        try {
            Thread.currentThread().join();
        } catch (InterruptedException ie) {
            try {
                server.stop();
            } catch (Exception se) {
                return CommandOutcome.failed(1, se);
            }
        }

        return CommandOutcome.succeeded();
    }

    private static CommandMetadata createMetadata() {
        return CommandMetadata
                .builder(ServerCommand.class)
                .description("Starts Undertow server.")
                .build();
    }
}

package io.bootique.undertow.command;

import com.google.inject.Inject;
import com.google.inject.Provider;
import io.bootique.cli.Cli;
import io.bootique.command.CommandOutcome;
import io.bootique.command.CommandWithMetadata;
import io.bootique.meta.application.CommandMetadata;
import io.bootique.undertow.UndertowServer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Command for running Undertow server.
 *
 * @since 0.1
 */
public class ServerCommand extends CommandWithMetadata {

    private static final Logger LOGGER = LoggerFactory.getLogger(ServerCommand.class);

    private final Provider<UndertowServer> serverProvider;

    @Inject
    public ServerCommand(Provider<UndertowServer> serverProvider) {
        super(createMetadata());
        this.serverProvider = serverProvider;
    }

    @Override
    public CommandOutcome run(Cli cli) {
        LOGGER.info("Will run Undertow Server...");

        UndertowServer server = serverProvider.get();

        try {
            server.start();
        } catch (Exception e) {
            return CommandOutcome.failed(1, e);
        }

        try {
            Thread.currentThread().join();
        } catch (InterruptedException ie) {
            try {
                server.stop();
            } catch (Exception se) {
                return CommandOutcome.failed(1, se);
            }
        }

        return CommandOutcome.succeeded();
    }

    private static CommandMetadata createMetadata() {
        return CommandMetadata
                .builder(ServerCommand.class)
                .description("Starts Undertow server.")
                .build();
    }
}

Fix build. Change CommandMetadata import.


package info.u_team.u_team_test.init;

import info.u_team.u_team_core.util.registry.*;
import info.u_team.u_team_test.screen.*;
import net.minecraftforge.eventbus.api.IEventBus;
import net.minecraftforge.fml.event.lifecycle.FMLClientSetupEvent;

public class TestScreens {

	public static void setup(FMLClientSetupEvent event) {
		MainThreadWorker.run(() -> {
			ClientRegistry.registerScreen(TestContainers.BASIC, BasicTileEntityScreen::new);
			ClientRegistry.registerScreen(TestContainers.BASIC_ENERGY_CREATOR, BasicEnergyCreatorScreen::new);
			ClientRegistry.registerScreen(TestContainers.BASIC_FLUID_INVENTORY, BasicFluidInventoryScreen::new);
		});
	}

	public static void registerMod(IEventBus bus) {
		bus.addListener(TestScreens::setup);
	}
}

package info.u_team.u_team_test.init;

import info.u_team.u_team_core.util.registry.*;
import info.u_team.u_team_test.screen.*;
import net.minecraftforge.eventbus.api.IEventBus;
import net.minecraftforge.fml.event.lifecycle.FMLClientSetupEvent;

public class TestScreens {

	private static void setup(FMLClientSetupEvent event) {
		MainThreadWorker.run(() -> {
			ClientRegistry.registerScreen(TestContainers.BASIC, BasicTileEntityScreen::new);
			ClientRegistry.registerScreen(TestContainers.BASIC_ENERGY_CREATOR, BasicEnergyCreatorScreen::new);
			ClientRegistry.registerScreen(TestContainers.BASIC_FLUID_INVENTORY, BasicFluidInventoryScreen::new);
		});
	}

	public static void registerMod(IEventBus bus) {
		bus.addListener(TestScreens::setup);
	}
}

Make the listener method private now

Make the listener method private now


/**
 * @file Introductions.java
 * @author Valery Samovich
 * @version 1
 * @date 2015/04/07
 */

/**
 * TeamTreehouse. Java Basics.
 */
package com.samovich.basics.introduction.treehouse;

import java.io.Console;

public class Introductions {

    public static void main(String[] args) {
        Console console = System.console();
        // Welcome to the Introductions program!
        String firstName = "Valery";
        // thisIsAnExampleOfCamelCasing
        console.printf("Hello, my name is %s\n", firstName);
        console.printf("%s is learning how to write Java\n", firstName);
    }

}

/**
 * @file Introductions.java
 * @author Valery Samovich
 * @version 1
 * @date 2015/04/07
 */

package com.samovich.basics.introduction.treehouse;

import java.io.Console;

public class Introductions {

    public static void main(String[] args) throws NullPointerException{
        Console console = System.console();
        // Welcome to the Introductions program!
        String firstName;
        firstName = console.readLine("What is your name? ");
        // thisIsAnExampleOfCamelCasing
        console.printf("Hello, my name is %s\n", firstName);
        console.printf("%s is learning how to write Java\n", firstName);
    }

}

Add Introduction class for Team Treehouse example


package me.anky.connectid.data;

import java.util.List;

public class ConnectionsRepository implements ConnectionsDataSource {

    @Override
    public List<ConnectidConnection> getConnections() {
        return null;
    }
}

package me.anky.connectid.data;

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

public class ConnectionsRepository implements ConnectionsDataSource {

    @Override
    public List<ConnectidConnection> getConnections() {

        // Retrieve data from a real database and return it here.
        // Because I am having trouble wrapping my head around Loaders
        // and ContentProviders in the Model, I am just returning some fake
        // data in the List format expected by the Presenter.
        // There is something called Room which may do this job better.
        // Room deals with something it calls DAOs (database access objects)

        List<ConnectidConnection> connections = new ArrayList<>();
        connections.add(new ConnectidConnection("Aragorn", "you have my sword"));
        connections.add(new ConnectidConnection("Legolas", "and you have my bow"));
        connections.add(new ConnectidConnection("Gimli", "and my axe!"));
        connections.add(new ConnectidConnection("Gandalf", "fly, you fools!"));
        connections.add(new ConnectidConnection("Bilbo", "misses his ring"));
        connections.add(new ConnectidConnection("Frodo", "misses his finger"));
        connections.add(new ConnectidConnection("Boromir", "one does not simply"));

        return connections;
    }
}

Implement MVP on john branch

feat: Implement MVP on john branch


package com.zyeeda.framework.entities.base;

import javax.validation.constraints.NotNull;

@javax.persistence.MappedSuperclass
public class SimpleDomainEntity extends DomainEntity {

    private static final long serialVersionUID = -2200108673372668900L;

    private String name;
    private String description;

    @javax.persistence.Basic
    @javax.persistence.Column(name = "F_NAME")
    @NotNull
    public String getName() {
        return this.name;
    }
    public void setName(String name) {
        this.name = name;
    }

    @javax.persistence.Basic
    @javax.persistence.Column(name = "F_DESC", length = 2000)
    public String getDescription() {
        return this.description;
    }
    public void setDescription(String description) {
        this.description = description;
    }

}

package com.zyeeda.framework.entities.base;

import javax.validation.constraints.NotNull;

@javax.persistence.MappedSuperclass
public class SimpleDomainEntity extends DomainEntity {

    private static final long serialVersionUID = -2200108673372668900L;

    private String name;
    private String description;

    @javax.persistence.Basic
    @javax.persistence.Column(name = "F_NAME")
    public String getName() {
        return this.name;
    }
    public void setName(String name) {
        this.name = name;
    }

    @javax.persistence.Basic
    @javax.persistence.Column(name = "F_DESC", length = 2000)
    public String getDescription() {
        return this.description;
    }
    public void setDescription(String description) {
        this.description = description;
    }

}

Remove @NotNull annotation to name field.


/**
 * Waffle (https://github.com/dblock/waffle)
 *
 * Copyright (c) 2010 - 2014 Application Security, Inc.
 *
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *     Application Security, Inc.
 */
package waffle.servlet;

import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

import org.junit.Test;

import waffle.windows.auth.IWindowsAccount;
import waffle.windows.auth.IWindowsIdentity;

/**
 * @author Tony BenBrahim <tony.benbrahim@airliquide.com>
 *
 */
public class WindowsPrincipalTest {

	private static final String TEST_FQN = "ACME\\john.smith";

	@Test
	public void testToString() {
		final IWindowsIdentity windowsIdentity = mock(IWindowsIdentity.class);
		when(windowsIdentity.getFqn()).thenReturn(TEST_FQN);
		when(windowsIdentity.getGroups()).thenReturn(new IWindowsAccount[0]);
		final WindowsPrincipal principal = new WindowsPrincipal(windowsIdentity);
		assertEquals(TEST_FQN, principal.getName());
		assertEquals(TEST_FQN, principal.toString());
	}

}

Format Enforced & JDK8 proper Javadoc

Format Enforced & JDK8 proper Javadoc

this code appears built off earlier version of code prior to formatting.
So formatted.
JDK8 javadoc is incorrect.  Fixed it.


package edu.pdx.cs410J.web;

import org.junit.Test;

import java.io.IOException;
import java.net.HttpURLConnection;

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

/**
 * Unit tests for the HttpRequestHelper class
 */
public class HttpRequestHelperTest {

  private HttpRequestHelper helper = new HttpRequestHelper();

  @Test
  public void testGet() throws IOException {
    HttpRequestHelper.Response response = helper.get("http://www.google.com");
    assertEquals(HttpURLConnection.HTTP_OK, response.getCode());
    assertTrue(response.getContent().contains("Google"));
  }

  @Test
  public void testGetWithParameters() throws IOException {
    HttpRequestHelper.Response response = helper.get("http://search.yahoo.com/search", "p", "Java");
    assertEquals(HttpURLConnection.HTTP_OK, response.getCode());
    assertTrue(response.getContent().contains("Java"));

  }
}

package edu.pdx.cs410J.web;

import org.junit.Test;

import java.io.IOException;
import java.net.HttpURLConnection;

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

/**
 * Unit tests for the HttpRequestHelper class
 */
public class HttpRequestHelperTest {

  private HttpRequestHelper helper = new HttpRequestHelper();

  @Test
  public void testGet() throws IOException {
    HttpRequestHelper.Response response = helper.get("http://www.google.com");
    assertEquals(HttpURLConnection.HTTP_OK, response.getCode());
    assertTrue(response.getContent().contains("Google"));
  }

  @Test
  public void testGetWithParameters() throws IOException {
    HttpRequestHelper.Response response = helper.get("https://www.google.com/search", "p", "Java");
    assertEquals(HttpURLConnection.HTTP_OK, response.getCode());
    assertTrue(response.getContent().contains("Java"));

  }
}

Test the HttpRequestHelper by loading a google search URL instead of Yahoo. Yahoo recently changed something that broke this.


package gcUnrelatedTypes;

import java.util.ArrayList;
import java.util.HashSet;

public class ComplicatedParameterization {

	static class Foo<E> extends HashSet<ArrayList<E>> {}

	Foo<Integer> myFoo = new Foo<Integer>();

	void add(ArrayList<Integer> a) {
		myFoo.add(a);
	}

	boolean contains(ArrayList<Integer> a) {
		return myFoo.contains(a);
	}

}

package gcUnrelatedTypes;

import java.util.ArrayList;
import java.util.HashSet;

public class ComplicatedParameterization {

	static class Foo<E> extends HashSet<ArrayList<E>> {}

	Foo<Integer> myFoo = new Foo<Integer>();

	void add(ArrayList<Integer> a) {
		myFoo.add(a);
	}

	boolean falsePositive(ArrayList<Integer> a) {
		return myFoo.contains(a);
	}

}

Rename method -> false positive

Rename method -> false positive

git-svn-id: e7d6bde23f017c9ff4efd468d79d66def666766b@10321 eae3c2d3-9b19-0410-a86e-396b6ccb6ab3


package src;

public class Main {

    public static void main(String[] args) {

        if(args.length != 2)    // принимаем 3 аргумента - имя пользователя, игру и имя файла кода
            return;

        Tournament tournament = new Tournament(args[0], args[1], args[2]);

        int gameResult = tournament.Game();

        return;
    }
}

package src;

import java.io.IOException;

public class Main {

    public static void main(String[] args) {

        if(args.length != 3)    // принимаем 3 аргумента - имя пользователя, игру и имя файла кода
            return;

        Tournament tournament = new Tournament(args[0], args[1], args[2]);

        try {
            int gameResult = tournament.Game();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return;
    }
}

Add try...catch for IOException. There are many places, where this exception may appear.


package com.fernandocejas.java.samples.optional;

import com.fernandocejas.arrow.annotations.See;
import com.fernandocejas.arrow.strings.Strings;

@See(ref = "")
public class UseCaseScenario03 {

  public UseCaseScenario03() {
    //empty
  }

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

package com.fernandocejas.java.samples.optional;

import com.fernandocejas.arrow.annotations.See;
import com.fernandocejas.arrow.optional.Optional;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import rx.Observable;
import rx.functions.Action1;
import rx.functions.Func1;
import rx.schedulers.Schedulers;

@See(ref = "")
public class UseCaseScenario03 {

  public static final Func1<Optional<List<String>>, Observable<List<String>>> TO_AD_ITEM =
      new Func1<Optional<List<String>>, Observable<List<String>>>() {
        @Override public Observable<List<String>> call(Optional<List<String>> ads) {
          return ads.isPresent()
              ? Observable.just(ads.get())
              : Observable.just(Collections.<String>emptyList());
        }
      };

  public static final Func1<List<String>, Boolean> EMPTY_ELEMENTS =
      new Func1<List<String>, Boolean>() {
        @Override public Boolean call(List<String> ads) {
          return !ads.isEmpty();
        }
      };

  public UseCaseScenario03() {
    //empty
  }

  @Override public String toString() {
    final StringBuilder builder = new StringBuilder();
    feed().subscribe(new Action1<List<String>>() {
      @Override public void call(List<String> feed) {
        for (String feedElement : feed) {
          builder.append("\n").append(feedElement);
        }
      }
    });
    return builder.toString();
  }

  private Observable<List<String>> feed() {
    return ads()
        .flatMap(TO_AD_ITEM)
        .filter(EMPTY_ELEMENTS)
        .concatWith(users())
        .observeOn(Schedulers.immediate());
  }

  private Observable<List<String>> users() {
    return Observable.just(Arrays.asList("IronMan", "Wolverine", "Batman", "Superman"));
  }

  private Observable<Optional<List<String>>> ads() {
    return Observable.just(Optional.fromNullable(Collections.singletonList("This is and Ad")));
  }
}

Add third case scenario for Optional sample.


package org.badvision.outlaweditor.data;

import java.util.List;
import org.badvision.outlaweditor.Application;
import org.badvision.outlaweditor.data.xml.Global;
import org.badvision.outlaweditor.data.xml.NamedEntity;

public class DataUtilities {
    public static void ensureGlobalExists() {
        if (Application.gameData.getGlobal() == null) {
            Application.gameData.setGlobal(new Global());
        }
    }

    public static void sortNamedEntities(List<? extends NamedEntity> entities) {
        if (entities == null) {
            return;
        }
        entities.sort((a,b)->{
            String nameA = a == null ? "" : nullSafe(a.getName());
            String nameB = b == null ? "" : nullSafe(b.getName());
            return nameA.compareTo(nameB);
        });
    }

    public static String nullSafe(String str) {
        if (str == null) return "";
        return str;
    }

    public static String uppercaseFirst(String str) {
        StringBuilder b = new StringBuilder(str);
        int i = 0;
        do {
            b.replace(i, i + 1, b.substring(i, i + 1).toUpperCase());
            i = b.indexOf(" ", i) + 1;
        } while (i > 0 && i < b.length());
        return b.toString();
    }
}

package org.badvision.outlaweditor.data;

import java.util.List;
import org.badvision.outlaweditor.Application;
import org.badvision.outlaweditor.data.xml.Global;
import org.badvision.outlaweditor.data.xml.NamedEntity;

public class DataUtilities {
    public static void ensureGlobalExists() {
        if (Application.gameData.getGlobal() == null) {
            Application.gameData.setGlobal(new Global());
        }
    }

    public static void sortNamedEntities(List<? extends NamedEntity> entities) {
        if (entities == null) {
            return;
        }
        entities.sort((a,b)->{
            String nameA = a == null ? "" : nullSafe(a.getName());
            String nameB = b == null ? "" : nullSafe(b.getName());
            if (nameA.equalsIgnoreCase("init")) return -1;
            if (nameB.equalsIgnoreCase("init")) return 1;
            return nameA.compareTo(nameB);
        });
    }

    public static String nullSafe(String str) {
        if (str == null) return "";
        return str;
    }

    public static String uppercaseFirst(String str) {
        StringBuilder b = new StringBuilder(str);
        int i = 0;
        do {
            b.replace(i, i + 1, b.substring(i, i + 1).toUpperCase());
            i = b.indexOf(" ", i) + 1;
        } while (i > 0 && i < b.length());
        return b.toString();
    }
}

Put "init" as the topmost item in the sort again


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

package com.google.android.gnd.rx;

import javax.annotation.Nullable;

/** The result of an operation that can return either true, false, or fail with an exception. */
public class BooleanResult extends Result<Boolean> {
  private BooleanResult(@Nullable Boolean value, @Nullable Throwable error) {
    super(value, error);
  }

  public static BooleanResult ofTrue() {
    return new BooleanResult(true, null);
  }

  public static BooleanResult ofFalse() {
    return new BooleanResult(false, null);
  }

  public static BooleanResult error(Throwable t) {
    return new BooleanResult(null, t);
  }

  /**
   * Returns true if the operation succeeded with a result of {@code true}, or false otherwise. Note
   * that false is also returned if the operation failed in error.
   */
  public boolean isTrue() {
    return get().orElse(false);
  }
}

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

package com.google.android.gnd.rx;

import javax.annotation.Nullable;

/** The result of an operation that can return either true, false, or fail with an exception. */
public class BooleanResult extends Result<Boolean> {
  private BooleanResult(@Nullable Boolean value, @Nullable Throwable error) {
    super(value, error);
  }

  public static BooleanResult ofTrue() {
    return new BooleanResult(true, null);
  }

  public static BooleanResult ofFalse() {
    return new BooleanResult(false, null);
  }

  public static BooleanResult error(Throwable t) {
    return new BooleanResult(null, t);
  }

  /**
   * Returns true if the operation succeeded with a result of {@code true}, or false otherwise. Note
   * that false is also returned if the operation failed in error.
   */
  public boolean isTrue() {
    return get().orElse(false);
  }
}

Correct copyright on new file

Correct copyright on new file


package com.chrisdempewolf.pinterest.methods.network;

import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.IOException;

public class NetworkHelper {

    public static ResponseMessageAndStatusCode submitDeleteRequest(final HttpDelete httpDelete) throws IOException {
        try (final CloseableHttpResponse response = HttpClients.createDefault().execute(httpDelete)) {
            final String responseBody = EntityUtils.toString(response.getEntity());
            final int statusCode = response.getStatusLine().getStatusCode();

            return new ResponseMessageAndStatusCode(statusCode, responseBody);
        }
    }
}

package com.chrisdempewolf.pinterest.methods.network;

import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.IOException;

public class NetworkHelper {

    public static ResponseMessageAndStatusCode submitDeleteRequest(final HttpDelete httpDelete) throws IOException {
        return submitRequest(httpDelete);
    }

    public static ResponseMessageAndStatusCode submitPostRequest(final HttpPost httpPost) throws IOException {
        return submitRequest(httpPost);
    }

    private static ResponseMessageAndStatusCode submitRequest(final HttpRequestBase httpRequestBase) throws IOException {
        try (final CloseableHttpResponse response = HttpClients.createDefault().execute(httpRequestBase)) {
            final String responseBody = EntityUtils.toString(response.getEntity());
            final int statusCode = response.getStatusLine().getStatusCode();

            return new ResponseMessageAndStatusCode(statusCode, responseBody);
        }
    }
}

Update network helper to include POST requests


/*
 * Copyright (C) 2014 Pedro Vicente Gómez Sánchez.
 *
 * 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.github.pedrovgs.problem63;

/**
 * How would you design an integer stack which, in addition to push and pop, also has a function
 * min which returns the minimum element? Push, pop and min should all operate in 0(1) time.
 *
 * @author Pedro Vicente Gómez Sánchez.
 */
public class ConstantComplexityOrderStack {

}

/*
 * Copyright (C) 2014 Pedro Vicente Gómez Sánchez.
 *
 * 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.github.pedrovgs.problem63;

import java.util.Stack;

/**
 * How would you design an integer stack which, in addition to push and pop, also has a function
 * min which returns the minimum element? Push, pop and min should all operate in 0(1) time.
 *
 * @author Pedro Vicente Gómez Sánchez.
 */
public class ConstantComplexityOrderStack {

  /**
   * Approach based on a inner data structure to store the stack of integers and in the same object
   * the current min value we had when the element was pushed. With this approach we get a time
   * complexity order equals to O(1) but a space complexity order equals to O(N) where N is the
   * number of elements in the stack.
   */
  public static class Stack1 extends Stack<MinValue> {

    public void push(int item) {
      int newMin = Math.min(item, getMin());
      super.push(new MinValue(item, newMin));
    }

    public int getMin() {
      if (isEmpty()) {
        return Integer.MAX_VALUE;
      } else {
        return peek().minValue;
      }
    }
  }

  static class MinValue {
    final int value;
    final int minValue;

    MinValue(int value, int minValue) {
      this.value = value;
      this.minValue = minValue;
    }
  }
}

Add first implementation to problem 63

Add first implementation to problem 63


// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.config.provision.zone;

import com.yahoo.config.provision.CloudName;
import com.yahoo.config.provision.Environment;
import com.yahoo.config.provision.RegionName;
import com.yahoo.config.provision.SystemName;

/**
 * @author hakonhall
 */
public interface ZoneApi {

    SystemName getSystemName();

    ZoneId getId();

    /** Returns the SYSTEM.ENVIRONMENT.REGION string. */
    default String getFullName() {
        return getSystemName().value() + "." + getEnvironment().value() + "." + getRegionName().value();
    }

    /**
     * Returns the virtual ID of this zone. For ordinary zones this is the same as {@link ZoneApi#getId()}, for a
     * system represented as a zone this is a fixed ID that is independent of the actual zone ID.
     */
    default ZoneId getVirtualId() {
        return getId();
    }

    default Environment getEnvironment() { return getId().environment(); }

    default RegionName getRegionName() { return getId().region(); }

    CloudName getCloudName();

    /** Returns the region name within the cloud, e.g. 'us-east-1' in AWS */
    String getCloudNativeRegionName();

}

// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.config.provision.zone;

import com.yahoo.config.provision.CloudName;
import com.yahoo.config.provision.Environment;
import com.yahoo.config.provision.RegionName;
import com.yahoo.config.provision.SystemName;

/**
 * @author hakonhall
 */
public interface ZoneApi {

    SystemName getSystemName();

    /**
     * Returns the ID of the zone.
     *
     * WARNING: The ID of a controller zone is equal to the ID of a prod zone in the same region.
     * @see #getVirtualId()
     */
    ZoneId getId();

    /** Returns the SYSTEM.ENVIRONMENT.REGION string. */
    default String getFullName() {
        return getSystemName().value() + "." + getEnvironment().value() + "." + getRegionName().value();
    }

    /**
     * Returns {@link #getId()} for all zones except the controller zone.  Unlike {@link #getId()},
     * the virtual ID of a controller is distinct from all other zones.
     */
    default ZoneId getVirtualId() {
        return getId();
    }

    default Environment getEnvironment() { return getId().environment(); }

    default RegionName getRegionName() { return getId().region(); }

    CloudName getCloudName();

    /** Returns the region name within the cloud, e.g. 'us-east-1' in AWS */
    String getCloudNativeRegionName();

}

Document difference between ID and virtual ID


package io.reon.http;

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

public class ResponseReader extends MessageReader {

	public ResponseReader(InputStream is) {
		super(is);
	}

	public Response read() throws IOException {
		Response resp = parse(readHeader());
		if (resp == null) return null;
		return ResponseBuilder.with(resp).withBody(input).build();
	}

	public static Response parse(String req) throws HttpBadRequestException {
		if (req == null || req.length() == 0) return null;
		String[] lines = req.split("\\r\\n", 2);
		String[] segments = lines[0].split(" ");
		String protocolVersion = segments[0];
		StatusCode sc = StatusCode.byValue(Integer.parseInt(segments[1]));
		String reason = null;
		if(segments.length>=3) {
			reason = lines[0].substring(lines[0].indexOf(segments[2]));
		}
		Headers headers = Headers.parse(lines[1]);
		return new Response(protocolVersion, sc, reason, headers);
	}
}

package io.reon.http;

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

public class ResponseReader extends MessageReader {

	public ResponseReader(InputStream is) {
		super(is);
	}

	public Response read() throws IOException {
		Response resp = parse(readHeader());
		if (resp == null) return null;
		return ResponseBuilder.with(resp).withBody(input).build();
	}

	public static Response parse(String req) throws HttpBadRequestException {
		if (req == null || req.length() == 0) return null;
		String[] lines = req.split("\\r\\n", 2);
		String[] segments = lines[0].split(" ");
		String protocolVersion = segments[0];
		StatusCode sc = StatusCode.byValue(Integer.parseInt(segments[1]));
		String reason = null;
		if(segments.length>=3) {
			reason = lines[0].substring(lines[0].indexOf(segments[2]));
		}
		Headers headers;
		if (lines.length > 1) {
			headers = Headers.parse(lines[1]);
		} else {
			headers = new Headers();
		}
		return new Response(protocolVersion, sc, reason, headers);
	}
}

Fix for one line HTTP responses

Fix for one line HTTP responses


package de.stephanlindauer.criticalmaps.model;

import android.app.Activity;
import android.provider.Settings;

import de.stephanlindauer.criticalmaps.utils.AeSimpleSHA1;

public class UserModel {

    //singleton
    private static UserModel instance;

    private String uniqueDeviceIdHashed;

    public static UserModel getInstance() {
        if (UserModel.instance == null) {
            UserModel.instance = new UserModel();
        }
        return UserModel.instance;
    }

    public void initialize(Activity activity) {
        this.uniqueDeviceIdHashed = AeSimpleSHA1.SHA1(Settings.Secure.getString(activity.getContentResolver(),
                Settings.Secure.ANDROID_ID));
    }

    public String getUniqueDeviceIdHashed() {
        return uniqueDeviceIdHashed;
    }
}

package de.stephanlindauer.criticalmaps.model;

import android.app.Activity;
import android.provider.Settings;
import de.stephanlindauer.criticalmaps.utils.AeSimpleSHA1;

import static android.provider.Settings.Secure.getString;

public class UserModel {

    //singleton
    private static UserModel instance;

    private String uniqueDeviceIdHashed;

    public static UserModel getInstance() {
        if (UserModel.instance == null) {
            UserModel.instance = new UserModel();
        }
        return UserModel.instance;
    }

    public void initialize(Activity activity) {
        final String androidId = getString(activity.getContentResolver(), Settings.Secure.ANDROID_ID);
        uniqueDeviceIdHashed = AeSimpleSHA1.SHA1(androidId);
    }

    public String getUniqueDeviceIdHashed() {
        return uniqueDeviceIdHashed;
    }
}

Break down really long line

Break down really long line