text:
/* This file was generated by SableCC (http://www.sablecc.org/). */

package org.acre.lang.node;

import java.util.*;
import org.acre.lang.analysis.*;

public final class AIdentifierUndefUndefinedExpr extends PUndefinedExpr
{
    private TIsUndefined _isUndefined_;
    private TBracketL _bracketL_;
    private TIdentifier _identifier_;
    private TBracketR _bracketR_;

    public AIdentifierUndefUndefinedExpr()
    {
    }

    public AIdentifierUndefUndefinedExpr(
        TIsUndefined _isUndefined_,
        TBracketL _bracketL_,
        TIdentifier _identifier_,
        TBracketR _bracketR_)
    {
        setIsUndefined(_isUndefined_);

        setBracketL(_bracketL_);

        setIdentifier(_identifier_);

        setBracketR(_bracketR_);

    }
    public Object clone()
    {
        return new AIdentifierUndefUndefinedExpr(
            (TIsUndefined) cloneNode(_isUndefined_),
            (TBracketL) cloneNode(_bracketL_),
            (TIdentifier) cloneNode(_identifier_),
            (TBracketR) cloneNode(_bracketR_));
    }

    public void apply(Switch sw)
    {
        ((Analysis) sw).caseAIdentifierUndefUndefinedExpr(this);
    }

    public TIsUndefined getIsUndefined()
    {
        return _isUndefined_;
    }

    public void setIsUndefined(TIsUndefined node)
    {
        if(_isUndefined_ != null)
        {
            _isUndefined_.parent(null);
        }

        if(node != null)
        {
            if(node.parent() != null)
            {
                node.parent().removeChild(node);
            }

            node.parent(this);
        }

        _isUndefined_ = node;
    }

    public TBracketL getBracketL()
    {
        return _bracketL_;
    }

    public void setBracketL(TBracketL node)
    {
        if(_bracketL_ != null)
        {
            _bracketL_.parent(null);
        }

        if(node != null)
        {
            if(node.parent() != null)
            {
                node.parent().removeChild(node);
            }

            node.parent(this);
        }

        _bracketL_ = node;
    }

    public TIdentifier getIdentifier()
    {
        return _identifier_;
    }

    public void setIdentifier(TIdentifier node)
    {
        if(_identifier_ != null)
        {
            _identifier_.parent(null);
        }

        if(node != null)
        {
            if(node.parent() != null)
            {
                node.parent().removeChild(node);
            }

            node.parent(this);
        }

        _identifier_ = node;
    }

    public TBracketR getBracketR()
    {
        return _bracketR_;
    }

    public void setBracketR(TBracketR node)
    {
        if(_bracketR_ != null)
        {
            _bracketR_.parent(null);
        }

        if(node != null)
        {
            if(node.parent() != null)
            {
                node.parent().removeChild(node);
            }

            node.parent(this);
        }

        _bracketR_ = node;
    }

    public String toString()
    {
        return ""
            + toString(_isUndefined_)
            + toString(_bracketL_)
            + toString(_identifier_)
            + toString(_bracketR_);
    }

    void removeChild(Node child)
    {
        if(_isUndefined_ == child)
        {
            _isUndefined_ = null;
            return;
        }

        if(_bracketL_ == child)
        {
            _bracketL_ = null;
            return;
        }

        if(_identifier_ == child)
        {
            _identifier_ = null;
            return;
        }

        if(_bracketR_ == child)
        {
            _bracketR_ = null;
            return;
        }

    }

    void replaceChild(Node oldChild, Node newChild)
    {
        if(_isUndefined_ == oldChild)
        {
            setIsUndefined((TIsUndefined) newChild);
            return;
        }

        if(_bracketL_ == oldChild)
        {
            setBracketL((TBracketL) newChild);
            return;
        }

        if(_identifier_ == oldChild)
        {
            setIdentifier((TIdentifier) newChild);
            return;
        }

        if(_bracketR_ == oldChild)
        {
            setBracketR((TBracketR) newChild);
            return;
        }

    }
}


text:
<?php

/**
 * @see https://developers.podio.com/doc/conversations
 */
class PodioConversationParticipant extends PodioObject
{
    public function __construct($podio, $attributes = array())
    {
        parent::__construct($podio);
        $this->property('created_on', 'datetime');

        $this->has_one('user', 'User');
        $this->has_one('created_via', 'Via');
        $this->has_one('created_by', 'ByLine');

        $this->init($attributes);
    }

}

redpajama_set_name: RedPajamaGithub


text:
module LazyHighCharts
  module LayoutHelper
    def high_chart_iruby(chart_class, placeholder, object, &block)
      object.html_options[:id] = placeholder
      object.options[:chart][:renderTo] = placeholder
      build_html_output_iruby(
        chart_class, placeholder, object, &block
      ).concat(content_tag('div', '', object.html_options))
    end

    def high_map(placeholder, object, &block)
      object.html_options[:id] = placeholder
      object.options[:chart][:renderTo] = placeholder
      build_html_output(
        'Map', placeholder, object, &block
      ).concat(content_tag('div', '', object.html_options))
    end

    private

    def build_html_output_iruby(type, placeholder, object, &block)
      core_js =<<-EOJS
        var options = #{options_collection_as_string(object)};
        #{capture(&block) if block_given?}
        window.chart_#{placeholder.underscore} = new Highcharts.#{type}(options);
      EOJS

      encapsulate_js_iruby core_js
    end

    def encapsulate_js_iruby(core_js)
      js_output =
        if request_is_xhr?
          "#{js_start_iruby} #{core_js} #{js_end_iruby}"
        # Turbolinks.version < 5
        elsif defined?(Turbolinks)
          encapsulate_js_for_turbolinks(core_js)
        else
          call_core_js(core_js)
        end

      defined?(raw) ? raw(js_output) : js_output
    end

    def encapsulate_js_for_turbolinks(core_js)
      if request_is_referrer?
        eventlistener_page_load(core_js)
      elsif request_turbolinks_5_tureferrer?
        eventlistener_turbolinks_load(core_js)
      end
    end

    def eventlistener_page_load(core_js)
      <<-EOJS
      #{js_start_iruby}
        var f = function(){
          document.removeEventListener('page:load', f, true);
          #{core_js}
        };
        document.addEventListener('page:load', f, true);
      #{js_end_iruby}
      EOJS
    end

    def eventlistener_turbolinks_load(core_js)
      <<-EOJS
      #{js_start_iruby}
        document.addEventListener("turbolinks:load", function() {
          #{core_js}
        });
      #{js_end_iruby}
      EOJS
    end

    def call_core_js(core_js)
      <<-EOJS
      #{js_start_iruby}
        #{core_js}
      #{js_end_iruby}
      EOJS
    end

    def js_start_iruby
      <<-EOJS
        <script type="text/javascript">
        $(function() {
      EOJS
    end

    def js_end_iruby
      <<-EOJS
        });
        </script>
      EOJS
    end
  end
end


text:
#ifndef __PU_GRAVITY_AFFECTOR_H__
#define __PU_GRAVITY_AFFECTOR_H__

#include "ParticleUniversePrerequisites.h"
#include "ParticleUniverseAffector.h"

namespace ParticleUniverse
{
	/** This affector applies Newton's law of universal gravitation. The distance between a particle
		and the GravityAffector is important in the calculation of the gravity. Therefor, this affector needs
		to have its position set.
    */
	class _ParticleUniverseExport GravityAffector : public ParticleAffector
	{
		public:
			// Constants
			static const Real DEFAULT_GRAVITY;

			GravityAffector(void);
	        virtual ~GravityAffector(void) {};

			/** @copydoc ParticleAffector::copyAttributesTo */
			virtual void copyAttributesTo (ParticleAffector* affector);

			/**
	        */
			virtual void _preProcessParticles(ParticleTechnique* particleTechnique, Real timeElapsed);

			/**
	        */
			virtual void _affect(ParticleTechnique* particleTechnique, Particle* particle, Real timeElapsed);

			/**
	        */
			Real getGravity(void) const;
			void setGravity(Real gravity);

	protected:
			Real mGravity;
	};

}
#endif


text:
from __future__ import unicode_literals, print_function, absolute_import

import os
from flask import Blueprint, render_template

tmpl_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), "templates")
stat_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), "static")
main_bp = Blueprint(
    "webui_main", __name__, template_folder=tmpl_dir, static_folder=stat_dir
)

@main_bp.route("/")
def home():
    return render_template("main.html")


text:
package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10;

import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.fasterxml.jackson.annotation.JsonTypeName;

/**
 * A2A provider specific recovery point details.
 */
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "instanceType")
@JsonTypeName("A2A")
public class A2ARecoveryPointDetails extends ProviderSpecificRecoveryPointDetails {
    /**
     * A value indicating whether the recovery point is multi VM consistent.
     * Possible values include: 'MultiVmSyncRecoveryPoint',
     * 'PerVmRecoveryPoint'.
     */
    @JsonProperty(value = "recoveryPointSyncType")
    private RecoveryPointSyncType recoveryPointSyncType;

    /**
     * Get a value indicating whether the recovery point is multi VM consistent. Possible values include: 'MultiVmSyncRecoveryPoint', 'PerVmRecoveryPoint'.
     *
     * @return the recoveryPointSyncType value
     */
    public RecoveryPointSyncType recoveryPointSyncType() {
        return this.recoveryPointSyncType;
    }

    /**
     * Set a value indicating whether the recovery point is multi VM consistent. Possible values include: 'MultiVmSyncRecoveryPoint', 'PerVmRecoveryPoint'.
     *
     * @param recoveryPointSyncType the recoveryPointSyncType value to set
     * @return the A2ARecoveryPointDetails object itself.
     */
    public A2ARecoveryPointDetails withRecoveryPointSyncType(RecoveryPointSyncType recoveryPointSyncType) {
        this.recoveryPointSyncType = recoveryPointSyncType;
        return this;
    }

}


text:
module ApiAiRuby
  class TextRequest < ApiAiRuby::RequestQuery
    def initialize (client, options={})
      options[:lang] = client.api_lang
      super client, options
      @headers['Content-Type'] = 'application/json; charset=UTF-8'
    end
  end
end


text:
require 'pact_broker/api/resources/badge'

module PactBroker
  module Api
    module Resources
      class MatrixBadge < Badge

        private

        def latest_verification
          @latest_verification ||= verification_service.find_latest_verification_for_tags(
            identifier_from_path[:consumer_name],
            identifier_from_path[:provider_name],
            identifier_from_path[:tag],
            identifier_from_path[:provider_tag]
          )
        end
      end
    end
  end
end


text:
package in.iask.electonrush.commands;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

/**
 * The CommandGroup Class is a easy way to execute a group of commands together.
 * @author ElectricFish
 *
 */
public abstract class CommandGroup extends Command{

	protected class CommandEntry {
		Command command;
		boolean waitForPreviousCommandsCompletion;
	}

	Queue<CommandEntry> commandQueue = new LinkedList<CommandEntry>();
	Queue<CommandEntry> workingCommandQueue;
	List<Command> activeCommands;

	@Override
	protected void initialize() {
		//resets working command queue and active command list
		workingCommandQueue = new LinkedList<CommandEntry>(commandQueue);
		activeCommands = new ArrayList<Command>();

	}

	@Override
	protected void execute() {
		//if no command is currently active, then load new commands
		if(activeCommands.isEmpty()) {
			loadCommands();
		}

		for(int index = 0; index < activeCommands.size(); index++ ) {
			boolean finished = activeCommands.get(index).run();
			if(finished) {
				removeCommand(activeCommands.get(index));
			}
		}

	}

	@Override
	protected boolean isFinished() {
		return activeCommands.isEmpty() && workingCommandQueue.isEmpty();
	}

	@Override
	protected void end() {
		//nothing to do here as all commands would have ended before this is called
	}

