package com.jedrzejewski.slisp.lexer;

import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;

@RunWith(JUnit4.class)
public class LexerTest {

    @Test
    public void testNextToken() {
        Lexer lexer = new Lexer("(fn (zero? 0) (+ 2 3))");
        List<Token> tokens = new LinkedList<Token>();
        Token token;
        while ((token = lexer.getNextToken()) != null) {
            tokens.add(token);
        }
        List<Token> expected = Arrays.asList(
                new OpenBracket(),
                new Symbol("fn"),
                new OpenBracket(),
                new Symbol("zero?"),
                new Number(0),
                new CloseBracket(),
                new OpenBracket(),
                new Symbol("+"),
                new Number(2),
                new Number(3),
                new CloseBracket(),
                new CloseBracket());
        org.junit.Assert.assertEquals(tokens, expected);
    }
}

package com.jedrzejewski.slisp.lexer;

import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;

@RunWith(JUnit4.class)
public class LexerTest {

    @Test
    public void testNextToken() {
        Lexer lexer = new Lexer("(fn (zero? 0) (+ 2 3))");
        List<Token> tokens = new LinkedList<Token>();
        Token token;
        while ((token = lexer.getNextToken()) != null) {
            tokens.add(token);
        }
        List<Token> expected = Arrays.asList(
                new OpenBracket(),
                new Symbol("fn"),
                new OpenBracket(),
                new Symbol("zero?"),
                new Number(0),
                new CloseBracket(),
                new OpenBracket(),
                new Symbol("+"),
                new Number(2),
                new Number(3),
                new CloseBracket(),
                new CloseBracket());
        org.junit.Assert.assertEquals(expected, tokens);
    }
}

Change order of assert arguments

Change order of assert arguments


package com.gr8pefish.portablecrafting.items.craftingItems;

import com.gr8pefish.portablecrafting.items.ItemBase;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;

import java.util.List;

public class ItemSubCrafting extends ItemBase {

    public String[] names = {"crafting_core", "blueprints"};

    public ItemSubCrafting() {
        super("subcrafting.");
        setHasSubtypes(true);
    }

    @Override
    @SideOnly(Side.CLIENT)
    public void getSubItems(Item id, CreativeTabs creativeTab, List<ItemStack> list) {
        for (int i = 0; i < names.length; i++)
            list.add(new ItemStack(id, 1, i));
    }

    @Override
    public String getUnlocalizedName(ItemStack stack) {
        return super.getUnlocalizedName(stack) + names[stack.getItemDamage()];
    }
}

package com.gr8pefish.portablecrafting.items.craftingItems;

import com.gr8pefish.portablecrafting.items.ItemBase;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;

import java.util.List;

public class ItemSubCrafting extends ItemBase {

    public String[] names = {"crafting_core"};

    public ItemSubCrafting() {
        super("subcrafting.");
        setHasSubtypes(true);
    }

    @Override
    @SideOnly(Side.CLIENT)
    public void getSubItems(Item id, CreativeTabs creativeTab, List<ItemStack> list) {
        for (int i = 0; i < names.length; i++)
            list.add(new ItemStack(id, 1, i));
    }

    @Override
    public String getUnlocalizedName(ItemStack stack) {
        return super.getUnlocalizedName(stack) + names[stack.getItemDamage()];
    }
}

Fix registry for no-longer-present subItem


package fr.insee.rmes.api;

public class Configuration {

	// TODO Externalize props
	public final static String SPARQL_END_POINT = "http://id.insee.fr/sparql";

}

package fr.insee.rmes.api;

public class Configuration {

	// TODO Externalize props
	public final static String SPARQL_END_POINT = "http://qfrmessnczlht01.ad.insee.intra/sparql";
	//public final static String SPARQL_END_POINT = "http://id.insee.fr/sparql";
}

Fix minor issue with endpoint configuration


package uk.ac.edukapp.util;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;

public class ServletUtils {

	public static String getCookieValue(Cookie[] cookies, String cookieName,
			String defaultValue) {
		for (int i = 0; i < cookies.length; i++) {
			Cookie cookie = cookies[i];
			if (cookieName.equals(cookie.getName()))
				return (cookie.getValue());
		}
		return (defaultValue);
	}

	public static String getServletRootURL ( HttpServletRequest request ) {
		String serverName = request.getServerName();
		int serverPort = request.getServerPort();
		String protocol;

		if (request.isSecure()){
			protocol = "https";
		}
		else {
			protocol = "http";
		}

		String root = protocol+"://"+serverName+":"+serverPort+"/edukapp";

		return root;
	}

	public static boolean isNumeric(String str) {
		return str.matches("-?\\d+(.\\d+)?");
	}
}

package uk.ac.edukapp.util;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.validator.routines.UrlValidator;

public class ServletUtils {

	public static String getCookieValue(Cookie[] cookies, String cookieName,
			String defaultValue) {
		for (int i = 0; i < cookies.length; i++) {
			Cookie cookie = cookies[i];
			if (cookieName.equals(cookie.getName()))
				return (cookie.getValue());
		}
		return (defaultValue);
	}

	public static String getServletRootURL ( HttpServletRequest request ) {
		String serverName = request.getServerName();
		int serverPort = request.getServerPort();
		String protocol;

		if (request.isSecure()){
			protocol = "https";
		}
		else {
			protocol = "http";
		}

		String root = protocol+"://"+serverName+":"+serverPort+"/edukapp";

		return root;
	}

	public static boolean isNumeric(String str) {
		return str.matches("-?\\d+(.\\d+)?");
	}

	public static boolean checkURL ( String url ) {
		String schemes[] = {"http", "https"};
		UrlValidator urlValidator = new UrlValidator(schemes);
		return urlValidator.isValid(url);
	}
}

Support for web url widget creator

Support for web url widget creator


package langton;

import java.awt.Point;
import java.util.HashMap;

public class LangtonsAnt
{
  private final Point[] directions =
  {
    new Point(1, 0),
    new Point(0, 1),
    new Point(-1, 0),
    new Point(0, -1)
  };

  private Point ant;                      // The ant's position
  private int direction = 0;              // The ant's direction
  private HashMap<Point, Boolean> field;  // The field which the ant moves on

  public LangtonsAnt()
  {
    // Create a new Map to hold coordinates for ant
    field = new HashMap<Point, Boolean>();
  }

  public void step()
  {
    // If the ant is on a black square
    if (field.get(ant))
    {
      direction = (direction - 1) % 4;
      field.put(ant, false);
    }
    else  // If the ant is on a white spot
    {
      direction = (direction + 1) % 4;
      field.put(ant, true);
    }

    ant.translate(directions[direction].x,
                  directions[direction].y);
  }

  public static void main(String[] args)
  {
  }
}

package langton;

import java.awt.Point;
import java.util.HashMap;

public class LangtonsAnt
{
  private final Point[] directions =
  {
    new Point(1, 0),
    new Point(0, 1),
    new Point(-1, 0),
    new Point(0, -1)
  };

  private Point ant;                      // The ant's position
  private int direction = 0;              // The ant's direction
  private HashMap<Point, Boolean> plane;  // The plane which the ant moves on

  public LangtonsAnt()
  {
    // Create a new Map to hold coordinates for ant
    plane = new HashMap<Point, Boolean>();
  }

  public Point getAnt()
  {
    return ant;
  }

  public HashMap<Point, Boolean> getPlane()
  {
    return plane;
  }

  public void step()
  {
    // If the ant is on a black square
    if (plane.get(ant))
    {
      direction = (direction - 1) % 4;
      plane.put(ant, false);
    }
    else  // If the ant is on a white spot
    {
      direction = (direction + 1) % 4;
      plane.put(ant, true);
    }

    ant.translate(directions[direction].x,
                  directions[direction].y);
  }
}

Add getPlane-method. Returns the plane which the ant moves on

Add getAnt-method. Returns the position of the ant

Remove main-method


package edu.northwestern.bioinformatics.studycalendar.dao.reporting;

import edu.northwestern.bioinformatics.studycalendar.dao.StudyCalendarDao;
import gov.nih.nci.cabig.ctms.domain.DomainObject;
import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.springframework.orm.hibernate3.HibernateCallback;

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

/**
 * @author John Dzak
 */
public abstract class ReportDao<F extends ReportFilters, R extends DomainObject> extends StudyCalendarDao<R> {
    @SuppressWarnings("unchecked")
    public List<R> search(final F filters) {
        return getHibernateTemplate().executeFind(new HibernateCallback() {
            @SuppressWarnings("unchecked")
            public Object doInHibernate(Session session) throws HibernateException {
                if (filters.isEmpty()) {
                    logger.debug("No filters selected, skipping search: " + filters);
                    return Collections.emptyList();
                } else {
                    Criteria criteria = session.createCriteria(domainClass());
                    filters.apply(session);
                    return (List<R>) criteria.list();

                }
            }
        });
    }
}

package edu.northwestern.bioinformatics.studycalendar.dao.reporting;

import edu.northwestern.bioinformatics.studycalendar.dao.StudyCalendarDao;
import gov.nih.nci.cabig.ctms.domain.DomainObject;
import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.criterion.Order;
import org.springframework.orm.hibernate3.HibernateCallback;

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

/**
 * @author John Dzak
 */
public abstract class ReportDao<F extends ReportFilters, R extends DomainObject> extends StudyCalendarDao<R> {
    @SuppressWarnings("unchecked")
    public List<R> search(final F filters) {
        return getHibernateTemplate().executeFind(new HibernateCallback() {
            @SuppressWarnings("unchecked")
            public Object doInHibernate(Session session) throws HibernateException {
                if (filters.isEmpty()) {
                    logger.debug("No filters selected, skipping search: " + filters);
                    return Collections.emptyList();
                } else {
                    Criteria criteria = session.createCriteria(domainClass()).addOrder(Order.asc("id"));
                    filters.apply(session);
                    return (List<R>) criteria.list();

                }
            }
        });
    }
}

Sort for testing.  Fix for test failures introduced in r3557.

git-svn-id: 4b387fe5ada7764508e2ca96c335714e4c1692c6@3563 0d517254-b314-0410-acde-c619094fa49f


//////////////////////////////////////////////////////////////////////////////
//
//               Copyright 2010, Starting Block Technologies
//                        www.startingblocktech.com
//
//////////////////////////////////////////////////////////////////////////////

package com.startingblocktech.tcases;

import java.util.Collection;
import java.util.regex.Pattern;

/**
 * Defines utility methods for constructing test definitions.
 *
 * @version $Revision$, $Date$
 */
