text:
package net.jforum.view.admin;

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

import net.jforum.dao.CategoryDAO;
import net.jforum.dao.DataAccessDriver;
import net.jforum.dao.ForumDAO;
import net.jforum.dao.GroupSecurityDAO;
import net.jforum.dao.MailIntegrationDAO;
import net.jforum.dao.TopicDAO;
import net.jforum.entities.Category;
import net.jforum.entities.Forum;
import net.jforum.entities.MailIntegration;
import net.jforum.repository.ForumRepository;
import net.jforum.repository.RolesRepository;
import net.jforum.repository.SecurityRepository;
import net.jforum.security.PermissionControl;
import net.jforum.security.Role;
import net.jforum.security.RoleValue;
import net.jforum.security.RoleValueCollection;
import net.jforum.security.SecurityConstants;
import net.jforum.util.TreeGroup;
import net.jforum.util.preferences.TemplateKeys;
import net.jforum.view.admin.common.ModerationCommon;

/**
 * @author Rafael Steil
 * @version $Id$
 */
public class ForumAction extends AdminCommand
{
	private static final String FORUM_ID = "forum_id";
	/**
	 * Listing
	 */
	public void list()
	{
		this.context.put("categories", DataAccessDriver.getInstance().newCategoryDAO().selectAll());
		this.context.put("repository", new ForumRepository());
		this.setTemplateName(TemplateKeys.FORUM_ADMIN_LIST);
	}

	/**
	 * One more, one more
	 */
	public void insert()
	{
		final CategoryDAO categoryDao = DataAccessDriver.getInstance().newCategoryDAO();

		this.context.put("groups", new TreeGroup().getNodes());
		this.context.put("selectedList", new ArrayList<Forum>());
		this.setTemplateName(TemplateKeys.FORUM_ADMIN_INSERT);
		this.context.put("categories",categoryDao.selectAll());
		this.context.put("action", "insertSave");
	}

	/**
	 * Edit
	 */
	public void edit()
	{
		final int forumId = this.request.getIntParameter(FORUM_ID);
		final ForumDAO forumDao = DataAccessDriver.getInstance().newForumDAO();

		final CategoryDAO categoryDao = DataAccessDriver.getInstance().newCategoryDAO();

		this.setTemplateName(TemplateKeys.FORUM_ADMIN_EDIT);
		this.context.put("categories", categoryDao.selectAll());
		this.context.put("action", "editSave");
		this.context.put("forum", forumDao.selectById(forumId));

		// Mail Integration
		final MailIntegrationDAO integrationDao = DataAccessDriver.getInstance().newMailIntegrationDAO();
		this.context.put("mailIntegration", integrationDao.find(forumId));
	}

	public void editSave()
	{
		ForumDAO forumDao = DataAccessDriver.getInstance().newForumDAO();
		Forum forum = forumDao.selectById(this.request.getIntParameter(FORUM_ID));

		boolean moderated = forum.isModerated();
		int categoryId = forum.getCategoryId();

		forum.setDescription(this.request.getParameter("description"));
		forum.setIdCategories(this.request.getIntParameter("categories_id"));
		forum.setName(this.request.getParameter("forum_name"));
		forum.setModerated("1".equals(this.request.getParameter("moderate")));

		forumDao.update(forum);

		if (moderated != forum.isModerated()) {
			new ModerationCommon().setTopicModerationStatus(forum.getId(), forum.isModerated());
		}

		if (categoryId != forum.getCategoryId()) {
			forum.setIdCategories(categoryId);
			ForumRepository.removeForum(forum);

			forum.setIdCategories(this.request.getIntParameter("categories_id"));
			ForumRepository.addForum(forum);
		}
		else {
			ForumRepository.reloadForum(forum.getId());
		}

		this.handleMailIntegration();

		this.list();
	}

	private void handleMailIntegration()
	{
		int forumId = this.request.getIntParameter(FORUM_ID);
		MailIntegrationDAO dao = DataAccessDriver.getInstance().newMailIntegrationDAO();

		if (!"1".equals(this.request.getParameter("mail_integration"))) {
			dao.delete(forumId);
		}
		else {
			boolean exists = dao.find(forumId) != null;

			MailIntegration mailIntegration = this.fillMailIntegrationFromRequest();

			if (exists) {
				dao.update(mailIntegration);
			}
			else {
				dao.add(mailIntegration);
			}
		}
	}

	private MailIntegration fillMailIntegrationFromRequest()
	{
		MailIntegration mailIntegration = new MailIntegration();

		mailIntegration.setForumId(this.request.getIntParameter(FORUM_ID));
		mailIntegration.setForumEmail(this.request.getParameter("forum_email"));
		mailIntegration.setPopHost(this.request.getParameter("pop_host"));
		mailIntegration.setPopUsername(this.request.getParameter("pop_username"));
		mailIntegration.setPopPassword(this.request.getParameter("pop_password"));
		mailIntegration.setPopPort(this.request.getIntParameter("pop_port"));
		mailIntegration.setSsl("1".equals(this.request.getParameter("requires_ssl")));

		return mailIntegration;
	}

	public void up()
	{
		this.processOrdering(true);
	}

	public void down()
	{
		this.processOrdering(false);
	}

	private void processOrdering(final boolean isUp)
	{
		Forum toChange = new Forum(ForumRepository.getForum(Integer.parseInt(
				this.request.getParameter(FORUM_ID))));

		Category category = ForumRepository.getCategory(toChange.getCategoryId());
		List<Forum> forums = new ArrayList<Forum>(category.getForums());
		int index = forums.indexOf(toChange);

		if (index == -1 || (isUp && index == 0) || (!isUp && index + 1 == forums.size())) {
			this.list();
			return;
		}

		ForumDAO fm = DataAccessDriver.getInstance().newForumDAO();

		if (isUp) {
			// Get the forum which comes *before* the forum we're changing
			Forum otherForum = new Forum(forums.get(index - 1));
			fm.setOrderUp(toChange, otherForum);
		}
		else {
			// Get the forum which comes *after* the forum we're changing
			Forum otherForum = new Forum(forums.get(index + 1));
			fm.setOrderDown(toChange, otherForum);
		}

		category.changeForumOrder(toChange);
		ForumRepository.refreshCategory(category);

		this.list();
	}

	/**
	 * Delete
	 */
	public void delete()
	{
		String ids[] = this.request.getParameterValues(FORUM_ID);

		ForumDAO forumDao = DataAccessDriver.getInstance().newForumDAO();
		TopicDAO topicDao = DataAccessDriver.getInstance().newTopicDAO();

		if (ids != null) {
			for (int i = 0; i < ids.length; i++) {
				int forumId = Integer.parseInt(ids[i]);

				topicDao.deleteByForum(forumId);
				forumDao.delete(forumId);

				ForumRepository.removeForum(ForumRepository.getForum(forumId));
			}

			SecurityRepository.clean();
			RolesRepository.clear();
		}

		this.list();
	}

	/**
	 * A new one
	 */
	public void insertSave()
	{
		Forum forum = new Forum();
		forum.setDescription(this.request.getParameter("description"));
		forum.setIdCategories(this.request.getIntParameter("categories_id"));
		forum.setName(this.request.getParameter("forum_name"));
		forum.setModerated("1".equals(this.request.getParameter("moderate")));

		int forumId = DataAccessDriver.getInstance().newForumDAO().addNew(forum);
		forum.setId(forumId);

		ForumRepository.addForum(forum);

		GroupSecurityDAO gmodel = DataAccessDriver.getInstance().newGroupSecurityDAO();
		PermissionControl pc = new PermissionControl();
		pc.setSecurityModel(gmodel);

		String[] allGroups = this.request.getParameterValues("groups");

		// Access
		String[] groups = this.request.getParameterValues("groupsAccess");
		if (groups != null) {
			this.addRole(pc, SecurityConstants.PERM_FORUM, forum.getId(), groups);
		}
		else {
			this.addRole(pc, SecurityConstants.PERM_FORUM, forum.getId(), allGroups);
		}

		// Anonymous posts
		groups = this.request.getParameterValues("groupsAnonymous");
		if (groups != null) {
			this.addRole(pc, SecurityConstants.PERM_ANONYMOUS_POST, forum.getId(), groups);
		}
		/*else {
			//this.addRole(pc, SecurityConstants.PERM_ANONYMOUS_POST, f.getId(), allGroups);
		}*/

		// Read-only
		groups = this.request.getParameterValues("groupsReadOnly");
		if (groups != null) {
			this.addRole(pc, SecurityConstants.PERM_READ_ONLY_FORUMS, forum.getId(), groups);
		}
		else {
			this.addRole(pc, SecurityConstants.PERM_READ_ONLY_FORUMS, forum.getId(), allGroups);
		}

		// Reply-only
		this.addRole(pc, SecurityConstants.PERM_REPLY_ONLY, forum.getId(), allGroups);

		// HTML
		groups = this.request.getParameterValues("groupsHtml");
		if (groups != null) {
			this.addRole(pc, SecurityConstants.PERM_HTML_DISABLED, forum.getId(), groups);
		}
		else {
			this.addRole(pc, SecurityConstants.PERM_HTML_DISABLED, forum.getId(), allGroups);
		}

		SecurityRepository.clean();
		RolesRepository.clear();

		this.request.addParameter(FORUM_ID, String.valueOf(forumId));
		this.handleMailIntegration();

		this.list();
	}

	private void addRole(final PermissionControl permissionControl, final String roleName, final int forumId, final String[] groups)
	{
		Role role = new Role();
		role.setName(roleName);

		for (int i = 0; i < groups.length; i++) {
			int groupId = Integer.parseInt(groups[i]);
			RoleValueCollection roleValues = new RoleValueCollection();

			RoleValue roleValue = new RoleValue();
			roleValue.setValue(Integer.toString(forumId));
			roleValues.add(roleValue);

			permissionControl.addRoleValue(groupId, role, roleValues);
		}
	}
}


text:
using System;

namespace SharpVk.Interop
{
    /// <summary>
    ///
    /// </summary>
    public unsafe delegate void VkImageGetMemoryRequirementsDelegate(SharpVk.Interop.Device device, SharpVk.Interop.Image image, SharpVk.MemoryRequirements* memoryRequirements);
}

redpajama_set_name: RedPajamaGithub


