package com.kii.thingif.command;

/**
 * Marks a class as group of actions of command. The class implements Acton defines single actions
 * as fields of the class.
 *
The class must define {@link ActionAnnotation} for each field of the class, SDK uses the
 * defined annotations to serialize the class to json data or deserialize json data to a instance
 * of the class.
 *
 *
Serialize Principles

 *

 *
Name of action after serialized.
 *

 *

 *             If value of actionName of {@link ActionAnnotation} is not an empty string, SDK uses
 *             this value as key of action in serialized json object.
 *

 *

 *             If value of actionName annotation is empty string, SDK will name of attribute of
 *             the class as key of action in serialized json object.
 *

 *

 *

 *
Value of action is serialized with Gson.
 *

 *

 *             If action value is null, SDK does not include the action into serialized json data.
 *

 *

 *             If action value is primitive type(like int, boolean, float, double), SDK serializes
 *             it by its type.
 *

 *

 *             If action value is simple data type(like String, Number or subclass of Number(Integer,
 *             Float, etc.)), SDK serializes it by its type.
 *

 *

 *             If action value is customized object defined by developer, SDK serializes it using Gson.
 *

 *

 *            If action value is Collection type, SDK serializes it using Gson.
 *

 *

 *            If action value is array(like int[]), SDK serialized it using Gson.
 *

 *

 *

 *

 */
public interface Action {
}

package com.kii.thingif.command;

/**
 * Represents base cass of Action.
 */
public interface Action{
}

Revert "Add description of serialize and deserialize(not completed)"


package net.pdp7.v2f.core;

import junit.framework.TestCase;
import net.pdp7.v2f.core.Router.ListTableRoute;

public class RouterTest extends TestCase {

	public void testRouter() {
		ListTableRoute route = (ListTableRoute) new Router(null, null).findRoute("/table_name/");
		assertEquals("table_name", route.table);
	}

	public void testDetailRoute() {
		assertFalse(new Router(null, null).getDetailRoute("table", "funky/id").contains("funky/id"));
	}
}

package net.pdp7.v2f.core;

import junit.framework.TestCase;
import net.pdp7.v2f.core.Router.ListTableRoute;

public class RouterTest extends TestCase {

	public void testRouter() {
		ListTableRoute route = (ListTableRoute) new Router(null, null, null).findRoute("/table_name/");
		assertEquals("table_name", route.table);
	}

	public void testDetailRoute() {
		assertFalse(new Router(null, null, null).getDetailRoute("table", "funky/id").contains("funky/id"));
	}
}

Fix broken build due to not running tests before committing :(


/*
 The caLAB Software License, Version 0.5

 Copyright 2006 SAIC. This software was developed in conjunction with the National
 Cancer Institute, and so to the extent government employees are co-authors, any
 rights in such works shall be subject to Title 17 of the United States Code,
 section 105.

 */
package gov.nih.nci.calab.ui.core;

/**
 * This class calls the Struts ForwardAction to forward to a page, aslo
 * extends AbstractBaseAction to inherit the user authentication features.
 *
 * @author pansu
 */

/* CVS $Id: BaseForwardAction.java,v 1.3 2006-08-02 21:27:59 pansu Exp $ */

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

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.actions.ForwardAction;

public class BaseForwardAction extends AbstractBaseAction {
	public ActionForward executeTask(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		ForwardAction forwardAction = new ForwardAction();
		return forwardAction.execute(mapping, form, request, response);
	}

	public boolean loginRequired() {
		return true;
	}

	public boolean canUserExecute(HttpSession session) {
		return true;
	}
}

/*
 The caLAB Software License, Version 0.5

 Copyright 2006 SAIC. This software was developed in conjunction with the National
 Cancer Institute, and so to the extent government employees are co-authors, any
 rights in such works shall be subject to Title 17 of the United States Code,
 section 105.

 */
package gov.nih.nci.calab.ui.core;

/**
 * This class calls the Struts ForwardAction to forward to a page, aslo
 * extends AbstractBaseAction to inherit the user authentication features.
 *
 * @author pansu
 */

/* CVS $Id: BaseForwardAction.java,v 1.4 2007-10-25 20:56:51 cais Exp $ */

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

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.actions.ForwardAction;

public class BaseForwardAction extends AbstractBaseAction {
	public ActionForward executeTask(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		ForwardAction forwardAction = new ForwardAction();
		return forwardAction.execute(mapping, form, request, response);
	}

	public boolean loginRequired() {
		//return true;
		return false;
	}

	public boolean canUserExecute(HttpSession session) {
		return true;
	}
}

Set loginRequired to false. For users without login, this is required for "back" link on some pages to function.


package com.andela.webservice;

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

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }
}

package com.andela.webservice;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.method.ScrollingMovementMethod;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {
    private TextView output;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        output = (TextView) findViewById(R.id.textView);
        output.setMovementMethod(new ScrollingMovementMethod());

        for(int i = 0; i<100; i++) {
            updateDisplay("Task " + i);
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if(item.getItemId() == R.id.action_do_task) {
            updateDisplay("Task done!");
        }
        return true;
    }

    private void updateDisplay(String s) {
        output.append(s + "\n");
    }
}

Inflate the Menu, set the textView to scroll vertically


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

import java.io.Closeable;

import org.apache.jmeter.report.core.Sample;

/**
 * Describes sample writer basic operations.

 *

 * Basically a sample writer is able to write samples to an unknown destination
 * and close itself.

 *
 * @since 2.14
 */
abstract public class SampleWriter implements Closeable {

    /**
     * Write a sample to the underlying destination
     *
     * @param s
     *            The sample to be written
     * @return The number of samples written at this time to the undernlying
     *         destination
     */
    abstract public long write(Sample s);
}

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

import java.io.Closeable;

import org.apache.jmeter.report.core.Sample;

/**
 * Describes sample writer basic operations.

 *

 * Basically a sample writer is able to write samples to an unknown destination
 * and close itself.

 *
 * @since 2.14
 */
abstract public class SampleWriter implements Closeable {

    /**
     * Write a sample to the underlying destination
     *
     * @param sample
     *            The sample to be written (Must not be {@code null})
     * @return The number of samples written at this time to the underlying
     *         destination
     */
    abstract public long write(Sample sample);
}

Use a more descriptive variable name and point out, that the parameter must not be null.


package net.piemaster.jario.systems;

import net.piemaster.jario.components.CollisionMesh;
import net.piemaster.jario.components.Transform;

import com.artemis.ComponentMapper;
import com.artemis.Entity;
import com.artemis.EntityProcessingSystem;

public class CollisionMeshSystem extends EntityProcessingSystem
{
	private ComponentMapper<Transform> transformMapper;
	private ComponentMapper<CollisionMesh> meshMapper;

	@SuppressWarnings("unchecked")
	public CollisionMeshSystem()
	{
		super(Transform.class, CollisionMesh.class);
	}

	@Override
	public void initialize()
	{
		transformMapper = new ComponentMapper<Transform>(Transform.class, world.getEntityManager());
		meshMapper = new ComponentMapper<CollisionMesh>(CollisionMesh.class, world.getEntityManager());
	}

	@Override
	protected void process(Entity e)
	{
		CollisionMesh mesh = meshMapper.get(e);
		if(mesh != null)
		{
			Transform t = transformMapper.get(e);
			meshMapper.get(e).setLocation((int)t.getX(), (int)t.getY());
		}
	}
}

package net.piemaster.jario.systems;

import net.piemaster.jario.components.CollisionMesh;
import net.piemaster.jario.components.Transform;

import com.artemis.ComponentMapper;
import com.artemis.Entity;
import com.artemis.EntityProcessingSystem;

public class CollisionMeshSystem extends EntityProcessingSystem
{
	private ComponentMapper<Transform> transformMapper;
	private ComponentMapper<CollisionMesh> meshMapper;

	@SuppressWarnings("unchecked")
	public CollisionMeshSystem()
	{
		super(Transform.class, CollisionMesh.class);
	}

	@Override
	public void initialize()
	{
		transformMapper = new ComponentMapper<Transform>(Transform.class, world.getEntityManager());
		meshMapper = new ComponentMapper<CollisionMesh>(CollisionMesh.class, world.getEntityManager());
	}

	@Override
	protected void process(Entity e)
	{
		CollisionMesh mesh = meshMapper.get(e);
		if(mesh != null)
		{
			Transform t = transformMapper.get(e);
			meshMapper.get(e).setLocation(t.getX(), t.getY());
		}
	}
}

Debug update continued: Removed the cost of mesh position to ints.


package com.genymobile.scrcpy;

import android.util.Log;

/**
 * Log both to Android logger (so that logs are visible in "adb logcat") and standard output/error (so that they are visible in the terminal
 * directly).
 */
public final class Ln {

    private static final String TAG = "scrcpy";

    private Ln() {
        // not instantiable
    }

    public static void d(String message) {
        Log.d(TAG, message);
        System.out.println("DEBUG: " + message);
    }

    public static void i(String message) {
        Log.i(TAG, message);
        System.out.println("INFO: " + message);
    }

    public static void w(String message) {
        Log.w(TAG, message);
        System.out.println("WARN: " + message);
    }

    public static void e(String message, Throwable throwable) {
        Log.e(TAG, message, throwable);
        System.out.println("ERROR: " + message);
        throwable.printStackTrace();
    }
}

package com.genymobile.scrcpy;

import android.util.Log;

/**
 * Log both to Android logger (so that logs are visible in "adb logcat") and standard output/error (so that they are visible in the terminal
 * directly).
 */
public final class Ln {

    private static final String TAG = "scrcpy";

    enum Level {
        DEBUG,
        INFO,
        WARN,
        ERROR;
    }

    private static final Level THRESHOLD = BuildConfig.DEBUG ? Level.DEBUG : Level.INFO;

    private Ln() {
        // not instantiable
    }

    public static boolean isEnabled(Level level) {
        return level.ordinal() >= THRESHOLD.ordinal();
    }

    public static void d(String message) {
        if (isEnabled(Level.DEBUG)) {
            Log.d(TAG, message);
            System.out.println("DEBUG: " + message);
        }
    }