public abstract class DefUtils
  {
  /**
   * Returns true if the given string is a valid identifier.
   */
  public static boolean isIdentifier( String id)
    {
    return id != null && identifierRegex_.matcher( id).matches();
    }

  /**
   * Throws an exception if the given string is not a valid identifier.
   */
  public static void assertIdentifier( String id) throws IllegalArgumentException
    {
    if( !isIdentifier( id))
      {
      throw new IllegalArgumentException( "\"" + String.valueOf( id) + "\" is not a valid identifier");
      }
    }

  /**
   * Throws an exception if any member of the given set of properties is not a valid identifier.
   */
  public static void assertPropertyIdentifiers( Collection<String> properties) throws IllegalArgumentException
    {
    if( properties != null)
      {
      try
        {
        for( String property : properties)
          {
          assertIdentifier( property);
          }
        }
      catch( Exception e)
        {
        throw new IllegalArgumentException( "Invalid property set", e);
        }
      }
    }

  private static final Pattern identifierRegex_ = Pattern.compile( "[\\w\\-]+");
  }

//////////////////////////////////////////////////////////////////////////////
//
//               Copyright 2010, Starting Block Technologies
//                        www.startingblocktech.com
//
//////////////////////////////////////////////////////////////////////////////

package com.startingblocktech.tcases;

import java.util.Collection;
import java.util.regex.Pattern;

/**
 * Defines utility methods for constructing test definitions.
 *
 * @version $Revision$, $Date$
 */
public abstract class DefUtils
  {
  /**
   * Returns true if the given string is a valid identifier.
   */
  public static boolean isIdentifier( String id)
    {
    return id != null && identifierRegex_.matcher( id).matches();
    }

  /**
   * Throws an exception if the given string is not a valid identifier.
   */
  public static void assertIdentifier( String id) throws IllegalArgumentException
    {
    if( !isIdentifier( id))
      {
      throw
        new IllegalArgumentException
        ( (id==null? "null" : ("\"" + String.valueOf( id) + "\""))
          + " is not a valid identifier");
      }
    }

  /**
   * Throws an exception if any member of the given set of properties is not a valid identifier.
   */
  public static void assertPropertyIdentifiers( Collection<String> properties) throws IllegalArgumentException
    {
    if( properties != null)
      {
      try
        {
        for( String property : properties)
          {
          assertIdentifier( property);
          }
        }
      catch( Exception e)
        {
        throw new IllegalArgumentException( "Invalid property set", e);
        }
      }
    }

  private static final Pattern identifierRegex_ = Pattern.compile( "[\\w\\-]+");
  }

assertIdentifier: Clean up exception message for null identifier


package openmods.asm;

import net.minecraft.launchwrapper.IClassTransformer;

import org.objectweb.asm.ClassReader;
import org.objectweb.asm.ClassVisitor;
import org.objectweb.asm.ClassWriter;

public class OpenModsClassTransformer implements IClassTransformer {

	public static interface TransformProvider {
		public ClassVisitor createVisitor(ClassVisitor cv);
	}

	private final static TransformProvider INCLUDING_CV = new TransformProvider() {

		@Override
		public ClassVisitor createVisitor(ClassVisitor cv) {
			return new IncludingClassVisitor(cv);
		}
	};

	public static byte[] applyVisitor(byte[] bytes, int flags, TransformProvider context) {
		ClassReader cr = new ClassReader(bytes);
		ClassWriter cw = new ClassWriter(cr, flags);
		ClassVisitor mod = context.createVisitor(cw);

		try {
			cr.accept(mod, 0);
			return cw.toByteArray();
		} catch (StopTransforming e) {
			return bytes;
		}
	}

	@Override
	public byte[] transform(final String name, String transformedName, byte[] bytes) {
		if (name.startsWith("openmods.asm")) return bytes;
		// / no need for COMPUTE_FRAMES, we can handle simple stuff
		return applyVisitor(bytes, 0, INCLUDING_CV);
	}
}

package openmods.asm;

import net.minecraft.launchwrapper.IClassTransformer;

import org.objectweb.asm.ClassReader;
import org.objectweb.asm.ClassVisitor;
import org.objectweb.asm.ClassWriter;

import com.google.common.base.Preconditions;

public class OpenModsClassTransformer implements IClassTransformer {

	public static interface TransformProvider {
		public ClassVisitor createVisitor(ClassVisitor cv);
	}

	private final static TransformProvider INCLUDING_CV = new TransformProvider() {

		@Override
		public ClassVisitor createVisitor(ClassVisitor cv) {
			return new IncludingClassVisitor(cv);
		}
	};

	public static byte[] applyVisitor(byte[] bytes, int flags, TransformProvider context) {
		Preconditions.checkNotNull(bytes);
		ClassReader cr = new ClassReader(bytes);
		ClassWriter cw = new ClassWriter(cr, flags);
		ClassVisitor mod = context.createVisitor(cw);

		try {
			cr.accept(mod, 0);
			return cw.toByteArray();
		} catch (StopTransforming e) {
			return bytes;
		}
	}

	@Override
	public byte[] transform(final String name, String transformedName, byte[] bytes) {
		if (bytes == null || name.startsWith("openmods.asm") || name.startsWith("net.minecraft.")) return bytes;
		// / no need for COMPUTE_FRAMES, we can handle simple stuff
		return applyVisitor(bytes, 0, INCLUDING_CV);
	}
}

