/****************************************************************************
 * Copyright (C) 2012 ecsec GmbH.
 * All rights reserved.
 * Contact: ecsec GmbH (info@ecsec.de)
 *
 * This file is part of the Open eCard App.
 *
 * GNU General Public License Usage
 * This file may be used under the terms of the GNU General Public
 * License version 3.0 as published by the Free Software Foundation
 * and appearing in the file LICENSE.GPL included in the packaging of
 * this file. Please review the following information to ensure the
 * GNU General Public License version 3.0 requirements will be met:
 * http://www.gnu.org/copyleft/gpl.html.
 *
 * Other Usage
 * Alternatively, this file may be used in accordance with the terms
 * and conditions contained in a signed written agreement between
 * you and ecsec GmbH.
 *
 ***************************************************************************/

package org.openecard.control.module.tctoken.hacks;

/**
 * @author Moritz Horsch <horsch@cdc.informatik.tu-darmstadt.de>
 */
public class PathSecurityParameters {

    public static String fix(String input) {
	if (!input.contains("PathSecurity-Parameters")) {
	    input = input.replace("PathSecurity-Parameter", "PathSecurity-Parameters");
	}
	return input;
    }

}

/****************************************************************************
 * Copyright (C) 2012 ecsec GmbH.
 * All rights reserved.
 * Contact: ecsec GmbH (info@ecsec.de)
 *
 * This file is part of the Open eCard App.
 *
 * GNU General Public License Usage
 * This file may be used under the terms of the GNU General Public
 * License version 3.0 as published by the Free Software Foundation
 * and appearing in the file LICENSE.GPL included in the packaging of
 * this file. Please review the following information to ensure the
 * GNU General Public License version 3.0 requirements will be met:
 * http://www.gnu.org/copyleft/gpl.html.
 *
 * Other Usage
 * Alternatively, this file may be used in accordance with the terms
 * and conditions contained in a signed written agreement between
 * you and ecsec GmbH.
 *
 ***************************************************************************/

package org.openecard.control.module.tctoken.hacks;

/**
 * @author Moritz Horsch <horsch@cdc.informatik.tu-darmstadt.de>
 */
public class PathSecurityParameters {

    public static String fix(String input) {
	if (! input.contains("PathSecurity-Parameters")) {
	    input = input.replace("PathSecurity-Parameter", "PathSecurity-Parameters");
	}
	if (input.contains("<PSK>")) {
	    input = input.replace("<PSK>", "<PSK>");
	}
	if (input.contains("</PSK>")) {
	    input = input.replace("</PSK>", "</PSK>");
	}
	return input;
    }

}

Add further workaround for PathSecurity-Parameters PSK content


package ee.ioc.phon.android.arvutaja.command;

import ee.ioc.phon.android.arvutaja.R;
import android.content.Context;

public class CommandParser {

	public static Command getCommand(Context context, String command) throws CommandParseException {
		if (command == null) {
			throw new CommandParseException();
		}

		if (Alarm.isCommand(command))
			return new Alarm(command, context.getString(R.string.alarmExtraMessage));

		if (Dial.isCommand(command))
			return new Dial(command);

		if (Expr.isCommand(command))
			return new Expr(command);

		if (Search.isCommand(command))
			return new Search(command);

		if (Unitconv.isCommand(command))
			return new Unitconv(command);

		if (Direction.isCommand(command))
			return new Direction(command);

		return new DefaultCommand(command);
	}

}

package ee.ioc.phon.android.arvutaja.command;

import ee.ioc.phon.android.arvutaja.R;
import android.content.Context;

public class CommandParser {

	public static Command getCommand(Context context, String command) throws CommandParseException {
		if (command == null) {
			throw new CommandParseException();
		}

		if (Alarm.isCommand(command))
			return new Alarm(command, context.getString(R.string.alarmExtraMessage));

		if (command.startsWith("weather "))
			return new DefaultCommand(command);

		if (Dial.isCommand(command))
			return new Dial(command);

		if (Expr.isCommand(command))
			return new Expr(command);

		if (Search.isCommand(command))
			return new Search(command);

		if (Unitconv.isCommand(command))
			return new Unitconv(command);

		if (Direction.isCommand(command))
			return new Direction(command);

		return new DefaultCommand(command);
	}

}

Add support for weather queries

Add support for weather queries


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

package com.consol.citrus.samples.common.exceptions;

import org.springframework.integration.core.Message;
import org.springframework.integration.message.MessageHandlingException;

/**
 * @author Christoph Deppisch
 */
public class XmlSchemaValidationException extends MessageHandlingException {

    private static final long serialVersionUID = 1L;

    /**
     * @param failedMessage
     */
    public XmlSchemaValidationException(Message<?> failedMessage, Throwable cause) {
        super(failedMessage, cause);
    }
}

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

package com.consol.citrus.samples.common.exceptions;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.integration.core.Message;
import org.springframework.integration.message.MessageHandlingException;

/**
 * @author Christoph Deppisch
 */
public class XmlSchemaValidationException extends MessageHandlingException {

    private static final long serialVersionUID = 1L;

    /**
     * Logger
     */
    private static final Logger log = LoggerFactory.getLogger(XmlSchemaValidationException.class);

    /**
     * @param failedMessage
     */
    public XmlSchemaValidationException(Message<?> failedMessage, Throwable cause) {
        super(failedMessage);

        log.error("Schema validation error", cause);
    }
}

Print XML valdation error cause for information purpose


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

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import com.mongodb.MongoClient;

/**
 * MongoDB detector auto configuration, depending on MongoDb classes being
 * available on the classpath. Requires a separate configuration class to
 * prevent issues with optional classes.
 *
 * @author lwarrot
 */
@Configuration
@ConditionalOnClass(MongoClient.class)
public class MongoDbRelationshipDetectorAutoConfiguration {

    @Autowired
    private List<MongoClient> clients;

    @Bean
    public MongoDbRelationshipDetector mongoDBRelationshipDetector() {
        return new MongoDbRelationshipDetector(clients);
    }

}

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

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import com.mongodb.MongoClient;

/**
 * MongoDB detector auto configuration, depending on MongoDb classes being
 * available on the classpath. Requires a separate configuration class to
 * prevent issues with optional classes.
 *
 * @author lwarrot
 */
@Configuration
@ConditionalOnClass(MongoClient.class)
public class MongoDbRelationshipDetectorAutoConfiguration {

    @Autowired(required = false)
    private List<MongoClient> clients;

    @Bean
    public MongoDbRelationshipDetector mongoDBRelationshipDetector() {
        return new MongoDbRelationshipDetector(clients);
    }

}

Make MongoDb config's dependencies optional


package com.redhat.ceylon.common;

public enum Backend {
    None("", BackendSupport.HEADER),
    Java("java", BackendSupport.JAVA),
    JavaScript("js", BackendSupport.JAVASCRIPT);

    public final String nativeAnnotation;
    public final BackendSupport backendSupport;

    Backend(String nativeAnnotation, BackendSupport backendSupport) {
        this.nativeAnnotation = nativeAnnotation;
        this.backendSupport = backendSupport;
    }

    public static boolean validAnnotation(String backend) {
        return fromAnnotation(backend) != null;
    }

    public static Backend fromAnnotation(String backend) {
        for (Backend b : Backend.values()) {
            if (b.nativeAnnotation.equals(backend)) {
                return b;
            }
        }
        return null;
    }

}

package com.redhat.ceylon.common;

public enum Backend {
    None("", BackendSupport.HEADER),
    Java("jvm", BackendSupport.JAVA),
    JavaScript("js", BackendSupport.JAVASCRIPT);

    public final String nativeAnnotation;
    public final BackendSupport backendSupport;

    Backend(String nativeAnnotation, BackendSupport backendSupport) {
        this.nativeAnnotation = nativeAnnotation;
        this.backendSupport = backendSupport;
    }

    public static boolean validAnnotation(String backend) {
        return fromAnnotation(backend) != null;
    }

    public static Backend fromAnnotation(String backend) {
        for (Backend b : Backend.values()) {
            if (b.nativeAnnotation.equals(backend)) {
                return b;
            }
        }
        return null;
    }

}

Revert "Annotation for Java backend renamed from "jvm" to "java""

This reverts commit d965d39bd33cbb8efde7c815537bdf02d4c287c8.


package editor;

import javax.swing.*;
import java.awt.*;

/**
 * The NewRootView is used to create the GUI that is used to create a new root
 * XML element.
 */
public class NewRootView extends JFrame {
    private NewRootController controller;
    private JTextField rootTagField;

    /**
     * Create the view and set up the look of the GUI
     * @param newRootController The controller with which to associate the
     *                          view. This controller will update the model.
     */
    public NewRootView(NewRootController newRootController) {
        controller = newRootController;

        setSize(400, 60);
        setTitle("New Root Element");
        setLayout(new FlowLayout());

        add(new JLabel("Root Tag"));
        rootTagField = new JTextField("", 20);
        add(rootTagField);
        JButton okButton = new JButton("OK");
        okButton.addActionListener(controller);
        add(okButton);

        setVisible(true);
    }

    /**
     * Get the root tag as set by the text field
     * @return The value of the root tag text field
     */
    public String getRootTag() {
        return rootTagField.getText();
    }

    /**
     * Get rid of this view (close the window)
     */
    public void teardown() {
        setVisible(false);
        dispose();
    }
}

package editor;

import javax.swing.*;
import java.awt.*;

/**
 * The NewRootView is used to create the GUI that is used to create a new root
 * XML element.
 */
