text:
package com.planet_ink.coffee_mud.Abilities.Diseases;
import com.planet_ink.coffee_mud.core.interfaces.*;
import com.planet_ink.coffee_mud.core.*;
import com.planet_ink.coffee_mud.core.collections.*;
import com.planet_ink.coffee_mud.Abilities.interfaces.*;
import com.planet_ink.coffee_mud.Areas.interfaces.*;
import com.planet_ink.coffee_mud.Behaviors.interfaces.*;
import com.planet_ink.coffee_mud.CharClasses.interfaces.*;
import com.planet_ink.coffee_mud.Commands.interfaces.*;
import com.planet_ink.coffee_mud.Common.interfaces.*;
import com.planet_ink.coffee_mud.Exits.interfaces.*;
import com.planet_ink.coffee_mud.Items.interfaces.*;
import com.planet_ink.coffee_mud.Libraries.interfaces.*;
import com.planet_ink.coffee_mud.Locales.interfaces.*;
import com.planet_ink.coffee_mud.MOBS.interfaces.*;
import com.planet_ink.coffee_mud.Races.interfaces.*;

import java.util.*;

public class Disease_Pneumonia extends Disease
{
	@Override public String ID() { return "Disease_Pneumonia"; }
	private final static String localizedName = CMLib.lang().L("Pneumonia");
	@Override public String name() { return localizedName; }
	private final static String localizedStaticDisplay = CMLib.lang().L("(Pneumonia)");
	@Override public String displayText() { return localizedStaticDisplay; }
	@Override protected int canAffectCode(){return CAN_MOBS;}
	@Override protected int canTargetCode(){return CAN_MOBS;}
	@Override public int abstractQuality(){return Ability.QUALITY_MALICIOUS;}
	@Override public boolean putInCommandlist(){return false;}

	@Override protected int DISEASE_TICKS(){return 38;}
	@Override protected int DISEASE_DELAY(){return 3;}
	@Override protected String DISEASE_DONE(){return L("Your pneumonia clears up.");}
	@Override protected String DISEASE_START(){return L("^G<S-NAME> come(s) down with pneumonia.^?");}
	@Override protected String DISEASE_AFFECT(){return L("<S-NAME> shake(s) feverishly.");}
	@Override public int spreadBitmap(){return DiseaseAffect.SPREAD_CONSUMPTION|DiseaseAffect.SPREAD_PROXIMITY|DiseaseAffect.SPREAD_CONTACT|DiseaseAffect.SPREAD_STD;}
	@Override public int difficultyLevel(){return 3;}

	@Override
	public boolean tick(Tickable ticking, int tickID)
	{
		if(!super.tick(ticking,tickID))
			return false;
		if(affected==null)
			return false;
		if(!(affected instanceof MOB))
			return true;

		final MOB mob=(MOB)affected;
		if((!mob.amDead())&&((--diseaseTick)<=0))
		{
			MOB diseaser=invoker;
			if(diseaser==null)
				diseaser=mob;
			diseaseTick=DISEASE_DELAY();
			mob.location().show(mob,null,CMMsg.MSG_QUIETMOVEMENT,DISEASE_AFFECT());
			final int damage=CMLib.dice().roll(4,mob.phyStats().level()+1,1);
			CMLib.combat().postDamage(diseaser,mob,this,damage,CMMsg.MASK_ALWAYS|CMMsg.TYP_DISEASE,-1,null);
			final Disease_Cold A=(Disease_Cold)CMClass.getAbility("Disease_Cold");
			A.catchIt(mob);
			if(CMLib.dice().rollPercentage()==1)
			{
				final Ability A2=CMClass.getAbility("Disease_Fever");
				if(A2!=null)
					A2.invoke(diseaser,mob,true,0);
			}
			return true;
		}
		return true;
	}

	@Override
	public void affectCharStats(MOB affected, CharStats affectableStats)
	{
		if(affected==null)
			return;
		affectableStats.setStat(CharStats.STAT_CONSTITUTION,affectableStats.getStat(CharStats.STAT_CONSTITUTION)-8);
		affectableStats.setStat(CharStats.STAT_STRENGTH,affectableStats.getStat(CharStats.STAT_STRENGTH)-10);
		if(affectableStats.getStat(CharStats.STAT_CONSTITUTION)<=0)
			affectableStats.setStat(CharStats.STAT_CONSTITUTION,1);
		if(affectableStats.getStat(CharStats.STAT_STRENGTH)<=0)
			affectableStats.setStat(CharStats.STAT_STRENGTH,1);
	}

	@Override
	public void affectCharState(MOB affected, CharState affectableState)
	{
		if(affected==null)
			return;
		affectableState.setMovement(10);
		affectableState.setMana(affectableState.getMana()-(affectableState.getMana()/2));
		affectableState.setHitPoints(affectableState.getHitPoints()-(affected.phyStats().level()*2));
	}
}


text:
<!--
~ Copyright (c) 2005-2014, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
~
~ WSO2 Inc. licenses this file to you under the Apache License,
~ Version 2.0 (the "License"); you may not use this file except
~ in compliance with the License.
~ You may obtain a copy of the License at
~
~    http://www.apache.org/licenses/LICENSE-2.0
~
~ Unless required by applicable law or agreed to in writing,
~ software distributed under the License is distributed on an
~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
~ KIND, either express or implied.  See the License for the
~ specific language governing permissions and limitations
~ under the License.
-->

<project default="run">

    <property name="cep.home" value="../../.."/>
    <property name="src.dir" value="src/main/java"/>
    <!--<property name="lib.dir" value="lib"/>-->
    <property name="resources.dir" value="src/main/resources"/>
    <property name="temp.dir" value="temp"/>
    <property name="class.dir" value="${temp.dir}/classes"/>

    <property name="host" value="localhost"/>
    <property name="port" value="7661"/>

    <path id="javac.classpath">
        <pathelement path="${class.dir}"/>
        <fileset dir="${cep.home}/repository/components/plugins/">
            <include name="org.wso2.carbon.logging_*.jar"/>
            <include name="com.google.gson_*.jar"/>
            <include name="com.google.guava_*.jar"/>
            <include name="libthrift_*.jar"/>
            <include name="slf4j.log4j*.jar"/>
            <include name="slf4j.api_*.jar"/>
            <include name="json_*.jar"/>
            <include name="org.wso2.carbon.databridge.commons.thrift_*.jar"/>
            <include name="org.wso2.carbon.user.core_*.jar"/>
            <include name="org.wso2.carbon.user.api_*.jar"/>
            <include name="org.wso2.carbon.databridge.commons_*.jar"/>
            <include name="org.wso2.carbon.databridge.core_*.jar"/>
            <include name="org.wso2.carbon.databridge.receiver.thrift_*.jar"/>
            <include name="org.wso2.carbon.base_*.jar"/>
            <include name="org.wso2.carbon.identity.authentication_*.jar"/>
        </fileset>
    </path>

    <target name="clean">
        <!--<delete dir="target" quiet="true"/>-->
        <delete dir="${class.dir}" quiet="true"/>
        <delete dir="${temp.dir}"/>
    </target>

    <target name="init">
        <mkdir dir="${temp.dir}"/>
        <mkdir dir="${class.dir}"/>
    </target>

    <target name="compile" depends="init">
        <javac srcdir="${src.dir}" destdir="${class.dir}">
            <include name="**/*"/>
            <classpath refid="javac.classpath"/>
        </javac>
        <copy todir="${class.dir}" overwrite="true">
            <fileset dir="${resources.dir}">
                <include name="*.properties"/>
            </fileset>
        </copy>
    </target>

    <target name="run" depends="compile">
        <echo>To configure host, port and events use -Dhost=xxxx -Dport=xxx -Devents=xx</echo>
        <echo>Sending to : http://${host}:${port}</echo>
        <java classname="org.wso2.carbon.sample.server.TestWso2EventServer"
              classpathref="javac.classpath" fork="true">
            <arg value="${host}"/>
            <arg value="${port}"/>
        </java>
    </target>

</project>

redpajama_set_name: RedPajamaGithub


text:
(function() {
	var ATTRIBUTE_NAME = "key";

	var labelPrototype = Object.create(HTMLSpanElement.prototype);

	labelPrototype.createdCallback = function(){
    	var shadowRoot = this.shadowRoot || this.createShadowRoot();
    	shadowRoot.appendChild(document.createTextNode(getLabel(this)));
	};

	labelPrototype.attributeChangedCallback = function(attr, oldValue, newValue) {
		var shadowRoot = this.shadowRoot || this.createShadowRoot();
		shadowRoot.innerHTML = "";
		shadowRoot.appendChild(document.createTextNode(getLabel(this)));
	};

	function getLabel(element) {
		if(element.hasAttribute(ATTRIBUTE_NAME)) {
			var key = element.getAttribute(ATTRIBUTE_NAME);
			return chrome.i18n.getMessage(key) || "[" + key + "]";
		}
	};

	document.registerElement('aurainspector-label', {
		prototype: labelPrototype
	});

})();


text:
'use strict';

var taunus = global.taunus;
if (taunus === void 0) {
  throw new Error('You must require(\'taunus\') earlier, when setting up the mountpoint!');
}

module.exports = taunus;


text:
<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope
  xmlns:soap="http://www.w3.org/2003/05/soap-envelope"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <soap:Body>
    <LoginResponse
      xmlns="http://url/DataService/">
      <LoginResult>xxx-777-xxx-123</LoginResult>
    </LoginResponse>
  </soap:Body>
</soap:Envelope>


text:
package com.google.appinventor.components.runtime;

import com.google.appinventor.components.annotations.DesignerComponent;
import com.google.appinventor.components.annotations.DesignerProperty;
import com.google.appinventor.components.annotations.PropertyCategory;
import com.google.appinventor.components.annotations.SimpleEvent;
import com.google.appinventor.components.annotations.SimpleFunction;
import com.google.appinventor.components.annotations.SimpleObject;
import com.google.appinventor.components.annotations.SimpleProperty;
import com.google.appinventor.components.annotations.UsesLibraries;
import com.google.appinventor.components.common.ComponentCategory;
import com.google.appinventor.components.common.PropertyTypeConstants;
import com.google.appinventor.components.common.PunyaVersion;
import com.google.appinventor.components.runtime.util.AsynchUtil;
import com.google.appinventor.components.runtime.util.ErrorMessages;
import com.google.appinventor.components.runtime.util.IOUtils;
import com.google.appinventor.components.runtime.util.MediaUtil;
import com.google.appinventor.components.runtime.util.YailDictionary;
import com.google.appinventor.components.runtime.util.YailList;
import com.hp.hpl.jena.query.Query;
import com.hp.hpl.jena.query.QueryExecution;
import com.hp.hpl.jena.query.QueryExecutionFactory;
import com.hp.hpl.jena.query.QueryFactory;
import com.hp.hpl.jena.query.QuerySolution;
import com.hp.hpl.jena.query.ResultSet;
import com.hp.hpl.jena.rdf.model.InfModel;
import com.hp.hpl.jena.rdf.model.ModelFactory2;
import com.hp.hpl.jena.rdf.model.RDFNode;
import com.hp.hpl.jena.reasoner.BaseInfGraph;
import com.hp.hpl.jena.reasoner.ReasonerRegistry;
import com.hp.hpl.jena.reasoner.rulesys.FBRuleReasoner;
import com.hp.hpl.jena.reasoner.rulesys.GenericRuleReasoner;
import com.hp.hpl.jena.reasoner.rulesys.Rule;
import com.hp.hpl.jena.reasoner.rulesys.RuleReasoner;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * The Reasoner component derives statements from the contents of a
 * LinkedData component.
 *
 * @author Evan W. Patton (ewpatton@mit.edu)
 */
@DesignerComponent(version = PunyaVersion.REASONER_COMPONENT_VERSION,
    nonVisible = true,
    category = ComponentCategory.LINKEDDATA,
    iconName = "images/reasoner.png"
)
@SimpleObject
@UsesLibraries({"jena-reasoner.jar"})
public class Reasoner extends LinkedDataBase<InfModel> {

  private static final String LOG_TAG = Reasoner.class.getSimpleName();
  private LinkedData basemodel = null;
  private String rulesEngine = "";
  private String rulesFile = "";
  private List<Rule> rules = new ArrayList<>();

  /**
   * Creates a new Reasoner..
   *
   * @param form the container that this component will be placed in
   */
  public Reasoner(Form form) {
    super(form);
  }

  ///region Properties

  @SimpleProperty
  public LinkedData Model() {
    return basemodel;
  }

  /**
   * Specifies the base model (A-Box + T-Box) for reasoning.
   */
  @DesignerProperty(
      editorType = PropertyTypeConstants.PROPERTY_TYPE_COMPONENT + ":com.google.appinventor.components.runtime.LinkedData"
  )
  @SimpleProperty(category = PropertyCategory.BEHAVIOR)
  public void Model(LinkedData model) {
    this.basemodel = model;
  }

  @SimpleProperty
  public String RulesEngine() {
    return "";
  }