	@Override
	protected void interrupted() {
		//interrupts all active commands is the entire group is interrupted.
		for(int index = 0; index < activeCommands.size(); index++ ) {
			activeCommands.get(index).cancel();
		}
	}
	/**
	 * This function offers a new command to the command queue.
	 * This function should only be called in the constructor.
	 *
	 * @param command the command to add
	 * @param waitForPreviousCommandsCompletion should the command should wait for previous commands to be completed?
	 */
	protected void addCommand(Command command,boolean waitForPreviousCommandsCompletion) {
		CommandEntry entry = new CommandEntry();
		entry.command = command;
		for(Subsystem requiredSubsystem:command.getRequiredSubsystems()) {
			requires(requiredSubsystem);
		}
		entry.waitForPreviousCommandsCompletion = waitForPreviousCommandsCompletion;
		commandQueue.offer(entry);
	}

	/**
	 * This function offers a new command to the command queue, this command will wait for all previous commands to finish before executing.
	 * This function should only be called in the constructor.
	 *
	 * @param command the command to add
	 */
	protected void addSequential(Command command) {
		addCommand(command,true);
	}

	/**
	 * This function offers a new command to the command queue, this command will NOT wait for all previous commands to finish before executing.
	 * This function should only be called in the constructor.
	 *
	 * @param command the command to add
	 */
	protected void addParallel(Command command) {
		addCommand(command,false);
	}

	/*
	 * Loads command into the active command list.
	 * This function should only be called if the active command list is empty.
	 */
	private void loadCommands() {
		//always load one command
		CommandEntry nextEntry = workingCommandQueue.poll();
		if(nextEntry != null) {
			activeCommands.add(nextEntry.command);

		}

		//continue to load commands until one that requires previous commands to be completed before executing it.
		while(true) {
			nextEntry = workingCommandQueue.peek();
			if(nextEntry != null) {
				if(nextEntry.waitForPreviousCommandsCompletion) {
					break; //if the command requires that currently running commands be completed first, do not load it.
				}else {
					workingCommandQueue.poll(); //removes this command from the queue first.
					activeCommands.add(nextEntry.command); //load the command.
				}
			}else {
				break; //if nextEntry is null, the command queue is empty. Stop attempting to load commands.
			}
		}
	}

	private void removeCommand(Command command) {
		activeCommands.remove(command);
	}

}


text:
> An example project based on SpringBoot2 integrated with oauth2 ( token persisted on redis ), swagger2, restful API, h2db, wechat miniapp, druid, mybatis ( generator and pagehelper included).

## Preparation
> install plugin `lombok` if you are using IDEA

> Create mysql database named `seed` by `db/schema.sql` & `db/data.sql`, then Run SpringBoot Application

## Features

#### druid
> see `http://localhost:8000/druid/login.html`

> username `root` and password `root` is same as mysql database

#### h2db console
> see `http://localhost:8000/h2`

> active when spring.profiles.active=dev

#### mybatis generator
> run `mvn mybatis-generator:generate`

#### swagger
> see `http://localhost:8000/swagger-ui.html `

#### oauth2
>use `curl http://localhost:8000/oauth/token -X POST -u client:security -d "grant_type=password&username=admin&password=admin"` to get access token, for example : `69aaaeb8-49c2-410d-8253-ad6c003c6091`

>then we can use `curl -X PUT -H "Authorization: Bearer 69aaaeb8-49c2-410d-8253-ad6c003c6091" --header "Content-Type: application/json" -d "{  \"newPassword\": \"new\",  \"oldPassword\": \"admin\"}" "http://localhost:8000/user/password"` to modify password

>also `curl http://localhost:8000/user/1 -X DELETE -H "Authorization: Bearer 69aaaeb8-49c2-410d-8253-ad6c003c6091"` to access other authenticated url

#### oauth2 with wechat miniapp login code
>baseURL `https://www.*.com`

>body `client_id=client&client_secret=security&grant_type=password&auth_type=wx_app&username=%3F&password=$code`

>method `POST`

>head Content-Type `application/x-www-form-urlencoded`

>url `/oauth/token`

#### remote service & client

> `https://github.com/ustcwudi/springboot-service`

> `https://github.com/ustcwudi/vue-seed`


text:
"""
    IsCool-e Pynba
    ~~~~~~~~~~~~~~

    :copyright: (c) 2015 by IsCool Entertainment.
    :license: MIT, see LICENSE for more details.
"""

from pynba.wsgi import PynbaMiddleware

__all__ = ['PynbaMiddleware']


text:
package javax.sound.midi;

import javax.sound.sampled.AudioInputStream;

/**
 * A {@code SoundbankResource} represents any audio resource stored in a
 * {@link Soundbank}. Common soundbank resources include:
 *

 *
Instruments. An instrument may be specified in a variety of ways.
 *   However, all soundbanks have some mechanism for defining instruments. In
 *   doing so, they may reference other resources stored in the soundbank.
 *   Each instrument has a {@code Patch} which specifies the MIDI program and
 *   bank by which it may be referenced in MIDI messages. Instrument information
 *   may be stored in {@link Instrument} objects.
 *
Audio samples. A sample typically is a sampled audio waveform which
 *   contains a short sound recording whose duration is a fraction of a
 *   second, or at most a few seconds. These audio samples may be used by a
 *   {@link Synthesizer} to synthesize sound in response to MIDI commands, or
 *   extracted for use by an application. (The terminology reflects musicians'
 *   use of the word "sample" to refer collectively to a series of contiguous
 *   audio samples or frames, rather than to a single, instantaneous sample.)
 *   The data class for an audio sample will be an object that encapsulates
 *   the audio sample data itself and information about how to interpret it
 *   (the format of the audio data), such as an {@link AudioInputStream}.
 *
Embedded sequences. A sound bank may contain built-in song data stored
 *   in a data object such as a {@link Sequence}.
 *

 * Synthesizers that use wavetable synthesis or related techniques play back the
 * audio in a sample when synthesizing notes, often when emulating the
 * real-world instrument that was originally recorded. However, there is not
 * necessarily a one-to-one correspondence between the {@code Instruments} and
 * samples in a {@code Soundbank}. A single {@code Instrument} can use multiple
 * SoundbankResources (typically for notes of dissimilar pitch or brightness).
 * Also, more than one {@code Instrument} can use the same sample.
 *
 * @author Kara Kytle
 */
public abstract class SoundbankResource {

    /**
     * The sound bank that contains the {@code SoundbankResources}.
     */
    private final Soundbank soundBank;

    /**
     * The name of the {@code SoundbankResource}.
     */
    private final String name;

    /**
     * The class used to represent the sample's data.
     */
    private final Class<?> dataClass;

    /**
     * The wavetable index.
     */
    //private final int index;

    /**
     * Constructs a new {@code SoundbankResource} from the given sound bank and
     * wavetable index. (Setting the {@code SoundbankResource's} name, sampled
     * audio data, and instruments is a subclass responsibility.)
     *
     * @param  soundBank the sound bank containing this
     *         {@code SoundbankResource}
     * @param  name the name of the sample
     * @param  dataClass the class used to represent the sample's data
     * @see #getSoundbank
     * @see #getName
     * @see #getDataClass
     * @see #getData
     */
    protected SoundbankResource(Soundbank soundBank, String name, Class<?> dataClass) {

        this.soundBank = soundBank;
        this.name = name;
        this.dataClass = dataClass;
    }

    /**
     * Obtains the sound bank that contains this {@code SoundbankResource}.
     *
     * @return the sound bank in which this {@code SoundbankResource} is stored
     */
    public Soundbank getSoundbank() {
        return soundBank;
    }

    /**
     * Obtains the name of the resource. This should generally be a string
     * descriptive of the resource.
     *
     * @return the instrument's name
     */
    public String getName() {
        return name;
    }

    /**
     * Obtains the class used by this sample to represent its data. The object
     * returned by {@code getData} will be of this class. If this
     * {@code SoundbankResource} object does not support direct access to its
     * data, returns {@code null}.
     *
     * @return the class used to represent the sample's data, or null if the
     *         data is not accessible
     */
    public Class<?> getDataClass() {
        return dataClass;
    }

    /**
     * Obtains the sampled audio that is stored in this
     * {@code SoundbankResource}. The type of object returned depends on the
     * implementation of the concrete class, and may be queried using
     * {@code getDataClass}.
     *
     * @return an object containing the sampled audio data
     * @see #getDataClass
     */
    public abstract Object getData();

    /**
     * Obtains the index of this {@code SoundbankResource} into the
     * {@code Soundbank's} set of {@code SoundbankResources}.
     *
     * @return the wavetable index
     */
    //public int getIndex() {
    //  return index;
    //}

    /**
     * Obtains a list of the instruments in the sound bank that use the
     * {@code SoundbankResource} for sound synthesis.
     *
     * @return an array of {@code Instruments} that reference this
     *         {@code SoundbankResource}
     * @see Instrument#getSamples
     */
    //public abstract Instrument[] getInstruments();
}


text:
<?php

use Hubzero\Content\Migration\Base;

/**
 * Migration script for installing Admin login module
 **/
class Migration20190109000000ModAdminlogin extends Base
{
	/**
	 * Up
	 **/
	public function up()
	{
		$this->addModuleEntry('mod_adminlogin', 1, '', 1);
	}

	/**
	 * Down
	 **/
	public function down()
	{
		$this->deleteModuleEntry('mod_adminlogin');
	}
}


text:
package br.com.developer.redu.models;

import com.google.gson.Gson;

/**
 * Created with IntelliJ IDEA.
 * User: igor
 * Date: 9/4/12
 * Time: 11:17 AM
 * To change this template use File | Settings | File Templates.
 */
public class CoursePayload {
    private course course;

    public CoursePayload(String name, String path, String workload, String description){
        course = new course();
        course.name = name;
        course.path = path;
        course.workload = workload;
        course.description = description;
    }

    class course{
        public String name;
        public String path;
        public String workload;
        public String description;
    }
    public static void main(String[] args){
        CoursePayload cp = new CoursePayload("coisa do cao", "coisa_do_cao","50", null);
        Gson g = new Gson();
        System.out.println(g.toJson(cp));
    }

}


text:
package ca.pfv.spmf.tools.dataset_converter;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URL;