    public static void i(String message) {
        if (isEnabled(Level.INFO)) {
            Log.i(TAG, message);
            System.out.println("INFO: " + message);
        }
    }

    public static void w(String message) {
        if (isEnabled(Level.WARN)) {
            Log.w(TAG, message);
            System.out.println("WARN: " + message);
        }
    }

    public static void e(String message, Throwable throwable) {
        if (isEnabled(Level.ERROR)) {
            Log.e(TAG, message, throwable);
            System.out.println("ERROR: " + message);
            throwable.printStackTrace();
        }
    }
}

Enable debug logs only for debug builds on server


package com.github.sbugat.samplerest.web.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletResponse;

@WebFilter(
		urlPatterns = "/*")
public class ApiOriginFilter implements Filter {

	@Override
	public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain) throws IOException, ServletException {
		final HttpServletResponse res = (HttpServletResponse) response;
		res.addHeader("Access-Control-Allow-Origin", "*");
		res.addHeader("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT");
		res.addHeader("Access-Control-Allow-Headers", "Content-Type");
		chain.doFilter(request, response);
	}

	@Override
	public void destroy() {
	}

	@Override
	public void init(final FilterConfig filterConfig) throws ServletException {
	}
}

package com.github.sbugat.samplerest.web.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletResponse;

@WebFilter(
		urlPatterns = "/*")
public class ApiOriginFilter implements Filter {

	@Override
	public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain) throws IOException, ServletException {
		final HttpServletResponse httpServletResponse = (HttpServletResponse) response;
		httpServletResponse.addHeader("Access-Control-Allow-Origin", "*");
		httpServletResponse.addHeader("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT");
		httpServletResponse.addHeader("Access-Control-Allow-Headers", "Content-Type, api_key, Authorization");
		chain.doFilter(request, response);
	}

	@Override
	public void destroy() {
	}

	@Override
	public void init(final FilterConfig filterConfig) throws ServletException {
	}
}

Add api-key and authorisation in http header


import arez.annotations.Action;
import arez.annotations.ArezComponent;
import arez.annotations.Memoize;
import arez.annotations.Observable;
import javax.annotation.Nonnull;

@ArezComponent
public abstract class AnnotationsOnModel
{
  @Observable
  @Nonnull
  @SuppressWarnings( "ThisANnotationShouldNotBeCopied" )
  public String getTime()
  {
    return "";
  }

  @Observable
  @SuppressWarnings( "ThisANnotationShouldNotBeCopied" )
  public void setTime( @Nonnull @SuppressWarnings( "ThisANnotationShouldNotBeCopied" ) final String time )
  {
  }

  @Action
  @SuppressWarnings( "ThisANnotationShouldNotBeCopied" )
  public void doStuff( @Nonnull @SuppressWarnings( "ThisANnotationShouldNotBeCopied" ) final String time )
  {
  }

  @Memoize
  @Nonnull
  @SuppressWarnings( "ThisANnotationShouldNotBeCopied" )
  public Integer someValue()
  {
    return 0;
  }
}

import arez.annotations.Action;
import arez.annotations.ArezComponent;
import arez.annotations.Memoize;
import arez.annotations.Observable;
import javax.annotation.Nonnull;

@ArezComponent
public abstract class AnnotationsOnModel
{
  public @interface DoNotCopyThisAnnotation
  {
  }

  @Observable
  @Nonnull
  @DoNotCopyThisAnnotation
  public String getTime()
  {
    return "";
  }

  @Observable
  @DoNotCopyThisAnnotation
  public void setTime( @Nonnull @DoNotCopyThisAnnotation final String time )
  {
  }

  @Action
  @DoNotCopyThisAnnotation
  public void doStuff( @Nonnull @DoNotCopyThisAnnotation final String time )
  {
  }

  @Memoize
  @Nonnull
  @DoNotCopyThisAnnotation
  public Integer someValue()
  {
    return 0;
  }
}

Use an explicit annotation in test for non copying annotation


package cl.fatman.capital.fund;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;

import org.hibernate.annotations.GenericGenerator;

import java.time.LocalDate;

@Entity
@Table(name = "foment_unit")
public class FomentUnit {

	@Id
	@GeneratedValue(generator = "increment")
	@GenericGenerator(name = "increment", strategy = "increment")
	private int id;
	private double value;
	@Column(unique = true)
	private LocalDate date;

	public FomentUnit() {
		super();
	}

	public FomentUnit(double value, LocalDate date) {
		super();
		this.value = value;
		this.date = date;
	}

	public int getId() {
		return id;
	}

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

	public double getValue() {
		return value;
	}

	public void setValue(double value) {
		this.value = value;
	}

	public LocalDate getDate() {
		return date;
	}

	public void setDate(LocalDate date) {
		this.date = date;
	}
}

package cl.fatman.capital.fund;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;

import java.time.LocalDate;

@Entity
@Table(name = "foment_unit")
public class FomentUnit {

	@Id
	private String id;
	private double value;
	@Column(unique = true)
	private LocalDate date;

	public FomentUnit() {
		super();
	}

	public FomentUnit(double value, LocalDate date) {
		super();
		this.id = date.toString();
		this.value = value;
		this.date = date;
	}

	public String getId() {
		return id;
	}

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

	public double getValue() {
		return value;
	}

	public void setValue(double value) {
		this.value = value;
	}

	public LocalDate getDate() {
		return date;
	}

	public void setDate(LocalDate date) {
		this.date = date;
	}
}

Change id to String type to avoid data duplication.


package org.commcare.utils;

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

/**
 * @author Phillip Mates (pmates@dimagi.com)
 */
public class ConnectivityStatus {
    public static boolean isAirplaneModeOn(Context context) {
        if (android.os.Build.VERSION.SDK_INT > android.os.Build.VERSION_CODES.JELLY_BEAN_MR1) {
            return Settings.Global.getInt(context.getApplicationContext().getContentResolver(), Settings.Global.AIRPLANE_MODE_ON, 0) != 0;
        } else {
            return Settings.System.getInt(context.getApplicationContext().getContentResolver(), Settings.System.AIRPLANE_MODE_ON, 0) != 0;
        }
    }

    public static boolean isNetworkAvailable(Context context) {
        ConnectivityManager connectivityManager
                = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
        return activeNetworkInfo != null && activeNetworkInfo.isConnected();
    }
}

package org.commcare.utils;

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

/**
 * @author Phillip Mates (pmates@dimagi.com)
 */
public class ConnectivityStatus {
    public static boolean isAirplaneModeOn(Context context) {
        if (android.os.Build.VERSION.SDK_INT > android.os.Build.VERSION_CODES.JELLY_BEAN_MR1) {
            return Settings.Global.getInt(context.getApplicationContext().getContentResolver(), Settings.Global.AIRPLANE_MODE_ON, 0) != 0;
        } else {
            return Settings.System.getInt(context.getApplicationContext().getContentResolver(), Settings.System.AIRPLANE_MODE_ON, 0) != 0;
        }
    }

    public static boolean isNetworkAvailable(Context context) {
        ConnectivityManager connectivityManager
                = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
        return activeNetworkInfo != null && activeNetworkInfo.isConnectedOrConnecting();
    }
}

Fix for Connectivity status check


package xyz.upperlevel.uppercore.util;

import java.io.File;
import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
import java.lang.reflect.Method;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;

public final class ExternalJarUtil {
    private static final MethodHandle addPath;

    static {//void addURL(URL var1)

        ClassLoader classLoader = ClassLoader.getSystemClassLoader();
        try {
            Method method = URLClassLoader.class.getDeclaredMethod("addURL", URL.class);
            method.setAccessible(true);
            MethodHandle tmp = MethodHandles.lookup().unreflect(method);
            addPath = tmp.bindTo(classLoader);
        } catch (NoSuchMethodException e) {
            throw new IllegalStateException("Unsupported class loader: " + classLoader.getClass().getName(), e);
        } catch (IllegalAccessException e) {
            throw new IllegalStateException("Cannot get addUrl method", e);
        }
    }

    public static void addUrl(URL url) {
        try {
            addPath.invoke(url);
        } catch (Throwable t) {
            throw new RuntimeException("Error while loading external jar", t);
        }
    }

    public static void addUrl(File file) throws MalformedURLException {
        addUrl(file.toURI().toURL());
    }

    private ExternalJarUtil() {
    }
}

package xyz.upperlevel.uppercore.util;

import java.io.File;
import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
import java.lang.reflect.Method;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;

public final class ExternalJarUtil {
    private static final MethodHandle addPath;

    static {//void addURL(URL var1)
        ClassLoader classLoader = ExternalJarUtil.class.getClassLoader();
        try {
            Method method = URLClassLoader.class.getDeclaredMethod("addURL", URL.class);
            method.setAccessible(true);
            MethodHandle tmp = MethodHandles.lookup().unreflect(method);
            addPath = tmp.bindTo(classLoader);
        } catch (NoSuchMethodException e) {
            throw new IllegalStateException("Unsupported class loader: " + classLoader.getClass().getName(), e);
        } catch (IllegalAccessException e) {
            throw new IllegalStateException("Cannot get addUrl method", e);
        }
    }

    public static void addUrl(URL url) {
        try {
            addPath.invoke(url);
        } catch (Throwable t) {
            throw new RuntimeException("Error while loading external jar", t);
        }
    }

    public static void addUrl(File file) throws MalformedURLException {
        addUrl(file.toURI().toURL());
    }

    private ExternalJarUtil() {
    }
}

Add semi-compatibility with Java 9+


package org.ohdsi.webapi.util;

import org.apache.commons.lang3.RandomStringUtils;

/**
 *
 */
public final class SessionUtils {
    public static final String sessionId(){
        return RandomStringUtils.randomAlphanumeric(10);
    }
}

package org.ohdsi.webapi.util;

import org.ohdsi.sql.SqlTranslate;

/**
 *
 */
public final class SessionUtils {

    public static final String sessionId() {
        return SqlTranslate.generateSessionId();
    }
}

Use SqlTranslate to generate random since there is some additional logic involved (e.g. non-numeric initial character)


package com.bigcommerce.api.resources;

import java.util.List;

import com.bigcommerce.api.Filter;
import com.bigcommerce.api.Response;