  /**
   * Specifies the base semantics that should be used for reasoning.
   *
   * @param rules the base semantics to use for reasoning
   */
  @DesignerProperty(editorType = PropertyTypeConstants.PROPERTY_TYPE_CHOICES,
      editorArgs = {"None", "RDFS", "OWL Micro", "OWL Mini", "OWL"},
      defaultValue = "None")
  @SimpleProperty(category = PropertyCategory.BEHAVIOR)
  public void RulesEngine(String rules) {
    this.rulesEngine = rules;
  }

  @SimpleProperty
  public String RulesFile() {
    return rulesFile;
  }

  /**
   * An optional file containing custom rules to be used during reasoning. The rules are applied
   * in addition to any reasoning applied by the choice of {@link #RulesEngine}.
   *
   * @param rules path to an additional ruleset to include for reasoning
   */
  @DesignerProperty(editorType = PropertyTypeConstants.PROPERTY_TYPE_ASSET)
  @SimpleProperty(category = PropertyCategory.BEHAVIOR)
  public void RulesFile(String rules) {
    this.rulesFile = rules;
  }

  ///endregion
  ///region Methods

  /**
   * Runs the reasoner in forward chaining model to derive conclusions. On success, the
   * {@link #ReasoningComplete} event will run. {@link #ErrorOccurred} event will run if reasoning
   * fails.
   */
  @SimpleFunction
  public void Run() {
    if (this.basemodel == null) {
      form.dispatchErrorOccurredEvent(this, "Run", 0);
      return;
    }
    final String rulesFile = this.rulesFile;
    final String rulesEngine = this.rulesEngine;
    AsynchUtil.runAsynchronously(new Runnable() {
      @Override
      public void run() {
        try {
          com.hp.hpl.jena.reasoner.Reasoner reasoner;
          if ("RDFS".equals(rulesEngine)) {
            reasoner = ReasonerRegistry.getRDFSReasoner();
          } else if ("OWL Micro".equals(rulesEngine)) {
            reasoner = ReasonerRegistry.getOWLMicroReasoner();
          } else if ("OWL Mini".equals(rulesEngine)) {
            reasoner = ReasonerRegistry.getOWLMiniReasoner();
          } else if ("OWL".equals(rulesEngine)) {
            reasoner = ReasonerRegistry.getOWLReasoner();
          } else {
            reasoner = new GenericRuleReasoner(new ArrayList<>(rules));
            ((GenericRuleReasoner) reasoner).setMode(GenericRuleReasoner.HYBRID);
          }
          model = ModelFactory2.createInfModel(reasoner, basemodel.getModel());
          if (rulesFile != null && !rulesFile.equals("")) {
            if (reasoner instanceof FBRuleReasoner) {
              ((FBRuleReasoner) reasoner).addRules(loadRules(rulesFile));
            } else if (reasoner instanceof RuleReasoner) {
              ((RuleReasoner) reasoner).setRules(loadRules(rulesFile));
            }
          }
          model.prepare();
          if (model.getGraph() instanceof BaseInfGraph) {
            ((BaseInfGraph) model.getGraph()).validate();
            // TODO(ewpatton): Report validity to blocks
          }
          form.runOnUiThread(new Runnable() {
            @Override
            public void run() {
              ReasoningComplete();
            }
          });
        } catch (final Exception e) {
          form.runOnUiThread(new Runnable() {
            @Override
            public void run() {
              ErrorOccurred(e.toString());
            }
          });
        }
      }
    });
  }

  /**
   * Populate the rule-based reasoner with the given ruleset of custom rules.
   *
   * @param ruleset the ruleset as a string
   */
  @SimpleFunction
  public void RulesFromRuleset(String ruleset) {
    rules = Rule.parseRules(ruleset);
    String[] lines = rules.toString().split("\n");
    System.err.println("Rules:");
    for (String line : lines) {
      System.err.println(line);
    }
  }

  /**
   * Return the loaded rules (if any) as a string.
   *
   * @return
   */
  @SimpleFunction
  public String RulesetToString() {
    StringBuffer ret = new StringBuffer();
    for (Rule rule : rules)
      ret.append(rule.toString()).append("\n");
    return ret.toString().trim();
  }

  /**
   * Adds additional rules to an existing ruleset.
   *
   * @param ruleset the ruleset as a string
   */
  @SimpleFunction
  public void AddRulesFromRuleset(String ruleset) {
    List<Rule> newRules = Rule.parseRules(ruleset);
    rules.addAll(newRules);
    String[] lines = rules.toString().split("\n");
    System.err.println("Rules:");
    for (String line : lines) {
      System.err.println(line);
    }
  }

  /**
   * Synchronously evaluate a SPARQL query over the knowledge base. The return type depends on the
   * type of query run. For SELECT queries, the return value is a JSON-like dictionary containing
   * results in the SPARQL 1.1 Query Result format.
   *
   * @param query a string containing a valid SPARQL query
   * @return the query results
   */
  @SimpleFunction
  public Object Query(String query) {
    Query sparql = QueryFactory.create(query);
    QueryExecution qe = QueryExecutionFactory.create(sparql, model);
    if (sparql.isSelectType()) {
      ResultSet rs = qe.execSelect();
      YailDictionary result = new YailDictionary();
      YailDictionary head = new YailDictionary();
      head.put("vars", YailList.makeList(rs.getResultVars()));
      result.put("head", head);
      List<YailDictionary> results = new ArrayList<>();
      while (rs.hasNext()) {
        YailDictionary yailBinding = new YailDictionary();
        QuerySolution binding = rs.next();
        Iterator<String> vars = binding.varNames();
        while (vars.hasNext()) {
          String var = vars.next();
          RDFNode value = binding.get(var);
          if (value != null) {
            yailBinding.put(var, value.toString());
          }
        }
        results.add(yailBinding);
      }
      result.put("results", YailList.makeList(results));
      return result;
    }
    return Collections.emptyList();
  }

  ///endregion
  ///region Events

  /**
   * Runs when the reasoner has been prepared and any forward-chaining rules have finished.
   */
  @SimpleEvent
  public void ReasoningComplete() {
    EventDispatcher.dispatchEvent(this, "ReasoningComplete");
  }

  /**
   * Runs when the reasoner encounters an error during reasoning.
   *
   * @param message the error message
   */
  @SimpleEvent
  public void ErrorOccurred(String message) {
    if (!EventDispatcher.dispatchEvent(this, "ErrorOccurred", message)) {
      form.dispatchErrorOccurredEvent(this, "Run", ErrorMessages.ERROR_REASONER_FAILED, message);
    }
  }

  ///endregion

  private List<Rule> loadRules(String filename) throws IOException {
    InputStream in = null;
    try {
      in = MediaUtil.openMedia(form, filename);
      return Rule.parseRules(IOUtils.readStream(in));
    } finally {
      IOUtils.closeQuietly(LOG_TAG, in);
    }
  }
}


text:
import {Type} from './abstract';

/**
 * Represents a type parameter type.
 *
 * ~~~
 * let value: T;
 * ~~~
 */
export class TypeParameterType extends Type {
    /**
     *
     */
    name: string;

    constraint: Type;

    /**
     * Clone this type.
     *
     * @return A clone of this type.
     */
    clone(): Type {
        const clone = new TypeParameterType();
        clone.isArray = this.isArray;
        clone.name = this.name;
        clone.constraint = this.constraint;
        return clone;
    }

    /**
     * Test whether this type equals the given type.
     *
     * @param type  The type that should be checked for equality.
     * @returns TRUE if the given type equals this type, FALSE otherwise.
     */
    equals(type: TypeParameterType): boolean {
        if (!(type instanceof TypeParameterType)) {
            return false;
        }

        let constraintEquals: boolean;
        if (this.constraint && type.constraint) {
            constraintEquals = type.constraint.equals(this.constraint);
        } else if (!this.constraint && !type.constraint) {
            constraintEquals = true;
        } else {
            return false;
        }

        return constraintEquals &&
            type.isArray === this.isArray;
    }

    /**
     * Return a raw object representation of this type.
     */
    toObject(): any {
        const result: any = super.toObject();
        result.type = 'typeParameter';
        result.name = this.name;

        if (this.constraint) {
            result.constraint = this.constraint.toObject();
        }

        return result;
    }

    /**
     * Return a string representation of this type.
     */
    toString() {
        return this.name;
    }
}


text:
class Admin::EngagementsController < Admin::BaseController
  before_filter :find_engagement, :only => [:edit, :update, :show, :destroy]
  def index
    @engagements = Engagement.all
  end

  def show
  end

  def new
    @engagement = Engagement.new
  end

  def create
    @engagement = Engagement.new(params[:engagement])
    if @engagement.save
      redirect_to admin_engagements_path, :notice => "Successfully created engagement."
    else
      render :action => 'new'
    end
  end

  def edit
  end

  def update
    if @engagement.update_attributes(params[:engagement])
      redirect_to admin_engagements_path, :notice  => "Successfully updated engagement."
    else
      render :action => 'edit'
    end
  end

  def destroy
    @engagement.destroy
    redirect_to admin_engagements_path, :notice => "Successfully destroyed engagement."
  end

  protected

  def find_engagement
    @engagement = Engagement.find(params[:id])
  end
end


text:
"""
Automatically download ancillary, given
a YAML config file. See the auto module.
"""
from __future__ import absolute_import

if __name__ == '__main__':
    from .scripts import service
    service.main()


text:
package gov.va.isaac.gui.refexViews.util;

import java.util.ArrayList;
import java.util.List;
import javafx.beans.property.ReadOnlyStringProperty;
import javafx.collections.ListChangeListener;
import javafx.collections.ObservableList;
import javafx.scene.Node;
import com.sun.javafx.collections.ObservableListWrapper;

/**
 * {@link SememeGUIDataTypeNodeDetails}
 *
 * A helper class that contains all of the return details for the structured created by a static call to
 * {@link SememeGUIDataTypeFXNodeBuilder}.
 *
 * *** WARNING *** boundToAllValid is an Observable List - because its contents will change based on user input if this
 * was created for a Polymorphic node!  You must add a listener to the list in this case!  A utility method is provided
 * for adding this listener which will automatically update a parent list.  Make sure to call cleanup, to prevent a memory
 * leak if you use this mechanism.
 *
 * The list will not change for data types other than Polymorphic.
 *
 * @author Dan Armbrust
 */
public class SememeGUIDataTypeNodeDetails
{
	protected Object dataField;
	protected Node nodeForDisplay;
	protected ObservableList<ReadOnlyStringProperty> boundToAllValid = new ObservableListWrapper<>(new ArrayList<>());
	private ListChangeListener<ReadOnlyStringProperty> changeListener;

	/**
	 * @return the dataField
	 */
	public Object getDataField()
	{
		return dataField;
	}
	/**
	 * @return the nodeForDisplay
	 */
	public Node getNodeForDisplay()
	{
		return nodeForDisplay;
	}
	/**
	 * @return things that were bound to the allValid parameter.
	 */
	public ObservableList<ReadOnlyStringProperty> getBoundToAllValid()
	{
		return boundToAllValid;
	}

	public void addUpdateParentListListener(List<ReadOnlyStringProperty> listToUpdate)
	{
		if (changeListener != null)
		{
			boundToAllValid.removeListener(changeListener);
		}
		changeListener = new ListChangeListener<ReadOnlyStringProperty>()
		{

			@Override
			public void onChanged(Change<? extends ReadOnlyStringProperty> listChange)
			{
				while (listChange.next())
				{
					for (ReadOnlyStringProperty sp : listChange.getRemoved())
					{
						listToUpdate.remove(sp);
					}
					listToUpdate.addAll(listChange.getAddedSubList());
				}
			}
		};
		boundToAllValid.addListener(changeListener);
	}

	public void cleanupListener()
	{
		if (changeListener != null)
		{
			boundToAllValid.removeListener(changeListener);
			changeListener = null;
		}
	}
}


text:
/*jslint node: true */
/*global module, require,describe,it*/
'use strict';

var mocha = require('mocha');
var assert = require('assert');
var expect = require('chai').expect;

var Workflow = require('../index');

var ValidationError = require('../lib/work/flow/error/validation');

var Bad = require('./data/bad');
var Good = require('./data/good');

