package org.ashanet;

import android.app.Application;
import android.content.res.Resources;
import android.util.Log;
import com.parse.Parse;
import com.parse.ParseObject;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.LineNumberReader;
import org.ashanet.typedef.Project;

public class AshaNetApp extends Application {

    public String parseAppId;

    @Override
    public void onCreate() {
        super.onCreate();
        LineNumberReader lnr = new LineNumberReader
            (new InputStreamReader
             (getResources().openRawResource(R.raw.keys)));

        registerClasses();

        String parseClientKey;

        try {
            parseAppId = lnr.readLine();
            parseClientKey = lnr.readLine();

            Parse.initialize(this, parseAppId, parseClientKey);
            Log.d("DEBUG", "Successfully initialized");
        }
        catch (IOException ioe) {
            Log.e("DEBUG", "Failed to read keys", ioe);
        }
    }

    private void registerClasses() {
        ParseObject.registerSubclass(Project.class);
    }
}

package org.ashanet;

import android.app.Application;
import android.content.res.Resources;
import android.util.Log;
import com.parse.Parse;
import com.parse.ParseObject;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.LineNumberReader;
import org.ashanet.typedef.Event;
import org.ashanet.typedef.Project;

public class AshaNetApp extends Application {

    public String parseAppId;

    @Override
    public void onCreate() {
        super.onCreate();
        LineNumberReader lnr = new LineNumberReader
            (new InputStreamReader
             (getResources().openRawResource(R.raw.keys)));

        registerClasses();

        String parseClientKey;

        try {
            parseAppId = lnr.readLine();
            parseClientKey = lnr.readLine();

            Parse.initialize(this, parseAppId, parseClientKey);
            Log.d("DEBUG", "Successfully initialized");
        }
        catch (IOException ioe) {
            Log.e("DEBUG", "Failed to read keys", ioe);
        }
    }

    private void registerClasses() {
        ParseObject.registerSubclass(Project.class);
        ParseObject.registerSubclass(Event.class);
    }
}

Fix up a parse error


package eventstore.j.examples;

import eventstore.EventData;
import eventstore.j.EventDataBuilder;

import java.util.UUID;

public class EventDataBuilderExample {

    final EventData empty = new EventDataBuilder("empty").build();

    final EventData binary = new EventDataBuilder("binary")
            .eventId(UUID.randomUUID())
            .data(new byte[]{1, 2, 3, 4})
            .metadata(new byte[]{5, 6, 7, 8})
            .build();

    final EventData string = new EventDataBuilder("string")
            .eventId(UUID.randomUUID())
            .data("data")
            .metadata("metadata")
            .build();

    final EventData json = new EventDataBuilder("json")
            .eventId(UUID.randomUUID())
            .jsonData("{\"data\":\"data\"}")
            .jsonMetadata("{\"metadata\":\"metadata\"}")
            .build();
}

package eventstore.j.examples;

import eventstore.EventData;
import eventstore.j.EventDataBuilder;

import java.util.UUID;

public class EventDataBuilderExample {

    final EventData empty = new EventDataBuilder("eventType").build();

    final EventData binary = new EventDataBuilder("eventType")
            .eventId(UUID.randomUUID())
            .data(new byte[]{1, 2, 3, 4})
            .metadata(new byte[]{5, 6, 7, 8})
            .build();

    final EventData string = new EventDataBuilder("eventType")
            .eventId(UUID.randomUUID())
            .data("data")
            .metadata("metadata")
            .build();

    final EventData json = new EventDataBuilder("eventType")
            .eventId(UUID.randomUUID())
            .jsonData("{\"data\":\"data\"}")
            .jsonMetadata("{\"metadata\":\"metadata\"}")
            .build();
}

Make event type more explicit in examples


package org.apache.maven.siteindexer.mojo;

import java.io.IOException;

import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.apache.maven.siteindexer.Indexer;

/**
 * This goal will build the index.
 *
 * @goal index
 * @aggregator
 *
 */
public class IndexerMojo extends AbstractMojo {

	@Override
	public void execute() throws MojoExecutionException, MojoFailureException {
		Indexer indexer = new Indexer(getLog());
		try {
			getLog().info("Maven Site Index");
			getLog().info("------------------------------");
			getLog().info("building index.js...");
			indexer.buildIndex(
					"target"+ File.separator +"site"+ File.separator,
					"target" + File.separator + "site" + File.separator + "js" + File.separator + "index.js");
			getLog().info("done.");
		} catch (IOException e) {
			getLog().error(e);
		}
	}
}

package org.apache.maven.siteindexer.mojo;

import java.io.File;
import java.io.IOException;

import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.apache.maven.siteindexer.Indexer;

/**
 * This goal will build the index.
 *
 * @goal index
 * @aggregator
 *
 */
public class IndexerMojo extends AbstractMojo {

	@Override
	public void execute() throws MojoExecutionException, MojoFailureException {
		Indexer indexer = new Indexer(getLog());
		try {
			getLog().info("Maven Site Index");
			getLog().info("------------------------------");
			getLog().info("building index.js...");
			indexer.buildIndex(
					"target"+ File.separator +"site"+ File.separator,
					"target" + File.separator + "site" + File.separator + "js" + File.separator + "index.js");
			getLog().info("done.");
		} catch (IOException e) {
			getLog().error(e);
		}
	}
}

Add support for linux with File.separator


package org.wildfly.swarm.examples.ds.war;

import java.sql.Connection;
import java.sql.SQLException;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;

/**
 * @author Bob McWhirter
 */
@Path("/")
public class MyResource {

    @GET
    @Produces("text/plain")
    public String get() throws NamingException, SQLException {
        Context ctx = new InitialContext();
        DataSource ds = (DataSource) ctx.lookup("jboss/datasources/ExampleDS");
        Connection conn = ds.getConnection();
        try {
            return "Howdy using connection: " + conn;
        } finally {
            conn.close();
        }
    }
}

package org.wildfly.swarm.examples.ds.war;

import java.sql.Connection;
import java.sql.SQLException;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;

/**
 * @author Bob McWhirter
 */
@Path("/")
public class MyResource {

    @GET
    @Produces("text/plain")
    public String get() throws NamingException, SQLException {
        Context ctx = new InitialContext();
        DataSource ds = (DataSource) ctx.lookup("jboss/datasources/ExampleDS");
        Connection conn = ds.getConnection();
        try {
            return "Howdy using driver: " + conn.getMetaData().getDriverName();
        } finally {
            conn.close();
        }
    }
}

Modify datasource example to actually show driver name


package com.izforge.izpack.compiler.packager.impl;

import static org.junit.Assert.fail;

import java.io.IOException;

import org.dom4j.dom.DOMElement;
import org.junit.Test;
import org.mockito.Mockito;

import com.izforge.izpack.api.adaptator.IXMLElement;
import com.izforge.izpack.api.adaptator.impl.XMLElementImpl;
import com.izforge.izpack.compiler.resource.ResourceFinder;
import com.izforge.izpack.merge.MergeManager;

public class PackagerTest {

	@Test
	public void testWritePacks() throws IOException {
		final ResourceFinder resourceFinder = new ResourceFinder(null, null,
				null, null) {
			@Override
			public IXMLElement getXMLTree() throws IOException {
				final DOMElement rootNode = new DOMElement("installation");
				final DOMElement guiPrefsNode = new DOMElement("guiprefs");
				rootNode.add(guiPrefsNode);
				return new XMLElementImpl(rootNode);
			}
		};
		final MergeManager mockMergeManager = Mockito.mock(MergeManager.class);
		final Packager packager = new Packager(null, null, null, null, null,
				null, null, mockMergeManager, null, null, null, resourceFinder);
		packager.writeManifest();
		fail("Not yet implemented");
	}

}

package com.izforge.izpack.compiler.packager.impl;

import static org.mockito.Matchers.anyString;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;

import java.io.IOException;

import org.dom4j.dom.DOMElement;
import org.junit.Test;

import com.izforge.izpack.api.adaptator.IXMLElement;
import com.izforge.izpack.api.adaptator.impl.XMLElementImpl;
import com.izforge.izpack.compiler.resource.ResourceFinder;
import com.izforge.izpack.merge.MergeManager;

public class PackagerTest {

	@Test
	public void testWritePacks() throws IOException {
		final ResourceFinder resourceFinder = new ResourceFinder(null, null,
				null, null) {
			@Override
			public IXMLElement getXMLTree() throws IOException {
				final DOMElement rootNode = new DOMElement("installation");
				final DOMElement guiPrefsNode = new DOMElement("guiprefs");
				rootNode.add(guiPrefsNode);
				return new XMLElementImpl(rootNode);
			}
		};
		final MergeManager mockMergeManager = mock(MergeManager.class);

		final Packager packager = new Packager(null, null, null, null, null,
				null, null, mockMergeManager, null, null, null, resourceFinder);

		packager.writeManifest();

		verify(mockMergeManager).addResourceToMerge(anyString(), anyString());

	}
}

Check if MergeManager's addResourceToMerge(String, String) had been called


/*
 * (C) Copyright 2015 Boni Garcia (http://bonigarcia.github.io/)
 *
 * 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-2.1.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.
 *
 */
package io.github.bonigarcia.wdm.test;

import org.junit.Before;

import io.github.bonigarcia.wdm.EdgeDriverManager;
import io.github.bonigarcia.wdm.base.BaseVersionTst;

/**
 * Test asserting MicrosoftWebDriver Edge versions.
 *
 * @author Boni Garcia (boni.gg@gmail.com)
 * @since 1.3.0
 */
public class EdgeVersionTest extends BaseVersionTst {

    @Before
    public void setup() {
        browserManager = EdgeDriverManager.getInstance();
        specificVersions = new String[] { "4.15063", "16.16299" };
    }

}

/*
 * (C) Copyright 2015 Boni Garcia (http://bonigarcia.github.io/)
 *
 * 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-2.1.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.
 *
 */
package io.github.bonigarcia.wdm.test;

import org.junit.Before;

import io.github.bonigarcia.wdm.EdgeDriverManager;
import io.github.bonigarcia.wdm.base.BaseVersionTst;

/**
 * Test asserting MicrosoftWebDriver Edge versions.
 *
 * @author Boni Garcia (boni.gg@gmail.com)
 * @since 1.3.0
 */
public class EdgeVersionTest extends BaseVersionTst {

    @Before
    public void setup() {
        browserManager = EdgeDriverManager.getInstance();
        specificVersions = new String[] { "4.15063" };
    }

}

Change version in specific version for Edge test


/*

Copyright 2015 Akexorcist

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.akexorcist.googledirection.request;

import com.google.android.gms.maps.model.LatLng;

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

/**
 * Created by Akexorcist on 11/29/15 AD.
 */