/**
 * Example of how to convert a transaction database from the ARFF format to the
 * SPMF format.
 *

 *
 * The ARFF format is a format used by other data mining software (rapid-miner,
 * etc.). It allows representing a relational table as a text file. In SPMF, a
 * good effort has been made to support the conversion from the ARFF format to a
 * transaction database in SPMF format. All features of the ARFF format
 * specification are supported (see
 * http://weka.wikispaces.com/ARFF+%28stable+version%29 for the full ARFF
 * specification), except that the character "=" is forbidden and that escape
 * characters are not supported.
 *

 *
 * For example, the following input file (example.arff) is in ARFF format and
 * can be converted to SPMF format by the tool. This file defines a table named
 * "sunburn" having 6 attributes. The first five attributes have a limited set
 * of possible values. For example, the attribute "weight" is an enumeration
 * that can only take "blonde", "brown" or "red" as value, or "?" if the value
 * is unknown. The instances in this table are represented by each line after
 * the @data instruction. In this example, there is 9 such instances. The first
 * 8 instances are in regular ARFF format: each attribute value is separated by
 * a comma. The last instance is in sparse ARFF format. This means that some
 * attributes having a value of "0" are ommitted. Finally, note that lines
 * starting with "%" are comments". For additional details about the ARFF
 * format, please refer to the official specification.
 *
 * % % SUNBURN DATA % This file is a modified version of
 * http://www.hakank.org/weka/sunburn.arf % additional
 *
 * @RELATION 'sunburn'% THIS IS A COMMENT
 * @ATTRIBUTE 'weight' {blonde, brown, red}
 * @ATTRIBUTE 'height' {short, average, tall}
 * @ATTRIBUTE weight {light, average, heavy}
 * @ATTRIBUTE 'lotion' {yes,no}
 * @ATTRIBUTE 'burned' {burned, none} % THIS IS A COMMENT
 * @attribute col_17 INTEGER
 * @DATA% THIS IS A TEST ?, average,light, no, burned, 1 % THIS IS A COMMENT
 *        blonde, tall, average,yes, none, 2% THIS IS A COMMENT brown, short,
 *        average,yes, none, 3 blonde, short, average,no, burned, 4 red,
 *        average,heavy, no, burned, 5 brown, tall, heavy, no, none, 6 brown,
 *        average,heavy, no, none, 7 blonde, short, light, yes, none, 4 {1
 *        blonde, 2 average, 3, heavy, 4 none} % THIS IS A SPARSE DATA INSTANCE
 *        SPECIFICATION
 *
 *        Note that according to the ARFF format, an unknown value for an
 *        attribute is represented by the character "?". In SPMF, if you choose
 *        the format "ARFF", the unknown values will be ommitted during the
 *        conversion. If you want to keep the unknown values, then choose the
 *        alternative format "ARFF_WITH_MISSING_VALUES" for conversion, which
 *        will keep the unknown values.
 *
 *        The result of the conversion of the previous ARFF file is a file in
 *        SPMF format:
 * @CONVERTED_FROM_ARFF
 * @RELATION_NAME=sunburn=
 * @ATTRIBUTE=weight=ENUMERATION=blonde=brown=red=
 * @ATTRIBUTE=height=ENUMERATION=short=average=tall=
 * @ATTRIBUTE=weight=ENUMERATION=light=average=heavy=
 * @ATTRIBUTE=lotion=ENUMERATION=yes=no=
 * @ATTRIBUTE=burned=ENUMERATION=burned=none=
 * @ATTRIBUTE=col_17=INTEGER=
 * @ITEM=1=height=average
 * @ITEM=2=weight=light
 * @ITEM=3=lotion=no
 * @ITEM=4=burned=burned
 * @ITEM=5=col_17=1 1 2 3 4 5
 * @ITEM=6=weight=blonde
 * @ITEM=7=height=tall
 * @ITEM=8=weight=average
 * @ITEM=9=lotion=yes
 * @ITEM=10=burned=none
 * @ITEM=11=col_17=2 6 7 8 9 10 11
 * @ITEM=12=weight=brown
 * @ITEM=13=height=short
 * @ITEM=14=col_17=3 8 9 10 12 13 14
 * @ITEM=15=col_17=4 3 4 6 8 13 15
 * @ITEM=16=weight=red
 * @ITEM=17=weight=heavy
 * @ITEM=18=col_17=5 1 3 4 16 17 18
 * @ITEM=19=col_17=6 3 7 10 12 17 19
 * @ITEM=20=col_17=7 1 3 10 12 17 20 2 6 9 10 13 15
 *
 *                   The first line indicates that this file was obtained by a
 *                   conversion from ARFF to SPMF format. The second line
 *                   indicates the name of the original relational table
 *                   specified in the ARFF file. Each line starting with
 *                   "@attribute" defines an attribute in the table, its type
 *                   and the possible values that the attribute can take if the
 *                   type is "ENUMERATION". For example, the attribute "weight"
 *                   is an enumeration that can take a value from "blonde",
 *                   "brown" or "red". The lines starting with
 *                   "@ITEM= indicates a mapping between a unique ID an an attribute value. For example, the line "
 *                   @ITEM=1=height=average
 *                   " means that the ID 1 represents the value "
 *                   average" for the attribute "height
 *                   ". Finally, the lines that are a list of integers separated by spaces each represents a data instances. For example, the line "
 *                   1 2 3 4
 *                   5" represents the data instance with the value "average
 *                   " for the attribute "
 *                   height", the value "light" for the attribute "
 *                   weight", the value "
 *                   no" for the attribute "lotion", the value "
 *                   burned" for the attribute "burned" and the value 1" for the
 *                   attribute "col_17".
 *
 *                   Note that all lines starting with "@" are metadata that are
 *                   not used by the algorithms in SPMF". But this data is kept
 *                   so that the results found by the algorithms can be
 *                   interpreted.
 */
class MainTestConvertTransactionDatabaseARFFtoSPMF {

	public static void main(String[] arg) throws IOException {

		String inputFile = fileToPath("example.arff"); // the file to be converted in ARFF format
		String outputFile = ".//output.txt"; // the resulting converted file in SPMF format
		Formats inputFileformat = Formats.ARFF;  // the format of the input file (ARFF)
		int transactionCount = Integer.MAX_VALUE;  // the number of transaction from the input file to be converted

		// Create a converter
		TransactionDatabaseConverter converter = new TransactionDatabaseConverter();
		// Call the method to convert the input file from ARFF to the SPMF format
		converter
				.convert(inputFile, outputFile, inputFileformat, transactionCount);
	}

	public static String fileToPath(String filename)
			throws UnsupportedEncodingException {
		URL url = MainTestConvertTransactionDatabaseARFFtoSPMF.class
				.getResource(filename);
		return java.net.URLDecoder.decode(url.getPath(), "UTF-8");
	}
}


text:
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

#nullable disable

using Microsoft.CodeAnalysis;

namespace Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel
{
    internal static class CodeModelExtensions
    {
        private static readonly SymbolDisplayFormat s_fullNameWithEscapedKeywordsFormat =
            new SymbolDisplayFormat(
                globalNamespaceStyle: SymbolDisplayGlobalNamespaceStyle.Omitted,
                typeQualificationStyle: SymbolDisplayTypeQualificationStyle.NameAndContainingTypesAndNamespaces,
                propertyStyle: SymbolDisplayPropertyStyle.NameOnly,
                genericsOptions: SymbolDisplayGenericsOptions.IncludeTypeParameters,
                memberOptions: SymbolDisplayMemberOptions.IncludeExplicitInterface | SymbolDisplayMemberOptions.IncludeContainingType,
                miscellaneousOptions: SymbolDisplayMiscellaneousOptions.EscapeKeywordIdentifiers);

        public static string GetEscapedFullName(this ISymbol symbol)
            => symbol.ToDisplayString(s_fullNameWithEscapedKeywordsFormat);
    }
}


text:
import * as LogManager from 'aurelia-logging';
import { RouteRecognizer } from 'aurelia-route-recognizer';
import { Container } from 'aurelia-dependency-injection';
import { History } from 'aurelia-history';
import { EventAggregator } from 'aurelia-event-aggregator';

export function _normalizeAbsolutePath(path, hasPushState, absolute = false) {
  if (!hasPushState && path[0] !== '#') {
    path = '#' + path;
  }

  if (hasPushState && absolute) {
    path = path.substring(1, path.length);
  }

  return path;
}

export function _createRootedPath(fragment, baseUrl, hasPushState, absolute) {
  if (isAbsoluteUrl.test(fragment)) {
    return fragment;
  }

  let path = '';

  if (baseUrl.length && baseUrl[0] !== '/') {
    path += '/';
  }

  path += baseUrl;

  if ((!path.length || path[path.length - 1] !== '/') && fragment[0] !== '/') {
    path += '/';
  }

  if (path.length && path[path.length - 1] === '/' && fragment[0] === '/') {
    path = path.substring(0, path.length - 1);
  }

  return _normalizeAbsolutePath(path + fragment, hasPushState, absolute);
}

export function _resolveUrl(fragment, baseUrl, hasPushState) {
  if (isRootedPath.test(fragment)) {
    return _normalizeAbsolutePath(fragment, hasPushState);
  }

  return _createRootedPath(fragment, baseUrl, hasPushState);
}

const isRootedPath = /^#?\//;
const isAbsoluteUrl = /^([a-z][a-z0-9+\-.]*:)?\/\//i;

export const pipelineStatus = {
  completed: 'completed',
  canceled: 'canceled',
  rejected: 'rejected',
  running: 'running'
};

export let Pipeline = class Pipeline {
  constructor() {
    this.steps = [];
  }

  addStep(step) {
    let run;

    if (typeof step === 'function') {
      run = step;
    } else if (typeof step.getSteps === 'function') {
      let steps = step.getSteps();
      for (let i = 0, l = steps.length; i < l; i++) {
        this.addStep(steps[i]);
      }

      return this;
    } else {
      run = step.run.bind(step);
    }

    this.steps.push(run);

    return this;
  }

  run(instruction) {
    let index = -1;
    let steps = this.steps;

    function next() {
      index++;

      if (index < steps.length) {
        let currentStep = steps[index];

        try {
          return currentStep(instruction, next);
        } catch (e) {
          return next.reject(e);
        }
      } else {
        return next.complete();
      }
    }

    next.complete = createCompletionHandler(next, pipelineStatus.completed);
    next.cancel = createCompletionHandler(next, pipelineStatus.canceled);
    next.reject = createCompletionHandler(next, pipelineStatus.rejected);

    return next();
  }
};

function createCompletionHandler(next, status) {
  return output => {
    return Promise.resolve({ status, output, completed: status === pipelineStatus.completed });
  };
}

export let CommitChangesStep = class CommitChangesStep {
  run(navigationInstruction, next) {
    return navigationInstruction._commitChanges(true).then(() => {
      navigationInstruction._updateTitle();
      return next();
    });
  }
};

export let NavigationInstruction = class NavigationInstruction {

  constructor(init) {
    this.plan = null;
    this.options = {};

    Object.assign(this, init);

    this.params = this.params || {};
    this.viewPortInstructions = {};

    let ancestorParams = [];
    let current = this;
    do {
      let currentParams = Object.assign({}, current.params);
      if (current.config && current.config.hasChildRouter) {
        delete currentParams[current.getWildCardName()];
      }

      ancestorParams.unshift(currentParams);
      current = current.parentInstruction;
    } while (current);

    let allParams = Object.assign({}, this.queryParams, ...ancestorParams);
    this.lifecycleArgs = [allParams, this.config, this];
  }

  getAllInstructions() {
    let instructions = [this];
    for (let key in this.viewPortInstructions) {
      let childInstruction = this.viewPortInstructions[key].childNavigationInstruction;
      if (childInstruction) {
        instructions.push(...childInstruction.getAllInstructions());
      }
    }

    return instructions;
  }

  getAllPreviousInstructions() {
    return this.getAllInstructions().map(c => c.previousInstruction).filter(c => c);
  }

  addViewPortInstruction(viewPortName, strategy, moduleId, component) {
    let viewportInstruction = this.viewPortInstructions[viewPortName] = {
      name: viewPortName,
      strategy: strategy,
      moduleId: moduleId,
      component: component,
      childRouter: component.childRouter,
      lifecycleArgs: this.lifecycleArgs.slice()
    };

    return viewportInstruction;
  }

  getWildCardName() {
    let wildcardIndex = this.config.route.lastIndexOf('*');
    return this.config.route.substr(wildcardIndex + 1);
  }

  getWildcardPath() {
    let wildcardName = this.getWildCardName();
    let path = this.params[wildcardName] || '';

    if (this.queryString) {
      path += '?' + this.queryString;
    }

    return path;
  }

  getBaseUrl() {
    if (!this.params) {
      return this.fragment;
    }

    let wildcardName = this.getWildCardName();
    let path = this.params[wildcardName] || '';

    if (!path) {
      return this.fragment;
    }

    path = encodeURI(path);
    return this.fragment.substr(0, this.fragment.lastIndexOf(path));
  }

  _commitChanges(waitToSwap) {
    let router = this.router;
    router.currentInstruction = this;

    if (this.previousInstruction) {
      this.previousInstruction.config.navModel.isActive = false;
    }

    this.config.navModel.isActive = true;

    router._refreshBaseUrl();
    router.refreshNavigation();

    let loads = [];
    let delaySwaps = [];

    for (let viewPortName in this.viewPortInstructions) {
      let viewPortInstruction = this.viewPortInstructions[viewPortName];
      let viewPort = router.viewPorts[viewPortName];

      if (!viewPort) {
        throw new Error(`There was no router-view found in the view for ${ viewPortInstruction.moduleId }.`);
      }

      if (viewPortInstruction.strategy === activationStrategy.replace) {
        if (waitToSwap) {
          delaySwaps.push({ viewPort, viewPortInstruction });
        }

        loads.push(viewPort.process(viewPortInstruction, waitToSwap).then(x => {
          if (viewPortInstruction.childNavigationInstruction) {
            return viewPortInstruction.childNavigationInstruction._commitChanges();
          }

          return undefined;
        }));
      } else {
        if (viewPortInstruction.childNavigationInstruction) {
          loads.push(viewPortInstruction.childNavigationInstruction._commitChanges(waitToSwap));
        }
      }
    }

    return Promise.all(loads).then(() => {
      delaySwaps.forEach(x => x.viewPort.swap(x.viewPortInstruction));
      return null;
    }).then(() => prune(this));
  }

  _updateTitle() {
    let title = this._buildTitle();
    if (title) {
      this.router.history.setTitle(title);
    }
  }

  _buildTitle(separator = ' | ') {
    let title = this.config.navModel.title || '';
    let childTitles = [];

    for (let viewPortName in this.viewPortInstructions) {
      let viewPortInstruction = this.viewPortInstructions[viewPortName];

      if (viewPortInstruction.childNavigationInstruction) {
        let childTitle = viewPortInstruction.childNavigationInstruction._buildTitle(separator);
        if (childTitle) {
          childTitles.push(childTitle);
        }
      }
    }

    if (childTitles.length) {
      title = childTitles.join(separator) + (title ? separator : '') + title;
    }

    if (this.router.title) {
      title += (title ? separator : '') + this.router.title;
    }

    return title;
  }
};