Fix crash on missing classes (it will crash later, but nobody will blame us


/*
 * JBoss, Home of Professional Open Source.
 * Copyright 2014 Red Hat, Inc., and individual contributors
 * as indicated by the @author tags.
 *
 * 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.jboss.modules;

import java.lang.management.ManagementFactory;
import java.lang.management.ThreadMXBean;
import java.security.AccessController;

/**
 * @author David M. Lloyd
 */
final class Metrics {
    static final boolean ENABLED;
    static final ThreadMXBean THREAD_MX_BEAN = ManagementFactory.getThreadMXBean();

    private Metrics() {
    }

    static long getCurrentCPUTime() {
        return ENABLED ? false ? THREAD_MX_BEAN.getCurrentThreadCpuTime() : System.nanoTime() : 0L;
    }

    static {
        ENABLED = Boolean.parseBoolean(AccessController.doPrivileged(new PropertyReadAction("jboss.modules.metrics", "false")));
    }
}

/*
 * JBoss, Home of Professional Open Source.
 * Copyright 2014 Red Hat, Inc., and individual contributors
 * as indicated by the @author tags.
 *
 * 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.jboss.modules;

import java.security.AccessController;

/**
 * @author David M. Lloyd
 */
final class Metrics {
    static final boolean ENABLED;

    private Metrics() {
    }

    static long getCurrentCPUTime() {
        return ENABLED ? System.nanoTime() : 0L;
    }

    static {
        ENABLED = Boolean.parseBoolean(AccessController.doPrivileged(new PropertyReadAction("jboss.modules.metrics", "false")));
    }
}

[MODULES-222] Fix early initialization of log manager on JDK 9+


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

package com.deltadna.android.sdk.notifications.example;

import android.content.Context;
import androidx.core.app.NotificationCompat;

import com.deltadna.android.sdk.notifications.NotificationFactory;
import com.deltadna.android.sdk.notifications.PushMessage;

/**
 * Example of a {@link NotificationFactory} which changes the look of the
 * notification after a push message is received.
 */
public class StyledNotificationFactory extends NotificationFactory {

    public StyledNotificationFactory(Context context) {
        super(context);
    }

    @Override
    public NotificationCompat.Builder configure(
            NotificationCompat.Builder builder,
            PushMessage message){

        return super.configure(builder, message);

    }
}

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

package com.deltadna.android.sdk.notifications.example;

import android.content.Context;
import androidx.core.app.NotificationCompat;

import com.deltadna.android.sdk.notifications.NotificationFactory;
import com.deltadna.android.sdk.notifications.PushMessage;

/**
 * Example of a {@link NotificationFactory} which changes the look of the
 * notification after a push message is received.
 */
public class StyledNotificationFactory extends NotificationFactory {

    public StyledNotificationFactory(Context context) {
        super(context);
    }

    @Override
    public NotificationCompat.Builder configure(
            Context context,
            PushMessage message){

        return super.configure(context, message);

    }
}

Update the example notifications app

DDSDK: Update the example notifications app


package com.codenvy.ide.ext.datasource.client.sqllauncher;

import com.google.gwt.i18n.client.Constants;

public interface SqlRequestLauncherConstants extends Constants {

    @DefaultStringValue("Open SQL editor")
    String menuEntryOpenSqlEditor();

    @DefaultStringValue("SQL editor")
    String sqlEditorWindowTitle();

    @DefaultStringValue("Select datasource")
    String selectDatasourceLabel();

    @DefaultStringValue("Result limit")
    String resultLimitLabel();

    @DefaultStringValue("Execute")
    String executeButtonLabel();
}

package com.codenvy.ide.ext.datasource.client.sqllauncher;

import com.google.gwt.i18n.client.Messages;

public interface SqlRequestLauncherConstants extends Messages {

    @DefaultMessage("Open SQL editor")
    String menuEntryOpenSqlEditor();

    @DefaultMessage("SQL editor")
    String sqlEditorWindowTitle();

    @DefaultMessage("Select datasource")
    String selectDatasourceLabel();

    @DefaultMessage("Result limit")
    String resultLimitLabel();

    @DefaultMessage("Execute")
    String executeButtonLabel();

    @DefaultMessage("{0} rows.")
    String updateCountMessage(int count);
}

Change constants class to messages

Change constants class to messages


package net.darkmorford.btweagles.eventhandler;

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

@Mod.EventBusSubscriber
public class EventHandlerBlockDrops
{
	@SubscribeEvent
	public static void modifyHarvestDrops(BlockEvent.HarvestDropsEvent event)
	{
		if (event.getState().getBlock() == Blocks.GRAVEL)
		{
			event.getDrops().add(new ItemStack(ModItems.shiny_stone));
		}
	}
}

package net.darkmorford.btweagles.eventhandler;

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

import java.util.Random;

@Mod.EventBusSubscriber
public class EventHandlerBlockDrops
{
	@SubscribeEvent
	public static void modifyHarvestDrops(BlockEvent.HarvestDropsEvent event)
	{
		if (event.getState().getBlock() == Blocks.GRAVEL)
		{
			Random rand = event.getWorld().rand;

			if (rand.nextInt(100) < 2)
			{
				event.getDrops().add(new ItemStack(ModItems.shiny_stone));
			}
		}
	}
}

Reduce drop rate of shiny_stone.

Reduce drop rate of shiny_stone.


package com.twilio.notify.quickstart.notifyapi;

import com.twilio.notify.quickstart.notifyapi.model.Binding;

import retrofit2.Call;
import retrofit2.Retrofit;
import retrofit2.converter.jackson.JacksonConverterFactory;
import retrofit2.http.Body;
import retrofit2.http.POST;

public class TwilioSDKStarterAPI {
    private static String BASE_SERVER_URL = "https://f5ab0b54.ngrok.io";

    /**
     * A resource defined to register Notify bindings using the sdk-starter projects available in
     * C#, Java, Node, PHP, Python, or Ruby.
     *
     * https://github.com/TwilioDevEd?q=sdk-starter
     */
    interface SDKStarterService {
        @POST("/register")
        Call<Void> register(@Body Binding binding);
    }

    private static SDKStarterService sdkStarterService = new Retrofit.Builder()
            .baseUrl(BASE_SERVER_URL)
            .addConverterFactory(JacksonConverterFactory.create())
            .build()
            .create(SDKStarterService.class);

    public static Call<Void> registerBinding(final Binding binding) {
        return sdkStarterService.register(binding);
    }

}

package com.twilio.notify.quickstart.notifyapi;

import com.twilio.notify.quickstart.notifyapi.model.Binding;

import retrofit2.Call;
import retrofit2.Retrofit;
import retrofit2.converter.jackson.JacksonConverterFactory;
import retrofit2.http.Body;
import retrofit2.http.POST;

public class TwilioSDKStarterAPI {
    private static String BASE_SERVER_URL = "YOUR_SDK_STARTER_SERVER_URL";

    /**
     * A resource defined to register Notify bindings using the sdk-starter projects available in
     * C#, Java, Node, PHP, Python, or Ruby.
     *
     * https://github.com/TwilioDevEd?q=sdk-starter
     */
    interface SDKStarterService {
        @POST("/register")
        Call<Void> register(@Body Binding binding);
    }

    private static SDKStarterService sdkStarterService = new Retrofit.Builder()
            .baseUrl(BASE_SERVER_URL)
            .addConverterFactory(JacksonConverterFactory.create())
            .build()
            .create(SDKStarterService.class);

    public static Call<Void> registerBinding(final Binding binding) {
        return sdkStarterService.register(binding);
    }

}

Replace ngrok url with stub

Replace ngrok url with stub


package ru.job4j.even.numbers.iterator;

import java.util.Iterator;
import java.util.NoSuchElementException;

public class EvenNumbersIterator implements Iterator {
    private int[] numbers;
    private int index = 0;
    private int size;

    public EvenNumbersIterator(final int[] numbers) {
        this.numbers = numbers;
        this.size = numbers.length;
    }

    @Override
    public boolean hasNext() {
        int pointer = index;
        while (pointer < size) {
            if (isEvenNumber(numbers[pointer])) {
                return true;
            } else {
                pointer++;
            }
        }
        return false;
    }

    @Override
    public Object next() {
//        if (size == 0 || !hasNext() || index > size) {
        if (!hasNext()) {
            throw new NoSuchElementException();
        }
        int tmp = numbers[index];
        while (index < size) {
            if (isEvenNumber(tmp)) {
                index++;
                break;
            } else {
                tmp = numbers[++index];
            }
        }
        return tmp;
    }

    private boolean isEvenNumber(int num) {
        return num % 2 == 0;
    }
}

package ru.job4j.even.numbers.iterator;

import java.util.Iterator;
import java.util.NoSuchElementException;

public class EvenNumbersIterator implements Iterator {
    private int[] numbers;
    private int index = 0;
    private int size;

    public EvenNumbersIterator(final int[] numbers) {
        this.numbers = numbers;
        this.size = numbers.length;
    }

    @Override
    public boolean hasNext() {
        int pointer = index;
        while (pointer < size) {
            if (isEvenNumber(numbers[pointer])) {
                return true;
            } else {
                pointer++;
            }
        }
        return false;
    }

    @Override
    public Object next() {
        if (!hasNext()) {
            throw new NoSuchElementException();
        }
        int tmp = numbers[index];
        while (index < size) {
            if (isEvenNumber(tmp)) {
                index++;
                break;
            } else {
                tmp = numbers[++index];
            }
        }
        return tmp;
    }

    private boolean isEvenNumber(int num) {
        return num % 2 == 0;
    }
}

Add a change to method.

Add a change to method.


/*
 * Copyright Red Hat Inc. and/or its affiliates and other contributors
 * as indicated by the authors tag. All rights reserved.
 *
 * This copyrighted material is made available to anyone wishing to use,
 * modify, copy, or redistribute it subject to the terms and conditions
 * of the GNU General Public License version 2.
 *
 * This particular file is subject to the "Classpath" exception as provided in the
 * LICENSE file that accompanied this code.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT A
 * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
 * PARTICULAR PURPOSE.  See the GNU General Public License for more details.
 * You should have received a copy of the GNU General Public License,
 * along with this distribution; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
 * MA  02110-1301, USA.
 */
package com.redhat.ceylon.common.tool;

import java.text.MessageFormat;
import java.util.ResourceBundle;

class ToolMessages {

    private static final ResourceBundle RESOURCE_BUNDLE = ResourceBundle.getBundle("com.redhat.ceylon.common.tool.tools");

    public static String msg(String msgKey, Object... msgArgs) {
        String msg = RESOURCE_BUNDLE.getString(msgKey);
        if (msgArgs != null) {
            msg = MessageFormat.format(msg, msgArgs);
        }
        return msg;
    }

}

/*
 * Copyright Red Hat Inc. and/or its affiliates and other contributors
 * as indicated by the authors tag. All rights reserved.
 *
 * This copyrighted material is made available to anyone wishing to use,
 * modify, copy, or redistribute it subject to the terms and conditions
 * of the GNU General Public License version 2.
 *
 * This particular file is subject to the "Classpath" exception as provided in the
 * LICENSE file that accompanied this code.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT A
 * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
 * PARTICULAR PURPOSE.  See the GNU General Public License for more details.
 * You should have received a copy of the GNU General Public License,
 * along with this distribution; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
 * MA  02110-1301, USA.
 */
package com.redhat.ceylon.common.tool;

import java.util.ResourceBundle;

import com.redhat.ceylon.common.Messages;

class ToolMessages extends Messages {

    private static final ResourceBundle RESOURCE_BUNDLE = ResourceBundle.getBundle("com.redhat.ceylon.common.tool.tools");

    public static String msg(String msgKey, Object... msgArgs) {
        return msg(RESOURCE_BUNDLE, msgKey, msgArgs);
    }

}

Extend the common Messages class

Extend the common Messages class


package gigaherz.graph.api;

import net.minecraftforge.fml.common.Mod;
import net.minecraftforge.fml.common.Mod.EventHandler;
import net.minecraftforge.fml.common.SidedProxy;
import net.minecraftforge.fml.common.event.FMLInitializationEvent;
import net.minecraftforge.fml.common.event.FMLInterModComms;
import net.minecraftforge.fml.common.event.FMLPreInitializationEvent;
import net.minecraftforge.fml.common.registry.GameRegistry;

@Mod(modid = GraphApiTest.MODID, version = GraphApiTest.VERSION)
public class GraphApiTest
{
    public static final String MODID = "GraphLib";
    public static final String VERSION = "1.0";

    @SidedProxy(clientSide = "gigaherz.graph.api.ClientProxy", serverSide = "gigaherz.graph.api.Proxy")
    public static Proxy proxy;

    public static BlockRegistered networkTest;

    @EventHandler
    public void preInit(FMLPreInitializationEvent event)
    {
        networkTest = new BlockNetworkTest("blockNetworkTest");
        GameRegistry.register(networkTest);
        GameRegistry.register(networkTest.createItemBlock());
        GameRegistry.registerTileEntity(TileNetworkTest.class, "tileNetworkTest");

        proxy.preInit();
    }

    @EventHandler
    public void init(FMLInitializationEvent event)
    {
        proxy.init();

        FMLInterModComms.sendMessage("Waila", "register", "gigaherz.graph.api.WailaProviders.callbackRegister");
    }
}

package gigaherz.graph.api;

import net.minecraftforge.fml.common.Mod;
import net.minecraftforge.fml.common.Mod.EventHandler;
import net.minecraftforge.fml.common.SidedProxy;
import net.minecraftforge.fml.common.event.FMLInitializationEvent;
import net.minecraftforge.fml.common.event.FMLInterModComms;
import net.minecraftforge.fml.common.event.FMLPreInitializationEvent;
import net.minecraftforge.fml.common.registry.GameRegistry;

@Mod(modid = GraphApiTest.MODID, version = GraphApiTest.VERSION)
public class GraphApiTest
{
    public static final String MODID = "GraphLib";
    public static final String VERSION = Constants.API_VERSION;

    @SidedProxy(clientSide = "gigaherz.graph.api.ClientProxy", serverSide = "gigaherz.graph.api.Proxy")
    public static Proxy proxy;

    public static BlockRegistered networkTest;

    @EventHandler
    public void preInit(FMLPreInitializationEvent event)
    {
        networkTest = new BlockNetworkTest("blockNetworkTest");
        GameRegistry.register(networkTest);
        GameRegistry.register(networkTest.createItemBlock());
        GameRegistry.registerTileEntity(TileNetworkTest.class, "tileNetworkTest");

        proxy.preInit();
    }

    @EventHandler
    public void init(FMLInitializationEvent event)
    {
        proxy.init();

        FMLInterModComms.sendMessage("Waila", "register", "gigaherz.graph.api.WailaProviders.callbackRegister");
    }
}

Make the test mod take the version from the API.


package jkind.api.results;

import java.util.Map;

/**
 * A renaming backed by a map from strings to strings
 */
public class MapRenaming extends Renaming {
	private Map<String, String> map;

	public MapRenaming(Map<String, String> map) {
		this.map = map;
	}

	@Override
	public String rename(String original) {
		return map.get(original);
	}
}

package jkind.api.results;

import java.util.Map;

/**
 * A renaming backed by a map from strings to strings
 */
public class MapRenaming extends Renaming {
	private final Map<String, String> map;
	private final Mode mode;

	public static enum Mode {
		NULL, IDENTITY
	}

	public MapRenaming(Map<String, String> map, Mode mode) {
		this.map = map;
		this.mode = mode;
	}

	@Override
	public String rename(String original) {
		String renamed = map.get(original);
		if (renamed == null && mode == Mode.IDENTITY) {
			return original;
		} else {
			return renamed;
		}
	}
}

Add two options for map renamings

Add two options for map renamings


/*
 * Copyright 2018, TeamDev. All rights reserved.
 *
 * Redistribution and use in source and/or binary forms, with or without
 * modification, must retain the above copyright notice and the following
 * disclaimer.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

/**
 * Test environment classes for tests of the {@link io.spine.server.storage.jdbc.aggregate} package.
 */

@ParametersAreNonnullByDefault
package io.spine.server.storage.jdbc.aggregate.given;

import javax.annotation.ParametersAreNonnullByDefault;

/*
 * Copyright 2018, TeamDev. All rights reserved.
 *
 * Redistribution and use in source and/or binary forms, with or without
 * modification, must retain the above copyright notice and the following
 * disclaimer.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

/**
 * Test environment classes for tests of the {@link io.spine.server.storage.jdbc.aggregate} package.
 */

@CheckReturnValue
@ParametersAreNonnullByDefault
package io.spine.server.storage.jdbc.aggregate.given;

import com.google.errorprone.annotations.CheckReturnValue;

import javax.annotation.ParametersAreNonnullByDefault;

Add `@CheckReturnValue` to package info

Add `@CheckReturnValue` to package info


package gov.samhsa.c2s.c2suiapi.infrastructure.dto;

import gov.samhsa.c2s.common.validator.constraint.PresentOrFuture;
import lombok.Data;
import org.hibernate.validator.constraints.ScriptAssert;

import javax.validation.Valid;
import javax.validation.constraints.Future;
import javax.validation.constraints.NotNull;
import java.time.LocalDate;

@Data
@ScriptAssert(
        lang = "javascript",
        alias = "_",
        script = "_.startDate != null && _.endDate != null && _.startDate.isBefore(_.endDate)",
        message = "consent end date must be after consent start date")
public class ConsentDto {
    private Long id;
    @NotNull
    @Future
    private LocalDate endDate;
    @Valid
    @NotNull
    private IdentifiersDto fromProviders;
    @Valid
    @NotNull
    private IdentifiersDto sharePurposes;
    @Valid
    @NotNull
    private IdentifiersDto shareSensitivityCategories;
    @NotNull
    @PresentOrFuture
    private LocalDate startDate;
    @Valid
    @NotNull
    private IdentifiersDto toProviders;
}

package gov.samhsa.c2s.c2suiapi.infrastructure.dto;

import gov.samhsa.c2s.common.validator.constraint.PresentOrFuture;
import lombok.Data;
import org.hibernate.validator.constraints.ScriptAssert;

import javax.validation.Valid;
import javax.validation.constraints.Future;
import javax.validation.constraints.NotNull;
import java.time.LocalDate;

@Data
@ScriptAssert(
        lang = "javascript",
        alias = "_",
        script = "_.startDate != null && _.endDate != null && _.startDate.isBefore(_.endDate)",
        message = "consent end date must be after consent start date")
public class ConsentDto {
    private Long id;
    @NotNull
    @Future
    private LocalDate endDate;
    @Valid
    @NotNull
    private IdentifiersDto fromProviders;
    @Valid
    @NotNull
    private IdentifiersDto purposes;
    @Valid
    @NotNull
    private IdentifiersDto sensitivityCategories;
    @NotNull
    @PresentOrFuture
    private LocalDate startDate;
    @Valid
    @NotNull
    private IdentifiersDto toProviders;

    @NotNull
    private boolean shareSensitivityCategoriesEnabled;
}

Update Consent Dto to have shareSensitivityCategoriesEnabled attribute

#14280 - As a developer I will make consent share/not share type configurable at Deployment Time to support patient UI - Backend


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

import org.eclipse.egit.github.core.client.GitHubClient;

/**
 * Default client used to communicate with GitHub API
 */
public class DefaultClient extends GitHubClient {

    private static final String USER_AGENT = "GitHubAndroid/1.9";

    /**
     * Create client
     */
    public DefaultClient() {
        super();

        setSerializeNulls(false);
        setUserAgent(USER_AGENT);
    }
}

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

import org.eclipse.egit.github.core.client.GitHubClient;

/**
 * Default client used to communicate with GitHub API
 */
public class DefaultClient extends GitHubClient {

    private static final String USER_AGENT = "ForkHub/1.0";

    /**
     * Create client
     */
    public DefaultClient() {
        super();

        setSerializeNulls(false);
        setUserAgent(USER_AGENT);
    }
}

Update user agent for all requests

Update user agent for all requests


package replicant.messages;

import elemental2.core.JsObject;
import javax.annotation.Nonnull;
import jsinterop.annotations.JsOverlay;
import jsinterop.annotations.JsPackage;
import jsinterop.annotations.JsType;
import jsinterop.base.Any;
import jsinterop.base.Js;

/**
 * A simple abstraction for key-value etag pairs.
 */
@JsType( isNative = true, name = "Object", namespace = JsPackage.GLOBAL )
public interface EtagsData
{
  /**
   * Return true if etag for channel is present.
   *
   * @param key the channel key.
   * @return true if the etag is present.
   */
  @JsOverlay
  default boolean containsChannel( @Nonnull final String key )
  {
    return Js.asPropertyMap( this ).has( key );
  }

  /**
   * Return the channels.
   *
   * @return eturn the channels.
   */
  @JsOverlay
  default String[] channels()
  {
    return JsObject.keys( this );
  }

  @Nonnull
  @JsOverlay
  default String getEtag( @Nonnull final String key )
  {
    final Any any = Js.asPropertyMap( this ).getAsAny( key );
    assert null != any;
    return any.asString();
  }
}

package replicant.messages;

import elemental2.core.JsArray;
import elemental2.core.JsObject;
import javax.annotation.Nonnull;
import jsinterop.annotations.JsOverlay;
import jsinterop.annotations.JsPackage;
import jsinterop.annotations.JsType;
import jsinterop.base.Any;
import jsinterop.base.Js;

/**
 * A simple abstraction for key-value etag pairs.
 */
@JsType( isNative = true, name = "Object", namespace = JsPackage.GLOBAL )
public interface EtagsData
{
  /**
   * Return true if etag for channel is present.
   *
   * @param key the channel key.
   * @return true if the etag is present.
   */
  @JsOverlay
  default boolean containsChannel( @Nonnull final String key )
  {
    return Js.asPropertyMap( this ).has( key );
  }

  /**
   * Return the channels.
   *
   * @return eturn the channels.
   */
  @JsOverlay
  default String[] channels()
  {
    final JsArray<String> keys = JsObject.keys( this );
    return keys.asArray( new String[ keys.length ] );
  }

  @Nonnull
  @JsOverlay
  default String getEtag( @Nonnull final String key )
  {
    final Any any = Js.asPropertyMap( this ).getAsAny( key );
    assert null != any;
    return any.asString();
  }
}

Upgrade to the latest Elemental2 API

Upgrade to the latest Elemental2 API


package nl.thehyve.ocdu.validators.fileValidators;

import nl.thehyve.ocdu.models.OCEntities.ClinicalData;
import nl.thehyve.ocdu.models.OcDefinitions.MetaData;
import nl.thehyve.ocdu.validators.ClinicalDataChecksRunner;
import nl.thehyve.ocdu.validators.clinicalDataChecks.ClinicalDataCrossCheck;
import nl.thehyve.ocdu.validators.clinicalDataChecks.CrfCouldNotBeVerifiedCrossCheck;
import nl.thehyve.ocdu.validators.clinicalDataChecks.CrfExistsCrossCheck;
import nl.thehyve.ocdu.validators.clinicalDataChecks.SiteSubjectMatchCrossCheck;
import nl.thehyve.ocdu.validators.clinicalDataChecks.SitesExistCrossCheck;
import nl.thehyve.ocdu.validators.clinicalDataChecks.StudyStatusAvailable;
import org.openclinica.ws.beans.StudySubjectWithEventsType;

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

/**
 * Created by piotrzakrzewski on 22/06/16.
 */
public class DataPreMappingValidator extends ClinicalDataChecksRunner {

    public DataPreMappingValidator(MetaData metadata, List<ClinicalData> clinicalData, List<StudySubjectWithEventsType> subjectWithEventsTypes) {
        super(metadata, clinicalData, subjectWithEventsTypes);
        Collection<ClinicalDataCrossCheck> checks = new ArrayList<>();
        checks.add(new SitesExistCrossCheck());
        checks.add(new SiteSubjectMatchCrossCheck());
        checks.add(new CrfExistsCrossCheck());
        checks.add(new StudyStatusAvailable());
        checks.add(new CrfCouldNotBeVerifiedCrossCheck());
        this.setChecks(checks);
    }
}

package nl.thehyve.ocdu.validators.fileValidators;

import nl.thehyve.ocdu.models.OCEntities.ClinicalData;
import nl.thehyve.ocdu.models.OcDefinitions.MetaData;
import nl.thehyve.ocdu.validators.ClinicalDataChecksRunner;
import nl.thehyve.ocdu.validators.clinicalDataChecks.*;
import org.openclinica.ws.beans.StudySubjectWithEventsType;

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

/**
 * Created by piotrzakrzewski on 22/06/16.
 */
public class DataPreMappingValidator extends ClinicalDataChecksRunner {

    public DataPreMappingValidator(MetaData metadata, List<ClinicalData> clinicalData, List<StudySubjectWithEventsType> subjectWithEventsTypes) {
        super(metadata, clinicalData, subjectWithEventsTypes);
        Collection<ClinicalDataCrossCheck> checks = new ArrayList<>();
        checks.add(new SitesExistCrossCheck());
        checks.add(new SiteSubjectMatchCrossCheck());
        checks.add(new CrfExistsCrossCheck());
        checks.add(new StudyStatusAvailable());
        checks.add(new CrfCouldNotBeVerifiedCrossCheck());
        checks.add(new EventExistsCrossCheck());
        this.setChecks(checks);
    }
}

Add event existence to the mapping pre checks


package cgeo.geocaching.sorting;

import cgeo.geocaching.Geocache;
import cgeo.geocaching.utils.TextUtils;

import org.apache.commons.lang3.StringUtils;

import java.text.Collator;

/**
 * sorts caches by name
 *
 */
class NameComparator extends AbstractCacheComparator {

    private final Collator collator;

    public NameComparator() {
        collator = TextUtils.getCollator();
    }

    @Override
    protected boolean canCompare(final Geocache cache) {
        return StringUtils.isNotBlank(cache.getName());
    }

    @Override
    protected int compareCaches(final Geocache cache1, final Geocache cache2) {
        return collator.compare(cache1.getNameForSorting(), cache2.getNameForSorting());
    }
}

package cgeo.geocaching.sorting;

import cgeo.geocaching.Geocache;
import cgeo.geocaching.utils.TextUtils;

import org.apache.commons.lang3.StringUtils;

import java.text.Collator;

/**
 * sorts caches by name
 *
 */
class NameComparator extends AbstractCacheComparator {

    private final Collator collator = TextUtils.getCollator();

    @Override
    protected boolean canCompare(final Geocache cache) {
        return StringUtils.isNotBlank(cache.getName());
    }

    @Override
    protected int compareCaches(final Geocache cache1, final Geocache cache2) {
        return collator.compare(cache1.getNameForSorting(), cache2.getNameForSorting());
    }
}

Initialize final field in field declaration


/*
 * Copyright 2015 Hewlett-Packard Development Company, L.P.
 * Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License.
 */

package com.hp.autonomy.searchcomponents.core.search;

import com.hp.autonomy.types.requests.Documents;

import java.io.Serializable;
import java.util.List;
import java.util.Set;

public interface DocumentsService<S extends Serializable, D extends SearchResult, E extends Exception> {
    String HIGHLIGHT_START_TAG = "<Find-IOD-QueryText-Placeholder>";
    String HIGHLIGHT_END_TAG = "</Find-IOD-QueryText-Placeholder>";

    Documents<D> queryTextIndex(final SearchRequest<S> searchRequest) throws E;

    Documents<D> queryTextIndexForPromotions(final SearchRequest<S> searchRequest) throws E;

    List<D> findSimilar(Set<S> indexes, String reference) throws E;

}

/*
 * Copyright 2015 Hewlett-Packard Development Company, L.P.
 * Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License.
 */

package com.hp.autonomy.searchcomponents.core.search;

import com.hp.autonomy.types.requests.Documents;

import java.io.Serializable;
import java.util.List;
import java.util.Set;

public interface DocumentsService<S extends Serializable, D extends SearchResult, E extends Exception> {
    String HIGHLIGHT_START_TAG = "<HavenSearch-QueryText-Placeholder>";
    String HIGHLIGHT_END_TAG = "</HavenSearch-QueryText-Placeholder>";

    Documents<D> queryTextIndex(final SearchRequest<S> searchRequest) throws E;

    Documents<D> queryTextIndexForPromotions(final SearchRequest<S> searchRequest) throws E;

    List<D> findSimilar(Set<S> indexes, String reference) throws E;

}

Change custom tag name [rev. matthew.gordon]


package a4_p01_JS_MJ_test;

public class a4Test {

}

package a4_p01_JS_MJ_test;

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

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

import org.jgrapht.Graph;
import org.jgrapht.WeightedGraph;
import org.jgrapht.graph.DefaultEdge;
import org.jgrapht.graph.DefaultWeightedEdge;
import org.jgrapht.graph.Pseudograph;
import org.junit.BeforeClass;
import org.junit.Test;

import a1_p01_JS_MJ.GraphParser;
import a1_p01_JS_MJ.GraphvizAdapter;
import a1_p01_JS_MJ.SearchResult;
import a2_p01_JS_MJ.AttributedNode;
import a2_p01_JS_MJ.GraphGenerator;
import a3_p01_JS_MJ.Kruskal;
import a4_p01_JS_MJ.Fleury;
import a4_p01_JS_MJ.Hierholzer;

public class a4Test {

	static Graph graphk5;
	static WeightedGraph<AttributedNode<String>, DefaultWeightedEdge> genGraph;

	@BeforeClass
	public static void init() {
		try {
			graphk5 = GraphParser.parseGraphFile("GraphK5.gka");
		} catch(Exception ex) {
			ex.printStackTrace();
		}
		genGraph = GraphGenerator.generateAttributedWeightedGraph(150, 30);
	}

	@Test
	public void fleury_test(){
		Fleury<String> fleury = new Fleury<String>();
		SearchResult result = fleury.search((Pseudograph<String, DefaultEdge>) graphk5);
		printTestResult("Test 1: Fleury - Graph K5", result);
		System.out.println("Test Green.");
		System.out.println("");
	}

	@Test
	public void hierholzer_test(){
		Hierholzer<String> hierholzer = new Hierholzer<String>();
		SearchResult result = hierholzer.algorithm((Pseudograph<String, DefaultEdge>) graphk5);
		printTestResult("Test 1: Fleury - Graph K5", result);
		System.out.println("Test Green.");
		System.out.println("");
	}

	public void printTestResult(String testname, SearchResult result){
		System.out.println(testname);
		System.out.print("Path: ");
		for(DefaultEdge s : (ArrayList<DefaultEdge>) result.getPath()){
			System.out.print(s+", ");
		}
		System.out.println("");
		System.out.println("Path Length " + result.getPathLength()+1);
		System.out.println("Accssess Counter: " + result.getAccsessCounter());
	}
}

Test with K5 graph for fleury and hierholzer added.


class forNameTest {
       public static void main(String argv[]) {
	      try {
		     Class.forName("loadThis");
		     Class c = Class.forName("loadThis", false,
		        new ClassLoader() {
			  public Class loadClass(String n, boolean resolve)
				      throws ClassNotFoundException {
				Class cl = findSystemClass(n);
				if (resolve) {
				      resolveClass(cl);
				}
				return cl;
			  }
		        });
		     System.out.println("constructor not called");
		     c.newInstance();
	      }
	      catch( Exception e ) {
		      System.out.println(e.getMessage());
		      e.printStackTrace();
	      }
       }
}

class loadThis {
      static {
	      try {
		      new loadThis();
	      }
	      catch( Exception e ) {
		      System.out.println(e.getMessage());
		      e.printStackTrace();
	      }
      }

      public loadThis() {
	      System.out.println("constructor called");
      }
}

/* Expected Output:
constructor called
constructor not called
constructor called
*/

class forNameTest {
       public static void main(String argv[]) {
	      try {
		     Class.forName("loadThis");
		     Class c = Class.forName("loadThis", false,
		        new ClassLoader() {
			  public Class loadClass(String n)
				throws ClassNotFoundException {
				return findSystemClass(n);
			  }
		        });
		     System.out.println("constructor not called");
		     c.newInstance();
	      }
	      catch( Exception e ) {
		      System.out.println(e.getMessage());
		      e.printStackTrace();
	      }
       }
}

class loadThis {
      static {
	      try {
		      new loadThis();
	      }
	      catch( Exception e ) {
		      System.out.println(e.getMessage());
		      e.printStackTrace();
	      }
      }

      public loadThis() {
	      System.out.println("constructor called");
      }
}

/* Expected Output:
constructor called
constructor not called
constructor called
*/

Revert to previous version.. it should still work.


package com.google.sps.servlets;

import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseAuthException;
import com.google.firebase.auth.SessionCookieOptions;
import com.google.sps.firebase.FirebaseAppManager;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/init")
public class SessionInit extends HttpServlet {
  // Return empty string if no comment, otherwise return text
  private String getParameter(HttpServletRequest request, String name, String defaultValue) {
    String value = request.getParameter(name);
    if (value == null) {
      return defaultValue;
    } else {
      return value;
    }
  }
}

package com.google.sps.servlets;

import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseAuthException;
import com.google.firebase.auth.SessionCookieOptions;
import com.google.sps.firebase.FirebaseAppManager;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/init")
public class SessionInit extends HttpServlet {
  // Return empty string if no comment, otherwise return text
  private String getParameter(HttpServletRequest request, String name, String defaultValue) {
    String value = request.getParameter(name);
    if (value == null) {
      return defaultValue;
    } else {
      return value;
    }
  }

  @Override
  public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
    String idToken = getParameter(request, "idToken", "");
    // Set session expiration to 5 days.
    long expiresIn = TimeUnit.DAYS.toMillis(5);
    SessionCookieOptions options = SessionCookieOptions.builder().setExpiresIn(expiresIn).build();
    try {
      // Create the session cookie. This will also verify the ID token in the process.
      // The session cookie will have the same claims as the ID token.
      String sessionCookie =
          FirebaseAuth.getInstance(FirebaseAppManager.getApp())
              .createSessionCookie(idToken, options);
      // Set cookie policy parameters as required.
      Cookie cookie = new Cookie("session", sessionCookie /* ... other parameters */);
      cookie.setMaxAge((int) TimeUnit.MILLISECONDS.toSeconds(expiresIn));
      response.addCookie(cookie);
    } catch (FirebaseAuthException e) {
      response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    }
  }
}