public class DirectionDestinationRequest {
    String apiKey;
    LatLng origin;
    List<LatLng> waypointList;

    public DirectionDestinationRequest(String apiKey, LatLng origin) {
        this.apiKey = apiKey;
        this.origin = origin;
    }

    public DirectionDestinationRequest and(LatLng waypoint) {
        if (waypointList == null) {
            waypointList = new ArrayList<>();
        }
        waypointList.add(waypoint);
        return this;
    }

    public DirectionRequest to(LatLng destination) {
        return new DirectionRequest(apiKey, origin, destination, waypointList);
    }
}

/*

Copyright 2015 Akexorcist

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.akexorcist.googledirection.request;

import com.google.android.gms.maps.model.LatLng;

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

/**
 * Created by Akexorcist on 11/29/15 AD.
 */
public class DirectionDestinationRequest {
    private String apiKey;
    private LatLng origin;
    private List<LatLng> waypointList;

    public DirectionDestinationRequest(String apiKey, LatLng origin) {
        this.apiKey = apiKey;
        this.origin = origin;
    }

    public DirectionDestinationRequest and(LatLng waypoint) {
        if (waypointList == null) {
            waypointList = new ArrayList<>();
        }
        waypointList.add(waypoint);
        return this;
    }

    public DirectionDestinationRequest and(List<LatLng> waypointList) {
        if (this.waypointList == null) {
            this.waypointList = new ArrayList<>();
        }
        this.waypointList.addAll(waypointList);
        return this;
    }

    public DirectionRequest to(LatLng destination) {
        return new DirectionRequest(apiKey, origin, destination, waypointList);
    }
}

Add LatLng list support for direction request


package ru.stqa.pft.addressbook.tests;

import org.testng.annotations.Test;
import ru.stqa.pft.addressbook.model.GroupData;

import java.util.HashSet;
import java.util.List;

import static org.testng.Assert.assertEquals;

/**
 * Created by Sergei on 16.04.2016.
 */
public class GroupModificationTests extends TestBase {
    @Test
    public void testGroupModification(){
        app.getNavigationHelper().goToGroupPage();
        if (! app.getGroupHelper().isThereAGroup()) {
            app.getGroupHelper().createGroup(new GroupData("Test1", null, null));
        }
        List<GroupData> before = app.getGroupHelper().getGroupList();
        app.getGroupHelper().selectGroup(before.size() - 1);
        app.getGroupHelper().initGroupModification();
        GroupData group = new GroupData("Test1", "Test2", "Test3");
        app.getGroupHelper().fillGroupForm(group);
        app.getGroupHelper().submitGroupModification();
        app.getGroupHelper().returnToGroupPage();
        List<GroupData> after = app.getGroupHelper().getGroupList();
        assertEquals(after.size(), before.size(), "Некорректное количество групп");
        before.remove(before.size() - 1);
        before.add(group);
    }
}

package ru.stqa.pft.addressbook.tests;

import org.testng.annotations.Test;
import ru.stqa.pft.addressbook.model.GroupData;

import java.util.HashSet;
import java.util.List;

import static org.testng.Assert.assertEquals;

/**
 * Created by Sergei on 16.04.2016.
 */
public class GroupModificationTests extends TestBase {
    @Test
    public void testGroupModification(){
        app.getNavigationHelper().goToGroupPage();
        if (! app.getGroupHelper().isThereAGroup()) {
            app.getGroupHelper().createGroup(new GroupData("Test1", null, null));
        }
        List<GroupData> before = app.getGroupHelper().getGroupList();
        app.getGroupHelper().selectGroup(before.size() - 1);
        app.getGroupHelper().initGroupModification();
        GroupData group = new GroupData(before.get(before.size() - 1).getId(), "Test1", "Test2", "Test3");
        app.getGroupHelper().fillGroupForm(group);
        app.getGroupHelper().submitGroupModification();
        app.getGroupHelper().returnToGroupPage();
        List<GroupData> after = app.getGroupHelper().getGroupList();
        assertEquals(after.size(), before.size(), "Некорректное количество групп");
        before.remove(before.size() - 1);
        before.add(group);
    }
}

Revert "Revert "Доработки в тесте на модификацию группы""


package com.madisp.bad.expr;

import com.madisp.bad.eval.BadConverter;
import com.madisp.bad.eval.Scope;
import com.madisp.bad.eval.Watcher;

/**
 * Created with IntelliJ IDEA.
 * User: madis
 * Date: 3/27/13
 * Time: 7:02 PM
 */
public class AssignExpression implements Expression {
	private final Expression expr;
	private final VarExpression var;

	public AssignExpression(VarExpression var, Expression expr) {
		this.var = var;
		this.expr = expr;
	}

	@Override
	public Object value(Scope scope) {
		Object newValue = BadConverter.object(expr.value(scope));
		scope.setVar(var.getBase(scope), var.getIdentifier(), newValue);
		return newValue;
	}

	@Override
	public void addWatcher(Scope scope, Watcher w) {
		expr.addWatcher(scope, w);
		var.addWatcher(scope, w);
	}
}

package com.madisp.bad.expr;

import com.madisp.bad.eval.BadConverter;
import com.madisp.bad.eval.Scope;
import com.madisp.bad.eval.Watcher;

/**
 * Created with IntelliJ IDEA.
 * User: madis
 * Date: 3/27/13
 * Time: 7:02 PM
 */
public class AssignExpression implements Expression {
	private final Expression expr;
	private final VarExpression var;

	public AssignExpression(VarExpression var, Expression expr) {
		this.var = var;
		this.expr = expr;
	}

	@Override
	public Object value(Scope scope) {
		Object newValue = BadConverter.object(expr.value(scope));
		scope.setVar(var.getBase(scope), var.getIdentifier(), newValue);
		return newValue;
	}

	@Override
	public void addWatcher(Scope scope, Watcher w) {
		expr.addWatcher(scope, w);
		// we don't need to watch var as it will trigger re-evaluation loop when this expression is watched
//		var.addWatcher(scope, w);
	}
}

Fix re-evaluation loop with assignment expression


package com.grayben.riskExtractor.htmlScorer;

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

public class ScoredText {
	private List<ScoredTextElement> text;

	public ScoredText() {
		super();
		text = new ArrayList<>();
	}

	@Override
	public String toString() {
		StringBuilder sb = new StringBuilder();
		for (ScoredTextElement element : text) {
			sb.append(element.getTextElement());
			sb.append(" ");
		}
		return sb.toString().trim();
	}

	public void add(ScoredTextElement st) {
        if(st.getScores() == null){
            throw new NullPointerException(
                    "param.getScores() must not be null"
            );
        }
        if(st.getScores().isEmpty()){
            throw new IllegalArgumentException(
                    "param.getScores() must not be empty"
            );
        }
        if(st.getTextElement() == null){
            throw new NullPointerException(
                    "param.getTextElement() must not be null"
            );
        }
        if(st.getTextElement().isEmpty()){
            throw new IllegalArgumentException(
                    "param.getTextElement() must not be empty"
            );
        }
		text.add(st);
	}
}

package com.grayben.riskExtractor.htmlScorer;

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

public class ScoredText {
	private List<ScoredTextElement> text;

	public ScoredText() {
		super();
		text = new ArrayList<>();
	}

	@Override
	public String toString() {
		StringBuilder sb = new StringBuilder();
		for (ScoredTextElement element : text) {
			sb.append(element.getTextElement());
			sb.append(" ");
		}
		return sb.toString().trim();
	}

	public void add(ScoredTextElement st) {
        if(st.getScores() == null){
            throw new NullPointerException(
                    "param.getScores() must not be null"
            );
        }
        if(st.getScores().isEmpty()){
            throw new IllegalArgumentException(
                    "param.getScores() must not be empty"
            );
        }
        if(st.getTextElement() == null){
            throw new NullPointerException(
                    "param.getTextElement() must not be null"
            );
        }
        if(st.getTextElement().isEmpty()){
            throw new IllegalArgumentException(
                    "param.getTextElement() must not be empty"
            );
        }
		text.add(st);
	}

	public List<ScoredTextElement> getList(){
        return Collections.unmodifiableList(this.text);
    }
}

Add access to list of elements


package com.khorn.terraincontrol.configuration.settingType;

import com.khorn.terraincontrol.exception.InvalidConfigException;
import com.khorn.terraincontrol.util.helpers.StringHelper;

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

/**
 * Reads and writes a list of strings. Strings are read using
 * {@link StringHelper#readCommaSeperatedString(String)}, and written with a
 * ", " between each string.
 *
 */
class StringListSetting extends Setting<List<String>>
{
    private String[] defaultValue;

    StringListSetting(String name, String... defaultValue)
    {
        super(name);
        this.defaultValue = defaultValue;
    }

    @Override
    public List<String> getDefaultValue()
    {
        return Arrays.asList(defaultValue);
    }

    @Override
    public List<String> read(String string) throws InvalidConfigException
    {
        String[] split = StringHelper.readCommaSeperatedString(string);
        for (int i = 0; i < split.length; i++)
        {
            // Trimming the values allows "Value1, Value2" instead of
            // "Value1,Value2"
            split[i] = split[i];
        }
        return Arrays.asList(split);
    }

    @Override
    public String write(List<String> value)
    {
        return StringHelper.join(value, ", ");
    }

}

package com.khorn.terraincontrol.configuration.settingType;

import com.khorn.terraincontrol.exception.InvalidConfigException;
import com.khorn.terraincontrol.util.helpers.StringHelper;

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

/**
 * Reads and writes a list of strings. Strings are read using
 * {@link StringHelper#readCommaSeperatedString(String)}, and written with a
 * ", " between each string.
 *
 */
class StringListSetting extends Setting<List<String>>
{
    private String[] defaultValue;

    StringListSetting(String name, String... defaultValue)
    {
        super(name);
        this.defaultValue = defaultValue;
    }

    @Override
    public List<String> getDefaultValue()
    {
        return Arrays.asList(defaultValue);
    }

    @Override
    public List<String> read(String string) throws InvalidConfigException
    {
        return Arrays.asList(StringHelper.readCommaSeperatedString(string));
    }

    @Override
    public String write(List<String> value)
    {
        return StringHelper.join(value, ", ");
    }

}

Remove some unneeded code, as StringHelper.readCommaSeperatedString already trims values


package bd.settings;

/**
 * VmSettings are determined based on Java properties. They are used to configure VM-wide
 * properties, for instance whether a tool is enabled or not.
 */
public class VmSettings {
  public static final boolean DYNAMIC_METRICS;

  static {
    Settings s = getSettings();

    DYNAMIC_METRICS = s.dynamicMetricsEnabled();
  }