public class NewRootView extends JFrame {
    private JTextField rootTagField;

    /**
     * Create the view and set up the look of the GUI
     * @param newRootController The controller with which to associate the
     *                          view. This controller will update the model.
     */
    public NewRootView(NewRootController newRootController) {
        setSize(400, 60);
        setTitle("New Root Element");
        setLayout(new FlowLayout());

        add(new JLabel("Root Tag"));
        rootTagField = new JTextField("", 20);
        add(rootTagField);
        JButton okButton = new JButton("OK");
        okButton.addActionListener(newRootController);
        add(okButton);

        setVisible(true);
    }

    /**
     * Get the root tag as set by the text field
     * @return The value of the root tag text field
     */
    public String getRootTag() {
        return rootTagField.getText();
    }

    /**
     * Get rid of this view (close the window)
     */
    public void teardown() {
        setVisible(false);
        dispose();
    }
}

Remove controller view from view (redundant)


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

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

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

        String cache = System.getenv("KRB5CCNAME");
        if (cache == null) {
            System.err.println("Uh-oh, KRB5CCNAME is not set.  Quitting.");
            return;
        }

        // The FileCredentialsCache does not want to see the "FILE:" prefix
        if ((cache.length() >= 5)
                && cache.substring(0,5).equalsIgnoreCase("FILE:")) {
            cache = cache.substring(5);
        }

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

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

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

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

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

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

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

Exit silently if ccache is not found or empty.


package todomore.android;

import org.metawidget.android.widget.AndroidMetawidget;

import com.darwinsys.todo.model.Task;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;

public class DetailsActivity extends Activity {

	private Task mTask;

	public void onCreate(Bundle saved) {
		super.onCreate(saved);
		setContentView(R.layout.details_activity);

		long id = getIntent().getLongExtra("taskId", -1);

		if (id != -1) {
			mTask = ((TodoMoreApplication) getApplication()).getTaskDao().findById(id);
		} else {
			mTask = new AndroidTask();
		}

		final AndroidMetawidget metawidget =
			(AndroidMetawidget) findViewById(R.id.metawidget);
        metawidget.setToInspect(mTask);
        if ( id == -1) {
            metawidget.setReadOnly(false);
        }

        if (!metawidget.isReadOnly()) {
            metawidget.buildWidgets();
            View view = metawidget.findViewWithTag("name");
            view.setFocusable(true);
            view.setFocusableInTouchMode(true);
            view.requestFocus();
        }
	}
}

package todomore.android;

import org.metawidget.android.widget.AndroidMetawidget;

import com.darwinsys.todo.model.Task;

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

/**
 * An Activity that shows all the Details of one Task, using MetaWidget.
 * It starts in display mode, but an Edit button makes it editable.
 * @author Ian Darwin
 */
public class DetailsActivity extends Activity {

	private static final String TAG = DetailsActivity.class.getSimpleName();
	private Task mTask;
	private AndroidMetawidget mMetawidget;

	public void onCreate(Bundle saved) {
		super.onCreate(saved);
		setContentView(R.layout.details_activity);

		long id = getIntent().getLongExtra("taskId", -1);
		Log.d(TAG, "_id = " + id);
		if (id != -1) {
			mTask = ((TodoMoreApplication) getApplication()).getTaskDao().findById(id);
		} else {
			mTask = new AndroidTask();
		}

		mMetawidget = (AndroidMetawidget) findViewById(R.id.metawidget);
        mMetawidget.setToInspect(mTask);
        if (id == -1) {
            mMetawidget.setReadOnly(false);
        }

        if (!mMetawidget.isReadOnly()) {
            mMetawidget.buildWidgets();
            View view = mMetawidget.findViewWithTag("name");
            view.setFocusable(true);
            view.setFocusableInTouchMode(true);
            view.requestFocus();
        }
	}

	public void enableEditing(View v) {
		Log.d(TAG, "enableEditing");
		mMetawidget.setReadOnly(false);
	}
}

Make metawidget object a field so enableEditing() can find it


package editor.gui.ccp.handler;

import java.awt.datatransfer.Transferable;
import java.util.Collection;
import java.util.function.Supplier;

import javax.swing.JComponent;
import javax.swing.TransferHandler;

import editor.database.card.Card;
import editor.gui.ccp.data.CardTransferData;

@SuppressWarnings("serial")
public class InventoryExportHandler extends TransferHandler
{
    private final Supplier<? extends Collection<? extends Card>> cards;

    public InventoryExportHandler(Supplier<? extends Collection<? extends Card>> c)
    {
        cards = c;
    }

    @Override
    public int getSourceActions(JComponent c)
    {
        return TransferHandler.COPY;
    }

    @Override
    public Transferable createTransferable(JComponent c)
    {
        return new CardTransferData(cards.get());
    }
}

package editor.gui.ccp.handler;

import java.awt.datatransfer.Transferable;
import java.util.Collection;
import java.util.function.Supplier;

import javax.swing.JComponent;
import javax.swing.TransferHandler;

import editor.database.card.Card;
import editor.gui.ccp.data.CardTransferData;

/**
 * This class is a handler for expording copied data from the inventory. It only
 * supports copying single copies of cards.
 */
@SuppressWarnings("serial")
public class InventoryExportHandler extends TransferHandler
{
    /** Function for generating the list of cards to export. */
    private final Supplier<? extends Collection<? extends Card>> cards;

    /**
     * Create a new inventory export handler that determines the cards to export
     * using the given function.
     *
     * @param c supplier of the list of cards to export
     */
    public InventoryExportHandler(Supplier<? extends Collection<? extends Card>> c)
    {
        cards = c;
    }

    @Override
    public int getSourceActions(JComponent c)
    {
        return TransferHandler.COPY;
    }

    @Override
    public Transferable createTransferable(JComponent c)
    {
        return new CardTransferData(cards.get());
    }
}

Add documentation to inventory exporter

Add documentation to inventory exporter


package org.reactfx;

public interface Subscription {
    void unsubscribe();

    static final Subscription EMPTY = () -> {};

    static Subscription multi(Subscription... subscriptions) {
        return () -> {
            for(Subscription s: subscriptions) {
                s.unsubscribe();
            }
        };
    }
}

package org.reactfx;

@FunctionalInterface
public interface Subscription {
    void unsubscribe();

    static final Subscription EMPTY = () -> {};

    static Subscription multi(Subscription... subs) {
        switch(subs.length) {
            case 0: return EMPTY;
            case 1: return subs[0];
            case 2: return new BiSubscription(subs[0], subs[1]);
            default: return new MultiSubscription(subs);
        }
    }
}

class BiSubscription implements Subscription {
    private final Subscription s1;
    private final Subscription s2;

    public BiSubscription(Subscription s1, Subscription s2) {
        this.s1 = s1;
        this.s2 = s2;
    }

    @Override
    public void unsubscribe() {
        s1.unsubscribe();
        s2.unsubscribe();
    }
}

class MultiSubscription implements Subscription {
    private final Subscription[] subscriptions;

    public MultiSubscription(Subscription... subscriptions) {
        this.subscriptions = subscriptions;
    }

    @Override
    public void unsubscribe() {
        for(Subscription s: subscriptions) {
            s.unsubscribe();
        }
    }
}

Add specialized implementation for bi-subscription


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

package com.facebook.buck.sqlite;

import org.sqlite.SQLiteJDBCLoader;

public class SQLiteUtils {
  private SQLiteUtils() {
    // This class cannot be instantiated
  }

  /**
   * Initializes the JDBC loader statically to avoid sqlite-jdbc loading its JNI library in a
   * thread-unsafe manner. This method should be called statically from any class that uses
   * SQLiteJDBC.
   */
  public static void initialize() {
    try {
      SQLiteJDBCLoader.initialize();
    } catch (Exception e) {
      throw new RuntimeException(e);
    }
  }
}

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

package com.facebook.buck.sqlite;

import org.sqlite.SQLiteJDBCLoader;

public class SQLiteUtils {
  private SQLiteUtils() {
    // This class cannot be instantiated
  }

  /**
   * Initializes the JDBC loader statically to avoid sqlite-jdbc loading its JNI library in a
   * thread-unsafe manner. This method should be called statically from any class that uses
   * SQLiteJDBC.
   */
  public static void initialize() {
    try {
      if (!SQLiteJDBCLoader.initialize()) {
        throw new RuntimeException("sqlite-jdbc initialization failed");
      }
    } catch (Exception e) {
      throw new RuntimeException(e);
    }
  }
}

Throw an exception when SQLiteJDBC initialization fails

Summary:
When sqlite-jdbc can't unpack its .so (e.g., if the disk is full), it
sometimes returns an error code instead of throwing.  Notice this and throw our
own error, rather than continuing until we hit a mysterious UnsatisfiedLinkError

Test Plan: create a tiny disk image to house buck-out and try some builds

Reviewed By: dinhviethoa

fbshipit-source-id: b8258a4


package in.twizmwaz.cardinal.util;

import org.bukkit.Material;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import org.bukkit.potion.PotionEffect;

public class PlayerUtil {

    public static void resetPlayer(Player player) {
        player.setMaxHealth(20);
        player.setFoodLevel(20);
        player.setSaturation(20);
        player.getInventory().clear();
        player.getInventory().setArmorContents(new ItemStack[]{new ItemStack(Material.AIR), new ItemStack(Material.AIR), new ItemStack(Material.AIR), new ItemStack(Material.AIR)});
        for (PotionEffect effect : player.getActivePotionEffects()) {
            try {
                player.removePotionEffect(effect.getType());
            } catch (NullPointerException e) {
            }
        }
        player.clearIgnorantEffects();
        player.setWalkSpeed(0.2F);
    }
}