function prune(instruction) {
  instruction.previousInstruction = null;
  instruction.plan = null;
}

export let NavModel = class NavModel {

  constructor(router, relativeHref) {
    this.isActive = false;
    this.title = null;
    this.href = null;
    this.relativeHref = null;
    this.settings = {};
    this.config = null;

    this.router = router;
    this.relativeHref = relativeHref;
  }

  setTitle(title) {
    this.title = title;

    if (this.isActive) {
      this.router.updateTitle();
    }
  }
};

export function isNavigationCommand(obj) {
  return obj && typeof obj.navigate === 'function';
}

export let Redirect = class Redirect {
  constructor(url, options = {}) {
    this.url = url;
    this.options = Object.assign({ trigger: true, replace: true }, options);
    this.shouldContinueProcessing = false;
  }

  setRouter(router) {
    this.router = router;
  }

  navigate(appRouter) {
    let navigatingRouter = this.options.useAppRouter ? appRouter : this.router || appRouter;
    navigatingRouter.navigate(this.url, this.options);
  }
};

export let RedirectToRoute = class RedirectToRoute {
  constructor(route, params = {}, options = {}) {
    this.route = route;
    this.params = params;
    this.options = Object.assign({ trigger: true, replace: true }, options);
    this.shouldContinueProcessing = false;
  }

  setRouter(router) {
    this.router = router;
  }

  navigate(appRouter) {
    let navigatingRouter = this.options.useAppRouter ? appRouter : this.router || appRouter;
    navigatingRouter.navigateToRoute(this.route, this.params, this.options);
  }
};

export let RouterConfiguration = class RouterConfiguration {
  constructor() {
    this.instructions = [];
    this.options = {};
    this.pipelineSteps = [];
  }

  addPipelineStep(name, step) {
    this.pipelineSteps.push({ name, step });
    return this;
  }

  addAuthorizeStep(step) {
    return this.addPipelineStep('authorize', step);
  }

  addPreActivateStep(step) {
    return this.addPipelineStep('preActivate', step);
  }

  addPreRenderStep(step) {
    return this.addPipelineStep('preRender', step);
  }

  addPostRenderStep(step) {
    return this.addPipelineStep('postRender', step);
  }

  map(route) {
    if (Array.isArray(route)) {
      route.forEach(this.map.bind(this));
      return this;
    }

    return this.mapRoute(route);
  }

  mapRoute(config) {
    this.instructions.push(router => {
      let routeConfigs = [];

      if (Array.isArray(config.route)) {
        for (let i = 0, ii = config.route.length; i < ii; ++i) {
          let current = Object.assign({}, config);
          current.route = config.route[i];
          routeConfigs.push(current);
        }
      } else {
        routeConfigs.push(Object.assign({}, config));
      }

      let navModel;
      for (let i = 0, ii = routeConfigs.length; i < ii; ++i) {
        let routeConfig = routeConfigs[i];
        routeConfig.settings = routeConfig.settings || {};
        if (!navModel) {
          navModel = router.createNavModel(routeConfig);
        }

        router.addRoute(routeConfig, navModel);
      }
    });

    return this;
  }

  mapUnknownRoutes(config) {
    this.unknownRouteConfig = config;
    return this;
  }

  exportToRouter(router) {
    let instructions = this.instructions;
    for (let i = 0, ii = instructions.length; i < ii; ++i) {
      instructions[i](router);
    }

    if (this.title) {
      router.title = this.title;
    }

    if (this.unknownRouteConfig) {
      router.handleUnknownRoutes(this.unknownRouteConfig);
    }

    router.options = this.options;

    let pipelineSteps = this.pipelineSteps;
    if (pipelineSteps.length) {
      if (!router.isRoot) {
        throw new Error('Pipeline steps can only be added to the root router');
      }

      let pipelineProvider = router.pipelineProvider;
      for (let i = 0, ii = pipelineSteps.length; i < ii; ++i) {
        let { name, step } = pipelineSteps[i];
        pipelineProvider.addStep(name, step);
      }
    }
  }
};

export const activationStrategy = {
  noChange: 'no-change',
  invokeLifecycle: 'invoke-lifecycle',
  replace: 'replace'
};

export let BuildNavigationPlanStep = class BuildNavigationPlanStep {
  run(navigationInstruction, next) {
    return _buildNavigationPlan(navigationInstruction).then(plan => {
      navigationInstruction.plan = plan;
      return next();
    }).catch(next.cancel);
  }
};

export function _buildNavigationPlan(instruction, forceLifecycleMinimum) {
  let prev = instruction.previousInstruction;
  let config = instruction.config;
  let plan = {};

  if ('redirect' in config) {
    let redirectLocation = _resolveUrl(config.redirect, getInstructionBaseUrl(instruction));
    if (instruction.queryString) {
      redirectLocation += '?' + instruction.queryString;
    }

    return Promise.reject(new Redirect(redirectLocation));
  }

  if (prev) {
    let newParams = hasDifferentParameterValues(prev, instruction);
    let pending = [];

    for (let viewPortName in prev.viewPortInstructions) {
      let prevViewPortInstruction = prev.viewPortInstructions[viewPortName];
      let nextViewPortConfig = config.viewPorts[viewPortName];

      if (!nextViewPortConfig) throw new Error(`Invalid Route Config: Configuration for viewPort "${ viewPortName }" was not found for route: "${ instruction.config.route }."`);

      let viewPortPlan = plan[viewPortName] = {
        name: viewPortName,
        config: nextViewPortConfig,
        prevComponent: prevViewPortInstruction.component,
        prevModuleId: prevViewPortInstruction.moduleId
      };

      if (prevViewPortInstruction.moduleId !== nextViewPortConfig.moduleId) {
        viewPortPlan.strategy = activationStrategy.replace;
      } else if ('determineActivationStrategy' in prevViewPortInstruction.component.viewModel) {
        viewPortPlan.strategy = prevViewPortInstruction.component.viewModel.determineActivationStrategy(...instruction.lifecycleArgs);
      } else if (config.activationStrategy) {
        viewPortPlan.strategy = config.activationStrategy;
      } else if (newParams || forceLifecycleMinimum) {
        viewPortPlan.strategy = activationStrategy.invokeLifecycle;
      } else {
        viewPortPlan.strategy = activationStrategy.noChange;
      }

      if (viewPortPlan.strategy !== activationStrategy.replace && prevViewPortInstruction.childRouter) {
        let path = instruction.getWildcardPath();
        let task = prevViewPortInstruction.childRouter._createNavigationInstruction(path, instruction).then(childInstruction => {
          viewPortPlan.childNavigationInstruction = childInstruction;

          return _buildNavigationPlan(childInstruction, viewPortPlan.strategy === activationStrategy.invokeLifecycle).then(childPlan => {
            childInstruction.plan = childPlan;
          });
        });

        pending.push(task);
      }
    }

    return Promise.all(pending).then(() => plan);
  }

  for (let viewPortName in config.viewPorts) {
    plan[viewPortName] = {
      name: viewPortName,
      strategy: activationStrategy.replace,
      config: instruction.config.viewPorts[viewPortName]
    };
  }

  return Promise.resolve(plan);
}

function hasDifferentParameterValues(prev, next) {
  let prevParams = prev.params;
  let nextParams = next.params;
  let nextWildCardName = next.config.hasChildRouter ? next.getWildCardName() : null;

  for (let key in nextParams) {
    if (key === nextWildCardName) {
      continue;
    }

    if (prevParams[key] !== nextParams[key]) {
      return true;
    }
  }

  for (let key in prevParams) {
    if (key === nextWildCardName) {
      continue;
    }

    if (prevParams[key] !== nextParams[key]) {
      return true;
    }
  }

  if (!next.options.compareQueryParams) {
    return false;
  }

  let prevQueryParams = prev.queryParams;
  let nextQueryParams = next.queryParams;
  for (let key in nextQueryParams) {
    if (prevQueryParams[key] !== nextQueryParams[key]) {
      return true;
    }
  }

  for (let key in prevQueryParams) {
    if (prevQueryParams[key] !== nextQueryParams[key]) {
      return true;
    }
  }

  return false;
}

function getInstructionBaseUrl(instruction) {
  let instructionBaseUrlParts = [];
  instruction = instruction.parentInstruction;

  while (instruction) {
    instructionBaseUrlParts.unshift(instruction.getBaseUrl());
    instruction = instruction.parentInstruction;
  }

  instructionBaseUrlParts.unshift('/');
  return instructionBaseUrlParts.join('');
}