  private static Settings getSettings() {
    String className = System.getProperty("bd.settings");
    if (className == null) {
      return new AllDisabled();
    }

    try {
      Class<?> clazz = VmSettings.class.getClassLoader().loadClass(className);
      return (Settings) clazz.newInstance();
    } catch (ClassNotFoundException | InstantiationException | IllegalAccessException e) {
      // Checkstyle: stop
      System.err.println("[BlackDiamonds] Could not load settings class: " + className);
      e.printStackTrace();
      return new AllDisabled();
      // Checkstyle: resume
    }
  }
}

package bd.settings;

/**
 * VmSettings are determined based on Java properties. They are used to configure VM-wide
 * properties, for instance whether a tool is enabled or not.
 */
public class VmSettings {
  public static final boolean DYNAMIC_METRICS;

  static {
    Settings s = getSettings();

    DYNAMIC_METRICS = s.dynamicMetricsEnabled();
  }

  private static Settings getSettings() {
    String className = System.getProperty("bd.settings");
    if (className == null) {
      return new AllDisabled();
    }

    try {
      Class<?> clazz = Class.forName(className);
      return (Settings) clazz.newInstance();
    } catch (ClassNotFoundException | InstantiationException | IllegalAccessException e) {
      // Checkstyle: stop
      System.err.println("[BlackDiamonds] Could not load settings class: " + className);
      e.printStackTrace();
      return new AllDisabled();
      // Checkstyle: resume
    }
  }
}

Use Class.forName instead of class loader


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

package org.apache.harmony.tests.java.nio.channels;

import java.io.File;
import java.io.FileOutputStream;
import java.nio.channels.FileChannel;

import junit.framework.TestCase;

public class FileChannelTest extends TestCase {

	/**
	 * @tests java.nio.channels.FileChannel#isOpen()
	 */
	public void test_close() throws Exception {
		// Regression for HARMONY-40
		File logFile = File.createTempFile("out", "tmp");
		logFile.deleteOnExit();
		FileOutputStream out = new FileOutputStream(logFile, true);
		FileChannel channel = out.getChannel();
		out.write(1);
		out.close();
		assertFalse("Assert 0: Channel is still open", channel.isOpen());
	}
}

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

package org.apache.harmony.tests.java.nio.channels;

import java.io.File;
import java.io.FileOutputStream;
import java.nio.channels.FileChannel;

import junit.framework.TestCase;

public class FileChannelTest extends TestCase {

	/**
	 * @tests java.nio.channels.FileChannel#isOpen()
	 */
	public void test_isOpen() throws Exception {
		// Regression for HARMONY-40
		File logFile = File.createTempFile("out", "tmp");
		logFile.deleteOnExit();
		FileOutputStream out = new FileOutputStream(logFile, true);
		FileChannel channel = out.getChannel();
		out.write(1);
		out.close();
		assertFalse("Assert 0: Channel is still open", channel.isOpen());
	}
}

Fix misleading test method name to avoid confusion.


package org.robockets.stronghold.robot.commands;

import org.robockets.stronghold.robot.highgoalshooter.MoveHood;
import org.robockets.stronghold.robot.highgoalshooter.MoveTurnTable;
import org.robockets.stronghold.robot.intake.IntakesUp;

import edu.wpi.first.wpilibj.command.CommandGroup;

/**
 *
 */
public class DrivePosition extends CommandGroup {

    public  DrivePosition() {
        addSequential(new MoveHood(-70));
        addSequential(new IntakesUp());
        addSequential(new MoveTurnTable(0));
    }
}

package org.robockets.stronghold.robot.commands;

import org.robockets.stronghold.robot.highgoalshooter.MoveHood;
import org.robockets.stronghold.robot.highgoalshooter.MoveTurnTable;
import org.robockets.stronghold.robot.intake.IntakesUp;

import edu.wpi.first.wpilibj.command.CommandGroup;

/**
 * Moves the robot into the position for driving around, shooting, and intaking ball
 */
public class DrivePosition extends CommandGroup {

    public  DrivePosition() {
        addSequential(new MoveHood(-70));
        addSequential(new IntakesUp());
        addSequential(new MoveTurnTable(0));
    }
}

Add javadocs for drive position


/*
 * This is part of Geomajas, a GIS framework, http://www.geomajas.org/.
 *
 * Copyright 2008-2014 Geosparc nv, http://www.geosparc.com/, Belgium.
 *
 * The program is available in open source according to the GNU Affero
 * General Public License. All contributions in this program are covered
 * by the Geomajas Contributors License Agreement. For full licensing
 * details, see LICENSE.txt in the project root.
 */

package org.geomajas.gwt.example.client.security;

import org.geomajas.gwt.client.command.TokenRequestHandler;
import org.geomajas.gwt.client.command.event.TokenChangedHandler;
import org.geomajas.plugin.staticsecurity.client.util.SsecAccess;

/**
 * {@link org.geomajas.gwt.client.command.TokenRequestHandler} which allows logging in to a specific userId and password.
 *
 * @author Joachim Van der Auwera
 */
public class ShowcaseTokenRequestHandler implements TokenRequestHandler {

	// CHECKSTYLE VISIBILITY MODIFIER: OFF

	/** UserId to use for logging in. */
	public static String userId;
	/** Password to use for logging in. */
	public static String password;

	// CHECKSTYLE VISIBILITY MODIFIER: ON

	@Override
	public void login(TokenChangedHandler tokenChangedHandler) {
		SsecAccess.login(userId, password, tokenChangedHandler);
	}
}

/*
 * This is part of Geomajas, a GIS framework, http://www.geomajas.org/.
 *
 * Copyright 2008-2014 Geosparc nv, http://www.geosparc.com/, Belgium.
 *
 * The program is available in open source according to the GNU Affero
 * General Public License. All contributions in this program are covered
 * by the Geomajas Contributors License Agreement. For full licensing
 * details, see LICENSE.txt in the project root.
 */

package org.geomajas.gwt.example.client.security;

import org.geomajas.gwt.client.command.TokenRequestHandler;
import org.geomajas.gwt.client.command.event.TokenChangedHandler;
import org.geomajas.plugin.staticsecurity.client.util.SsecAccess;

/**
 * {@link org.geomajas.gwt.client.command.TokenRequestHandler} which allows logging in to a specific userId and
 * password.
 *
 * @author Joachim Van der Auwera
 */
public class ShowcaseTokenRequestHandler implements TokenRequestHandler {

	// CHECKSTYLE VISIBILITY MODIFIER: OFF

	/** UserId to use for logging in. */
	public static String userId;
	/** Password to use for logging in. */
	public static String password;

	// CHECKSTYLE VISIBILITY MODIFIER: ON

	@Override
	public void login(TokenChangedHandler tokenChangedHandler) {
		SsecAccess.login(userId, password, tokenChangedHandler);
	}
}

Fix showcase to old (svn) state.


package study.hard.javalib.nativelib;

public class GetClassTest {

	public static void main(String[] args) {
		GetClassTest tester = new GetClassTest();
		ExtendedClassA extendedA = tester.new ExtendedClassA();
		extendedA.printClass(); // class study.hard.javalib.nativelib.GetClassTest$ExtendedClassA
	}

	public class ClassA {
		public void printThisClass() {
			System.out.println(getClass());
		}
	}

	public class ExtendedClassA extends ClassA {
		public void printClass() {
			printThisClass();
		}
	}

}

package study.hard.javalib.nativelib;

public class GetClassTest {

	public static void main(String[] args) {
		GetClassTest tester = new GetClassTest();
		ExtendedClassA extendedA = tester.new ExtendedClassA();
		extendedA.printClass(); // class study.hard.javalib.nativelib.GetClassTest$ExtendedClassA

		Class<? extends ClassA> clazz = extendedA.getClass();
		System.out.println(clazz.getName());
	}

	public class ClassA {
		public void printThisClass() {
			System.out.println(getClass());
		}
	}

	public class ExtendedClassA extends ClassA {
		public void printClass() {
			printThisClass();
		}
	}

}

Add some codes to test Class object.


package THE_PACKAGE;

import org.jruby.Ruby;
import org.jruby.javasupport.util.RuntimeHelpers;
import org.jruby.runtime.builtin.IRubyObject;
import org.jruby.javasupport.JavaUtil;
import org.jruby.exceptions.RaiseException;
import org.ruboto.Script;

public class THE_RUBOTO_CLASS THE_ACTION THE_ANDROID_CLASS {
  private Ruby __ruby__;

THE_CONSTANTS
  private IRubyObject[] callbackProcs = new IRubyObject[CONSTANTS_COUNT];

  private Ruby getRuby() {
    if (__ruby__ == null) __ruby__ = Script.getRuby();
    return __ruby__;
  }

  public void setCallbackProc(int id, IRubyObject obj) {
    callbackProcs[id] = obj;
  }

THE_METHODS
}

package THE_PACKAGE;

import org.jruby.Ruby;
import org.jruby.javasupport.util.RuntimeHelpers;
import org.jruby.runtime.builtin.IRubyObject;
import org.jruby.javasupport.JavaUtil;
import org.jruby.exceptions.RaiseException;
import org.ruboto.Script;

public class THE_RUBOTO_CLASS THE_ACTION THE_ANDROID_CLASS {
  private Ruby __ruby__;

THE_CONSTANTS
  private IRubyObject[] callbackProcs = new IRubyObject[CONSTANTS_COUNT];

THE_CONSTRUCTORS

  private Ruby getRuby() {
    if (__ruby__ == null) __ruby__ = Script.getRuby();
    return __ruby__;
  }

  public void setCallbackProc(int id, IRubyObject obj) {
    callbackProcs[id] = obj;
  }

THE_METHODS
}

Add place to put constructors


package me.devsaki.hentoid.json.sources;

import com.annimon.stream.Stream;

import java.util.List;

public class NexusGallery {
    private String b;
    private String r;
    private String i;
    private List<NexusPage> f;

    public List<String> toUrls() {
        return Stream.of(f).map(page -> b + r + page.h + "/" + i + "/" + page.p).toList();
    }

    static class NexusPage {
        private String h;
        private String p;
    }
}

package me.devsaki.hentoid.json.sources;

import com.squareup.moshi.Json;

import java.util.List;

public class NexusGallery {
    private String b;
    private String r;
    private String i;
    @Json(name = "pages")
    private List<String> pages;

    public List<String> toUrls() {
        return pages;
    }
}

Fix test for new nexus gallery structure


package com.miguelgaeta.bootstrap.mg_delay;

import java.util.concurrent.TimeUnit;

import rx.Observable;

/**
 * Created by Miguel Gaeta on 2/17/15.
 */
class MGDelayUtil {