public interface Resource {
	public List<? extends Response> listAll();
	public List<? extends Response> listAll(Filter filter);
	public Response getOne(Integer Id);
}

package com.bigcommerce.api.resources;

import java.util.List;

import com.bigcommerce.api.Filter;
import com.bigcommerce.api.Form;
import com.bigcommerce.api.Response;

public interface Resource {
	public List<? extends Response> listAll();
	public List<? extends Response> listAll(Filter filter);
	public Response getOne(Integer Id);
	public Boolean update(Integer Id, Form data);
}

Update (PUT) a resource API call is added.


package com.nincraft.ninbot.command;

import com.nincraft.ninbot.util.MessageUtils;
import lombok.val;
import net.dv8tion.jda.core.entities.Message;
import net.dv8tion.jda.core.events.message.MessageReceivedEvent;

public class DabCommand extends AbstractCommand {

    public DabCommand() {
        length = 3;
        name = "dab";
        description = "Adds all dab emojis to the last message of the user named";
    }

    @Override
    public void executeCommand(MessageReceivedEvent event) {
        val content = event.getMessage().getContent();
        if (isCommandLengthCorrect(content)) {
            val channel = event.getChannel();
            val dabUser = content.split(" ")[2].replaceFirst("@", "");
            int count = 0;
            int maxDab = 10;
            for (Message message : channel.getIterableHistory()) {
                if (message.getAuthor().getName().equalsIgnoreCase(dabUser)) {
                    dabOnMessage(message);
                    break;
                }
                if (count >= maxDab) {
                    MessageUtils.reactUnsuccessfulResponse(event.getMessage());
                    break;
                }
                count++;
            }
        } else {
            MessageUtils.reactUnsuccessfulResponse(event.getMessage());
        }
    }

    private void dabOnMessage(Message message) {
        val guild = message.getGuild();

        for (val emote : guild.getEmotes()) {
            if (emote.getName().contains("dab")) {
                MessageUtils.addReaction(message, emote);
            }
        }
    }
}

package com.nincraft.ninbot.command;

import com.nincraft.ninbot.util.MessageUtils;
import lombok.val;
import net.dv8tion.jda.core.entities.Message;
import net.dv8tion.jda.core.events.message.MessageReceivedEvent;

public class DabCommand extends AbstractCommand {

    public DabCommand() {
        length = 3;
        name = "dab";
        description = "Adds all dab emojis to the last message of the user named";
    }

    @Override
    public void executeCommand(MessageReceivedEvent event) {
        val content = event.getMessage().getContent();
        if (isCommandLengthCorrect(content)) {
            val channel = event.getChannel();
            val dabUser = content.substring(12).replaceFirst("@", "");
            int count = 0;
            int maxDab = 10;
            for (Message message : channel.getIterableHistory()) {
                if (message.getAuthor().getName().equalsIgnoreCase(dabUser)) {
                    dabOnMessage(message);
                    break;
                }
                if (count >= maxDab) {
                    MessageUtils.reactUnsuccessfulResponse(event.getMessage());
                    break;
                }
                count++;
            }
        } else {
            MessageUtils.reactUnsuccessfulResponse(event.getMessage());
        }
    }

    private void dabOnMessage(Message message) {
        val guild = message.getGuild();

        for (val emote : guild.getEmotes()) {
            if (emote.getName().contains("dab")) {
                MessageUtils.addReaction(message, emote);
            }
        }
    }

    @Override
    boolean isCommandLengthCorrect(String content) {
        return content.split(" ").length >= length;
    }
}

Fix dab command failing on users with multiple words in their name


package de.st_ddt.crazyutil.geo.block;

import org.bukkit.Location;
import org.bukkit.block.Block;

import de.st_ddt.crazyutil.geo.location.GeoLocation;

public class GeoBlock extends GeoLocation
{

	protected int material;
	protected byte data;

	// protected BlockState state;
	public GeoBlock(final Block block)
	{
		super(block.getX(), block.getY(), block.getZ());
		material = block.getTypeId();
		data = block.getData();
		// state = block.getState();
	}

	public void apply(final Location target, final boolean physics)
	{
		final Block block = target.clone().add(x, y, z).getBlock();
		block.setTypeIdAndData(material, data, physics);
	}
}

package de.st_ddt.crazyutil.geo.block;

import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.block.Block;

import de.st_ddt.crazyutil.geo.location.GeoLocation;

public class GeoBlock extends GeoLocation
{

	protected Material material;
	protected byte data;

	// protected BlockState state;
	public GeoBlock(final Block block)
	{
		super(block.getX(), block.getY(), block.getZ());
		material = block.getType();
		data = block.getData();
		// state = block.getState();
	}

	public void apply(final Location target, final boolean physics)
	{
		final Block block = target.clone().add(x, y, z).getBlock();
		block.setTypeIdAndData(material.getId(), data, physics);
	}
}

Store Material instead of materialid


package org.vaadin.viritin.layouts;

import com.vaadin.shared.ui.MarginInfo;

public class MMarginInfo extends MarginInfo {

    private static final long serialVersionUID = -3559703824387291269L;

    public MMarginInfo(boolean enabled) {
        super(enabled);
    }

    public MMarginInfo(int bitMask) {
        super(bitMask);
    }

    public MMarginInfo(boolean top, boolean right, boolean bottom, boolean left) {
        super(top, right, bottom, left);
    }

    public MMarginInfo(boolean vertical, boolean horizontal) {
        super(vertical, horizontal, vertical, horizontal);
    }

}

package org.vaadin.viritin.layouts;

import com.vaadin.shared.ui.MarginInfo;

public class MMarginInfo extends MarginInfo {

    private static final long serialVersionUID = -3559703824387291269L;

    public MMarginInfo(boolean enabled) {
        super(enabled);
    }

    @Deprecated
    public MMarginInfo(int bitMask) {
        super(bitMask);
    }

    public MMarginInfo(boolean top, boolean right, boolean bottom, boolean left) {
        super(top, right, bottom, left);
    }

    public MMarginInfo(boolean vertical, boolean horizontal) {
        super(vertical, horizontal, vertical, horizontal);
    }

}

Mark overriden deprecated method as deprected


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

import com.elmakers.mine.bukkit.action.BaseSpellAction;
import com.elmakers.mine.bukkit.api.action.CastContext;
import com.elmakers.mine.bukkit.api.block.MaterialBrush;
import com.elmakers.mine.bukkit.api.spell.SpellResult;
import org.bukkit.block.Block;

public class CheckBlockAction extends BaseSpellAction {
    @SuppressWarnings("deprecation")
    @Override
    public SpellResult perform(CastContext context) {
        MaterialBrush brush = context.getBrush();
        Block block = context.getTargetBlock();
        if (brush != null && brush.isErase()) {
            if (!context.hasBreakPermission(block)) {
                return SpellResult.CANCELLED;
            }
        } else {
            if (!context.hasBuildPermission(block)) {
                return SpellResult.CANCELLED;
            }
        }
        if (!context.isDestructible(block)) {
            return SpellResult.CANCELLED;
        }
        return SpellResult.CAST;
    }

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

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

import com.elmakers.mine.bukkit.action.BaseSpellAction;
import com.elmakers.mine.bukkit.api.action.CastContext;
import com.elmakers.mine.bukkit.api.block.MaterialBrush;
import com.elmakers.mine.bukkit.api.spell.SpellResult;
import org.bukkit.block.Block;

public class CheckBlockAction extends BaseSpellAction {
    @SuppressWarnings("deprecation")
    @Override
    public SpellResult perform(CastContext context) {
        MaterialBrush brush = context.getBrush();
        Block block = context.getTargetBlock();
        if (brush != null && brush.isErase()) {
            if (!context.hasBreakPermission(block)) {
                return SpellResult.STOP;
            }
        } else {
            if (!context.hasBuildPermission(block)) {
                return SpellResult.STOP;
            }
        }
        if (!context.isDestructible(block)) {
            return SpellResult.STOP;
        }
        return SpellResult.CAST;
    }

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

Use STOP instead of CANCELLED to cancel an action stack


package scalac.transformer.matching ;

import scalac.ast.Tree;
import scalac.util.Name;
import scalac.symtab.Symbol ;
import scalac.ast.Traverser ;

import Tree.Ident;
import Tree.Bind;

public class TestRegTraverser extends Traverser {

    boolean result;

    public TestRegTraverser() {
	super();
	result = false;
    }

    public void traverse(Tree tree) {
	switch (tree) {
	case Alternative(Tree[] ts):
	case Bind(_, _):
	    result = true;
	    break;
	default:
	    super.traverse( tree );
	}
    }

    public static boolean apply( Tree t ) {
	TestRegTraverser trt = new TestRegTraverser();
	trt.traverse( t );
	//System.err.println("TestRegTraverser says "+t+" -> "+trt.result);
	return trt.result;
    }

}

/*     ____ ____  ____ ____  ______                                     *\
**    / __// __ \/ __// __ \/ ____/    SOcos COmpiles Scala             **
**  __\_ \/ /_/ / /__/ /_/ /\_ \       (c) 2002, LAMP/EPFL              **
** /_____/\____/\___/\____/____/                                        **
**                                                                      **
** $Id$
\*                                                                      */

package scalac.transformer.matching;

import scalac.ast.*;
import scalac.util.*;
import scalac.symtab.*;
import java.util.*;

public class TestRegTraverser extends Traverser {
    boolean result = false;
	Set variables = new HashSet();

    public void traverse(Tree tree) {
    	if (!result)
			switch (tree) {
				case Alternative(Tree[] ts):
					result = true;
					break;
				case Bind(_, Tree pat):
					variables.add(tree.symbol());
					traverse(pat);
					break;
				case Ident(_):
					if (variables.contains(tree.symbol()))
						result = true;
					break;
				default:
					super.traverse( tree );
			}
    }