package in.twizmwaz.cardinal.util;

import org.bukkit.Material;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import org.bukkit.potion.PotionEffect;

public class PlayerUtil {

    public static void resetPlayer(Player player) {
        player.setMaxHealth(20);
        player.setHealth(20);
        player.setFoodLevel(20);
        player.setSaturation(20);
        player.getInventory().clear();
        player.getInventory().setArmorContents(new ItemStack[]{new ItemStack(Material.AIR), new ItemStack(Material.AIR), new ItemStack(Material.AIR), new ItemStack(Material.AIR)});
        for (PotionEffect effect : player.getActivePotionEffects()) {
            try {
                player.removePotionEffect(effect.getType());
            } catch (NullPointerException e) {
            }
        }
        player.clearIgnorantEffects();
        player.setWalkSpeed(0.2F);
    }
}

Fix observers dropping their items when joining after dying, but not respawning


package io.mkremins.whydah.interpreter;

import io.mkremins.whydah.ast.Expression;
import io.mkremins.whydah.ast.ExpressionUtils;

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

public class Scope {

	private final Map<String, Expression> vars;
	private final Scope parent;

	public Scope(final Scope parent) {
		vars = new HashMap<>();
		this.parent = parent;
	}

	public Scope() {
		this(null);
	}

	public void delete(final String varName) {
		getDeclaringScope(varName).vars.remove(varName);
	}

	public Expression get(final String varName) {
		return getDeclaringScope(varName).vars.get(varName);
	}

	public void set(final String varName, final Expression value) {
		Scope scope = getDeclaringScope(varName);
		if (scope == null) {
			scope = this;
		}
		scope.vars.put(varName, ExpressionUtils.fullyEvaluate(value, scope));
	}

	private Scope getDeclaringScope(final String varName) {
		Scope scope = this;
		while (scope != null && scope.vars.get(varName) == null) {
			scope = scope.parent;
		}
		return scope;
	}

}

package io.mkremins.whydah.interpreter;

import io.mkremins.whydah.ast.Expression;
import io.mkremins.whydah.ast.ExpressionUtils;

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

public class Scope {

	private final Map<String, Expression> vars;
	private final Scope parent;

	public Scope(final Scope parent) {
		vars = new HashMap<String, Expression>();
		this.parent = parent;
	}

	public Scope() {
		this(null);
	}

	public void delete(final String varName) {
		getDeclaringScope(varName).vars.remove(varName);
	}

	public Expression get(final String varName) {
		return getDeclaringScope(varName).vars.get(varName);
	}

	public void set(final String varName, final Expression value) {
		Scope scope = getDeclaringScope(varName);
		if (scope == null) {
			scope = this;
		}
		scope.vars.put(varName, ExpressionUtils.fullyEvaluate(value, scope));
	}

	private Scope getDeclaringScope(final String varName) {
		Scope scope = this;
		while (scope != null && scope.vars.get(varName) == null) {
			scope = scope.parent;
		}
		return scope;
	}

}

Make project Java 6 compliant

Make project Java 6 compliant


package com.cadyyan.levels.skills;

public interface ISkill
{
	public String getUnlocalizedName();
}

package com.cadyyan.levels.skills;

public interface ISkill
{
	String getUnlocalizedName();
}

Remove uncessary public on interface

Remove uncessary public on interface


package org.gluu.oxtrust.model.scim2;

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

/**
 * @author Rahat Ali Date: 05.08.2015
 * Udpated by jgomer on 2017-10-01.
 */
public class ListResponse {

    private int totalResults;
    private int startIndex;
    private int itemsPerPage;

    private List<BaseScimResource> resources;

    public ListResponse(int sindex, int ippage){
        totalResults=0;
        startIndex=sindex;
        itemsPerPage=ippage;
        resources =new ArrayList<BaseScimResource>();
    }

    public void addResource(BaseScimResource resource){
        resources.add(resource);
        totalResults++;
    }

    public int getTotalResults() {
        return totalResults;
    }

    public int getStartIndex() {
        return startIndex;
    }

    public int getItemsPerPage() {
        return itemsPerPage;
    }

    public List<BaseScimResource> getResources() {
        return resources;
    }

}

package org.gluu.oxtrust.model.scim2;

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

/**
 * @author Rahat Ali Date: 05.08.2015
 * Udpated by jgomer on 2017-10-01.
 */
public class ListResponse {

    private int totalResults;
    private int startIndex;
    private int itemsPerPage;

    private List<BaseScimResource> resources;

    public ListResponse(int sindex, int ippage, int total){
        totalResults=total;
        startIndex=sindex;
        itemsPerPage=ippage;
        resources =new ArrayList<BaseScimResource>();
    }

    public void addResource(BaseScimResource resource){
        resources.add(resource);
    }

    public int getTotalResults() {
        return totalResults;
    }

    public int getStartIndex() {
        return startIndex;
    }

    public int getItemsPerPage() {
        return itemsPerPage;
    }

    public List<BaseScimResource> getResources() {
        return resources;
    }

    public void setResources(List<BaseScimResource> resources) {
        this.resources = resources;
    }

}

Add total results to class constructor

Add total results to class constructor


package mireka.maildata;

import static org.junit.Assert.*;

import java.text.ParseException;

import org.junit.Test;

public class QEncodingParserTest extends QEncodingParser {

    private String in1 = "hi";
    private byte[] out1 = { 'h', 'i' };

    private String in2 = "h=69_jon";
    private byte[] out2 = { 'h', 'i', ' ', 'j', 'o', 'n' };

    @Test
    public void testSimple() throws ParseException {
        QEncodingParser parser = new QEncodingParser();
        byte[] result = parser.decode(in1);
        assertArrayEquals(out1, result);
    }

    @Test
    public void testComplex() throws ParseException {
        QEncodingParser parser = new QEncodingParser();
        byte[] result = parser.decode(in1);
        assertArrayEquals(out1, result);
    }
}

package mireka.maildata;

import static org.junit.Assert.*;

import java.text.ParseException;

import org.junit.Test;

public class QEncodingParserTest extends QEncodingParser {

    private String in1 = "hi";
    private byte[] out1 = { 'h', 'i' };

    private String in2 = "h=69_jon";
    private byte[] out2 = { 'h', 'i', ' ', 'j', 'o', 'n' };

    @Test
    public void testSimple() throws ParseException {
        QEncodingParser parser = new QEncodingParser();
        byte[] result = parser.decode(in1);
        assertArrayEquals(out1, result);
    }

    @Test
    public void testComplex() throws ParseException {
        QEncodingParser parser = new QEncodingParser();
        byte[] result = parser.decode(in2);
        assertArrayEquals(out2, result);
    }
}

Test data was not used

test: Test data was not used


package io.github.plastix.forage.data.local;

import android.location.Location;

import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;

import io.github.plastix.forage.ForageRoboelectricUnitTestRunner;
import io.github.plastix.forage.data.local.model.RealmLocation;

import static com.google.common.truth.Truth.assertThat;

@Ignore("Roboelectric problems")
@RunWith(ForageRoboelectricUnitTestRunner.class)
public class RealmLocationTest {

    @Test
    public void toLocation_shouldReturnCorrectLocation() {
        double lat = 40.7127;
        double lon = 74.0059;

        RealmLocation realmLocation = new RealmLocation();
        realmLocation.latitude = lat;
        realmLocation.longitude = lon;

        Location location = realmLocation.toLocation();

        assertThat(location.getLatitude()).isWithin(0.0).of(lat);
        assertThat(location.getLongitude()).isWithin(0.0).of(lon);
    }
}

package io.github.plastix.forage.data.local;

import android.location.Location;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;

import io.github.plastix.forage.data.local.model.RealmLocation;
import io.github.plastix.forage.util.LocationUtils;

import static com.google.common.truth.Truth.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

@RunWith(PowerMockRunner.class)
@PrepareForTest(LocationUtils.class)
public class RealmLocationTest {

    @Before
    public void beforeEachTest() {
        PowerMockito.mockStatic(LocationUtils.class);
    }

    @Test
    public void toLocation_shouldCallLocationUtils() {
        double lat = 40.7127;
        double lon = 74.0059;

        RealmLocation realmLocation = new RealmLocation();
        realmLocation.latitude = lat;
        realmLocation.longitude = lon;

        realmLocation.toLocation();

        PowerMockito.verifyStatic();
        LocationUtils.buildLocation(lat, lon);
    }

    @Test
    public void toLocation_shouldReturnFromLocationUtils() {
        double lat = 40.7127;
        double lon = 74.0059;

        RealmLocation realmLocation = new RealmLocation();
        realmLocation.latitude = lat;
        realmLocation.longitude = lon;

        Location location = mock(Location.class);
        when(LocationUtils.buildLocation(lat, lon)).thenReturn(location);

        Location result = realmLocation.toLocation();

        assertThat(result).isSameAs(location);
    }
}

Switch to PowerMock for RealmLocation unit tests


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

import org.jspecify.annotations.DefaultNonNull;
import org.jspecify.annotations.Nullable;

@DefaultNonNull
interface CovariantReturns {
  @Nullable
  Object makeObject();

  Lib<?> makeImplicitlyObjectBounded();

  Lib<? extends @Nullable Object> makeExplicitlyObjectBounded();

  interface Subtype extends CovariantReturns {
    @Override
    Object makeObject();