export let Router = class Router {
  constructor(container, history) {
    this.parent = null;
    this.options = {};

    this.container = container;
    this.history = history;
    this.reset();
  }

  reset() {
    this.viewPorts = {};
    this.routes = [];
    this.baseUrl = '';
    this.isConfigured = false;
    this.isNavigating = false;
    this.navigation = [];
    this.currentInstruction = null;
    this._fallbackOrder = 100;
    this._recognizer = new RouteRecognizer();
    this._childRecognizer = new RouteRecognizer();
    this._configuredPromise = new Promise(resolve => {
      this._resolveConfiguredPromise = resolve;
    });
  }

  get isRoot() {
    return !this.parent;
  }

  registerViewPort(viewPort, name) {
    name = name || 'default';
    this.viewPorts[name] = viewPort;
  }

  ensureConfigured() {
    return this._configuredPromise;
  }

  configure(callbackOrConfig) {
    this.isConfigured = true;

    let result = callbackOrConfig;
    let config;
    if (typeof callbackOrConfig === 'function') {
      config = new RouterConfiguration();
      result = callbackOrConfig(config);
    }

    return Promise.resolve(result).then(c => {
      if (c && c.exportToRouter) {
        config = c;
      }

      config.exportToRouter(this);
      this.isConfigured = true;
      this._resolveConfiguredPromise();
    });
  }

  navigate(fragment, options) {
    if (!this.isConfigured && this.parent) {
      return this.parent.navigate(fragment, options);
    }

    return this.history.navigate(_resolveUrl(fragment, this.baseUrl, this.history._hasPushState), options);
  }

  navigateToRoute(route, params, options) {
    let path = this.generate(route, params);
    return this.navigate(path, options);
  }

  navigateBack() {
    this.history.navigateBack();
  }

  createChild(container) {
    let childRouter = new Router(container || this.container.createChild(), this.history);
    childRouter.parent = this;
    return childRouter;
  }

  generate(name, params, options = {}) {
    let hasRoute = this._recognizer.hasRoute(name);
    if ((!this.isConfigured || !hasRoute) && this.parent) {
      return this.parent.generate(name, params);
    }

    if (!hasRoute) {
      throw new Error(`A route with name '${ name }' could not be found. Check that \`name: '${ name }'\` was specified in the route's config.`);
    }

    let path = this._recognizer.generate(name, params);
    let rootedPath = _createRootedPath(path, this.baseUrl, this.history._hasPushState, options.absolute);
    return options.absolute ? `${ this.history.getAbsoluteRoot() }${ rootedPath }` : rootedPath;
  }

  createNavModel(config) {
    let navModel = new NavModel(this, 'href' in config ? config.href : config.route);
    navModel.title = config.title;
    navModel.order = config.nav;
    navModel.href = config.href;
    navModel.settings = config.settings;
    navModel.config = config;

    return navModel;
  }

  addRoute(config, navModel) {
    validateRouteConfig(config, this.routes);

    if (!('viewPorts' in config) && !config.navigationStrategy) {
      config.viewPorts = {
        'default': {
          moduleId: config.moduleId,
          view: config.view
        }
      };
    }

    if (!navModel) {
      navModel = this.createNavModel(config);
    }

    this.routes.push(config);

    let path = config.route;
    if (path.charAt(0) === '/') {
      path = path.substr(1);
    }
    let caseSensitive = config.caseSensitive === true;
    let state = this._recognizer.add({ path: path, handler: config, caseSensitive: caseSensitive });

    if (path) {
      let settings = config.settings;
      delete config.settings;
      let withChild = JSON.parse(JSON.stringify(config));
      config.settings = settings;
      withChild.route = `${ path }/*childRoute`;
      withChild.hasChildRouter = true;
      this._childRecognizer.add({
        path: withChild.route,
        handler: withChild,
        caseSensitive: caseSensitive
      });

      withChild.navModel = navModel;
      withChild.settings = config.settings;
    }

    config.navModel = navModel;

    if ((navModel.order || navModel.order === 0) && this.navigation.indexOf(navModel) === -1) {
      if (!navModel.href && navModel.href !== '' && (state.types.dynamics || state.types.stars)) {
        throw new Error('Invalid route config for "' + config.route + '" : dynamic routes must specify an "href:" to be included in the navigation model.');
      }

      if (typeof navModel.order !== 'number') {
        navModel.order = ++this._fallbackOrder;
      }

      this.navigation.push(navModel);
      this.navigation = this.navigation.sort((a, b) => a.order - b.order);
    }
  }

  hasRoute(name) {
    return !!(this._recognizer.hasRoute(name) || this.parent && this.parent.hasRoute(name));
  }

  hasOwnRoute(name) {
    return this._recognizer.hasRoute(name);
  }

  handleUnknownRoutes(config) {
    if (!config) {
      throw new Error('Invalid unknown route handler');
    }

    this.catchAllHandler = instruction => {
      return this._createRouteConfig(config, instruction).then(c => {
        instruction.config = c;
        return instruction;
      });
    };
  }

  updateTitle() {
    if (this.parent) {
      return this.parent.updateTitle();
    }

    this.currentInstruction._updateTitle();
    return undefined;
  }

  refreshNavigation() {
    let nav = this.navigation;

    for (let i = 0, length = nav.length; i < length; i++) {
      let current = nav[i];
      if (!current.config.href) {
        current.href = _createRootedPath(current.relativeHref, this.baseUrl, this.history._hasPushState);
      } else {
        current.href = _normalizeAbsolutePath(current.config.href, this.history._hasPushState);
      }
    }
  }

  _refreshBaseUrl() {
    if (this.parent) {
      let baseUrl = this.parent.currentInstruction.getBaseUrl();
      this.baseUrl = this.parent.baseUrl + baseUrl;
    }
  }

  _createNavigationInstruction(url = '', parentInstruction = null) {
    let fragment = url;
    let queryString = '';

    let queryIndex = url.indexOf('?');
    if (queryIndex !== -1) {
      fragment = url.substr(0, queryIndex);
      queryString = url.substr(queryIndex + 1);
    }

    let results = this._recognizer.recognize(url);
    if (!results || !results.length) {
      results = this._childRecognizer.recognize(url);
    }

    let instructionInit = {
      fragment,
      queryString,
      config: null,
      parentInstruction,
      previousInstruction: this.currentInstruction,
      router: this,
      options: {
        compareQueryParams: this.options.compareQueryParams
      }
    };

    if (results && results.length) {
      let first = results[0];
      let instruction = new NavigationInstruction(Object.assign({}, instructionInit, {
        params: first.params,
        queryParams: first.queryParams || results.queryParams,
        config: first.config || first.handler
      }));

      if (typeof first.handler === 'function') {
        return evaluateNavigationStrategy(instruction, first.handler, first);
      } else if (first.handler && 'navigationStrategy' in first.handler) {
        return evaluateNavigationStrategy(instruction, first.handler.navigationStrategy, first.handler);
      }

      return Promise.resolve(instruction);
    } else if (this.catchAllHandler) {
      let instruction = new NavigationInstruction(Object.assign({}, instructionInit, {
        params: { path: fragment },
        queryParams: results && results.queryParams,
        config: null }));

      return evaluateNavigationStrategy(instruction, this.catchAllHandler);
    }

    return Promise.reject(new Error(`Route not found: ${ url }`));
  }

  _createRouteConfig(config, instruction) {
    return Promise.resolve(config).then(c => {
      if (typeof c === 'string') {
        return { moduleId: c };
      } else if (typeof c === 'function') {
        return c(instruction);
      }

      return c;
    }).then(c => typeof c === 'string' ? { moduleId: c } : c).then(c => {
      c.route = instruction.params.path;
      validateRouteConfig(c, this.routes);

      if (!c.navModel) {
        c.navModel = this.createNavModel(c);
      }

      return c;
    });
  }
};

function validateRouteConfig(config, routes) {
  if (typeof config !== 'object') {
    throw new Error('Invalid Route Config');
  }

  if (typeof config.route !== 'string') {
    let name = config.name || '(no name)';
    throw new Error('Invalid Route Config for "' + name + '": You must specify a "route:" pattern.');
  }

  if (!('redirect' in config || config.moduleId || config.navigationStrategy || config.viewPorts)) {
    throw new Error('Invalid Route Config for "' + config.route + '": You must specify a "moduleId:", "redirect:", "navigationStrategy:", or "viewPorts:".');
  }
}

function evaluateNavigationStrategy(instruction, evaluator, context) {
  return Promise.resolve(evaluator.call(context, instruction)).then(() => {
    if (!('viewPorts' in instruction.config)) {
      instruction.config.viewPorts = {
        'default': {
          moduleId: instruction.config.moduleId
        }
      };
    }

    return instruction;
  });
}

export let CanDeactivatePreviousStep = class CanDeactivatePreviousStep {
  run(navigationInstruction, next) {
    return processDeactivatable(navigationInstruction.plan, 'canDeactivate', next);
  }
};

export let CanActivateNextStep = class CanActivateNextStep {
  run(navigationInstruction, next) {
    return processActivatable(navigationInstruction, 'canActivate', next);
  }
};

export let DeactivatePreviousStep = class DeactivatePreviousStep {
  run(navigationInstruction, next) {
    return processDeactivatable(navigationInstruction.plan, 'deactivate', next, true);
  }
};

export let ActivateNextStep = class ActivateNextStep {
  run(navigationInstruction, next) {
    return processActivatable(navigationInstruction, 'activate', next, true);
  }
};

function processDeactivatable(plan, callbackName, next, ignoreResult) {
  let infos = findDeactivatable(plan, callbackName);
  let i = infos.length;

  function inspect(val) {
    if (ignoreResult || shouldContinue(val)) {
      return iterate();
    }

    return next.cancel(val);
  }

  function iterate() {
    if (i--) {
      try {
        let viewModel = infos[i];
        let result = viewModel[callbackName]();
        return processPotential(result, inspect, next.cancel);
      } catch (error) {
        return next.cancel(error);
      }
    }

    return next();
  }

  return iterate();
}

function findDeactivatable(plan, callbackName, list = []) {
  for (let viewPortName in plan) {
    let viewPortPlan = plan[viewPortName];
    let prevComponent = viewPortPlan.prevComponent;

    if ((viewPortPlan.strategy === activationStrategy.invokeLifecycle || viewPortPlan.strategy === activationStrategy.replace) && prevComponent) {
      let viewModel = prevComponent.viewModel;

      if (callbackName in viewModel) {
        list.push(viewModel);
      }
    }

    if (viewPortPlan.childNavigationInstruction) {
      findDeactivatable(viewPortPlan.childNavigationInstruction.plan, callbackName, list);
    } else if (prevComponent) {
      addPreviousDeactivatable(prevComponent, callbackName, list);
    }
  }

  return list;
}

function addPreviousDeactivatable(component, callbackName, list) {
  let childRouter = component.childRouter;

  if (childRouter && childRouter.currentInstruction) {
    let viewPortInstructions = childRouter.currentInstruction.viewPortInstructions;

    for (let viewPortName in viewPortInstructions) {
      let viewPortInstruction = viewPortInstructions[viewPortName];
      let prevComponent = viewPortInstruction.component;
      let prevViewModel = prevComponent.viewModel;

      if (callbackName in prevViewModel) {
        list.push(prevViewModel);
      }

      addPreviousDeactivatable(prevComponent, callbackName, list);
    }
  }
}

function processActivatable(navigationInstruction, callbackName, next, ignoreResult) {
  let infos = findActivatable(navigationInstruction, callbackName);
  let length = infos.length;
  let i = -1;

  function inspect(val, router) {
    if (ignoreResult || shouldContinue(val, router)) {
      return iterate();
    }

    return next.cancel(val);
  }

  function iterate() {
    i++;

    if (i < length) {
      try {
        let current = infos[i];
        let result = current.viewModel[callbackName](...current.lifecycleArgs);
        return processPotential(result, val => inspect(val, current.router), next.cancel);
      } catch (error) {
        return next.cancel(error);
      }
    }

    return next();
  }

  return iterate();
}

function findActivatable(navigationInstruction, callbackName, list = [], router) {
  let plan = navigationInstruction.plan;

  Object.keys(plan).filter(viewPortName => {
    let viewPortPlan = plan[viewPortName];
    let viewPortInstruction = navigationInstruction.viewPortInstructions[viewPortName];
    let viewModel = viewPortInstruction.component.viewModel;

    if ((viewPortPlan.strategy === activationStrategy.invokeLifecycle || viewPortPlan.strategy === activationStrategy.replace) && callbackName in viewModel) {
      list.push({
        viewModel,
        lifecycleArgs: viewPortInstruction.lifecycleArgs,
        router
      });
    }

    if (viewPortPlan.childNavigationInstruction) {
      findActivatable(viewPortPlan.childNavigationInstruction, callbackName, list, viewPortInstruction.component.childRouter || router);
    }
  });

  return list;
}

function shouldContinue(output, router) {
  if (output instanceof Error) {
    return false;
  }

  if (isNavigationCommand(output)) {
    if (typeof output.setRouter === 'function') {
      output.setRouter(router);
    }

    return !!output.shouldContinueProcessing;
  }

  if (output === undefined) {
    return true;
  }

  return output;
}

let SafeSubscription = class SafeSubscription {
  constructor(subscriptionFunc) {
    this._subscribed = true;
    this._subscription = subscriptionFunc(this);

    if (!this._subscribed) this.unsubscribe();
  }

  get subscribed() {
    return this._subscribed;
  }

  unsubscribe() {
    if (this._subscribed && this._subscription) this._subscription.unsubscribe();

    this._subscribed = false;
  }
};

function processPotential(obj, resolve, reject) {
  if (obj && typeof obj.then === 'function') {
    return Promise.resolve(obj).then(resolve).catch(reject);
  }

  if (obj && typeof obj.subscribe === 'function') {
    let obs = obj;
    return new SafeSubscription(sub => obs.subscribe({
      next() {
        if (sub.subscribed) {
          sub.unsubscribe();
          resolve(obj);
        }
      },
      error(error) {
        if (sub.subscribed) {
          sub.unsubscribe();
          reject(error);
        }
      },
      complete() {
        if (sub.subscribed) {
          sub.unsubscribe();
          resolve(obj);
        }
      }
    }));
  }

  try {
    return resolve(obj);
  } catch (error) {
    return reject(error);
  }
}

export let RouteLoader = class RouteLoader {
  loadRoute(router, config, navigationInstruction) {
    throw Error('Route loaders must implement "loadRoute(router, config, navigationInstruction)".');
  }
};