    public static boolean apply(Tree t) {
        TestRegTraverser trt = new TestRegTraverser();
        trt.traverse(t);
        //System.err.println("TestRegTraverser says "+t+" -> "+trt.result);
        return trt.result;
    }
}

Allow non-recursive bindings for the "old" patt...


package com.freak.asteroid.randomiser;

import android.app.Activity;
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;

import java.io.File;

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    @Override
    protected void onResume() {
        super.onResume();
        File root = new File(Environment.getExternalStorageDirectory() + "/Music");
        RandomiseThread randomiser = new RandomiseThread(root);
        randomiser.start();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}

package com.freak.asteroid.randomiser;

import android.app.Activity;
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;

import java.io.File;

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    @Override
    protected void onResume() {
        super.onResume();
        File root = new File(Environment.getExternalStorageDirectory() + "/Musique");
        RandomiseThread randomiser = new RandomiseThread(root);
        randomiser.start();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}

Fix issue on root directory


package pt.fccn.mobile.arquivo.suite;

import org.junit.runner.RunWith;
import org.junit.runners.Suite;
import org.junit.runners.Suite.SuiteClasses;

import pt.fccn.mobile.arquivo.tests.FullTextSearchTest;
import pt.fccn.mobile.arquivo.tests.URLSearchTest;
import pt.fccn.mobile.arquivo.tests.imagesearch.ImageAdvancedSearchTest;
import pt.fccn.mobile.arquivo.tests.imagesearch.ImageSearchDirectUrlTest;
import pt.fccn.mobile.arquivo.tests.imagesearch.ImageSearchTest;

/**
 *
 * @author João Nobre
 *
 */
@RunWith(Suite.class)
@SuiteClasses({ FullTextSearchTest.class, URLSearchTest.class, ImageAdvancedSearchTest.class,
		ImageSearchDirectUrlTest.class, ImageSearchTest.class })
public class TestSuite {

}

//package pt.fccn.mobile.arquivo.suite;
//
//import org.junit.runner.RunWith;
//import org.junit.runners.Suite;
//import org.junit.runners.Suite.SuiteClasses;
//
//import pt.fccn.mobile.arquivo.tests.FullTextSearchTest;
//import pt.fccn.mobile.arquivo.tests.URLSearchTest;
//import pt.fccn.mobile.arquivo.tests.imagesearch.ImageAdvancedSearchTest;
//import pt.fccn.mobile.arquivo.tests.imagesearch.ImageSearchDirectUrlTest;
//import pt.fccn.mobile.arquivo.tests.imagesearch.ImageSearchTest;
//import pt.fccn.mobile.arquivo.tests.menu.MenuAboutTest;
//import pt.fccn.mobile.arquivo.tests.menu.MenuImagesAdvancedSearchTest;
//import pt.fccn.mobile.arquivo.tests.menu.MenuImagesNewSearchTest;
//import pt.fccn.mobile.arquivo.tests.menu.MenuPagesNewAvancedSearchTest;
//import pt.fccn.mobile.arquivo.tests.menu.MenuPagesNewSearchTest;
//import pt.fccn.mobile.arquivo.tests.menu.MenuReportBugTest;
//
///**
// *
// * @author João Nobre
// *
// */
//@RunWith(Suite.class)
//@SuiteClasses({ FullTextSearchTest.class, URLSearchTest.class, ImageAdvancedSearchTest.class,
//		ImageSearchDirectUrlTest.class, ImageSearchTest.class,
//
//		MenuAboutTest.class,
//
//		MenuImagesAdvancedSearchTest.class,
//
//		MenuImagesNewSearchTest.class,
//
//		MenuPagesNewAvancedSearchTest.class,
//
//		MenuPagesNewSearchTest.class,
//
//		MenuReportBugTest.class })
//public class TestSuite {
//
//}

Remove mobile test suite because tests can be executed with wildcard.


package uk.co.alynn.games.ld30;

import java.util.List;
import uk.co.alynn.games.ld30.world.Planet;
import uk.co.alynn.games.ld30.world.Adversary;

public class SuperimposedWave extends Wave {

    private final Wave m_left;
    private final Wave m_right;

    public SuperimposedWave(Wave left, Wave right) {
        m_left = left;
        m_right = right;
    }

    @Override
    public boolean dispatch(List<Planet> planets, List<Adversary> adversaries, int tickID) {
        boolean ok = true;
        ok = ok && m_left.dispatch(planets, adversaries, tickID);
        ok = ok && m_right.dispatch(planets, adversaries, tickID);
        return ok;
    }

    @Override
    protected boolean tick(int tick) {
        throw new RuntimeException("Cannot tick a superwave");
    }
}

package uk.co.alynn.games.ld30;

import java.util.List;
import uk.co.alynn.games.ld30.world.Planet;
import uk.co.alynn.games.ld30.world.Adversary;

public class SuperimposedWave extends Wave {

    private final Wave m_left;
    private final Wave m_right;

    public SuperimposedWave(Wave left, Wave right) {
        m_left = left;
        m_right = right;
    }

    @Override
    public boolean dispatch(List<Planet> planets, List<Adversary> adversaries, int tickID) {
        boolean ok = true;
        ok = m_left.dispatch(planets, adversaries, tickID) && ok;
        ok = m_right.dispatch(planets, adversaries, tickID) && ok;
        return ok;
    }

    @Override
    protected boolean tick(int tick) {
        throw new RuntimeException("Cannot tick a superwave");
    }
}

Fix the spawning bug with autogenerated levels


package main;
/**
 * @author XYLau
 */
import edu.dynamic.dynamiz.UI.*;

public class Dynamiz {
	public static void main() {
		UI sc = new UI();
	}
}

package main;
/**
 * @author XYLau
 */
import edu.dynamic.dynamiz.UI.*;

public class Dynamiz {
	public static void main() {
		new UI();
	}
}

Update main driver using UI()


package org.bouncycastle.asn1;

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

class ConstructedOctetStream
    extends InputStream
{
    private final ASN1ObjectParser _parser;

    private boolean                _first = true;
    private InputStream            _currentStream;

    ConstructedOctetStream(
        ASN1ObjectParser parser)
    {
        _parser = parser;
    }

    public int read()
        throws IOException
    {
        if (_first)
        {
            ASN1OctetStringParser s = (ASN1OctetStringParser)_parser.readObject();

            if (s == null)
            {
                return -1;
            }

            _first = false;
            _currentStream = s.getOctetStream();
        }
        else if (_currentStream == null)
        {
            return -1;
        }

        int b = _currentStream.read();

        if (b < 0)
        {
            ASN1OctetStringParser s = (ASN1OctetStringParser)_parser.readObject();

            if (s == null)
            {
                _currentStream = null;

                return -1;
            }

            _currentStream = s.getOctetStream();

            return _currentStream.read();
        }
        else
        {
            return b;
        }
    }
}

package org.bouncycastle.asn1;

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

class ConstructedOctetStream
    extends InputStream
{
    private final ASN1ObjectParser _parser;

    private boolean                _first = true;
    private InputStream            _currentStream;

    ConstructedOctetStream(
        ASN1ObjectParser parser)
    {
        _parser = parser;
    }

    public int read(byte[] b, int off, int len) throws IOException
    {
        if (_currentStream == null)
        {
            if (!_first)
            {
                return -1;
            }

            ASN1OctetStringParser s = (ASN1OctetStringParser)_parser.readObject();

            if (s == null)
            {
                return -1;
            }

            _first = false;
            _currentStream = s.getOctetStream();
        }

        for (;;)
        {
            int numRead = _currentStream.read(b, off, len);

            if (numRead >= 0)
            {
                return numRead;
            }

            ASN1OctetStringParser aos = (ASN1OctetStringParser)_parser.readObject();

            if (aos == null)
            {
                _currentStream = null;
                return -1;
            }

            _currentStream = aos.getOctetStream();
        }
    }

    public int read()
        throws IOException
    {
        if (_currentStream == null)
        {
            if (!_first)
            {
                return -1;
            }

            ASN1OctetStringParser s = (ASN1OctetStringParser)_parser.readObject();

            if (s == null)
            {
                return -1;
            }

            _first = false;
            _currentStream = s.getOctetStream();
        }

        for (;;)
        {
            int b = _currentStream.read();

            if (b >= 0)
            {
                return b;
            }

            ASN1OctetStringParser s = (ASN1OctetStringParser)_parser.readObject();

            if (s == null)
            {
                _currentStream = null;
                return -1;
            }

            _currentStream = s.getOctetStream();
        }
    }
}

Handle empty "component" streams Implement read(byte[],int,int) as optimisation


package org.hyperledger.indy.sdk.pool;

import org.hyperledger.indy.sdk.IndyException;
import org.hyperledger.indy.sdk.IndyIntegrationTest;
import org.hyperledger.indy.sdk.utils.PoolUtils;
import org.junit.Test;

import java.io.IOException;
import java.util.concurrent.ExecutionException;

import static org.junit.Assert.assertNotNull;

public class ClosePoolTest extends IndyIntegrationTest {

	@Test
	public void testClosePoolWorks() throws IndyException, ExecutionException, InterruptedException, IOException {
		Pool pool = PoolUtils.createAndOpenPoolLedger();
		assertNotNull(pool);
		openedPools.add(pool);

		pool.closePoolLedger().get();
		openedPools.remove(pool);
	}
}

package org.hyperledger.indy.sdk.pool;

import org.hyperledger.indy.sdk.ErrorCode;
import org.hyperledger.indy.sdk.ErrorCodeMatcher;
import org.hyperledger.indy.sdk.IndyException;
import org.hyperledger.indy.sdk.IndyIntegrationTest;
import org.hyperledger.indy.sdk.utils.PoolUtils;
import org.junit.Test;

import java.io.IOException;
import java.util.concurrent.ExecutionException;

import static org.junit.Assert.assertNotNull;

public class ClosePoolTest extends IndyIntegrationTest {

	@Test
	public void testClosePoolWorks() throws IndyException, ExecutionException, InterruptedException, IOException {
		Pool pool = PoolUtils.createAndOpenPoolLedger();
		assertNotNull(pool);
		openedPools.add(pool);

		pool.closePoolLedger().get();
		openedPools.remove(pool);
	}