text:
module.exports = function(db, store, payload, response){
	if( typeof store.token[payload.mail] === 'undefined' ){
		var date = new Date();
		var collection = db.collection('users');

		store.users[payload.token].type = 'user';
		store.users[payload.token].name = store.users[payload.token].name || payload.name;
		store.users[payload.token].lastName = store.users[payload.token].lastName || payload.lastName;
		store.users[payload.token].mail = store.users[payload.token].mail || payload.mail;
		store.users[payload.token].password = store.users[payload.token].password || payload.password;

		store.token[payload.mail] = payload.token;

		response({auth: 1, token: payload.token});

		collection.update(
			{token: payload.token},
			{$set:
				{
					type: 'user',
					name: store.users[payload.token].name,
					lastName: store.users[payload.token].lastName,
					mail: store.users[payload.token].mail,
					password: store.users[payload.token].password,
					address: store.users[payload.token].address || {},
					orders: store.users[payload.token].orders || [],
					providerType: store.users[payload.token].providerType || 0,
					phone: payload.phone
				}
			},
			{},
			function(){}
		);

		delete store.users[payload.token]._id;
	}
	else{
		response({auth:0});
	}
	return;
};


text:
int main( int argc, char** argv )
{
  std::string topic = "/sim_dispatcher/sim_state1";
  ros::init(argc, argv, "sim_pub_tester");
  ros::NodeHandle n;

  ros::Publisher sim_state_pub = n.advertise<race_imagination::SimState>(topic , 1000);
  ROS_INFO("Publishing on topic %s", topic.c_str());

  race_imagination::SimState msg;
  msg.header.stamp = ros::Time::now();
  msg.header.frame_id = "/map";
  msg.action = "move_base_param";

  race_msgs::ParamList pl;
  race_msgs::ParamList pl2;
  pl.param_list.push_back("premanipulationareanorthtable1");
  pl2.param_list.push_back("slow");

  msg.parameter.push_back(pl);
  msg.parameter.push_back(pl2);

  while ( ros::ok())
  {
    sim_state_pub.publish(msg);

    ros::spinOnce();
    ros::Duration(2).sleep();
  }

  return 0;
}


text:
function image2 = gray2rgb(image,colorMap,isRescale);
% Timothee Cour, 21-Apr-2008 17:31:23
% This software is made publicly for research use only.
% It may be modified and redistributed under the terms of the GNU General Public License.

if isempty(image)
    image2=[];
    return;
end
if nargin<3
    isRescale=1;
end

image=double(image);
if nargin<2
    colorMap=jet(128);%TODO:unused...
end
%image2 = gray2rgb(image,jet); for 'default' colormap
[p,q,r] = size(image);
image = full(image);
if r==1
%     image2=repmat(image,[1,1,3]);
    if nargin < 2
        if isRescale
            image=rescaleImage(image);
        end
        image2=repmat(image,[1,1,3]);
    else
        k=size(colorMap,1);

        if isRescale
%             image=rescaleImage(image);
%             image=round(rescaleImage(image,[1,k]));
            image=rescaleImage(image,[1,k]);
        else
%             image=round((k-1)*image+1);
            image=(k-1)*image+1;
        end
%         image=uint8(image);
%         image2 = ind2rgb(image,colorMap);
%         image2=uint8(image2);
%         image2 = ind2rgb8(image, colorMap);
        image2 = ind2rgb8_2(image, colorMap);
    end
else
    image2 = image;
end

% image2=rescaleImage(image2);


text:
import { ListStreams } from '../../src/Commands'
import { TestCommand } from '../test-helpers'

describe('/ListStreams', function() {
  it(
    'ListStreams() should return a properly configured JSON-RPC request',
  )
})


text:
<?php
// Heading
$_['heading_title']          = 'QuickerPro Editor';

$_['text_qtags']           	 = 'QuickerPro Editor';
$_['text_success']           = 'Success: You have modified products!';

// Column
$_['column_name']            = 'Product Name';
$_['column_category']        = 'Category';
$_['column_model']           = 'Model';
$_['column_image']           = 'Image';
$_['column_price']           = 'Price';
$_['column_quantity'] 		 = 'Quantity';
$_['column_weight']          = 'Weight';
$_['column_status']    		 = 'Status';
$_['column_action']          = 'Action';
$_['button_update']          = 'Update';

// Error
$_['error_permission']       = 'Warning: You do not have permission to modify products!';
$_['error_name']             = 'Product Name must be greater than 3 and less than 255 characters!';
$_['error_model']            = 'Product Model must be greater than 3 and less than 64 characters!';
$_['error_required_data']    = 'Required Data has not been entered. Check for field errors!';
?>


text:
// Copyright 2015 Colin Stewart.  All rights reserved.
// Use of this source code is governed by an MIT
// license that can be found in the LICENSE.txt file.

package tal


text:
import createTester from './internal/createTester.js'
import eachOfLimit from './internal/eachOfLimit.js'
import awaitify from './internal/awaitify.js'

/**
 * The same as [`every`]{@link module:Collections.every} but runs a maximum of `limit` async operations at a time.
 *
 * @name everyLimit
 * @static
 * @memberOf module:Collections
 * @method
 * @see [async.every]{@link module:Collections.every}
 * @alias allLimit
 * @category Collection
 * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.
 * @param {number} limit - The maximum number of async operations at a time.
 * @param {AsyncFunction} iteratee - An async truth test to apply to each item
 * in the collection in parallel.
 * The iteratee must complete with a boolean result value.
 * Invoked with (item, callback).
 * @param {Function} [callback] - A callback which is called after all the
 * `iteratee` functions have finished. Result will be either `true` or `false`
 * depending on the values of the async tests. Invoked with (err, result).
 * @returns {Promise} a promise, if no callback provided
 */
function everyLimit(coll, limit, iteratee, callback) {
    return createTester(bool => !bool, res => !res)(eachOfLimit(limit), coll, iteratee, callback)
}
export default awaitify(everyLimit, 4);


text:
====================
Django User Accounts
====================

.. image:: http://slack.pinaxproject.com/badge.svg
   :target: http://slack.pinaxproject.com/

.. image:: https://img.shields.io/travis/pinax/django-user-accounts.svg
    :target: https://travis-ci.org/pinax/django-user-accounts

.. image:: https://img.shields.io/coveralls/pinax/django-user-accounts.svg
    :target: https://coveralls.io/r/pinax/django-user-accounts

.. image:: https://img.shields.io/pypi/dm/django-user-accounts.svg
    :target:  https://pypi.python.org/pypi/django-user-accounts/

.. image:: https://img.shields.io/pypi/v/django-user-accounts.svg
    :target:  https://pypi.python.org/pypi/django-user-accounts/

.. image:: https://img.shields.io/badge/license-MIT-blue.svg
    :target:  https://pypi.python.org/pypi/django-user-accounts/

Pinax
-------

Pinax is an open-source platform built on the Django Web Framework. It is an ecosystem of reusable Django apps, themes, and starter project templates.
This collection can be found at http://pinaxproject.com.

This app was developed as part of the Pinax ecosystem but is just a Django app and can be used independently of other Pinax apps.

django-user-accounts
-------------------------

django-user-accounts provides a Django project with a very extensible infrastructure for dealing
with user accounts.

Features
----------

* Functionality for:

  - Log in (email or username authentication)
  - Sign up
  - Email confirmation
  - Signup tokens for private betas
  - Password reset
  - Account management (update account settings and change password)
  - Account deletion

* Extensible class-based views and hooksets
* Custom ``User`` model support

Requirements
--------------

* Django 1.7 or 1.8
* Python 2.7, 3.3 or 3.4
* django-appconf (included in ``install_requires``)
* pytz (included in ``install_requires``)

Documentation
----------------

See http://django-user-accounts.readthedocs.org/ for the ``django-user-accounts`` documentation.
We recently did a Pinax Hangout on ``django-user-accounts``, you can read the recap blog post and find the video here http://blog.pinaxproject.com/2015/10/12/recap-september-pinax-hangout/.

The Pinax documentation is available at http://pinaxproject.com/pinax/. If you would like to help us improve our documentation or write more documentation, please join our Slack channel and let us know!

Contributing
--------------

We accept contributions from everyone! See the ``CONTRIBUTING.md`` file for more
information about how to contribute.

Code of Conduct
-----------------

In order to foster a kind, inclusive, and harassment-free community, the Pinax Project has a code of conduct, which can be found here  http://pinaxproject.com/pinax/code_of_conduct/.

Pinax Project Blog and Twitter
--------------------------------

For updates and news regarding the Pinax Project, please follow us on Twitter at @pinaxproject and check out our blog http://blog.pinaxproject.com.


text:
package gnu.javax.crypto.jce.key;

import gnu.java.security.Registry;

public class RijndaelKeyGeneratorImpl
    extends SecretKeyGeneratorImpl
{
  public RijndaelKeyGeneratorImpl()
  {
    super(Registry.RIJNDAEL_CIPHER);
  }
}


text:
/*
 * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 */

/*
 * Copyright (c) 2009, 2013, by Oracle Corporation. All Rights Reserved.
 */

package javax.xml.stream;
import java.util.Iterator;
import javax.xml.namespace.NamespaceContext;
import javax.xml.namespace.QName;
import javax.xml.stream.events.*;
/**
 * This interface defines a utility class for creating instances of
 * XMLEvents
 * @version 1.2
 * @author Copyright (c) 2009 by Oracle Corporation. All Rights Reserved.
 * @see StartElement
 * @see EndElement
 * @see ProcessingInstruction
 * @see Comment
 * @see Characters
 * @see StartDocument
 * @see EndDocument
 * @see DTD
 * @since 1.6
 */
public abstract class XMLEventFactory {
  protected XMLEventFactory(){}

    static final String JAXPFACTORYID = "javax.xml.stream.XMLEventFactory";
    static final String DEFAULIMPL = "com.sun.xml.internal.stream.events.XMLEventFactoryImpl";

  /**
   * Creates a new instance of the factory in exactly the same manner as the
   * {@link #newFactory()} method.
   * @throws FactoryConfigurationError if an instance of this factory cannot be loaded
   */
  public static XMLEventFactory newInstance()
    throws FactoryConfigurationError
  {
    return FactoryFinder.find(XMLEventFactory.class, DEFAULIMPL);
  }