export let LoadRouteStep = class LoadRouteStep {
  static inject() {
    return [RouteLoader];
  }

  constructor(routeLoader) {
    this.routeLoader = routeLoader;
  }

  run(navigationInstruction, next) {
    return loadNewRoute(this.routeLoader, navigationInstruction).then(next).catch(next.cancel);
  }
};

function loadNewRoute(routeLoader, navigationInstruction) {
  let toLoad = determineWhatToLoad(navigationInstruction);
  let loadPromises = toLoad.map(current => loadRoute(routeLoader, current.navigationInstruction, current.viewPortPlan));

  return Promise.all(loadPromises);
}

function determineWhatToLoad(navigationInstruction, toLoad = []) {
  let plan = navigationInstruction.plan;

  for (let viewPortName in plan) {
    let viewPortPlan = plan[viewPortName];

    if (viewPortPlan.strategy === activationStrategy.replace) {
      toLoad.push({ viewPortPlan, navigationInstruction });

      if (viewPortPlan.childNavigationInstruction) {
        determineWhatToLoad(viewPortPlan.childNavigationInstruction, toLoad);
      }
    } else {
      let viewPortInstruction = navigationInstruction.addViewPortInstruction(viewPortName, viewPortPlan.strategy, viewPortPlan.prevModuleId, viewPortPlan.prevComponent);

      if (viewPortPlan.childNavigationInstruction) {
        viewPortInstruction.childNavigationInstruction = viewPortPlan.childNavigationInstruction;
        determineWhatToLoad(viewPortPlan.childNavigationInstruction, toLoad);
      }
    }
  }

  return toLoad;
}

function loadRoute(routeLoader, navigationInstruction, viewPortPlan) {
  let moduleId = viewPortPlan.config.moduleId;

  return loadComponent(routeLoader, navigationInstruction, viewPortPlan.config).then(component => {
    let viewPortInstruction = navigationInstruction.addViewPortInstruction(viewPortPlan.name, viewPortPlan.strategy, moduleId, component);

    let childRouter = component.childRouter;
    if (childRouter) {
      let path = navigationInstruction.getWildcardPath();

      return childRouter._createNavigationInstruction(path, navigationInstruction).then(childInstruction => {
        viewPortPlan.childNavigationInstruction = childInstruction;

        return _buildNavigationPlan(childInstruction).then(childPlan => {
          childInstruction.plan = childPlan;
          viewPortInstruction.childNavigationInstruction = childInstruction;

          return loadNewRoute(routeLoader, childInstruction);
        });
      });
    }

    return undefined;
  });
}

function loadComponent(routeLoader, navigationInstruction, config) {
  let router = navigationInstruction.router;
  let lifecycleArgs = navigationInstruction.lifecycleArgs;

  return routeLoader.loadRoute(router, config, navigationInstruction).then(component => {
    let { viewModel, childContainer } = component;
    component.router = router;
    component.config = config;

    if ('configureRouter' in viewModel) {
      let childRouter = childContainer.getChildRouter();
      component.childRouter = childRouter;

      return childRouter.configure(c => viewModel.configureRouter(c, childRouter, ...lifecycleArgs)).then(() => component);
    }

    return component;
  });
}

let PipelineSlot = class PipelineSlot {

  constructor(container, name, alias) {
    this.steps = [];

    this.container = container;
    this.slotName = name;
    this.slotAlias = alias;
  }

  getSteps() {
    return this.steps.map(x => this.container.get(x));
  }
};

export let PipelineProvider = class PipelineProvider {
  static inject() {
    return [Container];
  }

  constructor(container) {
    this.container = container;
    this.steps = [BuildNavigationPlanStep, CanDeactivatePreviousStep, LoadRouteStep, this._createPipelineSlot('authorize'), CanActivateNextStep, this._createPipelineSlot('preActivate', 'modelbind'), DeactivatePreviousStep, ActivateNextStep, this._createPipelineSlot('preRender', 'precommit'), CommitChangesStep, this._createPipelineSlot('postRender', 'postcomplete')];
  }

  createPipeline() {
    let pipeline = new Pipeline();
    this.steps.forEach(step => pipeline.addStep(this.container.get(step)));
    return pipeline;
  }

  _findStep(name) {
    return this.steps.find(x => x.slotName === name || x.slotAlias === name);
  }

  addStep(name, step) {
    let found = this._findStep(name);
    if (found) {
      if (!found.steps.includes(step)) {
        found.steps.push(step);
      }
    } else {
      throw new Error(`Invalid pipeline slot name: ${ name }.`);
    }
  }

  removeStep(name, step) {
    let slot = this._findStep(name);
    if (slot) {
      slot.steps.splice(slot.steps.indexOf(step), 1);
    }
  }

  _clearSteps(name = '') {
    let slot = this._findStep(name);
    if (slot) {
      slot.steps = [];
    }
  }

  reset() {
    this._clearSteps('authorize');
    this._clearSteps('preActivate');
    this._clearSteps('preRender');
    this._clearSteps('postRender');
  }

  _createPipelineSlot(name, alias) {
    return new PipelineSlot(this.container, name, alias);
  }
};

const logger = LogManager.getLogger('app-router');

export let AppRouter = class AppRouter extends Router {
  static inject() {
    return [Container, History, PipelineProvider, EventAggregator];
  }

  constructor(container, history, pipelineProvider, events) {
    super(container, history);
    this.pipelineProvider = pipelineProvider;
    this.events = events;
  }

  reset() {
    super.reset();
    this.maxInstructionCount = 10;
    if (!this._queue) {
      this._queue = [];
    } else {
      this._queue.length = 0;
    }
  }

  loadUrl(url) {
    return this._createNavigationInstruction(url).then(instruction => this._queueInstruction(instruction)).catch(error => {
      logger.error(error);
      restorePreviousLocation(this);
    });
  }

  registerViewPort(viewPort, name) {
    super.registerViewPort(viewPort, name);

    if (!this.isActive) {
      let viewModel = this._findViewModel(viewPort);
      if ('configureRouter' in viewModel) {
        if (!this.isConfigured) {
          let resolveConfiguredPromise = this._resolveConfiguredPromise;
          this._resolveConfiguredPromise = () => {};
          return this.configure(config => viewModel.configureRouter(config, this)).then(() => {
            this.activate();
            resolveConfiguredPromise();
          });
        }
      } else {
        this.activate();
      }
    } else {
      this._dequeueInstruction();
    }

    return Promise.resolve();
  }

  activate(options) {
    if (this.isActive) {
      return;
    }

    this.isActive = true;
    this.options = Object.assign({ routeHandler: this.loadUrl.bind(this) }, this.options, options);
    this.history.activate(this.options);
    this._dequeueInstruction();
  }

  deactivate() {
    this.isActive = false;
    this.history.deactivate();
  }

  _queueInstruction(instruction) {
    return new Promise(resolve => {
      instruction.resolve = resolve;
      this._queue.unshift(instruction);
      this._dequeueInstruction();
    });
  }

  _dequeueInstruction(instructionCount = 0) {
    return Promise.resolve().then(() => {
      if (this.isNavigating && !instructionCount) {
        return undefined;
      }

      let instruction = this._queue.shift();
      this._queue.length = 0;

      if (!instruction) {
        return undefined;
      }

      this.isNavigating = true;
      instruction.previousInstruction = this.currentInstruction;

      if (!instructionCount) {
        this.events.publish('router:navigation:processing', { instruction });
      } else if (instructionCount === this.maxInstructionCount - 1) {
        logger.error(`${ instructionCount + 1 } navigation instructions have been attempted without success. Restoring last known good location.`);
        restorePreviousLocation(this);
        return this._dequeueInstruction(instructionCount + 1);
      } else if (instructionCount > this.maxInstructionCount) {
        throw new Error('Maximum navigation attempts exceeded. Giving up.');
      }

      let pipeline = this.pipelineProvider.createPipeline();

      return pipeline.run(instruction).then(result => processResult(instruction, result, instructionCount, this)).catch(error => {
        return { output: error instanceof Error ? error : new Error(error) };
      }).then(result => resolveInstruction(instruction, result, !!instructionCount, this));
    });
  }

  _findViewModel(viewPort) {
    if (this.container.viewModel) {
      return this.container.viewModel;
    }

    if (viewPort.container) {
      let container = viewPort.container;

      while (container) {
        if (container.viewModel) {
          this.container.viewModel = container.viewModel;
          return container.viewModel;
        }

        container = container.parent;
      }
    }

    return undefined;
  }
};

function processResult(instruction, result, instructionCount, router) {
  if (!(result && 'completed' in result && 'output' in result)) {
    result = result || {};
    result.output = new Error(`Expected router pipeline to return a navigation result, but got [${ JSON.stringify(result) }] instead.`);
  }

  let finalResult = null;
  if (isNavigationCommand(result.output)) {
    result.output.navigate(router);
  } else {
    finalResult = result;

    if (!result.completed) {
      if (result.output instanceof Error) {
        logger.error(result.output);
      }

      restorePreviousLocation(router);
    }
  }

  return router._dequeueInstruction(instructionCount + 1).then(innerResult => finalResult || innerResult || result);
}

function resolveInstruction(instruction, result, isInnerInstruction, router) {
  instruction.resolve(result);

  if (!isInnerInstruction) {
    router.isNavigating = false;
    let eventArgs = { instruction, result };
    let eventName;

    if (result.output instanceof Error) {
      eventName = 'error';
    } else if (!result.completed) {
      eventName = 'canceled';
    } else {
      let queryString = instruction.queryString ? '?' + instruction.queryString : '';
      router.history.previousLocation = instruction.fragment + queryString;
      eventName = 'success';
    }

    router.events.publish(`router:navigation:${ eventName }`, eventArgs);
    router.events.publish('router:navigation:complete', eventArgs);
  }

  return result;
}

function restorePreviousLocation(router) {
  let previousLocation = router.history.previousLocation;
  if (previousLocation) {
    router.navigate(router.history.previousLocation, { trigger: false, replace: true });
  } else {
    logger.error('Router navigation failed, and no previous location could be restored.');
  }
}