	@Test
	public void testClosePoolWorksForTwice() throws IndyException, ExecutionException, InterruptedException, IOException {
		thrown.expectCause(new ErrorCodeMatcher(ErrorCode.PoolLedgerInvalidPoolHandle));

		Pool pool = PoolUtils.createAndOpenPoolLedger();
		assertNotNull(pool);
		openedPools.add(pool);

		pool.closePoolLedger().get();
		openedPools.remove(pool);
		pool.closePoolLedger().get();
	}

	@Test
	public void testClosePoolWorksForReopenAfterClose() throws IndyException, ExecutionException, InterruptedException, IOException {
		String poolName = PoolUtils.createPoolLedgerConfig();

		Pool pool = Pool.openPoolLedger(poolName, null).get();
		assertNotNull(pool);
		openedPools.add(pool);

		pool.closePoolLedger().get();

		Pool.openPoolLedger(poolName, null).get();
	}
}

Add more tests for ClosePool.


package net.bettyluke.tracinstant.data;

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;

import net.bettyluke.tracinstant.prefs.SiteSettings;

public final class AuthenticatedHttpRequester {
    private AuthenticatedHttpRequester() {}

    public static InputStream getInputStream(SiteSettings settings, URL url) throws IOException {
        URLConnection uc = url.openConnection();

        if (!settings.getUsername().isEmpty()) {
            String userpass = settings.getUsername() + ":" + settings.getPassword();
            String basicAuth = "Basic " + javax.xml.bind.DatatypeConverter.printBase64Binary(
                    userpass.getBytes());
            uc.setRequestProperty ("Authorization", basicAuth);
        }

        return uc.getInputStream();
    }
}

package net.bettyluke.tracinstant.data;

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;

import net.bettyluke.tracinstant.prefs.SiteSettings;

public final class AuthenticatedHttpRequester {
    private AuthenticatedHttpRequester() {}

    public static InputStream getInputStream(SiteSettings settings, URL url) throws IOException {
        URLConnection uc = url.openConnection();

        if (!settings.getUsername().isEmpty()) {
            String userpass = settings.getUsername() + ":" + settings.getPassword();
            String basicAuth = "Basic " +
                    javax.xml.bind.DatatypeConverter.printBase64Binary(userpass.getBytes());

// Note: change to the following when moving to Java 8, as the above will stop working in Java 9.
//                    Base64.getEncoder().encodeToString(userpass.getBytes());
            uc.setRequestProperty ("Authorization", basicAuth);
        }

        return uc.getInputStream();
    }
}

Comment how to port to new Base64 encoder in Java 8 and 9


package io.jasonsparc.chemistry.util;

import android.support.annotation.AnyRes;
import android.support.v7.widget.RecyclerView;

import io.jasonsparc.chemistry.ViewType;

/**
 * Created by jason on 11/07/2016.
 */
@UtilityClass
public final class ViewTypes {

	/**
	 * An invalid view type, disguised to be valid. The value is equivalent to
	 * {@link RecyclerView#INVALID_TYPE}.
	 * <p>
	 * This can be used in situations where an invalid view type is actually intended but is
	 * restricted to use only valid view types. This variable however disregards such restrictions.
	 */
	@ViewType
	@AnyRes
	public static final int INVALID = invalid();

	public static void validateArgument(int viewType) {
		if (viewType < ValidRes.MIN_RES_ID) {
			throw new IllegalArgumentException("Invalid view type! Must be a resource identifier.");
		}
	}

	public static void validateForState(int viewType) {
		if (viewType < ValidRes.MIN_RES_ID) {
			throw new IllegalStateException("Invalid view type! Must be a resource identifier.");
		}
	}

	// Internals

	@SuppressWarnings("Range")
	@ViewType
	@AnyRes
	private static int invalid() {
		return RecyclerView.INVALID_TYPE;
	}
}

package io.jasonsparc.chemistry.util;

import android.support.annotation.AnyRes;
import android.support.v7.widget.RecyclerView;

import io.jasonsparc.chemistry.ViewType;

/**
 * Created by jason on 11/07/2016.
 */
@UtilityClass
public final class ViewTypes {

	/**
	 * An invalid view type, disguised to be valid. The value is equivalent to
	 * {@link RecyclerView#INVALID_TYPE}.
	 * <p>
	 * This can be used in situations where an invalid view type is actually intended but is
	 * restricted to use only valid view types. This variable however disregards such restrictions.
	 */
	@ViewType
	@AnyRes
	public static final int INVALID = invalid();

	public static boolean isValid(int viewType) {
		return viewType >= ValidRes.MIN_RES_ID;
	}

	public static void validateArgument(int viewType) {
		if (viewType < ValidRes.MIN_RES_ID) {
			throw new IllegalArgumentException("Invalid view type! Must be a resource identifier.");
		}
	}

	public static void validateForState(int viewType) {
		if (viewType < ValidRes.MIN_RES_ID) {
			throw new IllegalStateException("Invalid view type! Must be a resource identifier.");
		}
	}

	// Internals

	@SuppressWarnings("Range")
	@ViewType
	@AnyRes
	private static int invalid() {
		return RecyclerView.INVALID_TYPE;
	}
}

Add a utility for checking valid view types


package org.ehcache.build.conventions;

import org.gradle.api.Plugin;
import org.gradle.api.Project;
import org.gradle.api.tasks.testing.Test;
import org.gradle.testing.jacoco.plugins.JacocoPlugin;
import org.gradle.testing.jacoco.plugins.JacocoTaskExtension;
import org.gradle.testing.jacoco.tasks.JacocoReport;

public class JacocoConvention implements Plugin<Project> {

  @Override
  public void apply(Project project) {
    project.getPlugins().apply(JacocoPlugin.class);

    project.getTasks().withType(JacocoReport.class).configureEach(jacocoReport -> {
      jacocoReport.getReports().configureEach(report -> {
        report.getRequired().set(false);
      });
    });

    project.getTasks().withType(Test.class).configureEach(test -> {
      test.getExtensions().configure(JacocoTaskExtension.class, jacoco -> {
        jacoco.getExcludes().add("org.terracotta.tripwire.*");
      });
    });
  }
}

package org.ehcache.build.conventions;

import org.gradle.api.Plugin;
import org.gradle.api.Project;
import org.gradle.api.tasks.testing.Test;
import org.gradle.testing.jacoco.plugins.JacocoPlugin;
import org.gradle.testing.jacoco.plugins.JacocoPluginExtension;
import org.gradle.testing.jacoco.plugins.JacocoTaskExtension;
import org.gradle.testing.jacoco.tasks.JacocoReport;

public class JacocoConvention implements Plugin<Project> {

  @Override
  public void apply(Project project) {
    project.getPlugins().apply(JacocoPlugin.class);

    project.getExtensions().configure(JacocoPluginExtension.class, jacoco -> {
      jacoco.setToolVersion("0.8.8");
    });

    project.getTasks().withType(JacocoReport.class).configureEach(jacocoReport -> {
      jacocoReport.getReports().configureEach(report -> {
        report.getRequired().set(false);
      });
    });

    project.getTasks().withType(Test.class).configureEach(test -> {
      test.getExtensions().configure(JacocoTaskExtension.class, jacoco -> {
        jacoco.getExcludes().add("org.terracotta.tripwire.*");
      });
    });
  }
}

Upgrade to Jacoco 0.8.8 for Java 18 compatibility.


// ========================================================================
// Copyright 2010 NEXCOM Systems
// ------------------------------------------------------------------------
// 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.cipango.diameter.router;

import java.util.Hashtable;
import java.util.Map;

import org.cipango.diameter.node.DiameterRequest;
import org.cipango.diameter.node.Node;
import org.cipango.diameter.node.Peer;

public class DefaultRouter implements DiameterRouter
{

	private Map<String, Peer> _peers = new Hashtable<String, Peer>();

	public Peer getRoute(DiameterRequest request)
	{
		return _peers.get(request.getDestinationHost());
	}

	public void peerAdded(Peer peer)
	{
		_peers.put(peer.getHost(), peer);
	}

	public void peerRemoved(Peer peer)
	{
		_peers.remove(peer.getHost());
	}

}

// ========================================================================
// Copyright 2010 NEXCOM Systems
// ------------------------------------------------------------------------
// 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.cipango.diameter.router;

import java.util.Hashtable;
import java.util.Map;

import org.cipango.diameter.node.DiameterRequest;
import org.cipango.diameter.node.Peer;

public class DefaultRouter implements DiameterRouter
{

	private Map<String, Peer> _peers = new Hashtable<String, Peer>();

	public Peer getRoute(DiameterRequest request)
	{
		if (request.getDestinationHost() == null)
			return null;
		return _peers.get(request.getDestinationHost());
	}

	public void peerAdded(Peer peer)
	{
		_peers.put(peer.getHost(), peer);
	}

	public void peerRemoved(Peer peer)
	{
		_peers.remove(peer.getHost());
	}

}

Fix CIPANGO-99: Creating a DiameterServletRequest without specifying the destinationhost field leads to a null pointer exception when sending a the request


/*
 * Hibernate Validator, declare and validate application constraints
 *
 * License: Apache License, Version 2.0
 * See the license.txt file in the root directory or <http://www.apache.org/licenses/LICENSE-2.0>.
 */

// $Id:$
package org.hibernate.validator.constraints;

/**
 * The Enum {@code CompositionType} which is used as argument to the annotation {@code ConstraintComposition}.
 */
public enum CompositionType {
	/**
	 * Used to indicate the disjunction of all constraints it is applied to.
	 */
	OR,

	/**
	 * Used to indicate the conjunction of all the constraints it is applied to.
	 */
	AND,

	/**
	 * ALL_FALSE is a generalisation of the usual NOT operator, which is applied to
	 * a list of conditions rather than just one element.
	 * When the annotation it is used on is composed of a single constraint annotation, then it is equivalent to NOT.
	 */
	ALL_FALSE
}

/*
 * Hibernate Validator, declare and validate application constraints
 *
 * License: Apache License, Version 2.0
 * See the license.txt file in the root directory or <http://www.apache.org/licenses/LICENSE-2.0>.
 */

package org.hibernate.validator.constraints;

/**
 * The Enum {@code CompositionType} which is used as argument to the annotation {@code ConstraintComposition}.
 */
public enum CompositionType {
	/**
	 * Used to indicate the disjunction of all constraints it is applied to.
	 */
	OR,