    @Override
    Lib<? extends Object> makeImplicitlyObjectBounded();

    @Override
    Lib<? extends Object> makeExplicitlyObjectBounded();
  }

  interface Lib<T extends @Nullable Object> {}
}

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

import org.jspecify.annotations.DefaultNonNull;
import org.jspecify.annotations.Nullable;

@DefaultNonNull
interface CovariantReturns {
  @Nullable
  Object makeObject();

  Lib<?> makeImplicitlyObjectBounded();

  Lib<? extends @Nullable Object> makeExplicitlyObjectBounded();

  interface Subtype extends CovariantReturns {
    @Override
    Object makeObject();

    @Override
    Lib<? extends Object> makeImplicitlyObjectBounded();

    @Override
    Lib<? extends Object> makeExplicitlyObjectBounded();
  }

  default void go(Subtype s) {
    checkObject(s.makeObject());
    checkLibOfObject(s.makeImplicitlyObjectBounded());
    checkLibOfObject(s.makeExplicitlyObjectBounded());
  }

  void checkObject(Object o);

  void checkLibOfObject(Lib<? extends Object> o);

  interface Lib<T extends @Nullable Object> {}
}

Test that annotations are not inherited.


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

package tachyon.client;

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

/**
 * Tests {@link ClientUtils}.
 */
public final class ClientUtilsTest {

  /**
   * Tests if output of getRandomNonNegativeLong from {@link ClientUtils} is non-negative, allowing for zero.
   */
  @Test
  public void getRandomNonNegativeLongTest() throws Exception {
    Assert.assertTrue(ClientUtils.getRandomNonNegativeLong() > 0);
  }

}

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

package tachyon.client;

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

/**
 * Tests {@link ClientUtils}.
 */
public final class ClientUtilsTest {

  /**
   * Tests if output of getRandomNonNegativeLong from {@link ClientUtils} is non-negative.
   */
  @Test
  public void getRandomNonNegativeLongTest() throws Exception {
    Assert.assertTrue(ClientUtils.getRandomNonNegativeLong() > 0);
  }

}

[TACHYON-1559] Fix checkstyle errors originating out of changes


package uk.sky.cirrus;

import com.datastax.driver.core.Cluster;
import com.datastax.driver.core.Host;
import uk.sky.cirrus.exception.ClusterUnhealthyException;

import java.net.InetAddress;
import java.util.List;
import java.util.stream.Collectors;

class ClusterHealth {

    private final Cluster cluster;

    ClusterHealth(Cluster cluster) {
        this.cluster = cluster;
    }

    void check() throws ClusterUnhealthyException{

        final List<InetAddress> unhealthyHosts = cluster.getMetadata().getAllHosts()
                .parallelStream()
                .filter(host -> !host.isUp())
                .map(Host::getAddress)
                .collect(Collectors.toList());

        if(!unhealthyHosts.isEmpty()){
            throw new ClusterUnhealthyException("Cluster not healthy, the following hosts are down: " + unhealthyHosts);
        }

        if (!cluster.getMetadata().checkSchemaAgreement()) {
            throw new ClusterUnhealthyException("Cluster not healthy, schema not in agreement");
        }
    }
}

package uk.sky.cirrus;

import com.datastax.driver.core.Cluster;
import com.datastax.driver.core.Host;
import uk.sky.cirrus.exception.ClusterUnhealthyException;

import java.net.InetAddress;
import java.util.List;
import java.util.stream.Collectors;

class ClusterHealth {

    private final Cluster cluster;

    ClusterHealth(Cluster cluster) {
        this.cluster = cluster;
    }

    void check() throws ClusterUnhealthyException{

        final List<InetAddress> unhealthyHosts = cluster.getMetadata().getAllHosts()
                .stream()
                .filter(host -> !host.isUp())
                .map(Host::getAddress)
                .collect(Collectors.toList());

        if(!unhealthyHosts.isEmpty()){
            throw new ClusterUnhealthyException("Cluster not healthy, the following hosts are down: " + unhealthyHosts);
        }

        if (!cluster.getMetadata().checkSchemaAgreement()) {
            throw new ClusterUnhealthyException("Cluster not healthy, schema not in agreement");
        }
    }
}

Change to use a stream() rather than parallelStream()


package com.nmuzychuk.blog.model;

import javax.persistence.*;
import java.util.HashSet;
import java.util.Set;

/**
 * Simple object representing a post.
 */
@Entity
public class Post {

    @ManyToOne
    private User user;

    @Id
    @GeneratedValue
    private Long id;
    private String title;
    private String body;

    @OneToMany(mappedBy = "post")
    private Set<Comment> comments = new HashSet<>();

    protected Post() {
    }

    public Post(User user, String title, String body) {
        this.user = user;
        this.title = title;
        this.body = body;
    }

    public User getUser() {
        return user;
    }

    public void setUser(User user) {
        this.user = user;
    }

    public Long getId() {
        return id;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getBody() {
        return body;
    }

    public void setBody(String body) {
        this.body = body;
    }

}

package com.nmuzychuk.blog.model;

import javax.persistence.*;
import java.util.HashSet;
import java.util.Set;

/**
 * Simple object representing a post.
 */
@Entity
public class Post {

    @ManyToOne
    private User user;

    @Id
    @GeneratedValue
    private Long id;
    private String title;

    @Lob
    private String body;

    @OneToMany(mappedBy = "post")
    private Set<Comment> comments = new HashSet<>();

    protected Post() {
    }

    public Post(User user, String title, String body) {
        this.user = user;
        this.title = title;
        this.body = body;
    }

    public User getUser() {
        return user;
    }

    public void setUser(User user) {
        this.user = user;
    }

    public Long getId() {
        return id;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getBody() {
        return body;
    }

    public void setBody(String body) {
        this.body = body;
    }

}

Update post body data type

Update post body data type


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

import com.intellij.openapi.extensions.ExtensionPointName;
import com.intellij.openapi.util.TextRange;
import com.intellij.psi.PsiElement;

/**
 * @author Anna Bulenkova
 */
public interface RegExpRangeProvider {
  ExtensionPointName<RegExpRangeProvider> EP_NAME = new ExtensionPointName<RegExpRangeProvider>("com.intellij.regExpRangeProvider");

  TextRange getTextRange(PsiElement element);
}

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

import com.intellij.openapi.extensions.ExtensionPointName;
import com.intellij.openapi.util.Pair;
import com.intellij.openapi.util.TextRange;
import com.intellij.psi.PsiElement;

/**
 * @author Anna Bulenkova
 */
public interface RegExpRangeProvider {
  ExtensionPointName<RegExpRangeProvider> EP_NAME = new ExtensionPointName<RegExpRangeProvider>("com.intellij.regExpRangeProvider");

  Pair<PsiElement, TextRange> getRangePair(PsiElement element);
}

Check regexp intention action language detection fix


package com.github.arteam.dropwizard.http2.client;

import io.dropwizard.setup.Environment;
import org.eclipse.jetty.client.HttpClient;

/**
 * Date: 11/26/15
 * Time: 10:22 AM
 * <p>
 * A builder for {@link HttpClient}. It builds an instance from an external
 * configuration and ties it to Dropwizard environment.
 *
 * @author Artem Prigoda
 */
public class JettyHttpClientBuilder {

    private Environment environment;
    private Http2ClientConfiguration configuration = new Http2ClientConfiguration();

    public JettyHttpClientBuilder(Environment environment) {
        this.environment = environment;
    }

    public JettyHttpClientBuilder using(Http2ClientConfiguration configuration) {
        this.configuration = configuration;
        return this;
    }

    public HttpClient build(String name) {
        ClientTransportFactory connectionFactoryBuilder = configuration.getConnectionFactoryBuilder();
        HttpClient httpClient = new HttpClient(
                connectionFactoryBuilder.httpClientTransport(environment.metrics(), name),
                connectionFactoryBuilder.sslContextFactory());
        httpClient.setConnectTimeout(configuration.getConnectionTimeout().toMilliseconds());
        httpClient.setIdleTimeout(configuration.getIdleTimeout().toMilliseconds());
        environment.lifecycle().manage(httpClient);
        return httpClient;
    }

    public HttpClient build() {
        return build("");
    }
}

package com.github.arteam.dropwizard.http2.client;

import com.google.common.base.Strings;
import io.dropwizard.setup.Environment;
import org.eclipse.jetty.client.HttpClient;
import org.eclipse.jetty.http.HttpField;
import org.eclipse.jetty.http.HttpHeader;

/**
 * Date: 11/26/15
 * Time: 10:22 AM
 * <p>
 * A builder for {@link HttpClient}. It builds an instance from an external
 * configuration and ties it to Dropwizard environment.
 *
 * @author Artem Prigoda
 */
public class JettyHttpClientBuilder {

    private Environment environment;
    private Http2ClientConfiguration configuration = new Http2ClientConfiguration();

    public JettyHttpClientBuilder(Environment environment) {
        this.environment = environment;
    }

    public JettyHttpClientBuilder using(Http2ClientConfiguration configuration) {
        this.configuration = configuration;
        return this;
    }

    public HttpClient build(String name) {
        ClientTransportFactory connectionFactoryBuilder = configuration.getConnectionFactoryBuilder();
        HttpClient httpClient = new HttpClient(
                connectionFactoryBuilder.httpClientTransport(environment.metrics(), name),
                connectionFactoryBuilder.sslContextFactory());
        httpClient.setConnectTimeout(configuration.getConnectionTimeout().toMilliseconds());
        httpClient.setIdleTimeout(configuration.getIdleTimeout().toMilliseconds());
        if (!Strings.isNullOrEmpty(name)) {
            httpClient.setUserAgentField(new HttpField(HttpHeader.USER_AGENT, name));
        }
        environment.lifecycle().manage(httpClient);
        return httpClient;
    }