describe('client', function clientTest() {

  it('should initialize', function shouldInitialize() {
    assert(expect(Workflow).to.exist);

    var work = new Workflow();
    assert(expect(work).to.exist);
    assert(expect(work).to.exist);
  });

  it('should flow', function shouldFlow() {
    var work = new Workflow();
    assert(expect(work).to.exist);
    assert(expect(work.flow).to.exist);
  });

  it('should flow.path', function shouldFlowPath() {
    var work = new Workflow();
    assert(expect(work).to.exist);
    assert(expect(work.flow).to.exist);
    assert(expect(work.flow.path).to.exist);
  });

  it('should flow.path.definition', function shouldFlowPathDefinition() {
    var work = new Workflow();
    assert(expect(work).to.exist);
    assert(expect(work.flow).to.exist);
    assert(expect(work.flow.path.definition).to.exist);
    expect(work.flow.path.definition).to.be.instanceOf(Function);
  });

  it('should return flow.path.definition', function shouldFlowTaskDefinition(
    done) {
    var work = new Workflow();
    assert(expect(work).to.exist);
    assert(expect(work.flow).to.exist);
    assert(expect(work.flow.path.definition).to.exist);
    expect(work.flow.path.definition).to.be.instanceOf(Function);
    work.flow.path.definition(Good.path.definition, function(err,
      result) {
      assert(expect(err).to.not.exist);
      assert(expect(result).to.exist);
      expect(result.uri).to.equal(Good.path.definition.uri);
      expect(result.properties).to.equal(Good.path.definition.properties);
      done();
    });
  });

  it('should return failed flow.path.definition', function shouldFlowTaskDefinition(
    done) {
    var work = new Workflow();
    assert(expect(work).to.exist);
    assert(expect(work.flow).to.exist);
    assert(expect(work.flow.path.definition).to.exist);
    expect(work.flow.path.definition).to.be.instanceOf(Function);
    work.flow.path.definition(Bad.path.definition, function(err,
      result) {
      assert(expect(err).to.exist);
      assert(expect(result).to.not.exist);
      done();
    });
  });

  it('should fail flow.path.definition', function shouldFlowTaskDefinition() {
    var work = new Workflow();
    assert(expect(work).to.exist);
    assert(expect(work.flow).to.exist);
    assert(expect(work.flow.path.definition).to.exist);
    expect(work.flow.path.definition).to.be.instanceOf(Function);
    expect(function() {
      work.flow.path.definition(Bad.path.definition);
    }).to.throw(ValidationError);
  });

  it('should flow.task', function shouldFlowTask() {
    var work = new Workflow();
    assert(expect(work).to.exist);
    assert(expect(work.flow).to.exist);
    assert(expect(work.flow.task).to.exist);
  });

  it('should flow.task.definition', function shouldFlowTaskDefinition() {
    var work = new Workflow();
    assert(expect(work).to.exist);
    assert(expect(work.flow).to.exist);
    assert(expect(work.flow.task.definition).to.exist);
    expect(work.flow.task.definition).to.be.instanceOf(Function);
  });

  it('should return flow.task.definition', function shouldFlowTaskDefinition(
    done) {
    var work = new Workflow();
    assert(expect(work).to.exist);
    assert(expect(work.flow).to.exist);
    assert(expect(work.flow.task.definition).to.exist);
    expect(work.flow.task.definition).to.be.instanceOf(Function);
    work.flow.task.definition(Good.task.definition, function(err,
      result) {
      assert(expect(err).to.not.exist);
      assert(expect(result).to.exist);
      expect(result.uri).to.equal(Good.task.definition.uri);
      expect(result.properties).to.equal(Good.task.definition.properties);
      done();
    });
  });

  it('should return failed flow.task.definition', function shouldFlowTaskDefinition(
    done) {
    var work = new Workflow();
    assert(expect(work).to.exist);
    assert(expect(work.flow).to.exist);
    assert(expect(work.flow.task.definition).to.exist);
    expect(work.flow.task.definition).to.be.instanceOf(Function);
    work.flow.task.definition(Bad.task.definition, function(err,
      result) {
      assert(expect(err).to.exist);
      assert(expect(result).to.not.exist);
      done();
    });
  });

  it('should fail flow.task.definition', function shouldFlowTaskDefinition() {
    var work = new Workflow();
    assert(expect(work).to.exist);
    assert(expect(work.flow).to.exist);
    assert(expect(work.flow.task.definition).to.exist);
    expect(work.flow.task.definition).to.be.instanceOf(Function);
    expect(function() {
      work.flow.task.definition(Bad.task.definition);
    }).to.throw(ValidationError);
  });

  it('should flow.definition', function shouldFlowPathDefinition() {
    var work = new Workflow();
    assert(expect(work).to.exist);
    assert(expect(work.flow).to.exist);
    assert(expect(work.flow.definition).to.exist);
    expect(work.flow.definition).to.be.instanceOf(Function);
  });

  it('should return flow.definition', function shouldFlowTaskDefinition(
    done) {
    var work = new Workflow();
    assert(expect(work).to.exist);
    assert(expect(work.flow).to.exist);
    assert(expect(work.flow.definition).to.exist);
    expect(work.flow.definition).to.be.instanceOf(Function);
    work.flow.definition(Good.workflow.definition, function(err, result) {
      assert(expect(err).to.not.exist);
      assert(expect(result).to.exist);
      expect(result.uri).to.equal(Good.workflow.definition.uri);
      expect(result.properties).to.equal(Good.workflow.definition.properties);
      done();
    });

  });

  it('should return fail flow.definition', function shouldFlowTaskDefinition(
    done) {
    var work = new Workflow();
    assert(expect(work).to.exist);
    assert(expect(work.flow).to.exist);
    assert(expect(work.flow.definition).to.exist);
    expect(work.flow.definition).to.be.instanceOf(Function);
    work.flow.definition(Bad.workflow.definition, function(err, result) {
      assert(expect(err).to.exist);
      assert(expect(result).to.not.exist);
      done();
    });
  });

  it('should return failed flow.definition x2', function shouldFlowTaskDefinition(
    done) {
    var work = new Workflow();
    assert(expect(work).to.exist);
    assert(expect(work.flow).to.exist);
    assert(expect(work.flow.definition).to.exist);
    expect(work.flow.definition).to.be.instanceOf(Function);
    work.flow.definition({
      uri: ' '
    }, function(err, result) {
      assert(expect(err).to.exist);
      assert(expect(result).to.not.exist);
      done();
    });
  });

  it('should fail flow.definition', function shouldFlowTaskDefinition() {
    var work = new Workflow();
    assert(expect(work).to.exist);
    assert(expect(work.flow).to.exist);
    assert(expect(work.flow.definition).to.exist);
    expect(function() {
      work.flow.definition(Bad.workflow.definition);
    }).to.throw(ValidationError);
  });

  it('should flow.run', function shouldFlowPathDefinition(done) {
    var work = new Workflow();
    assert(expect(work).to.exist);
    assert(expect(work.flow).to.exist);
    assert(expect(work.flow.run).to.exist);
    expect(work.flow.run).to.be.instanceOf(Function);
    work.flow.run(Good.workflow.run, function(err, result) {
      assert(expect(err).to.not.exist);
      done();
    });
  });
});


text:
package command

/*
 * convert package setting to env.
 * ex:
 * root.setting => _ROOT__SETTING_
 * if 1st argument == root, will set root.setting to _SETTING_ too.
 */

import (
	"fmt"
	"os"
	"strings"

	"github.com/BurntSushi/toml"
	"github.com/boltdb/bolt"
	"github.com/mitchellh/cli"
)

type EnvCommand struct {
	UI cli.Ui
}

func init() {
	_ENV = os.Environ()
	_HOME = os.Getenv("HOME")
}

func (c *EnvCommand) Help() string {
	helpText := `
Usage: rogi env pkg [filename]

`
	return strings.TrimSpace(helpText)
}

// Run will return integer as true or false.
func (c *EnvCommand) Run(args []string) int {
	length := len(args)
	db := initDb()
	defer db.Close()

	db.View(func(tx *bolt.Tx) error {
		b, err := tx.CreateBucketIfNotExists([]byte(SETTING_BUCKET))
		if err != nil {
			return fmt.Errorf("create bucket: %s", err)
		}

		cur := b.Cursor()

		for k, v := cur.First(); k != nil; k, v = cur.Next() {
			var x settings
			if _, err := toml.Decode(string(v), &x); err != nil {
				continue
			}

			for y, z := range x {
				env := fmt.Sprintf("_%s__%s=%s", strings.ToUpper(string(k)), strings.ToUpper(y), strings.ToUpper(z))
				_ENV = append(_ENV, env)
			}
		}

		return nil
	})

	switch length {
	case 2:
		out, err := Run(args[1])
		if err != nil {
			msg := fmt.Sprintf("Could not run (%s) error (%v)", args[1], err)
			c.UI.Warn(msg)
		}
		fmt.Printf("out: %s\n", out)
	default:
		for i := range _ENV {
			fmt.Fprintf(os.Stdout, "%s\n", _ENV[i])
		}
	}

	return 0
}

func (c *EnvCommand) Synopsis() string {
	return "env"
}


text:
package org.fest.assertions;

import org.jetbrains.annotations.NotNull;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;

import static org.fest.util.Lists.newArrayList;

/**
 * @author Alex Ruiz
 */
public class TestObjectGroupAssert extends ObjectGroupAssert<TestObjectGroupAssert, List<?>> {
  public TestObjectGroupAssert(List<?> actual) {
    super(TestObjectGroupAssert.class, actual);
  }

  @Override
  protected int actualGroupSize() {
    return actual.size();
  }

  @Override
  protected @NotNull TestObjectGroupAssert onProperty(@NotNull String propertyName) {
    throw new UnsupportedOperationException();
  }

  /**
   * {@inheritDoc}
   */
  @Override
  protected Set<Object> actualAsSet() {
    return new LinkedHashSet<Object>(actual);
  }

  /**
   * {@inheritDoc}
   */
  @Override
  protected List<Object> actualAsList() {
    return newArrayList(actual);
  }
}


text:
package com.papercut.dust;

import com.papercut.dust.claim.AlreadyClaimedException;
import com.papercut.dust.claim.NoSuchClaimException;
import com.papercut.dust.device.NoSuchUniqueDeviceException;

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

@Provider
public class CustomExceptionMapper implements ExceptionMapper<Exception> {

    @Override
    public Response toResponse(final Exception exception) {
        if (exception instanceof AlreadyClaimedException) {
            return withStatus(exception, Response.Status.CONFLICT);
        } else if (exception instanceof NoSuchClaimException) {
            return withStatus(exception, Response.Status.CONFLICT);
        } else if (exception instanceof NoSuchUniqueDeviceException) {
            return withStatus(exception, Response.Status.NOT_FOUND);
        } else {
            return withStatus(exception, Response.Status.INTERNAL_SERVER_ERROR);
        }
    }

    private static Response withStatus(final Exception exception, final Response.Status status) {
        return Response.status(status)
                .entity(exception.getMessage())
                .type(MediaType.TEXT_PLAIN)
                .build();
    }

}


text:
package partition;

/**
 *
 * @author gburdell
 */
public class Util {

    public static void error(String msg, Object... args) {
        errora(msg, args);
    }

    public static void errora(String msg, Object args[]) {
        gblib.MessageMgr.message('E', msg, args);
        System.exit(2);
    }

    public static class Pair<T1, T2> {

        public Pair() {
            first = null;
            second = null;
        }

        public Pair(T1 first, T2 second) {
            this.first = first;
            this.second = second;
        }
        public final T1 first;
        public final T2 second;
    }
}


text:
import 'react-native';
import React from 'react';
// Note: test renderer must be required after react-native.
import renderer from 'react-test-renderer';
import Subheader from '../index';

it('default props', () => {
  const subheader = renderer.create(<Subheader text="Test" />).toJSON();

  expect(subheader).toMatchSnapshot();
});
it('with inset', () => {
  const subheader = renderer.create(<Subheader text="Test" inset />).toJSON();

  expect(subheader).toMatchSnapshot();
});


text:
<!doctype html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Magic Web</title>
    <meta name="description" content="Discover all the amazing things your browser can do" />
    <link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico">
    <link rel="manifest" href="%PUBLIC_URL%/manifest.json">
    <meta name="mobile-web-app-capable" content="yes" />
    <meta name="theme-color" content="#c41162" />

    <meta itemprop="name" content="Magic Web" />
    <meta itemprop="description" content="Discover all the amazing things your browser can do" />
    <meta itemprop="image" content="https://soyguijarro.github.io/magic-web/favicon.ico" />

    <meta name="twitter:card" content="summary" />
    <meta name="twitter:site" content="@soyguijarro" />
    <meta name="twitter:title" content="Magic Web" />
    <meta name="twitter:description" content="Discover all the amazing things your browser can do" />
    <meta name="twitter:creator" content="@soyguijarro" />
    <meta name="twitter:image" content="https://soyguijarro.github.io/magic-web/favicon.ico" />
    <meta name="twitter:image:alt" content="Discover all the amazing things your browser can do" />

    <meta property="og:title" content="Magic Web" />
    <meta property="og:type" content="website" />
    <meta property="og:url" content="https://soyguijarro.github.io/magic-web/" />
    <meta property="og:image" content="https://soyguijarro.github.io/magic-web/favicon.ico" />
    <meta property="og:description" content="Discover all the amazing things your browser can do" />
    <meta property="og:site_name" content="Magic Web" />


text:
/* A simple C++ wrapper around libffi. */

#include "vm/config.h"

#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <unistd.h>
#include <sys/stat.h>
#ifdef RBX_WINDOWS
#include <malloc.h>
#else
#include <dlfcn.h>
#endif

#include "prelude.hpp"
#include "object_utils.hpp"
#include "vm.hpp"
#include "objectmemory.hpp"
#include "on_stack.hpp"