    /**
     * Setup an observable object based
     * on the specified delay parameters.
     */
    static Observable<Void> observe(long delayMilliseconds, boolean loop, boolean startImmediately) {

        // Create timer or looping observable.
        Observable<Long> observable = loop ?
                Observable.interval(delayMilliseconds, TimeUnit.MILLISECONDS) :
                Observable.timer   (delayMilliseconds, TimeUnit.MILLISECONDS);

        if (startImmediately) {

            // Start right away.
            observable = observable.startWith(0L);
        }

        return observable.flatMap(aLong -> Observable.create(subscriber -> {

            subscriber.onNext(null);
            subscriber.onCompleted();
        }));
    }
}

package com.miguelgaeta.bootstrap.mg_delay;

import java.util.concurrent.TimeUnit;

import rx.Observable;

/**
 * Created by Miguel Gaeta on 2/17/15.
 */
class MGDelayUtil {

    /**
     * Setup an observable object based
     * on the specified delay parameters.
     */
    static Observable<Void> observe(long delayMilliseconds, boolean loop, boolean startImmediately) {

        // Create timer or looping observable.
        Observable<Long> observable = loop ?
                Observable.interval(delayMilliseconds, TimeUnit.MILLISECONDS) :
                Observable.timer   (delayMilliseconds, TimeUnit.MILLISECONDS);

        if (startImmediately) {

            // Start right away.
            observable = observable.startWith(0L);
        }

        return observable.flatMap(aLong -> Observable.create(subscriber -> {

            subscriber.onNext(null);
            subscriber.onCompleted();

        })).onBackpressureDrop().map(r -> null);
    }
}

Handle back pressure in MGDelay - it should drop.


package com.vladmihalcea.book.hpjp.util.providers.queries;

/**
 * @author Vlad Mihalcea
 */
public class PostgreSQLQueries implements Queries {

    public static final Queries INSTANCE = new PostgreSQLQueries();

    @Override
    public String transactionId() {
        return "SELECT CAST(txid_current() AS text)";
    }
}

package com.vladmihalcea.book.hpjp.util.providers.queries;

/**
 * @author Vlad Mihalcea
 */
public class PostgreSQLQueries implements Queries {

    public static final Queries INSTANCE = new PostgreSQLQueries();

    @Override
    public String transactionId() {
        return "SELECT CAST(pg_current_xact_id_if_assigned() AS text)";
    }
}

Update PostgreSQL transaction id query


package skadistats.clarity.parser.handler;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import skadistats.clarity.match.Match;
import skadistats.clarity.model.UserMessage;
import skadistats.clarity.parser.Handler;
import skadistats.clarity.parser.HandlerHelper;
import skadistats.clarity.parser.RegisterHandler;

import com.dota2.proto.DotaUsermessages.CDOTAUserMsg_DodgeTrackingProjectiles;

@RegisterHandler(CDOTAUserMsg_DodgeTrackingProjectiles.class)
public class UserMsgDodgeTrackingProjectilesHandler implements Handler<CDOTAUserMsg_DodgeTrackingProjectiles> {

    private final Logger log = LoggerFactory.getLogger(getClass());

    @Override
    public void apply(int peekTick, CDOTAUserMsg_DodgeTrackingProjectiles message, Match match) {
        HandlerHelper.traceMessage(log, peekTick, message);
        log.debug("{} DODGE_TRACKING_PROJECTILES [target={}]",
            match.getReplayTimeAsString(),
            match.getEntities().getByIndex(message.getEntindex()).getDtClass().getDtName()
        );
        match.getUserMessages().add(UserMessage.build(message, match));
    }

}

package skadistats.clarity.parser.handler;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import skadistats.clarity.match.Match;
import skadistats.clarity.model.UserMessage;
import skadistats.clarity.parser.Handler;
import skadistats.clarity.parser.HandlerHelper;
import skadistats.clarity.parser.RegisterHandler;

import com.dota2.proto.DotaUsermessages.CDOTAUserMsg_DodgeTrackingProjectiles;

@RegisterHandler(CDOTAUserMsg_DodgeTrackingProjectiles.class)
public class UserMsgDodgeTrackingProjectilesHandler implements Handler<CDOTAUserMsg_DodgeTrackingProjectiles> {

    private final Logger log = LoggerFactory.getLogger(getClass());

    @Override
    public void apply(int peekTick, CDOTAUserMsg_DodgeTrackingProjectiles message, Match match) {
        HandlerHelper.traceMessage(log, peekTick, message);
        log.debug("{} DODGE_TRACKING_PROJECTILES [target_index={}]",
            match.getReplayTimeAsString(),
            message.getEntindex()
        );
        match.getUserMessages().add(UserMessage.build(message, match));
    }

}

Fix NullPointerException when referencing an already deleted ent


package com.jmb.springfactory.service.productionschedule;

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

import com.jmb.springfactory.dao.GenericMySQLService;
import com.jmb.springfactory.dao.productionschedule.ProductionScheduleMySQLService;
import com.jmb.springfactory.model.bo.BusinessObjectBase;
import com.jmb.springfactory.model.dto.ProductionScheduleDto;
import com.jmb.springfactory.model.entity.ProductionSchedule;
import com.jmb.springfactory.service.GenericServiceImpl;

public class ProductionScheduleServiceImpl extends GenericServiceImpl<ProductionSchedule, ProductionScheduleDto,
  BusinessObjectBase, Integer> implements ProductionScheduleService {

  @Autowired
  private ProductionScheduleMySQLService productionScheduleMySQLService;

  @Override
  public GenericMySQLService<ProductionSchedule, Integer> genericDao() {
    return productionScheduleMySQLService;
  }

  @Override
  public Class<? extends ProductionSchedule> getClazz() {
    return ProductionSchedule.class;
  }

  @Override
  public Class<? extends ProductionScheduleDto> getDtoClazz() {
    return ProductionScheduleDto.class;
  }

  @Override
  public Class<? extends BusinessObjectBase> getBoClazz() {
    return BusinessObjectBase.class;
  }

}

package com.jmb.springfactory.service.productionschedule;

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

import com.jmb.springfactory.dao.GenericMySQLService;
import com.jmb.springfactory.dao.productionschedule.ProductionScheduleMySQLService;
import com.jmb.springfactory.model.bo.BusinessObjectBase;
import com.jmb.springfactory.model.dto.ProductionScheduleDto;
import com.jmb.springfactory.model.entity.ProductionSchedule;
import com.jmb.springfactory.service.GenericServiceImpl;

@Service
public class ProductionScheduleServiceImpl extends GenericServiceImpl<ProductionSchedule, ProductionScheduleDto,
  BusinessObjectBase, Integer> implements ProductionScheduleService {

  @Autowired
  private ProductionScheduleMySQLService productionScheduleMySQLService;

  @Override
  public GenericMySQLService<ProductionSchedule, Integer> genericDao() {
    return productionScheduleMySQLService;
  }

  @Override
  public Class<? extends ProductionSchedule> getClazz() {
    return ProductionSchedule.class;
  }

  @Override
  public Class<? extends ProductionScheduleDto> getDtoClazz() {
    return ProductionScheduleDto.class;
  }

  @Override
  public Class<? extends BusinessObjectBase> getBoClazz() {
    return BusinessObjectBase.class;
  }

}

Fix problem with context load


package forager.newui;

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

public class Launcher {

    public static void main(String[] args) throws Exception {
        if (args.length < 1) {
            printHelp();
        }

        Client clientCommand = new Client();

        Map<String, Command> commands = new HashMap<>();
        commands.put(clientCommand.name(), clientCommand);

        String commandName = args[0].toLowerCase();

        Command cmd = commands.get(commandName);
        if (cmd != null) {
            String[] argList = new String[args.length - 1];
            for (int i = 0; i < argList.length; ++i) {
                argList[i] = args[i + 1];
            }
            cmd.execute(argList);
        }

    }

    private static void printHelp() {
        System.out.println("usage: ...");

    }
}

package forager.newui;

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

public class Launcher {

    public static void main(String[] args) throws Exception {
        if (args.length < 1) {
            printHelp();
        }

        Client clientCommand = new Client();

        Map<String, Command> commands = new HashMap<>();
        commands.put(clientCommand.name(), clientCommand);

        String commandName = args[0].toLowerCase();

        Command cmd = commands.get(commandName);
        if (cmd != null) {
            String[] argList = new String[args.length - 1];
            for (int i = 0; i < argList.length; ++i) {
                argList[i] = args[i + 1];
            }
            try {
                cmd.execute(argList);
            } catch (Exception e) {
                System.out.println(e.getMessage());
                cmd.printUsage();
            }
        }

    }

    private static void printHelp() {
        System.out.println("usage: ...");

    }
}

Print command usage on errors


package com.avairebot.orion.commands.music;

import com.avairebot.orion.Orion;
import com.avairebot.orion.audio.AudioHandler;
import com.avairebot.orion.contracts.commands.AbstractCommand;
import net.dv8tion.jda.core.entities.Message;

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

public class SkipCommand extends AbstractCommand {

    public SkipCommand(Orion orion) {
        super(orion, false);
    }

    @Override
    public String getName() {
        return "Skip Music Command";
    }

    @Override
    public String getDescription() {
        return "Skips to the next song in the music queue.";
    }

    @Override
    public List<String> getUsageInstructions() {
        return Arrays.asList("`!skip` - Skips to the next song in the queue");
    }

    @Override
    public String getExampleUsage() {
        return null;
    }

    @Override
    public List<String> getTriggers() {
        return Arrays.asList("skip");
    }

    @Override
    public boolean onCommand(Message message, String[] args) {
        AudioHandler.skipTrack(message);
        return true;
    }
}

package com.avairebot.orion.commands.music;

import com.avairebot.orion.Orion;
import com.avairebot.orion.audio.AudioHandler;
import com.avairebot.orion.audio.GuildMusicManager;
import com.avairebot.orion.contracts.commands.AbstractCommand;
import net.dv8tion.jda.core.entities.Message;

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

public class SkipCommand extends AbstractCommand {

    public SkipCommand(Orion orion) {
        super(orion, false);
    }

    @Override
    public String getName() {
        return "Skip Music Command";
    }

    @Override
    public String getDescription() {
        return "Skips to the next song in the music queue.";
    }

    @Override
    public List<String> getUsageInstructions() {
        return Arrays.asList("`!skip` - Skips to the next song in the queue");
    }

    @Override
    public String getExampleUsage() {
        return "`!skip`";
    }

    @Override
    public List<String> getTriggers() {
        return Arrays.asList("skip");
    }

    @Override
    public boolean onCommand(Message message, String[] args) {
        GuildMusicManager musicManager = AudioHandler.getGuildAudioPlayer(message.getGuild());

        if (musicManager.getPlayer().getPlayingTrack() == null) {
            return sendErrorMessage(message, "Nothing to skip, request music first with `!play`");
        }

        AudioHandler.skipTrack(message);
        return true;
    }
}