    public HttpClient build() {
        return build("");
    }
}

Set user-agent from the client's name

Set user-agent from the client's name


package com.alexrnl.request.shows;

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

import com.alexrnl.request.Request;
import com.alexrnl.request.Verb;

/**
 * Archive a show in the logged member account.

 * @author Alex
 */
public class ShowArchive extends Request {

	/** Address of the method */
	private static final String	ADDRESS			= "/shows/archive";
	/** Name of the id parameter */
	private static final String	PARAMETER_ID	= "id";

	/** */
	private final String		id;

	/**
	 * Constructor #1.

	 * @param id
	 *        the id of the show to archive.
	 */
	public ShowArchive (final String id) {
		super(Verb.GET, ADDRESS);
		this.id = id;
	}

	/**
	 * Return the attribute id.
	 * @return the attribute id.
	 */
	public String getId () {
		return id;
	}

	@Override
	public Map<String, String> getParameters () {
		final Map<String, String> parameters = new HashMap<>();
		parameters.put(PARAMETER_ID, getId());
		return parameters;
	}

}

package com.alexrnl.request.shows;

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

import com.alexrnl.request.Request;
import com.alexrnl.request.Verb;

/**
 * Archive a show in the logged member account.

 * @author Alex
 */
public class ShowArchive extends Request {

	/** Address of the method */
	private static final String	ADDRESS			= "/shows/archive";
	/** Name of the id parameter */
	private static final String	PARAMETER_ID	= "id";

	/** The id of the show to archive */
	private final Integer		id;

	/**
	 * Constructor #1.

	 * @param id
	 *        the id of the show to archive.
	 */
	public ShowArchive (final Integer id) {
		super(Verb.GET, ADDRESS);
		this.id = id;
	}

	/**
	 * Return the attribute id.
	 * @return the attribute id.
	 */
	public Integer getId () {
		return id;
	}

	@Override
	public Map<String, String> getParameters () {
		final Map<String, String> parameters = new HashMap<>();
		parameters.put(PARAMETER_ID, getId().toString());
		return parameters;
	}

}

Make the id of the show an Integer

Make the id of the show an Integer


package org.scribe.model;

/**
 * An enumeration containing the most common HTTP Verbs.
 *
 * @author Pablo Fernandez
 */
public enum Verb
{
  GET, POST, PUT, DELETE
}

package org.scribe.model;

/**
 * An enumeration containing the most common HTTP Verbs.
 *
 * @author Pablo Fernandez
 */
public enum Verb
{
  GET, POST, PUT, DELETE, HEAD, OPTIONS, TRACE, PATCH
}

Add support for HEAD, OPTIONS, TRACE and PATCH


/*
 * Copyright (c) Facebook, Inc. and its affiliates.
 *
 * 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.facebook.buck.core.rules.analysis;

import com.facebook.buck.core.exceptions.HumanReadableException;
import javax.annotation.Nullable;

/**
 * Represents the failure of an analysis phase implementation function
 *
 * <p>This exception should result in a {@link com.facebook.buck.util.ExitCode.BUILD_ERROR}
 */
public class RuleAnalysisException extends HumanReadableException {

  public RuleAnalysisException(
      @Nullable Throwable cause, String humanReadableFormatString, Object... args) {
    super(cause, humanReadableFormatString, args);
  }
}

/*
 * Copyright (c) Facebook, Inc. and its affiliates.
 *
 * 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.facebook.buck.core.rules.analysis;

import com.facebook.buck.core.exceptions.HumanReadableException;
import javax.annotation.Nullable;

/**
 * Represents the failure of an analysis phase implementation function
 *
 * <p>This exception should result in a {@link com.facebook.buck.util.ExitCode.BUILD_ERROR}
 */
public class RuleAnalysisException extends HumanReadableException {

  public RuleAnalysisException(
      @Nullable Throwable cause, String humanReadableFormatString, Object... args) {
    super(cause, humanReadableFormatString, args);
  }

  public RuleAnalysisException(@Nullable Throwable cause, String message) {
    super(cause, message);
  }
}

Add second constructor for already formed string

Summary: When catching an exception that has formatting chars in it, we can run into issues if we try to format again

Reviewed By: cjhopman

shipit-source-id: 1929d59f1795cfbdefd0c86688b6c852f4438205


package cz.quanti.mailq.entities.v2;

import cz.quanti.mailq.entities.v2.enums.NotificationStatus;

public class SmsNotificationEntity extends BaseEntity {

    private Long id;
    private String name;
    private String code;
    private String template;
    private NotificationStatus status;
    private LinkEntity company;

    public Long getId() {
        return id;
    }

    public String getName() {
        return name;
    }

    public String getCode() {
        return code;
    }

    public NotificationStatus getStatus() {
        return status;
    }

    public LinkEntity getCompany() {
        return company;
    }

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

    public SmsNotificationEntity setCode(String code) {
        this.code = code;
        return this;
    }

    public SmsNotificationEntity setTemplate(String template) {
        this.template = template;
        return this;
    }
}

package cz.quanti.mailq.entities.v2;

import cz.quanti.mailq.entities.v2.enums.NotificationStatus;

public class SmsNotificationEntity extends BaseEntity {

    private Long id;
    private String name;
    private String code;
    private String template;
    private NotificationStatus status;
    private LinkEntity company;

    public Long getId() {
        return id;
    }

    public String getName() {
        return name;
    }

    public String getCode() {
        return code;
    }

    public NotificationStatus getStatus() {
        return status;
    }

    public LinkEntity getCompany() {
        return company;
    }

    public String getTemplate() {
        return template;
    }

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

    public SmsNotificationEntity setCode(String code) {
        this.code = code;
        return this;
    }

    public SmsNotificationEntity setTemplate(String template) {
        this.template = template;
        return this;
    }
}

Add getter for template variable

Add getter for template variable


package com.intellij.debugger.streams.trace.smart.handler;

import org.jetbrains.annotations.NotNull;

/**
 * @author Vitaliy.Bibaev
 */
public class HashMapVariableImpl extends VariableImpl {
  private final String myFromType;

  public HashMapVariableImpl(@NotNull String name, @NotNull String from, @NotNull String to, boolean isLinked) {
    super(String.format("Map<%s, %s>", from, to), name, isLinked ? "new LinkedHashMap<>()" : "new HashMap<>()");
    myFromType = from;
  }

  public String convertToArray(@NotNull String arrayName) {
    final StringBuilder builder = new StringBuilder();
    final String newLine = System.lineSeparator();
    builder.append("final ").append(arrayName).append(String.format("new Object[%s.size()];", getName())).append(System.lineSeparator());
    builder.append("{").append(newLine);
    builder.append("int i = 0;").append(newLine);
    builder.append("for (final ").append(myFromType).append(String.format(" key : %s.keySet()) {", getName())).append(newLine);
    builder.append("final Object value = ").append(String.format("%s.get(key);", getName())).append(newLine);
    builder.append(String.format("%s[i] = ", arrayName)).append("new Object[] { key, value };").append(newLine);
    builder.append("}").append(newLine);

    return builder.toString();
  }
}

package com.intellij.debugger.streams.trace.smart.handler;

import org.jetbrains.annotations.NotNull;

/**
 * @author Vitaliy.Bibaev
 */
public class HashMapVariableImpl extends VariableImpl {
  private final String myFromType;

  public HashMapVariableImpl(@NotNull String name, @NotNull String from, @NotNull String to, boolean isLinked) {
    super(String.format("Map<%s, %s>", from, to), name, isLinked ? "new LinkedHashMap<>()" : "new HashMap<>()");
    myFromType = from;
  }

  public String convertToArray(@NotNull String arrayName) {
    final StringBuilder builder = new StringBuilder();
    final String newLine = System.lineSeparator();
    builder.append("final ").append(arrayName).append(String.format(" = new Object[%s.size()];", getName())).append(System.lineSeparator());
    builder.append("{").append(newLine);
    builder.append("int i = 0;").append(newLine);
    builder.append("for (final ").append(myFromType).append(String.format(" key : %s.keySet()) {", getName())).append(newLine);
    builder.append("final Object value = ").append(String.format("%s.get(key);", getName())).append(newLine);
    builder.append(String.format("%s[i] = ", arrayName)).append("new Object[] { key, value };").append(newLine);
    builder.append("  }").append(newLine);
    builder.append("}").append(newLine);

    return builder.toString();
  }
}

Fix expression: brace is missed

Fix expression: brace is missed


/******************************************************************************
 * This program and the accompanying materials are made available under
 * the terms of the Common Public License v1.0 which accompanies this
 * distribution, and is available at the following URL:
 * http://www.eclipse.org/legal/cpl-v10.html
 * Copyright(c) 2003-2005 by the authors indicated in the @author tags.
 *
 * All Rights are Reserved by the various authors.
 *******************************************************************************/
package org.tigris.subversion.subclipse.core.client;

import org.eclipse.core.runtime.IProgressMonitor;

/**
 * ISVNNotifyListener implementation which intercepts the logMessage() method
 * and used it to display the operation progress within the supplied progress monitor.
 *
 * @author Martin Letenay (letenay at tigris.org)
 */
public class OperationProgressNotifyListener extends ISVNNotifyAdapter {