#include "builtin/array.hpp"
#include "builtin/class.hpp"
#include "builtin/fixnum.hpp"
#include "builtin/float.hpp"
#include "builtin/proc.hpp"
#include "builtin/ffi_pointer.hpp"
#include "builtin/nativefunction.hpp"
#include "builtin/string.hpp"
#include "builtin/symbol.hpp"
#include "builtin/system.hpp"
#include "builtin/location.hpp"
#include "builtin/nativemethod.hpp"

#include "ontology.hpp"

#include "ffi_util.hpp"
#include "arguments.hpp"
#include "dispatch.hpp"

#include "builtin/nativefunction.hpp"

#include "instruments/tooling.hpp"

namespace rubinius {

  void NativeFunction::init(STATE) {
    GO(native_function).set(ontology::new_class(state,
          "NativeFunction", G(executable), G(rubinius)));
    G(native_function)->set_object_type(state, NativeFunctionType);
  }

  FFIData* FFIData::create(NativeFunction* func, int count, FFIArgInfo* args,
                           FFIArgInfo* ret)
  {
    void* ep;

    FFIData* data = new FFIData(func, count, args, ret);
    data->closure = reinterpret_cast<ffi_closure*>(
                      ffi_closure_alloc(sizeof(ffi_closure), &ep));

    data->ep = ep;

    return data;
  }

  FFIData::FFIData(NativeFunction* func,  int count, FFIArgInfo* args, FFIArgInfo* ret)
    : closure(0)
    , callable(0)
    , function(func)
    , args_info(args)
    , ret_info(*ret)
    , arg_count(count)
  {}

  FFIData::~FFIData() {
    free(args_info);
    XFREE(cif.arg_types);
    if(closure) ffi_closure_free(closure);
  }

  /* Run when a NativeFunction is executed.  Executes the related C function.
   */
  Object* NativeFunction::execute(STATE, CallFrame* call_frame, Executable* exec, Module* mod,
                                  Arguments& args) {
    NativeFunction* nfunc = as<NativeFunction>(exec);

    state->set_call_frame(call_frame);

    try {

#ifdef RBX_PROFILER
      if(unlikely(state->vm()->tooling())) {
        tooling::MethodEntry method(state, exec, mod, args);
        return nfunc->call(state, args, call_frame);
      } else {
        return nfunc->call(state, args, call_frame);
      }
#else
      return nfunc->call(state, args, msg, call_frame);
#endif

    } catch(TypeError &e) {
      Exception* exc =
        Exception::make_type_error(state, e.type, e.object, e.reason);
      exc->locations(state, Location::from_call_stack(state, call_frame));

      state->raise_exception(exc);
      return NULL;
    }
  }

  size_t NativeFunction::type_size(size_t type) {
    switch(type) {
      case RBX_FFI_TYPE_CHAR:
      case RBX_FFI_TYPE_UCHAR:
      case RBX_FFI_TYPE_BOOL:
        return sizeof(char);

      case RBX_FFI_TYPE_SHORT:
      case RBX_FFI_TYPE_USHORT:
        return sizeof(short);

      case RBX_FFI_TYPE_INT:
      case RBX_FFI_TYPE_UINT:
        return sizeof(int);

      case RBX_FFI_TYPE_LONG:
      case RBX_FFI_TYPE_ULONG:
        return sizeof(long);

      case RBX_FFI_TYPE_LONG_LONG:
      case RBX_FFI_TYPE_ULONG_LONG:
        return sizeof(long long);

      case RBX_FFI_TYPE_FLOAT:
        return sizeof(float);

      case RBX_FFI_TYPE_DOUBLE:
        return sizeof(double);

      case RBX_FFI_TYPE_PTR:
      case RBX_FFI_TYPE_STRING:
      case RBX_FFI_TYPE_STATE:
      case RBX_FFI_TYPE_STRPTR:
      case RBX_FFI_TYPE_OBJECT:
        return sizeof(void*);

      default:
        rubinius::bug("Unsupported FFI type");
		return 0;	// Keep GCC happy
    }
  }

  Fixnum* NativeFunction::type_size_prim(STATE, Fixnum* type) {
    return Fixnum::from(NativeFunction::type_size(type->to_native()));
  }

  NativeFunction* NativeFunction::create(STATE, Symbol* name, int args) {
    NativeFunction* nf = state->new_object<NativeFunction>(G(native_function));
    nf->primitive(state, state->symbol("nativefunction_call"));
    nf->required(state, Fixnum::from(args));
    nf->serial(state, Fixnum::from(0));
    nf->name(state, name);
    nf->file(state, state->symbol("<system>"));

    nf->set_executor(NativeFunction::execute);
    nf->inliners_ = 0;
    nf->ffi_data = 0;

    return nf;
  }

  void NativeFunction::prep(STATE, int arg_count, FFIArgInfo* args,
                            FFIArgInfo* ret) {

    ffi_type** types;
    ffi_status status;
    ffi_type* rtype;
    int i;

    types = ALLOC_N(ffi_type*, arg_count);

    for(i = 0; i < arg_count; i++) {
      switch(args[i].type) {
      case RBX_FFI_TYPE_CHAR:
        types[i] = &ffi_type_schar;
        break;
      case RBX_FFI_TYPE_UCHAR:
      case RBX_FFI_TYPE_BOOL:
        types[i] = &ffi_type_uchar;
        break;
      case RBX_FFI_TYPE_SHORT:
        types[i] = &ffi_type_sshort;
        break;
      case RBX_FFI_TYPE_USHORT:
        types[i] = &ffi_type_ushort;
        break;
      case RBX_FFI_TYPE_INT:
      case RBX_FFI_TYPE_ENUM:
        types[i] = &ffi_type_sint;
        break;
      case RBX_FFI_TYPE_UINT:
        types[i] = &ffi_type_uint;
        break;
      case RBX_FFI_TYPE_LONG:
        types[i] = &ffi_type_slong;
        break;
      case RBX_FFI_TYPE_ULONG:
        types[i] = &ffi_type_ulong;
        break;
      case RBX_FFI_TYPE_FLOAT:
        types[i] = &ffi_type_float;
        break;
      case RBX_FFI_TYPE_DOUBLE:
        types[i] = &ffi_type_double;
        break;
      case RBX_FFI_TYPE_LONG_LONG:
        types[i] = &ffi_type_sint64;
        break;
      case RBX_FFI_TYPE_ULONG_LONG:
        types[i] = &ffi_type_uint64;
        break;
      case RBX_FFI_TYPE_OBJECT:
      case RBX_FFI_TYPE_PTR:
      case RBX_FFI_TYPE_CALLBACK:
      case RBX_FFI_TYPE_STRING:
      case RBX_FFI_TYPE_STATE:
        types[i] = &ffi_type_pointer;
        break;
      }
    }

    switch(ret->type) {
    case RBX_FFI_TYPE_CHAR:
      rtype = &ffi_type_schar;
      break;
    case RBX_FFI_TYPE_UCHAR:
    case RBX_FFI_TYPE_BOOL:
      rtype = &ffi_type_uchar;
      break;
    case RBX_FFI_TYPE_SHORT:
      rtype = &ffi_type_sshort;
      break;
    case RBX_FFI_TYPE_USHORT:
      rtype = &ffi_type_ushort;
      break;
    case RBX_FFI_TYPE_INT:
    case RBX_FFI_TYPE_ENUM:
      rtype = &ffi_type_sint;
      break;
    case RBX_FFI_TYPE_UINT:
      rtype = &ffi_type_uint;
      break;
    case RBX_FFI_TYPE_LONG:
      rtype = &ffi_type_slong;
      break;
    case RBX_FFI_TYPE_ULONG:
      rtype = &ffi_type_ulong;
      break;
    case RBX_FFI_TYPE_FLOAT:
      rtype = &ffi_type_float;
      break;
    case RBX_FFI_TYPE_DOUBLE:
      rtype = &ffi_type_double;
      break;
    case RBX_FFI_TYPE_LONG_LONG:
      rtype = &ffi_type_sint64;
      break;
    case RBX_FFI_TYPE_ULONG_LONG:
      rtype = &ffi_type_uint64;
      break;
    case RBX_FFI_TYPE_OBJECT:
    case RBX_FFI_TYPE_PTR:
    case RBX_FFI_TYPE_CALLBACK:
    case RBX_FFI_TYPE_STRING:
    case RBX_FFI_TYPE_STATE:
    case RBX_FFI_TYPE_STRPTR:
      rtype = &ffi_type_pointer;
      break;
    default:
    case RBX_FFI_TYPE_VOID:
      rtype = &ffi_type_void;
      break;
    }

    FFIArgInfo* out_args_info = ALLOC_N(FFIArgInfo, arg_count);
    memcpy(out_args_info, args, sizeof(FFIArgInfo) * arg_count);

    FFIData* data = FFIData::create(this, arg_count, out_args_info, ret);

    status = ffi_prep_cif(&data->cif, FFI_DEFAULT_ABI, arg_count, rtype, types);

    if(status != FFI_OK) {
      XFREE(out_args_info);
      if(status != FFI_OK) rubinius::bug("ffi_prep_cif failed");
    }

    state->shared().om->add_code_resource(data);
    this->ffi_data = data;
  }

  /* The main interface function, handles looking up the pointer in the library,
   * generating the stub, wrapping it up and attaching it to the module.
   */
  NativeFunction* NativeFunction::generate(STATE, Pointer* ptr, Symbol* name,
                                           Array* args, Object* ret)
  {
    int i, tot, arg_count;
    Object* type;
    FFIArgInfo ret_info;
    FFIArgInfo* args_info;

    tot = args->size();
    arg_count = tot;

    NativeFunction* cb = 0;

    if(tot > 0) {
      args_info = ALLOC_N(FFIArgInfo, tot);

      for(i = 0; i < tot; i++) {
        type = args->get(state, i);
        if(type->fixnum_p()) {
          args_info[i].type = as<Integer>(type)->to_native();
          args_info[i].enum_obj = NULL;
          args_info[i].callback = NULL;

          /* State can only be passed as the first arg, and it's invisible,
             ie doesn't get seen as in onbound arg by ruby. But it can ONLY
             be the first arg. */
          if(args_info[i].type == RBX_FFI_TYPE_STATE) {
            if(i == 0) {
              arg_count--;
            } else {
              XFREE(args_info);
              return (NativeFunction*)Primitives::failure();
            }
          }
        } else if((cb = try_as<NativeFunction>(type))) {
          args_info[i].type = RBX_FFI_TYPE_CALLBACK;
          args_info[i].enum_obj = NULL;
          args_info[i].callback = cb;
        } else if(CBOOL(type->respond_to(state, state->symbol("[]"), cTrue))) {
          args_info[i].type = RBX_FFI_TYPE_ENUM;
          args_info[i].enum_obj = type;
          args_info[i].callback = NULL;
        } else {
          XFREE(args_info);
          return (NativeFunction*)Primitives::failure();
        }
      }
    } else {
      args_info = NULL;
    }

    if(ret->fixnum_p()) {
      ret_info.type = as<Integer>(ret)->to_native();
      ret_info.enum_obj = NULL;
      ret_info.callback = NULL;
    } else if((cb = try_as<NativeFunction>(ret))) {
      ret_info.type = RBX_FFI_TYPE_CALLBACK;
      ret_info.enum_obj = NULL;
      ret_info.callback = cb;
    } else if(CBOOL(ret->respond_to(state, state->symbol("symbol"), cTrue))) {
      ret_info.type = RBX_FFI_TYPE_ENUM;
      ret_info.enum_obj = ret;
      ret_info.callback = NULL;
    } else {
      XFREE(args_info);
      return (NativeFunction*)Primitives::failure();
    }

    NativeFunction* func = NativeFunction::create(state, name, arg_count);
    func->prep(state, tot, args_info, &ret_info);
    func->ffi_data->ep = ptr->pointer;

    if(args_info) XFREE(args_info);

    return func;
  }