  /**
   * Create a new instance of the factory.
   *

   * This static method creates a new factory instance.
   * This method uses the following ordered lookup procedure to determine
   * the XMLEventFactory implementation class to load:
   *

   *

   *

   *   Use the javax.xml.stream.XMLEventFactory system property.
   *

   *

   *   Use the properties file "lib/stax.properties" in the JRE directory.
   *     This configuration file is in standard java.util.Properties format
   *     and contains the fully qualified name of the implementation class
   *     with the key being the system property defined above.
   *

   *

   *   Use the service-provider loading facilities, defined by the
   *   {@link java.util.ServiceLoader} class, to attempt to locate and load an
   *   implementation of the service using the {@linkplain
   *   java.util.ServiceLoader#load(Class) default loading mechanism}:
   *   the service-provider loading facility will use the {@linkplain
   *   Thread#getContextClassLoader() current thread's context class loader}
   *   to attempt to load the service. If the context class
   *   loader is null, the {@linkplain
   *   ClassLoader#getSystemClassLoader() system class loader} will be used.
   *

   *

   *   Otherwise, the system-default implementation is returned.
   *

   *

   *

   *   Once an application has obtained a reference to a XMLEventFactory it
   *   can use the factory to configure and obtain stream instances.
   *

   *

   *   Note that this is a new method that replaces the deprecated newInstance() method.
   *     No changes in behavior are defined by this replacement method relative to
   *     the deprecated method.
   *

   * @throws FactoryConfigurationError in case of {@linkplain
   *   java.util.ServiceConfigurationError service configuration error} or if
   *   the implementation is not available or cannot be instantiated.
   */
  public static XMLEventFactory newFactory()
    throws FactoryConfigurationError
  {
    return FactoryFinder.find(XMLEventFactory.class, DEFAULIMPL);
  }

  /**
   * Create a new instance of the factory
   *
   * @param factoryId             Name of the factory to find, same as
   *                              a property name
   * @param classLoader           classLoader to use
   * @return the factory implementation
   * @throws FactoryConfigurationError if an instance of this factory cannot be loaded
   *
   * @deprecated  This method has been deprecated to maintain API consistency.
   *              All newInstance methods have been replaced with corresponding
   *              newFactory methods. The replacement {@link
   *              #newFactory(String, ClassLoader)}
   *              method defines no changes in behavior.
   */
  public static XMLEventFactory newInstance(String factoryId,
          ClassLoader classLoader)
          throws FactoryConfigurationError {
      //do not fallback if given classloader can't find the class, throw exception
      return FactoryFinder.find(XMLEventFactory.class, factoryId, classLoader, null);
  }

  /**
   * Create a new instance of the factory.
   * If the classLoader argument is null, then the ContextClassLoader is used.
   *

   * This method uses the following ordered lookup procedure to determine
   * the XMLEventFactory implementation class to load:
   *

   *

   *

   *   Use the value of the system property identified by {@code factoryId}.
   *

   *

   *   Use the properties file "lib/stax.properties" in the JRE directory.
   *     This configuration file is in standard java.util.Properties format
   *     and contains the fully qualified name of the implementation class
   *     with the key being the given {@code factoryId}.
   *

   *

   *   If {@code factoryId} is "javax.xml.stream.XMLEventFactory",
   *   use the service-provider loading facilities, defined by the
   *   {@link java.util.ServiceLoader} class, to attempt to {@linkplain
   *   java.util.ServiceLoader#load(Class, ClassLoader) locate and load}
   *   an implementation of the service using the specified {@code ClassLoader}.
   *   If {@code classLoader} is null, the {@linkplain
   *   java.util.ServiceLoader#load(Class) default loading mechanism} will apply:
   *   That is, the service-provider loading facility will use the {@linkplain
   *   Thread#getContextClassLoader() current thread's context class loader}
   *   to attempt to load the service. If the context class
   *   loader is null, the {@linkplain
   *   ClassLoader#getSystemClassLoader() system class loader} will be used.
   *

   *

   *   Otherwise, throws a {@link FactoryConfigurationError}.
   *

   *

   *
   *

   * Note that this is a new method that replaces the deprecated
   *   {@link #newInstance(String, ClassLoader)
   *   newInstance(String factoryId, ClassLoader classLoader)} method.
   * No changes in behavior are defined by this replacement method relative
   * to the deprecated method.
   *

   *
   * @apiNote The parameter factoryId defined here is inconsistent with that
   * of other JAXP factories where the first parameter is fully qualified
   * factory class name that provides implementation of the factory.
   *
   * @param factoryId             Name of the factory to find, same as
   *                              a property name
   * @param classLoader           classLoader to use
   * @return the factory implementation
   * @throws FactoryConfigurationError in case of {@linkplain
   *   java.util.ServiceConfigurationError service configuration error} or if
   *   the implementation is not available or cannot be instantiated.
   */
  public static XMLEventFactory newFactory(String factoryId,
                                           ClassLoader classLoader)
          throws FactoryConfigurationError {
      //do not fallback if given classloader can't find the class, throw exception
      return FactoryFinder.find(XMLEventFactory.class, factoryId, classLoader, null);
  }

 /**
   * This method allows setting of the Location on each event that
   * is created by this factory.  The values are copied by value into
   * the events created by this factory.  To reset the location
   * information set the location to null.
   * @param location the location to set on each event created
   */
  public abstract void setLocation(Location location);

  /**
   * Create a new Attribute
   * @param prefix the prefix of this attribute, may not be null
   * @param namespaceURI the attribute value is set to this value, may not be null
   * @param localName the local name of the XML name of the attribute, localName cannot be null
   * @param value the attribute value to set, may not be null
   * @return the Attribute with specified values
   */
  public abstract Attribute createAttribute(String prefix, String namespaceURI, String localName, String value);

  /**
   * Create a new Attribute
   * @param localName the local name of the XML name of the attribute, localName cannot be null
   * @param value the attribute value to set, may not be null
   * @return the Attribute with specified values
   */
  public abstract Attribute createAttribute(String localName, String value);

  /**
   * Create a new Attribute
   * @param name the qualified name of the attribute, may not be null
   * @param value the attribute value to set, may not be null
   * @return the Attribute with specified values
   */
  public abstract Attribute createAttribute(QName name, String value);

  /**
   * Create a new default Namespace
   * @param namespaceURI the default namespace uri
   * @return the Namespace with the specified value
   */
  public abstract Namespace createNamespace(String namespaceURI);

  /**
   * Create a new Namespace
   * @param prefix the prefix of this namespace, may not be null
   * @param namespaceUri the attribute value is set to this value, may not be null
   * @return the Namespace with the specified values
   */
  public abstract Namespace createNamespace(String prefix, String namespaceUri);

  /**
   * Create a new StartElement.  Namespaces can be added to this StartElement
   * by passing in an Iterator that walks over a set of Namespace interfaces.
   * Attributes can be added to this StartElement by passing an iterator
   * that walks over a set of Attribute interfaces.
   *
   * @param name the qualified name of the attribute, may not be null
   * @param attributes an optional unordered set of objects that
   * implement Attribute to add to the new StartElement, may be null
   * @param namespaces an optional unordered set of objects that
   * implement Namespace to add to the new StartElement, may be null
   * @return an instance of the requested StartElement
   */
  public abstract StartElement createStartElement(QName name,
                                                  Iterator attributes,
                                                  Iterator namespaces);

  /**
   * Create a new StartElement.  This defaults the NamespaceContext to
   * an empty NamespaceContext.  Querying this event for its namespaces or
   * attributes will result in an empty iterator being returned.
   *
   * @param namespaceUri the uri of the QName of the new StartElement
   * @param localName the local name of the QName of the new StartElement
   * @param prefix the prefix of the QName of the new StartElement
   * @return an instance of the requested StartElement
   */
  public abstract StartElement createStartElement(String prefix,
                                                  String namespaceUri,
                                                  String localName);
  /**
   * Create a new StartElement.  Namespaces can be added to this StartElement
   * by passing in an Iterator that walks over a set of Namespace interfaces.
   * Attributes can be added to this StartElement by passing an iterator
   * that walks over a set of Attribute interfaces.
   *
   * @param namespaceUri the uri of the QName of the new StartElement
   * @param localName the local name of the QName of the new StartElement
   * @param prefix the prefix of the QName of the new StartElement
   * @param attributes an unordered set of objects that implement
   * Attribute to add to the new StartElement
   * @param namespaces an unordered set of objects that implement
   * Namespace to add to the new StartElement
   * @return an instance of the requested StartElement
   */
  public abstract StartElement createStartElement(String prefix,
                                                  String namespaceUri,
                                                  String localName,
                                                  Iterator attributes,
                                                  Iterator namespaces
                                                  );
  /**
   * Create a new StartElement.  Namespaces can be added to this StartElement
   * by passing in an Iterator that walks over a set of Namespace interfaces.
   * Attributes can be added to this StartElement by passing an iterator
   * that walks over a set of Attribute interfaces.
   *
   * @param namespaceUri the uri of the QName of the new StartElement
   * @param localName the local name of the QName of the new StartElement
   * @param prefix the prefix of the QName of the new StartElement
   * @param attributes an unordered set of objects that implement
   * Attribute to add to the new StartElement, may be null
   * @param namespaces an unordered set of objects that implement
   * Namespace to add to the new StartElement, may be null
   * @param context the namespace context of this element
   * @return an instance of the requested StartElement
   */
  public abstract StartElement createStartElement(String prefix,
                                                  String namespaceUri,
                                                  String localName,
                                                  Iterator attributes,
                                                  Iterator namespaces,
                                                  NamespaceContext context
                                                  );

  /**
   * Create a new EndElement
   * @param name the qualified name of the EndElement
   * @param namespaces an optional unordered set of objects that
   * implement Namespace that have gone out of scope, may be null
   * @return an instance of the requested EndElement
   */
  public abstract EndElement createEndElement(QName name,
                                              Iterator namespaces);

  /**
   * Create a new EndElement
   * @param namespaceUri the uri of the QName of the new StartElement
   * @param localName the local name of the QName of the new StartElement
   * @param prefix the prefix of the QName of the new StartElement
   * @return an instance of the requested EndElement
   */
  public abstract EndElement createEndElement(String prefix,
                                              String namespaceUri,
                                              String localName);
  /**
   * Create a new EndElement
   * @param namespaceUri the uri of the QName of the new StartElement
   * @param localName the local name of the QName of the new StartElement
   * @param prefix the prefix of the QName of the new StartElement
   * @param namespaces an unordered set of objects that implement
   * Namespace that have gone out of scope, may be null
   * @return an instance of the requested EndElement
   */
  public abstract EndElement createEndElement(String prefix,
                                              String namespaceUri,
                                              String localName,
                                              Iterator namespaces);