	/**
	 * Used to indicate the conjunction of all the constraints it is applied to.
	 */
	AND,

	/**
	 * ALL_FALSE is a generalisation of the usual NOT operator, which is applied to
	 * a list of conditions rather than just one element.
	 * When the annotation it is used on is composed of a single constraint annotation, then it is equivalent to NOT.
	 */
	ALL_FALSE
}

Remove a remaining $Id:$ marker


/**
 * Copyright 2005 The Apache Software Foundation
 *
 * 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.hadoop.mapred;

/*******************************
 * Some handy constants
 *
 * @author Mike Cafarella
 *******************************/
interface MRConstants {
    //
    // Timeouts, constants
    //
    public static final long HEARTBEAT_INTERVAL = 3 * 1000;
    public static final long TASKTRACKER_EXPIRY_INTERVAL = 60 * 1000;

    //
    // Result codes
    //
    public static int SUCCESS = 0;
    public static int FILE_NOT_FOUND = -1;
}

/**
 * Copyright 2005 The Apache Software Foundation
 *
 * 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.hadoop.mapred;

/*******************************
 * Some handy constants
 *
 * @author Mike Cafarella
 *******************************/
interface MRConstants {
    //
    // Timeouts, constants
    //
    public static final long HEARTBEAT_INTERVAL = 10 * 1000;
    public static final long TASKTRACKER_EXPIRY_INTERVAL = 10 * 60 * 1000;

    //
    // Result codes
    //
    public static int SUCCESS = 0;
    public static int FILE_NOT_FOUND = -1;
}

Increase some intervals to further reduce stress on the jobtracker.


package com.faforever.client.fx.contextmenu;

import com.faforever.client.domain.PlayerBean;
import com.faforever.client.i18n.I18n;
import com.faforever.client.player.PlayerInfoWindowController;
import com.faforever.client.player.SocialStatus;
import com.faforever.client.theme.UiService;
import com.faforever.client.util.Assert;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

@Component
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
@RequiredArgsConstructor
public class ShowPlayerInfoMenuItem extends AbstractMenuItem<PlayerBean> {

  private final I18n i18n;
  private final UiService uiService;

  @Override
  protected void onClicked() {
    Assert.checkNullIllegalState(object, "no player has been set");
    PlayerInfoWindowController controller = uiService.loadFxml("theme/user_info_window.fxml");
    controller.setPlayer(object);
    controller.setOwnerWindow(getParentPopup().getOwnerWindow());
    controller.show();
  }

  @Override
  protected boolean isItemVisible() {
    return object != null && object.getSocialStatus() != SocialStatus.SELF;
  }

  @Override
  protected String getItemText() {
    return i18n.get("chat.userContext.userInfo");
  }
}

package com.faforever.client.fx.contextmenu;

import com.faforever.client.domain.PlayerBean;
import com.faforever.client.i18n.I18n;
import com.faforever.client.player.PlayerInfoWindowController;
import com.faforever.client.theme.UiService;
import com.faforever.client.util.Assert;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

@Component
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
@RequiredArgsConstructor
public class ShowPlayerInfoMenuItem extends AbstractMenuItem<PlayerBean> {

  private final I18n i18n;
  private final UiService uiService;

  @Override
  protected void onClicked() {
    Assert.checkNullIllegalState(object, "no player has been set");
    PlayerInfoWindowController controller = uiService.loadFxml("theme/user_info_window.fxml");
    controller.setPlayer(object);
    controller.setOwnerWindow(getParentPopup().getOwnerWindow());
    controller.show();
  }

  @Override
  protected boolean isItemVisible() {
    return object != null;
  }

  @Override
  protected String getItemText() {
    return i18n.get("chat.userContext.userInfo");
  }
}

Allow players to see their own stats


package top.quantic.sentry.discord.core;

import joptsimple.OptionSet;
import sx.blah.discord.handle.obj.IMessage;

public class CommandContext {

    private IMessage message;
    private String prefix;
    private Command command;
    private String[] args;
    private OptionSet optionSet;

    public IMessage getMessage() {
        return message;
    }

    public void setMessage(IMessage message) {
        this.message = message;
    }

    public String getPrefix() {
        return prefix;
    }

    public void setPrefix(String prefix) {
        this.prefix = prefix;
    }

    public Command getCommand() {
        return command;
    }

    public void setCommand(Command command) {
        this.command = command;
    }

    public String[] getArgs() {
        return args;
    }

    public void setArgs(String[] args) {
        this.args = args;
    }

    public OptionSet getOptionSet() {
        return optionSet;
    }

    public void setOptionSet(OptionSet optionSet) {
        this.optionSet = optionSet;
    }
}

package top.quantic.sentry.discord.core;

import joptsimple.OptionSet;
import sx.blah.discord.handle.obj.IMessage;

public class CommandContext {

    private IMessage message;
    private String prefix;
    private Command command;
    private String[] args;
    private OptionSet optionSet;

    public IMessage getMessage() {
        return message;
    }

    public void setMessage(IMessage message) {
        this.message = message;
    }

    public String getPrefix() {
        return prefix;
    }

    public void setPrefix(String prefix) {
        this.prefix = prefix;
    }

    public Command getCommand() {
        return command;
    }

    public void setCommand(Command command) {
        this.command = command;
    }

    public String[] getArgs() {
        return args;
    }

    public void setArgs(String[] args) {
        this.args = args;
    }

    public OptionSet getOptionSet() {
        return optionSet;
    }

    public void setOptionSet(OptionSet optionSet) {
        this.optionSet = optionSet;
    }

    public String getContentAfterPrefix() {
        if (message == null || prefix == null) {
            return null;
        }
        String content = message.getContent();
        if (!content.contains(prefix)) {
            return content;
        }
        return content.substring(prefix.length());
    }
}

Add method to get a command's content after the prefix


package revert.MainScene.notifications;

/**
 * Notification type of the game's scoring mechanics
 *
 * @author nhydock
 */
public class WorldNotification {

	private static final String SCORE_FMT = "$\n%d";
	private static final String TIME_FMT = "%02d";

	public final String score;
	public final String time;

	public WorldNotification(final int score, final int time)
	{
		this.score = String.format(SCORE_FMT, score);
		this.time = String.format(TIME_FMT, time);
	}

}

package revert.MainScene.notifications;

/**
 * Notification type of the game's scoring mechanics
 *
 * @author nhydock
 */
public class WorldNotification {

	private static final String SCORE_FMT = "$\n%d";
	private static final String TIME_FMT = "%02d";

	public final String score;
	public final String time;

	public WorldNotification(final int score, final int time)
	{
		this.score = String.format(SCORE_FMT, score);
		//make sure to convert time from ms to sec
		this.time = String.format(TIME_FMT, (int)(time/1000));
	}

}

Fix time display to be in seconds instead of ms


package net.minecraftforge.common;

import java.util.UUID;

import net.minecraft.src.*;
import net.minecraftforge.event.*;
import net.minecraftforge.event.entity.*;
import net.minecraftforge.event.world.WorldEvent;

public class ForgeInternalHandler
{
    @ForgeSubscribe(priority = EventPriority.HIGHEST)
    public void onEntityJoinWorld(EntityJoinWorldEvent event)
    {
        if (!event.world.isRemote)
        {
            if (event.entity.getPersistentID() == null)
            {
                event.entity.generatePersistentID();
            }
            else
            {
                ForgeChunkManager.loadEntity(event.entity);
            }
        }
        Entity entity = event.entity;
        if (entity instanceof EntityItem)
        {
            ItemStack item = ((EntityItem)entity).item;
            if (item != null && item.getItem().hasCustomEntity(item))
            {
                Entity newEntity = item.getItem().createEntity(event.world, entity, item);
                if (newEntity != null)
                {
                    entity.setDead();
                    event.setCanceled(true);
                    event.world.spawnEntityInWorld(newEntity);
                }
            }
        }
    }

    @ForgeSubscribe(priority = EventPriority.HIGHEST)
    public void onDimensionLoad(WorldEvent.Load event)
    {
        ForgeChunkManager.loadWorld(event.world);
    }

    @ForgeSubscribe(priority = EventPriority.HIGHEST)
    public void onDimensionSave(WorldEvent.Save event)
    {
    	ForgeChunkManager.saveWorld(event.world);
    }
}

package net.minecraftforge.common;

import java.util.UUID;

import net.minecraft.src.*;
import net.minecraftforge.event.*;
import net.minecraftforge.event.entity.*;
import net.minecraftforge.event.world.WorldEvent;

public class ForgeInternalHandler
{
    @ForgeSubscribe(priority = EventPriority.HIGHEST)
    public void onEntityJoinWorld(EntityJoinWorldEvent event)
    {
        if (!event.world.isRemote)
        {
            if (event.entity.getPersistentID() == null)
            {
                event.entity.generatePersistentID();
            }
            else
            {
                ForgeChunkManager.loadEntity(event.entity);
            }
        }
        Entity entity = event.entity;
        if (entity.getClass().equals(EntityItem.class))
        {
            ItemStack item = ((EntityItem)entity).item;
            if (item != null && item.getItem().hasCustomEntity(item))
            {
                Entity newEntity = item.getItem().createEntity(event.world, entity, item);
                if (newEntity != null)
                {
                    entity.setDead();
                    event.setCanceled(true);
                    event.world.spawnEntityInWorld(newEntity);
                }
            }
        }
    }

    @ForgeSubscribe(priority = EventPriority.HIGHEST)
    public void onDimensionLoad(WorldEvent.Load event)
    {
        ForgeChunkManager.loadWorld(event.world);
    }

    @ForgeSubscribe(priority = EventPriority.HIGHEST)
    public void onDimensionSave(WorldEvent.Save event)
    {
    	ForgeChunkManager.saveWorld(event.world);
    }
}

Make Item.createEntity only call when its specifically a EntityItem, not a subclass of it.


package io.induct.yle;

import com.google.inject.Guice;
import com.google.inject.Injector;
import io.induct.daniel.DanielModule;
import io.induct.yle.ioc.YleApiModule;
import org.junit.BeforeClass;

import java.io.ByteArrayInputStream;
import java.io.InputStream;

/**
 * @since 2015-05-09
 */
public abstract class YleApiTestingBase {

    protected static Injector injector;

    @BeforeClass
    public static void preTestingSetUp() throws Exception {
        injector = Guice.createInjector(
                new DanielModule(),
                new YleApiModule());
    }

    protected InputStream asStream(String s) {
        return new ByteArrayInputStream(s.getBytes());
    }
}

package io.induct.yle;

import com.google.inject.Guice;
import com.google.inject.Injector;
import io.induct.daniel.DanielModule;
import io.induct.yle.ioc.YleApiModule;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import sun.net.www.http.HttpClient;

import java.io.ByteArrayInputStream;
import java.io.InputStream;

/**
 * @since 2015-05-09
 */
public abstract class YleApiTestingBase {

    protected static Injector injector;

    @BeforeClass
    public static void preTestingSetUp() throws Exception {
        injector = Guice.createInjector(
                new DanielModule(),
                new YleApiModule());
    }

    @AfterClass
    public static void postTestingSetup() throws Exception {
        ((AutoCloseable) injector.getInstance(HttpClient.class)).close();
    }

    protected InputStream asStream(String s) {
        return new ByteArrayInputStream(s.getBytes());
    }
}

Clean up HttpClient after tests.


import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

/**
 * Created by smurphy on 2/24/15.
 */
public class RampOptionsPanel extends OptionsPanel {
    JComboBox drop;
    RampSimulator rs;

    public RampOptionsPanel(RampSimulator rs){

        this.rs = rs;

        this.setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));

        JLabel title = new JLabel("Select a variable to graph:");
        title.setVisible(true);
        this.add(title);

        String[] sims = {"Kinetic Energy", "Potential Energy"};
        drop = new JComboBox<String>(sims);
        drop.setVisible(true);
        this.add(drop);

        JButton selected = new JButton("Submit");
        selected.setVisible(true);
        this.add(selected);

        selected.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                //Execute when button is pressed
                //System.out.println("You clicked the button");
                startSim();
            }
        });
    }

    private void startSim(){
        int k = drop.getSelectedIndex();
        System.out.println(k);
        //rs.startRecording(drop.get); To implement
    }
}

Test commit of the Ramp Options Panel


package com.jakewharton.trakt.entities;

import com.jakewharton.trakt.TraktEntity;

public class Response implements TraktEntity {
    private static final long serialVersionUID = 5921890886906816035L;

    public String status; //TODO: enum
    public String message;
    public String error;

    /** @deprecated Use {@link #status} */
    @Deprecated
    public String getStatus() {
        return this.status;
    }
    /** @deprecated Use {@link #message} */
    @Deprecated
    public String getMessage() {
        return this.message;
    }
    /** @deprecated Use {@link #error} */
    @Deprecated
    public String getError() {
        return this.error;
    }
}

package com.jakewharton.trakt.entities;

import com.jakewharton.trakt.TraktEntity;

public class Response implements TraktEntity {
    private static final long serialVersionUID = 5921890886906816035L;

    public String status; //TODO: enum
    public String message;
    public String error;
    public int wait;

    /** @deprecated Use {@link #status} */
    @Deprecated
    public String getStatus() {
        return this.status;
    }
    /** @deprecated Use {@link #message} */
    @Deprecated
    public String getMessage() {
        return this.message;
    }
    /** @deprecated Use {@link #error} */
    @Deprecated
    public String getError() {
        return this.error;
    }
}

Add wait field. This is used when checking in returns a failure. It specifies the time until the next possible check in.


package gwt.material.design.client.base.mixin;

/*
 * #%L
 * GwtBootstrap3
 * %%
 * Copyright (C) 2013 GwtBootstrap3
 * %%
 * 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%
 */

import com.google.gwt.safehtml.shared.SafeHtmlUtils;
import com.google.gwt.user.client.ui.UIObject;

/**
 * @author Ben Dol
 */
public class TextMixin<T extends UIObject> extends AbstractMixin<T> {

    public TextMixin(final T uiObject) {
        super(uiObject);
    }

    public String getText() {
        return uiObject.getElement().getInnerText();
    }

    public void setText(final String text) {
        uiObject.getElement().setInnerText(text != null ? SafeHtmlUtils.htmlEscape(text) : "");
    }
}

package gwt.material.design.client.base.mixin;

/*
 * #%L
 * GwtBootstrap3
 * %%
 * Copyright (C) 2013 GwtBootstrap3
 * %%
 * 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%
 */

import com.google.gwt.safehtml.shared.SafeHtmlUtils;
import com.google.gwt.user.client.ui.UIObject;

/**
 * @author Ben Dol
 */
public class TextMixin<T extends UIObject> extends AbstractMixin<T> {

    public TextMixin(final T uiObject) {
        super(uiObject);
    }

    public String getText() {
        return uiObject.getElement().getInnerText();
    }

    public void setText(final String text) {
        uiObject.getElement().setInnerText(text);
    }
}

Use setInnerText only which already solves XSS Attacks (Avoid duplication)


package specs;

import static com.greghaskins.spectrum.Spectrum.beforeEach;
import static com.greghaskins.spectrum.Spectrum.describe;
import static com.greghaskins.spectrum.Spectrum.it;
import static junit.framework.TestCase.assertNull;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;

import com.greghaskins.spectrum.Spectrum;
import com.greghaskins.spectrum.Variable;

import org.junit.runner.RunWith;

@RunWith(Spectrum.class)
public class VariableSpecs {
  {

    describe("The Variable convenience wrapper", () -> {

      final Variable<Integer> counter = new Variable<>();

      beforeEach(() -> {
        counter.set(0);
      });

      beforeEach(() -> {
        counter.set(counter.get() + 1);
      });

      it("lets you work around Java's requirement that closures only use `final` variables", () -> {
        counter.set(counter.get() + 1);
        assertThat(counter.get(), is(2));
      });

      it("can optionally have an initial value set", () -> {
        final Variable<String> name = new Variable<>("Alice");
        assertThat(name.get(), is("Alice"));
      });

      it("has a null value if not specified", () -> {
        final Variable<String> name = new Variable<>();
        assertNull(name.get());
      });

    });

  }
}

package specs;

import static com.greghaskins.spectrum.Spectrum.beforeAll;
import static com.greghaskins.spectrum.Spectrum.beforeEach;
import static com.greghaskins.spectrum.Spectrum.describe;
import static com.greghaskins.spectrum.Spectrum.it;
import static junit.framework.TestCase.assertNull;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;

import com.greghaskins.spectrum.Spectrum;
import com.greghaskins.spectrum.Variable;

import org.junit.runner.RunWith;

@RunWith(Spectrum.class)
public class VariableSpecs {
  {

    describe("The Variable convenience wrapper", () -> {

      final Variable<Integer> counter = new Variable<>();

      beforeAll(() -> {
        counter.set(0);
      });

      beforeEach(() -> {
        final int previousValue = counter.get();
        counter.set(previousValue + 1);
      });

      it("lets you work around Java's requirement that closures only use `final` variables", () -> {
        assertThat(counter.get(), is(1));
      });

      it("can share values across scopes, so use it carefully", () -> {
        assertThat(counter.get(), is(2));
      });

      it("can optionally have an initial value set", () -> {
        final Variable<String> name = new Variable<>("Alice");
        assertThat(name.get(), is("Alice"));
      });

      it("has a null value if not specified", () -> {
        final Variable<String> name = new Variable<>();
        assertNull(name.get());
      });

    });

  }
}

Clarify specs for Variable helper


package rsc.publisher;

import java.util.Objects;

import org.reactivestreams.Subscriber;

import rsc.flow.Cancellation;
import rsc.scheduler.Scheduler;
import rsc.util.EmptySubscription;
import rsc.util.ExceptionHelper;

/**
 * Publisher indicating a scalar/empty source that subscribes on the specified scheduler.
 *
 * @param <T>
 */
final class PublisherSubscribeOnValue<T> extends Px<T> {

    final T value;

    final Scheduler scheduler;

    public PublisherSubscribeOnValue(T value,
            Scheduler scheduler) {
        this.value = value;
        this.scheduler = Objects.requireNonNull(scheduler, "scheduler");
    }

    @Override
    public void subscribe(Subscriber<? super T> s) {
        Scheduler.Worker worker;

        try {
            worker = scheduler.createWorker();
        } catch (Throwable e) {
            ExceptionHelper.throwIfFatal(e);
            EmptySubscription.error(s, e);
            return;
        }

        if (worker == null) {
            EmptySubscription.error(s, new NullPointerException("The scheduler returned a null Function"));
            return;
        }

        T v = value;
        if (v == null) {
            PublisherSubscribeOn.ScheduledEmpty parent = new PublisherSubscribeOn.ScheduledEmpty(s);
            s.onSubscribe(parent);
            Cancellation f = scheduler.schedule(parent);
            parent.setFuture(f);
        } else {
            s.onSubscribe(new PublisherSubscribeOn.ScheduledScalar<>(s, v, scheduler));
        }
    }
}

package rsc.publisher;

import java.util.Objects;

import org.reactivestreams.Subscriber;

import rsc.flow.Cancellation;
import rsc.scheduler.Scheduler;

/**
 * Publisher indicating a scalar/empty source that subscribes on the specified scheduler.
 *
 * @param <T>
 */
final class PublisherSubscribeOnValue<T> extends Px<T> {

    final T value;

    final Scheduler scheduler;

    public PublisherSubscribeOnValue(T value,
            Scheduler scheduler) {
        this.value = value;
        this.scheduler = Objects.requireNonNull(scheduler, "scheduler");
    }

    @Override
    public void subscribe(Subscriber<? super T> s) {
        T v = value;
        if (v == null) {
            PublisherSubscribeOn.ScheduledEmpty parent = new PublisherSubscribeOn.ScheduledEmpty(s);
            s.onSubscribe(parent);
            Cancellation f = scheduler.schedule(parent);
            parent.setFuture(f);
        } else {
            s.onSubscribe(new PublisherSubscribeOn.ScheduledScalar<>(s, v, scheduler));
        }
    }
}

Remove unused worker (and thus a worker leak)


package us.crast.mondochest.persist;

import org.bukkit.Location;
import org.bukkit.entity.Player;

public class PlayerState {
	private Location lastClickedMaster;
	private State state = State.NORMAL;
	public PlayerState(Player player) {}

	/* Getters/Setters */
	public Location getLastClickedMaster() {
		return lastClickedMaster;
	}
	public void setLastClickedMaster(Location lastClickedMaster) {
		this.lastClickedMaster = lastClickedMaster;
	}

	public boolean isManagingChest() {
	    return this.state == State.MANAGING_CHEST;
	}

	public void setManagingChest() {
	    this.state = State.MANAGING_CHEST;
	}

	public void setNormalMode() {
	    this.state = State.NORMAL;
	}

	enum State {
	    NORMAL,
	    MANAGING_CHEST;
	}
}

package us.crast.mondochest.persist;

import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.entity.Player;
import org.bukkit.util.Vector;

public class PlayerState {
	private String lastClickedWorld;
	private Vector lastClickedVector;

	private State state = State.NORMAL;
	public PlayerState(Player player) {}

	/* Getters/Setters */
	public Location getLastClickedMaster() {
		return new Location(
		    Bukkit.getWorld(lastClickedWorld),
		    lastClickedVector.getX(),
		    lastClickedVector.getY(),
		    lastClickedVector.getZ()
		);
	}

	public void setLastClickedMaster(Location lastClickedMaster) {
		this.lastClickedWorld = lastClickedMaster.getWorld().toString();
		this.lastClickedVector = lastClickedMaster.toVector();
	}

	public boolean isManagingChest() {
	    return this.state == State.MANAGING_CHEST;
	}

	public void setManagingChest() {
	    this.state = State.MANAGING_CHEST;
	}

	public void setNormalMode() {
	    this.state = State.NORMAL;
	}

	enum State {
	    NORMAL,
	    MANAGING_CHEST;
	}
}

Clean up possible World memory leak in storing locations.


/*
 ** 2013 July 01
 **
 ** The author disclaims copyright to this source code.  In place of
 ** a legal notice, here is a blessing:
 **    May you do good and not evil.
 **    May you find forgiveness for yourself and forgive others.
 **    May you share freely, never taking more than you give.
 */
package info.ata4.unity.cli.extract;

import info.ata4.unity.serdes.UnityObject;
import java.io.IOException;

/**
 *
 * @author Nico Bergemann <barracuda415 at yahoo.de>
 */
public class TextAssetHandler extends AssetExtractHandler {

    public TextAssetHandler(String ext) {
        setOutputFileExtension(ext);
    }

    @Override
    public void extract(UnityObject obj) throws IOException {
        String name = obj.getValue("m_Name");
        String script = obj.getValue("m_Script");

        setOutputFileName(name);
        writeData(script.getBytes("UTF8"));
    }
}

/*
 ** 2013 July 01
 **
 ** The author disclaims copyright to this source code.  In place of
 ** a legal notice, here is a blessing:
 **    May you do good and not evil.
 **    May you find forgiveness for yourself and forgive others.
 **    May you share freely, never taking more than you give.
 */
package info.ata4.unity.cli.extract;

import info.ata4.unity.serdes.UnityObject;
import info.ata4.unity.serdes.UnityString;
import java.io.IOException;

/**
 *
 * @author Nico Bergemann <barracuda415 at yahoo.de>
 */
public class TextAssetHandler extends AssetExtractHandler {

    public TextAssetHandler(String ext) {
        setOutputFileExtension(ext);
    }

    @Override
    public void extract(UnityObject obj) throws IOException {
        String name = obj.getValue("m_Name");
        UnityString script = obj.getValue("m_Script", false);

        setOutputFileName(name);
        writeData(script.getRaw());
    }
}

Write strings directly and don't convert them to UTF-8


package sg.ncl.testbed_interface;

import org.springframework.context.annotation.Configuration;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.transaction.annotation.EnableTransactionManagement;

/**
 * @author Christopher Zhong
 */
@Configuration
@EnableJpaRepositories
@EnableTransactionManagement
public class JpaConfig {
}

package sg.ncl.testbed_interface;

import org.springframework.context.annotation.Configuration;
import org.springframework.data.jpa.repository.config.EnableJpaAuditing;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.transaction.annotation.EnableTransactionManagement;

/**
 * @author Christopher Zhong
 */
@Configuration
@EnableJpaRepositories
@EnableJpaAuditing
@EnableTransactionManagement
public class JpaConfig {
}

Enable auditing of entities (DEV-15)


package org.realityforge.replicant.server.transport;

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.JsonTypeName;

@JsonAutoDetect( fieldVisibility = JsonAutoDetect.Visibility.ANY, getterVisibility = JsonAutoDetect.Visibility.NONE, setterVisibility = JsonAutoDetect.Visibility.NONE, isGetterVisibility = JsonAutoDetect.Visibility.NONE, creatorVisibility = JsonAutoDetect.Visibility.NONE )
@JsonTypeName( "testFilter" )
public class TestFilter
{
  private int myField;

  public TestFilter()
  {
  }

  public TestFilter( final int myField )
  {
    this.myField = myField;
  }

  public int getMyField()
  {
    return myField;
  }
}

package org.realityforge.replicant.server.transport;

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.JsonTypeName;
import java.io.Serializable;

@JsonAutoDetect( fieldVisibility = JsonAutoDetect.Visibility.ANY, getterVisibility = JsonAutoDetect.Visibility.NONE, setterVisibility = JsonAutoDetect.Visibility.NONE, isGetterVisibility = JsonAutoDetect.Visibility.NONE, creatorVisibility = JsonAutoDetect.Visibility.NONE )
@JsonTypeName( "testFilter" )
public class TestFilter
  implements Serializable
{
  private int myField;

  public TestFilter()
  {
  }

  public TestFilter( final int myField )
  {
    this.myField = myField;
  }

  public int getMyField()
  {
    return myField;
  }
}

Make class serializable to make testing easier


package com.attehuhtakangas.navigationbar;

import com.facebook.react.ReactPackage;
import com.facebook.react.bridge.JavaScriptModule;
import com.facebook.react.bridge.NativeModule;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.uimanager.ViewManager;

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

public class NavigationBarPackage implements ReactPackage {

    @Override
    public List<NativeModule> createNativeModules(ReactApplicationContext reactContext) {
        List<NativeModule> modules = new ArrayList<>();
        modules.add(new NavigationBarModule(reactContext));

        return modules;
    }

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

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

package com.attehuhtakangas.navigationbar;

import com.facebook.react.ReactPackage;
import com.facebook.react.bridge.JavaScriptModule;
import com.facebook.react.bridge.NativeModule;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.uimanager.ViewManager;

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

public class NavigationBarPackage implements ReactPackage {

    @Override
    public List<NativeModule> createNativeModules(ReactApplicationContext reactContext) {
        List<NativeModule> modules = new ArrayList<>();
        modules.add(new NavigationBarModule(reactContext));

        return modules;
    }

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

Fix react native support for v0.47 on the proper file


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

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 * Annotation that identifies a Class as a Plugin.
 */
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface Plugin {
    /**
     * Value of the elementType when none is specified.
     */
    String EMPTY = "";

    String name();
    String category();
    String elementType() default EMPTY;
    boolean printObject() default false;
    boolean deferChildren() default false;
}

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

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

import org.apache.logging.log4j.util.Strings;

/**
 * Annotation that identifies a Class as a Plugin.
 */
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface Plugin {

    /**
     * Value of the elementType when none is specified.
     */
    String EMPTY = Strings.EMPTY;

    String name();
    String category();
    String elementType() default EMPTY;
    boolean printObject() default false;
    boolean deferChildren() default false;
}

Refactor magic strings into a constant.


package com.alexstyl.specialdates.search;

import android.content.Context;
import android.util.AttributeSet;
import android.view.KeyEvent;
import android.widget.EditText;

public class BackKeyEditText extends EditText {
    public BackKeyEditText(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    private OnBackKeyPressedListener listener;

    public void setOnBackKeyPressedListener(OnBackKeyPressedListener listener) {
        this.listener = listener;
    }

    @Override
    public boolean onKeyPreIme(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && listener.onBackButtonPressed()) {
            return true;
        }
        return super.onKeyPreIme(keyCode, event);
    }
}

package com.alexstyl.specialdates.search;

import android.content.Context;
import android.util.AttributeSet;
import android.view.KeyEvent;
import android.widget.EditText;

public class BackKeyEditText extends android.support.v7.widget.AppCompatEditText {
    public BackKeyEditText(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    private OnBackKeyPressedListener listener;

    public void setOnBackKeyPressedListener(OnBackKeyPressedListener listener) {
        this.listener = listener;
    }

    @Override
    public boolean onKeyPreIme(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && listener.onBackButtonPressed()) {
            return true;
        }
        return super.onKeyPreIme(keyCode, event);
    }
}

Extend AppCompatEditText instead of system EditText


package com.kickstarter.libs;

import android.util.Pair;

import rx.Observable;

public class RxUtils {
  private RxUtils() {
    throw new AssertionError();
  }

  public static <F, S> Observable<Pair<F, S>> combineLatestPair(final Observable<F> ob1, final Observable<S> ob2) {
    return Observable.combineLatest(ob1, ob2, Pair::new);
  }

  public static <F, S> Observable<F> takeWhen(final Observable<F> ob1, final Observable<S> ob2) {
    return RxUtils.combineLatestPair(ob1, ob2).map(x -> x.first);
  }
}

package com.kickstarter.libs;

import android.util.Pair;

import rx.Observable;

public class RxUtils {
  private RxUtils() {
    throw new AssertionError();
  }

  public static <F, S> Observable<Pair<F, S>> combineLatestPair(final Observable<F> ob1, final Observable<S> ob2) {
    return Observable.combineLatest(ob1, ob2, Pair::new);
  }

  // Take values of ob1 when ob2 pings
  public static <F, S> Observable<F> takeWhen(final Observable<F> ob1, final Observable<S> ob2) {
    return RxUtils.combineLatestPair(ob1, ob2).map(x -> x.first);
  }
}

Add a lil comment explaining takeWhen