  static void invoke_callback(ffi_cif* cif, void* retval,
                              void** parameters, void* user_data) {
    NativeMethodEnvironment* env = NativeMethodEnvironment::get();
    FFIData* stub =
      reinterpret_cast<FFIData*>(user_data);

    GCTokenImpl gct;
    State* state = env->state();

    state->gc_dependent();

    Array* args = Array::create(state, stub->arg_count);

    for(size_t i = 0; i < stub->arg_count; i++) {
      switch(stub->args_info[i].type) {
      case RBX_FFI_TYPE_CHAR:
        args->set(state, i, Fixnum::from(*(int8_t*)parameters[i]));
        break;
      case RBX_FFI_TYPE_UCHAR:
        args->set(state, i, Fixnum::from(*(uint8_t*)parameters[i]));
        break;
      case RBX_FFI_TYPE_BOOL:
        args->set(state, i, (*(uint8_t*)parameters[i]) ? cTrue : cFalse);
        break;
      case RBX_FFI_TYPE_SHORT:
        args->set(state, i, Fixnum::from(*(int16_t*)parameters[i]));
        break;
      case RBX_FFI_TYPE_USHORT:
        args->set(state, i, Fixnum::from(*(uint16_t*)parameters[i]));
        break;
      case RBX_FFI_TYPE_INT:
        args->set(state, i, Fixnum::from(*(int*)parameters[i]));
        break;
      case RBX_FFI_TYPE_UINT:
        args->set(state, i, Fixnum::from(*(unsigned int*)parameters[i]));
        break;
      case RBX_FFI_TYPE_LONG:
        args->set(state, i, Fixnum::from(*(long*)parameters[i]));
        break;
      case RBX_FFI_TYPE_ULONG:
        args->set(state, i, Fixnum::from(*(unsigned long*)parameters[i]));
        break;
      case RBX_FFI_TYPE_FLOAT:
        args->set(state, i, Float::create(state, *(float*)parameters[i]));
        break;
      case RBX_FFI_TYPE_DOUBLE:
        args->set(state, i, Float::create(state, *(double*)parameters[i]));
        break;
      case RBX_FFI_TYPE_LONG_LONG:
        args->set(state, i, Fixnum::from(*(long long*)parameters[i]));
        break;
      case RBX_FFI_TYPE_ULONG_LONG:
        args->set(state, i, Fixnum::from(*(unsigned long long*)parameters[i]));
        break;
      case RBX_FFI_TYPE_OBJECT:
        args->set(state, i, *(Object**)parameters[i]);
        break;
      case RBX_FFI_TYPE_ENUM:{
        Array* ary = Array::create(state, 1);
        ary->set(state, 0, Fixnum::from(*(int*)parameters[i]));
        args->set(state, i, stub->args_info[i].enum_obj->send(state, env->current_call_frame(), state->symbol("symbol"), ary) );
        break;
      }
      case RBX_FFI_TYPE_CALLBACK: {
        void* ptr = *(void**)parameters[i];
        if(ptr) {
          NativeFunction* orig = stub->args_info[i].callback;
          NativeFunction* func = NativeFunction::create(state, state->symbol("ffi_tramp"), orig->ffi_data->arg_count);
          func->prep(state, orig->ffi_data->arg_count, orig->ffi_data->args_info, &orig->ffi_data->ret_info);
          func->ffi_data->ep = ptr;
          Proc* prc = Proc::create(state, state->vm()->shared.globals.proc.get());
          prc->bound_method(state, func);
          args->set(state, i, prc);
        } else {
          args->set(state, i, Pointer::create(state,cNil));
        }
        break;
      }
      case RBX_FFI_TYPE_PTR: {
        void* ptr = *(void**)parameters[i];
        args->set(state, i, Pointer::create(state,
              ptr ? Pointer::create(state, ptr) : cNil));
        break;
      }
      case RBX_FFI_TYPE_STRING: {
        char* ptr = *(char**)parameters[i];
        Object* obj = cNil;
        if(ptr) {
          obj = String::create(state, ptr);
          obj->taint(state);
        }

        args->set(state, i, obj);
        break;
      }
      case RBX_FFI_TYPE_STRPTR: {
        char* result = *(char**)parameters[i];
        Object* s;
        Object* p;

        if(result == NULL) {
          s = p = cNil;
        } else {
          s = String::create(state, result);
          s->taint(state);
          p = Pointer::create(state, result);
        }

        Array* ary = Array::create(state, 2);
        ary->set(state, 0, s);
        ary->set(state, 1, p);

        args->set(state, i, ary);
        break;
      }
      default:
      case RBX_FFI_TYPE_VOID:
        args->set(state, i, cNil);
        break;
      }
    }

    Object* obj = stub->callable->send(state, env->current_call_frame(),
                                       state->symbol("call"), args);

    // Ug. An exception is being raised...
    if(!obj) {
      // For now, print out a warning to stderr and just eat it.
      std::cerr << "[WARNING] Exception raised by callback, ignoring.\n";
      state->vm()->thread_state()->clear();
      obj = cNil;
    }

    switch(stub->ret_info.type) {
    case RBX_FFI_TYPE_CHAR:
    case RBX_FFI_TYPE_SHORT:
    case RBX_FFI_TYPE_INT:
    case RBX_FFI_TYPE_LONG:
      if(Integer* io = try_as<Integer>(obj)) {
        *((ffi_sarg*)retval) = io->to_native();
      } else {
        *((ffi_sarg*)retval) = 0;
      }
      break;
    case RBX_FFI_TYPE_UCHAR:
    case RBX_FFI_TYPE_USHORT:
    case RBX_FFI_TYPE_UINT:
    case RBX_FFI_TYPE_ULONG:
      if(Integer* io = try_as<Integer>(obj)) {
        *((ffi_arg*)retval) = io->to_native();
      } else {
        *((ffi_arg*)retval) = 0;
      }
      break;
    case RBX_FFI_TYPE_BOOL:
      if(CBOOL(obj)) {
        *((ffi_arg*)retval) = 1;
      } else {
        *((ffi_arg*)retval) = 0;
      }
      break;
    case RBX_FFI_TYPE_FLOAT:
      if(Float* flt = try_as<Float>(obj)) {
        *((float*)retval) = flt->val;
      } else {
        *((float*)retval) = 0.0;
      }
      break;
    case RBX_FFI_TYPE_DOUBLE:
      if(Float* flt = try_as<Float>(obj)) {
        *((double*)retval) = flt->val;
      } else {
        *((double*)retval) = 0.0;
      }
      break;
    case RBX_FFI_TYPE_LONG_LONG:
      if(Integer* io = try_as<Integer>(obj)) {
        *((ffi_sarg*)retval) = io->to_long_long();
      } else {
        *((ffi_sarg*)retval) = 0;
      }
      break;
    case RBX_FFI_TYPE_ULONG_LONG:
      if(Integer* io = try_as<Integer>(obj)) {
        *((ffi_arg*)retval) = io->to_ulong_long();
      } else {
        *((ffi_arg*)retval) = 0;
      }
      break;
    case RBX_FFI_TYPE_OBJECT:
      *((Object**)retval) = obj;
      break;
    case RBX_FFI_TYPE_PTR:
      if(Pointer* ptr = try_as<Pointer>(obj)) {
        *((void**)retval) = ptr->pointer;
      } else {
        *((void**)retval) = 0;
      }
      break;
    case RBX_FFI_TYPE_ENUM: {
      Array* ary = Array::create(state, 1);
      ary->set(state, 0, obj);
      Object* value = stub->ret_info.enum_obj->send(state, env->current_call_frame(), state->symbol("[]"), ary);
      if(value->nil_p()) {
        *((Object**)retval) = value;
      } else {
        *((ffi_sarg*)retval) = as<Integer>(value)->to_native();
      }
      break;
    }
    case RBX_FFI_TYPE_CALLBACK: {
      Pointer* ptr = NativeFunction::adjust_tramp(state, obj, stub->ret_info.callback);
      *((void**)retval) = ptr->pointer;
      break;
    }
    default:
    case RBX_FFI_TYPE_VOID:
      *((ffi_arg*)retval) = 0;
      break;
    }

    state->gc_independent(gct);
  }

  Array* NativeFunction::generate_tramp(STATE, Object* obj, Symbol* name,
                                        Array* args, Object* ret)
  {
    int i, tot;
    Object* type;
    FFIArgInfo ret_info;
    FFIArgInfo* args_info;

    tot = args->size();
    NativeFunction* cb = 0;

    if(tot > 0) {
      args_info = ALLOC_N(FFIArgInfo, tot);

      for(i = 0; i < tot; i++) {
        type = args->get(state, i);
        if(type->fixnum_p()) {
          args_info[i].type = as<Integer>(type)->to_native();
          args_info[i].enum_obj = NULL;
          args_info[i].callback = NULL;

          /* State can not be passed. */
          if(args_info[i].type == RBX_FFI_TYPE_STATE) {
            XFREE(args_info);
            return nil<Array>();
          }
        } else if((cb = try_as<NativeFunction>(type))) {
          args_info[i].type = RBX_FFI_TYPE_CALLBACK;
          args_info[i].enum_obj = NULL;
          args_info[i].callback = cb;
        } else if(CBOOL(type->respond_to(state, state->symbol("[]"), cTrue))) {
          args_info[i].type = RBX_FFI_TYPE_ENUM;
          args_info[i].enum_obj = type;
          args_info[i].callback = NULL;
        } else {
          XFREE(args_info);
          return nil<Array>();
        }
      }
    } else {
      args_info = NULL;
    }

    if(ret->fixnum_p()) {
      ret_info.type = as<Integer>(ret)->to_native();
      ret_info.enum_obj = NULL;
      ret_info.callback = NULL;
    } else if((cb = try_as<NativeFunction>(ret))) {
      ret_info.type = RBX_FFI_TYPE_CALLBACK;
      ret_info.enum_obj = NULL;
      ret_info.callback = cb;
    } else if(CBOOL(ret->respond_to(state, state->symbol("symbol"), cTrue))) {
      ret_info.type = RBX_FFI_TYPE_ENUM;
      ret_info.enum_obj = ret;
      ret_info.callback = NULL;
    } else {
      XFREE(args_info);
      return nil<Array>();
    }

    NativeFunction* func = NativeFunction::create(state, name, tot);
    func->prep(state, tot, args_info, &ret_info);

    func->ffi_data->callable = obj;

    int status = ffi_prep_closure_loc(func->ffi_data->closure, &func->ffi_data->cif,
        invoke_callback, func->ffi_data, func->ffi_data->ep);

    if(args_info) XFREE(args_info);
    if(status != FFI_OK) {
      return force_as<Array>(Primitives::failure());
    }

    Array* ary = Array::create(state, 2);
    ary->set(state, 0, func);
    ary->set(state, 1, Pointer::create(state, func->ffi_data->ep));

    return ary;
  }

  Pointer* NativeFunction::adjust_tramp(STATE, Object* obj, NativeFunction* orig) {
    Symbol* ffi_tramp = state->symbol("ffi_tramp");

    Object* existing = obj->get_ivar(state, ffi_tramp);
    if(NativeFunction* f = try_as<NativeFunction>(existing)) {
      return Pointer::create(state, f->ffi_data->ep);
    }

    NativeFunction* func = NativeFunction::create(state, ffi_tramp,
                             orig->ffi_data->arg_count);

    func->prep(state, orig->ffi_data->arg_count, orig->ffi_data->args_info,
               &orig->ffi_data->ret_info);

    func->ffi_data->callable = obj;

    int status = ffi_prep_closure_loc(func->ffi_data->closure, &func->ffi_data->cif,
        invoke_callback, func->ffi_data, func->ffi_data->ep);

    if(status != FFI_OK) {
      return nil<Pointer>();
    }

    obj->set_ivar(state, ffi_tramp, func);

    return Pointer::create(state, func->ffi_data->ep);
  }