  /**
   * Create a Characters event, this method does not check if the content
   * is all whitespace.  To create a space event use #createSpace(String)
   * @param content the string to create
   * @return a Characters event
   */
  public abstract Characters createCharacters(String content);

  /**
   * Create a Characters event with the CData flag set to true
   * @param content the string to create
   * @return a Characters event
   */
  public abstract Characters createCData(String content);

  /**
   * Create a Characters event with the isSpace flag set to true
   * @param content the content of the space to create
   * @return a Characters event
   */
  public abstract Characters createSpace(String content);
  /**
   * Create an ignorable space
   * @param content the space to create
   * @return a Characters event
   */
  public abstract Characters createIgnorableSpace(String content);

  /**
   * Creates a new instance of a StartDocument event
   * @return a StartDocument event
   */
  public abstract StartDocument createStartDocument();

  /**
   * Creates a new instance of a StartDocument event
   *
   * @param encoding the encoding style
   * @param version the XML version
   * @param standalone the status of standalone may be set to "true" or "false"
   * @return a StartDocument event
   */
  public abstract StartDocument createStartDocument(String encoding,
                                                  String version,
                                                  boolean standalone);

  /**
   * Creates a new instance of a StartDocument event
   *
   * @param encoding the encoding style
   * @param version the XML version
   * @return a StartDocument event
   */
  public abstract StartDocument createStartDocument(String encoding,
                                                  String version);

  /**
   * Creates a new instance of a StartDocument event
   *
   * @param encoding the encoding style
   * @return a StartDocument event
   */
  public abstract StartDocument createStartDocument(String encoding);

  /**
   * Creates a new instance of an EndDocument event
   * @return an EndDocument event
   */
  public abstract EndDocument createEndDocument();

  /** Creates a new instance of a EntityReference event
   *
   * @param name The name of the reference
   * @param declaration the declaration for the event
   * @return an EntityReference event
   */
  public abstract EntityReference createEntityReference(String name,
                                                        EntityDeclaration declaration);
  /**
   * Create a comment
   * @param text The text of the comment
   * a Comment event
   */
  public abstract Comment createComment(String text);

  /**
   * Create a processing instruction
   * @param target The target of the processing instruction
   * @param data The text of the processing instruction
   * @return a ProcessingInstruction event
   */
  public abstract ProcessingInstruction createProcessingInstruction(String target,
                                                                   String data);

  /**
   * Create a document type definition event
   * This string contains the entire document type declaration that matches
   * the doctypedecl in the XML 1.0 specification
   * @param dtd the text of the document type definition
   * @return a DTD event
   */
  public abstract DTD createDTD(String dtd);
}


text:
#ifndef itkAggregateLabelMapFilter_h
#define itkAggregateLabelMapFilter_h

#include "itkInPlaceLabelMapFilter.h"

namespace itk
{
/**
 * \class AggregateLabelMapFilter
 * \brief Collapses all labels into the first label.
 *
 * This filter takes a label map as input and visits the pixels of all labels
 * and assigns them to the first label of the label map. At the end of the
 * execution of this filter, the map will contain a single filter.
 *
 * This implementation was taken from the Insight Journal paper:
 * https://www.insight-journal.org/browse/publication/176
 *
 * \author Gaetan Lehmann. Biologie du Developpement et de la Reproduction,
 * INRA de Jouy-en-Josas, France.
 *
 * \sa ShapeLabelObject, RelabelComponentImageFilter
 * \ingroup ImageEnhancement  MathematicalMorphologyImageFilters
 * \ingroup ITKLabelMap
 */
template <typename TImage>
class ITK_TEMPLATE_EXPORT AggregateLabelMapFilter : public InPlaceLabelMapFilter<TImage>
{
public:
  ITK_DISALLOW_COPY_AND_MOVE(AggregateLabelMapFilter);

  /** Standard class type aliases. */
  using Self = AggregateLabelMapFilter;
  using Superclass = InPlaceLabelMapFilter<TImage>;
  using Pointer = SmartPointer<Self>;
  using ConstPointer = SmartPointer<const Self>;

  /** Some convenient type alias. */
  using ImageType = TImage;
  using ImagePointer = typename ImageType::Pointer;
  using ImageConstPointer = typename ImageType::ConstPointer;
  using PixelType = typename ImageType::PixelType;
  using IndexType = typename ImageType::IndexType;
  using LabelObjectType = typename ImageType::LabelObjectType;

  /** ImageDimension constants */
  static constexpr unsigned int ImageDimension = TImage::ImageDimension;

  /** Standard New method. */
  itkNewMacro(Self);

  /** Runtime information support. */
  itkTypeMacro(AggregateLabelMapFilter, InPlaceLabelMapFilter);

#ifdef ITK_USE_CONCEPT_CHECKING
  // Begin concept checking
/*  itkConceptMacro(InputEqualityComparableCheck,
    (Concept::EqualityComparable<InputImagePixelType>));
  itkConceptMacro(IntConvertibleToInputCheck,
    (Concept::Convertible<int, InputImagePixelType>));
  itkConceptMacro(InputOStreamWritableCheck,
    (Concept::OStreamWritable<InputImagePixelType>));*/
// End concept checking
#endif

protected:
  AggregateLabelMapFilter() = default;
  ~AggregateLabelMapFilter() override = default;

  void
  PrintSelf(std::ostream & os, Indent indent) const override;

  void
  GenerateData() override;
}; // end of class
} // end namespace itk

#ifndef ITK_MANUAL_INSTANTIATION
#  include "itkAggregateLabelMapFilter.hxx"
#endif

#endif


text:
'''
A simple script for passing commands to various media players.

This script needs ``dbus-python`` for spotify communication.

To run simply::

    ./mediakeys.py <command>

Where command is one of the following::

    ``toggle``
    ``stop``
    ``next``
    ``previous``
'''

# pylint: disable=W0703

import dbus
from dbus.mainloop.glib import DBusGMainLoop
import sys
import subprocess

def send_pandora(command):
    '''
    Send the command to pithos using dbus interface.
    '''
    try:
        bus = dbus.SessionBus()
        pithos_object = bus.get_object("net.kevinmehall.Pithos",
                                       "/net/kevinmehall/Pithos")
        pithos = dbus.Interface(pithos_object, "net.kevinmehall.Pithos")
        if command == 'toggle':
            pithos.PlayPause()
        elif command == 'stop':
            pithos.Stop()
        elif command == 'next':
            pithos.SkipSong()
        return True
    except dbus.exceptions.DBusException:
        return False

def send_spotify(command):
    '''
    Send the command to spotify using dbus iterface.
    '''
    try:
        bus_loop = DBusGMainLoop(set_as_default=True)
        session_bus = dbus.SessionBus(mainloop=bus_loop)
        spotify_bus = session_bus.get_object('org.mpris.MediaPlayer2.spotify',
                                             '/org/mpris/MediaPlayer2')
        spotify = dbus.Interface(spotify_bus, 'org.mpris.MediaPlayer2.Player')
        if command == 'toggle':
            spotify.PlayPause()
        elif command == 'stop':
            spotify.Stop()
        elif command == 'next':
            spotify.Next()
        elif command == 'prev':
            spotify.Previous()
        return True
    except Exception:
        return False

def send_ncmpcpp(command):
    '''
    Pass the command to ncmpcpp using a subprocess.
    '''
    if command == 'prev':
        cmd = 'mpc repeat off && mpc {} && mpc repeat on'
    else:
        cmd = 'mpc {}'

    cmd = cmd.format(command)
    kwargs = {'shell': True}
    proc = subprocess.Popen(cmd, **kwargs)
    proc.communicate()
    if proc.returncode == 0:
        return True
    return False

def main(arg):
    '''
    Pass the arg to media players.
    '''
    if arg in ('toggle', 'stop', 'next', 'prev'):
        # First try sending command to Spotify, then ncmpcpp
        return send_pandora(arg) or send_spotify(arg) or send_ncmpcpp(arg)
    return False

if __name__ == '__main__':
    if len(sys.argv) == 2:
        if main(sys.argv[1]):
            exit(0)
        else:
            exit(100)
    else:
        exit(101)


text:
package org.eclipse.mat.util;

/**
 * File utilities for things like copying icon files.
 */
/**
 * File utilities for things like copying icon files.
 */
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;

public final class FileUtils {
	private static DirDeleter deleterThread;

	static {
		deleterThread = new DirDeleter();
		Runtime.getRuntime().addShutdownHook(deleterThread);
	}

	private FileUtils() {
	}

	/**
	 * Basic stream copy
	 *
	 * @param in
	 *            input stream
	 * @param out
	 *            output stream
	 * @throws IOException
	 */
	public static void copy(InputStream in, OutputStream out) throws IOException {
		byte[] b = new byte[256];
		int i = 0;

		while (true) {
			i = in.read(b);
			if (i == -1)
				break;
			out.write(b, 0, i);
		}

	}

	/**
	 * Create a temporary directory which should be deleted on application close.
	 *
	 * @param prefix
	 * @param parent
	 * @return the temporary directory, to be deleted on shutdown
	 * @throws IOException
	 */
	public static File createTempDirectory(String prefix, File parent) throws IOException {
		File tempFile = File.createTempFile(prefix, "", parent);
		if (!tempFile.delete())
			throw new IOException();
		if (!tempFile.mkdir())
			throw new IOException();
		deleterThread.add(tempFile);
		return tempFile;
	}

	public static String toFilename(String name, String extension) {
		return toFilename(name, "", extension);
	}

	/**
	 * Build a file name. Convert non-letters or digits to underscore.
	 *
	 * @param prefix
	 *            the prefix of the file
	 * @param suffix
	 *            the suffix
	 * @param extension
	 *            the file extension
	 * @return the combined file name
	 */
	public static String toFilename(String prefix, String suffix, String extension) {
		StringBuilder buf = new StringBuilder(prefix.length() + suffix.length() + extension.length() + 1);

		for (String s : new String[] { prefix, suffix }) {
			for (int ii = 0; ii < s.length() && ii < 20; ii++) {
				char c = s.charAt(ii);
				if (Character.isLetterOrDigit(c))
					buf.append(c);
				else
					buf.append("_");
			}
		}

		buf.append(".").append(extension);

		return buf.toString();
	}