text:
module TM4R
  require 'set' # for ancestors
  class Topic < TopicMapConstruct
    has_many :names, :class_name => "Name", :dependent => :destroy
    has_many :occurrences, :dependent => :destroy
    has_many :subject_identifiers, :dependent => :destroy
    has_many :subject_locators, :dependent => :destroy
    belongs_to :reified, :polymorphic => true
    has_one :reifier, :class_name=> "Topic", :foreign_key=> "reified_id"
    has_many :roles, :foreign_key=> "player_id", :dependent => :destroy
    has_many :associations, :through => :roles
    #before_create :merge

    def to_s
     names[0..2].collect{|n| n.value}.join("; ")
    end

    def hash
      self.id
    end

    def eql?(other)
      self.id == other.id
    end

    # role types that the topic has in associations
    def roles_from_player
        Topic.roles_from_player(self.id)
    end

    # types of associations that this topic participates
    def associations_from_player
        Topic.associations_from_player(self.id)
    end

    # topics that this topic associated with
    def other_players_from_player
      Topic.other_players_from_player(self.id)
    end

    # role players that that have this topic as role type
    def players_from_role
        Topic.players_from_role(self.id)
    end

    # associations that has this topic as role type
    def associations_from_role
        Topic.associations_from_role(self.id)
    end

    # players in the associations of this particular type
    def players_from_association
       Topic.players_from_association(self.id)
    end

    # roles in the associations of this particular type
    def roles_from_association
       Topic.roles_from_association(self.id)
    end

    # instances of this topic
    def instances
        Topic.instances(self.id)
    end

    # deep instances
    def descendants
       results = Set.new
       results.merge instances
       subtypes.each {|subtype|
        results.merge subtype.descendants
       }
    end

    # deep types
    def ancestors
       results = Set.new
       supertypes.each {|supertype|
         results.add supertype
         results.merge supertype.ancestors
       }
       types.each {|type|
         results.add type
         results.merge type.ancestors
       }
       results.to_a
    end

    # types of this topic
    def types
        Topic.types(self.id)
    end

    def subtypes
        Topic.subtypes(self.id)
    end

    def supertypes
        Topic.supertypes(self.id)
    end

    # is this topic used as a role player?
    def role_player?
      Topic.role_player?(self.id)
    end

    # is this topic used to type other topics?
    def topic_type?
      Topic.topic_type?(self.id)
    end

    # is this topic an instance of some other topic?
    def topic_instance?
      Topic.topic_instance?(self.id)
    end

    # is this topic used as a supertype of some other topic?
    def topic_supertype?
      Topic.topic_supertype?(self.id)
    end

    # is this topic used as a subtype of some other topic?
    def topic_subtype?
      Topic.topic_subtype?(self.id)
    end

    # is this topic used as a name type?
    def name_type?
      Topic.name_type?(self.id)
    end

    # is this topic used as an association type?
    def association_type?
      Topic.association_type?(self.id)
    end

    # is this topic used as an occurrence type?
    def occurrence_type?
      Topic.occurrence_type?(self.id)
    end

    # is this topic used as a role type?
    def role_type?
      Topic.role_type?(self.id)
    end

    # is this topic used as a name scope?
    def name_scope?
      Topic.name_scope?(self.id)
    end

    # is this topic used as a variant scope?
    def variant_scope?
      Topic.variant_scope?(self.id)
    end

    # is this topic used as an occurrence scope?
    def occurrence_scope?
      Topic.occurrence_scope?(self.id)
    end

    # is this topic used as an association scope?
    def association_scope?
      Topic.association_scope?(self.id)
    end

    # is this topic used as a topic map reifier?
    def topic_map_reifier?
      Topic.topic_map_reifier?(self.id)
    end

    # is this topic used as a name reifier?
    def name_reifier?
      Topic.name_reifier?(self.id)
    end

    # is this topic used as an association reifier?
    def association_reifier?
      Topic.association_reifier?(self.id)
    end

    # is this topic used as an occurrence reifier?
    def occurrence_reifier?
      Topic.occurrence_reifier?(self.id)
    end

    # is this topic used as a role reifier?
    def role_reifier?
      Topic.role_reifier?(self.id)
    end

    # is this topic used as a variant reifier?
    def variant_reifier?
      Topic.variant_reifier?(self.id)
    end

    def merge
      topics = find_equal
      return true if topics.empty?
      print "self.id: #{self.id}\n"
      $stderr << "Size of equal topics: #{topics.size}\n"
      $stderr << "topics.empty?: #{topics.empty?}\n"
      last = topics.pop
      Topic.merge(self, last)
      Topic.delete(self.id) if self.id
      self.freeze
      last.save
      last.merge
      return false
    end

    def find_equal
      iis_sis=[]
      item_identifiers.each {|item_identifier|
        iis_sis.push item_identifier.href
      }
      subject_identifiers.each {|subject_identifier|
        iis_sis.push subject_identifier.href
      }
      sls=[]
      subject_locators.each{|subject_locator|
        sls.push subject_locator.href
      }
      if self.id && self.topic_map_id
        Topic.find(:all,
          :conditions=>[%{((item_identifiers.href IN (?)
            OR subject_identifiers.href IN (?))
            OR subject_locators.href IN (?))
            AND NOT topics.id = ?
            AND topics.topic_map_id= ?}, iis_sis, iis_sis, sls, self.id, self.topic_map_id],
          :include =>
            [:item_identifiers, :subject_identifiers, :subject_locators])
      elsif self.topic_map_id
        Topic.find(:all,
          :conditions=>[%{(item_identifiers.href IN (?)
            OR subject_identifiers.href IN (?))
            OR subject_locators.href IN (?)
            AND topics.topic_map_id = ? }, iis_sis, iis_sis, sls, self.topic_map_id],
          :include =>
            [:item_identifiers, :subject_identifiers, :subject_locators])
      else
        $stderr << "#{__FILE__}:#{__LINE__} entered, this should never happen.\n"
        []
      end
    end

    def Topic.merge(from, to)
      #to.names = to.names | from.names
      from.names.each {|n|
        n.topic = to
        n.save
      }
      #to.occurrences = to.occurrences | from.occurrences
      from.occurrences.each {|o|
        o.topic = to
        n.save
      }
      #to.subject_identifiers =
      #   to.subject_identifiers | from.subject_identifiers
      from.subject_identifiers.each {|si|
        si.topic = to unless to.subject_indentifier.member?(si)
        si.save
      }
      #to.subject_locators = to.subject_locators | from.subject_locators
      from.subject_locators.each {|sl|
        sl.topic = to unless to.subject_locators.member?(sl)
        sl.save
      }
      #to.item_identifiers = to.item_identifiers | from.item_identifiers
      from.item_identifiers.each {|ii|
        unless to.item_identifiers.member?(ii)
          ii.topic_map_construct = to
          ii.topic_map_construct_type =
            Topic.to_s.classify.constantize.base_class.to_s
          ii.save
        end
      }
      # TODO move associations
    end

    class << self

      ROLES_FROM_PLAYER=
      %{SELECT t.* from topics t
      JOIN (roles r)
      ON (r.type_id=t.id)
      WHERE r.player_id=?}

      ASSOCIATIONS_FROM_PLAYER=
      %{SELECT t.* from topics t
      JOIN (associations a, roles r)
      ON (r.association_id=a.id AND a.type_id=t.id)
      WHERE r.player_id=?}

      OTHER_PLAYERS_FROM_PLAYER=
      %{SELECT DISTINCT t2.*
      FROM topics t2
      JOIN (associations a,
        roles r1, roles r2)
      ON (r1.association_id = a.id AND
          r2.association_id = a.id AND
          r2.player_id      = t2.id)
      WHERE r1.player_id=?  AND NOT t2.id = ?}

      PLAYERS_FROM_ROLE=
      %{SELECT DISTINCT t.* from topics t
      JOIN (roles r)
      ON (r.player_id=t.id)
      WHERE r.type_id=?}

      ASSOCIATIONS_FROM_ROLE=
      %{SELECT DISTINCT t.* from topics t
      JOIN (roles r, associations a)
      ON (r.association_id_id=a.id AND
          a.type_id=t.id)
      WHERE r.type_id=?}

      PLAYERS_FROM_ASSOCIATION=
      %{SELECT DISTINCT t.* from topics t
      JOIN (associations a, roles r)
      ON (a.id = r.association_id AND r.player_id=t.id)
      WHERE a.type_id=?}

      ROLES_FROM_ASSOCIATION=
      %{SELECT DISTINCT t.* from topics t
      JOIN (associations a, roles r)
      ON (a.id = r.association_id AND r.type_id=t.id)
      WHERE a.type_id=?}

      SQL_XXX =
      %{SELECT DISTINCT tpt.*
      FROM topics tpt
      JOIN (subject_identifiers si,
        associations a,
        roles rt,
        roles ri)
      ON (ri.association_id=a.id
        AND rt.association_id=a.id AND
         rt.type_id=si.topic_id AND
         rt.player_id = tpt.id)
      WHERE si.href=?
        AND ri.player_id=?
        AND NOT tpt.id = ?}

      SQL_IS_ROLE_PLAYER =
      %{SELECT id FROM roles WHERE player_id=? LIMIT 1}

      SQL_IS_XXX =
      %{SELECT p.id
      FROM topics p
      JOIN (subject_identifiers si, roles r, topics t)
      WHERE si.href=?
        AND si.topic_id=t.id AND r.type_id=t.id
        AND r.player_id=p.id AND p.id=? LIMIT 1}

      SQL_IS_NAME_TYPE =
      %{SELECT id FROM names WHERE type_id=? LIMIT 1}

      SQL_IS_ASSOCIATION_TYPE =
      %{SELECT id FROM associations WHERE type_id=? LIMIT 1}

      SQL_IS_OCCURRENCE_TYPE =
      %{SELECT id FROM occurrences WHERE type_id=? LIMIT 1}

      SQL_IS_ROLE_TYPE =
      %{SELECT id FROM roles WHERE type_id=? LIMIT 1}

      SQL_IS_NAME_SCOPE =
      %{SELECT id FROM scopes
      WHERE scopable_type="TM4R::Name" AND topic_id=? LIMIT 1}

      SQL_IS_VARIANT_SCOPE =
      %{SELECT id FROM scopes
      WHERE scopable_type="TM4R::Variant" AND topic_id=? LIMIT 1}

      SQL_IS_OCCURRENCE_SCOPE =
      %{SELECT id FROM scopes
      WHERE scopable_type="TM4R::Occurrence" AND topic_id=? LIMIT 1}

      SQL_IS_ASSOCIATION_SCOPE =
      %{SELECT id FROM scopes
      WHERE scopable_type="TM4R::Association" AND topic_id=?}

      SQL_IS_TOPIC_MAP_REIFIER =
      %{SELECT id FROM topics
      WHERE reified_id IS NOT NULL
      AND reified_type="TM4R::TopicMap" AND id=?}

      SQL_IS_NAME_REIFIER =
      %{SELECT id FROM topics
      WHERE reified_id IS NOT NULL
      AND reified_type="TM4R::Name" AND id=?}

      SQL_IS_ASSOCIATION_REIFIER =
      %{SELECT id FROM topics
      WHERE reified_id IS NOT NULL
      AND reified_type="TM4R::Association" AND id=?}

      SQL_IS_OCCURRENCE_REIFIER =
      %{SELECT id FROM topics
      WHERE reified_id IS NOT NULL
      AND reified_type="TM4R::Occurrence" AND id=?}

      SQL_IS_ROLE_REIFIER =
      %{SELECT id FROM topics
      WHERE reified_id IS NOT NULL
      AND reified_type="TM4R::Role" AND id=?}

      SQL_IS_VARIANT_REIFIER =
      %{SELECT id FROM topics
      WHERE reified_id IS NOT NULL
      AND reified_type="TM4R::Variant" AND id=?}

      SQL_BY_NAME =
      %{SELECT DISTINCT t.id FROM topics t
      JOIN (names n) ON (t.id=n.topic_id)
      WHERE (n.value LIKE ?)
      AND t.topic_map_id = ?}

      SQL_BY_NAME_AND_VARIANT =
      %{SELECT DISTINCT t.id FROM topics t
      LEFT OUTER JOIN (names n) ON (t.id=n.topic_id)
      LEFT OUTER JOIN (variants v)  ON (t.id=n.topic_id AND n.id=v.name_id)
      WHERE (n.value LIKE ? OR v.value like ?)
      AND t.topic_map_id = ?}

      SQL_BY_NAME_AND_VARIANT_AND_OCCURRENCE =
      %{SELECT DISTINCT t.id FROM topics t
      LEFT OUTER JOIN (names n) ON (t.id=n.topic_id)
      LEFT OUTER JOIN (variants v)  ON (t.id=n.topic_id AND n.id=v.name_id)
      LEFT OUTER JOIN (occurrences o)  ON (t.id=o.topic_id)
      WHERE (n.value LIKE ? OR v.value like ? OR o.value like ?)
      AND t.topic_map_id = ?}

      SQL_TOPIC_ID_BY_II_OR_SI =
      %{SELECT t.* FROM topics t
      JOIN item_identifiers ii
      ON ii.topic_map_construct_id = t.id AND ii.topic_map_construct_type = 'TM4R::Topic'
      WHERE ii.href = ? AND t.topic_map_id = ?
      UNION
      SELECT t.* FROM topics t
      JOIN subject_identifiers si ON si.topic_id = t.id
      WHERE si.href = ?  AND t.topic_map_id = ?}

      def roles_from_player(topic_id)
          find_by_sql([ROLES_FROM_PLAYER, topic_id])
      end

      def associations_from_player(topic_id)
          find_by_sql([ASSOCIATIONS_FROM_PLAYER, topic_id])
      end

      def other_players_from_player(topic_id)
          find_by_sql([OTHER_PLAYERS_FROM_PLAYER, topic_id, topic_id])
      end

      def players_from_role(topic_id)
          find_by_sql([PLAYERS_FROM_ROLE, topic_id])
      end

      def associations_from_role(topic_id)
          find_by_sql([ASSOCIATIONS_FROM_ROLE, topic_id])
      end

      def players_from_association(topic_id)
          find_by_sql([PLAYERS_FROM_ASSOCIATION, topic_id])
      end

      def roles_from_association(topic_id)
          find_by_sql([ROLES_FROM_ASSOCIATION, topic_id])
      end

      def instances(topic_id)
          find_by_sql([SQL_XXX, PSI[:instance],  topic_id, topic_id])
      end

      def types(topic_id)
          find_by_sql([SQL_XXX, PSI[:type],      topic_id, topic_id])
      end

      def subtypes(topic_id)
          find_by_sql([SQL_XXX, PSI[:subtype],   topic_id, topic_id])
      end

      def supertypes(topic_id)
          find_by_sql([SQL_XXX, PSI[:supertype], topic_id, topic_id])
      end

      def role_player?(topic_id)
          Topic.find_by_sql([SQL_IS_ROLE_PLAYER, topic_id]).size != 0
      end

      def topic_type?(topic_id)
          Topic.find_by_sql([SQL_IS_XXX, PSI[:type], topic_id]).size != 0
      end

      def topic_instance?(topic_id)
          Topic.find_by_sql([SQL_IS_XXX, PSI[:instance], topic_id]).size != 0
      end

      def topic_supertype?(topic_id)
          Topic.find_by_sql([SQL_IS_XXX, PSI[:supertype], topic_id]).size != 0
      end

      def topic_subtype?(topic_id)
          Topic.find_by_sql([SQL_IS_XXX, PSI[:subtype], topic_id]).size != 0
      end

      def name_type?(topic_id)
          Topic.find_by_sql([SQL_IS_NAME_TYPE, topic_id]).size != 0
      end

      def association_type?(topic_id)
          Topic.find_by_sql([SQL_IS_ASSOCIATION_TYPE, topic_id]).size != 0
      end

      def occurrence_type?(topic_id)
          Topic.find_by_sql([SQL_IS_OCCURRENCE_TYPE, topic_id]).size != 0
      end

      def role_type?(topic_id)
          Topic.find_by_sql([SQL_IS_ROLE_TYPE, topic_id]).size != 0
      end

      def name_scope?(topic_id)
          Topic.find_by_sql([SQL_IS_NAME_SCOPE, topic_id]).size != 0
      end

      def variant_scope?(topic_id)
          Topic.find_by_sql([SQL_IS_VARIANT_SCOPE, topic_id]).size != 0
      end

      def occurrence_scope?(topic_id)
          Topic.find_by_sql([SQL_IS_OCCURRENCE_SCOPE, topic_id]).size != 0
      end

      def association_scope?(topic_id)
          Topic.find_by_sql([SQL_IS_ASSOCIATION_SCOPE, topic_id]).size != 0
      end

      def topic_map_reifier?(topic_id)
          Topic.find_by_sql([SQL_IS_TOPIC_MAP_REIFIER, topic_id]).size != 0
      end

      def name_reifier?(topic_id)
          Topic.find_by_sql([SQL_IS_NAME_REIFIER, topic_id]).size != 0
      end

      def association_reifier?(topic_id)
          Topic.find_by_sql([SQL_IS_ASSOCIATION_REIFIER, topic_id]).size != 0
      end

      def occurrence_reifier?(topic_id)
          Topic.find_by_sql([SQL_IS_OCCURRENCE_REIFIER, topic_id]).size != 0
      end

      def role_reifier?(topic_id)
          Topic.find_by_sql([SQL_IS_ROLE_REIFIER, topic_id]).size != 0
      end

      def variant_reifier?(topic_id)
          Topic.find_by_sql([SQL_IS_VARIANT_REIFIER, topic_id]).size != 0
      end

      def search_by_name(topic_map, name)
        find_by_sql([SQL_BY_NAME, name, topic_map.id])
      end
      alias search_by_n search_by_name

      def search_by_name_and_variant(topic_map, name)
        find_by_sql([SQL_BY_NAME_AND_VARIANT, name, name, topic_map.id])
      end
      alias search_by_nv search_by_name_and_variant

      def search_by_name_and_variant_and_occurrence(name, topic_map)
        find_by_sql([SQL_BY_NAME_AND_VARIANT_AND_OCCURRENCE,
                    name, name, name, topic_map.id])
      end
      alias search_by_nvo search_by_name_and_variant_and_occurrence

      def find_or_create_by_item_identifier(topic_map, iri)
        topic = Topic.find_by_sql([SQL_TOPIC_ID_BY_II_OR_SI, iri, topic_map.id, iri, topic_map.id]).first
        if topic == nil
          topic = new(:topic_map => topic_map,
                      :item_identifiers=>[ItemIdentifier.new(:href=>iri)])
          topic_map.topics << topic
        end
        return topic
      end
      alias by_ii find_or_create_by_item_identifier

      def find_or_create_by_subject_identifier(topic_map, iri)
        topic = Topic.find_by_sql([SQL_TOPIC_ID_BY_II_OR_SI, iri, topic_map.id, iri, topic_map.id]).first
        if topic == nil
          topic = new(:topic_map => topic_map,
                      :subject_identifiers=>[SubjectIdentifier.new(:href=>iri)])
          topic_map.topics << topic
        end
        return topic
      end
      alias by_si find_or_create_by_subject_identifier

      def find_or_create_by_subject_locator(topic_map, iri)
        topic = find(:first,
          :conditions=>[%{topic_map_id = #{topic_map.id}
            AND subject_locators.href ='#{iri}'}],
          :include =>[:subject_locators])
        if topic == nil
          topic = new(:topic_map => topic_map,
                      :subject_locators=>[SubjectLocator.new(:href=>iri)])
          topic_map.topics << topic
        end
        return topic
      end
      alias by_sl find_or_create_by_subject_locator

      def instance(topic_map)
         by_si(topic_map, PSI[:instance])
      end

      def type(topic_map)
         by_si(topic_map, PSI[:type])
      end

      def type_instance(topic_map)
         by_si(topic_map, PSI[:type_instance])
      end
    end
  end