  Object* NativeFunction::call(STATE, Arguments& args, CallFrame* call_frame)
  {
    Object* ret;
    Object* obj;
    GCTokenImpl gct;

    bool use_cb_block = false;

    if(args.total() != ffi_data->arg_count) {
      if(args.total() + 1 == ffi_data->arg_count &&
          args.block() && !args.block()->nil_p())
      {
        use_cb_block = true;
      } else {
        Exception* exc =
          Exception::make_argument_error(state, ffi_data->arg_count,
                                         args.total(), args.name());
        exc->locations(state, Location::from_call_stack(state, call_frame));
        state->raise_exception(exc);

        return NULL;
      }
    }

    // Because we call back into ruby to do conversions.
    RootBuffer vrf(state->vm()->root_buffers(), args.arguments(), args.total());

    void** values = ALLOCA_N(void*, ffi_data->arg_count);
    void** heap_allocations = ALLOCA_N(void*, ffi_data->arg_count);
    size_t i;

    for(i = 0; i < ffi_data->arg_count; i++) {
      heap_allocations[i] = NULL;

      switch(ffi_data->args_info[i].type) {
      case RBX_FFI_TYPE_CHAR: {
        char* tmp = ALLOCA(char);
        obj = args.get_argument(i);
        type_assert(state, obj, FixnumType, "converting to char");
        *tmp = (char)as<Fixnum>(obj)->to_native();
        values[i] = tmp;
        break;
      }
      case RBX_FFI_TYPE_UCHAR: {
        unsigned char* tmp = ALLOCA(unsigned char);
        obj = args.get_argument(i);
        type_assert(state, obj, FixnumType, "converting to uchar");
        *tmp = (unsigned char)as<Fixnum>(obj)->to_native();
        values[i] = tmp;
        break;
      }
      case RBX_FFI_TYPE_BOOL: {
        unsigned char* tmp = ALLOCA(unsigned char);
        obj = args.get_argument(i);
        *tmp = (unsigned char)CBOOL(obj);
        values[i] = tmp;
        break;
      }
      case RBX_FFI_TYPE_SHORT: {
        short* tmp = ALLOCA(short);
        obj = args.get_argument(i);
        type_assert(state, obj, FixnumType, "converting to short");
        *tmp = (short)as<Fixnum>(obj)->to_native();
        values[i] = tmp;
        break;
      }
      case RBX_FFI_TYPE_USHORT: {
        unsigned short* tmp = ALLOCA(unsigned short);
        obj = args.get_argument(i);
        type_assert(state, obj, FixnumType, "converting to ushort");
        *tmp = (unsigned short)as<Fixnum>(obj)->to_native();
        values[i] = tmp;
        break;
      }
      case RBX_FFI_TYPE_INT: {
        int* tmp = ALLOCA(int);
        obj = args.get_argument(i);
        if(obj->fixnum_p()) {
          *tmp = as<Fixnum>(obj)->to_int();
        } else {
          type_assert(state, obj, BignumType, "converting to int");
          *tmp = as<Bignum>(obj)->to_int();
        }
        values[i] = tmp;
        break;
      }
      case RBX_FFI_TYPE_UINT: {
        unsigned int* tmp = ALLOCA(unsigned int);
        obj = args.get_argument(i);
        if(obj->fixnum_p()) {
          *tmp = as<Fixnum>(obj)->to_uint();
        } else {
          type_assert(state, obj, BignumType, "converting to unsigned int");
          *tmp = as<Bignum>(obj)->to_uint();
        }
        values[i] = tmp;
        break;
      }
      case RBX_FFI_TYPE_LONG: {
        long* tmp = ALLOCA(long);
        obj = args.get_argument(i);
        if(obj->fixnum_p()) {
          *tmp = as<Fixnum>(obj)->to_long();
        } else {
          type_assert(state, obj, BignumType, "converting to long");
          *tmp = as<Bignum>(obj)->to_long();
        }
        values[i] = tmp;
        break;
      }
      case RBX_FFI_TYPE_ULONG: {
        unsigned long* tmp = ALLOCA(unsigned long);
        obj = args.get_argument(i);
        if(obj->fixnum_p()) {
          *tmp = as<Fixnum>(obj)->to_ulong();
        } else {
          type_assert(state, obj, BignumType, "converting to unsigned long");
          *tmp = as<Bignum>(obj)->to_ulong();
        }
        values[i] = tmp;
        break;
      }
      case RBX_FFI_TYPE_FLOAT: {
        float* tmp = ALLOCA(float);
        obj = args.get_argument(i);
        type_assert(state, obj, FloatType, "converting to float");
        *tmp = (float)as<Float>(obj)->to_double(state);
        values[i] = tmp;
        break;
      }
      case RBX_FFI_TYPE_DOUBLE: {
        double* tmp = ALLOCA(double);
        obj = args.get_argument(i);
        type_assert(state, obj, FloatType, "converting to double");
        *tmp = as<Float>(obj)->to_double(state);
        values[i] = tmp;
        break;
      }
      case RBX_FFI_TYPE_LONG_LONG: {
        long long* tmp = ALLOCA(long long);
        obj = args.get_argument(i);
        if(obj->fixnum_p()) {
          *tmp = as<Fixnum>(obj)->to_long_long();
        } else {
          type_assert(state, obj, BignumType, "converting to long long");
          *tmp = as<Bignum>(obj)->to_long_long();
        }
        values[i] = tmp;
        break;
      }
      case RBX_FFI_TYPE_ULONG_LONG: {
        unsigned long long* tmp = ALLOCA(unsigned long long);
        obj = args.get_argument(i);
        if(obj->fixnum_p()) {
          *tmp = as<Fixnum>(obj)->to_ulong_long();
        } else {
          type_assert(state, obj, BignumType, "converting to unsigned long long");
          *tmp = as<Bignum>(obj)->to_ulong_long();
        }
        values[i] = tmp;
        break;
      }
      case RBX_FFI_TYPE_STATE: {
        VM** tmp = ALLOCA(VM*);
        *tmp = state->vm();
        values[i] = tmp;
        break;
      }
      case RBX_FFI_TYPE_OBJECT: {
        Object** tmp = ALLOCA(Object*);
        obj = args.get_argument(i);
        *tmp = obj;
        values[i] = tmp;
        break;
      }
      case RBX_FFI_TYPE_PTR: {
        void** tmp = ALLOCA(void*);
        obj = args.get_argument(i);
        if(obj->nil_p()) {
          *tmp = NULL;
        } else {
          Pointer* mp = try_as<Pointer>(obj);
          if(!mp) {
            if(String* so = try_as<String>(obj)) {
              int size;
              size = so->byte_size();

              char* data = ALLOCA_N(char, size + 1);
              memcpy(data, so->byte_address(), size);
              data[size] = 0;
              *tmp = data;
            } else if(CBOOL(obj->respond_to(state, state->symbol("to_ptr"), cTrue))) {
              Object* o2 = obj->send(state, call_frame, state->symbol("to_ptr"));
              type_assert(state, o2, PointerType, "converting to pointer");
              mp = as<Pointer>(o2);
              *tmp = mp->pointer;
            } else {
              type_assert(state, obj, PointerType, "converting to pointer");
            }
          } else {
            *tmp = mp->pointer;
          }
        }
        values[i] = tmp;
        break;
      }
      case RBX_FFI_TYPE_ENUM: {
        int* tmp = ALLOCA(int);
        obj = args.get_argument(i);
        if(obj->fixnum_p()) {
          *tmp = as<Fixnum>(obj)->to_int();
        } else {
          Array* ary = Array::create(state, 1);
          ary->set(state, 0, obj);
          Object* val = ffi_data->args_info[i].enum_obj->send(state, call_frame, state->symbol("[]"), ary);
          if(val->nil_p()) {
            *tmp = 0;
          } else {
            if(val->fixnum_p()) {
              *tmp = as<Fixnum>(val)->to_int();
            } else {
              type_assert(state, val, BignumType, "converting to int");
              *tmp = as<Bignum>(val)->to_int();
            }
          }
        }
        values[i] = tmp;
        break;
      }
      case RBX_FFI_TYPE_CALLBACK: {
        void** tmp = ALLOCA(void*);
        if(use_cb_block) {
          obj = args.block();
        } else {
          obj = args.get_argument(i);
        }
        if(obj->reference_p()) {
          Pointer* ptr = NativeFunction::adjust_tramp(state, obj, ffi_data->args_info[i].callback);
          *tmp = ptr->pointer;
        } else {
          *tmp = NULL;
        }
        values[i] = tmp;
        break;
      }
      case RBX_FFI_TYPE_STRING: {
        char** tmp = ALLOCA(char*);
        obj = args.get_argument(i);

        if(obj->nil_p()) {
          *tmp = NULL;
        } else {
          int size;
          String* so;

          so = as<String>(obj);
          size = so->byte_size();

          char* data = (char *)malloc(sizeof(char) * (size + 1));

          if (!data) {
            rubinius::bug("could not allocate memory for string");
          }

          memcpy(data, so->byte_address(), size);
          data[size] = 0;

          heap_allocations[i] = data;
          *tmp = data;
        }
        values[i] = tmp;
        break;
      }
      }
    }

    NativeMethodEnvironment* env = NativeMethodEnvironment::get();
    CallFrame* saved_frame = env->current_call_frame();
    env->set_current_call_frame(call_frame);

    state->set_call_frame(call_frame);

    // Make sure we have this on the stack
    NativeFunction* self = this;
    OnStack<1> on(state, self);

    // We need to have ffi_data on the stack since
    // a GC might move this and there ffi_data will
    // point at the wrong place in memory
    FFIData* ffi_data_local = ffi_data;
    state->gc_independent(gct);

    switch(ffi_data_local->ret_info.type) {
    case RBX_FFI_TYPE_CHAR: {
      ffi_arg result;
      ffi_call(&ffi_data_local->cif, FFI_FN(ffi_data_local->ep), &result, values);
      state->gc_dependent();
      ret = Fixnum::from((native_int)result);
      break;
    }
    case RBX_FFI_TYPE_UCHAR: {
      ffi_arg result;
      ffi_call(&ffi_data_local->cif, FFI_FN(ffi_data_local->ep), &result, values);
      state->gc_dependent();
      ret = Fixnum::from((native_int)result);
      break;
    }
    case RBX_FFI_TYPE_BOOL: {
      ffi_arg result;
      ffi_call(&ffi_data_local->cif, FFI_FN(ffi_data_local->ep), &result, values);
      state->gc_dependent();
      ret = (result != 0) ? cTrue : cFalse;
      break;
    }
    case RBX_FFI_TYPE_SHORT: {
      ffi_arg result;
      ffi_call(&ffi_data_local->cif, FFI_FN(ffi_data_local->ep), &result, values);
      state->gc_dependent();
      ret = Fixnum::from((native_int)result);
      break;
    }
    case RBX_FFI_TYPE_USHORT: {
      ffi_arg result;
      ffi_call(&ffi_data_local->cif, FFI_FN(ffi_data_local->ep), &result, values);
      state->gc_dependent();
      ret = Fixnum::from((native_int)result);
      break;
    }
    case RBX_FFI_TYPE_INT: {
      ffi_arg result;
      ffi_call(&ffi_data_local->cif, FFI_FN(ffi_data_local->ep), &result, values);
      state->gc_dependent();
      ret = Integer::from(state, (native_int)result);
      break;
    }
    case RBX_FFI_TYPE_UINT: {
      ffi_arg result;
      ffi_call(&ffi_data_local->cif, FFI_FN(ffi_data_local->ep), &result, values);
      state->gc_dependent();
      ret = Integer::from(state, (unsigned int)result);
      break;
    }
    case RBX_FFI_TYPE_LONG: {
      long result;
      ffi_call(&ffi_data_local->cif, FFI_FN(ffi_data_local->ep), &result, values);
      state->gc_dependent();
      ret = Integer::from(state, result);
      break;
    }
    case RBX_FFI_TYPE_ULONG: {
      unsigned long result;
      ffi_call(&ffi_data_local->cif, FFI_FN(ffi_data_local->ep), &result, values);
      state->gc_dependent();
      ret = Integer::from(state, result);
      break;
    }
    case RBX_FFI_TYPE_FLOAT: {
      float result;
      ffi_call(&ffi_data_local->cif, FFI_FN(ffi_data_local->ep), &result, values);
      state->gc_dependent();
      ret = Float::create(state, (double)result);
      break;
    }
    case RBX_FFI_TYPE_DOUBLE: {
      double result;
      ffi_call(&ffi_data_local->cif, FFI_FN(ffi_data_local->ep), &result, values);
      state->gc_dependent();
      ret = Float::create(state, result);
      break;
    }
    case RBX_FFI_TYPE_LONG_LONG: {
      long long result;
      ffi_call(&ffi_data_local->cif, FFI_FN(ffi_data_local->ep), &result, values);
      state->gc_dependent();
      ret = Integer::from(state, result);
      break;
    }
    case RBX_FFI_TYPE_ULONG_LONG: {
      unsigned long long result;
      ffi_call(&ffi_data_local->cif, FFI_FN(ffi_data_local->ep), &result, values);
      state->gc_dependent();
      ret = Integer::from(state, result);
      break;
    }
    case RBX_FFI_TYPE_OBJECT: {
      ffi_call(&ffi_data_local->cif, FFI_FN(ffi_data_local->ep), &ret, values);
      state->gc_dependent();
      break;
    }
    case RBX_FFI_TYPE_PTR: {
      void* result;
      ffi_call(&ffi_data_local->cif, FFI_FN(ffi_data_local->ep), &result, values);
      state->gc_dependent();
      if(result == NULL) {
        ret = cNil;
      } else {
        ret = Pointer::create(state, result);
      }
      break;
    }
    case RBX_FFI_TYPE_ENUM: {
      ffi_arg result;
      ffi_call(&ffi_data_local->cif, FFI_FN(ffi_data_local->ep), &result, values);
      state->gc_dependent();
      Array* ary = Array::create(state, 1);
      ary->set(state, 0, Integer::from(state, (native_int)result));
      ret = ffi_data->ret_info.enum_obj->send(state, call_frame, state->symbol("symbol"), ary);
      break;
    }
    case RBX_FFI_TYPE_CALLBACK: {
      void* result;
      ffi_call(&ffi_data_local->cif, FFI_FN(ffi_data_local->ep), &result, values);
      state->gc_dependent();
      if(result == NULL) {
        ret = cNil;
      } else {
        NativeFunction* orig = ffi_data_local->ret_info.callback;
        NativeFunction* func = NativeFunction::create(state, state->symbol("ffi_tramp"), orig->ffi_data->arg_count);
        func->prep(state, orig->ffi_data->arg_count, orig->ffi_data->args_info, &orig->ffi_data->ret_info);
        func->ffi_data->ep = result;
        Proc* prc = Proc::create(state, state->vm()->shared.globals.proc.get());
        prc->bound_method(state, func);
        ret = (Object*)prc;
      }
      break;
    }
    case RBX_FFI_TYPE_STRING: {
      char* result;
      ffi_call(&ffi_data_local->cif, FFI_FN(ffi_data_local->ep), &result, values);
      state->gc_dependent();
      if(result == NULL) {
        ret = cNil;
      } else {
        ret = String::create(state, result);
        ret->taint(state);
      }
      break;
    }
    case RBX_FFI_TYPE_STRPTR: {
      char* result;
      Object* s;
      Object* p;

      ffi_call(&ffi_data_local->cif, FFI_FN(ffi_data_local->ep), &result, values);
      state->gc_dependent();

      if(result == NULL) {
        s = p = cNil;
      } else {
        s = String::create(state, result);
        s->taint(state);
        p = Pointer::create(state, result);
      }

      Array* ary = Array::create(state, 2);
      ary->set(state, 0, s);
      ary->set(state, 1, p);
      ret = ary;
      break;
    }
    default:
    case RBX_FFI_TYPE_VOID: {
      ffi_arg result;
      ffi_call(&ffi_data_local->cif, FFI_FN(ffi_data_local->ep), &result, values);
      state->gc_dependent();
      ret = cNil;
      break;
    }
    }

    env->set_current_call_frame(saved_frame);

    for(i = 0; i < ffi_data_local->arg_count; i++) {
      if (heap_allocations[i]) {
        free(heap_allocations[i]);
      }
    }

    return ret;
  }