	// //////////////////////////////////////////////////////////////
	// inner classes
	// //////////////////////////////////////////////////////////////

	private static class DirDeleter extends Thread {
		private List<File> dirList = new ArrayList<File>();

		public synchronized void add(File dir) {
			dirList.add(dir);
		}

		@Override
		public void run() {
			synchronized (this) {
				for (File dir : dirList)
					deleteDirectory(dir);
			}
		}

		private void deleteDirectory(File dir) {
			if (!dir.exists())
				return;

			File[] fileArray = dir.listFiles();

			if (fileArray != null) {
				for (int i = 0; i < fileArray.length; i++) {
					if (fileArray[i].isDirectory())
						deleteDirectory(fileArray[i]);
					else
						fileArray[i].delete();
				}
			}

			dir.delete();
		}
	}

}


text:
@echo off

cmd /C "_stylehelper.bat ..\src cpp"
cmd /C "_stylehelper.bat ..\src h"
cmd /C "_stylehelper.bat ..\src hpp"
cmd /C "_stylehelper.bat ..\inc cpp"
cmd /C "_stylehelper.bat ..\inc h"
cmd /C "_stylehelper.bat ..\inc hpp"

pause


text:
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE StrictData #-}
{-# LANGUAGE TupleSections #-}

-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-cloudtrail-trail-dataresource.html

module Stratosphere.ResourceProperties.CloudTrailTrailDataResource where

import Stratosphere.ResourceImports

-- | Full data type definition for CloudTrailTrailDataResource. See
-- 'cloudTrailTrailDataResource' for a more convenient constructor.
data CloudTrailTrailDataResource =
  CloudTrailTrailDataResource
  { _cloudTrailTrailDataResourceType :: Val Text
  , _cloudTrailTrailDataResourceValues :: Maybe (ValList Text)
  } deriving (Show, Eq)

instance ToJSON CloudTrailTrailDataResource where
  toJSON CloudTrailTrailDataResource{..} =
    object $
    catMaybes
    [ (Just . ("Type",) . toJSON) _cloudTrailTrailDataResourceType
    , fmap (("Values",) . toJSON) _cloudTrailTrailDataResourceValues
    ]

-- | Constructor for 'CloudTrailTrailDataResource' containing required fields
-- as arguments.
cloudTrailTrailDataResource
  :: Val Text -- ^ 'cttdrType'
  -> CloudTrailTrailDataResource
cloudTrailTrailDataResource typearg =
  CloudTrailTrailDataResource
  { _cloudTrailTrailDataResourceType = typearg
  , _cloudTrailTrailDataResourceValues = Nothing
  }

-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-cloudtrail-trail-dataresource.html#cfn-cloudtrail-trail-dataresource-type
cttdrType :: Lens' CloudTrailTrailDataResource (Val Text)
cttdrType = lens _cloudTrailTrailDataResourceType (\s a -> s { _cloudTrailTrailDataResourceType = a })

-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-cloudtrail-trail-dataresource.html#cfn-cloudtrail-trail-dataresource-values
cttdrValues :: Lens' CloudTrailTrailDataResource (Maybe (ValList Text))
cttdrValues = lens _cloudTrailTrailDataResourceValues (\s a -> s { _cloudTrailTrailDataResourceValues = a })


text:
<?php namespace Anomaly\UsersModule\User\Table\Action;

use Anomaly\Streams\Platform\Ui\Table\Component\Action\ActionHandler;
use Anomaly\UsersModule\Suspension\SuspensionManager;
use Anomaly\UsersModule\User\Contract\UserRepositoryInterface;

/**
 * Class ReinstateHandler
 *
 * @link          http://anomaly.is/streams-platform
 * @author        AnomalyLabs, Inc. <hello@anomaly.is>
 * @author        Ryan Thompson <ryan@anomaly.is>
 * @package       Anomaly\UsersModule\User\Table\Action
 */
class ReinstateHandler extends ActionHandler
{

    /**
     * Handle the action.
     *
     * @param UserRepositoryInterface $users
     * @param SuspensionManager       $manager
     * @param                         $selected
     */
    public function handle(UserRepositoryInterface $users, SuspensionManager $manager, $selected)
    {
        foreach ($selected as $id) {
            $manager->reinstate($users->find($id));
        }

        $this->messages->success(
            trans('anomaly.module.users::success.reinstate_users', ['count' => count($selected)])
        );
    }
}


text:
package com.pme.exe.res.vi;

import com.pme.exe.Bin;

public class StringTable extends VersionInfoBin {

  public StringTable(String name) {
    super(name, null, new VersionInfoFactory() {
      @Override
      public VersionInfoBin createChild(int index) {
        return new StringTableEntry();
      }
    });
  }

  public void setStringValue(String key, String value) {
    for (Bin bin : getMembers()) {
      if (bin.getName().equals(key)) {
        StringTableEntry entry = (StringTableEntry) bin;
        ((WChar) entry.getMember("Value")).setValue(value);
        ((Word) entry.getMember("wValueLength")).setValue(value.length() + 1);
        return;
      }
    }
    assert false: "Could not find string with key " + key;
  }
}


text:
"use strict";

const {
  builders: {
    breakParent,
    dedentToRoot,
    group,
    ifBreak,
    indentIfBreak,
    indent,
    line,
    softline,
  },
  utils: { replaceTextEndOfLine },
} = require("../../document/index.js");
const getNodeContent = require("../get-node-content.js");
const {
  shouldPreserveContent,
  isScriptLikeTag,
  isVueCustomBlock,
  countParents,
  forceBreakContent,
} = require("../utils/index.js");
const {
  printOpeningTagPrefix,
  printOpeningTag,
  printClosingTagSuffix,
  printClosingTag,
  needsToBorrowPrevClosingTagEndMarker,
  needsToBorrowLastChildClosingTagEndMarker,
} = require("./tag.js");
const { printChildren } = require("./children.js");

function printElement(path, options, print) {
  const node = path.getValue();

  if (shouldPreserveContent(node, options)) {
    return [
      printOpeningTagPrefix(node, options),
      group(printOpeningTag(path, options, print)),
      ...replaceTextEndOfLine(getNodeContent(node, options)),
      ...printClosingTag(node, options),
      printClosingTagSuffix(node, options),
    ];
  }
  /**
   * do not break:
   *
   *     <div>{{
   *         ~
   *       interpolation
   *     }}</div>
   *            ~
   *
   * exception: break if the opening tag breaks
   *
   *     <div
   *       long
   *           ~
   *       >{{
   *         interpolation
   *       }}</div
   *              ~
   *     >
   */
  const shouldHugContent =
    node.children.length === 1 &&
    node.firstChild.type === "interpolation" &&
    node.firstChild.isLeadingSpaceSensitive &&
    !node.firstChild.hasLeadingSpaces &&
    node.lastChild.isTrailingSpaceSensitive &&
    !node.lastChild.hasTrailingSpaces;

  const attrGroupId = Symbol("element-attr-group-id");

  const printTag = (doc) =>
    group([
      group(printOpeningTag(path, options, print), { id: attrGroupId }),
      doc,
      printClosingTag(node, options),
    ]);

  const printChildrenDoc = (childrenDoc) => {
    if (shouldHugContent) {
      return indentIfBreak(childrenDoc, { groupId: attrGroupId });
    }
    if (
      (isScriptLikeTag(node) || isVueCustomBlock(node, options)) &&
      node.parent.type === "root" &&
      options.parser === "vue" &&
      !options.vueIndentScriptAndStyle
    ) {
      return childrenDoc;
    }
    return indent(childrenDoc);
  };

  const printLineBeforeChildren = () => {
    if (shouldHugContent) {
      return ifBreak(softline, "", { groupId: attrGroupId });
    }
    if (
      node.firstChild.hasLeadingSpaces &&
      node.firstChild.isLeadingSpaceSensitive
    ) {
      return line;
    }
    if (
      node.firstChild.type === "text" &&
      node.isWhitespaceSensitive &&
      node.isIndentationSensitive
    ) {
      return dedentToRoot(softline);
    }
    return softline;
  };

  const printLineAfterChildren = () => {
    const needsToBorrow = node.next
      ? needsToBorrowPrevClosingTagEndMarker(node.next)
      : needsToBorrowLastChildClosingTagEndMarker(node.parent);
    if (needsToBorrow) {
      if (
        node.lastChild.hasTrailingSpaces &&
        node.lastChild.isTrailingSpaceSensitive
      ) {
        return " ";
      }
      return "";
    }
    if (shouldHugContent) {
      return ifBreak(softline, "", { groupId: attrGroupId });
    }
    if (
      node.lastChild.hasTrailingSpaces &&
      node.lastChild.isTrailingSpaceSensitive
    ) {
      return line;
    }
    if (
      (node.lastChild.type === "comment" ||
        (node.lastChild.type === "text" &&
          node.isWhitespaceSensitive &&
          node.isIndentationSensitive)) &&
      new RegExp(
        `\\n[\\t ]{${
          options.tabWidth *
          countParents(
            path,
            (node) => node.parent && node.parent.type !== "root"
          )
        }}$`
      ).test(node.lastChild.value)
    ) {
      return "";
    }
    return softline;
  };

  if (node.children.length === 0) {
    return printTag(
      node.hasDanglingSpaces && node.isDanglingSpaceSensitive ? line : ""
    );
  }

  return printTag([
    forceBreakContent(node) ? breakParent : "",
    printChildrenDoc([
      printLineBeforeChildren(),
      printChildren(path, options, print),
    ]),
    printLineAfterChildren(),
  ]);
}

module.exports = { printElement };


text:
package org.lwjglx.debug;

import static org.lwjglx.debug.Log.*;
import static org.lwjglx.debug.Properties.*;

import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;

import org.lwjglx.debug.ClassMetadata.MethodInfo;
import org.objectweb.asm.ClassReader;
import org.objectweb.asm.ClassVisitor;
import org.objectweb.asm.ClassWriter;
import org.objectweb.asm.MethodVisitor;
import org.objectweb.asm.Opcodes;
import org.objectweb.asm.Type;
import org.objectweb.asm.util.TraceClassVisitor;

class InterceptedCall {
    private static final AtomicInteger counter = new AtomicInteger();

    int index;
    String receiverInternalName;
    String resolvedReceiverInternalName;
    String name;
    String glName;
    String desc;
    String generatedMethodName;

    InterceptedCall(String receiverInternalName, String resolvedReceiverInternalName, String name, String desc) {
        this.index = counter.incrementAndGet();
        this.receiverInternalName = receiverInternalName;
        this.resolvedReceiverInternalName = resolvedReceiverInternalName;
        this.name = name;
        this.desc = desc;
    }
}

class Method {
    final String name;
    final String desc;

    Method(String name, String desc) {
        this.name = name;
        this.desc = desc;
    }

    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + desc.hashCode();
        result = prime * result + name.hashCode();
        return result;
    }

    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        Method other = (Method) obj;
        if (!desc.equals(other.desc))
            return false;
        if (!name.equals(other.name))
            return false;
        return true;
    }
}