end


text: <!DOCTYPE html>


text:
import { pageable } from "relay-cursor-paging"
import { connectionDefinitions, connectionFromArraySlice } from "graphql-relay"
import Artwork from "schema/artwork"
import ArtworkSorts from "schema/sorts/artwork_sorts"
import Image from "schema/image"
import { GraphQLList, GraphQLObjectType, GraphQLString } from "graphql"
import { omit, groupBy, map } from "lodash"
import { parseRelayOptions } from "lib/helpers"
import { GlobalIDField, NodeInterface } from "schema/object_identification"

const FollowedArtistsArtworksGroupType = new GraphQLObjectType({
  name: "FollowedArtistsArtworksGroup",
  interfaces: [NodeInterface],
  isTypeOf: obj => obj._type === "FollowedArtistsArtworksGroup",
  fields: () => ({
    __id: GlobalIDField,
    artworks: {
      type: new GraphQLList(Artwork.type),
      description: "List of artworks in this group.",
    },
    artists: {
      type: GraphQLString,
    },
    summary: {
      type: GraphQLString,
    },
    image: {
      type: Image.type,
      resolve: ({ artworks }) => {
        return artworks.length > 0 && artworks[0].artists.length > 0 && Image.resolve(artworks[0].artists[0])
      },
    },
  }),
})

const FollowedArtistsArtworksGroup = {
  type: connectionDefinitions({ nodeType: FollowedArtistsArtworksGroupType }).connectionType,
  description: "A list of published artworks by followed artists (grouped by date and artists).",
  args: pageable({
    sort: ArtworkSorts,
  }),
  resolve: (root, options, request, { rootValue: { followedArtistsArtworksLoader } }) => {
    if (!followedArtistsArtworksLoader) return null

    // Convert Relay-style pagination to the supported page/size style for the backend.
    const gravityOptions = parseRelayOptions(options)
    gravityOptions.total_count = true

    return followedArtistsArtworksLoader(omit(gravityOptions, "offset")).then(({ body, headers }) => {
      const connection = connectionFromArraySlice(body, options, {
        arrayLength: headers["x-total-count"],
        sliceStart: gravityOptions.offset,
      })

      const groupedByArtist = groupBy(connection.edges, item => {
        return item.node.artist.id
      })

      let newEdges = []
      let newEdge
      Object.keys(groupedByArtist).forEach(artist => {
        const groupedNodes = groupedByArtist[artist]
        newEdge = {
          node: {
            summary: `${groupedNodes.length} Work${groupedNodes.length === 1 ? "" : "s"} Added`,
            artworks: map(groupedNodes, groupped => {
              return groupped.node
            }),
            id: groupedNodes[0].node._id,
            artists: groupedNodes[0].node.artist.name,
            _type: "FollowedArtistsArtworksGroup",
          },
          cursor: groupedNodes[0].cursor,
        }
        newEdges = newEdges.concat(newEdge)
      })

      connection.edges = newEdges
      return connection
    })
  },
}

export default FollowedArtistsArtworksGroup


text:
package com.aspose.cloud.sdk.cells.model;

import com.aspose.cloud.sdk.common.BaseResponse;
import com.aspose.cloud.sdk.common.LinkModel;
import com.google.gson.annotations.SerializedName;

public class CellsResponse extends BaseResponse {

	@SerializedName("Cell")
	public CellData cell;

    public class CellData {
    	public LinkModel link;
    	public String Name;
    	public String Type;
    	public int Row;
    	public int Column;
    	public String Value;
    	public String Formula;
    	public boolean IsFormula;
    	public boolean IsMerged;
    	@SerializedName("Style")
    	public Style style;
    }

    public class Style {
    	public LinkModel link;
    }
}


text:
//
//  PXLexeme.m
//  Pixate
//
//  Created by Kevin Lindsey on 6/23/12.
//  Copyright (c) 2012 Pixate, Inc. All rights reserved.
//

#import "PXStylesheetLexeme.h"
#import "PXStylesheetTokenType.h"

@implementation PXStylesheetLexeme
{
    NSUInteger flags_;
}

@synthesize type = _type;
@synthesize text = _text;
@synthesize value = _value;
@synthesize range = _range;

#pragma mark - Static Initializers

+ (id)lexemeWithType:(int)type
{
    return [[PXStylesheetLexeme alloc] initWithType:type withRange:NSMakeRange(NSNotFound, 0) withValue:nil];
}

+ (id)lexemeWithType:(int)type withRange:(NSRange)range
{
    return [[PXStylesheetLexeme alloc] initWithType:type withRange:range withValue:nil];
}

+ (id)lexemeWithType:(int)type withValue:(id)value
{
    return [[PXStylesheetLexeme alloc] initWithType:type withRange:NSMakeRange(NSNotFound, 0) withValue:value];
}

+ (id)lexemeWithType:(int)type withRange:(NSRange)range withValue:(id)value
{
    return [[PXStylesheetLexeme alloc] initWithType:type withRange:range withValue:value];
}

#pragma mark - Initializers

- (id)initWithType:(int)type text:(NSString *)text
{
    return [self initWithType:type withRange:NSMakeRange(NSNotFound, 0) withValue:text];
}

- (id)initWithType:(int)aType withRange:(NSRange)aRange withValue:(id)aValue
{
    if (self = [super init])
    {
        _type = aType;
        _range = aRange;
        _value = aValue;
        flags_ = 0;
    }

    return self;
}

#pragma mark - Getters

- (NSString *)name
{
    //return [PXSSTokenType typeNameForInt:type];
    return [PXStylesheetTokenType typeNameForInt:_type];
}

#pragma mark - Methods

- (NSString *)description
{
    return [NSString stringWithFormat:@"%@@%lu-%lu:«%@»", self.name, (unsigned long) _range.location, (unsigned long) _range.location + _range.length, _value];
}

#pragma mark - Flags

- (void)clearFlag:(int)type
{
    flags_ &= ~type;
}

- (void)setFlag:(int)type
{
    flags_ |= type;
}

- (BOOL)flagIsSet:(int)type
{
    return ((flags_ & type) == type);
}

@end