  void NativeFunction::Info::mark(Object* obj, ObjectMark& mark) {
    auto_mark(obj, mark);
    mark_inliners(obj, mark);

    NativeFunction* func = force_as<NativeFunction>(obj);

    if(func->ffi_data) {
      func->ffi_data->set_mark();

      if(func->ffi_data->callable) {
        Object* tmp = mark.call(func->ffi_data->callable);
        if(tmp) {
          func->ffi_data->callable = tmp;
          mark.just_set(obj, tmp);
        }
      }
      for(size_t i = 0; i<func->ffi_data->arg_count; i++) {
        FFIArgInfo* arg = &func->ffi_data->args_info[i];
        if(arg->callback) {
          Object* tmp = mark.call(arg->callback);
          if(tmp) {
            arg->callback = force_as<NativeFunction>(tmp);
            mark.just_set(obj, tmp);
          }
        }
        if(arg->enum_obj) {
          Object* tmp = mark.call(arg->enum_obj);
          if(tmp) {
            arg->enum_obj = tmp;
            mark.just_set(obj, tmp);
          }
        }
      }
      FFIArgInfo* arg = &func->ffi_data->ret_info;
      if(arg->callback) {
        Object* tmp = mark.call(arg->callback);
        if(tmp) {
          arg->callback = force_as<NativeFunction>(tmp);
          mark.just_set(obj, tmp);
        }
      }
      if(arg->enum_obj) {
        Object* tmp = mark.call(arg->enum_obj);
        if(tmp) {
          arg->enum_obj = tmp;
          mark.just_set(obj, tmp);
        }
      }
      func->ffi_data->function = func;
    }
  }

}


text:
(function() {
  var method;
  var noop = function () {};
  var methods = [
    'assert', 'clear', 'count', 'debug', 'dir', 'dirxml', 'error',
    'exception', 'group', 'groupCollapsed', 'groupEnd', 'info', 'log',
    'markTimeline', 'profile', 'profileEnd', 'table', 'time', 'timeEnd',
    'timeline', 'timelineEnd', 'timeStamp', 'trace', 'warn'
  ];
  var length = methods.length;
  var console = (window.console = window.console || {});

  while (length--) {
    method = methods[length];

    // Only stub undefined methods.
    if (!console[method]) {
      console[method] = noop;
    }
  }
}());

// Place any jQuery/helper plugins in here.

// Check if element exists
// Should use when query dom
jQuery.fn.doOnce = function(func) {
  this.length && func.apply(this);

  return this;
};


text:
package com.github.haixing_hu.text.tostring;

import javax.annotation.concurrent.Immutable;

/**
 * The default {@code toString()} style.
 *

 * Using the {@code Person} example from {@link ToStringBuilder}, the
 * output would look like this:
 *

 *
 *

 * Person@182f0db[name=John Doe,age=33,smoker=false]
 *

 *
 * @author Haixing Hu
 */
@Immutable
public final class DefaultToStringStyle extends ToStringStyle {

  private static final long serialVersionUID = - 2169892717080992996L;

  public static final DefaultToStringStyle INSTANCE = new DefaultToStringStyle();

  public DefaultToStringStyle() {
    super();
  }

  @Override
  public String toString() {
    return "DefaultToStringStyle";
  }
}


text:
require "rubygems"
require "bundler/setup"

require_relative '../exif_thing'
require "test/unit"

# DIRECTORY = "sample_data/DCIM/102_VIRB"

class ExifThingTest < Test::Unit::TestCase
	def test_nothing
		assert_true(true)
	end

	def test_get_data
		origin = DIRECTORY
		photos_array = Dir.glob(File.join(origin, '*.jpg'))
		photos_array.each_with_index do |photopath, index|
			puts photopath
			data = Exif::Data.new(IO.read(photopath))   # load from string
			date_time = data.date_time
			puts date_time
			date_time.sub!(':', '-')
			date_time.sub!(':', '-')
			timezone = Time.now.strftime('%z')
			puts "Timezone is #{timezone}"
			puts Time.parse("#{date_time} #{timezone}")
		end

	end

end


text:
// Copyright 2013 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

/*
This file contains the code to check for useless function comparisons.
A useless comparison is one like f == nil as opposed to f() == nil.
*/

package main

import (
	"go/ast"
	"go/token"

	"github.com/chenjianlong/go.tools/go/types"
)

func init() {
	register("nilfunc",
		"check for comparisons between functions and nil",
		checkNilFuncComparison,
		binaryExpr)
}

func checkNilFuncComparison(f *File, node ast.Node) {
	e := node.(*ast.BinaryExpr)

	// Only want == or != comparisons.
	if e.Op != token.EQL && e.Op != token.NEQ {
		return
	}

	// Only want comparisons with a nil identifier on one side.
	var e2 ast.Expr
	switch {
	case f.isNil(e.X):
		e2 = e.Y
	case f.isNil(e.Y):
		e2 = e.X
	default:
		return
	}

	// Only want identifiers or selector expressions.
	var obj types.Object
	switch v := e2.(type) {
	case *ast.Ident:
		obj = f.pkg.uses[v]
	case *ast.SelectorExpr:
		obj = f.pkg.uses[v.Sel]
	default:
		return
	}

	// Only want functions.
	if _, ok := obj.(*types.Func); !ok {
		return
	}

	f.Badf(e.Pos(), "comparison of function %v %v nil is always %v", obj.Name(), e.Op, e.Op == token.NEQ)
}

// isNil reports whether the provided expression is the built-in nil
// identifier.
func (f *File) isNil(e ast.Expr) bool {
	return f.pkg.types[e].Type == types.Typ[types.UntypedNil]
}


text:
package org.jspare.server.jetty;

import static org.jspare.core.container.Environment.CONFIG;

import java.net.URI;
import java.util.Optional;
import java.util.concurrent.ThreadFactory;

import javax.ws.rs.ProcessingException;

import org.eclipse.jetty.server.Connector;
import org.eclipse.jetty.server.HttpConfiguration;
import org.eclipse.jetty.server.HttpConnectionFactory;
import org.eclipse.jetty.server.SecureRequestCustomizer;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.ServerConnector;
import org.eclipse.jetty.server.SslConnectionFactory;
import org.eclipse.jetty.util.ssl.SslContextFactory;
import org.eclipse.jetty.util.thread.QueuedThreadPool;
import org.glassfish.jersey.jetty.JettyHttpContainer;
import org.glassfish.jersey.jetty.internal.LocalizationMessages;
import org.glassfish.jersey.process.JerseyProcessingUncaughtExceptionHandler;
import org.glassfish.jersey.server.ContainerFactory;
import org.glassfish.jersey.server.ResourceConfig;
import org.glassfish.jersey.server.spi.Container;
import org.jspare.server.jetty.commons.JettyDefinitions;

import jersey.repackaged.com.google.common.util.concurrent.ThreadFactoryBuilder;

/**
 * A factory for creating JettyServerEngine objects.
 */
public final class JettyServerEngineFactory {

	/**
	 * The Class JettyConnectorThreadPool.
	 *
	 * @author pflima
	 * @since 30/03/2016
	 */
	private static final class JettyConnectorThreadPool extends QueuedThreadPool {

		/** The thread factory. */
		private final ThreadFactory threadFactory = new ThreadFactoryBuilder().setNameFormat("jetty-http-server-%d")
				.setUncaughtExceptionHandler(new JerseyProcessingUncaughtExceptionHandler()).build();

		/**
		 * Instantiates a new jetty connector thread pool.
		 */
		public JettyConnectorThreadPool() {

			setName("jspare-server-thread");
			setMinThreads(Integer
					.valueOf(CONFIG.get(JettyDefinitions.SERVER_MIN_POOL_THREADS_KEY, JettyDefinitions.SERVER_MIN_POOL_THREADS_DEFAULT)));
			setMaxThreads(Integer
					.valueOf(CONFIG.get(JettyDefinitions.SERVER_MAX_POOL_THREADS_KEY, JettyDefinitions.SERVER_MAX_POOL_THREADS_DEFAULT)));
			setDaemon(Boolean.valueOf(CONFIG.get(JettyDefinitions.SERVER_DAEMON_KEY, Boolean.FALSE)));
			setDetailedDump(true);
		}

		/*
		 * (non-Javadoc)
		 *
		 * @see
		 * org.eclipse.jetty.util.thread.QueuedThreadPool#newThread(java.lang.
		 * Runnable)
		 */
		@Override
		protected Thread newThread(Runnable runnable) {
			return threadFactory.newThread(runnable);
		}
	}

	/**
	 * Creates a new JettyServerEngine object.
	 *
	 * @param uri
	 *            the uri
	 * @param resourceConfig
	 *            the resource config
	 * @param sslContextFactory
	 *            the ssl context factory
	 * @param start
	 *            the start
	 * @return the server
	 */
	public static Server createServer(final URI uri, final ResourceConfig resourceConfig,
			final Optional<SslContextFactory> sslContextFactory, boolean start) {

		final JettyHttpContainer handler = ContainerFactory.createContainer(JettyHttpContainer.class, resourceConfig);

		if (uri == null) {
			throw new IllegalArgumentException(LocalizationMessages.URI_CANNOT_BE_NULL());
		}
		final String scheme = uri.getScheme();
		int defaultPort = Container.DEFAULT_HTTP_PORT;

		if (!sslContextFactory.isPresent()) {
			if (!"http".equalsIgnoreCase(scheme)) {
				throw new IllegalArgumentException(LocalizationMessages.WRONG_SCHEME_WHEN_USING_HTTP());
			}
		} else {
			if (!"https".equalsIgnoreCase(scheme)) {
				throw new IllegalArgumentException(LocalizationMessages.WRONG_SCHEME_WHEN_USING_HTTPS());
			}
			defaultPort = Container.DEFAULT_HTTPS_PORT;
		}
		final int port = (uri.getPort() == -1) ? defaultPort : uri.getPort();

		final Server server = new Server(new JettyConnectorThreadPool());
		final HttpConfiguration config = new HttpConfiguration();

		if (sslContextFactory.isPresent()) {
			config.setSecureScheme("https");
			config.setSecurePort(port);
			config.addCustomizer(new SecureRequestCustomizer());

			final ServerConnector https = new ServerConnector(server, new SslConnectionFactory(sslContextFactory.get(), "http/1.1"),
					new HttpConnectionFactory(config));
			https.setPort(port);
			server.setConnectors(new Connector[] { https });

		} else {
			final ServerConnector http = new ServerConnector(server, new HttpConnectionFactory(config));
			http.setPort(port);
			server.setConnectors(new Connector[] { http });
		}
		if (handler != null) {
			server.setHandler(handler);
		}

		if (start) {
			try {
				// Start the server.
				server.start();
			} catch (final Exception e) {
				throw new ProcessingException(LocalizationMessages.ERROR_WHEN_CREATING_SERVER(), e);
			}
		}
		return server;
	}

	/**
	 * Instantiates a new jetty server engine factory.
	 */
	private JettyServerEngineFactory() {
	}
}


text:
There are two ways to quit out of an Interactive Elixir shell. The standard
way is with `Ctrl-c`. This gives you a list of options, one of which is `a`
for _abort_. This will terminate your IEx session and drop you back on the
command line where the process started.