Create session cookie that expires in 5 days.


package see.integration;

import org.junit.experimental.theories.DataPoints;
import org.junit.experimental.theories.Theories;
import org.junit.experimental.theories.Theory;
import org.junit.runner.RunWith;
import see.See;
import see.tree.Node;

import static org.junit.Assert.assertEquals;

@RunWith(Theories.class)
public class TreeEquivalenceTest {
    See see = new See();

    @DataPoints
    public static final String[] data = {"a", "1+2", "sum(2,3)", "9+42+100500.0", "a = 5", "isDefined(crn)"};

    @Theory
    public void testEquivalence(String example) throws Exception {
        Node<Object> run1 = see.parseExpression(example);
        Node<Object> run2 = see.parseExpression(example);

        assertEquals(run1, run2);
    }
}

package see.integration;

import org.junit.experimental.theories.DataPoints;
import org.junit.experimental.theories.Theories;
import org.junit.experimental.theories.Theory;
import org.junit.runner.RunWith;
import see.See;
import see.tree.Node;

import static org.junit.Assert.assertEquals;

@RunWith(Theories.class)
public class TreeEquivalenceTest {
    See see = new See();

    @DataPoints
    public static final String[] data = {"a", "1+2", "sum(2,3)", "9+42+100500.0", "a = 5", "isDefined(crn)"};