	private IProgressMonitor monitor = null;

	public OperationProgressNotifyListener(final IProgressMonitor monitor)
	{
		super();
		this.monitor = monitor;
	}

	/**
	 * Display the log the message in the progress monitor and increase the progress by 1
	 */
	public void logMessage(String message) {
		if (monitor != null)
		{
		    monitor.worked(1);
		    monitor.subTask(message);
		}
	}

	/**
	 * The operation was completed, clear the progress' subTask.
	 */
	public void logCompleted(String message) {
		if (monitor != null)
		{
		    monitor.subTask(" ");
		}
	}

}

Set svn:eol-style on new files

Set svn:eol-style on new files


package org.digitalsoft.android.test;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;

public class LaunchReceiver extends BroadcastReceiver {
	@Override
	public void onReceive(Context context, Intent intent) {
		String number = intent.getStringExtra(Intent.EXTRA_PHONE_NUMBER);
		String compareNumber = "\\+010.*";
		if (number.matches(compareNumber)) {
			Log.d("Bilal", "The dialed number is " + number);
			setResultData(null);
		}
	}

}

package org.digitalsoft.android.test;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;

public class LaunchReceiver extends BroadcastReceiver {
	@Override
	public void onReceive(Context context, Intent intent) {
		String number = intent.getStringExtra(Intent.EXTRA_PHONE_NUMBER);
		String numberPrefix = "\\+01.*";
		if (number.matches(numberPrefix)) {
			Log.d("Bilal", "The dialed number is " + number);
			setResultData(null);
		}
	}

}

Change number prefix to from +010 to +01


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

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

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

public class TextBuddyTest {

	private static final String FILE_NAME = "mytextfile.txt";

	@BeforeClass
	public static void initialize() throws IOException {
		TextBuddy tb = new TextBuddy(FILE_NAME);
		tb.checkFileStatus();
	}

	@Test
	public void testSortEmpty() {
		TextBuddy.clearText();

		List<String> list = TextBuddy.sortText();
		assertThat(list.isEmpty(), is(true));
	}

	@Test
	public void testSort() {
		TextBuddy.addText("cccc");
		TextBuddy.addText("aaaa");
		TextBuddy.addText("bbbb");

		List<String> list = TextBuddy.sortText();

		// Not empty.
		assertThat(list.isEmpty(), is(false));

		// Check sorted.
		assertEquals("[aaaa, bbbb, cccc]", list.toString());
	}

}

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

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

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

public class TextBuddyTest {

	private static final String FILE_NAME = "mytextfile.txt";

	@BeforeClass
	public static void initialize() throws IOException {
		TextBuddy tb = new TextBuddy(FILE_NAME);
		tb.checkFileStatus();
	}

	@Test
	public void testSortEmpty() {
		TextBuddy.clearText();

		List<String> list = TextBuddy.sortText();
		assertThat(list.isEmpty(), is(true));
	}

	@Test
	public void testSort1() {
		TextBuddy.clearText();

		TextBuddy.addText("cccc");
		TextBuddy.addText("aaaa");
		TextBuddy.addText("bbbb");

		List<String> list = TextBuddy.sortText();

		// Not empty.
		assertThat(list.isEmpty(), is(false));

		// Check sorted.
		assertEquals("[aaaa, bbbb, cccc]", list.toString());
	}

	@Test
	public void testSort2() {
		TextBuddy.clearText();

		TextBuddy.addText("CCCC");
		TextBuddy.addText("aaaa");
		TextBuddy.addText("xxxx");

		List<String> list = TextBuddy.sortText();

		// Not empty.
		assertThat(list.isEmpty(), is(false));

		// Check sorted.
		assertEquals("[aaaa, CCCC, xxxx]", list.toString());
	}

}

Test case with uppercase and lowercase combination.


package net.engin33r.luaspigot;

import net.engin33r.luaspigot.lua.Library;

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

/**
 * Registry for keeping track of Lua libraries available to scripts.
 */
public class LibraryRegistry {
    private final Map<String, Library> nameRegistry = new HashMap<>();

    public void register(Library lib) {
        nameRegistry.put(lib.getName(), lib);
        System.out.println("Successfully added library " + lib.getName() +
                " to registry");
    }

    public Library get(String name) {
        return nameRegistry.get(name);
    }
}

package net.engin33r.luaspigot;

import net.engin33r.luaspigot.lua.Library;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * Registry for keeping track of Lua libraries available to scripts.
 */
public class LibraryRegistry {
    private final Map<String, Library> nameRegistry = new HashMap<>();

    public void register(Library lib) {
        nameRegistry.put(lib.getName(), lib);
        System.out.println("Successfully added library " + lib.getName() +
                " to registry");
    }

    public Library get(String name) {
        return nameRegistry.get(name);
    }

    public Set<Library> get(Class<? extends Library> clazz) {
        return nameRegistry.values().stream()
                .filter(lib -> clazz.isAssignableFrom(lib.getClass()))
                .collect(Collectors.toSet());
    }
}

Add method for getting libraries by class


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

package com.aacsla.bluray.online;

import java.io.File;
import java.io.FileInputStream;

public class ContentAttribute {
    public ContentAttribute() {
    }

    public byte[] getContentCertID() {
        try {
            FileInputStream is = new FileInputStream(
                System.getProperty("bluray.vfs.root") + File.separator + "AACS/Content000.cer");
            is.skip(14);
            byte[] bytes = new byte[6];
            is.read(bytes, 0, 6);
            is.close();
            return bytes;
        } catch (Throwable e) {
            e.printStackTrace();
            return null;
        }
    }
}

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

package com.aacsla.bluray.online;

import java.io.File;
import java.io.FileInputStream;

public class ContentAttribute {
    public ContentAttribute() {
    }