Check if music is playing before skipping in music skip command


package com.sangdol.experiment.portableDb;

import com.codahale.metrics.annotation.Timed;

import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;
import java.util.List;

/**
 * @author hugh
 */
@Path("/user")
@Produces(MediaType.APPLICATION_JSON)
public class ViewResource {
    private ViewService viewService;

    public ViewResource(ViewService viewService) {
        this.viewService = viewService;
    }

    @GET
    @Path("{id}")
    @Timed
    public List<View> viewList(@PathParam("id") int userId) {
        return viewService.getLatest10Visitors(userId);
    }

    @POST
    @Path("{id}")
    @Timed
    public int createView(@PathParam("id") int hostId, @QueryParam("visitor_id") int visitorId) {
        if (visitorId == 0)
            return 0;   // TODO throw 404

        return viewService.createView(hostId, visitorId);
    }

    @POST
    @Path("clear")
    @Timed
    public String clear() {
        viewService.clear();
        return "Success";
    }

    @GET
    @Path("view-count")
    @Timed
    public List<Integer> viewCount() {
        return viewService.getAllViewCounts();
    }
}

package com.sangdol.experiment.portableDb;

import com.codahale.metrics.annotation.Timed;

import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;
import java.util.List;

/**
 * @author hugh
 */
@Path("/user")
@Produces(MediaType.APPLICATION_JSON)
public class ViewResource {
    private ViewService viewService;

    public ViewResource(ViewService viewService) {
        this.viewService = viewService;
    }

    @GET
    @Path("{id}")
    @Timed
    public List<View> viewList(@PathParam("id") int hostId) {
        checkValidity(hostId);

        return viewService.getLatest10Visitors(hostId);
    }

    @POST
    @Path("{id}")
    @Timed
    public int createView(@PathParam("id") int hostId, @QueryParam("visitor_id") int visitorId) {
        checkValidity(visitorId);

        return viewService.createView(hostId, visitorId);
    }

    private void checkValidity(int userId) {
        if (userId < 1)
            throw new WebApplicationException(404);
    }

    @POST
    @Path("clear")
    @Timed
    public String clear() {
        viewService.clear();
        return "Success";
    }

    @GET
    @Path("view-counts")
    @Timed
    public List<Integer> viewCount() {
        return viewService.getAllViewCounts();
    }
}

Throw 404 exception when accessing with invalid userId


package uk.ac.ebi.spot.goci.service;

import org.apache.poi.xssf.usermodel.XSSFSheet;
import uk.ac.ebi.spot.goci.model.AssociationUploadRow;

import java.util.Collection;

/**
 * Created by emma on 13/04/2016.
 *
 * @author emma
 *         <p>
 *         Service to read an spreadsheet of associations
 */
public interface UploadSheetProcessor {
    Collection<AssociationUploadRow> readSheetRows(XSSFSheet sheet);
}

package uk.ac.ebi.spot.goci.service;

import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import uk.ac.ebi.spot.goci.model.AssociationUploadRow;

import java.util.Collection;
import java.util.Map;

/**
 * Created by emma on 13/04/2016.
 *
 * @author emma
 *         <p>
 *         Service to read an spreadsheet of associations, create a map of headers in the file and process all further
 *         rows
 */
public interface UploadSheetProcessor {

    Map<Integer, String> createHeaderMap(XSSFRow row);

    Collection<AssociationUploadRow> readSheetRows(XSSFSheet sheet);
}

Add method to process headers


package de.apileipzig.mediahandbook.entity;

/**
 * Default implementation of a Branch.
 *
 * @author cpieloth
 */
public class DefaultBranch implements Branch {
    private int id;
    private int parentId;
    private String internalType;
    private String internalKey;
    private String name;
    private String description;

    @Override
    public int getId() {
        return id;
    }

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

    @Override
    public int getParentId() {
        return parentId;
    }

    @Override
    public void setParentId(int id) {
        this.parentId = id;
    }

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

    @Override
    public void setInternalType(String internalType) {
        this.internalType = internalType;
    }

    @Override
    public String getInternalKey() {
        return internalKey;
    }

    @Override
    public void setInternalKey(String internalKey) {
        this.internalKey = internalKey;
    }

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

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

    @Override
    public String getDescription() {
        return description;
    }

    @Override
    public void setDescription(String street) {
        this.description = street;
    }

    @Override
    public String toString() {
        return "" + this.getClass().getSimpleName() + "[id=" + id + ",name=" + name + ",...]";
    }
}

package de.apileipzig.mediahandbook.entity;

/**
 * Default implementation of a Branch.
 *
 * @author cpieloth
 */
public class DefaultBranch implements Branch {
    private int id;
    private int parentId;
    private String internalType;
    private String internalKey;
    private String name;
    private String description;

    @Override
    public int getId() {
        return id;
    }

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

    @Override
    public int getParentId() {
        return parentId;
    }

    @Override
    public void setParentId(int id) {
        this.parentId = id;
    }

    @Override
    public String getInternalType() {
        return internalType;
    }

    @Override
    public void setInternalType(String internalType) {
        this.internalType = internalType;
    }

    @Override
    public String getInternalKey() {
        return internalKey;
    }

    @Override
    public void setInternalKey(String internalKey) {
        this.internalKey = internalKey;
    }

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

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

    @Override
    public String getDescription() {
        return description;
    }

    @Override
    public void setDescription(String street) {
        this.description = street;
    }

    @Override
    public String toString() {
        return "" + this.getClass().getSimpleName() + "[id=" + id + ",name=" + name + ",...]";
    }
}

Fix wrong member in getter.


/*
 * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
 *
 * This program and the accompanying materials are made available under the
 * terms of the Eclipse Public License v1.0 which accompanies this distribution,
 * and is available at http://www.eclipse.org/legal/epl-v10.html
 */
package org.opendaylight.controller.netconf.monitoring.xml;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.transform.dom.DOMResult;
import org.opendaylight.controller.netconf.monitoring.xml.model.NetconfState;
import org.w3c.dom.Document;
import org.w3c.dom.Element;

public class JaxBSerializer {

    public Element toXml(final NetconfState monitoringModel) {
        final DOMResult res;
        try {
            final JAXBContext jaxbContext = JAXBContext.newInstance(NetconfState.class);
            final Marshaller marshaller = jaxbContext.createMarshaller();

            marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);

            res = new DOMResult();
            marshaller.marshal(monitoringModel, res);
        } catch (final JAXBException e) {
            throw new RuntimeException("Unable to serialize netconf state " + monitoringModel, e);
        }
        return ((Document)res.getNode()).getDocumentElement();
    }
}

/*
 * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
 *
 * This program and the accompanying materials are made available under the
 * terms of the Eclipse Public License v1.0 which accompanies this distribution,
 * and is available at http://www.eclipse.org/legal/epl-v10.html
 */
package org.opendaylight.controller.netconf.monitoring.xml;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.transform.dom.DOMResult;
import org.opendaylight.controller.netconf.monitoring.xml.model.NetconfState;
import org.w3c.dom.Document;
import org.w3c.dom.Element;

public class JaxBSerializer {
    private static final JAXBContext JAXB_CONTEXT;

    static {
        try {
            JAXB_CONTEXT = JAXBContext.newInstance(NetconfState.class);
        } catch (JAXBException e) {
            throw new ExceptionInInitializerError(e);
        }
    }

    public Element toXml(final NetconfState monitoringModel) {
        final DOMResult res;
        try {
            final Marshaller marshaller = JAXB_CONTEXT.createMarshaller();

            marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);

            res = new DOMResult();
            marshaller.marshal(monitoringModel, res);
        } catch (final JAXBException e) {
            throw new RuntimeException("Unable to serialize netconf state " + monitoringModel, e);
        }
        return ((Document)res.getNode()).getDocumentElement();
    }
}

Fix netconf-monitoring not reusing JAXB context


package joshie.harvest.plugins.crafttweaker;

import minetweaker.IUndoableAction;
import minetweaker.api.item.IIngredient;
import minetweaker.api.oredict.IOreDictEntry;
import net.minecraft.item.ItemStack;

public abstract class BaseUndoable implements IUndoableAction {
    private boolean applied;

    @Override
    public boolean canUndo() {
        return false;
    }

    @Override
    public void undo() {}

    public abstract String getDescription();

    @Override
    public void apply() {
        if (!applied) {
            applied = true;
            applyOnce();
        }
    }

    public abstract void applyOnce();

    @Override
    public String describe() {
        return "[Harvest Festival] " + getDescription();
    }

    @Override
    public String describeUndo() {
        return "";
    }

    @Override
    public Object getOverrideKey() {
        return null;
    }

    //Helpers
    public static ItemStack asStack(IIngredient ingredient) {
        return ingredient.getInternal() instanceof ItemStack ? (ItemStack) ingredient.getInternal() : null;
    }

    public static String asOre(IIngredient ingredient) {
        return ingredient.getInternal() instanceof IOreDictEntry ? ((IOreDictEntry) ingredient).getName() : null;
    }
}

package joshie.harvest.plugins.crafttweaker;

import minetweaker.IUndoableAction;
import minetweaker.api.item.IIngredient;
import minetweaker.api.oredict.IOreDictEntry;
import net.minecraft.item.ItemStack;

public abstract class BaseUndoable implements IUndoableAction {
    private boolean applied;

    @Override
    public boolean canUndo() {
        return true;
    }

    @Override
    public void undo() {}

    public abstract String getDescription();

    @Override
    public void apply() {
        if (!applied) {
            applied = true;
            applyOnce();
        }
    }

    public abstract void applyOnce();

    @Override
    public String describe() {
        return "[Harvest Festival] " + getDescription();
    }

    @Override
    public String describeUndo() {
        return "";
    }

    @Override
    public Object getOverrideKey() {
        return null;
    }

    //Helpers
    public static ItemStack asStack(IIngredient ingredient) {
        return ingredient.getInternal() instanceof ItemStack ? (ItemStack) ingredient.getInternal() : null;
    }

    public static String asOre(IIngredient ingredient) {
        return ingredient.getInternal() instanceof IOreDictEntry ? ((IOreDictEntry) ingredient).getName() : null;
    }
}

Make canUndo true because @jaredlll08 told me to.


package io.quarkus.vertx.http.deployment.devmode;

import java.util.Optional;

import org.jboss.logging.Logger;

import io.quarkus.deployment.dev.remote.RemoteDevClient;
import io.quarkus.deployment.dev.remote.RemoteDevClientProvider;
import io.quarkus.runtime.LiveReloadConfig;
import io.quarkus.runtime.configuration.ConfigInstantiator;