    @Theory
    public void testEquivalence(String example) throws Exception {
        Node<Object> run1 = see.parseExpression(example);
        Node<Object> run2 = see.parseExpression(example);

        assertEquals(run1, run2);
        assertEquals(run1.hashCode(), run2.hashCode());
    }
}

Test for tree equivalence now checks hashCode


package com.axellience.vuegwt.client.definitions;

import com.axellience.vuegwt.client.VueComponent;

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

/**
 * A Cache for generated VueComponentDefinitions.
 * Using static initializer block, VueComponentDefinitions register an instance of themselves in
 * this Cache.
 * VueGWT then use this cache to get definitions for VueComponents.
 * @author Adrien Baron
 */
public class VueComponentDefinitionCache
{
    private static Map<Class<? extends VueComponent>, VueComponentDefinition>
        componentDefinitionsCache = new HashMap<>();

    public static void registerComponent(Class<? extends VueComponent> vueComponentClass,
        VueComponentDefinition componentDefinition)
    {
        componentDefinitionsCache.put(vueComponentClass, componentDefinition);
    }

    public static VueComponentDefinition getComponentDefinitionForClass(
        Class<? extends VueComponent> vueComponentClass)
    {
        VueComponentDefinition componentDefinition =
            componentDefinitionsCache.get(vueComponentClass);
        if (componentDefinition != null)
            return componentDefinition;

        throw new RuntimeException(
            "Couldn't find the given Component " + vueComponentClass.getCanonicalName() +
                ". Are you sure annotations are being processed?");
    }
}