    public byte[] getContentCertID() {
        FileInputStream is = null;
        try {
            is = new FileInputStream(
                System.getProperty("bluray.vfs.root") + File.separator + "AACS/Content000.cer");
            is.skip(14);
            byte[] bytes = new byte[6];
            is.read(bytes, 0, 6);
            return bytes;
        } catch (Throwable e) {
            e.printStackTrace();
            return null;
        } finally {
            if (is != null) {
                try {
                    is.close();
                } catch (Throwable e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

Fix resource leak in error path

Fix resource leak in error path


package de.aikiit.fotocollector.main;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author hirsch
 * @version 2016-03-10, 23:38
 */
public class DateJacksonSerializer extends JsonSerializer<Date> {
    @Override
    public void serialize(final Date value, final JsonGenerator gen, final SerializerProvider serializers) throws IOException, JsonProcessingException {
        String formattedDate = value != null ? new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(value) : "none";
        gen.writeString(formattedDate);
    }
}

package de.aikiit.fotocollector.main;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

/**
 * @author hirsch
 * @version 2016-03-10, 23:38
 */
public class DateJacksonSerializer extends JsonSerializer<Date> {
    @Override
    public void serialize(final Date value, final JsonGenerator gen, final SerializerProvider serializers) throws IOException, JsonProcessingException {
        String formattedDate = value != null ? new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.GERMANY).format(value) : "none";
        gen.writeString(formattedDate);
    }
}

Add Locale to date formatting.

Add Locale to date formatting.


package com.hiagg.item;

import com.hiagg.creativetabs.ModTabs;

import net.minecraft.client.Minecraft;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.world.World;
import net.minecraft.world.WorldSettings;
import net.minecraft.world.WorldSettings.GameType;

public class CurleSpawner extends Item {
	public CurleSpawner() {
		setUnlocalizedName("CurleSpawner");
		setTextureName("hiaggium:CurleSpawner");
		setCreativeTab(ModTabs.tabGear);
	}

	@Override
    public boolean onItemUse(ItemStack item, EntityPlayer player, World world, int x, int y, int z, int dim, float p, float ya, float r) {
        player.setGameType(GameType.CREATIVE);
		player.inventory.openInventory();
		player.setGameType(GameType.SURVIVAL);
		return true;
    }

}

package com.hiagg.item;

import com.hiagg.creativetabs.ModTabs;

import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.inventory.GuiInventory;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.world.World;
import net.minecraft.world.WorldSettings;
import net.minecraft.world.WorldSettings.GameType;

public class CurleSpawner extends Item {
	public CurleSpawner() {
		setUnlocalizedName("CurleSpawner");
		setTextureName("hiaggium:CurleSpawner");
		setCreativeTab(ModTabs.tabGear);
	}

	@Override
    public ItemStack onItemRightClick(ItemStack item, World world, EntityPlayer player) {
        if(world.isRemote) {
        	// player.setGameType(GameType.CREATIVE);
        	// Minecraft.getMinecraft().displayGuiScreen(new GuiInventory(player));
        	// player.setGameType(GameType.SURVIVAL);
        }
    	return item;
    }

}

Fix Spawner Well, not really.

Fix Spawner
Well, not really.


package uk.gov.register.db;

import org.skife.jdbi.v2.sqlobject.*;
import uk.gov.register.core.Entry;

public interface EntryDAO {
    @SqlBatch("insert into entry(entry_number, sha256hex, timestamp) values(:entryNumber, :sha256hex, :timestampAsLong)")
    void insertInBatch(@BindBean Iterable<Entry> entries);

    @SqlQuery("select value from current_entry_number")
    int currentEntryNumber();

    @SqlUpdate("update current_entry_number set value=:entryNumber")
    void setEntryNumber(@Bind("entryNumber") int currentEntryNumber);
}

package uk.gov.register.db;

import org.skife.jdbi.v2.sqlobject.*;
import uk.gov.register.core.Entry;

public interface EntryDAO {
    @SqlBatch("insert into entry(entry_number, sha256hex, timestamp, item_key) values(:entryNumber, :sha256hex, :timestampAsLong, :itemKey)")
    void insertInBatch(@BindBean Iterable<Entry> entries);

    @SqlQuery("select value from current_entry_number")
    int currentEntryNumber();

    @SqlUpdate("update current_entry_number set value=:entryNumber")
    void setEntryNumber(@Bind("entryNumber") int currentEntryNumber);
}

Add item key to query inserting values in entry table


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

package io.prometheus.client.utility.labels;

/**
 *

 * A collection of various reserved label names.
 *

 *
 * @author matt.proud@gmail.com (Matt T. Proud)
 */
public enum Reserved {
  /**
   *

   * {@code name} is a reserved label name key in Prometheus used to indicate
   * the name of the {@link io.prometheus.client.metrics.Metric}.
   *

   */
  NAME("name");

  private final String name;

  private Reserved(final String name) {
    this.name = name;
  }

  public String label() {
    return name;
  }
}

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

package io.prometheus.client.utility.labels;

/**
 *

 * A collection of various reserved label names.
 *

 *
 * @author matt.proud@gmail.com (Matt T. Proud)
 */
public enum Reserved {
  /**
   *

   * {@code name} is a reserved label name key in Prometheus used to indicate
   * the name of the {@link io.prometheus.client.metrics.Metric}.
   *

   */
  NAME("__name__");

  private final String name;

  private Reserved(final String name) {
    this.name = name;
  }

  public String label() {
    return name;
  }
}

Update metric name label to "__name__".

Update metric name label to "__name__".


package com.orgsync.api;

public enum Version {

    V1("v1"),
    V2("v2");

    private final String path;

    private Version(final String path) {
        this.path = path;
    }

    public String getPath() {
        return path;
    }
}

package com.orgsync.api;

public enum Version {

	V2("v2");

	private final String path;

	private Version(final String path) {
		this.path = path;
	}

	public String getPath() {
		return path;
	}
}

Remove V1.. we aren't going to support it.


/*
  Write a program that displays Welcome to Java five times.
*/

public class E1_02 {
  public static void main(String[] args) {
    for (int i = 0; i < 5; i++) {
      System.out.println("Welcome to Java");
    }
    //OR
    int i = 0;
    while (i < 5) {
      System.out.println("Welcome to Java");
    }
    i = 0;
    //OR
    do {
      System.out.println("Welcome to Java");
    } while (i < 5);
  }
}

/*
  Write a program that displays Welcome to Java five times.
*/

public class E1_02 {
  public static void main(String[] args) {
    for (int i = 0; i < 5; i++) {
      System.out.println("Welcome to Java");
    }
  }
}

Revert back to original solution.

Revert back to original solution.


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

package org.yaml.snakeyaml;

import junit.framework.TestCase;

public class YamlTest extends TestCase {

    public void testSetNoName() {
        Yaml yaml = new Yaml();
        assertTrue(yaml.toString().matches("Yaml:\\d+"));
    }

    public void testSetName() {
        Yaml yaml = new Yaml();
        yaml.setName("REST");
        assertEquals("REST", yaml.getName());
        assertEquals("REST", yaml.toString());
    }
}

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

package org.yaml.snakeyaml;

import java.util.Iterator;

import junit.framework.TestCase;

public class YamlTest extends TestCase {

    public void testSetNoName() {
        Yaml yaml = new Yaml();
        assertTrue(yaml.toString().matches("Yaml:\\d+"));
    }

    public void testSetName() {
        Yaml yaml = new Yaml();
        yaml.setName("REST");
        assertEquals("REST", yaml.getName());
        assertEquals("REST", yaml.toString());
    }

    /**
     * Check that documents are parsed only when they are asked to be loaded.
     */
    public void testOneDocument() {
        Yaml yaml = new Yaml();
        String doc = "--- a\n--- [:]";
        Iterator<Object> loaded = yaml.loadAll(doc).iterator();
        assertTrue(loaded.hasNext());
        Object obj1 = loaded.next();
        assertEquals("a", obj1);
        assertTrue(loaded.hasNext());
        try {
            loaded.next();
            fail("Second document is invalid");
        } catch (Exception e) {
            assertEquals("while parsing a flow node; expected the node content, but found Value", e
                    .getMessage());
        }
    }
}

Add test: check that documents are parsed only when they are asked to be loaded


//
// SortList.java
//

import java.io.*;
import java.util.Arrays;
import java.util.Vector;

/** Sorts a text file alphabetically, removing duplicates. */
public class SortList {

  public static void main(String[] args) throws Exception {
    String file = args[0];
    Vector v = new Vector();
    BufferedReader fin = new BufferedReader(new FileReader(file));
    while (true) {
      String line = fin.readLine();
      if (line == null) break;
      v.add(line);
    }
    fin.close();
    String[] lines = new String[v.size()];
    v.copyInto(lines);
    Arrays.sort(lines);
    new File(file).renameTo(new File(file + ".old"));
    PrintWriter fout = new PrintWriter(new FileWriter(file));
    for (int i=0; i<lines.length; i++) {
      if (i == 0 || !lines[i].equals(lines[i-1])) fout.println(lines[i]);
    }
    fout.close();
  }

}

//
// SortList.java
//

import java.io.*;
import java.util.Arrays;
import java.util.Vector;

/** Sorts a text file alphabetically, removing duplicates. */
public class SortList {

  public static void main(String[] args) throws Exception {
    boolean showDups = args[0].equals("-v");
    String file = args[showDups ? 1 : 0];
    Vector v = new Vector();
    BufferedReader fin = new BufferedReader(new FileReader(file));
    while (true) {
      String line = fin.readLine();
      if (line == null) break;
      v.add(line);
    }
    fin.close();
    String[] lines = new String[v.size()];
    v.copyInto(lines);
    Arrays.sort(lines);
    new File(file).renameTo(new File(file + ".old"));
    PrintWriter fout = new PrintWriter(new FileWriter(file));
    for (int i=0; i<lines.length; i++) {
      if (i == 0 || !lines[i].equals(lines[i-1])) fout.println(lines[i]);
      else if (showDups) System.out.println("Duplicate line: " + lines[i]);
    }
    fout.close();
  }

}

Add command line option to print a warning for each duplicate.


package name.abuchen.portfolio.ui.views.dashboard;

import java.util.List;

import com.ibm.icu.text.MessageFormat;

import name.abuchen.portfolio.model.Dashboard.Widget;
import name.abuchen.portfolio.snapshot.trades.Trade;
import name.abuchen.portfolio.ui.views.trades.TradeDetailsView;
import name.abuchen.portfolio.util.TextUtil;

public class TradesWidget extends AbstractTradesWidget
{
    public TradesWidget(Widget widget, DashboardData dashboardData)
    {
        super(widget, dashboardData);
    }

    @Override
    public void update(TradeDetailsView.Input input)
    {
        this.title.setText(TextUtil.tooltip(getWidget().getLabel()));

        List<Trade> trades = input.getTrades();
        long positive = trades.stream().filter(t -> t.getIRR() > 0).count();
        String text = MessageFormat.format("{0} <green>↑{1}</green> <red>↓{2}</red>", //$NON-NLS-1$
                        trades.size(), positive, trades.size() - positive);

        this.indicator.setText(text);
    }
}

package name.abuchen.portfolio.ui.views.dashboard;

import java.util.List;

import com.ibm.icu.text.MessageFormat;

import name.abuchen.portfolio.model.Dashboard.Widget;
import name.abuchen.portfolio.snapshot.trades.Trade;
import name.abuchen.portfolio.ui.views.trades.TradeDetailsView;
import name.abuchen.portfolio.util.TextUtil;

public class TradesWidget extends AbstractTradesWidget
{
    public TradesWidget(Widget widget, DashboardData dashboardData)
    {
        super(widget, dashboardData);
    }

    @Override
    public void update(TradeDetailsView.Input input)
    {
        this.title.setText(TextUtil.tooltip(getWidget().getLabel()));

        List<Trade> trades = input.getTrades();
        long positive = trades.stream().filter(t -> t.getProfitLoss().isPositive()).count();
        String text = MessageFormat.format("{0} <green>↑{1}</green> <red>↓{2}</red>", //$NON-NLS-1$
                        trades.size(), positive, trades.size() - positive);

        this.indicator.setText(text);
    }
}

Fix Trades Widget to count by isPositive rather than IRR


package com.elmakers.mine.bukkit.action.builtin;

import com.elmakers.mine.bukkit.api.action.CastContext;
import org.bukkit.configuration.ConfigurationSection;

public class PlaneAction extends VolumeAction
{
	protected enum Axis { X, Y, Z };
	protected Axis axis;

	@Override
	public void prepare(CastContext context, ConfigurationSection parameters) {
		super.prepare(context, parameters);
		String axisType = parameters.getString("axis");
		if (axisType.equalsIgnoreCase("x")) {
			axis = Axis.X;
		} else if (axisType.equalsIgnoreCase("z")) {
			axis = Axis.Z;
		} else {
			axis = Axis.Y;
		}
		switch (axis)
		{
			case X:
				xSize = 0;
				break;
			case Z:
				zSize = 0;
				break;
			default:
				ySize = 0;
				break;
		}
	}

	protected boolean containsPoint(int x, int y, int z)
	{
		return true;
	}
}

package com.elmakers.mine.bukkit.action.builtin;

import com.elmakers.mine.bukkit.api.action.CastContext;
import org.bukkit.configuration.ConfigurationSection;

public class PlaneAction extends VolumeAction
{
	protected enum Axis { X, Y, Z };
	protected Axis axis;

	@Override
	public void prepare(CastContext context, ConfigurationSection parameters) {
		super.prepare(context, parameters);
		String axisType = parameters.getString("axis");
		if (axisType != null) {
			if (axisType.equalsIgnoreCase("x")) {
				axis = Axis.X;
			} else if (axisType.equalsIgnoreCase("z")) {
				axis = Axis.Z;
			} else {
				axis = Axis.Y;
			}
		} else {
			axis = Axis.Y;
		}
		switch (axis)
		{
			case X:
				xSize = 0;
				break;
			case Z:
				zSize = 0;
				break;
			default:
				ySize = 0;
				break;
		}
	}

	protected boolean containsPoint(int x, int y, int z)
	{
		return true;
	}
}

Fix Plane action with default axis

Fix Plane action with default axis


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

/**
 * Workers.
 */
package org.gradle.workers;

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

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

Mark workers since 3.5 and Incubating

Mark workers since 3.5 and Incubating


package com.hypirion.io;

import java.io.InputStream;
import java.io.OutputStream;

public class Pipe {

    private final Thread threadPumper;
    private final PipeThread pt;
    private final InputStream in;
    private final OutputStream out;

    public Pipe(InputStream in, OutputStream out) {
        this.in = in;
        this.out = out;
        pt = new PipeThread();
        threadPumper = new Thread(pt);
        threadPumper.setName(String.format("PipeThread %s %s", in.hashCode(),
                                           out.hashCode()));
        threadPumper.setDaemon(true);
    }

    public void join() throws InterruptedException {
        threadPumper.join();
    }

    public void start() {

    }

    public void stop() {
        stop(true);
    }

    public void stop(boolean block) {

    }

    private class PipeThread implements Runnable {
        @Override
        public void run() {
            while (true) {

            }
        }
    }
}

package com.hypirion.io;

import java.io.InputStream;
import java.io.OutputStream;

public class Pipe {

    private final Thread threadPumper;
    private final PipeThread pt;
    private final InputStream in;
    private final OutputStream out;
    private final Object readLock, writeLock;

    public Pipe(InputStream in, OutputStream out) {
        this.in = in;
        this.out = out;
        pt = new PipeThread();
        threadPumper = new Thread(pt);
        threadPumper.setName(String.format("PipeThread %s %s", in.hashCode(),
                                           out.hashCode()));
        threadPumper.setDaemon(true);
        readLock = new Object();
        writeLock = new Object();
    }

    public void join() throws InterruptedException {
        threadPumper.join();
    }

    public void start() {

    }

    public void stop() {
        stop(true);
    }

    public void stop(boolean block) {

    }

    private class PipeThread implements Runnable {
        @Override
        public void run() {
            while (true) {

            }
        }
    }
}

Add in locks for pipe.

Add in locks for pipe.


/*
 * Copyright (c) 2017. Vitus Lehner. UrbanLife+. Universität der Bundeswehr München.
 */

package org.sociotech.urbanlifeplus.microinforadiator;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.eventbus.EventBus;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @author vituslehner 03.07.17
 */
@Configuration
public class CoreConfiguration {

    @Bean("reactorEventBus")
    public EventBus reactorEventBus() {
        return new EventBus("reactorEventBus");
    }

    @Bean
    public ObjectMapper objectMapper() {
        return new ObjectMapper();
    }

    @Value("${ULP_MIR_ID}")
    private String id;

    public String getId() {
        return id;
    }

    @Value("${ULP_RECURSION_DEPTH:3}")
    private int recursionDepth;

    public int getRecursionDepth() {
        return recursionDepth;
    }
}

/*
 * Copyright (c) 2017. Vitus Lehner. UrbanLife+. Universität der Bundeswehr München.
 */

package org.sociotech.urbanlifeplus.microinforadiator;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.eventbus.EventBus;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @author vituslehner 03.07.17
 */
@Configuration
public class CoreConfiguration {

    @Bean("reactorEventBus")
    public EventBus reactorEventBus() {
        return new EventBus("reactorEventBus");
    }

    @Bean
    public ObjectMapper objectMapper() {
        return new ObjectMapper();
    }

    @Value("${ULP_MIR_ID}")
    private String mirId;

    public String getMirId() {
        return mirId;
    }

    @Value("${ULP_RECURSION_DEPTH:3}")
    private int recursionDepth;

    public int getRecursionDepth() {
        return recursionDepth;
    }
}

Rename core config "id" to "mirId"

Rename core config "id" to "mirId"


package ee.shy.cli.command;

import ee.shy.cli.Command;
import ee.shy.cli.HelptextBuilder;
import ee.shy.core.Repository;

import java.io.IOException;

/**
 * A command to checkout.
 */
public class CheckoutCommand implements Command {
    @Override
    public void execute(String[] args) throws IOException {
        Repository repository = Repository.newExisting();
        repository.checkout(args[0]);
    }

    @Override
    public String getHelp() {
        return new HelptextBuilder()
                .addWithArgs("<String>", "Checkouts to given commit or branch")
                .addDescription("This command checkouts to commit with hash of <string>.")
                .create();
    }

    @Override
    public String getHelpBrief() {
        return "Checkouts to given commit.";
    }
}

package ee.shy.cli.command;

import ee.shy.cli.Command;
import ee.shy.cli.HelptextBuilder;
import ee.shy.core.Repository;

import java.io.IOException;

/**
 * A command to checkout.
 */
public class CheckoutCommand implements Command {
    @Override
    public void execute(String[] args) throws IOException {
        Repository repository = Repository.newExisting();
        repository.checkout(args[0]);
    }

    @Override
    public String getHelp() {
        return new HelptextBuilder()
                .addWithArgs("<String>", "Checkouts to given commit or branch")
                .addDescription("This command checkouts to commit with hash of <string>.")
                .create();
    }

    @Override
    public String getHelpBrief() {
        return "Checkouts to given commit.";
    }

    @Override
    public String[] getCompletion(String[] args) throws IOException {
        Repository repository = Repository.newExisting();
        return repository.getBranches().keySet().toArray(new String[0]);
    }
}

Add branch completions to checkout command


package com.lukekorth.android_500px;

import android.content.Context;

import com.lukekorth.android_500px.helpers.Cache;
import com.lukekorth.android_500px.helpers.ThreadBus;
import com.squareup.otto.Bus;
import com.squareup.picasso.Picasso;

public class WallpaperApplication extends com.activeandroid.app.Application {

    private static ThreadBus sBus;
    private static Picasso sPicasso;

    @Override
    public void onCreate() {
        super.onCreate();
        sBus = new ThreadBus();
    }

    public static Bus getBus() {
        return sBus;
    }

    public static Picasso getPicasso(Context context) {
        if (sPicasso == null) {
            sPicasso = new Picasso.Builder(context.getApplicationContext())
                    .downloader(Cache.createCacheDownloader(context.getApplicationContext()))
                    .build();
        }
        return sPicasso;
    }

}

package com.lukekorth.android_500px;

import android.content.Context;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;

import com.activeandroid.ActiveAndroid;
import com.lukekorth.android_500px.helpers.Cache;
import com.lukekorth.android_500px.helpers.ThreadBus;
import com.squareup.otto.Bus;
import com.squareup.picasso.Picasso;

public class WallpaperApplication extends com.activeandroid.app.Application {

    private static final String VERSION = "version";

    private static ThreadBus sBus;
    private static Picasso sPicasso;

    @Override
    public void onCreate() {
        super.onCreate();
        sBus = new ThreadBus();

        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
        if (prefs.getInt(VERSION, 0) <= 1) {
            ActiveAndroid.getDatabase().delete("Photos", null, null);
            prefs.edit().putInt(VERSION, BuildConfig.VERSION_CODE).apply();
        }
    }

    public static Bus getBus() {
        return sBus;
    }

    public static Picasso getPicasso(Context context) {
        if (sPicasso == null) {
            sPicasso = new Picasso.Builder(context.getApplicationContext())
                    .downloader(Cache.createCacheDownloader(context.getApplicationContext()))
                    .build();
        }
        return sPicasso;
    }

}

Clear database for version <= 1

Clear database for version <= 1


public class Wift {

  /**
   *  Wift - The BASIC Programming Language
   *
   *        BASIC FUNCTIONALITY:
   *            - STRINGS []
   *            - INTEGERS []
   *            - ARITHMETIC []
   *            - VARIABLES []
   *
   *        FUNCTIONS:
   *            - PRINT []
   *            - INPUT []
   *            - IF []
   *            - FOR []
   *
   *
   */

  public static void main(){}

  //        #readFile() -> char content
  //        #tokenize() -> list
  //        #parse()    -> symbol table

}

public class Wift {

  /**
   *  Wift - The BASIC Programming Language
   *
   *        BASIC FUNCTIONALITY:
   *            - STRINGS []
   *            - INTEGERS []
   *            - ARITHMETIC []
   *            - VARIABLES []
   *
   *        FUNCTIONS:
   *            - PRINT []
   *            - INPUT []
   *            - IF []
   *            - FOR []
   *
   *
   */

  public static void main(String...args){}

  //        #readFile() -> char content
  //        #tokenize() -> list
  //        #parse()    -> symbol table

}

Add "String...args" into "public..." :maple_leaf: