package fault.metrics;

import fault.concurrent.LongAdder;

/**
 * Created by timbrooks on 6/1/15.
 */
public class Second {

    private final LongAdder successes = new LongAdder();
    private final LongAdder errors = new LongAdder();
    private final LongAdder timeouts = new LongAdder();
    private final LongAdder circuitOpen = new LongAdder();
    private final LongAdder queueFull = new LongAdder();
    private final LongAdder maxConcurrencyExceeded = new LongAdder();
}

package fault.metrics;

import fault.concurrent.LongAdder;

/**
 * Created by timbrooks on 6/1/15.
 */
public class Second {

    private final LongAdder successes = new LongAdder();
    private final LongAdder errors = new LongAdder();
    private final LongAdder timeouts = new LongAdder();
    private final LongAdder circuitOpen = new LongAdder();
    private final LongAdder queueFull = new LongAdder();
    private final LongAdder maxConcurrencyExceeded = new LongAdder();

    public void incrementMetric(Metric metric) {
        switch (metric) {
            case SUCCESS:
                successes.increment();
                break;
            case ERROR:
                errors.increment();
                break;
            case TIMEOUT:
                timeouts.increment();
                break;
            case CIRCUIT_OPEN:
                circuitOpen.increment();
                break;
            case QUEUE_FULL:
                queueFull.increment();
                break;
            case MAX_CONCURRENCY_LEVEL_EXCEEDED:
                maxConcurrencyExceeded.increment();
                break;
            default:
                throw new RuntimeException("Unknown metric: " + metric);
        }
    }
}

Add method to increment metrics

Add method to increment metrics


package com.fsck.k9.message.html;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.safety.Cleaner;
import org.jsoup.safety.Whitelist;

public class HtmlSanitizer {
    private final HeadCleaner headCleaner;
    private final Cleaner cleaner;

    HtmlSanitizer() {
        Whitelist whitelist = Whitelist.relaxed()
                .addTags("font", "hr", "ins", "del")
                .addAttributes("table", "align", "bgcolor", "border", "cellpadding", "cellspacing", "width")
                .addAttributes("tr", "align", "bgcolor", "valign")
                .addAttributes("th",
                        "align", "bgcolor", "colspan", "headers", "height", "nowrap", "rowspan", "scope", "sorted",
                        "valign", "width")
                .addAttributes("td",
                        "align", "bgcolor", "colspan", "headers", "height", "nowrap", "rowspan", "scope", "valign",
                        "width")
                .addAttributes(":all", "class", "style", "id")
                .addProtocols("img", "src", "http", "https", "cid", "data");

        cleaner = new Cleaner(whitelist);
        headCleaner = new HeadCleaner();
    }

    public Document sanitize(String html) {
        Document dirtyDocument = Jsoup.parse(html);
        Document cleanedDocument = cleaner.clean(dirtyDocument);
        headCleaner.clean(dirtyDocument, cleanedDocument);
        return cleanedDocument;
    }
}

package com.fsck.k9.message.html;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.safety.Cleaner;
import org.jsoup.safety.Whitelist;

public class HtmlSanitizer {
    private final HeadCleaner headCleaner;
    private final Cleaner cleaner;

    HtmlSanitizer() {
        Whitelist whitelist = Whitelist.relaxed()
                .addTags("font", "hr", "ins", "del")
                .addAttributes("table", "align", "background", "bgcolor", "border", "cellpadding", "cellspacing",
                        "width")
                .addAttributes("tr", "align", "bgcolor", "valign")
                .addAttributes("th",
                        "align", "bgcolor", "colspan", "headers", "height", "nowrap", "rowspan", "scope", "sorted",
                        "valign", "width")
                .addAttributes("td",
                        "align", "bgcolor", "colspan", "headers", "height", "nowrap", "rowspan", "scope", "valign",
                        "width")
                .addAttributes(":all", "class", "style", "id")
                .addProtocols("img", "src", "http", "https", "cid", "data");

        cleaner = new Cleaner(whitelist);
        headCleaner = new HeadCleaner();
    }

    public Document sanitize(String html) {
        Document dirtyDocument = Jsoup.parse(html);
        Document cleanedDocument = cleaner.clean(dirtyDocument);
        headCleaner.clean(dirtyDocument, cleanedDocument);
        return cleanedDocument;
    }
}

Add 'background' attribute for 'table' tag to the whitelist


package gui;

import java.awt.GridLayout;

import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPasswordField;

import controller.Controller;

public class PasswordPane
{
	public static String showUnlockWalletDialog()
	{
		JPanel userPanel = new JPanel();
		userPanel.setLayout(new GridLayout(2,2));

		//Labels for the textfield components
		JLabel passwordLbl = new JLabel("Enter wallet password:");
		JPasswordField passwordFld = new JPasswordField();

		//Add the components to the JPanel
		userPanel.add(passwordLbl);
		userPanel.add(passwordFld);

		Object[] options = {"Unlock",
                "Unlock for 2 minutes",
                "Cancel"};

		//As the JOptionPane accepts an object as the message
		//it allows us to use any component we like - in this case
		//a JPanel containing the dialog components we want

		int n = JOptionPane.showOptionDialog(
					null,
					userPanel,
					"Unlock Wallet",
					JOptionPane.YES_NO_CANCEL_OPTION,
					JOptionPane.QUESTION_MESSAGE,
					null,
					options,
					options[2]
				);

		if(n == JOptionPane.YES_OPTION) {
			Controller.getInstance().setSecondsToUnlock(-1);
		} else if (n == JOptionPane.NO_OPTION) {
			Controller.getInstance().setSecondsToUnlock(120);
		} else {
			return "";
		}

		return new String(passwordFld.getPassword());
	}
}

package gui;

import java.awt.GridLayout;

import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPasswordField;

import controller.Controller;

public class PasswordPane
{
	public static String showUnlockWalletDialog()
	{
		JPanel userPanel = new JPanel();
		userPanel.setLayout(new GridLayout(2,2));

		//Labels for the textfield components
		JLabel passwordLbl = new JLabel("Enter wallet password:");
		JPasswordField passwordFld = new JPasswordField();

		//Add the components to the JPanel
		userPanel.add(passwordLbl);
		userPanel.add(passwordFld);

		Object[] options = {"Unlock",
                "Unlock for 2 minutes",
                "Cancel"};

		//As the JOptionPane accepts an object as the message
		//it allows us to use any component we like - in this case
		//a JPanel containing the dialog components we want

		int n = JOptionPane.showOptionDialog(
					null,
					userPanel,
					"Unlock Wallet",
					JOptionPane.YES_NO_CANCEL_OPTION,
					JOptionPane.QUESTION_MESSAGE,
					null,
					options,
					passwordFld
				);

		if(n == JOptionPane.YES_OPTION) {
			Controller.getInstance().setSecondsToUnlock(-1);
		} else if (n == JOptionPane.NO_OPTION) {
			Controller.getInstance().setSecondsToUnlock(120);
		} else {
			return "";
		}

		return new String(passwordFld.getPassword());
	}
}

Set default selection to password

Set default selection to password


package org.cafebabepy.runtime.object;

import org.cafebabepy.runtime.PyObject;
import org.cafebabepy.runtime.Python;

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

/**
 * Created by yotchang4s on 2017/06/19.
 */
public class PyTupleObject extends AbstractPyObjectObject {

    private final List<PyObject> list;

    public PyTupleObject(Python runtime, PyObject... value) {
        super(runtime, runtime.typeOrThrow("builtins.list"));

        this.list = Collections.unmodifiableList(Arrays.asList(value));
    }

    public List<PyObject> getList() {
        return this.list;
    }

    public PyObject get(PyIntObject i) {
        return this.list.get(i.getIntValue());
    }

    public PyObject getLen() {
        return this.runtime.number(list.size());
    }

    @Override
    public String asJavaString() {
        return this.list.stream()
                .map(PyObject::asJavaString)
                .collect(Collectors.joining(",", "(", ")"));
    }
}

package org.cafebabepy.runtime.object;

import org.cafebabepy.runtime.PyObject;
import org.cafebabepy.runtime.Python;

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

/**
 * Created by yotchang4s on 2017/06/19.
 */
public class PyTupleObject extends AbstractPyObjectObject {

    private final List<PyObject> list;

    public PyTupleObject(Python runtime, PyObject... value) {
        super(runtime, runtime.typeOrThrow("builtins.tuple"));

        this.list = Collections.unmodifiableList(Arrays.asList(value));
    }

    public List<PyObject> getList() {
        return this.list;
    }

    public PyObject get(PyIntObject i) {
        return this.list.get(i.getIntValue());
    }

    public PyObject getLen() {
        return this.runtime.number(list.size());
    }

    @Override
    public String asJavaString() {
        return this.list.stream()
                .map(PyObject::asJavaString)
                .collect(Collectors.joining(",", "(", ")"));
    }
}

Fix list to tuple type

Fix list to tuple type


package org.msf.records.model;

import java.io.Serializable;

/**
 * Created by Gil on 03/10/2014.
 */
public class Patient implements Serializable {

    public String id;
    public String given_name;
    public String family_name;

    public String important_information;

    /**
     * Accepted values:
     * suspected, probable, confirmed, non-case, convalescent,
     * can_be_discharged, dischraged, suspected_dead, confirmed_dead
     */
    public String status;

    public boolean pregnant;

    // Must be "M" or "F".
    public String gender;

    @Deprecated
    public String movement;
    @Deprecated
    public String eating;

    public Long admission_timestamp;
    public Long created_timestamp;
    public Long first_showed_symptoms_timestamp;

    public String origin_location;
    // Not yet ready.
    public String next_of_kin;

    public PatientLocation assigned_location;
    public PatientAge age;

}

package org.msf.records.model;

import java.io.Serializable;

/**
 * Created by Gil on 03/10/2014.
 */
public class Patient implements Serializable {

    public String id;
    public String uuid;
    public String given_name;
    public String family_name;

    public String important_information;

    /**
     * Accepted values:
     * suspected, probable, confirmed, non-case, convalescent,
     * can_be_discharged, dischraged, suspected_dead, confirmed_dead
     */
    public String status;

    public boolean pregnant;

    // Must be "M" or "F".
    public String gender;

    @Deprecated
    public String movement;
    @Deprecated
    public String eating;

    public Long admission_timestamp;
    public Long created_timestamp;
    public Long first_showed_symptoms_timestamp;

    public String origin_location;
    // Not yet ready.
    public String next_of_kin;

    public PatientLocation assigned_location;
    public PatientAge age;

}

Add uuid to the patient bean in Android

Add uuid to the patient bean in Android


package com.github.tomakehurst.wiremock.admin;

import com.github.tomakehurst.wiremock.admin.model.ResponseDefinitionBodyMatcher;
import com.github.tomakehurst.wiremock.http.ResponseDefinition;
import org.junit.Test;

import static com.github.tomakehurst.wiremock.client.ResponseDefinitionBuilder.responseDefinition;
import static junit.framework.TestCase.assertFalse;

public class ResponseDefinitionBodyMatcherTest {
    @Test
    public void doesNotMatchEmptyBody() {
        ResponseDefinition emptyBody = responseDefinition().build();
        ResponseDefinitionBodyMatcher matcher = new ResponseDefinitionBodyMatcher(0, 0);
        assertFalse(matcher.match(emptyBody).isExactMatch());
    }
}

package com.github.tomakehurst.wiremock.admin;

import com.github.tomakehurst.wiremock.admin.model.ResponseDefinitionBodyMatcher;
import com.github.tomakehurst.wiremock.client.ResponseDefinitionBuilder;
import com.github.tomakehurst.wiremock.http.ResponseDefinition;
import org.junit.Test;

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

public class ResponseDefinitionBodyMatcherTest {
    @Test
    public void noThresholds() {
        ResponseDefinitionBodyMatcher matcher = new ResponseDefinitionBodyMatcher(0, 0);
        assertFalse(matcher.match(new ResponseDefinition()).isExactMatch());
        assertTrue(matcher.match(textResponseDefinition("a")).isExactMatch());
        assertTrue(matcher.match(binaryResponseDefinition(new byte[] { 0x1 })).isExactMatch());
    }

    @Test
    public void textBodyMatchingWithThreshold() {
        ResponseDefinitionBodyMatcher matcher = new ResponseDefinitionBodyMatcher(2, 0);
        assertFalse(matcher.match(textResponseDefinition("f")).isExactMatch());
        assertFalse(matcher.match(textResponseDefinition("fo")).isExactMatch());
        assertTrue(matcher.match(textResponseDefinition("foo")).isExactMatch());
    }

    @Test
    public void binaryBodyMatchingWithThreshold() {
        ResponseDefinitionBodyMatcher matcher = new ResponseDefinitionBodyMatcher(0, 2);
        assertFalse(matcher.match(binaryResponseDefinition(new byte[] { 0x1 })).isExactMatch());
        assertFalse(matcher.match(binaryResponseDefinition(new byte[] { 0x1, 0xc })).isExactMatch());
        assertTrue(matcher.match(binaryResponseDefinition(new byte[] { 0x1, 0xc, 0xf })).isExactMatch());
    }

    private static ResponseDefinition textResponseDefinition(String body) {
        return new ResponseDefinitionBuilder()
            .withHeader("Content-Type", "text/plain")
            .withBody(body)
            .build();
    }

    private static ResponseDefinition binaryResponseDefinition(byte[] body) {
        return new ResponseDefinitionBuilder()
            .withBody(body)
            .build();
    }
}

Add more tests for ResponseDefinitionBodyMatcher


package com.grailbox.twicket;

import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.form.StatelessForm;
import org.apache.wicket.markup.html.form.TextField;
import org.apache.wicket.markup.html.panel.Panel;
import org.apache.wicket.model.CompoundPropertyModel;
import org.apache.wicket.validation.validator.StringValidator.MinimumLengthValidator;

public class SearchPanel extends Panel {
  private static final long serialVersionUID = -8610733111417498232L;

  public SearchPanel(String id) {
    super(id);
    add(new SearchForm("searchForm"));
  }

  private class SearchForm extends StatelessForm<SearchParams> {
    private static final long serialVersionUID = -5253297831508495384L;

    private SearchForm(final String id) {
      super(id);
      setModel(new CompoundPropertyModel<SearchParams>(new SearchParams()));
      add(new Label("searchLabel", "Search Terms:"));
      add(new TextField<String>("searchString").setRequired(true).add(new MinimumLengthValidator(3)));
    }

    @Override
    protected final void onSubmit() {
      SearchParams params = getModelObject();
      if (params != null) {
        setResponsePage(new HomePage(new SearchTweetRetriever(params)));
      }
    }
  }
}

package com.grailbox.twicket;

import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.form.StatelessForm;
import org.apache.wicket.markup.html.form.TextField;
import org.apache.wicket.markup.html.panel.Panel;
import org.apache.wicket.model.CompoundPropertyModel;
import org.apache.wicket.validation.validator.StringValidator.MinimumLengthValidator;

public class SearchPanel extends Panel {
  private static final long serialVersionUID = -8610733111417498232L;

  public SearchPanel(String id) {
    super(id);
    add(new SearchForm("searchForm"));
  }

  private class SearchForm extends StatelessForm<SearchParams> {
    private static final long serialVersionUID = -5253297831508495384L;

    private SearchForm(final String id) {
      super(id);
      setModel(new CompoundPropertyModel<SearchParams>(new SearchParams()));
      add(new Label("searchLabel", "Search Terms:"));
      add(new TextField<String>("searchString").setRequired(true).add(new MinimumLengthValidator(3)));
    }

    @Override
    protected final void onSubmit() {
      setResponsePage(new HomePage(new SearchTweetRetriever(getModelObject())));
    }
  }
}

Remove check for null params in onSubmit


package com.mssngvwls;

import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
import java.util.stream.Collectors;

import org.springframework.stereotype.Service;

@Service
public class GamePhraseSelector {

    private final PhraseRepository phraseRepository;
    private final PhraseFormatter phraseFormatter;

    public GamePhraseSelector(final PhraseRepository phraseRepository, final PhraseFormatter phraseFormatter) {
        this.phraseRepository = phraseRepository;
        this.phraseFormatter = phraseFormatter;
    }

    public Queue<GamePhrase> generateCategories() {
        final List<Phrase> phrases = phraseRepository.getPhrases();
        Collections.shuffle(phrases);
        return phrases.stream()
                .limit(10)
                .map(phrase -> new GamePhrase(phrase.getFullPhrase(), phraseFormatter.format(phrase.getFullPhrase()), phrase.getCategory().getName()))
                .collect(Collectors.toCollection(LinkedList::new));
    }

}

package com.mssngvwls;

import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
import java.util.stream.Collectors;

import org.springframework.stereotype.Service;

@Service
public class GamePhraseSelector {

    private final CategoryRepository categoryRepository;
    private final PhraseFormatter phraseFormatter;

    public GamePhraseSelector(final CategoryRepository categoryRepository, final PhraseFormatter phraseFormatter) {
        this.categoryRepository = categoryRepository;
        this.phraseFormatter = phraseFormatter;
    }

    public Queue<GamePhrase> generateCategories(final int numberOfCategories, final int numberOfPhrasesPerCategory) {
        final List<Category> categories = categoryRepository.getAllCategories();

        return categories.stream()
                .filter(category -> category.getPhrases().size() >= numberOfPhrasesPerCategory)
                .limit(numberOfCategories)
                .map(Category::getPhrases)
                .limit(numberOfPhrasesPerCategory)
                .flatMap(List::stream)
                .map(phrase -> new GamePhrase(phrase.getFullPhrase(), phraseFormatter.format(phrase.getFullPhrase()), phrase.getCategory().getName()))
                .collect(Collectors.toCollection(LinkedList::new));
    }

}

Change how game phrases are generated - more streams!


package org.pentaho.ui.xul.swing.tags;

import java.awt.GridBagLayout;
import java.util.ArrayList;

import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JPanel;

import org.pentaho.ui.xul.XulComponent;
import org.pentaho.ui.xul.XulDomContainer;
import org.pentaho.ui.xul.containers.XulMenubar;
import org.pentaho.ui.xul.swing.SwingElement;

public class SwingMenubar extends SwingElement implements XulMenubar{

  private JMenuBar menuBar;
  public SwingMenubar(XulComponent parent, XulDomContainer domContainer, String tagName) {
    super("menubar");

    children = new ArrayList<XulComponent>();

    menuBar = new JMenuBar();
    managedObject = menuBar;

  }

  @Override
  public void layout(){
    for(XulComponent comp : children){
      if(comp instanceof SwingMenu){
        this.menuBar.add((JMenu) ((SwingMenu) comp).getManagedObject());
      }
    }
  }

}

package org.pentaho.ui.xul.swing.tags;

import java.awt.Dimension;
import java.awt.GridBagLayout;
import java.util.ArrayList;

import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JPanel;

import org.pentaho.ui.xul.XulComponent;
import org.pentaho.ui.xul.XulDomContainer;
import org.pentaho.ui.xul.containers.XulMenubar;
import org.pentaho.ui.xul.swing.SwingElement;

public class SwingMenubar extends SwingElement implements XulMenubar{

  private JMenuBar menuBar;
  public SwingMenubar(XulComponent parent, XulDomContainer domContainer, String tagName) {
    super("menubar");

    children = new ArrayList<XulComponent>();

    menuBar = new JMenuBar();
    menuBar.setMinimumSize(new Dimension(20,20));
    managedObject = menuBar;

  }

  @Override
  public void layout(){
    for(XulComponent comp : children){
      if(comp instanceof SwingMenu){
        this.menuBar.add((JMenu) ((SwingMenu) comp).getManagedObject());
      }
    }
  }

}

Set a minimum height to prevent the menu from surrendering it's entire space


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

package co.phoenixlab.discord.api.endpoints;

public interface AuthenticationEndpoint {

}

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

package co.phoenixlab.discord.api.endpoints;

import co.phoenixlab.discord.api.entities.TokenResponse;
import co.phoenixlab.discord.api.request.EmailPasswordLoginRequest;
import co.phoenixlab.discord.api.request.LogoutRequest;

public interface AuthenticationEndpoint {

    TokenResponse logIn(EmailPasswordLoginRequest request)
            throws ApiException;

    void logOut(LogoutRequest request)
            throws ApiException;

}

Add methods to Auth endpoint

Add methods to Auth endpoint


/*
 * Copyright 2016 Hippo Seven
 *
 * 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.hippo.ehviewer.client;

public class EhCacheKeyFactory {

    public static String getThumbKey(long gid) {
        return "thumb:" + gid;
    }

    public static String getNormalPreviewKey(long gid, int index) {
        return "preview:normal:" + gid + ":" + index;
    }

    public static String getLargePreviewKey(long gid, int index) {
        return "preview:large:" + gid + ":" + index;
    }

    public static String getLargePreviewSetKey(long gid, int index) {
        return "large_preview_set:" + gid + ":" + index;
    }

    public static String getImageKey(long gid, int index) {
        return "image:" + gid + ":" + index;
    }
}

/*
 * Copyright 2016 Hippo Seven
 *
 * 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.hippo.ehviewer.client;

public class EhCacheKeyFactory {

    public static String getThumbKey(long gid) {
        return "preview:large:" + gid + ":" + 0; // "thumb:" + gid;
    }

    public static String getNormalPreviewKey(long gid, int index) {
        return "preview:normal:" + gid + ":" + index;
    }

    public static String getLargePreviewKey(long gid, int index) {
        return "preview:large:" + gid + ":" + index;
    }

    public static String getLargePreviewSetKey(long gid, int index) {
        return "large_preview_set:" + gid + ":" + index;
    }

    public static String getImageKey(long gid, int index) {
        return "image:" + gid + ":" + index;
    }
}

Make thumb cache key as first large preview cache key


//@author A0116538A

package bakatxt.gui;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.geom.Path2D;

import bakatxt.core.Task;

/**
 * This class dictates the color and shape of the box which the task will be put in.
 * This box is specifically for a top most box.
 *
 */
class FirstTaskBox extends TaskBox {

    public FirstTaskBox(Task task, Color backgroundColor) {
        super(task, backgroundColor);
    }

    @Override
    protected void paintComponent(Graphics g) {
        Graphics2D g2d = (Graphics2D) g.create();
        g2d.setColor(getBackground());
        g2d.setRenderingHints(UIHelper.antiAlias());
        g2d.fill(new TopRounded(getWidth(), getHeight()));
        g2d.dispose();
        super.paintComponent(g);
    }

    // TODO fix topRounded method
    class TopRounded extends Path2D.Double {

        public TopRounded(double width, double height) {
            moveTo(0, 0);
            lineTo(width, 0);
            lineTo(width, height - UIHelper.WINDOW_ROUNDNESS);
            curveTo(width, height, width, height, width - UIHelper.WINDOW_ROUNDNESS, height);
            lineTo(UIHelper.WINDOW_ROUNDNESS, height);
            curveTo(0, height, 0, height, 0, height - UIHelper.WINDOW_ROUNDNESS);
            lineTo(0, 0);
            closePath();
        }
    }
}

//@author A0116538A

package bakatxt.gui;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.geom.Path2D;

import bakatxt.core.Task;

/**
 * This class dictates the color and shape of the box which the task will be put in.
 * This box is specifically for a top most box.
 *
 */
class FirstTaskBox extends TaskBox {

    public FirstTaskBox(Task task, Color backgroundColor) {
        super(task, backgroundColor);
    }

    @Override
    protected void paintComponent(Graphics g) {
        Graphics2D g2d = (Graphics2D) g.create();
        g2d.setColor(getBackground());
        g2d.setRenderingHints(UIHelper.antiAlias());
        g2d.fill(new TopRounded(getWidth(), getHeight()));
        g2d.dispose();
        super.paintComponent(g);
    }

    class TopRounded extends Path2D.Double {

        public TopRounded(double width, double height) {
            moveTo(0, height);
            lineTo(0, UIHelper.WINDOW_ROUNDNESS);
            curveTo(0, 0, 0, 0, UIHelper.WINDOW_ROUNDNESS, 0);
            lineTo(width - UIHelper.WINDOW_ROUNDNESS, 0);
            curveTo(width, 0, width, 0, width, UIHelper.WINDOW_ROUNDNESS);
            lineTo(width, height);
            lineTo(0, height);
            closePath();
        }
    }
}

Fix topRounded method to draw the correct shape


package com.laytonsmith.abstraction.enums;

import com.laytonsmith.annotations.MEnum;

/**
 * A MCItemFlag can hide some Attributes from MCItemStacks, through MCItemMeta.
 */
@MEnum("com.commandhelper.ItemFlag")
public enum MCItemFlag {
	/**
	 * Setting to show/hide enchants
	 */
	HIDE_ENCHANTS,
	/**
	 * Setting to show/hide Attributes like Damage
	 */
	HIDE_ATTRIBUTES,
	/**
	 * Setting to show/hide the unbreakable State
	 */
	HIDE_UNBREAKABLE,
	/**
	 * Setting to show/hide what the ItemStack can break/destroy
	 */
	HIDE_DESTROYS,
	/**
	 * Setting to show/hide where this ItemStack can be build/placed on
	 */
	HIDE_PLACED_ON,
	/**
	 * Setting to show/hide potion effects on this ItemStack
	 */
	HIDE_POTION_EFFECTS;
}

package com.laytonsmith.abstraction.enums;

import com.laytonsmith.annotations.MEnum;

/**
 * A MCItemFlag can hide some Attributes from MCItemStacks, through MCItemMeta.
 */
@MEnum("com.commandhelper.ItemFlag")
public enum MCItemFlag {
	/**
	 * Setting to show/hide enchants
	 */
	HIDE_ENCHANTS,
	/**
	 * Setting to show/hide Attributes like Damage
	 */
	HIDE_ATTRIBUTES,
	/**
	 * Setting to show/hide the unbreakable State
	 */
	HIDE_UNBREAKABLE,
	/**
	 * Setting to show/hide what the ItemStack can break/destroy
	 */
	HIDE_DESTROYS,
	/**
	 * Setting to show/hide where this ItemStack can be build/placed on
	 */
	HIDE_PLACED_ON,
	/**
	 * Setting to show/hide potion effects on this ItemStack
	 */
	HIDE_POTION_EFFECTS,
	/**
	 * Setting to show/hide dyes from coloured leather armour
	 */
	HIDE_DYE;
}

Add HIDE_DYE item meta flag

Add HIDE_DYE item meta flag


/*
 * Copyright (C) 2014 Pedro Vicente Gómez Sánchez.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.github.pedrovgs.tuentitv.ui.util;

import android.content.Context;

/**
 * @author Pedro Vicente Gómez Sánchez.
 */
public class Util {

  public static int convertDpToPixel(Context context, int dp) {
    float density = context.getResources().getDisplayMetrics().density;
    return Math.round((float) dp * density);
  }
}

Add copyright header to util package

Add copyright header to util package


package org.commcare.util.externalizable;

import org.javarosa.core.util.externalizable.Hasher;
import org.javarosa.core.util.externalizable.PrototypeFactory;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * @author ctsims
 */
public class AndroidClassHasher extends Hasher {

    private static final int CLASS_HASH_SIZE = 4;

    MessageDigest mMessageDigester;

    public AndroidClassHasher() {
        try {
            mMessageDigester = java.security.MessageDigest.getInstance("MD5");
        } catch (NoSuchAlgorithmException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    public static void registerAndroidClassHashStrategy() {
        PrototypeFactory.setStaticHasher(new AndroidClassHasher());
    }

    public byte[] getHash(Class c){
        byte[] ret;
        synchronized(mMessageDigester) {
            ret = mMessageDigester.digest(c.getName().getBytes());
        }
        return ret;
    }

    @Override
    public int getHashSize(){
        return CLASS_HASH_SIZE;
    }

}

package org.commcare.util.externalizable;

import org.javarosa.core.util.externalizable.Hasher;
import org.javarosa.core.util.externalizable.PrototypeFactory;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * @author ctsims
 */
public class AndroidClassHasher extends Hasher {

    private static final int CLASS_HASH_SIZE = 4;

    private final MessageDigest mMessageDigester;

    public AndroidClassHasher() {
        try {
            mMessageDigester = java.security.MessageDigest.getInstance("MD5");
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        }
    }

    public static void registerAndroidClassHashStrategy() {
        PrototypeFactory.setStaticHasher(new AndroidClassHasher());
    }

    public byte[] getHash(Class c){
        byte[] ret;
        synchronized(mMessageDigester) {
            ret = mMessageDigester.digest(c.getName().getBytes());
        }
        return ret;
    }

    @Override
    public int getHashSize(){
        return CLASS_HASH_SIZE;
    }
}

Raise runtime exception on unfound hasher method


package greendroid.util;

/**
 * Utility class containing several useful constants related to time.
 *
 * @author Cyril Mottier
 */
public class Time {

	/**
	 * The number of milliseconds in a second.
	 */
	public static final int GD_SECOND = 1000;

	/**
	 * The number of milliseconds in a minute.
	 */
	public static final int GD_MINUTE = GD_SECOND * 60;

	/**
	 * The number of milliseconds in an hour.
	 */
	public static final int GD_HOUR = GD_MINUTE * 60;

	/**
	 * The number of milliseconds in a day.
	 */
	public static final int GD_DAY = GD_HOUR * 24;

	/**
	 * The number of milliseconds in a week.
	 */
	public static final int GD_WEEK = GD_DAY * 7;

}

package greendroid.util;

/**
 * Utility class containing several useful constants related to time.
 *
 * @author Cyril Mottier
 */
public class Time {

	/**
	 * The number of milliseconds in a second.
	 */
	public static final long GD_SECOND = 1000;

	/**
	 * The number of milliseconds in a minute.
	 */
	public static final long GD_MINUTE = GD_SECOND * 60;

	/**
	 * The number of milliseconds in an hour.
	 */
	public static final long GD_HOUR = GD_MINUTE * 60;

	/**
	 * The number of milliseconds in a day.
	 */
	public static final long GD_DAY = GD_HOUR * 24;

	/**
	 * The number of milliseconds in a week.
	 */
	public static final long GD_WEEK = GD_DAY * 7;

}

Use longs for time related constants

Use longs for time related constants


/*
 * (C) Copyright 2012 Nuxeo SA (http://nuxeo.com/) and contributors.
 *
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the GNU Lesser General Public License
 * (LGPL) version 2.1 which accompanies this distribution, and is available at
 * http://www.gnu.org/licenses/lgpl.html
 *
 * 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.
 *
 * Contributors:
 *     Olivier Grisel <ogrisel@nuxeo.com>
 *     Antoine Taillefer <ataillefer@nuxeo.com>
 */
package org.nuxeo.drive.service;

import java.io.Serializable;

public final class NuxeoDriveEvents {

    private NuxeoDriveEvents() {
        // Utility class
    }

    public static final String ABOUT_TO_REGISTER_ROOT = "aboutToRegisterRoot";

    public static final String ROOT_REGISTERED = "rootRegistered";

    public static final String ABOUT_TO_UNREGISTER_ROOT = "aboutToUnRegisterRoot";

    public static final String ROOT_UNREGISTERED = "rootUnregistered";

    public static final String IMPACTED_USERNAME_PROPERTY = "impactedUserName";

    public static final Serializable EVENT_CATEGORY = "NuxeoDrive";

    public static final String DELETED_EVENT = "deleted";

}

/*
 * (C) Copyright 2012 Nuxeo SA (http://nuxeo.com/) and contributors.
 *
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the GNU Lesser General Public License
 * (LGPL) version 2.1 which accompanies this distribution, and is available at
 * http://www.gnu.org/licenses/lgpl.html
 *
 * 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.
 *
 * Contributors:
 *     Olivier Grisel <ogrisel@nuxeo.com>
 *     Antoine Taillefer <ataillefer@nuxeo.com>
 */
package org.nuxeo.drive.service;

import java.io.Serializable;

/**
 *
 * Core event related constants for Nuxeo Drive.
 *
 * @author Antoine Taillefer
 */
public final class NuxeoDriveEvents {

    private NuxeoDriveEvents() {
        // Utility class
    }

    public static final String ABOUT_TO_REGISTER_ROOT = "aboutToRegisterRoot";

    public static final String ROOT_REGISTERED = "rootRegistered";

    public static final String ABOUT_TO_UNREGISTER_ROOT = "aboutToUnRegisterRoot";

    public static final String ROOT_UNREGISTERED = "rootUnregistered";

    public static final String IMPACTED_USERNAME_PROPERTY = "impactedUserName";

    public static final Serializable EVENT_CATEGORY = "NuxeoDrive";

    public static final String DELETED_EVENT = "deleted";

}

NXP-11577: Fix Sonar Major violations: Javadoc Type


/*
 * Copyright 2012 The Netty Project
 *
 * The Netty Project 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 io.netty.channel;

import java.util.concurrent.ThreadFactory;

public abstract class MultithreadEventLoop extends MultithreadEventExecutor implements EventLoop {

    protected MultithreadEventLoop(int nThreads, ThreadFactory threadFactory,
            Object... args) {
        super(nThreads, threadFactory, args);
    }

    @Override
    protected abstract EventExecutor newChild(ThreadFactory threadFactory, Object... args) throws Exception;

    @Override
    public ChannelFuture register(Channel channel) {
        return ((EventLoop) unsafe().nextChild()).register(channel);
    }

    @Override
    public ChannelFuture register(Channel channel, ChannelFuture future) {
        return ((EventLoop) unsafe().nextChild()).register(channel, future);
    }
}

/*
 * Copyright 2012 The Netty Project
 *
 * The Netty Project 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 io.netty.channel;

import java.util.concurrent.ThreadFactory;

public abstract class MultithreadEventLoop extends MultithreadEventExecutor implements EventLoop {

    protected MultithreadEventLoop(int nThreads, ThreadFactory threadFactory,
            Object... args) {
        super(nThreads, threadFactory, args);
    }

    @Override
    public ChannelFuture register(Channel channel) {
        return ((EventLoop) unsafe().nextChild()).register(channel);
    }

    @Override
    public ChannelFuture register(Channel channel, ChannelFuture future) {
        return ((EventLoop) unsafe().nextChild()).register(channel, future);
    }
}

Remove a redundant method declaration

Remove a redundant method declaration


package uk.ac.ebi.quickgo.index.annotation.coterms;

import java.util.Iterator;
import org.springframework.batch.item.ItemReader;

/**
 * Provide a list of all GO Terms for which co-occurrence has been determined ( which is all of them that have been
 * processed, since at worst a GO Term will have a statistic for co-occurring with itself).
 *
 * @author Tony Wardell
 * Date: 07/09/2016
 * Time: 15:38
 * Created with IntelliJ IDEA.
 */
class Co_occurringTermItemReader implements ItemReader<String> {

    private final AnnotationCoOccurringTermsAggregator aggregator;
    private Iterator<String> termsIt;

    public Co_occurringTermItemReader(AnnotationCoOccurringTermsAggregator annotationCoOccurringTermsAggregator) {
        this.aggregator = annotationCoOccurringTermsAggregator;

    }

    @Override public String read() throws Exception {

        //Delay providing full list until aggregator has fully processed all records.
        if (termsIt == null) {
            termsIt = aggregator.getTermToTermOverlapMatrix().keySet().iterator();
        }

        if (termsIt.hasNext()) {
            return termsIt.next();
        }

        return null;
    }
}

package uk.ac.ebi.quickgo.index.annotation.coterms;

import java.util.Iterator;
import org.springframework.batch.item.ItemReader;

/**
 * Provide a list of all GO Terms for which co-occurrence has been determined ( which is all of them that have been
 * processed, since at worst a GO Term will have a statistic for co-occurring with itself).
 *
 * @author Tony Wardell
 * Date: 07/09/2016
 * Time: 15:38
 * Created with IntelliJ IDEA.
 */
class Co_occurringTermItemReader implements ItemReader<String> {

    private final AnnotationCoOccurringTermsAggregator aggregator;
    private Iterator<String> termsIt;

    public Co_occurringTermItemReader(AnnotationCoOccurringTermsAggregator annotationCoOccurringTermsAggregator) {
        this.aggregator = annotationCoOccurringTermsAggregator;

    }

    @Override public String read() throws Exception {

        //Delay providing full list until aggregator has fully processed all records.
        if (termsIt == null) {
            termsIt = aggregator.getCoTerms().keySet().iterator();
        }

        if (termsIt.hasNext()) {
            return termsIt.next();
        }

        return null;
    }
}

Rename methods and instance variables to make intentions clearer.


/**
 * Copyright 2015 Google Inc. All Rights Reserved.
 *
 * 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.google.devtools.cdbg.debuglets.java;

/**
 * Defines the version of the Java Cloud Debugger agent.
 */
public final class GcpDebugletVersion {
  /**
   * Major version of the debugger.

   * All agents of the same major version are compatible with each other. In other words an
   * application can mix different agents with the same major version within the same debuggee.
   */
  public static final int MAJOR_VERSION = 2;

  /**
   * Minor version of the agent.
   */
  public static final int MINOR_VERSION = 13;

  /**
   * Debugger agent version string in the format of MAJOR.MINOR.
   */
  public static final String VERSION = String.format("%d.%d", MAJOR_VERSION, MINOR_VERSION);

  /**
   * Main function to print the version string.
   */
  public static void main(String[] args) {
    System.out.println(VERSION);
  }
}

/**
 * Copyright 2015 Google Inc. All Rights Reserved.
 *
 * 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.google.devtools.cdbg.debuglets.java;

/**
 * Defines the version of the Java Cloud Debugger agent.
 */
public final class GcpDebugletVersion {
  /**
   * Major version of the debugger.

   * All agents of the same major version are compatible with each other. In other words an
   * application can mix different agents with the same major version within the same debuggee.
   */
  public static final int MAJOR_VERSION = 2;

  /**
   * Minor version of the agent.
   */
  public static final int MINOR_VERSION = 14;

  /**
   * Debugger agent version string in the format of MAJOR.MINOR.
   */
  public static final String VERSION = String.format("%d.%d", MAJOR_VERSION, MINOR_VERSION);

  /**
   * Main function to print the version string.
   */
  public static void main(String[] args) {
    System.out.println(VERSION);
  }
}

Increment minor version to 2.14 to prepare for a new release.

-------------
Created by MOE: https://github.com/google/moe
MOE_MIGRATED_REVID=156319538


package io.tracee.backend.jbosslogging;

import io.tracee.MDCLike;
import org.jboss.logging.MDC;

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

final class JbossLoggingMdcLikeAdapter implements MDCLike {

    @Override
    public boolean containsKey(String key) {
        return MDC.get(key) != null;
    }

    @Override
    public void put(String key, String value) {
        MDC.put(key, value);
    }

    @Override
    public String get(String key) {

        return (String) MDC.get(key);
    }

    @Override
    public void remove(String key) {
        MDC.remove(key);
    }

    @Override
    public Map<String, String> getCopyOfContext() {
        final Map<String, Object> map = MDC.getMap();
        final Map<String, String> copy = new HashMap<String, String>(map.size());
        for (Map.Entry<String, Object> entry : map.entrySet()) {
            if (!(entry.getValue() instanceof String)) continue;
            copy.put(entry.getKey(), (String) entry.getValue());
        }
        return copy;
    }
}

package io.tracee.backend.jbosslogging;

import io.tracee.MDCLike;
import org.jboss.logging.MDC;

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

final class JbossLoggingMdcLikeAdapter implements MDCLike {

    @Override
    public boolean containsKey(String key) {
        return MDC.get(key) != null;
    }

    @Override
    public void put(String key, String value) {
        MDC.put(key, value);
    }

    @Override
    public String get(String key) {
        return String.valueOf(MDC.get(key));
    }

    @Override
    public void remove(String key) {
        MDC.remove(key);
    }

    @Override
    public Map<String, String> getCopyOfContext() {
        final Map<String, Object> map = MDC.getMap();
        final Map<String, String> copy = new HashMap<String, String>(map.size());
        for (Map.Entry<String, Object> entry : map.entrySet()) {
			copy.put(entry.getKey(), String.valueOf(entry.getValue()));
        }
        return copy;
    }
}

Use String.valueOf() instead. It's more robust against Object values in the MDC.


/*
 * Copyright 2016-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.cxx.toolchain;

import com.facebook.buck.core.toolchain.tool.Tool;
import com.google.common.collect.ImmutableList;
import java.nio.file.Path;

/** Subclass of WindowsCompiler with overrides specific for clang-cl. */
public class ClangClCompiler extends WindowsCompiler {

  public ClangClCompiler(Tool tool) {
    super(tool);
  }

  @Override
  public ImmutableList<String> getFlagsForReproducibleBuild(
      String altCompilationDir, Path currentCellPath) {
    return ImmutableList.of(
        "/Brepro", "-Xclang", "-fdebug-compilation-dir", "-Xclang", altCompilationDir);
  }
}

/*
 * Copyright 2016-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.cxx.toolchain;

import com.facebook.buck.core.toolchain.tool.Tool;
import com.facebook.buck.util.ProcessExecutor;
import com.google.common.collect.ImmutableList;
import java.nio.file.Path;
import java.util.Optional;

/** Subclass of WindowsCompiler with overrides specific for clang-cl. */
public class ClangClCompiler extends WindowsCompiler {

  public ClangClCompiler(Tool tool) {
    super(tool);
  }

  @Override
  public ImmutableList<String> getFlagsForReproducibleBuild(
      String altCompilationDir, Path currentCellPath) {
    return ImmutableList.of(
        "/Brepro", "-Xclang", "-fdebug-compilation-dir", "-Xclang", altCompilationDir);
  }

  @Override
  public Optional<String> getStderr(ProcessExecutor.Result result) {
    // clang-cl is sensible
    return result.getStderr();
  }
}

Fix diagnostics output for clang-cl

Fix diagnostics output for clang-cl

Summary:
clang-cl is sensible and emits diagnostics to stderr, unlike cl.exe.
Override WindowsCompiler's override for this.

Reviewed By: ilya-klyuchnikov

fbshipit-source-id: a251903b5d


package net.wizardsoflua.lua.module.print;

import java.io.IOException;
import java.io.OutputStream;

import net.sandius.rembulan.Table;
import net.sandius.rembulan.lib.BasicLib;
import net.sandius.rembulan.runtime.LuaFunction;

public class PrintRedirector {

  public interface Context {
    public void send(String message);
  }

  public static PrintRedirector installInto(Table env, Context context) {
    return new PrintRedirector(env, context);
  }

  private final Context context;

  public PrintRedirector(Table env, Context context) {
    this.context = context;
    OutputStream out = new ChatOutputStream();
    LuaFunction printFunc = BasicLib.print(out, env);
    env.rawset("print", printFunc);
  }

  private class ChatOutputStream extends org.apache.commons.io.output.ByteArrayOutputStream {
    @Override
    public void flush() throws IOException {
      String message = toString();
      // Remove trailing line-feed.
      if (message.endsWith("\n")) {
        message = message.substring(0, message.length() - 1);
      }
      reset();
      print(message);
    }
  }

  private void print(String message) {
    context.send(TabEncoder.encode(message));
  }
}

package net.wizardsoflua.lua.module.print;

import java.io.IOException;
import java.io.OutputStream;
import java.nio.charset.Charset;
import net.sandius.rembulan.Table;
import net.sandius.rembulan.lib.BasicLib;
import net.sandius.rembulan.runtime.LuaFunction;

public class PrintRedirector {

  public interface Context {
    public void send(String message);
  }

  public static PrintRedirector installInto(Table env, Context context) {
    return new PrintRedirector(env, context);
  }

  private final Context context;

  public PrintRedirector(Table env, Context context) {
    this.context = context;
    OutputStream out = new ChatOutputStream();
    LuaFunction printFunc = BasicLib.print(out, env);
    env.rawset("print", printFunc);
  }

  private class ChatOutputStream extends org.apache.commons.io.output.ByteArrayOutputStream {
    @Override
    public void flush() throws IOException {
      String message = toString(Charset.defaultCharset());
      // Remove trailing line-feed.
      if (message.endsWith("\n")) {
        message = message.substring(0, message.length() - 1);
      }
      reset();
      print(message);
    }
  }

  private void print(String message) {
    context.send(TabEncoder.encode(message));
  }
}

Remove use of the deprecated method ByteArrayOutputStream.toString()


package br.com.bloder.blormlib.validation.validations;

import android.text.TextUtils;
import android.widget.EditText;

import br.com.bloder.blormlib.validation.Validate;
import br.com.bloder.blormlib.validation.Validation;

/**
 * Created by bloder on 31/07/16.
 */
public class Number extends Validation {

  EditText editText;

  @Override
  public Validate validate() {
    return new Validate() {
      @Override
      public boolean validate() {
        editText = (EditText) field;
        if (editText.getText().toString().isEmpty()) return false;
        return TextUtils.isDigitsOnly(editText.getText().toString());
      }

      @Override
      public void onError() {
        editText.setError("This field only accept numbers!");
      }

      @Override
      public void onSuccess() {

      }
    };
  }
}

package br.com.bloder.blormlib.validation.validations;

import android.text.TextUtils;
import android.widget.EditText;

import br.com.bloder.blormlib.validation.Validate;
import br.com.bloder.blormlib.validation.Validation;

/**
 * Created by bloder on 31/07/16.
 */
public class Number extends Validation {

  EditText editText;

  @Override
  public Validate validate() {
    return new Validate() {
      @Override
      public boolean validate() {
        editText = (EditText) field;
        if (editText.getText().toString().isEmpty()) return false;
        return TextUtils.isDigitsOnly(editText.getText().toString());
      }

      @Override
      public void onError() {
        editText.setError(errorMessage != null || !errorMessage.isEmpty() ? errorMessage : "This field only accept numbers!");
      }

      @Override
      public void onSuccess() {

      }
    };
  }
}

Add custom error message to number validation


package com.ezardlabs.dethsquare.multiplayer;

import com.ezardlabs.dethsquare.Component;

import java.nio.ByteBuffer;

public abstract class NetworkBehaviour extends Component {
	private static int networkIdCounter = 0;
	int networkId;
	protected int playerId;
	protected final ByteBuffer data = ByteBuffer.allocate(getSize());

	public NetworkBehaviour() {
		this(networkIdCounter++, Network.getPlayerID());
	}

	NetworkBehaviour(int networkId, int playerId) {
		this.networkId = networkId;
		this.playerId = playerId;
	}

	protected abstract ByteBuffer onSend();

	protected abstract void onReceive(ByteBuffer data, int index);

	public abstract int getSize();
}

package com.ezardlabs.dethsquare.multiplayer;

import com.ezardlabs.dethsquare.Component;

import java.nio.ByteBuffer;
import java.util.Random;

public abstract class NetworkBehaviour extends Component {
	String networkId;
	protected int playerId;
	protected final ByteBuffer data = ByteBuffer.allocate(getSize());

	public NetworkBehaviour() {
		networkId = generateRandomId();
		playerId = Network.getPlayerID();
	}

	private String generateRandomId() {
		char[] chars = {'0',
				'1',
				'2',
				'3',
				'4',
				'5',
				'6',
				'7',
				'8',
				'9',
				'a',
				'b',
				'c',
				'd',
				'e',
				'f',
				'g',
				'h',
				'i',
				'j',
				'k',
				'l',
				'm',
				'n',
				'o',
				'p',
				'q',
				'r',
				's',
				't',
				'u',
				'v',
				'w',
				'x',
				'y',
				'z',
				'A',
				'B',
				'C',
				'D',
				'E',
				'F',
				'G',
				'H',
				'I',
				'J',
				'K',
				'L',
				'M',
				'N',
				'O',
				'P',
				'Q',
				'R',
				'S',
				'T',
				'U',
				'V',
				'W',
				'X',
				'Y',
				'Z'};
		Random r = new Random();
		StringBuilder sb = new StringBuilder(10);
		for (int i = 0; i < sb.capacity(); i++) {
			sb.append(chars[r.nextInt(chars.length)]);
		}
		return sb.toString();
	}

	protected abstract ByteBuffer onSend();

	protected abstract void onReceive(ByteBuffer data, int index);

	public abstract int getSize();
}

Change from integer network IDs to random strings


package de.gurkenlabs.litiengine;

public class GameTime {
  private final IGameLoop gameLoop;

  public GameTime(final IGameLoop loop) {
    this.gameLoop = loop;
  }

  public long getDays() {
    return this.getMilliseconds() / 1000 / 60 / 60 / 24 % 365;
  }

  public long getHours() {
    return this.getMilliseconds() / 1000 / 60 / 60 % 24;
  }

  public long getMilliseconds() {
    return this.gameLoop.convertToMs(this.gameLoop.getTicks());
  }

  public long getMinutes() {
    return this.getMilliseconds() / 1000 / 60 % 60;
  }

  public long getSeconds() {
    return this.getMilliseconds() / 1000 % 60;
  }

  public long getYears() {
    return this.getMilliseconds() / 1000 / 60 / 60 / 24 / 365;
  }
}

package de.gurkenlabs.litiengine;

public class GameTime {
  private final IGameLoop gameLoop;

  public GameTime(final IGameLoop loop) {
    this.gameLoop = loop;
  }

  public long getDays() {
    return getDays(this.getMilliseconds());
  }

  public long getHours() {
    return getHours(this.getMilliseconds());
  }

  public long getMilliseconds() {
    return this.gameLoop.convertToMs(this.gameLoop.getTicks());
  }

  public long getMinutes() {
    return getMinutes(this.getMilliseconds());
  }

  public long getSeconds() {
    return getSeconds(this.getMilliseconds());
  }

  public long getYears() {
    return getYears(this.getMilliseconds());
  }

  public static long getDays(long ms) {
    return ms / 1000 / 60 / 60 / 24 % 365;
  }

  public static long getHours(long ms) {
    return ms / 1000 / 60 / 60 % 24;
  }

  public static long getMinutes(long ms) {
    return ms / 1000 / 60 % 60;
  }

  public static long getSeconds(long ms) {
    return ms / 1000 % 60;
  }

  public static long getMilliSeconds(long ms) {
    return ms % 1000;
  }

  public static long getYears(long ms) {
    return ms / 1000 / 60 / 60 / 24 / 365;
  }
}

Extend game time by static methods to get parts of a time format

Returns integer values for every time division like hours or minutes with the intention to be used for a "timer" like application


package ceylon.language;

import com.redhat.ceylon.compiler.java.metadata.Annotation;
import com.redhat.ceylon.compiler.java.metadata.Annotations;
import com.redhat.ceylon.compiler.java.metadata.CaseTypes;
import com.redhat.ceylon.compiler.java.metadata.Ceylon;
import com.redhat.ceylon.compiler.java.metadata.Name;
import com.redhat.ceylon.compiler.java.metadata.TypeInfo;
import com.redhat.ceylon.compiler.java.metadata.TypeParameter;
import com.redhat.ceylon.compiler.java.metadata.TypeParameters;
import com.redhat.ceylon.compiler.java.metadata.Variance;

@Ceylon(major = 2)
@TypeParameters(@TypeParameter(value = "Other", variance = Variance.OUT,
    		       satisfies="ceylon.language.Ordinal<Other>"))
@CaseTypes(of = "Other")
public interface Ordinal<Other extends Ordinal<? extends Other>> {

    @Annotations(@Annotation("formal"))
    public Other getSuccessor();

    @Annotations(@Annotation("formal"))
    public Other getPredecessor();

    @Annotations(@Annotation("formal"))
    @TypeInfo("ceylon.language.Integer")
    public long distanceFrom(@Name("other")
        @TypeInfo("Other") Other other);
}

package ceylon.language;

import com.redhat.ceylon.compiler.java.metadata.Annotation;
import com.redhat.ceylon.compiler.java.metadata.Annotations;
import com.redhat.ceylon.compiler.java.metadata.CaseTypes;
import com.redhat.ceylon.compiler.java.metadata.Ceylon;
import com.redhat.ceylon.compiler.java.metadata.Name;
import com.redhat.ceylon.compiler.java.metadata.TypeInfo;
import com.redhat.ceylon.compiler.java.metadata.TypeParameter;
import com.redhat.ceylon.compiler.java.metadata.TypeParameters;
import com.redhat.ceylon.compiler.java.metadata.Variance;

@Ceylon(major = 2)
@TypeParameters(@TypeParameter(value = "Other", variance = Variance.NONE,
    		       satisfies="ceylon.language.Ordinal<Other>"))
@CaseTypes(of = "Other")
public interface Ordinal<Other extends Ordinal<? extends Other>> {

    @Annotations(@Annotation("formal"))
    public Other getSuccessor();

    @Annotations(@Annotation("formal"))
    public Other getPredecessor();

    @Annotations(@Annotation("formal"))
    @TypeInfo("ceylon.language.Integer")
    public long distanceFrom(@Name("other")
        @TypeInfo("Other") Other other);
}

Change variance of type parameter

Change variance of type parameter


import java.applet.*;
import java.awt.*;

public class PingsApplet extends Applet {

    private final String SERVER_HOSTNAME = "localhost";
    private final int SERVER_PORT = 6543;

    private PingsClient m_pings_client;

    public void init() {
        // Initialization (on page load).
        m_pings_client = new PingsClient(SERVER_HOSTNAME, SERVER_PORT);
        m_pings_client.start();
    }

    public void destroy() {
        // Don't leave the Pings client thread running!
        m_pings_client.interrupt();
    }

    public void paint(Graphics g) {
        // Draw applet here.
        g.setColor(Color.gray);
    }
}

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

public class PingsApplet extends JApplet {

    private final String SERVER_HOSTNAME = "localhost";
    private final int SERVER_PORT = 6543;

    private PingsClient m_pings_client;

    public void init() {
        // Initialization (on page load).
        m_pings_client = new PingsClient(SERVER_HOSTNAME, SERVER_PORT);
        m_pings_client.start();
    }

    public void destroy() {
        // Don't leave the Pings client thread running!
        m_pings_client.interrupt();
    }

    public void paint(Graphics g) {
        // Draw applet here.
        g.setColor(Color.gray);
    }
}

Use Swing-enabled JApplet class as base class for our applet instead.


package io.quarkus.deployment;

import java.util.Optional;

import io.quarkus.deployment.annotations.BuildProducer;
import io.quarkus.deployment.annotations.BuildStep;
import io.quarkus.deployment.builditem.SslNativeConfigBuildItem;
import io.quarkus.deployment.builditem.nativeimage.RuntimeReinitializedClassBuildItem;
import io.quarkus.runtime.annotations.ConfigItem;
import io.quarkus.runtime.annotations.ConfigPhase;
import io.quarkus.runtime.annotations.ConfigRoot;

public class SslProcessor {

    private static final String JAVA_11_PLUS_SSL_LOGGER = "sun.security.ssl.SSLLogger";
    private static final String JAVA_8_PLUS_SSL_LOGGER = "sun.security.ssl.Debug";

    SslConfig ssl;

    @ConfigRoot(phase = ConfigPhase.BUILD_TIME)
    static class SslConfig {
        /**
         * Enable native SSL support.
         */
        @ConfigItem(name = "native")
        Optional<Boolean> native_;
    }

    @BuildStep
    SslNativeConfigBuildItem setupNativeSsl() {
        return new SslNativeConfigBuildItem(ssl.native_);
    }

    @BuildStep
    void runtime(BuildProducer<RuntimeReinitializedClassBuildItem> reinitialized) {
        registerIfExists(reinitialized, JAVA_11_PLUS_SSL_LOGGER);
        registerIfExists(reinitialized, JAVA_8_PLUS_SSL_LOGGER);
    }

    private void registerIfExists(BuildProducer<RuntimeReinitializedClassBuildItem> reinitialized, String className) {
        try {
            Class.forName(className, false, Thread.currentThread().getContextClassLoader());
            reinitialized.produce(new RuntimeReinitializedClassBuildItem(className));
        } catch (ClassNotFoundException ignored) {

        }
    }
}

package io.quarkus.deployment;

import java.util.Optional;

import io.quarkus.deployment.annotations.BuildProducer;
import io.quarkus.deployment.annotations.BuildStep;
import io.quarkus.deployment.builditem.SslNativeConfigBuildItem;
import io.quarkus.deployment.builditem.nativeimage.RuntimeReinitializedClassBuildItem;
import io.quarkus.runtime.annotations.ConfigItem;
import io.quarkus.runtime.annotations.ConfigPhase;
import io.quarkus.runtime.annotations.ConfigRoot;

public class SslProcessor {

    private static final String JAVA_11_PLUS_SSL_LOGGER = "sun.security.ssl.SSLLogger";

    SslConfig ssl;

    @ConfigRoot(phase = ConfigPhase.BUILD_TIME)
    static class SslConfig {
        /**
         * Enable native SSL support.
         */
        @ConfigItem(name = "native")
        Optional<Boolean> native_;
    }

    @BuildStep
    SslNativeConfigBuildItem setupNativeSsl() {
        return new SslNativeConfigBuildItem(ssl.native_);
    }

    @BuildStep
    void runtime(BuildProducer<RuntimeReinitializedClassBuildItem> reinitialized) {
        reinitialized.produce(new RuntimeReinitializedClassBuildItem(JAVA_11_PLUS_SSL_LOGGER));
    }
}

Remove conditional code testing JDK 8

Remove conditional code testing JDK 8


package info.u_team.u_team_core.item.armor;

import info.u_team.u_team_core.util.ItemProperties;
import net.minecraft.item.*;
import net.minecraft.item.Item.Properties;

public class ArmorSetCreator {

	public static ArmorSet create(String name, Properties properties, IArmorMaterial material) {
		return create(name, null, properties, material);
	}

	public static ArmorSet create(String name, ItemGroup group, Properties properties, IArmorMaterial material) {
		return new ArmorSet(new UHelmetItem(name, group, new ItemProperties(properties), material), new UChestplateItem(name, group, new ItemProperties(properties), material), new ULeggingsItem(name, group, new ItemProperties(properties), material), new UBootsItem(name, group, new ItemProperties(properties), material));
	}
}

package info.u_team.u_team_core.item.armor;

import info.u_team.u_team_core.util.ItemProperties;
import net.minecraft.item.*;
import net.minecraft.item.Item.Properties;
import net.minecraftforge.fml.RegistryObject;
import net.minecraftforge.registries.DeferredRegister;

public class ArmorSetCreator {

	public static ArmorSet create(DeferredRegister<Item> register, String name, Properties properties, IArmorMaterial material) {
		return create(register, name, null, properties, material);
	}

	public static ArmorSet create(DeferredRegister<Item> register, String name, ItemGroup group, Properties properties, IArmorMaterial material) {
		final RegistryObject<UHelmetItem> helmet = register.register(name + "_helmet", () -> new UHelmetItem(name, group, new ItemProperties(properties), material));
		final RegistryObject<UChestplateItem> chestplate = register.register(name + "_chestplate", () -> new UChestplateItem(name, group, new ItemProperties(properties), material));
		final RegistryObject<ULeggingsItem> leggings = register.register(name + "_leggings", () -> new ULeggingsItem(name, group, new ItemProperties(properties), material));
		final RegistryObject<UBootsItem> boots = register.register(name + "_boots", () -> new UBootsItem(name, group, new ItemProperties(properties), material));

		return new ArmorSet(helmet, chestplate, leggings, boots);
	}
}

Update armor set with new register

Update armor set with new register


package wge3.game.entity.creatures;

import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.graphics.g2d.Batch;
import com.badlogic.gdx.graphics.glutils.ShapeRenderer;
import static wge3.game.engine.constants.StateFlag.PICKS_UP_ITEMS;
import static wge3.game.engine.constants.Team.PlayerTeam;

public final class Player extends Creature {

    private OrthographicCamera camera;
    private ShapeRenderer shapeRenderer;
    private boolean showHP;

    public Player() {
        setSprite(4, 3);
        team = PlayerTeam;
        size = 14;
        HP.setMaximum(100);
        strength = 10;
        defense = 5;

        stateFlags.add(PICKS_UP_ITEMS);
        System.out.println(stateFlags);
        showHP = true;
        shapeRenderer = new ShapeRenderer();
    }

    public void setCamera(OrthographicCamera camera) {
        this.camera = camera;
    }

    @Override
    public void move(float dx, float dy) {
        float oldX = getX();
        float oldY = getY();
        super.move(dx, dy);
        camera.translate(getX() - oldX, getY() - oldY);
        camera.update();
    }

    @Override
    public void draw(Batch batch) {
        super.draw(batch);
    }
}

package wge3.game.entity.creatures;

import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.graphics.g2d.Batch;
import com.badlogic.gdx.graphics.glutils.ShapeRenderer;
import wge3.game.engine.constants.StateFlag;
import static wge3.game.engine.constants.Team.PlayerTeam;

public final class Player extends Creature {

    private OrthographicCamera camera;
    private ShapeRenderer shapeRenderer;
    private boolean showHP;

    public Player() {
        setSprite(4, 3);
        team = PlayerTeam;
        size = 14;
        HP.setMaximum(100);
        strength = 10;
        defense = 5;

        stateFlags.add(StateFlag.PICKS_UP_ITEMS);
        showHP = true;
        shapeRenderer = new ShapeRenderer();
    }

    public void setCamera(OrthographicCamera camera) {
        this.camera = camera;
    }

    @Override
    public void move(float dx, float dy) {
        float oldX = getX();
        float oldY = getY();
        super.move(dx, dy);
        camera.translate(getX() - oldX, getY() - oldY);
        camera.update();
    }

    @Override
    public void draw(Batch batch) {
        super.draw(batch);
    }
}

Include enum class name when using flags.


package com.github.aureliano.edocs.app.gui.menu.help;

import javax.swing.JMenu;
import javax.swing.event.MenuEvent;
import javax.swing.event.MenuListener;

import com.github.aureliano.edocs.app.model.IDatabaseConnectionDependent;
import com.github.aureliano.edocs.common.locale.EdocsLocale;

public class HelpMenu extends JMenu implements IDatabaseConnectionDependent {

	private static final long serialVersionUID = -3275074190970882751L;

	private LicenseMenuItem licenseMenuItem;
	private AboutMenuItem aboutMenuItem;

	public HelpMenu() {
		super.setText(EdocsLocale.instance().getMessage(""));
		this.addMenuItems();
	}

	private void addMenuItems() {
		this.licenseMenuItem = new LicenseMenuItem();
		this.aboutMenuItem = new AboutMenuItem();

		super.add(this.licenseMenuItem);
		super.add(this.aboutMenuItem);

		super.addMenuListener(new MenuListener() {

			@Override
			public void menuSelected(MenuEvent e) {
				licenseMenuItem.setMenuItemAvailability();
				aboutMenuItem.setMenuItemAvailability();
			}

			@Override
			public void menuDeselected(MenuEvent e) {}

			@Override
			public void menuCanceled(MenuEvent e) {}
		});
	}

	@Override
	public void setDatabaseGuiEnabled(boolean enabled) {}
}

package com.github.aureliano.edocs.app.gui.menu.help;

import javax.swing.JMenu;
import javax.swing.event.MenuEvent;
import javax.swing.event.MenuListener;

import com.github.aureliano.edocs.app.model.IDatabaseConnectionDependent;
import com.github.aureliano.edocs.common.locale.EdocsLocale;

public class HelpMenu extends JMenu implements IDatabaseConnectionDependent {

	private static final long serialVersionUID = -3275074190970882751L;

	private LicenseMenuItem licenseMenuItem;
	private AboutMenuItem aboutMenuItem;

	public HelpMenu() {
		super.setText(EdocsLocale.instance().getMessage("gui.menubar.help"));
		this.addMenuItems();
	}

	private void addMenuItems() {
		this.licenseMenuItem = new LicenseMenuItem();
		this.aboutMenuItem = new AboutMenuItem();

		super.add(this.licenseMenuItem);
		super.add(this.aboutMenuItem);

		super.addMenuListener(new MenuListener() {

			@Override
			public void menuSelected(MenuEvent e) {
				licenseMenuItem.setMenuItemAvailability();
				aboutMenuItem.setMenuItemAvailability();
			}

			@Override
			public void menuDeselected(MenuEvent e) {}

			@Override
			public void menuCanceled(MenuEvent e) {}
		});
	}

	@Override
	public void setDatabaseGuiEnabled(boolean enabled) {}
}

Set text to help menu.

Set text to help menu.


/**
 *
 */
package org.mwc.cmap.plotViewer.actions;

import org.mwc.cmap.core.CorePlugin;
import org.mwc.cmap.core.operations.DebriefActionWrapper;

import MWC.GUI.PlainChart;
import MWC.GUI.Tools.Action;
import MWC.GenericData.WorldArea;

/**
 * @author ian.mayo
 *
 */
public class FitToWindow extends CoreEditorAction
{
	protected void execute()
	{
		PlainChart theChart = getChart();

		WorldArea oldArea = new WorldArea(theChart.getCanvas().getProjection().getVisibleDataArea());
		Action theAction = 	new MWC.GUI.Tools.Chart.FitToWin.FitToWinAction(theChart, oldArea);

		// and wrap it
		DebriefActionWrapper daw = new DebriefActionWrapper(theAction, null);

		// and add it to the clipboard
		CorePlugin.run(daw);

	}

}

/**
 *
 */
package org.mwc.cmap.plotViewer.actions;

import org.mwc.cmap.core.CorePlugin;
import org.mwc.cmap.core.operations.DebriefActionWrapper;

import MWC.GUI.PlainChart;
import MWC.GUI.Tools.Action;
import MWC.GenericData.WorldArea;

/**
 * @author ian.mayo
 *
 */
public class FitToWindow extends CoreEditorAction
{
	protected void execute()
	{
		PlainChart theChart = getChart();

		WorldArea oldArea = new WorldArea(theChart.getCanvas().getProjection().getVisibleDataArea());
		Action theAction = 	new MWC.GUI.Tools.Chart.FitToWin.FitToWinAction(theChart, oldArea);

		// and wrap it
		DebriefActionWrapper daw = new DebriefActionWrapper(theAction, theChart.getLayers());

		// and add it to the clipboard
		CorePlugin.run(daw);

	}

}

Include parent layers object, to ease update

git-svn-id: d2601f1668e3cd2de409f5c059006a6eeada0abf@1481 cb33b658-6c9e-41a7-9690-cba343611204


package org.pentaho.platform.dataaccess.datasource.wizard.models;

/**
 * User: nbaker
 * Date: Aug 13, 2010
 */
public class DatasourceDTOUtil {

  public static DatasourceDTO generateDTO(DatasourceModel model){
    DatasourceDTO dto = new DatasourceDTO();
    dto.setDatasourceName(model.getDatasourceName());
    dto.setCsvModelInfo(model.getModelInfo());
    dto.setDatasourceType(model.getDatasourceType());
    dto.setQuery(model.getQuery());
    dto.setConnectionName(model.getSelectedRelationalConnection().getName());
    return dto;
  }

  public static void populateModel(DatasourceDTO dto, DatasourceModel model){
    model.setDatasourceName(dto.getDatasourceName());
    model.setModelInfo(dto.getCsvModelInfo());
    model.setDatasourceType(dto.getDatasourceType());
    model.setQuery(dto.getQuery());
    model.setSelectedRelationalConnection(model.getGuiStateModel().getConnectionByName(dto.getConnectionName()));
  }

}

package org.pentaho.platform.dataaccess.datasource.wizard.models;

/**
 * User: nbaker
 * Date: Aug 13, 2010
 */
public class DatasourceDTOUtil {

  public static DatasourceDTO generateDTO(DatasourceModel model){
    DatasourceDTO dto = new DatasourceDTO();
    dto.setDatasourceName(model.getDatasourceName());
    dto.setCsvModelInfo(model.getModelInfo());
    dto.setDatasourceType(model.getDatasourceType());
    dto.setQuery(model.getQuery());
    if(model.getSelectedRelationalConnection() != null){
    	dto.setConnectionName(model.getSelectedRelationalConnection().getName());
    }
    return dto;
  }

  public static void populateModel(DatasourceDTO dto, DatasourceModel model){
    model.setDatasourceName(dto.getDatasourceName());
    model.setModelInfo(dto.getCsvModelInfo());
    model.setDatasourceType(dto.getDatasourceType());
    model.setQuery(dto.getQuery());
    model.setSelectedRelationalConnection(model.getGuiStateModel().getConnectionByName(dto.getConnectionName()));
  }

}

Fix for BISERVER-7626 Unable to create a CSV based data source


package com.sedmelluq.discord.lavaplayer.container.mp3;

import com.sedmelluq.discord.lavaplayer.tools.io.SeekableInputStream;
import com.sedmelluq.discord.lavaplayer.track.AudioTrackInfo;
import com.sedmelluq.discord.lavaplayer.track.BaseAudioTrack;
import com.sedmelluq.discord.lavaplayer.track.playback.AudioTrackExecutor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * Audio track that handles an MP3 stream
 */
public class Mp3AudioTrack extends BaseAudioTrack {
  private static final Logger log = LoggerFactory.getLogger(Mp3AudioTrack.class);

  private final SeekableInputStream inputStream;

  /**
   * @param executor Track executor
   * @param trackInfo Track info
   * @param inputStream Input stream for the MP3 file
   */
  public Mp3AudioTrack(AudioTrackExecutor executor, AudioTrackInfo trackInfo, SeekableInputStream inputStream) {
    super(executor, trackInfo);

    this.inputStream = inputStream;
  }

  @Override
  public void process(AtomicInteger volumeLevel) throws Exception {
    Mp3StreamingFile file = new Mp3StreamingFile(inputStream, executor.getFrameConsumer(), volumeLevel);
    file.parseHeaders();

    log.debug("Starting to play MP3 track {}", getIdentifier());

    try {
      executor.executeProcessingLoop(file::provideFrames, file::seekToTimecode);
    } finally {
      file.close();
    }
  }
}

package com.sedmelluq.discord.lavaplayer.container.mp3;

import com.sedmelluq.discord.lavaplayer.tools.io.SeekableInputStream;
import com.sedmelluq.discord.lavaplayer.track.AudioTrackInfo;
import com.sedmelluq.discord.lavaplayer.track.BaseAudioTrack;
import com.sedmelluq.discord.lavaplayer.track.playback.AudioTrackExecutor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * Audio track that handles an MP3 stream
 */
public class Mp3AudioTrack extends BaseAudioTrack {
  private static final Logger log = LoggerFactory.getLogger(Mp3AudioTrack.class);

  private final SeekableInputStream inputStream;

  /**
   * @param executor Track executor
   * @param trackInfo Track info
   * @param inputStream Input stream for the MP3 file
   */
  public Mp3AudioTrack(AudioTrackExecutor executor, AudioTrackInfo trackInfo, SeekableInputStream inputStream) {
    super(executor, trackInfo);

    this.inputStream = inputStream;
  }

  @Override
  public void process(AtomicInteger volumeLevel) throws Exception {
    Mp3StreamingFile file = new Mp3StreamingFile(inputStream, executor.getFrameConsumer(), volumeLevel);

    try {
      file.parseHeaders();

      log.debug("Starting to play MP3 track {}", getIdentifier());
      executor.executeProcessingLoop(file::provideFrames, file::seekToTimecode);
    } finally {
      file.close();
    }
  }
}

Fix MP3 track not closed when header parsing fails.


// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.jrt;

import java.nio.ByteBuffer;

/**
 * Data value (a sequence of bytes)
 **/
public class DataValue extends Value
{
    private byte[] value;

    /**
     * Create from a Java-type value
     *
     * @param value the value
     **/
    public DataValue(byte[] value) { this.value = value; }

    /**
     * Create by decoding the value from the given buffer
     *
     * @param src buffer where the value is stored
     **/
    DataValue(ByteBuffer src) {
        int size = src.getInt();
        value = new byte[size];
        src.get(value);
    }

    /**
     * @return DATA
     **/
    public byte type() { return DATA; }
    public int count() { return 1; }

    int bytes() { return 4 + value.length; }
    void encode(ByteBuffer dst) {
        dst.putInt(value.length);
        dst.put(value);
    }

    public byte[] asData() { return value; }

    @Override
    public String toString() {
        return String.valueOf(value);
    }

}

// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.jrt;

import java.nio.ByteBuffer;

/**
 * Data value (a sequence of bytes)
 **/
public class DataValue extends Value
{
    private final byte[] value;

    /**
     * Create from a Java-type value
     *
     * @param value the value
     **/
    public DataValue(byte[] value) { this.value = value; }

    /**
     * Create by decoding the value from the given buffer
     *
     * @param src buffer where the value is stored
     **/
    public DataValue(ByteBuffer src) {
        int size = src.getInt();
        value = new byte[size];
        src.get(value);
    }

    /**
     * @return DATA
     **/
    public byte type() { return DATA; }
    public int count() { return 1; }

    int bytes() { return 4 + value.length; }
    void encode(ByteBuffer dst) {
        dst.putInt(value.length);
        dst.put(value);
    }

    public byte[] asData() { return value; }

    @Override
    public String toString() {
        return String.valueOf(value);
    }

}

Make constructor public and member final


public class ControlFlow {

	public static void main(String[] args) {
		int value = 0;

		while (value < 10) {
			System.out.println(value);
			value = value + 1;
		}

		for (int i=0; i<90; i++) {
			System.out.println(i);
		}

		int checker = -11;
		if (checker > 10) {
			System.out.println("checker greater than ten");
		} else if (checker > 0 && checker <= 10)  {
			System.out.println("checker is less than or equal to 10 but greater that zero");
		} else {
			System.out.println("checker is less than zero");
		}
	}

}

import java.util.Scanner;

public class ControlFlow {

	private static Scanner input;

	public static void main(String[] args) {
		int value = 0;

		while (value < 10) {
			System.out.println(value);
			value = value + 1;
		}

		for (int i=0; i<90; i++) {
			System.out.println(i);
		}

		input = new Scanner(System.in);
		System.out.println("Enter a number");
		int checker = input.nextInt();
		if (checker > 10) {
			System.out.println("checker greater than ten");
		} else if (checker > 0 && checker <= 10)  {
			System.out.println("checker is less than or equal to 10 but greater that zero");
		} else {
			System.out.println("checker is less than zero");
		}
	}

}

Use scanner to get input

Use scanner to get input


package com.techern.minecraft.melonblockdrop;

import net.minecraft.init.Blocks;
import net.minecraft.item.ItemStack;
import net.minecraftforge.event.world.BlockEvent;
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent;

/**
 * An event handler for when breaking {@link net.minecraft.block.BlockMelon}s
 *
 * @since 1.0.0
 */
public class MelonBlockHarvestEventHandler {

    /**
     * Called when harvesting any block
     *
     * @param event The {@link net.minecraftforge.event.world.BlockEvent.HarvestDropsEvent}
     *
     * @since 1.0.0
     */
    @SubscribeEvent
    public void harvest(BlockEvent.HarvestDropsEvent event) {

        if (event.state.getBlock().equals(Blocks.melon_block)) {
            //We're doing a melon block

            //First reset the drop list
            event.drops.clear();

            //Then add the new drop
            event.drops.add(new ItemStack(Blocks.melon_block, 1));

        } //Do nothing if not

    }

}

package com.techern.minecraft.melonblockdrop;

import net.minecraft.init.Blocks;
import net.minecraft.item.ItemStack;
import net.minecraftforge.event.world.BlockEvent;
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent;

/**
 * An event handler for when breaking {@link net.minecraft.block.BlockMelon}s
 *
 * @since 1.0.0
 */
public class MelonBlockHarvestEventHandler {

    /**
     * Called when harvesting any block
     *
     * @param event The {@link net.minecraftforge.event.world.BlockEvent.HarvestDropsEvent}
     *
     * @since 1.0.0
     */
    @SubscribeEvent
    public void harvest(BlockEvent.HarvestDropsEvent event) {

        if (event.getState().getBlock().equals(Blocks.melon_block)) {
            //We're doing a melon block

            //First reset the drop list
            event.getDrops().clear();

            //Then add the new drop
            event.getDrops().add(new ItemStack(Blocks.melon_block, 1));

        } //Do nothing if not

    }

}

Fix the drop harvest event

Fix the drop harvest event


package com.nbsp.materialfilepicker.utils;

import java.io.File;
import java.io.FileFilter;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

/**
 * Created by Dimorinny on 24.10.15.
 */
public class FileUtils {
    public static List<File> getFileListByDirPath(FileFilter filter, PickerState pickerState) {
        File directory = new File(pickerState.getPath());
        File[] files = directory.listFiles(filter);

        if (files == null) {
            return new ArrayList<>();
        }

        List<File> result = Arrays.asList(files);
        Collections.sort(result, new FileComparator(pickerState.getSortMethod(),
                pickerState.isSortDirectionAsc()));
        return result;
    }

    public static String cutLastSegmentOfPath(String path) {
        return path.substring(0, path.lastIndexOf("/"));
    }

    public static String getReadableFileSize(long size) {
        if (size <= 0) return "0";
        final String[] units = new String[]{"B", "KB", "MB", "GB", "TB"};
        int digitGroups = (int) (Math.log10(size) / Math.log10(1024));
        return new DecimalFormat("#").format(size / Math.pow(1024, digitGroups)) + " " + units[digitGroups];
    }
}

package com.nbsp.materialfilepicker.utils;

import java.io.File;
import java.io.FileFilter;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

/**
 * Created by Dimorinny on 24.10.15.
 */
public class FileUtils {
    public static List<File> getFileListByDirPath(FileFilter filter, PickerState pickerState) {
        File directory = new File(pickerState.getPath());
        File[] files = directory.listFiles(filter);

        if (files == null) {
            return new ArrayList<>();
        }

        List<File> result = Arrays.asList(files);
        Collections.sort(result, new FileComparator(pickerState.getSortMethod(),
                pickerState.isSortDirectionAsc()));
        return result;
    }

    public static String cutLastSegmentOfPath(String path) {
        if(path.contains("/")) return path.substring(0, path.lastIndexOf("/"));
        else return "/";
    }

    public static String getReadableFileSize(long size) {
        if (size <= 0) return "0";
        final String[] units = new String[]{"B", "KB", "MB", "GB", "TB"};
        int digitGroups = (int) (Math.log10(size) / Math.log10(1024));
        return new DecimalFormat("#").format(size / Math.pow(1024, digitGroups)) + " " + units[digitGroups];
    }
}

Fix crash when you try to ascend above the root directory


package typecheck;

import java.util.*;

public class SubtypingRelation {
    private static Map<Symbol, Set<Symbol>> relation = new LinkedHashMap<>();

    public static void insert(Symbol base, Symbol child) {
        relation.putIfAbsent(base, new HashSet<>());
        relation.get(base).add(child);

        // Subtyping is transitive
        for (Iterator<Symbol> it = relation.keySet().iterator(); it.hasNext(); ) {
            Symbol s = it.next();

            if (s.equals(base)) {
                Set<Symbol> children = relation.get(s);
                if (children.contains(base))
                    children.add(child);
            }
        }
    }

    public static boolean isSubtyping(Symbol child, Symbol base) {
        if (relation.containsKey(base))
            return relation.get(base).contains(child);
        else
            return false;
    }

    public static boolean contains(Symbol c) {
        return relation.containsKey(c);
    }
}

package typecheck;

import java.util.*;

public class SubtypingRelation {
    private static Map<Symbol, Set<Symbol>> relation = new LinkedHashMap<>();

    public static void insert(Symbol base, Symbol child) {
        relation.putIfAbsent(base, new LinkedHashSet<>());
        relation.get(base).add(child);

        // Subtyping is transitive
        for (Iterator<Symbol> it = relation.keySet().iterator(); it.hasNext(); ) {
            Symbol s = it.next();

            if (s.equals(base)) {
                Set<Symbol> children = relation.get(s);
                if (children.contains(base))
                    children.add(child);
            }
        }
    }

    public static boolean isSubtyping(Symbol child, Symbol base) {
        if (relation.containsKey(base))
            return relation.get(base).contains(child);
        else
            return false;
    }

    public static boolean contains(Symbol c) {
        return relation.containsKey(c);
    }
}

Change to LinkedHashSet to keep insertion order.


package com.jakewharton.threetenabp;

import android.app.Application;
import java.io.IOException;
import java.io.InputStream;
import java.util.concurrent.atomic.AtomicBoolean;
import org.threeten.bp.zone.TzdbZoneRulesProvider;
import org.threeten.bp.zone.ZoneRulesProvider;

/** Android-specific initializer for the JSR-310 library. */
public final class AndroidThreeTen {
  private static final AtomicBoolean initialized = new AtomicBoolean();

  public static void init(Application application) {
    if (initialized.getAndSet(true)) {
      return;
    }

    TzdbZoneRulesProvider provider;
    InputStream is = null;
    try {
      is = application.getAssets().open("org/threeten/bp/TZDB.dat");
      provider = new TzdbZoneRulesProvider(is);
    } catch (IOException e) {
      throw new IllegalStateException("TZDB.dat missing from assets.", e);
    } finally {
      if (is != null) {
        try {
          is.close();
        } catch (IOException ignored) {
        }
      }
    }

    ZoneRulesProvider.registerProvider(provider);
  }

  private AndroidThreeTen() {
    throw new AssertionError("No instances.");
  }
}

package com.jakewharton.threetenabp;

import android.app.Application;
import android.content.Context;
import java.io.IOException;
import java.io.InputStream;
import java.util.concurrent.atomic.AtomicBoolean;
import org.threeten.bp.zone.TzdbZoneRulesProvider;
import org.threeten.bp.zone.ZoneRulesProvider;

/** Android-specific initializer for the JSR-310 library. */
public final class AndroidThreeTen {
  private static final AtomicBoolean initialized = new AtomicBoolean();

  public static void init(Application application) {
    init((Context) application);
  }

  public static void init(Context context) {
    if (initialized.getAndSet(true)) {
      return;
    }

    TzdbZoneRulesProvider provider;
    InputStream is = null;
    try {
      is = context.getAssets().open("org/threeten/bp/TZDB.dat");
      provider = new TzdbZoneRulesProvider(is);
    } catch (IOException e) {
      throw new IllegalStateException("TZDB.dat missing from assets.", e);
    } finally {
      if (is != null) {
        try {
          is.close();
        } catch (IOException ignored) {
        }
      }
    }

    ZoneRulesProvider.registerProvider(provider);
  }

  private AndroidThreeTen() {
    throw new AssertionError("No instances.");
  }
}

Add a version of the init method that accepts Context as a parameter

Closes #34


package codechicken.lib.util.registry;

import net.minecraft.util.ResourceLocation;
import net.minecraftforge.fml.common.registry.LegacyNamespacedRegistry;

import javax.annotation.Nullable;
import java.util.HashMap;

public class DuplicateValueRegistry<V> extends LegacyNamespacedRegistry<V> {

    private final LegacyNamespacedRegistry<V> wrapped;
    private final HashMap<V, ResourceLocation> classMap = new HashMap<>();

    public DuplicateValueRegistry(LegacyNamespacedRegistry<V> wrapped) {
        this.wrapped = wrapped;
    }

    @Nullable
    @Override
    public ResourceLocation getNameForObject(V value) {
        if (classMap.containsKey(value)) {
            return classMap.get(value);
        }
        return wrapped.getNameForObject(value);
    }

    public void addMapping(V clazz, ResourceLocation mapping) {
        classMap.put(clazz, mapping);
    }
}

package codechicken.lib.util.registry;

import net.minecraft.util.ResourceLocation;
import net.minecraftforge.fml.common.registry.LegacyNamespacedRegistry;

import javax.annotation.Nullable;
import java.util.HashMap;

public class DuplicateValueRegistry extends LegacyNamespacedRegistry {

    private final LegacyNamespacedRegistry wrapped;
    private final HashMap<Object, ResourceLocation> classMap = new HashMap<>();

    public DuplicateValueRegistry(LegacyNamespacedRegistry wrapped) {
        this.wrapped = wrapped;
    }

    @SuppressWarnings ("unchecked")
    @Nullable
    @Override
    public ResourceLocation getNameForObject(Object value) {
        if (classMap.containsKey(value)) {
            return classMap.get(value);
        }
        return (ResourceLocation) wrapped.getNameForObject(value);
    }

    public void addMapping(Object clazz, ResourceLocation mapping) {
        classMap.put(clazz, mapping);
    }
}

Fix some bullshit with generics.

Fix some bullshit with generics.


package edu.brown.hackathon.fifteenminutes;

import com.google.appengine.api.datastore.Entity;

/**
 *  All the info about a famous user that is sent to the client.
 */
public class UserResource {

  private long userId;

  public UserResource(long userId) {
    this.userId = userId;
  }

  public static long parseUserIdFromEntity(Entity user) {
    return Long.parseLong((String)user.getProperty("user_id"));
  }
}

package edu.brown.hackathon.fifteenminutes;

import com.google.appengine.api.datastore.Entity;

/**
 *  All the info about a famous user that is sent to the client.
 */
public class UserResource {

  private long userId;

  public UserResource(long userId) {
    this.userId = userId;
  }

  public static long parseUserIdFromEntity(Entity user) {
    Object userId = user.getProperty("user_id");
    if (userId instanceof Long) {
      return (Long) userId;
    } else {
      return Long.parseLong((String) userId);
    }
  }
}

Deal with numeric or non-numeric user IDs.


package com.github.sandorw.mocabogaso.games.tictactoe;

import static org.junit.Assert.*;

import org.junit.Test;

import com.github.sandorw.mocabogaso.Game;
import com.github.sandorw.mocabogaso.games.GameResult;
import com.github.sandorw.mocabogaso.games.defaults.DefaultGameMove;
import com.github.sandorw.mocabogaso.games.mnkgame.MNKGameState;
import com.github.sandorw.mocabogaso.players.AIPlayerFactory;

public class TicTacToeGameStateTest {

    @Test
    public void playFullGameTest() {
        TicTacToeGameState gameState = TicTacToeGameState.of();
        Game<DefaultGameMove, MNKGameState> game = new Game<>(gameState);
        game.addPlayer("X", AIPlayerFactory.getNewAIPlayer(gameState, 50));
        game.addPlayer("O", AIPlayerFactory.getNewAIPlayer(gameState, 50));
        game.playGame();
        assertTrue(game.isGameOver());
        GameResult gameResult = game.getGameResult();
        assertTrue(gameResult.isTie());
    }

}

package com.github.sandorw.mocabogaso.games.tictactoe;

import static org.junit.Assert.*;

import org.junit.Test;

import com.github.sandorw.mocabogaso.Game;
import com.github.sandorw.mocabogaso.games.GameResult;
import com.github.sandorw.mocabogaso.games.defaults.DefaultGameMove;
import com.github.sandorw.mocabogaso.games.mnkgame.MNKGameState;
import com.github.sandorw.mocabogaso.players.AIPlayerFactory;

public class TicTacToeGameStateTest {

    @Test
    public void playFullGameTest() {
        TicTacToeGameState gameState = TicTacToeGameState.of();
        Game<DefaultGameMove, MNKGameState> game = new Game<>(gameState);
        game.addPlayer("X", AIPlayerFactory.getNewAIPlayer(gameState, 150));
        game.addPlayer("O", AIPlayerFactory.getNewAIPlayer(gameState, 150));
        game.playGame();
        assertTrue(game.isGameOver());
        GameResult gameResult = game.getGameResult();
        assertTrue(gameResult.isTie());
    }

}

Increase turn timer to avoid flaky test

Increase turn timer to avoid flaky test

Longer turn timer for Tic Tac Toe game test


package org.openntf.domino.tests.ntf;

import lotus.domino.NotesFactory;

import org.openntf.domino.Database;
import org.openntf.domino.Session;
import org.openntf.domino.thread.DominoThread;
import org.openntf.domino.utils.Factory;

public class DominoRunnable implements Runnable {
	public static void main(String[] args) {
		DominoThread thread = new DominoThread(new DominoRunnable(), "My thread");
		thread.start();
	}

	public DominoRunnable() {
		// whatever you might want to do in your constructor, but stay away from Domino objects
	}

	@Override
	public void run() {
		try {
			Session session = Factory.fromLotus(NotesFactory.createSession(), Session.class, null);
			Database db = session.getDatabase("", "names.nsf");
			// whatever you're gonna do, do it fast!
		} catch (Throwable t) {
			t.printStackTrace();
		}
	}
}

package org.openntf.domino.tests.ntf;

import lotus.domino.NotesFactory;

import org.openntf.domino.Database;
import org.openntf.domino.Session;
import org.openntf.domino.thread.DominoThread;
import org.openntf.domino.utils.DominoUtils;
import org.openntf.domino.utils.Factory;

public class DominoRunnable implements Runnable {
	public static void main(final String[] args) {
		DominoThread thread = new DominoThread(new DominoRunnable(), "My thread");
		thread.start();
	}

	public DominoRunnable() {
		// whatever you might want to do in your constructor, but stay away from Domino objects
	}

	@Override
	public void run() {
		Session session = this.getSession();
		Database db = session.getDatabase("", "names.nsf");
		// whatever you're gonna do, do it fast!
	}

	protected Session getSession() {
		try {
			Session session = Factory.fromLotus(NotesFactory.createSession(), Session.class, null);
			return session;
		} catch (Throwable t) {
			DominoUtils.handleException(t);
			return null;
		}
	}
}

Make it easier to get a session from a sub-class