package com.axellience.vuegwt.client.definitions;

import com.axellience.vuegwt.client.VueComponent;

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

/**
 * A Cache for generated VueComponentDefinitions.
 * Using static initializer block, VueComponentDefinitions register an instance of themselves in
 * this Cache.
 * VueGWT then use this cache to get definitions for VueComponents.
 * @author Adrien Baron
 */
public class VueComponentDefinitionCache
{
    private static Map<Class<? extends VueComponent>, VueComponentDefinition>
        componentDefinitionsCache = new HashMap<>();

    public static void registerComponent(Class<? extends VueComponent> vueComponentClass,
        VueComponentDefinition componentDefinition)
    {
        componentDefinitionsCache.put(vueComponentClass, componentDefinition);
    }

    public static VueComponentDefinition getComponentDefinitionForClass(
        Class<? extends VueComponent> vueComponentClass)
    {
        VueComponentDefinition componentDefinition =
            componentDefinitionsCache.get(vueComponentClass);
        if (componentDefinition != null)
            return componentDefinition;

        throw new RuntimeException("Couldn't find the given Component "
            + vueComponentClass.getCanonicalName()
            + ". Make sure your annotations are being processed, and that you added the -generateJsInteropExports flag to GWT.");
    }
}

Improve error message when Component is not found in Cache


/*
 * 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.hadoop.hbase.client;

import static org.apache.hadoop.hbase.HConstants.CLIENT_CONNECTION_REGISTRY_IMPL_CONF_KEY;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.util.ReflectionUtils;
import org.apache.yetus.audience.InterfaceAudience;

/**
 * Factory class to get the instance of configured connection registry.
 */
@InterfaceAudience.Private
final class ConnectionRegistryFactory {

  private ConnectionRegistryFactory() {
  }

  /**
   * @return The connection registry implementation to use.
   */
  static ConnectionRegistry getRegistry(Configuration conf) {
    Class<? extends ConnectionRegistry> clazz = conf.getClass(
        CLIENT_CONNECTION_REGISTRY_IMPL_CONF_KEY, ZKConnectionRegistry.class,
        ConnectionRegistry.class);
    return ReflectionUtils.newInstance(clazz, conf);
  }
}

/*
 * 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.hadoop.hbase.client;

import static org.apache.hadoop.hbase.HConstants.CLIENT_CONNECTION_REGISTRY_IMPL_CONF_KEY;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.util.ReflectionUtils;
import org.apache.yetus.audience.InterfaceAudience;

/**
 * Factory class to get the instance of configured connection registry.
 */
@InterfaceAudience.Private
final class ConnectionRegistryFactory {

  private ConnectionRegistryFactory() {
  }

  /**
   * @return The connection registry implementation to use.
   */
  static ConnectionRegistry getRegistry(Configuration conf) {
    Class<? extends ConnectionRegistry> clazz = conf.getClass(
        CLIENT_CONNECTION_REGISTRY_IMPL_CONF_KEY, MasterRegistry.class,
        ConnectionRegistry.class);
    return ReflectionUtils.newInstance(clazz, conf);
  }
}

Revert "Switch the default registry to ZK based"

This reverts commit 558ee079fd04dfab8e61eca10ee98ab5bac89dfa because
it wasn't tagged with a jira ID. Will be re-applied.


package com.example.client;

import jsinterop.annotations.JsMethod;
import jsinterop.annotations.JsPackage;
import jsinterop.annotations.JsType;

@JsType(isNative = true)
public class Dragula {

	@JsMethod(namespace = JsPackage.GLOBAL)
	public native static Dragula dragula(Element... elements);

}

package com.example.client;

import jsinterop.annotations.JsMethod;
import jsinterop.annotations.JsOverlay;
import jsinterop.annotations.JsPackage;
import jsinterop.annotations.JsProperty;
import jsinterop.annotations.JsType;

@JsType(isNative = true)
public class Dragula {

	@JsMethod(namespace = JsPackage.GLOBAL)
	public native static Dragula dragula(Element... elements);

	@JsMethod(namespace = JsPackage.GLOBAL)
	public native static Dragula dragula(Element[] elements, DragulaOptions options);

	@JsMethod(namespace = JsPackage.GLOBAL)
	public native static Dragula dragula(DragulaOptions options);

	@JsOverlay
	public static Dragula dragula(Element element, DragulaOptions options) {
		return dragula(new Element[] { element }, options);
	}

	@JsOverlay
	public static Dragula dragula(Element element, Element element2, DragulaOptions options) {
		return dragula(new Element[] { element, element2 }, options);
	}

	@JsOverlay
	public static Dragula dragula(Element element, Element element2, Element element3, DragulaOptions options) {
		return dragula(new Element[] { element, element2, element3 }, options);
	}

	@JsOverlay
	public static Dragula dragula(DragulaOptions options, Element... elements) {
		return dragula(elements, options);
	}

	@JsProperty
	public native JsArray<Element> getContainers();

}

Add more methods to dragula

Add more methods to dragula


package interfaces;

import java.util.List;

public interface Semantics {

	public List<Integer> getPossibleActions(Graph graph) throws Exception;

	public Graph executeAction(Graph graph, List<Integer> ids) throws Exception;

	public boolean isFinished(Graph graph) throws Exception;

}

Remove some weird unnecessary whitespace


package codesample.java10;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

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

        /* Type-inference (Note: does not work for non-local variables, array initializers,
        lambdas (when you create lambda. Returning result into var is OK) */
        var message = "Hello, world!";
        System.out.println(message);

        // Note: This will be array list of Objects
        var empList = new ArrayList<>();

        /* copyOf for collections */
        var list = List.of(1,2,3);
        var copy = List.copyOf(list);

        /* unmodifiable collections on collectors*/
        var set = copy.stream()
                .map(value -> value * 3)
                .collect(Collectors.toUnmodifiableSet());

        /* orElseThrow without arguments throws NoSuchElementException */
        var oneElementList = List.of(5);
        var onlyElement = oneElementList.stream()
                .filter(value -> value > 3)
                .findFirst()
                .orElseThrow();
    }
}

package codesample.java10;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

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

        /* Type-inference (Note: does not work for non-local variables, array initializers,
        lambdas (when you create lambda. Returning result into var is OK) */
        var message = "Hello, world!";

        var кукареку = new Кукареку<Кукарек>();

        System.out.println(message);

        // Note: This will be array list of Objects
        var empList = new ArrayList<>();

        /* copyOf for collections */
        var list = List.of(1,2,3);
        var copy = List.copyOf(list);

        /* unmodifiable collections on collectors*/
        var set = copy.stream()
                .map(value -> value * 3)
                .collect(Collectors.toUnmodifiableSet());

        /* orElseThrow without arguments throws NoSuchElementException */
        var oneElementList = List.of(5);
        var onlyElement = oneElementList.stream()
                .filter(value -> value > 3)
                .findFirst()
                .orElseThrow();

        var var = Var.var();
        var.var().var().var().var();

        var listOfInt = new ArrayList<Integer>(List.of(1,2,3));
        var copyy = Collections.unmodifiableList(listOfInt);
        System.out.println(copyy);
        listOfInt.add(4);
        System.out.println(copyy);
    }

    public interface Animal {}
    public interface Cat extends Animal { void meow(); }
    public interface Dog extends Animal { void woof(); }

    void makeSound(Animal animal) {
        var catDog = (Cat & Dog) animal;
        catDog.meow();
        catDog.woof();
    }

    static class Кукареку<T> {

    }

    static class Кукарек {

    }

    public static class Var {
        public static Var var() {
            return new Var();
        }
    }
}

Add new java 10 code

Add new java 10 code


package com.dnmaze.dncli.util;

import jdk.nashorn.api.scripting.NashornScriptEngineFactory;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import javax.script.Compilable;
import javax.script.CompiledScript;
import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptException;

/**
 * Created by blei on 6/19/16.
 */
public class JsUtil {
  /**
   *
A helper method to compile a javascript file and return
   * an engine that is common.

   *
   * @param script the javascript file
   * @return the script engine
   * @throws FileNotFoundException if file was not found
   * @throws ScriptException       if cannot eval the javascript file
   */
  public static Invocable compileAndEval(File script)
      throws ScriptException, FileNotFoundException {
    File scriptDir = script.getParentFile();
    NashornScriptEngineFactory scriptEngineFactory = new NashornScriptEngineFactory();
    ScriptEngine scriptEngine =
        scriptEngineFactory.getScriptEngine("-Ddncli.cwd=" + scriptDir.getAbsolutePath(),
            "-scripting");

    FileInputStream fis = new FileInputStream(script);
    InputStreamReader isr = new InputStreamReader(fis, StandardCharsets.UTF_8);
    CompiledScript compiledScript = ((Compilable) scriptEngine).compile(isr);

    compiledScript.eval();

    return (Invocable) compiledScript.getEngine();
  }
}

package com.dnmaze.dncli.util;

import jdk.nashorn.api.scripting.NashornScriptEngineFactory;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import javax.script.Compilable;
import javax.script.CompiledScript;
import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptException;

/**
 * Created by blei on 6/19/16.
 */
public class JsUtil {
  /**
   *
A helper method to compile a javascript file and return
   * an engine that is common.

   *
   * @param script the javascript file
   * @return the script engine
   * @throws FileNotFoundException if file was not found
   * @throws ScriptException       if cannot eval the javascript file
   */
  public static Invocable compileAndEval(File script)
      throws ScriptException, FileNotFoundException {
    File scriptDir = script.getParentFile();
    NashornScriptEngineFactory scriptEngineFactory = new NashornScriptEngineFactory();
    ScriptEngine scriptEngine =
        scriptEngineFactory.getScriptEngine("-Ddncli.cwd=" + scriptDir.getAbsolutePath(),
            "-scripting", "--language=es6");

    FileInputStream fis = new FileInputStream(script);
    InputStreamReader isr = new InputStreamReader(fis, StandardCharsets.UTF_8);
    CompiledScript compiledScript = ((Compilable) scriptEngine).compile(isr);

    compiledScript.eval();

    return (Invocable) compiledScript.getEngine();
  }
}

Use es6 language for the newer features.


package benchmarking;

import converters.JsonConverter;
import datamodel.PerformanceSelfMonitoring;
import mongo.MongoManager;

public class Monitoring {
    PerformanceMonitoring performanceMonitoring = new PerformanceMonitoring();
    long startTime = -1, endTime = -1, totalTime = -1;

    public void startMonitoring() {
        performanceMonitoring.startMonitoring();
        startTime = System.currentTimeMillis();
    }

    public void stopMonitoring() {
        performanceMonitoring.stopMonitoring();
        endTime = System.currentTimeMillis();
        totalTime = endTime - startTime;
    }

    public PerformanceSelfMonitoring getResults(long pid) {
        PerformanceSelfMonitoring perfSelf = new PerformanceSelfMonitoring();
        perfSelf.setCpuUsageResults(performanceMonitoring.parseForPid(pid));
        perfSelf.setExecutionTime(totalTime);

        return perfSelf;
    }

    public void saveResultsInDb (long pid, MongoManager mm) {
        Thread writeRestuls = new Thread(new Runnable() {
            @Override
            public void run() {
                PerformanceSelfMonitoring perfSelf = new PerformanceSelfMonitoring();
                perfSelf.setCpuUsageResults(performanceMonitoring.parseForPid(pid));
                perfSelf.setExecutionTime(totalTime);
                mm.pushJson(JsonConverter.objectToJsonString(perfSelf), "selfPerformance");            }
        });
        writeRestuls.start();
    }

}

package benchmarking;

import converters.JsonConverter;
import datamodel.monitoring.PerformanceMonitoringResults;
import mongo.MongoManager;

public class Monitoring {
    PerformanceMonitoring performanceMonitoring = new PerformanceMonitoring();
    long startTime = -1, endTime = -1, totalTime = -1;

    public void startMonitoring() {
        performanceMonitoring.startMonitoring();
        startTime = System.currentTimeMillis();
    }

    public void stopMonitoring() {
        performanceMonitoring.stopMonitoring();
        endTime = System.currentTimeMillis();
        totalTime = endTime - startTime;
    }

    public void saveResultsInDb (long pid, MongoManager mm) {
        Thread writeRestuls = new Thread(new Runnable() {
            @Override
            public void run() {
                PerformanceMonitoringResults performanceMonitoringResults = new PerformanceMonitoringResults();
                performanceMonitoringResults.setSubcomponents(performanceMonitoring.parseForPid(pid));
                mm.pushJson(JsonConverter.objectToJsonString(performanceMonitoringResults), "selfPerformanceMonitoring");
            }
        });
        writeRestuls.start();
    }

}

Use PerformanceMontoringResults as a datamodel.


/**
 * 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.jena.base;

import java.io.File ;

public class Sys {
    /** Is this windows? */
    public static final boolean isWindows = (File.pathSeparatorChar == ';') ;
}

/**
 * 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.jena.base;

import org.apache.commons.lang3.SystemUtils;

public class Sys {
    /** Is this windows? */
    public static final boolean isWindows = SystemUtils.IS_OS_WINDOWS;

    /** Is this MacOS? */
    public static final boolean isMacOS = SystemUtils.IS_OS_MAC;
}

Use apache.common.lang3 for OS determination.


package com.brg.controller;

import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.web.WebView;

import java.net.URL;
import java.util.ResourceBundle;

public class DefineTab implements Initializable, TabControllerImpl {

    @FXML private WebView webView;

    @Override
    public void initialize(URL location, ResourceBundle resources) {
        this.updateContents();
    }

    @Override
    public void updateContents() {
        this.webView.getEngine().load("https://ondora02.hu.nl:8080/ords/f?p=1567:LOGIN_DESKTOP:15608328208288:::::");
        this.webView.autosize();
    }
}

package com.brg.controller;

import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.web.WebView;

import java.net.URL;
import java.util.ResourceBundle;

public class DefineTab implements Initializable, TabControllerImpl {

    @FXML private WebView webView;

    @Override
    public void initialize(URL location, ResourceBundle resources) {
        this.updateContents();
        this.webView.getEngine().load("https://ondora02.hu.nl:8080/ords/f?p=1567:LOGIN_DESKTOP:15608328208288:::::");
    }

    @Override
    public void updateContents() {
        this.webView.autosize();
    }
}

Define tab will not reload automatically anymore.


package fi.helsinki.cs.tmc.cli.io;

public abstract class Io {

    public abstract void print(String str);

    public void print(Object obj) {
        print(String.valueOf(obj));
    }

    public void println(String str) {
        print(str + "\n");
    }

    public abstract String readLine(String prompt);

    public abstract String readPassword(String prompt);
}

package fi.helsinki.cs.tmc.cli.io;

import java.io.IOException;
import java.io.Writer;
import java.util.Arrays;

public abstract class Io extends Writer {

    public abstract void print(String str);

    public void print(Object obj) {
        print(String.valueOf(obj));
    }

    public void println(String str) {
        print(str + "\n");
    }

    public abstract String readLine(String prompt);

    public abstract String readPassword(String prompt);

    @Override
    public void write(char[] cbuf, int offset, int len) throws IOException {
        print(new String(Arrays.copyOfRange(cbuf, offset, offset + len)));
    }

    @Override
    public void flush() throws IOException {
    }

    @Override
    public void close() throws IOException {
    }
}

Extend the writer class in the IO class.


package mil.dds.anet.resources;

import java.util.List;

import javax.annotation.security.RolesAllowed;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.core.Response;

import mil.dds.anet.AnetObjectEngine;
import mil.dds.anet.beans.AdminSetting;
import mil.dds.anet.database.AdminDao;
import mil.dds.anet.graphql.GraphQLFetcher;
import mil.dds.anet.graphql.IGraphQLResource;
import mil.dds.anet.views.AbstractAnetBean;

@Path("/api/admin")
public class AdminResource implements IGraphQLResource {

	private AdminDao dao;

	public AdminResource(AnetObjectEngine engine) {
		this.dao = engine.getAdminDao();
	}

	@GET
	@GraphQLFetcher
	@Path("/")
	public List<AdminSetting> getAll() {
		return dao.getAllSettings();
	}

	@POST
	@Path("/save")
	@RolesAllowed("ADMINISTRATOR")
	public Response save(AdminSetting setting) {
		dao.saveSetting(setting);
		return Response.ok().build();
	}

	@Override
	public String getDescription() { return "Admin Resources";}
	@Override
	public Class<? extends AbstractAnetBean> getBeanClass() { return AdminSetting.class; }

}

package mil.dds.anet.resources;

import java.util.List;

import javax.annotation.security.RolesAllowed;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.core.Response;

import mil.dds.anet.AnetObjectEngine;
import mil.dds.anet.beans.AdminSetting;
import mil.dds.anet.database.AdminDao;
import mil.dds.anet.graphql.GraphQLFetcher;
import mil.dds.anet.graphql.IGraphQLResource;
import mil.dds.anet.views.AbstractAnetBean;

@Path("/api/admin")
public class AdminResource implements IGraphQLResource {

	private AdminDao dao;

	public AdminResource(AnetObjectEngine engine) {
		this.dao = engine.getAdminDao();
	}

	@GET
	@GraphQLFetcher
	@Path("/")
	public List<AdminSetting> getAll() {
		return dao.getAllSettings();
	}

	@POST
	@Path("/save")
	@RolesAllowed("ADMINISTRATOR")
	public Response save(List<AdminSetting> settings) {
		for (AdminSetting setting : settings) {
			dao.saveSetting(setting);
		}

		return Response.ok().build();
	}

	@Override
	public String getDescription() { return "Admin Resources";}
	@Override
	public Class<? extends AbstractAnetBean> getBeanClass() { return AdminSetting.class; }

}

Change adminSettings/save to accept a list of settings instead of just one


package org.kohsuke.github;

import java.util.Locale;

/**
 * Hook event type.
 *
 * @author Kohsuke Kawaguchi
 * @see GHEventInfo
 * @see Event type reference
 */
public enum GHEvent {
    COMMIT_COMMENT,
    CREATE,
    DELETE,
    DEPLOYMENT,
    DEPLOYMENT_STATUS,
    DOWNLOAD,
    FOLLOW,
    FORK,
    FORK_APPLY,
    GIST,
    GOLLUM,
    ISSUE_COMMENT,
    ISSUES,
    MEMBER,
    PAGE_BUILD,
    PUBLIC,
    PULL_REQUEST,
    PULL_REQUEST_REVIEW_COMMENT,
    PUSH,
    RELEASE,
    REPOSITORY, // only valid for org hooks
    STATUS,
    TEAM_ADD,
    WATCH,
    PING,
    /**
     * Special event type that means "every possible event"
     */
    ALL;

    /**
     * Returns GitHub's internal representation of this event.
     */
    String symbol() {
        if (this==ALL)  return "*";
        return name().toLowerCase(Locale.ENGLISH);
    }
}

package org.kohsuke.github;

import java.util.Locale;

/**
 * Hook event type.
 *
 * @author Kohsuke Kawaguchi
 * @see GHEventInfo
 * @see Event type reference
 */
public enum GHEvent {
    COMMIT_COMMENT,
    CREATE,
    DELETE,
    DEPLOYMENT,
    DEPLOYMENT_STATUS,
    DOWNLOAD,
    FOLLOW,
    FORK,
    FORK_APPLY,
    GIST,
    GOLLUM,
    INSTALLATION,
    INSTALLATION_REPOSITORIES,
    ISSUE_COMMENT,
    ISSUES,
    LABEL,
    MARKETPLACE_PURCHASE,
    MEMBER,
    MEMBERSHIP,
    MILESTONE,
    ORGANIZATION,
    ORG_BLOCK,
    PAGE_BUILD,
    PROJECT_CARD,
    PROJECT_COLUMN,
    PROJECT,
    PUBLIC,
    PULL_REQUEST,
    PULL_REQUEST_REVIEW,
    PULL_REQUEST_REVIEW_COMMENT,
    PUSH,
    RELEASE,
    REPOSITORY, // only valid for org hooks
    STATUS,
    TEAM,
    TEAM_ADD,
    WATCH,
    PING,
    /**
     * Special event type that means "every possible event"
     */
    ALL;

    /**
     * Returns GitHub's internal representation of this event.
     */
    String symbol() {
        if (this==ALL)  return "*";
        return name().toLowerCase(Locale.ENGLISH);
    }
}

Add missing event types used by repository webhooks


package ee.ioc.phon.android.speak.service;

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

public class Constants {

    public static final Set<Character> CHARACTERS_WS =
            new HashSet<>(Arrays.asList(new Character[]{' ', '\n', '\t'}));

    // Symbols that should not be preceded by space in a written text.
    public static final Set<Character> CHARACTERS_PUNCT =
            new HashSet<>(Arrays.asList(new Character[]{',', ':', ';', '.', '!', '?'}));

    // Symbols after which the next word should be capitalized.
    public static final Set<Character> CHARACTERS_EOS =
            new HashSet<>(Arrays.asList(new Character[]{'.', '!', '?'}));
}

package ee.ioc.phon.android.speak.service;

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

public class Constants {

    public static final Set<Character> CHARACTERS_WS =
            new HashSet<>(Arrays.asList(new Character[]{' ', '\n', '\t'}));

    // Symbols that should not be preceded by space in a written text.
    public static final Set<Character> CHARACTERS_PUNCT =
            new HashSet<>(Arrays.asList(new Character[]{',', ':', ';', '.', '!', '?'}));

    // Symbols after which the next word should be capitalized.
    // We include ) because ;-) often finishes a sentence.
    public static final Set<Character> CHARACTERS_EOS =
            new HashSet<>(Arrays.asList(new Character[]{'.', '!', '?', ')'}));
}

Add ) as sentence end marker to cap word after :-)


package city.smug.projectmercury.messaging;

import java.util.ArrayList;

import city.smug.projectmercury.sms.SmsHandler;

public class Messenger {
    protected ArrayList<Group> groups = new ArrayList<>();

    protected static Messenger instance = new Messenger();
    public static Messenger getInstance() {
        return instance;
    }

    protected Messenger() {}

    public void send(Message message) {
        if (ConnectionStatus.getInstance().isConnected()) {
            // Send over TCP
        }
        else {
            SmsHandler.getInstance().send(message);
        }
    }

    public void receive(Message message) {
        for (Group group : groups) {
            if (group.getId() == message.getTo().getId()) {
                group.getQueue().insert(message);
                break;
            }
        }
    }
}

package city.smug.projectmercury.messaging;

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.Socket;
import java.util.ArrayList;
import java.util.Calendar;

import city.smug.projectmercury.api.Rest;
import city.smug.projectmercury.sms.SmsHandler;

public class Messenger {
    protected ArrayList<Group> groups = new ArrayList<>();
    protected NetworkRunnable netRunner = new NetworkRunnable();

    protected static Messenger instance = new Messenger();
    public static Messenger getInstance() {
        return instance;
    }

    protected class NetworkRunnable implements Runnable {
        Socket socket = null;

        public void send(Message message) {
            if (socket == null)
                return;

            try {
                DataOutputStream stream = new DataOutputStream(socket.getOutputStream());
                stream.writeLong(-1L);
                stream.writeLong(message.getFrom().getId());
                stream.writeLong(message.getTo().getId());
                stream.writeUTF(message.getContent());
                stream.flush();
            }
            catch (Exception ignored) {}
        }

        @Override
        public void run() {
            try {
                Socket socket = new Socket("pdc-amd01.poly.edu", 8080);
                DataInputStream stream = new DataInputStream(socket.getInputStream());

                while (true) {
                    receive(new Message(stream.readLong(), Rest.getUser(stream.readLong()), Rest.getGroup(stream.readLong()),
                            Calendar.getInstance().getTime(), stream.readUTF()));
                }
            }
            catch (Exception ignored) {}
        }
    }

    protected Messenger() {
        new Thread(netRunner).start();
    }

    public void send(Message message) {
        if (ConnectionStatus.getInstance().isConnected()) {
            try {
                netRunner.send(message);
            }
            catch (Exception ignored) {
                SmsHandler.getInstance().send(message);
            }
        }
        else {
            SmsHandler.getInstance().send(message);
        }
    }

    public void receive(Message message) {
        for (Group group : groups) {
            if (group.getId() == message.getTo().getId()) {
                group.getQueue().insert(message);
                break;
            }
        }
    }
}

Send and receive TCP messages

Send and receive TCP messages


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

package org.gradle.internal.logging.util;

/**
 * This class contains references to log4j-core which had a critical vulnerability,
 * see CVE-2021-44228.
 */
public class Log4jBannedVersion {
    public static final String LOG4J2_CORE_COORDINATES = "org.apache.logging.log4j:log4j-core";
    public static final String LOG4J2_CORE_VULNERABLE_VERSION_RANGE = "[2.0, 2.15[";
    public static final String LOG4J2_CORE_REQUIRED_VERSION = "2.16.0";
}

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

package org.gradle.internal.logging.util;

/**
 * This class contains references to log4j-core which had a critical vulnerability,
 * see CVE-2021-44228.
 */
public class Log4jBannedVersion {
    public static final String LOG4J2_CORE_COORDINATES = "org.apache.logging.log4j:log4j-core";
    public static final String LOG4J2_CORE_VULNERABLE_VERSION_RANGE = "[2.0, 2.16)";
    public static final String LOG4J2_CORE_REQUIRED_VERSION = "2.16.0";
}

Mark Log4j 2.15 as vulnerable

Mark Log4j 2.15 as vulnerable

Follows publication of
https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2021-45046

Issue #19300


package com.yammer.dropwizard.client;

import javax.validation.constraints.Max;
import javax.validation.constraints.Min;

public class JerseyClientConfiguration extends HttpClientConfiguration {
    // TODO: 11/16/11 <coda> -- validate minThreads <= maxThreads

    @Max(16 * 1024)
    @Min(1)
    private int minThreads;

    @Max(16 * 1024)
    @Min(1)
    private int maxThreads;

    public int getMinThreads() {
        return minThreads;
    }

    public void setMinThreads(int minThreads) {
        this.minThreads = minThreads;
    }

    public int getMaxThreads() {
        return maxThreads;
    }

    public void setMaxThreads(int maxThreads) {
        this.maxThreads = maxThreads;
    }
}

package com.yammer.dropwizard.client;

import javax.validation.constraints.Max;
import javax.validation.constraints.Min;

public class JerseyClientConfiguration extends HttpClientConfiguration {
    // TODO: 11/16/11 <coda> -- validate minThreads <= maxThreads

    @Max(16 * 1024)
    @Min(1)
    private int minThreads = 1;

    @Max(16 * 1024)
    @Min(1)
    private int maxThreads = 128;

    public int getMinThreads() {
        return minThreads;
    }

    public void setMinThreads(int minThreads) {
        this.minThreads = minThreads;
    }

    public int getMaxThreads() {
        return maxThreads;
    }

    public void setMaxThreads(int maxThreads) {
        this.maxThreads = maxThreads;
    }
}

Make sure the JerseryClient thread pools are sized.


package com.conveyal.gtfs.validator.json;

import java.util.Collection;
import java.util.Date;

import com.conveyal.gtfs.model.ValidationResult;

/**
 * A class to hold all of the results of a validation on a single feed.
 * Not to be confused with {@link com.conveyal.gtfs.model.ValidationResult}, which holds all instances of
 * a particular type of error.
 * @author mattwigway
 *
 */
public class FeedValidationResult {
	/** Were we able to load the GTFS at all (note that this should only indicate corrupted files,
	 * not missing ones; that should raise an exception instead.)
	 */
	public LoadStatus loadStatus;

	/**
	 * Additional description of why the feed failed to load.
	 */
	public String loadFailureReason;

	/**
	 * The name of the feed on the file system
	 */
	public String feedFileName;

	/**
	 * All of the agencies in the feed
	 */
	public Collection<String> agencies;

	public ValidationResult routes;
	public ValidationResult stops;
	public ValidationResult trips;
	public ValidationResult shapes;

	// statistics
	public int agencyCount;
	public int routeCount;
	public int tripCount;
	public int stopTimesCount;

	/** The first date the feed has service, either in calendar.txt or calendar_dates.txt */
	public Date startDate;

	/** The last date the feed has service, either in calendar.txt or calendar_dates.txt */
	public Date endDate;
}

package com.conveyal.gtfs.validator.json;

import java.util.Collection;
import java.util.Date;

import com.conveyal.gtfs.model.ValidationResult;
import com.fasterxml.jackson.annotation.JsonProperty;

/**
 * A class to hold all of the results of a validation on a single feed.
 * Not to be confused with {@link com.conveyal.gtfs.model.ValidationResult}, which holds all instances of
 * a particular type of error.
 * @author mattwigway
 *
 */
public class FeedValidationResult {
	/** Were we able to load the GTFS at all (note that this should only indicate corrupted files,
	 * not missing ones; that should raise an exception instead.)
	 */
        @JsonProperty
	public LoadStatus loadStatus;

	/**
	 * Additional description of why the feed failed to load.
	 */
	public String loadFailureReason;

	/**
	 * The name of the feed on the file system
	 */
	public String feedFileName;

	/**
	 * All of the agencies in the feed
	 */
	public Collection<String> agencies;

	public ValidationResult routes;
	public ValidationResult stops;
	public ValidationResult trips;
	public ValidationResult shapes;

	// statistics
	public int agencyCount;
	public int routeCount;
	public int tripCount;
	public int stopTimesCount;

	/** The first date the feed has service, either in calendar.txt or calendar_dates.txt */
	public Date startDate;

	/** The last date the feed has service, either in calendar.txt or calendar_dates.txt */
	public Date endDate;
}

Make loadstatus end up in the json.

Make loadstatus end up in the json.


package com.quantxt.io.model;

public interface Cell {

    Row getRow();

    CellType getCellType();

    CellStyle getCellStyle();

    void setCellStyle(CellStyle cellStyle);

    String getStringCellValue();

    String getFormulaCellValue();

    boolean getBooleanCellValue();

    double getNumericCellValue();

    void setCellValue(String value);

    void setCellValue(boolean value);

    void setCellValue(double value);

    void setCellType(CellType cellType);

}

package com.quantxt.io.model;

public interface Cell {

    Row getRow();

    CellType getCellType();

    CellStyle getCellStyle();

    void setCellStyle(CellStyle cellStyle);

    String getStringCellValue();

    String getFormulaCellValue();

    boolean getBooleanCellValue();

    double getNumericCellValue();

    void setCellValue(String value);

    void setCellValue(boolean value);

    void setCellValue(double value);

    void setCellType(CellType cellType);

    int getCellIndex();

}

Add getter for cellIndex field

Add getter for cellIndex field


package com.shippo.model;

public enum LabelFileType {
	PNG, PDF, PDF_4X6, ZPLII
}

package com.shippo.model;

public enum LabelFileType {
	PNG, PDF, PDF_4x6, ZPLII
}

Correct label name - thanks @vinhhv!

Correct label name - thanks @vinhhv!