public class HttpRemoteDevClientProvider implements RemoteDevClientProvider {

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

    /**
     * Used for remote dev mode, a bit of a hack to expose the config to the client
     */
    public static volatile LiveReloadConfig liveReloadConfig;

    @Override
    public Optional<RemoteDevClient> getClient() {
        if (liveReloadConfig == null) {
            liveReloadConfig = new LiveReloadConfig();
            ConfigInstantiator.handleObject(liveReloadConfig);
        }
        if (!liveReloadConfig.url.isPresent()) {
            return Optional.empty();
        }
        if (!liveReloadConfig.password.isPresent()) {
            log.warn(
                    "Live reload URL set but no password, remote dev requires a password, set quarkus.live-reload.password on both server and client");
            return Optional.empty();
        }
        return Optional.of(new HttpRemoteDevClient(liveReloadConfig.url.get(), liveReloadConfig.password.get(),
                liveReloadConfig.connectTimeout));
    }
}

package io.quarkus.vertx.http.deployment.devmode;

import java.util.Optional;

import org.jboss.logging.Logger;

import io.quarkus.deployment.dev.remote.RemoteDevClient;
import io.quarkus.deployment.dev.remote.RemoteDevClientProvider;
import io.quarkus.runtime.LiveReloadConfig;
import io.quarkus.runtime.configuration.ConfigInstantiator;

public class HttpRemoteDevClientProvider implements RemoteDevClientProvider {

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

    /**
     * Used for remote dev mode, a bit of a hack to expose the config to the client
     */
    public static volatile LiveReloadConfig liveReloadConfig;

    @Override
    public Optional<RemoteDevClient> getClient() {
        if (liveReloadConfig == null) {
            liveReloadConfig = new LiveReloadConfig();
            ConfigInstantiator.handleObject(liveReloadConfig);
        }
        if (!liveReloadConfig.url.isPresent()) {
            return Optional.empty();
        }
        if (!liveReloadConfig.password.isPresent()) {
            throw new RuntimeException(
                    "Live reload URL set but no password, remote dev requires a password, set quarkus.live-reload.password on both server and client");
        }
        return Optional.of(new HttpRemoteDevClient(liveReloadConfig.url.get(), liveReloadConfig.password.get(),
                liveReloadConfig.connectTimeout));
    }
}

Make missing password and error


package com.wkovacs64.mtorch;

import android.app.Application;
import android.os.Build;
import android.os.StrictMode;

import timber.log.Timber;

public final class CustomApplication extends Application {

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

        if (BuildConfig.DEBUG) {
            // Initialize Timber logging library
            Timber.plant(new Timber.DebugTree());

            // Enable StrictMode for debug builds
            enabledStrictMode();
        }
    }

    private void enabledStrictMode() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD) {
            StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
                    .detectAll()
                    .penaltyLog()
                    .penaltyDialog()
                    .build());
        }
    }
}

package com.wkovacs64.mtorch;

import android.app.Application;
import android.os.Build;
import android.os.StrictMode;

import timber.log.Timber;

public final class CustomApplication extends Application {

    @Override
    public void onCreate() {
        if (BuildConfig.DEBUG) {
            // Initialize Timber logging library
            Timber.plant(new Timber.DebugTree());

            // Enable StrictMode for debug builds
            enabledStrictMode();
        }

        super.onCreate();
    }

    private void enabledStrictMode() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD) {
            StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
                    .detectAll()
                    .penaltyLog()
                    .penaltyDialog()
                    .build());
            StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()
                    .detectAll()
                    .penaltyLog()
                    .build());
        }
    }
}

Set VM policy for Strict Mode


package io.github.shark_app.shark;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

public class ScanActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }
}

package io.github.shark_app.shark;

import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.util.SparseArray;

import com.google.android.gms.samples.vision.barcodereader.BarcodeCapture;
import com.google.android.gms.samples.vision.barcodereader.BarcodeGraphic;
import com.google.android.gms.vision.barcode.Barcode;

import java.util.List;

import xyz.belvi.mobilevisionbarcodescanner.BarcodeRetriever;

import static io.github.shark_app.shark.R.id.barcode;

public class ScanActivity extends AppCompatActivity implements BarcodeRetriever {
    private static final String TAG = "CAMERA";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_scan);
        BarcodeCapture barcodeCapture = (BarcodeCapture) getSupportFragmentManager().findFragmentById(barcode);
        barcodeCapture.setRetrieval(this);
    }

    @Override
    public void onRetrieved(final Barcode barcode) {
        Log.d(TAG, "Barcode read: " + barcode.displayValue);
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                AlertDialog.Builder builder = new AlertDialog.Builder(ScanActivity.this)
                        .setTitle("code retrieved")
                        .setMessage(barcode.displayValue);
                builder.show();
            }
        });
    }

    @Override
    public void onRetrievedFailed(final String reason) {
        Log.d(TAG, "Barcode reading failed : " + reason);
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                AlertDialog.Builder builder = new AlertDialog.Builder(ScanActivity.this)
                        .setTitle("Barcode failed")
                        .setMessage(reason);
                builder.show();
            }
        });
    }

    @Override
    public void onRetrievedMultiple(final Barcode closetToClick, final List<BarcodeGraphic> barcodeGraphics) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                String message = "Code selected : " + closetToClick.displayValue + "\n\nother " +
                        "codes in frame include : \n";
                for (int index = 0; index < barcodeGraphics.size(); index++) {
                    Barcode barcode = barcodeGraphics.get(index).getBarcode();
                    message += (index + 1) + ". " + barcode.displayValue + "\n";
                }
                AlertDialog.Builder builder = new AlertDialog.Builder(ScanActivity.this)
                        .setTitle("code retrieved")
                        .setMessage(message);
                builder.show();
            }
        });
    }

    @Override
    public void onBitmapScanned(SparseArray<Barcode> sparseArray) {
        // when image is scanned and processed
    }
}

Add QR Code scanning functionality


//package org.openhmis.provider;
//
//import javax.ws.rs.WebApplicationException;
//import javax.ws.rs.core.Response;
//import javax.ws.rs.ext.ExceptionMapper;
//import javax.ws.rs.ext.Provider;
//
//import org.apache.log4j.Logger;
//import org.glassfish.jersey.spi.ExtendedExceptionMapper;
//
//@Provider
//public class LoggerExceptionMapper implements ExceptionMapper<Throwable> {
//    private static final Logger log = Logger.getLogger(LoggerExceptionMapper.class);
//
//    public Response toResponse(Throwable t) {
//        log.error("Uncaught exception thrown by REST service", t);
//        if (t instanceof WebApplicationException) {
//            return ((WebApplicationException)t).getResponse();
//        } else {
//            return Response.status(Response.Status.INTERNAL_SERVER_ERROR)
//                   // Add an entity, etc.
//                   .build();
//        }
//    }
//}

package org.openhmis.provider;

import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.Response;
import javax.ws.rs.ext.ExceptionMapper;
import javax.ws.rs.ext.Provider;

import org.apache.log4j.Logger;
import org.glassfish.jersey.spi.ExtendedExceptionMapper;

@Provider
public class LoggerExceptionMapper implements ExceptionMapper<Throwable> {
    private static final Logger log = Logger.getLogger(LoggerExceptionMapper.class);

    public Response toResponse(Throwable t) {
        log.error("Uncaught exception thrown by REST service", t);
        if (t instanceof WebApplicationException) {
            return ((WebApplicationException)t).getResponse();
        } else {
            return Response.status(Response.Status.INTERNAL_SERVER_ERROR)
                   // Add an entity, etc.
                   .build();
        }
    }
}

Return logging removed in 1b3de81d


/*
 * #%L
 * GwtMaterial
 * %%
 * Copyright (C) 2015 - 2017 GwtMaterialDesign
 * %%
 * 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.
 * #L%
 */
package gwt.material.design.client.ui.table;

import com.google.gwt.user.client.Window;
import gwt.material.design.client.jquery.JQueryExtension;
import gwt.material.design.client.ui.html.Div;

public class XScrollPanel extends Div {

    private Div scrollBar = new Div();

    public XScrollPanel() {
        super("x-scroll");

        add(scrollBar);

        super.setStyle("width: calc(100% - "+ JQueryExtension.scrollBarWidth() +"px)");
        setHeight("16px");
    }

    @Override
    public void setWidth(String width) {
        scrollBar.setWidth(width);
    }

    @Override
    public void setHeight(String height) {
        super.setHeight(height);
        scrollBar.setHeight(height);
    }
}

/*
 * #%L
 * GwtMaterial
 * %%
 * Copyright (C) 2015 - 2017 GwtMaterialDesign
 * %%
 * 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.
 * #L%
 */
package gwt.material.design.client.ui.table;

import gwt.material.design.client.jquery.JQueryExtension;
import gwt.material.design.client.ui.html.Div;

public class XScrollPanel extends Div {

    private Div scrollBar = new Div();

    public XScrollPanel() {
        super("x-scroll");

        add(scrollBar);

        int barSize = JQueryExtension.scrollBarWidth();
        super.setStyle("width: calc(100% - " + barSize + "px)");
        setHeight((barSize + 1) + "px");
    }

    @Override
    public void setWidth(String width) {
        scrollBar.setWidth(width);
    }

    @Override
    public void setHeight(String height) {
        super.setHeight(height);
        scrollBar.setHeight(height);
    }
}

Use exact bar height calculations.


package de.retest.recheck;

import static org.assertj.core.api.Assertions.assertThat;

import org.junit.Test;

public class TestCaseFinderJunitVintageTest {

	@Test
	public void junit_vintage_test_cases_should_be_found() throws Exception {
		final StackTraceElement element = TestCaseFinder.findTestCaseMethodInStack();
		assertThat( element.getClassName() ).isEqualTo( getClass().getName() );
		assertThat( element.getMethodName() ).isEqualTo( "junit_vintage_test_cases_should_be_found" );
	}

}

package de.retest.recheck;

import static org.assertj.core.api.Assertions.assertThat;

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

public class TestCaseFinderJunitVintageTest {

	@Test
	public void junit_vintage_test_annotation_should_be_found() throws Exception {
		final StackTraceElement element = TestCaseFinder.findTestCaseMethodInStack();
		assertThat( element.getClassName() ).isEqualTo( getClass().getName() );
		assertThat( element.getMethodName() ).isEqualTo( "junit_vintage_test_annotation_should_be_found" );
	}

	@Before
	public void junit_vintage_before_annotation_should_be_found() throws Exception {
		final StackTraceElement element = TestCaseFinder.findTestCaseMethodInStack();
		assertThat( element.getClassName() ).isEqualTo( getClass().getName() );
		assertThat( element.getMethodName() ).isEqualTo( "junit_vintage_before_annotation_should_be_found" );
	}