class ClassKey {
    final ClassLoader cl;
    final String internalName;

    ClassKey(ClassLoader cl, String internalName) {
        this.cl = cl;
        this.internalName = internalName;
    }

    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + cl.hashCode();
        result = prime * result + internalName.hashCode();
        return result;
    }

    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        ClassKey other = (ClassKey) obj;
        if (cl != other.cl)
            return false;
        if (!internalName.equals(other.internalName))
            return false;
        return true;
    }
}

class InterceptClassGenerator implements Opcodes {

    private static final String MethodCall_InternalName = "org/lwjglx/debug/MethodCall";
    private static final String MethodCall_Desc = "L" + MethodCall_InternalName + ";";
    private static final String RT_InternalName = "org/lwjglx/debug/RT";

    private static final Map<ClassKey, HashSet<Method>> declaredMethods = new ConcurrentHashMap<>();

    private static boolean isGLcall(InterceptedCall call) {
        return (call.name.startsWith("gl") || call.name.startsWith("ngl")) && call.resolvedReceiverInternalName.startsWith("org/lwjgl/opengl/");
    }

    private static String glCall(InterceptedCall call) {
        if (!isGLcall(call))
            return null;
        String name = call.name;
        if (name.startsWith("ngl")) {
            name = name.substring(1);
        }
        try {
            org.lwjgl.opengl.GLCapabilities.class.getField(name);
            return name;
        } catch (Exception e) {
            /* Try with 'v' suffix */
            String nameV = name + "v";
            try {
                org.lwjgl.opengl.GLCapabilities.class.getField(nameV);
                return nameV;
            } catch (Exception e2) {
                if (DEBUG.enabled)
                    debug("Expected field GLCapabilities." + name + " to exist");
                return null;
            }
        }
    }

    private static boolean isMainThreadMethod(InterceptedCall call) {
        if (call.resolvedReceiverInternalName.equals("org/lwjgl/glfw/GLFW")) {
            return Arrays
                    .asList("glfwInit", "glfwTerminate", "glfwCreateWindow", "glfwDefaultWindowHints", "glfwDestroyWindow", "glfwFocusWindow", "glfwGetFramebufferSize", "glfwGetWindowAttrib",
                            "glfwGetWindowFrameSize", "glfwGetWindowMonitor", "glfwGetWindowPos", "glfwGetWindowSize", "glfwHideWindow", "glfwIconifyWindow", "glfwMaximizeWindow", "glfwPollEvents",
                            "glfwRestoreWindow", "glfwSetFramebufferSizeCallback", "glfwSetWindowAspectRatio", "glfwSetWindowCloseCallback", "glfwSetWindowFocusCallback", "glfwSetWindowIcon",
                            "glfwSetWindowIconifyCallback", "glfwSetWindowMonitor", "glfwSetWindowPos", "glfwSetWindowPosCallback", "glfwSetWindowRefreshCallback", "glfwSetWindowSize",
                            "glfwSetWindowSizeCallback", "glfwSetWindowSizeLimits", "glfwSetWindowTitle", "glfwShowWindow", "glfwWaitEvents", "glfwWaitEventsTimeout", "glfwWindowHint")
                    .contains(call.name);
        }
        return false;
    }

    private static boolean requiresGlfwInit(InterceptedCall call) {
        if (call.resolvedReceiverInternalName.equals("org/lwjgl/glfw/GLFW")) {
            return call.name.startsWith("glfw") && !call.name.equals("glfwSetErrorCallback") && !call.name.equals("glfwInit");
        }
        return false;
    }

    private static void checkFunctionSupported(MethodVisitor mv, String name) {
        mv.visitFieldInsn(GETFIELD, "org/lwjgl/opengl/GLCapabilities", name, "J");
        mv.visitLdcInsn(name);
        mv.visitMethodInsn(INVOKESTATIC, RT_InternalName, "checkFunction", "(JLjava/lang/String;)V", false);
    }

    private static String getClassForMethod(ClassLoader cl, String desc, InterceptedCall call) {
        String className = "org/lwjglx/debug/" + call.resolvedReceiverInternalName;
        ClassKey key = new ClassKey(cl, className);
        HashSet<Method> dmethods = declaredMethods.get(key);
        if (dmethods == null) {
            dmethods = new HashSet<>();
            declaredMethods.put(key, dmethods);
            InputStream is = cl.getResourceAsStream(className + ".class");
            if (is == null) {
                return null;
            }
            ClassReader cr;
            try {
                cr = new ClassReader(is);
            } catch (IOException e) {
                return null;
            }
            final HashSet<Method> methods = dmethods;
            cr.accept(new ClassVisitor(ASM9) {
                public MethodVisitor visitMethod(int access, String name, String desc, String signature, String[] exceptions) {
                    boolean isStatic = (access & ACC_STATIC) != 0;
                    boolean isPublic = (access & ACC_PUBLIC) != 0;
                    if (!isStatic || !isPublic)
                        return null;
                    methods.add(new Method(name, desc));
                    return null;
                }
            }, ClassReader.SKIP_CODE | ClassReader.SKIP_DEBUG | ClassReader.SKIP_FRAMES);
        }
        Method searched = new Method(call.name, desc);
        if (dmethods.contains(searched))
            return className;
        return null;
    }