Additionally, IEx also understands `Ctrl-\` which is control key that will
terminate just about any interactive environment. This command will cause
IEx to immediately exit with no prompt.

Note: IEx does not, however, respond to `Ctrl-d`.

[source](http://blog.plataformatec.com.br/2016/03/how-to-quit-the-elixir-shell-iex/)


text:
import httplib
import urllib
from Tkinter import *
import tkFileDialog

module = euzernaem = parsewerd = destination = ''

def getContents():
    global module, euzernaem, parsewerd
    conn = httplib.HTTPSConnection('libbrs.nus.edu.sg')
    page = '/infogate/loginAction.do?execution=login'
    conn.request('GET', page)

    resp = conn.getresponse()
    conn.close()
    cookie = resp.getheader('Set-Cookie')
    sessionid = cookie[:cookie.find(';')]
    cookie = sessionid
    print(cookie)

    headers = {
        "Content-Type" : "application/x-www-form-urlencoded",
        "Cookie" : cookie
    }
    headersGet = {
        "Cookie" : cookie
    }

    params = 'userid='+euzernaem+'&password='+parsewerd+'&domain=NUSSTU&key=blankid%2BRESULT%2BEXAM%2B'+module

    conn = httplib.HTTPSConnection('libbrs.nus.edu.sg')
    conn.request("POST", page, params, headers)
    resp = conn.getresponse()
    data = str(resp.read())
    conn.close()

    conn = httplib.HTTPConnection('libbrs.nus.edu.sg:8080')
    page = '/infogate/jsp/login/success.jsp;jsessionid='+sessionid+'?exe=ResultList'
    conn.request("GET", page, params, headersGet)
    conn.close()

    conn = httplib.HTTPConnection('libbrs.nus.edu.sg:8080')
    page = '/infogate/searchAction.do?execution=ResultList'
    params = 'database=EXAM&searchstring='+module+'&d='
    conn.request("POST", page, params, headers)
    resp = conn.getresponse()
    data = resp.read()
    conn.close()

    data = str(data)
    downloadall(data, headers, headersGet)

def printNice(params):
    for key in params:
        print(str(key) + ' = ' + str(params[key]))

def downloadall(data, headers, headersGet):
    params = getParams(data)
    maxDocIndex = int(params['maxNo'])
    params['maxDocIndex'] = params['maxNo']

    for i in range(1,maxDocIndex+1):
        conn = httplib.HTTPConnection('libbrs.nus.edu.sg:8080')
        page = '/infogate/searchAction.do?execution=ViewSelectedResultListLong'
        params['preSelectedId'] = i
        params['exportids'] = i
        conn.request("POST", page, urllib.urlencode(params), headers)
        resp = conn.getresponse()
        data = resp.read()
        conn.close()
        data = str(data)

        pdfIndex = data.find('View attached PDF file')
        if pdfIndex == -1:
            continue
        pdfIndex = data.rfind('href=', 0, pdfIndex)
        openquotes = data.find('"', pdfIndex)
        closequotes = data.find('"', openquotes+1)
        page = page[:page.rfind('/')+1] + data[openquotes+1:closequotes]

        titleIndex = data.find('title=', pdfIndex)
        if titleIndex == -1:
            continue
        openquotes = data.find('"', titleIndex)
        closequotes = data.find('"', openquotes+1)
        title = data[openquotes+1: closequotes]

        conn = httplib.HTTPConnection('libbrs.nus.edu.sg:8080')
        conn.request("GET", page, None, headersGet)
        resp = conn.getresponse()
        data = resp.read()

        conn.close()

        title = title[title.find('file')+5:]
        print('Writing ' + title)
        f = open(destination + '/' + title, 'wb+')
        f.write(data)
        f.close()

    updateStatus("Done!", 'success')

def getParams(data):
    start = data.find('databasenamesasstring')
    start = data.rfind('<', 0, start)
    end = data.find('<select', start)

    params = {
        'databasenamesasstring' : 'Examination Papers Database',
        'searchid':'-6901505210342489183',
        'f':'list',
        'b':'1',
        'p':'1',
        'd':'EXAM',
        'u':'dummy',
        'r':'',
        'l':'20',
        'n':'',
        'nn':'',
        'historyid':'1',
        'maxDocIndex':'11',
        'preSelectedId':'1,', #id
        'maxNo':'11',
        'sPage1':'1',
        'pageNo1':'1',
        'exportids':'1', #id
        'maxNo':'11',
        'sPage2':'1',
        'pageNo2':'1',
        'paraid[0]':'PGH2',
        'parashortname[0]':'FACU',
        'paravalue[0]':'',
        'paraid[1]':'PGH3',
        'parashortname[1]':'SUBJ',
        'paravalue[1]':'',
        'paraid[2]':'PGH5',
        'parashortname[2]':'CNAM',
        'paravalue[2]':''
    }

    start = data.find('name=', start, end)
    while start != -1:
        openquotes = data.find('"', start, end)
        closequotes = data.find('"', openquotes+1, end)
        name = data[openquotes+1:closequotes]
        start = data.find('value=', start, end)
        openquotes = data.find('"', start, end)
        closequotes = data.find('"', openquotes+1, end)
        value = data[openquotes+1:closequotes]
        params[name] = value

        #print (name + ' ==> ' + value)
        start = data.find('name=', start, end)

    return params

def askForDestination():
    global destination, destField
    destination = tkFileDialog.askdirectory(mustexist=False, parent=top, title="Choose a destination")
    destField.delete(0)
    destField.insert(0, destination)

def startDownload():
    global module, euzernaem, parsewerd, destination
    module = moduleField.get()
    euzernaem = usernameField.get()
    parsewerd = passwordField.get()
    getContents()

def updateStatus(msg, type='normal'):
    global statusLabel
    statusLabel['text'] = msg
    if type == 'success':
        statusLabel['fg'] = 'green'
    elif type == 'error':
        statusLabel['fg'] = 'red'

root = Tk()
root.title("NUS Past Year Exam Paper Downloader")

top = Frame(root)
top.grid(row=0, column=0, padx=20, pady=20)
top.columnconfigure(0, weight=1)
top.rowconfigure(0, weight=1)

moduleLabel = Label(top, text="Module Code:")
moduleLabel.grid(row=1, column=0)
moduleField = Entry(top, bd=2, textvariable=module)
moduleField.grid(row=1, column=1, columnspan=2)

usernameLabel = Label(top, text="NUSNET ID:")
usernameLabel.grid(row=2, column=0)
usernameField = Entry(top, bd=2, textvariable=euzernaem)
usernameField.grid(row=2, column=1, columnspan=2)

passwordLabel = Label(top, text="Password:")
passwordLabel.grid(row=3, column=0)
passwordField = Entry(top, bd=2, show='*', textvariable=parsewerd)
passwordField.grid(row=3, column=1, columnspan=2)

destLabel = Label(top, text="Destination:")
destLabel.grid(row=4, column=0)
destField = Entry(top, bd=2, textvariable=destination)
destField.grid(row=4, column=1)
destButton = Button(top, text="...", command=askForDestination)
destButton.grid(row=4, column=2)

statusLabel = Label(top, text="^____^", justify=CENTER)
statusLabel.grid(row=5, columnspan=3)

startButton = Button(top, text="Start!", command=startDownload)
startButton.grid(row=6, columnspan=3)

root.mainloop()


text:
<?php
namespace Luracast\Restler\UI;

use ArrayAccess;
use Countable;
use Luracast\Restler\Util;

class Tags implements ArrayAccess, Countable
{
    public static $humanReadable = true;
    public static $initializer = null;
    protected static $instances = array();
    public $prefix = '';
    public $indent = '    ';
    public $tag;
    protected $attributes = array();
    protected $children = array();
    protected $_parent;

    public function __construct($name = null, array $children = array())
    {
        $this->tag = $name;
        $c = array();
        foreach ($children as $child) {
            is_array($child)
                ? $c = array_merge($c, $child)
                : $c [] = $child;
        }
        $this->markAsChildren($c);
        $this->children = $c;
        if (static::$initializer)
            call_user_func_array(static::$initializer, array(& $this));
    }

    /**
     * Get Tag by id
     *
     * Retrieve a tag by its id attribute
     *
     * @param string $id
     *
     * @return Tags|null
     */
    public static function byId($id)
    {
        return Util::nestedValue(static::$instances, $id);
    }

    /**
     * @param       $name
     * @param array $children
     *
     * @return Tags
     */
    public static function __callStatic($name, array $children)
    {
        return new static($name, $children);
    }

    public function toString($prefix = '', $indent = '    ')
    {
        $this->prefix = $prefix;
        $this->indent = $indent;
        return $this->__toString();
    }

    public function __toString()
    {
        $children = '';
        if (static::$humanReadable) {
            $lineBreak = false;
            foreach ($this->children as $key => $child) {
                $prefix = $this->prefix;
                if (!is_null($this->tag))
                    $prefix .= $this->indent;
                if ($child instanceof $this) {
                    $child->prefix = $prefix;
                    $child->indent = $this->indent;
                    $children .= PHP_EOL . $child;
                    $lineBreak = true;
                } else {
                    $children .= $child;
                }
            }
            if ($lineBreak)
                $children .= PHP_EOL . $this->prefix;
        } else {
            $children = implode('', $this->children);
        }
        if (is_null($this->tag))
            return $children;
        $attributes = '';
        foreach ($this->attributes as $attribute => &$value)
            $attributes .= " $attribute=\"$value\"";

        if (count($this->children))
            return static::$humanReadable
                ? "$this->prefix<{$this->tag}{$attributes}>"
                . "$children"
                . "</{$this->tag}>"
                : "<{$this->tag}{$attributes}>$children</{$this->tag}>";

        return "$this->prefix<{$this->tag}{$attributes}/>";
    }

    public function toArray()
    {
        $r = array();
        $r['attributes'] = $this->attributes;
        $r['tag'] = $this->tag;
        $children = array();
        foreach ($this->children as $key => $child) {
            $children[$key] = $child instanceof $this
                ? $child->toArray()
                : $child;
        }
        $r['children'] = $children;
        return $r;
    }

    /**
     * Set the id attribute of the current tag
     *
     * @param string $value
     *
     * @return string
     */
    public function id($value)
    {
        $this->attributes['id'] = isset($value)
            ? (string)$value
            : Util::nestedValue($this->attributes, 'name');
        static::$instances[$value] = $this;
        return $this;
    }

    public function __get($name)
    {
        if ('parent' == $name)
            return $this->_parent;
        if (isset($this->attributes[$name]))
            return $this->attributes[$name];
        return;
    }

    public function __set($name, $value)
    {
        if ('parent' == $name) {
            if ($this->_parent) {
                unset($this->_parent[array_search($this, $this->_parent->children)]);
            }
            if (!empty($value)) {
                $value[] = $this;
            }
        }
    }

    public function __isset($name)
    {
        return isset($this->attributes[$name]);
    }

    /**
     * @param $attribute
     * @param $value
     *
     * @return Tags
     */
    public function __call($attribute, $value)
    {
        if (is_null($value)) {
            return isset($this->attributes[$attribute])
                ? $this->attributes[$attribute]
                : null;
        }
        $value = $value[0];
        if (is_null($value)) {
            unset($this->attributes[$attribute]);
            return $this;
        }
        $this->attributes[$attribute] = is_bool($value)
            ? ($value ? 'true' : 'false')
            : @(string)$value;
        return $this;
    }

    public function offsetGet($index)
    {
        if ($this->offsetExists($index)) {
            return $this->children[$index];
        }
        return false;
    }

    public function offsetExists($index)
    {
        return isset($this->children[$index]);
    }

    public function offsetSet($index, $value)
    {
        if ($index) {
            $this->children[$index] = $value;
        } elseif (is_array($value)) {
            $c = array();
            foreach ($value as $child) {
                is_array($child)
                    ? $c = array_merge($c, $child)
                    : $c [] = $child;
            }
            $this->markAsChildren($c);
            $this->children += $c;
        } else {
            $c = array($value);
            $this->markAsChildren($c);
            $this->children[] = $value;
        }
        return true;
    }

    public function offsetUnset($index)
    {
        $this->children[$index]->_parent = null;
        unset($this->children[$index]);
        return true;
    }

    public function getContents()
    {
        return $this->children;
    }

    public function count()
    {
        return count($this->children);
    }

    private function markAsChildren(& $children)
    {
        foreach ($children as $i => $child) {
            if (is_string($child))
                continue;
            if (!is_object($child)) {
                unset($children[$i]);
                continue;
            }
            //echo $child;
            if (isset($child->_parent) && $child->_parent != $this) {
                //remove from current parent
                unset($child->_parent[array_search($child, $child->_parent->children)]);
            }
            $child->_parent = $this;
        }
    }
}


text:
<?php

namespace app\modules\admin\models\base;

use Yii;
use yii\behaviors\TimestampBehavior;

/**
 * This is the base model class for table "user".
 *
 * @property integer $id
 * @property string $username
 * @property string $auth_key
 * @property string $password_hash
 * @property string $password_reset_token
 * @property string $email
 * @property integer $status
 * @property string $created_at
 * @property string $updated_at
 */
class User extends \yii\db\ActiveRecord
{

    use \mootensai\relation\RelationTrait;

    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'user';
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'username' => 'Username',
            'auth_key' => 'Auth Key',
            'password_hash' => 'Password Hash',
            'password_reset_token' => 'Password Reset Token',
            'email' => 'Email',
            'status' => 'Status',
            'permission' => 'Permission',
            'position' => 'Position',
        ];
    }

/**
     * @inheritdoc
     * @return type mixed
     */
    public function behaviors()
    {
        return [
            [
                'class' => TimestampBehavior::className(),
                'createdAtAttribute' => 'created_at',
                'updatedAtAttribute' => 'updated_at',
                'value' => new \yii\db\Expression('NOW()'),
            ],
        ];
    }

    /**
     * @inheritdoc
     * @return \app\modules\admin\models\UserQuery the active query used by this AR class.
     */
    public static function find()
    {
        return new \app\modules\admin\models\UserQuery(get_called_class());
    }
}