	@After
	public void junit_vintage_after_annotation_should_be_found() throws Exception {
		final StackTraceElement element = TestCaseFinder.findTestCaseMethodInStack();
		assertThat( element.getClassName() ).isEqualTo( getClass().getName() );
		assertThat( element.getMethodName() ).isEqualTo( "junit_vintage_after_annotation_should_be_found" );
	}

	@BeforeClass
	public static void junit_vintage_before_class_annotation_should_be_found() throws Exception {
		final StackTraceElement element = TestCaseFinder.findTestCaseMethodInStack();
		assertThat( element.getClassName() ).isEqualTo( TestCaseFinderJunitVintageTest.class.getName() );
		assertThat( element.getMethodName() ).isEqualTo( "junit_vintage_before_class_annotation_should_be_found" );
	}

	@AfterClass
	public static void junit_vintage_after_class_annotation_should_be_found() throws Exception {
		final StackTraceElement element = TestCaseFinder.findTestCaseMethodInStack();
		assertThat( element.getClassName() ).isEqualTo( TestCaseFinderJunitVintageTest.class.getName() );
		assertThat( element.getMethodName() ).isEqualTo( "junit_vintage_after_class_annotation_should_be_found" );
	}

}

Test all JUnit vintage annotations from TestCaseFinder


package com.alibaba.json.bvt.jsonp;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.JSONPObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import junit.framework.TestCase;

/**
 * Created by wenshao on 21/02/2017.
 */
public class JSONPParseTest3 extends TestCase {
    public void test_f() throws Exception {
        String text = "parent.callback ({'id':1, 'name':'ido)nans'},1,2 );   /**/ ";

        JSONPObject jsonpObject = (JSONPObject) JSON.parseObject(text, JSONPObject.class);
        assertEquals("parent.callback", jsonpObject.getFunction());

        assertEquals(3, jsonpObject.getParameters().size());
        JSONObject param = (JSONObject) jsonpObject.getParameters().get(0);
        assertEquals(1, param.get("id"));
        assertEquals("ido)nans", param.get("name"));

        String json = JSON.toJSONString(jsonpObject, SerializerFeature.BrowserSecure);
        assertEquals("/**/parent.callback({\"name\":\"ido\\u0029nans\",\"id\":1},1,2)", json);
    }
}

package com.alibaba.json.bvt.jsonp;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.JSONPObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import junit.framework.TestCase;

/**
 * Created by wenshao on 21/02/2017.
 */
public class JSONPParseTest3 extends TestCase {
    public void test_f() throws Exception {
        String text = "parent.callback ({'id':1, 'name':'ido)nans'},1,2 );   /**/ ";

        JSONPObject jsonpObject = (JSONPObject) JSON.parseObject(text, JSONPObject.class);
        assertEquals("parent.callback", jsonpObject.getFunction());

        assertEquals(3, jsonpObject.getParameters().size());
        JSONObject param = (JSONObject) jsonpObject.getParameters().get(0);
        assertEquals(1, param.get("id"));
        assertEquals("ido)nans", param.get("name"));

        String json = JSON.toJSONString(jsonpObject, SerializerFeature.BrowserSecure, SerializerFeature.MapSortField);
        assertEquals("/**/parent.callback({\"id\":1,\"name\":\"ido\\u0029nans\"},1,2)", json);
    }
}

Enable SerializeFeature.MapSortField for deterministic order


import java.util.spi.ToolProvider;

/** Use tool provider to find and run javac tool. */
class Tool0 {
  public static void main(String... args) {
    ToolProvider.findFirst("javac").orElseThrow().run(System.out, System.err, args);
  }
}

import java.util.spi.ToolProvider;

/** Use tool provider to find and run javac tool. */
class Tool0 {
  public static void main(String... args) {
    ToolProvider.findFirst("javac").orElseThrow().run(System.out, System.err, "--version");
  }
}

Reset setup of step zero


package me.xdrop.passlock.datasource.sqlite;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;

public class SQLitePrepare {

    private final static Logger LOG = LoggerFactory.getLogger(SQLitePrepare.class);

    /**
     * Creates the SQLite passwords table
     */
    public static void createPassTable(Connection sqLiteConnection) {

        String sql =
                "CREATE TABLE IF NOT EXISTS passwords (id integer PRIMARY KEY ,\n" +
                "ref TEXT UNIQUE NOT NULL, description TEXT, payload TEXT NOT NULL, salt TEXT NOT NULL,\n" +
                "algo TEXT, iv TEXT NOT NULL, date_created INTEGER, last_updated INTEGER)";

        performSingleTransaction(sqLiteConnection, sql);

    }

    /**
     * Resets (deletes and recreates) the passwords table
     */
    public static void resetTable(Connection sqLiteConnection) {

        String sql = "DROP TABLE passwords";

        performSingleTransaction(sqLiteConnection, sql);

        createPassTable(sqLiteConnection);

    }

    private static void performSingleTransaction(Connection sqLiteConnection, String sql) {
        PreparedStatement statement = null;

        try {

            statement = sqLiteConnection.prepareStatement(sql);
            statement.executeUpdate();
            statement.close();

        } catch (SQLException e) {
            LOG.debug("SQL exception occurred", e);
        } finally {

            if (statement != null) {
                try {
                    statement.close();
                } catch (SQLException e) {
                    LOG.debug("Failed to close statement", e);
                }
            }

        }

    }

}

package me.xdrop.passlock.datasource.sqlite;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;

public class SQLitePrepare {

    private final static Logger LOG = LoggerFactory.getLogger(SQLitePrepare.class);

    /**
     * Creates the SQLite passwords table
     */
    public static void createPassTable(Connection sqLiteConnection) {

        String sql =
                "CREATE TABLE IF NOT EXISTS passwords (id integer PRIMARY KEY ,\n" +
                "ref TEXT UNIQUE NOT NULL, description TEXT, payload TEXT NOT NULL, salt TEXT NOT NULL,\n" +
                "algo TEXT, iv TEXT NOT NULL, date_created INTEGER, last_updated INTEGER)";

        performSingleTransaction(sqLiteConnection, sql);

    }

    /**
     * Resets (deletes and recreates) the passwords table
     */
    public static void resetTable(Connection sqLiteConnection) {

        String sql = "DROP TABLE IF EXISTS passwords";

        performSingleTransaction(sqLiteConnection, sql);

        createPassTable(sqLiteConnection);

    }

    private static void performSingleTransaction(Connection sqLiteConnection, String sql) {
        PreparedStatement statement = null;

        try {

            statement = sqLiteConnection.prepareStatement(sql);
            statement.executeUpdate();
            statement.close();

        } catch (SQLException e) {
            LOG.debug("SQL exception occurred", e);
        } finally {

            if (statement != null) {
                try {
                    statement.close();
                } catch (SQLException e) {
                    LOG.debug("Failed to close statement", e);
                }
            }

        }

    }

}

Switch back to DROP IF EXISTS


package edu.deanza.calendar.models;

/**
 * Created by soso1 on 8/8/2016.
 */

public class Organization {

    protected String name;
    protected String description;
    protected String facebookUrl;

    public Organization() {}

    public Organization(String name, String description) {
        this.name = name;
        this.description = description;
        this.facebookUrl = null;
    }
    public Organization(String name, String description, String facebookUrl) {
        this.name = name;
        this.description = description;
        this.facebookUrl = facebookUrl;
    }

    public String getName() {
        return name;
    }

    public String getDescription() {
        return description;
    }

    public String getFacebookUrl() {
        return facebookUrl;
    }

}

package edu.deanza.calendar.models;

/**
 * Created by soso1 on 8/8/2016.
 */

public class Organization {

    protected String name;
    protected String description;
    protected String facebookUrl;

    public Organization() {}

    public Organization(String name, String description, String facebookUrl) {
        this.name = name;
        this.description = description;
        this.facebookUrl = facebookUrl;
    }

    public String getName() {
        return name;
    }

    public String getDescription() {
        return description;
    }

    public String getFacebookUrl() {
        return facebookUrl;
    }

}

Remove constructor w/o fbUrl; empty string guaranteed


/*
 * Copyright (c) 2012-2022 The ANTLR Project. All rights reserved.
 * Use of this file is governed by the BSD 3-clause license that
 * can be found in the LICENSE.txt file in the project root.
 */

package org.antlr.v4.test.runtime.states;

import org.antlr.v4.test.runtime.Stage;

public abstract class State {
	public final State previousState;

	public final Exception exception;

	public abstract Stage getStage();

	public boolean containsErrors() {
		return exception != null;
	}

	public String getErrorMessage() {
		String result = "State: " + getStage() + "; ";
		if (exception != null) {
			result += exception.toString();
			result += "\nCause:\n";
			result += exception.getCause().toString();
		}
		return result;
	}

	public State(State previousState, Exception exception) {
		this.previousState = previousState;
		this.exception = exception;
	}
}

/*
 * Copyright (c) 2012-2022 The ANTLR Project. All rights reserved.
 * Use of this file is governed by the BSD 3-clause license that
 * can be found in the LICENSE.txt file in the project root.
 */

package org.antlr.v4.test.runtime.states;

import org.antlr.v4.test.runtime.Stage;

public abstract class State {
	public final State previousState;

	public final Exception exception;

	public abstract Stage getStage();

	public boolean containsErrors() {
		return exception != null;
	}

	public String getErrorMessage() {
		String result = "State: " + getStage() + "; ";
		if (exception != null) {
			result += exception.toString();
			if ( exception.getCause()!=null ) {
				result += "\nCause:\n";
				result += exception.getCause().toString();
			}
		}
		return result;
	}

	public State(State previousState, Exception exception) {
		this.previousState = previousState;
		this.exception = exception;
	}
}

Augment error message during testing to include full cause of problem. (round 2 to avoid null ptr)


package org.elasticsoftware.elasticactors.kubernetes.cluster.statemachine.impl;

import io.fabric8.kubernetes.api.model.apps.StatefulSet;
import org.elasticsoftware.elasticactors.kubernetes.cluster.TaskScheduler;
import org.elasticsoftware.elasticactors.kubernetes.cluster.statemachine.AbstractKubernetesStateMachine;

import java.util.concurrent.ExecutorService;

import static java.util.concurrent.Executors.newSingleThreadExecutor;

public class SingleThreadKubernetesStateMachine extends AbstractKubernetesStateMachine {

    private final ExecutorService executorService = newSingleThreadExecutor();

    public SingleThreadKubernetesStateMachine(TaskScheduler taskScheduler) {
        super(taskScheduler);
    }