    public static Class<?> generate(ClassLoader classLoader, String proxyInternalName, String callerName, Collection<InterceptedCall> calls, String source) {
        ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_MAXS);
        cw.visit(V1_6, ACC_PUBLIC | ACC_SUPER | ACC_SYNTHETIC, proxyInternalName, null, "java/lang/Object", null);
        MethodVisitor ctor = cw.visitMethod(ACC_PRIVATE | ACC_SYNTHETIC, "<init>", "()V", null, null);
        ctor.visitCode();
        ctor.visitVarInsn(ALOAD, 0);
        ctor.visitMethodInsn(INVOKESPECIAL, "java/lang/Object", "<init>", "()V", false);
        ctor.visitInsn(RETURN);
        ctor.visitMaxs(-1, -1);
        ctor.visitEnd();
        /* Generate a new method for each intercepted call */
        for (InterceptedCall call : calls) {
            String effectiveDesc = call.desc;
            if (TRACE.enabled) {
                effectiveDesc = call.desc.substring(0, call.desc.lastIndexOf(')')) + "I" + call.desc.substring(call.desc.lastIndexOf(')'));
            }
            MethodVisitor mv = cw.visitMethod(ACC_PUBLIC | ACC_STATIC | ACC_SYNTHETIC, call.generatedMethodName, effectiveDesc, null, null);
            mv.visitCode();
            {
                if (VALIDATE.enabled) {
                    /* Check if the method may only be called from the main thread */
                    if (isMainThreadMethod(call)) {
                        mv.visitLdcInsn(call.name);
                        mv.visitMethodInsn(INVOKESTATIC, RT_InternalName, "checkMainThread", "(Ljava/lang/String;)V", false);
                    }
                    /* and whether it was a GLFW method that requires glfwInit() to have been called */
                    if (requiresGlfwInit(call)) {
                        mv.visitLdcInsn(call.name);
                        mv.visitMethodInsn(INVOKESTATIC, RT_InternalName, "checkGlfwInitialized", "(Ljava/lang/String;)V", false);
                    }
                }
                /* Validate buffer arguments and also load all arguments onto stack */
                Type[] paramTypes = Type.getArgumentTypes(call.desc);
                Type retType = Type.getReturnType(call.desc);
                ClassMetadata classMetadata = ClassMetadata.create(call.resolvedReceiverInternalName, classLoader);
                MethodInfo minfo = classMetadata.methods.get(call.name + call.desc);
                int var = loadArgumentsAndValidateArguments(mv, paramTypes, classMetadata, minfo, call);
                /* Allocate locals for the source/line parameters (only available when TRACE) */
                int lineVar = var++;
                /* check if GL call */
                call.glName = glCall(call);
                if (call.glName != null) {
                    if (VALIDATE.enabled) {
                        /* if GL call, then check whether GLCapabilities have been set */
                        mv.visitMethodInsn(INVOKESTATIC, "org/lwjgl/opengl/GL", "getCapabilities", "()Lorg/lwjgl/opengl/GLCapabilities;", false);
                        /* and whether the function is supported */
                        checkFunctionSupported(mv, call.glName);
                    }
                }
                /* Optionally delay the call */
                sleep(mv);
                /* Do we want to output a call trace? */
                if (TRACE.enabled) {
                    /* What is the expected descriptor of the trace method? */
                    String traceMethodDesc = buildTraceMethodDesc(call, retType);
                    /* push a new MethodCall object on the stack */
                    if (source != null)
                        mv.visitLdcInsn(source);
                    else
                        mv.visitInsn(ACONST_NULL);
                    mv.visitVarInsn(ILOAD, lineVar);
                    mv.visitLdcInsn(call.name);
                    mv.visitMethodInsn(INVOKESTATIC, RT_InternalName, "methodCall", "(Ljava/lang/String;ILjava/lang/String;)" + MethodCall_Desc, false);
                    int methodCallVar = var++; // <- local to hold the created MethodCall
                    /* check if we have a user-provided trace method */
                    String traceMethodOwnerName = getClassForMethod(classLoader, traceMethodDesc, call);
                    if (traceMethodOwnerName != null) {
                        mv.visitVarInsn(ASTORE, methodCallVar); // <- store in local
                        /* Call a user-provided intercept method or the target method */
                        callUserMethodOrDirect(classLoader, call, mv);
                        /* Store the return value in a local */
                        int retVar = var++;
                        if (retType.getSort() != Type.VOID) {
                            mv.visitVarInsn(retType.getOpcode(ISTORE), retVar);
                        }
                        /* Repeat the arguments onto stack */
                        loadArguments(mv, paramTypes);
                        /* and load the return value (if any) */
                        if (retType.getSort() != Type.VOID) {
                            mv.visitVarInsn(retType.getOpcode(ILOAD), retVar);
                        } else {
                            mv.visitInsn(ACONST_NULL);
                        }
                        /* Call the trace method */
                        mv.visitVarInsn(ALOAD, methodCallVar);
                        mv.visitMethodInsn(INVOKESTATIC, traceMethodOwnerName, call.name, traceMethodDesc, false);
                        mv.visitVarInsn(ALOAD, methodCallVar);
                        mv.visitMethodInsn(INVOKESTATIC, RT_InternalName, "methodCall", "(Lorg/lwjglx/debug/MethodCall;)V", false);
                        if (retType.getSort() != Type.VOID) {
                            /* Load return value on stack for final return from proxy method */
                            mv.visitVarInsn(retType.getOpcode(ILOAD), retVar);
                        }
                    } else {
                        /* No user-provided trace method -> generate default trace prolog */
                        mv.visitInsn(DUP); // <- duplicate MethodCall to be reused in generateDefaultTraceBefore()
                        mv.visitVarInsn(ASTORE, methodCallVar); // <- store in local
                        /* Generate trace prolog */
                        generateDefaultTraceBefore(call, mv, paramTypes, minfo);
                        /* Call a user-provided intercept method or the target method */
                        callUserMethodOrDirect(classLoader, call, mv);
                        /* Generate default trace epilog */
                        generateDefaultTraceAfter(call, mv, methodCallVar, retType, minfo);
                    }
                } else {
                    /* Call a user-provided intercept method or the target method */
                    callUserMethodOrDirect(classLoader, call, mv);
                }
                /* and finally return the return value */
                mv.visitInsn(retType.getOpcode(IRETURN));
            }
            mv.visitMaxs(-1, -1);
            mv.visitEnd();
        }
        cw.visitEnd();
        byte[] arr = cw.toByteArray();
        if (DEBUG.enabled) {
            debug("Created proxy class for [" + callerName + "] (" + String.format("%,d", arr.length) + " bytes)");
            TraceClassVisitor tcv = new TraceClassVisitor(new PrintWriter(System.err));
            ClassReader tcr = new ClassReader(arr);
            tcr.accept(tcv, 0);
        }
        Class<?> generatedClass = ClassUtils.defineClass(classLoader, RT.class, proxyInternalName, arr);
        return generatedClass;
    }

    private static String buildTraceMethodDesc(InterceptedCall call, Type retType) {
        String traceMethodDesc = call.desc.substring(0, call.desc.lastIndexOf(')'));
        if (retType.getSort() != Type.VOID) {
            traceMethodDesc += retType.getDescriptor();
        } else {
            traceMethodDesc += "Ljava/lang/Void;";
        }
        traceMethodDesc += "Lorg/lwjglx/debug/MethodCall;";
        traceMethodDesc += ")V";
        return traceMethodDesc;
    }

    private static void sleep(MethodVisitor mv) {
        if (Properties.SLEEP > 0L) {
            mv.visitMethodInsn(INVOKESTATIC, RT_InternalName, "delay", "()V", false);
        }
    }

    private static int loadArgumentsAndValidateArguments(MethodVisitor mv, Type[] paramTypes, ClassMetadata classMetadata, MethodInfo minfo, InterceptedCall call) {
        int var = 0; // <- counts the used local variables
        for (int i = 0; i < paramTypes.length; i++) {
            Type paramType = paramTypes[i];
            mv.visitVarInsn(paramType.getOpcode(ILOAD), var);
            if (VALIDATE.enabled) {
                if (paramType.getSort() == Type.OBJECT && Util.isBuffer(paramType.getInternalName())) {
                    mv.visitInsn(DUP);
                    mv.visitLdcInsn(call.resolvedReceiverInternalName);
                    mv.visitLdcInsn(minfo.name);
                    mv.visitMethodInsn(INVOKESTATIC, RT_InternalName, "checkBuffer", "(" + paramType.getDescriptor() + "Ljava/lang/String;Ljava/lang/String;)V", false);
                }
                if (ClassMetadata.hasNullables && (paramType.getSort() == Type.OBJECT || paramType.getSort() == Type.ARRAY) && !minfo.nullable[i]) {
                    mv.visitInsn(DUP);
                    mv.visitLdcInsn(i);
                    if (minfo.parameterNames[i] != null)
                        mv.visitLdcInsn(minfo.parameterNames[i]);
                    else
                        mv.visitInsn(ACONST_NULL);
                    mv.visitMethodInsn(INVOKESTATIC, RT_InternalName, "checkNotNull", "(Ljava/lang/Object;ILjava/lang/String;)V", false);
                }
            }
            var += paramType.getSize();
        }
        return var;
    }

    private static void loadArguments(MethodVisitor mv, Type[] paramTypes) {
        int var = 0;
        for (int i = 0; i < paramTypes.length; i++) {
            Type paramType = paramTypes[i];
            mv.visitVarInsn(paramType.getOpcode(ILOAD), var);
            var += paramType.getSize();
        }
    }

    private static void callUserMethodOrDirect(ClassLoader classLoader, InterceptedCall call, MethodVisitor mv) {
        /* Check if we have a user-provided validation method */
        String validationMethodOwnerName = getClassForMethod(classLoader, call.desc, call);
        if (validationMethodOwnerName != null) {
            /* we have, so call it... */
            mv.visitMethodInsn(INVOKESTATIC, validationMethodOwnerName, call.name, call.desc, false);
        } else {
            /* we don't have a user-defined validation method yet, so just call the target method directly */
            mv.visitMethodInsn(INVOKESTATIC, call.resolvedReceiverInternalName, call.name, call.desc, false);
        }
        /* Check GL error if it was a GL call */
        if (VALIDATE.enabled && call.glName != null && !call.glName.equals("glGetError")) {
            mv.visitLdcInsn(call.name);
            mv.visitMethodInsn(INVOKESTATIC, RT_InternalName, "checkError", "(Ljava/lang/String;)V", false);
        }
    }

    private static int loadGLenum(String name, String helperMethod, MethodVisitor mv, int var, int glEnumIndex) {
        String fieldName = name;
        try {
            GLmetadata.class.getDeclaredField(fieldName);
        } catch (NoSuchFieldException e) {
            fieldName += "v";
        }
        mv.visitMethodInsn(INVOKESTATIC, "org/lwjglx/debug/GLmetadata", fieldName, "()Lorg/lwjglx/debug/Command;", false);
        Util.ldcI(mv, glEnumIndex);
        mv.visitVarInsn(ILOAD, var);
        mv.visitMethodInsn(INVOKESTATIC, RT_InternalName, helperMethod, "(Lorg/lwjglx/debug/Command;II)Ljava/lang/String;", false);
        mv.visitMethodInsn(INVOKEVIRTUAL, MethodCall_InternalName, "paramEnum", "(Ljava/lang/String;)" + MethodCall_Desc, false);
        glEnumIndex++;
        return glEnumIndex;
    }

    private static void loadGLenumReturn(String name, String helperMethod, MethodVisitor mv) {
        String fieldName = name;
        try {
            GLmetadata.class.getDeclaredField(fieldName);
        } catch (NoSuchFieldException e) {
            fieldName += "v";
        }
        mv.visitMethodInsn(INVOKESTATIC, "org/lwjglx/debug/GLmetadata", fieldName, "()Lorg/lwjglx/debug/Command;", false);
        mv.visitMethodInsn(INVOKESTATIC, RT_InternalName, helperMethod, "(I" + MethodCall_Desc + "Lorg/lwjglx/debug/Command;)I", false);
    }

    private static void generateDefaultTraceBefore(InterceptedCall call, MethodVisitor mv, Type[] paramTypes, MethodInfo minfo) {
        int var = 0;
        int glEnumIndex = 0;
        for (int i = 0; i < paramTypes.length; i++) {
            Type paramType = paramTypes[i];
            String nativeType = minfo.parameterNativeTypes[i];
            if ("GLenum".equals(nativeType) || "GLboolean".equals(nativeType)) {
                glEnumIndex = loadGLenum(call.glName, "glEnumFor", mv, var, glEnumIndex);
            } else if ("GLbitfield".equals(nativeType)) {
                glEnumIndex = loadGLenum(call.glName, "decodeBitField", mv, var, glEnumIndex);
            } else if ("GLFWwindow *".equals(nativeType)) {
                mv.visitVarInsn(paramType.getOpcode(ILOAD), var);
                mv.visitMethodInsn(INVOKESTATIC, RT_InternalName, "paramGlfwWindow", "(" + MethodCall_Desc + paramType.getDescriptor() + ")" + MethodCall_Desc, false);
            } else if ("GLFWmonitor *".equals(nativeType)) {
                mv.visitVarInsn(paramType.getOpcode(ILOAD), var);
                mv.visitMethodInsn(INVOKESTATIC, RT_InternalName, "paramGlfwMonitor", "(" + MethodCall_Desc + paramType.getDescriptor() + ")" + MethodCall_Desc, false);
            } else {
                mv.visitVarInsn(paramType.getOpcode(ILOAD), var);
                if (paramType.getSort() == Type.ARRAY || paramType.getSort() == Type.OBJECT) {
                    mv.visitMethodInsn(INVOKEVIRTUAL, MethodCall_InternalName, "param", "(Ljava/lang/Object;)" + MethodCall_Desc, false);
                } else {
                    mv.visitMethodInsn(INVOKEVIRTUAL, MethodCall_InternalName, "param", "(" + paramType.getDescriptor() + ")" + MethodCall_Desc, false);
                }
            }
            var += paramType.getSize();
        }
        mv.visitInsn(POP);
    }

    private static void generateDefaultTraceAfter(InterceptedCall call, MethodVisitor mv, int mcvar, Type retType, MethodInfo minfo) {
        if (retType.getSort() == Type.VOID) {
            // Do nothing
        } else if (retType.getSort() == Type.ARRAY || retType.getSort() == Type.OBJECT) {
            mv.visitVarInsn(ALOAD, mcvar);
            mv.visitMethodInsn(INVOKESTATIC, RT_InternalName, "returnValue", "(Ljava/lang/Object;" + MethodCall_Desc + ")Ljava/lang/Object;", false);
            if (!"java/lang/Object".equals(retType.getInternalName()))
                mv.visitTypeInsn(CHECKCAST, retType.getInternalName());
        } else {
            mv.visitVarInsn(ALOAD, mcvar);
            String returnNativeType = minfo.returnNativeType;
            if ("GLenum".equals(returnNativeType) || "GLboolean".equals(returnNativeType)) {
                loadGLenumReturn(call.glName, "glEnumReturn", mv);
            } else if ("GLFWwindow *".equals(returnNativeType)) {
                mv.visitMethodInsn(INVOKESTATIC, RT_InternalName, "returnValueGlfwWindow", "(" + retType.getDescriptor() + MethodCall_Desc + ")" + retType.getDescriptor(), false);
            } else if ("GLFWmonitor *".equals(returnNativeType)) {
                mv.visitMethodInsn(INVOKESTATIC, RT_InternalName, "returnValueGlfwMonitor", "(" + retType.getDescriptor() + MethodCall_Desc + ")" + retType.getDescriptor(), false);
            } else {
                mv.visitMethodInsn(INVOKESTATIC, RT_InternalName, "returnValue", "(" + retType.getDescriptor() + MethodCall_Desc + ")" + retType.getDescriptor(), false);
            }
        }
        mv.visitVarInsn(ALOAD, mcvar);
        mv.visitMethodInsn(INVOKESTATIC, RT_InternalName, "methodCall", "(Lorg/lwjglx/debug/MethodCall;)V", false);
    }

}


text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.sudoku.grid.tests;

import com.sudoku.data.model.Comment;
import static com.sudoku.data.factory.GridFactory.generateRandomGrid;
import com.sudoku.data.manager.UserManager;
import com.sudoku.data.model.Grid;
import com.sudoku.data.model.Tag;
import com.sudoku.data.model.User;
import com.sudoku.grid.editor.IhmGridEditorManuallyFilled;
import com.sudoku.grid.editor.IhmGridEditorRandomlyFilled;
import com.sudoku.grid.manager.IhmGridLayout;
import com.sudoku.grid.preview.IhmGridDetailledPreview;
import com.sudoku.grid.player.IhmGridPlayer;
import com.sudoku.grid.popups.IhmPopupsList;
import java.util.ArrayList;
import java.util.List;
import javafx.application.Application;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.stage.Stage;
import javafx.stage.WindowEvent;

/**
 * @author Mehdi KANE, Céline TO, This is a test class for grid ihm (editor,
 * player and preview)
 */
public class SudokuTest extends Application {

  /**
   * @param args the command line arguments
   */
  public static void main(String[] args) {
    launch(args);
  }

  @Override
  public void start(Stage primaryStage) {

    IhmGridLayout ihm_test1;
    IhmGridLayout ihm_test2;
    IhmGridLayout ihm_test3;
    IhmGridLayout ihm_test4;
    IhmGridLayout ihm_test5;

    ihm_test1 = new IhmGridEditorRandomlyFilled();
    //ihm_test2 = new IhmGridEditorManuallyFilled();
    //ihm_test3 = new IhmGridPlayer(generateRandomGrid(20));
    //ihm_test4 = new IhmGridPreview(2, new Grid("", UserManager.getInstance().getLoggedUser()), 100);

    Grid g = generateRandomGrid();
    ArrayList<Tag> tagsList = new ArrayList<Tag>();
    tagsList.add(new Tag("tag1"));
    tagsList.add(new Tag("tag2"));
    g.setTags(tagsList);
    List<Comment> commentsList = new ArrayList<Comment>();
    Comment c1 = new Comment();
    c1.setComment("Comment1");
    Comment c2 = new Comment();
    c2.setComment("Comment2");
    commentsList.add(c1);
    commentsList.add(c2);
    g.setComments(commentsList);
    User user = UserManager.getInstance().getLoggedUser();
    g.setCreateUser(user);
    g.setTitle("test title");
    //ihm_test5 = new IhmGridDetailledPreview(g, 200);

    Scene scene = new Scene(ihm_test1, 800, 1000);
    //Scene scene = new Scene(ihm_test2, 800, 1000);
    //Scene scene = new Scene(ihm_test3, 800, 1000);
    //Scene scene = new Scene(ihm_test4, 800, 1000);
    //Scene scene = new Scene(ihm_test5, 300, 300);

    primaryStage.setTitle("Sudoku preview");
    primaryStage.setScene(scene);
    primaryStage.show();

    primaryStage.setOnCloseRequest(new EventHandler<WindowEvent>() {

      @Override
      public void handle(WindowEvent t) {
//        if (t.getEventType() == WindowEvent.WINDOW_CLOSE_REQUEST) {
//          IhmPopupsList.getInstance().killAllTimers();
//        }
      }

    });
  }

}


text:
package org.apache.maven.internal.impl;

import static org.apache.maven.internal.impl.Utils.nonNull;

import java.nio.file.Path;
import javax.inject.Inject;
import org.apache.maven.api.LocalRepository;
import org.apache.maven.api.annotations.Nonnull;

public class DefaultLocalRepository implements LocalRepository {

    private final @Nonnull org.eclipse.aether.repository.LocalRepository repository;

    @Inject
    public DefaultLocalRepository(@Nonnull org.eclipse.aether.repository.LocalRepository repository) {
        this.repository = nonNull(repository, "repository can not be null");
    }

    @Nonnull
    public org.eclipse.aether.repository.LocalRepository getRepository() {
        return repository;
    }

    @Nonnull
    @Override
    public String getId() {
        return repository.getId();
    }

    @Nonnull
    @Override
    public String getType() {
        return repository.getContentType();
    }

    @Nonnull
    @Override
    public Path getPath() {
        return repository.getBasedir().toPath();
    }
}


text:
import { Box, Flex, Sans, Serif, color } from "@artsy/palette"
import { ArtistSeriesEntity_member } from "v2/__generated__/ArtistSeriesEntity_member.graphql"
import { AnalyticsSchema } from "v2/Artsy/Analytics"
import { useTracking } from "v2/Artsy/Analytics/useTracking"
import { RouterLink } from "v2/Artsy/Router/RouterLink"
import { Truncator } from "v2/Components/Truncator"
import currency from "currency.js"
import React from "react"
import { createFragmentContainer, graphql } from "react-relay"
import { data as sd } from "sharify"
import styled from "styled-components"
import { get } from "v2/Utils/get"

export interface ArtistSeriesEntityProps {
  member: ArtistSeriesEntity_member
  itemNumber: number
}

export const ArtistSeriesEntity: React.FC<ArtistSeriesEntityProps> = ({
  member,
  itemNumber,
}) => {
  const {
    headerImage,
    artworksConnection,
    price_guidance,
    slug,
    title,
  } = member
  const artworks = artworksConnection.edges.map(({ node }) => node)
  const bgImages = artworks.map(({ image }) => image && image.url)
  const imageSize =
    bgImages!.length === 1 ? 221 : bgImages!.length === 2 ? 109 : 72

  const { trackEvent } = useTracking()

  const handleLinkClick = () => {
    trackEvent({
      action_type: AnalyticsSchema.ActionType.Click,
      context_page: AnalyticsSchema.PageName.CollectionPage,
      context_module: AnalyticsSchema.ContextModule.ArtistCollectionsRail,
      context_page_owner_type: AnalyticsSchema.OwnerType.Collection,
      type: AnalyticsSchema.Type.Thumbnail,
      destination_path: `${sd.APP_URL}/collection/${slug}`,
      item_number: itemNumber,
    })
  }

  return (
    <Container px={2} pt={2} pb={2} m={1}>
      <StyledLink to={`/collection/${slug}`} onClick={handleLinkClick}>
        <ImgWrapper>
          {bgImages!.length
            ? bgImages.map((url, i) => {
                const hit = artworks![i]
                const artistName = get(hit!.artist, a => a!.name)
                const alt = `${artistName ? artistName + ", " : ""}${
                  hit!.title
                }`
                return (
                  <SingleImgContainer key={i}>
                    <ImgOverlay width={imageSize} />
                    {url && (
                      <ArtworkImage
                        key={i}
                        src={url}
                        width={imageSize}
                        alt={alt}
                      />
                    )}
                  </SingleImgContainer>
                )
              })
            : headerImage && <ArtworkImage src={headerImage} width={221} />}
        </ImgWrapper>
        {
          <CollectionTitle pt={1} pb={0.5} size="3">
            <Truncator maxLineCount={1}>{title}</Truncator>
          </CollectionTitle>
        }
        {price_guidance && (
          <Sans size="2" color="black60" pb={1}>
            From $
            {currency(price_guidance, {
              separator: ",",
              precision: 0,
            }).format()}
          </Sans>
        )}
      </StyledLink>
    </Container>
  )
}

export const ArtworkImage = styled.img<{ width: number }>`
  width: ${({ width }) => width}px;
  height: 125px;
  background-color: ${color("black10")};
  object-fit: cover;
  object-position: center;
  opacity: 0.9;
`

const ImgOverlay = styled(Box)<{ width: number }>`
  height: 125px;
  background-color: ${color("black30")};
  opacity: 0.1;
  position: absolute;
  top: 0;
  left: 0;
  z-index: 7;
`

export const Container = styled(Box)`
  border: 1px solid ${color("black10")};
  border-radius: 2px;

  &:hover {
    text-decoration: none;
    border: 1px solid ${color("black60")};
  }
`

const SingleImgContainer = styled(Box)`
  position: relative;
  margin-right: 2px;

  &:last-child {
    margin-right: 0;
  }
`

const CollectionTitle = styled(Serif)`
  width: 100%;
`

export const ImgWrapper = styled(Flex)`
  width: 221px;
`

export const StyledLink = styled(RouterLink)`
  text-decoration: none;
  -webkit-tap-highlight-color: rgba(0, 0, 0, 0);

  &:hover {
    text-decoration: none;
  }
`

export const ArtistSeriesRailContainer = createFragmentContainer(
  ArtistSeriesEntity,
  {
    member: graphql`
      fragment ArtistSeriesEntity_member on MarketingCollection {
        slug
        headerImage
        thumbnail
        title
        price_guidance: priceGuidance
        artworksConnection(
          first: 3
          aggregations: [TOTAL]
          sort: "-decayed_merch"
        ) {
          edges {
            node {
              artist {
                name
              }
              title
              image {
                url(version: "small")
              }
            }
          }
        }
      }
    `,
  }
)