    @Override
    public void handleStateUpdate(StatefulSet resource) {
        logger.info("Received state update. Submitting processing task to the Single Thread Executor Service");
        executorService.submit(() -> processStateUpdate(resource));
    }
}

package org.elasticsoftware.elasticactors.kubernetes.cluster.statemachine.impl;

import io.fabric8.kubernetes.api.model.apps.StatefulSet;
import org.elasticsoftware.elasticactors.kubernetes.cluster.TaskScheduler;
import org.elasticsoftware.elasticactors.kubernetes.cluster.statemachine.AbstractKubernetesStateMachine;

import java.util.concurrent.ExecutorService;

import static java.util.concurrent.Executors.newSingleThreadExecutor;

public class SingleThreadKubernetesStateMachine extends AbstractKubernetesStateMachine {

    private final ExecutorService executorService = newSingleThreadExecutor(r -> new Thread(r, "KUBERNETES_CLUSTERSERVICE_STATE_MACHINE"));

    public SingleThreadKubernetesStateMachine(TaskScheduler taskScheduler) {
        super(taskScheduler);
    }

    @Override
    public void handleStateUpdate(StatefulSet resource) {
        logger.info("Received state update. Submitting processing task to the Single Thread Executor Service");
        executorService.submit(() -> processStateUpdate(resource));
    }
}

Add thread name to the state machine


package com.github.slidekb.back.settings;

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

public class PluginSettings {
    String usedSlider;
    List<String> processes;
    List<String> hotkeys;
    boolean alwaysRun;
    List<String> sliderList;

    public List<String> getSliderList() {
        return sliderList;
    }

    public void setSliderList(List<String> list) {
        this.sliderList = list;
    }

    public String getUsedSlider() {
        return usedSlider;
    }

    public void setUsedSlider(String usedSlider, int position) {
        this.usedSlider = usedSlider;
    }

    public List<String> getProcesses() {
        if (processes == null) {
            processes = new ArrayList<>();
        }

        return processes;
    }

    public List<String> getHotkeys() {
        if (hotkeys == null) {
            hotkeys = new ArrayList<>();
        }

        return hotkeys;
    }

    public boolean isAlwaysRun() {
        return alwaysRun;
    }

    public void setAlwaysRun(boolean alwaysRun) {
        this.alwaysRun = alwaysRun;
    }
}

package com.github.slidekb.back.settings;

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

public class PluginSettings {
    List<String> processes;
    List<String> hotkeys;
    boolean alwaysRun;
    List<String> sliderList;

    public List<String> getSliderList() {
        return sliderList;
    }

    public void setSliderList(List<String> list) {
        this.sliderList = list;
    }

    public List<String> getProcesses() {
        if (processes == null) {
            processes = new ArrayList<>();
        }

        return processes;
    }

    public List<String> getHotkeys() {
        if (hotkeys == null) {
            hotkeys = new ArrayList<>();
        }

        return hotkeys;
    }

    public boolean isAlwaysRun() {
        return alwaysRun;
    }

    public void setAlwaysRun(boolean alwaysRun) {
        this.alwaysRun = alwaysRun;
    }
}

Remove single slider entry from plugin settings


package mytown.protection.segment.getter;

public class GetterConstant extends Getter {

    public final Object constant;

    public GetterConstant(Object constant) {
        this.constant = constant;
    }

    @Override
    public Object invoke(Class<?> returnType, Object instance, Object... parameters) {
        return constant;
    }
}

package mytown.protection.segment.getter;

import com.google.gson.internal.LazilyParsedNumber;

public class GetterConstant extends Getter {

    public final Object constant;

    public GetterConstant(Object constant) {
        this.constant = constant;
    }

    @Override
    public Object invoke(Class<?> returnType, Object instance, Object... parameters) {
        if (returnType.equals(Integer.class)) {
            return (Object)((LazilyParsedNumber)constant).intValue();
        }
        return constant;
    }
}

Allow conversion to Integer from constant.


package cc.clv.BlueRobe.desktop;

import com.badlogic.gdx.backends.lwjgl.LwjglApplication;
import com.badlogic.gdx.backends.lwjgl.LwjglApplicationConfiguration;

import cc.clv.BlueRobe.BlueRobe;

public class DesktopLauncher {
    public static void main(String[] arg) {
        LwjglApplicationConfiguration config = new LwjglApplicationConfiguration();
        config.width = 640;
        config.height = 1136;
        new LwjglApplication(new BlueRobe(), config);
    }
}

package cc.clv.BlueRobe.desktop;

import com.badlogic.gdx.backends.lwjgl.LwjglApplication;
import com.badlogic.gdx.backends.lwjgl.LwjglApplicationConfiguration;

import cc.clv.BlueRobe.BlueRobe;

public class DesktopLauncher {
    public static void main(String[] arg) {
        LwjglApplicationConfiguration config = new LwjglApplicationConfiguration();
        config.width = 320;
        config.height = 568;
        new LwjglApplication(new BlueRobe(), config);
    }
}

Change window size for desktop


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

package alluxio;

import org.junit.Assert;
import org.junit.Test;
import org.junit.runners.model.Statement;

import java.io.ByteArrayOutputStream;
import java.io.PrintStream;

/**
 * Unit tests for {@link SystemOutRule}.
 */
public class SystemOutRuleTest {
  private static final ByteArrayOutputStream OUTPUT = new ByteArrayOutputStream();
  private static final PrintStream ORIGINAL_SYSTEM_OUT = System.out;

  private Statement mStatement = new Statement() {
    @Override
    public void evaluate() throws Throwable {
      System.out.println("2048");
      Assert.assertEquals("2048\n", OUTPUT.toString());
      OUTPUT.reset();

      System.out.println("1234");
      Assert.assertEquals("1234\n", OUTPUT.toString());
    }
  };

  @Test
  public void testSystemOutRule() throws Throwable {
    new SystemOutRule(OUTPUT).apply(mStatement, null).evaluate();
    Assert.assertEquals(System.out, ORIGINAL_SYSTEM_OUT);
  }
}

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

package alluxio;

import static org.junit.Assert.assertEquals;

import org.junit.Test;
import org.junit.runners.model.Statement;

import java.io.ByteArrayOutputStream;
import java.io.PrintStream;

/**
 * Unit tests for {@link SystemOutRule}.
 */
public class SystemOutRuleTest {
  private static final ByteArrayOutputStream OUTPUT = new ByteArrayOutputStream();
  private static final PrintStream ORIGINAL_SYSTEM_OUT = System.out;

  private Statement mStatement = new Statement() {
    @Override
    public void evaluate() throws Throwable {
      System.out.println("2048");
      assertEquals("2048\n", OUTPUT.toString());
      OUTPUT.reset();

      System.out.println("1234");
      assertEquals("1234\n", OUTPUT.toString());
    }
  };

  @Test
  public void testSystemOutRule() throws Throwable {
    new SystemOutRule(OUTPUT).apply(mStatement, null).evaluate();
    assertEquals(System.out, ORIGINAL_SYSTEM_OUT);
  }
}

Use static imports for standard test utilities


/*
 * Copyright (c) 2014-present, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 */

package com.facebook.yoga;

import com.facebook.proguard.annotations.DoNotStrip;

/**
 * Inteface for recieving logs from native layer. Use by setting YogaNode.setLogger(myLogger);
 * See YogaLogLevel for the different log levels.
 */
@DoNotStrip
public interface YogaLogger {
  @DoNotStrip
  void log(YogaNode node, YogaLogLevel level, String message);
}

/*
 * Copyright (c) 2014-present, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 */

package com.facebook.yoga;

import com.facebook.proguard.annotations.DoNotStrip;

/**
 * Interface for receiving logs from native layer. Use by setting YogaNode.setLogger(myLogger);
 * See YogaLogLevel for the different log levels.
 */
@DoNotStrip
public interface YogaLogger {
  @DoNotStrip
  void log(YogaNode node, YogaLogLevel level, String message);
}

Fix Android comment and docblock typos


package com.github.arteam.jdbi3;

import com.codahale.metrics.health.HealthCheck;
import io.dropwizard.db.TimeBoundHealthCheck;
import io.dropwizard.util.Duration;
import org.jdbi.v3.core.Handle;
import org.jdbi.v3.core.Jdbi;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.ExecutorService;

/**
 * Health check which verifies the availability of the database
 */
public class JdbiHealthCheck extends HealthCheck {
    private static final Logger log = LoggerFactory.getLogger(JdbiHealthCheck.class);
    protected static final String VALIDATION_QUERY_FAILED = "Validation query failed";

    private final Jdbi jdbi;
    private final String validationQuery;
    private final TimeBoundHealthCheck timeBoundHealthCheck;

    public JdbiHealthCheck(ExecutorService executorService, Duration duration, Jdbi dbi, String validationQuery) {
        this.jdbi = dbi;
        this.validationQuery = validationQuery;
        this.timeBoundHealthCheck = new TimeBoundHealthCheck(executorService, duration);
    }

    @Override
    protected Result check() throws Exception {
        return timeBoundHealthCheck.check(() -> {
            try (Handle handle = jdbi.open()) {
                handle.execute(validationQuery);
                return Result.healthy();
            } catch (Exception e) {
                log.error("jDBI Healthcheck failed. validation-query={}", validationQuery, e);
                return Result.unhealthy(VALIDATION_QUERY_FAILED);
            }
        });
    }
}

package com.github.arteam.jdbi3;

import com.codahale.metrics.health.HealthCheck;
import io.dropwizard.db.TimeBoundHealthCheck;
import io.dropwizard.util.Duration;
import org.jdbi.v3.core.Handle;
import org.jdbi.v3.core.Jdbi;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.ExecutorService;

/**
 * Health check which verifies the availability of the database
 */
public class JdbiHealthCheck extends HealthCheck {
    private static final Logger log = LoggerFactory.getLogger(JdbiHealthCheck.class);

    private static final String VALIDATION_QUERY_FAILED = "Validation query failed";

    private final Jdbi jdbi;
    private final String validationQuery;
    private final TimeBoundHealthCheck timeBoundHealthCheck;

    public JdbiHealthCheck(ExecutorService executorService, Duration duration, Jdbi dbi, String validationQuery) {
        this.jdbi = dbi;
        this.validationQuery = validationQuery;
        this.timeBoundHealthCheck = new TimeBoundHealthCheck(executorService, duration);
    }

    @Override
    protected Result check() throws Exception {
        return timeBoundHealthCheck.check(() -> {
            try (Handle handle = jdbi.open()) {
                handle.execute(validationQuery);
                return Result.healthy();
            } catch (Exception e) {
                log.error("jDBI Healthcheck failed. validation-query={}", validationQuery, e);
                return Result.unhealthy(VALIDATION_QUERY_FAILED);
            }
        });
    }
}

Make the validation query constant private