text:
namespace Steamworks {
	[System.Serializable]
	public struct SteamLeaderboard_t : System.IEquatable<SteamLeaderboard_t>, System.IComparable<SteamLeaderboard_t> {
		public ulong m_SteamLeaderboard;

		public SteamLeaderboard_t(ulong value) {
			m_SteamLeaderboard = value;
		}

		public override string ToString() {
			return m_SteamLeaderboard.ToString();
		}

		public override bool Equals(object other) {
			return other is SteamLeaderboard_t && this == (SteamLeaderboard_t)other;
		}

		public override int GetHashCode() {
			return m_SteamLeaderboard.GetHashCode();
		}

		public static bool operator ==(SteamLeaderboard_t x, SteamLeaderboard_t y) {
			return x.m_SteamLeaderboard == y.m_SteamLeaderboard;
		}

		public static bool operator !=(SteamLeaderboard_t x, SteamLeaderboard_t y) {
			return !(x == y);
		}

		public static explicit operator SteamLeaderboard_t(ulong value) {
			return new SteamLeaderboard_t(value);
		}

		public static explicit operator ulong(SteamLeaderboard_t that) {
			return that.m_SteamLeaderboard;
		}

		public bool Equals(SteamLeaderboard_t other) {
			return m_SteamLeaderboard == other.m_SteamLeaderboard;
		}

		public int CompareTo(SteamLeaderboard_t other) {
			return m_SteamLeaderboard.CompareTo(other.m_SteamLeaderboard);
		}
	}
}

#endif // !DISABLESTEAMWORKS


text:
package edu.isi.wubble.physics.entity;

import com.jme.bounding.BoundingBox;
import com.jme.math.Vector3f;
import com.jme.renderer.ColorRGBA;
import com.jme.scene.Node;
import com.jme.scene.shape.Box;
import com.jmex.physics.DynamicPhysicsNode;

public class WubbleEntity extends ActiveEntity {

	protected ColorRGBA          _color;

	public WubbleEntity(EntityManager em, String name, boolean makeUnique) {
		super(em, name, makeUnique);

		_color = ColorRGBA.blue;
		_entityManager.addWubbleEntity(this);
		_entityManager.addUpdateEntity(this);
	}

	public String getEntityType() {
		return "wubble";
	}

	public ColorRGBA getColor() {
		return _color;
	}

	public void initWubbleEntity(Vector3f startPos) {
		createVisualNode();
		createPhysicsNode(startPos);

		Node parent = new Node(getName());
		parent.attachChild(_physicsNode);
		parent.attachChild(_visualNode);

		setNode(parent);
		setPhysicsNode(_physicsNode);
	}

	public void createVisualNode() {
		Box b = new Box(getName(), new Vector3f(0,0,0), 0.5f, 0.5f, 0.5f);
		b.setModelBound(new BoundingBox());

		_visualNode = new Node(getName());
		_visualNode.attachChild(b);
		_visualNode.setLocalScale(new Vector3f(0.25f, 0.25f, 0.25f));
		_visualNode.lookAt(new Vector3f(0,0,-1), new Vector3f(0,1,0));
	}

	public void createPhysicsNode(Vector3f startPos) {
		_physicsNode = _entityManager.getPhysicsSpace().createDynamicNode();
		getPhysicsNode().setName(getName());
		getPhysicsNode().createSphere(getName());
		getPhysicsNode().setLocalTranslation(startPos);
		getPhysicsNode().setLocalScale(new Vector3f(0.25f,0.25f,0.25f));
		getPhysicsNode().generatePhysicsGeometry();
		getPhysicsNode().computeMass();
	}
}

redpajama_set_name: RedPajamaGithub


text:
from predictor import Predictor

class BasicBiasPredictor(Predictor):
    def __init__(self, contributors):
        super(BasicBiasPredictor,self).__init__()
        self.contributors = contributors
        self.model = self.contributors.get_model()
        #self.user_delta_rates = {}

    def predict(self,user_id, item_id):
        ru  = self.model.get_user_rate_mean(user_id)
        nbs = self.contributors.get_neighbors(user_id,-1)
        nb_delta = self.get_delta(nbs, item_id)
        pref = ru+nb_delta
        return pref

    def get_delta(self,users,item_id):
        t_delta = 0
        t_sim = 0
        for u_id, sim in users:
            #sim = 1.0
            delta = self.get_one_delta(u_id,item_id)
            if delta is None:
                continue
            t_delta += float(delta)*float(sim)
            t_sim += sim

        if t_sim == 0:
            return 0.0
        r_d = float(t_delta)/float(t_sim)
        return r_d

    def get_one_delta(self,user_id,item_id):
        delta = None
        ru  = self.model.get_user_rate_mean(user_id)
        rate = self.model.get_rate(user_id,item_id)
        if not rate is None:
            ri, ts = rate
            delta = float(ri)-ru

        return delta


text:
class ScoreWeightCalculator::Weighted
  attr_reader :score_weights

  def initialize(score_weights)
    @score_weights = score_weights
    raise unless score_weights.sum == 100
  end

  def total(raw_scores)
    sum = 0
    raw_scores.each_with_index do |score, index|
      next if score_weights[index].nil?

      sum += score * score_weights[index]
    end
    (sum / 100.0).round(4)
  end
end


text:
import { Component, OnInit } from '@angular/core';

import { ProductModel } from '../model/product-model';
import { ProductDatabaseService } from '../service/product-database.service';

@Component({
  selector: 'app-product-register',
  templateUrl: './product-register.component.html',
  styleUrls: ['./product-register.component.css']
})
export class ProductRegisterComponent implements OnInit {

  sent: boolean = false;

  _name: string;
  _barcode: string;
  _ncm: string;

  constructor(private databaseService: ProductDatabaseService) { }

  ngOnInit() {
  }

  sendData() {
    let newProduct = new ProductModel(this._name, this._barcode, this._ncm);
    this.databaseService.setProduct(newProduct);
    this.sent = !this.sent;
  }

  back() {
    this._name = '';
    this._barcode = '';
    this._ncm = '';
    this.sent = !this.sent;
  }

}


text:
package org.jboss.hal.client.configuration.subsystem.elytron;

import java.util.List;
import java.util.Map;
import java.util.function.Consumer;

import javax.inject.Inject;

import com.google.web.bindery.event.shared.EventBus;
import com.gwtplatform.mvp.client.annotations.NameToken;
import com.gwtplatform.mvp.client.annotations.ProxyCodeSplit;
import com.gwtplatform.mvp.client.proxy.ProxyPlace;
import org.jboss.hal.ballroom.LabelBuilder;
import org.jboss.hal.ballroom.form.Form;
import org.jboss.hal.core.ComplexAttributeOperations;
import org.jboss.hal.core.CrudOperations;
import org.jboss.hal.core.configuration.PathsAutoComplete;
import org.jboss.hal.core.finder.Finder;
import org.jboss.hal.core.finder.FinderPath;
import org.jboss.hal.core.finder.FinderPathFactory;
import org.jboss.hal.core.mbui.MbuiPresenter;
import org.jboss.hal.core.mbui.MbuiView;
import org.jboss.hal.core.mbui.dialog.AddResourceDialog;
import org.jboss.hal.core.mbui.dialog.NameItem;
import org.jboss.hal.core.mbui.form.ModelNodeForm;
import org.jboss.hal.core.mbui.form.RequireAtLeastOneAttributeValidation;
import org.jboss.hal.core.mvp.SupportsExpertMode;
import org.jboss.hal.dmr.ModelDescriptionConstants;
import org.jboss.hal.dmr.ModelNode;
import org.jboss.hal.dmr.NamedNode;
import org.jboss.hal.dmr.Operation;
import org.jboss.hal.dmr.ResourceAddress;
import org.jboss.hal.meta.Metadata;
import org.jboss.hal.meta.MetadataRegistry;
import org.jboss.hal.meta.StatementContext;
import org.jboss.hal.meta.token.NameTokens;
import org.jboss.hal.resources.Ids;
import org.jboss.hal.resources.Names;
import org.jboss.hal.resources.Resources;
import org.jboss.hal.spi.Message;
import org.jboss.hal.spi.MessageEvent;
import org.jboss.hal.spi.Requires;

import static java.util.Arrays.asList;
import static org.jboss.hal.client.configuration.subsystem.elytron.AddressTemplates.*;
import static org.jboss.hal.dmr.ModelDescriptionConstants.*;
import static org.jboss.hal.dmr.ModelNodeHelper.asNamedNodes;
import static org.jboss.hal.dmr.ModelNodeHelper.failSafeBoolean;
import static org.jboss.hal.dmr.ModelNodeHelper.failSafeGet;
import static org.jboss.hal.dmr.ModelNodeHelper.move;

public class RealmsPresenter extends MbuiPresenter<RealmsPresenter.MyView, RealmsPresenter.MyProxy>
        implements SupportsExpertMode {

    static final String[] KEY_MAPPERS = new String[]{
            "clear-password-mapper",
            "bcrypt-mapper",
            "modular-crypt-mapper",
            "salted-simple-digest-mapper",
            "simple-digest-mapper",
            "scram-mapper",
    };
    private static final String DOT = ".";

    private final CrudOperations crud;
    private final ComplexAttributeOperations ca;
    private final FinderPathFactory finderPathFactory;
    private final StatementContext statementContext;
    private final Resources resources;
    private MetadataRegistry metadataRegistry;

    @Inject
    public RealmsPresenter(EventBus eventBus,
            RealmsPresenter.MyView view,
            RealmsPresenter.MyProxy proxy,
            Finder finder,
            CrudOperations crud,
            ComplexAttributeOperations ca,
            FinderPathFactory finderPathFactory,
            StatementContext statementContext,
            MetadataRegistry metadataRegistry,
            Resources resources) {
        super(eventBus, view, proxy, finder);
        this.crud = crud;
        this.ca = ca;
        this.finderPathFactory = finderPathFactory;
        this.statementContext = statementContext;
        this.metadataRegistry = metadataRegistry;
        this.resources = resources;
    }

    @Override
    protected void onBind() {
        super.onBind();
        getView().setPresenter(this);
    }

    @Override
    public ResourceAddress resourceAddress() {
        return ELYTRON_SUBSYSTEM_TEMPLATE.resolve(statementContext);
    }

    @Override
    public FinderPath finderPath() {
        return finderPathFactory.configurationSubsystemPath(Ids.ELYTRON)
                .append(Ids.ELYTRON, Ids.asId(Names.SECURITY_REALMS),
                        resources.constants().settings(), Names.SECURITY_REALMS);
    }

    @Override
    public void reload() {
        ResourceAddress address = ELYTRON_SUBSYSTEM_TEMPLATE.resolve(statementContext);
        crud.readChildren(address, asList(
                ElytronResource.AGGREGATE_REALM.resource,
                ElytronResource.CACHING_REALM.resource,
                ElytronResource.CUSTOM_MODIFIABLE_REALM.resource,
                ElytronResource.CUSTOM_REALM.resource,
                ElytronResource.FILESYSTEM_REALM.resource,
                ElytronResource.IDENTITY_REALM.resource,
                ElytronResource.JDBC_REALM.resource,
                ElytronResource.KEY_STORE_REALM.resource,
                ElytronResource.LDAP_REALM.resource,
                ElytronResource.PROPERTIES_REALM.resource,
                ElytronResource.TOKEN_REALM.resource,
                ElytronResource.CONSTANT_REALM_MAPPER.resource,
                ElytronResource.CUSTOM_REALM_MAPPER.resource,
                ElytronResource.MAPPED_REGEX_REALM_MAPPER.resource,
                ElytronResource.SIMPLE_REGEX_REALM_MAPPER.resource),
                result -> {
                    int i = 0;
                    getView().updateResourceElement(ElytronResource.AGGREGATE_REALM.resource,
                            asNamedNodes(result.step(i++).get(RESULT).asPropertyList()));
                    getView().updateResourceElement(ElytronResource.CACHING_REALM.resource,
                            asNamedNodes(result.step(i++).get(RESULT).asPropertyList()));
                    getView().updateResourceElement(ElytronResource.CUSTOM_MODIFIABLE_REALM.resource,
                            asNamedNodes(result.step(i++).get(RESULT).asPropertyList()));
                    getView().updateResourceElement(ElytronResource.CUSTOM_REALM.resource,
                            asNamedNodes(result.step(i++).get(RESULT).asPropertyList()));
                    getView().updateResourceElement(ElytronResource.FILESYSTEM_REALM.resource,
                            asNamedNodes(result.step(i++).get(RESULT).asPropertyList()));
                    getView().updateResourceElement(ElytronResource.IDENTITY_REALM.resource,
                            asNamedNodes(result.step(i++).get(RESULT).asPropertyList()));
                    getView().updateJdbcRealm(asNamedNodes(result.step(i++).get(RESULT).asPropertyList()));
                    getView().updateResourceElement(ElytronResource.KEY_STORE_REALM.resource,
                            asNamedNodes(result.step(i++).get(RESULT).asPropertyList()));
                    getView().updateLdapRealm(asNamedNodes(result.step(i++).get(RESULT).asPropertyList()));
                    getView().updateResourceElement(ElytronResource.PROPERTIES_REALM.resource,
                            asNamedNodes(result.step(i++).get(RESULT).asPropertyList()));
                    getView().updateResourceElement(ElytronResource.TOKEN_REALM.resource,
                            asNamedNodes(result.step(i++).get(RESULT).asPropertyList()));
                    getView().updateResourceElement(ElytronResource.CONSTANT_REALM_MAPPER.resource,
                            asNamedNodes(result.step(i++).get(RESULT).asPropertyList()));
                    getView().updateResourceElement(ElytronResource.CUSTOM_REALM_MAPPER.resource,
                            asNamedNodes(result.step(i++).get(RESULT).asPropertyList()));
                    getView().updateResourceElement(ElytronResource.MAPPED_REGEX_REALM_MAPPER.resource,
                            asNamedNodes(result.step(i++).get(RESULT).asPropertyList()));
                    //noinspection UnusedAssignment
                    getView().updateResourceElement(ElytronResource.SIMPLE_REGEX_REALM_MAPPER.resource,
                            asNamedNodes(result.step(i++).get(RESULT).asPropertyList()));
                });
    }

    void reload(String resource, Consumer<List<NamedNode>> callback) {
        crud.readChildren(AddressTemplates.ELYTRON_SUBSYSTEM_TEMPLATE, resource,
                children -> callback.accept(asNamedNodes(children)));
    }

    // ------------------------------------------------------ JDBC realm

    void reloadJdbcRealms() {
        crud.readChildren(AddressTemplates.ELYTRON_SUBSYSTEM_TEMPLATE, ModelDescriptionConstants.JDBC_REALM,
                children -> getView().updateJdbcRealm(asNamedNodes(children)));
    }

    void addJdbcRealm() {
        Metadata metadata = metadataRegistry.lookup(JDBC_REALM_TEMPLATE)
                .forComplexAttribute(PRINCIPAL_QUERY);
        NameItem nameItem = new NameItem();
        Form<ModelNode> form = new ModelNodeForm.Builder<>(Ids.build(Ids.ELYTRON_JDBC_REALM, Ids.ADD), metadata)
                .addOnly()
                .requiredOnly()
                .unboundFormItem(nameItem, 0)
                .build();
        AddResourceDialog dialog = new AddResourceDialog(resources.messages().addResourceTitle(Names.JDBC_REALM), form,
                (n1, model) -> {
                    ModelNode payload = new ModelNode();
                    payload.get(PRINCIPAL_QUERY).add(model);
                    crud.add(Names.JDBC_REALM, nameItem.getValue(), JDBC_REALM_TEMPLATE, payload,
                            (n2, address) -> reloadJdbcRealms());
                });
        dialog.show();
    }

    void addPrincipalQuery(String jdbcRealm) {
        ca.listAdd(Ids.build(Ids.ELYTRON_JDBC_REALM, PRINCIPAL_QUERY, Ids.ADD), jdbcRealm, PRINCIPAL_QUERY,
                Names.PRINCIPAL_QUERY, JDBC_REALM_TEMPLATE, this::reloadJdbcRealms);
    }

    void savePrincipalQuery(String jdbcRealm, int pqIndex, Map<String, Object> changedValues) {
        ca.save(jdbcRealm, PRINCIPAL_QUERY, Names.PRINCIPAL_QUERY, pqIndex, JDBC_REALM_TEMPLATE,
                changedValues, this::reloadJdbcRealms);
    }

    void removePrincipalQuery(String jdbcRealm, int pqIndex) {
        ca.remove(jdbcRealm, PRINCIPAL_QUERY, Names.PRINCIPAL_QUERY, pqIndex, JDBC_REALM_TEMPLATE,
                this::reloadJdbcRealms);
    }

    void addKeyMapper(String jdbcRealm, ModelNode principalQuery, int pqIndex,
            String keyMapper) {
        // WFLYELY00034: A principal query can only have a single key mapper
        boolean moreThanOne = false;
        for (String km : KEY_MAPPERS) {
            if (failSafeGet(principalQuery, km).isDefined()) {
                moreThanOne = true;
                break;
            }
        }

        if (moreThanOne) {
            MessageEvent.fire(getEventBus(),
                    Message.error(resources.messages().moreThanOneKeyMapperForPrincipalQuery()));

        } else {
            String type = new LabelBuilder().label(keyMapper);
            Metadata metadata = metadataRegistry.lookup(JDBC_REALM_TEMPLATE)
                    .forComplexAttribute(PRINCIPAL_QUERY)
                    .forComplexAttribute(keyMapper);
            String id = Ids.build(Ids.ELYTRON_JDBC_REALM, PRINCIPAL_QUERY, keyMapper, Ids.ADD);
            Form<ModelNode> form = new ModelNodeForm.Builder<>(id, metadata)
                    .addOnly()
                    .requiredOnly()
                    .build();
            AddResourceDialog dialog = new AddResourceDialog(resources.messages().addResourceTitle(type), form,
                    (name, model) -> ca.add(jdbcRealm, keyMapperAttribute(pqIndex, keyMapper), type,
                            JDBC_REALM_TEMPLATE, model, RealmsPresenter.this::reloadJdbcRealms));
            dialog.show();
        }
    }

    Operation pingKeyMapper(String jdbcRealm, ModelNode principalQuery, String keyMapper) {
        if (jdbcRealm != null) {
            ResourceAddress address = JDBC_REALM_TEMPLATE.resolve(statementContext, jdbcRealm);
            int pqIndex = principalQuery.get(HAL_INDEX).asInt();
            return new Operation.Builder(address, READ_ATTRIBUTE_OPERATION)
                    .param(NAME, keyMapperAttribute(pqIndex, keyMapper))
                    .build();
        }
        return null;
    }

    void saveKeyMapper(String jdbcRealm, int pqIndex, String keyMapper, Map<String, Object> changedValues) {
        String type = new LabelBuilder().label(keyMapper);
        ca.save(jdbcRealm, keyMapperAttribute(pqIndex, keyMapper), type, JDBC_REALM_TEMPLATE,
                changedValues, this::reloadJdbcRealms);
    }

    void resetKeyMapper(String jdbcRealm, int pqIndex, String keyMapper, Form<ModelNode> form) {
        String type = new LabelBuilder().label(keyMapper);
        Metadata metadata = metadataRegistry.lookup(JDBC_REALM_TEMPLATE)
                .forComplexAttribute(PRINCIPAL_QUERY)
                .forComplexAttribute(keyMapper);
        ca.reset(jdbcRealm, keyMapperAttribute(pqIndex, keyMapper), type, JDBC_REALM_TEMPLATE,
                metadata, form, new Form.FinishReset<ModelNode>(form) {
                    @Override
                    public void afterReset(Form<ModelNode> form) {
                        reloadJdbcRealms();
                    }
                });
    }

    void removeKeyMapper(String jdbcRealm, int pqIndex, String keyMapper, Form<ModelNode> form) {
        String type = new LabelBuilder().label(keyMapper);
        ca.remove(jdbcRealm, keyMapperAttribute(pqIndex, keyMapper), type, JDBC_REALM_TEMPLATE,
                new Form.FinishRemove<ModelNode>(form) {
                    @Override
                    public void afterRemove(Form<ModelNode> form) {
                        reloadJdbcRealms();
                    }
                });
    }

    void addAttributeMapping(String jdbcRealm, int pqIndex) {
        Metadata metadata = metadataRegistry.lookup(JDBC_REALM_TEMPLATE)
                .forComplexAttribute(PRINCIPAL_QUERY)
                .forComplexAttribute(ATTRIBUTE_MAPPING);
        Form<ModelNode> form = new ModelNodeForm.Builder<>(
                Ids.build(Ids.ELYTRON_JDBC_REALM, ATTRIBUTE_MAPPING, Ids.ADD), metadata)
                .addOnly()
                .include(TO, INDEX)
                .build();
        AddResourceDialog dialog = new AddResourceDialog(resources.messages().addResourceTitle(Names.ATTRIBUTE_MAPPING),
                form, (name, model) -> ca.listAdd(jdbcRealm, attributeMappingAttribute(pqIndex),
                Names.ATTRIBUTE_MAPPING, JDBC_REALM_TEMPLATE, model, this::reloadJdbcRealms));
        dialog.show();
    }

    void saveAttributeMapping(String jdbcRealm, int pqIndex, int amIndex,
            Map<String, Object> changedValues) {
        ca.save(jdbcRealm, attributeMappingAttribute(pqIndex), Names.ATTRIBUTE_MAPPING, amIndex,
                JDBC_REALM_TEMPLATE, changedValues, this::reloadJdbcRealms);
    }

    void removeAttributeMapping(String jdbcRealm, int pqIndex, int amIndex) {
        ca.remove(jdbcRealm, attributeMappingAttribute(pqIndex), Names.ATTRIBUTE_MAPPING, amIndex,
                JDBC_REALM_TEMPLATE, this::reloadJdbcRealms);
    }

    private String keyMapperAttribute(int pqIndex, String keyMapper) {
        return PRINCIPAL_QUERY + "[" + pqIndex + "]." + keyMapper;
    }

    private String attributeMappingAttribute(int pqIndex) {
        return PRINCIPAL_QUERY + "[" + pqIndex + "]." + ATTRIBUTE_MAPPING;
    }

    // ------------------------------------------------------ LDAP Realm

    void reloadLdapRealms() {
        crud.readChildren(AddressTemplates.ELYTRON_SUBSYSTEM_TEMPLATE, ModelDescriptionConstants.LDAP_REALM,
                children -> getView().updateLdapRealm(asNamedNodes(children)));
    }

    void addLdapRealm() {
        Metadata metadata = metadataRegistry.lookup(LDAP_REALM_TEMPLATE);
        Metadata imMetadata = metadata.forComplexAttribute(IDENTITY_MAPPING, true);
        imMetadata.copyComplexAttributeAttributes(asList(RDN_IDENTIFIER, SEARCH_BASE_DN, USE_RECURSIVE_SEARCH),
                metadata);

        NameItem nameItem = new NameItem();
        String id = Ids.build(Ids.ELYTRON_LDAP_REALM, Ids.ADD);
        Form<ModelNode> form = new ModelNodeForm.Builder<>(id, metadata)
                .addOnly()
                .unboundFormItem(nameItem, 0)
                .include(DIR_CONTEXT, DIRECT_VERIFICATION, ALLOW_BLANK_PASSWORD, RDN_IDENTIFIER, SEARCH_BASE_DN,
                        USE_RECURSIVE_SEARCH)
                .build();

        new AddResourceDialog(resources.messages().addResourceTitle(Names.LDAP_REALM), form,
                (name, model) -> {
                    if (model != null) {
                        move(model, RDN_IDENTIFIER, IDENTITY_MAPPING + "/" + RDN_IDENTIFIER);
                        move(model, SEARCH_BASE_DN, IDENTITY_MAPPING + "/" + SEARCH_BASE_DN);
                        // workaround for "WFLYCTL0380: Attribute 'identity-mapping.search-base-dn' needs to be set or
                        // passed before attribute 'identity-mapping.use-recursive-search' can be correctly set"
                        // only pass USE_RECURSIVE_SEARCH if true (not default-value)
                        if (failSafeBoolean(model, USE_RECURSIVE_SEARCH)) {
                            move(model, USE_RECURSIVE_SEARCH, IDENTITY_MAPPING + "/" + USE_RECURSIVE_SEARCH);
                        } else {
                            model.remove(USE_RECURSIVE_SEARCH);
                        }
                    }
                    ResourceAddress address = LDAP_REALM_TEMPLATE.resolve(statementContext, nameItem.getValue());
                    crud.add(Names.IDENTITY_ATTRIBUTE_MAPPING, name, address, model, (n, a) -> reloadLdapRealms());
                }).show();
    }

    void saveLdapRealm(Form<NamedNode> form, Map<String, Object> changedValues) {
        crud.save(Names.LDAP_REALM, form.getModel().getName(), AddressTemplates.LDAP_REALM_TEMPLATE, changedValues,
                this::reloadLdapRealms);
    }

    void addIdentityMappingComplexAttribute(String ldapRealm, String complexAttribute, String type) {
        String id = Ids.build(Ids.ELYTRON_LDAP_REALM, complexAttribute, Ids.ADD);
        Metadata metadata = metadataRegistry.lookup(LDAP_REALM_TEMPLATE)
                .forComplexAttribute(IDENTITY_MAPPING)
                .forComplexAttribute(complexAttribute);
        boolean requiredAttributes = !metadata.getDescription().getRequiredAttributes(ATTRIBUTES).isEmpty();
        ModelNodeForm.Builder<ModelNode> builder = new ModelNodeForm.Builder<>(id, metadata)
                .addOnly();
        if (requiredAttributes) {
            builder.requiredOnly();
        }
        AddResourceDialog dialog = new AddResourceDialog(resources.messages().addResourceTitle(type), builder.build(),
                (name, model) -> ca.add(ldapRealm, IDENTITY_MAPPING + DOT + complexAttribute, type,
                        LDAP_REALM_TEMPLATE, model, this::reloadLdapRealms));
        dialog.show();
    }

    Operation pingIdentityMappingComplexAttribute(String ldapRealm, String complexAttribute) {
        if (ldapRealm != null) {
            ResourceAddress address = LDAP_REALM_TEMPLATE.resolve(statementContext, ldapRealm);
            return new Operation.Builder(address, READ_ATTRIBUTE_OPERATION)
                    .param(NAME, IDENTITY_MAPPING + DOT + complexAttribute)
                    .build();
        }
        return null;
    }

    void saveIdentityMapping(String ldapRealm, Map<String, Object> changedValues) {
        ResourceAddress address = LDAP_REALM_TEMPLATE.resolve(statementContext, ldapRealm);
        Metadata metadata = metadataRegistry.lookup(LDAP_REALM_TEMPLATE)
                .forComplexAttribute(IDENTITY_MAPPING);
        ca.save(IDENTITY_MAPPING, Names.IDENTITY_MAPPING, address, changedValues, metadata, this::reloadLdapRealms);
    }

    void resetIdentityMapping(String ldapRealm, Form<ModelNode> form) {
        ResourceAddress address = LDAP_REALM_TEMPLATE.resolve(statementContext, ldapRealm);
        Metadata metadata = metadataRegistry.lookup(LDAP_REALM_TEMPLATE)
                .forComplexAttribute(IDENTITY_MAPPING);
        ca.reset(IDENTITY_MAPPING, Names.IDENTITY_MAPPING, address, metadata, form, this::reloadLdapRealms);
    }

    void saveIdentityMappingComplexAttribute(String ldapRealm, String complexAttribute, String type,
            Map<String, Object> changedValues) {
        ResourceAddress address = LDAP_REALM_TEMPLATE.resolve(statementContext, ldapRealm);
        Metadata metadata = metadataRegistry.lookup(LDAP_REALM_TEMPLATE)
                .forComplexAttribute(IDENTITY_MAPPING)
                .forComplexAttribute(complexAttribute);
        ca.save(IDENTITY_MAPPING + DOT + complexAttribute, type, address, changedValues, metadata,
                this::reloadLdapRealms);
    }

    void resetIdentityMappingComplexAttribute(String ldapRealm, String complexAttribute, String type,
            Form<ModelNode> form) {
        ResourceAddress address = LDAP_REALM_TEMPLATE.resolve(statementContext, ldapRealm);
        Metadata metadata = metadataRegistry.lookup(LDAP_REALM_TEMPLATE)
                .forComplexAttribute(IDENTITY_MAPPING)
                .forComplexAttribute(complexAttribute);
        ca.reset(IDENTITY_MAPPING + DOT + complexAttribute, type, address, metadata, form, this::reloadLdapRealms);
    }

    void removeIdentityMappingComplexAttribute(String ldapRealm, String complexAttribute, String type,
            Form<ModelNode> form) {
        ca.remove(ldapRealm, IDENTITY_MAPPING + DOT + complexAttribute, type, LDAP_REALM_TEMPLATE,
                new Form.FinishRemove<ModelNode>(form) {
                    @Override
                    public void afterRemove(Form<ModelNode> form) {
                        reloadLdapRealms();
                    }
                });
    }

    // TODO Fix requires validation:
    // If 'search-rekursive' which requires 'filter' and which defaults to true is not touched
    // and 'filter' is set, the RequiredByValidation does not detect an validation error, because
    // 'search-rekursive' isEmptyOrDefault()
    void addIdentityAttributeMapping(String selectedLdapRealm) {
        Metadata iamMetadata = metadataRegistry.lookup(LDAP_REALM_TEMPLATE)
                .forComplexAttribute(IDENTITY_MAPPING)
                .forComplexAttribute(ATTRIBUTE_MAPPING);
        String id = Ids.build(Ids.ELYTRON_LDAP_REALM, ATTRIBUTE_MAPPING, Ids.ADD);
        Form<ModelNode> form = new ModelNodeForm.Builder<>(id, iamMetadata)
                .addOnly()
                .include(FROM, TO)
                .build();
        form.addFormValidation(new RequireAtLeastOneAttributeValidation<>(
                asList(FROM, TO), resources));
        AddResourceDialog dialog = new AddResourceDialog(resources.messages().addResourceTitle(Names.ATTRIBUTE_MAPPING),
                form, (name, model) ->
                ca.listAdd(selectedLdapRealm, IDENTITY_MAPPING + DOT + ATTRIBUTE_MAPPING,
                        Names.IDENTITY_ATTRIBUTE_MAPPING, LDAP_REALM_TEMPLATE, model, this::reloadLdapRealms));
        dialog.show();
    }

    void saveIdentityAttributeMapping(String selectedLdapRealm, int iamIndex, Map<String, Object> changedValues) {
        // passed before attribute 'identity-mapping.attribute-mapping[n].search-recursive' can be correctly set"

        ca.save(selectedLdapRealm, IDENTITY_MAPPING + DOT + ATTRIBUTE_MAPPING,
                Names.IDENTITY_ATTRIBUTE_MAPPING, iamIndex, AddressTemplates.LDAP_REALM_TEMPLATE,
                changedValues, this::reloadLdapRealms);
    }

    void removeIdentityAttributeMapping(String selectedLdapRealm, int iamIndex) {
        ca.remove(selectedLdapRealm, IDENTITY_MAPPING + DOT + ATTRIBUTE_MAPPING,
                Names.IDENTITY_ATTRIBUTE_MAPPING, iamIndex, AddressTemplates.LDAP_REALM_TEMPLATE,
                this::reloadLdapRealms);
    }

    // ------------------------------------------------------  properties realm

    void addPropertiesRealm() {
        Metadata metadata = metadataRegistry.lookup(PROPERTIES_REALM_TEMPLATE);
        Metadata upMetadata = metadata.forComplexAttribute(USERS_PROPERTIES, true);
        upMetadata.copyComplexAttributeAttributes(asList(PATH, RELATIVE_TO), metadata);

        String id = Ids.build(Ids.ELYTRON_PROPERTIES_REALM, Ids.ADD);
        NameItem nameItem = new NameItem();
        Form<ModelNode> form = new ModelNodeForm.Builder<>(id, metadata)
                .addOnly()
                .unboundFormItem(nameItem, 0)
                .include(PATH, RELATIVE_TO, GROUPS_ATTRIBUTE)
                .build();
        form.getFormItem(RELATIVE_TO).registerSuggestHandler(new PathsAutoComplete());

        new AddResourceDialog(resources.messages().addResourceTitle(Names.PROPERTIES_REALM), form, (name, model) -> {
            if (model != null) {
                move(model, PATH, USERS_PROPERTIES + "/" + PATH);
                move(model, RELATIVE_TO, USERS_PROPERTIES + "/" + RELATIVE_TO);
            }
            ResourceAddress address = PROPERTIES_REALM_TEMPLATE.resolve(statementContext, nameItem.getValue());
            crud.add(Names.PROPERTIES_REALM, name, address, model, (n, a) ->
                    reload(PROPERTIES_REALM, nodes ->
                            getView().updateResourceElement(PROPERTIES_REALM, nodes)));
        }).show();
    }

    @ProxyCodeSplit
    @Requires(value = {
            AGGREGATE_REALM_ADDRESS,
            CACHING_REALM_ADDRESS,
            CONSTANT_REALM_MAPPER_ADDRESS,
            CUSTOM_MODIFIABLE_REALM_ADDRESS,
            CUSTOM_REALM_ADDRESS,
            CUSTOM_REALM_MAPPER_ADDRESS,
            FILESYSTEM_REALM_ADDRESS,
            IDENTITY_REALM_ADDRESS,
            JDBC_REALM_ADDRESS,
            KEY_STORE_REALM_ADDRESS,
            LDAP_REALM_ADDRESS,
            MAPPED_REGEX_REALM_MAPPER_ADDRESS,
            PROPERTIES_REALM_ADDRESS,
            SIMPLE_REGEX_REALM_MAPPER_ADDRESS,
            TOKEN_REALM_ADDRESS})
    @NameToken(NameTokens.ELYTRON_SECURITY_REALMS)
    public interface MyProxy extends ProxyPlace<RealmsPresenter> {
    }

    // @formatter:off
    public interface MyView extends MbuiView<RealmsPresenter> {
        void updateResourceElement(String resource, List<NamedNode> nodes);
        void updateJdbcRealm(List<NamedNode> nodes);
        void updateLdapRealm(List<NamedNode> nodes);
    }
    // @formatter:on
}


text:
<?php

if ( !defined( 'ABSPATH' ) )
	exit( 'No direct script access allowed' ); // Exit if accessed directly

?>

			<button type="button" class="icon-stack" data-dismiss="modal" aria-label="Close">

			</button>


text:
#include "globus_xio_driver.h"
#include "globus_xio_load.h"
#include "globus_common.h"
#include "globus_xio_rate_driver.h"

GlobusDebugDefine(GLOBUS_XIO_RATE);
GlobusXIODeclareDriver(rate);

typedef enum
{
    GLOBUS_XIO_RATE_DEBUG_ERROR = 1,
    GLOBUS_XIO_RATE_DEBUG_WARNING = 2,
    GLOBUS_XIO_RATE_DEBUG_TRACE = 4,
    GLOBUS_XIO_RATE_DEBUG_INFO = 8,
} globus_xio_rate_debug_levels_t;

#define GlobusXIORateDebugPrintf(level, message)                              \
    GlobusDebugPrintf(GLOBUS_XIO_RATE, level, message)

#define GlobusXIORateDebugEnter()                                             \
    GlobusXIORateDebugPrintf(                                                 \
        GLOBUS_XIO_RATE_DEBUG_TRACE,                                          \
        ("[%s] Entering\n", _xio_name))

#define GlobusXIORateDebugExit()                                              \
    GlobusXIORateDebugPrintf(                                                 \
        GLOBUS_XIO_RATE_DEBUG_TRACE,                                          \
        ("[%s] Exiting\n", _xio_name))

/* set to a gigabit per sec */
#define DEFAULT_RATE                    (1024*1024*1024/8)
#define DEFAULT_PERIOD_US               1000000

static int
globus_l_xio_rate_activate();

static int
globus_l_xio_rate_deactivate();

#include "version.h"

GlobusXIODefineModule(rate) =
{
    "globus_xio_rate",
    globus_l_xio_rate_activate,
    globus_l_xio_rate_deactivate,
    GLOBUS_NULL,
    GLOBUS_NULL,
    &local_version
};

typedef void
(*l_xio_rate_finished_func_t)(
    globus_xio_operation_t              op,
    globus_result_t                     result,
    globus_size_t                       nread);

typedef globus_result_t
(*l_xio_rate_pass_func_t)(
    globus_xio_operation_t              op,
    globus_xio_iovec_t *                iovec,
    int                                 iovec_count,
    globus_size_t                       wait_for,
    globus_xio_driver_data_callback_t   cb,
    void *                              user_arg);

typedef struct l_xio_rate_attr_s
{
    globus_off_t                        rate;
    int                                 us_period;
    globus_size_t                       burst_size;
} l_xio_rate_attr_t;

typedef struct l_xio_rate_rw_attr_s
{
    l_xio_rate_attr_t                     read_attr;
    l_xio_rate_attr_t                     write_attr;
} l_xio_rate_attr_rw_t;

static l_xio_rate_attr_rw_t               l_xio_rate_default_attr;

typedef struct l_xio_rate_op_handle_s
{
    globus_mutex_t                      mutex;
    globus_off_t                        allowed;
    globus_off_t                        per_tic;
    globus_callback_handle_t            cb_handle;
    globus_reltime_t                    us_period;
    l_xio_rate_finished_func_t            finished_func;
    l_xio_rate_pass_func_t                pass_func;
    globus_bool_t                       outstanding;
    globus_size_t                       max_allowed;
    int                                 ref;
    struct l_xio_rate_data_s *          data;
} l_xio_rate_op_handle_t;

typedef struct l_xio_rate_data_s
{
    globus_xio_operation_t              op;
    globus_xio_iovec_t *                iov;
    int                                 iovc;
    globus_off_t                        nbytes;
    globus_object_t *                   error;
    l_xio_rate_op_handle_t *            op_handle;
} l_xio_rate_data_t;

typedef struct l_xio_rate_handle_s
{
    globus_result_t                     close_result;
    globus_xio_operation_t              close_op;
    l_xio_rate_op_handle_t *            read_handle;
    l_xio_rate_op_handle_t *            write_handle;
} l_xio_rate_handle_t;

static
void
l_xio_rate_net_ops(
    l_xio_rate_op_handle_t *    op_handle);

static globus_mutex_t                   xio_l_rate_hash_mutex;

static
void
l_xio_rate_destroy_op_handle(
    l_xio_rate_op_handle_t *    op_handle)
{
    globus_mutex_destroy(&op_handle->mutex);
    assert(op_handle->ref == 0);

    globus_free(op_handle);
}

static
void
l_xio_rate_destroy_handle(
    l_xio_rate_handle_t *       handle)
{
    GlobusXIOName(l_xio_rate_destroy_handle);

    GlobusXIORateDebugEnter();

    l_xio_rate_destroy_op_handle(handle->read_handle);
    l_xio_rate_destroy_op_handle(handle->write_handle);

    globus_free(handle);

    GlobusXIORateDebugExit();
}

static
void
globus_l_xio_rate_error_cb(
    void *                              user_arg)
{
    l_xio_rate_op_handle_t *            op_handle;
    l_xio_rate_data_t *                 data;
    globus_result_t                     result;
    GlobusXIOName(globus_l_xio_rate_error_cb);

    GlobusXIORateDebugEnter();
    data = (l_xio_rate_data_t *) user_arg;
    op_handle = data->op_handle;

    result = globus_error_put(data->error);

    op_handle->finished_func(data->op, result, 0);

    globus_free(data->iov);
    globus_free(data);
    GlobusXIORateDebugExit();
}

static
void
globus_l_xio_rate_op_cb(
    globus_xio_operation_t              op,
    globus_result_t                     result,
    globus_size_t                       nbytes,
    void *                              user_arg)
{
    l_xio_rate_op_handle_t *            op_handle;
    l_xio_rate_data_t *                 data;
    GlobusXIOName(globus_l_xio_rate_op_cb);

    GlobusXIORateDebugEnter();
    data = (l_xio_rate_data_t *) user_arg;
    op_handle = data->op_handle;

    if(result != GLOBUS_SUCCESS)
    {
        GlobusXIORateDebugPrintf(GLOBUS_XIO_RATE_DEBUG_INFO,
            ("    error setting done true\n"));
    }

    op_handle->finished_func(data->op, result, nbytes);
    globus_free(data);

    globus_mutex_unlock(&op_handle->mutex);
    GlobusXIORateDebugExit();
}

/*
 *   called locked
 */
static
void
l_xio_rate_net_ops(
    l_xio_rate_op_handle_t *    op_handle)
{
    globus_size_t                       len;
    globus_result_t                     res;
    l_xio_rate_data_t *         data;
    GlobusXIOName(l_xio_rate_net_ops);

    GlobusXIORateDebugEnter();
    if(op_handle->outstanding)
    {
        return;
    }
    if(op_handle->data != NULL && op_handle->allowed > 0)
    {
        data = (l_xio_rate_data_t *) op_handle->data;

        GlobusXIOUtilIovTotalLength(len, data->iov, data->iovc);
        if(len > op_handle->allowed)
        {
            /* if there are bytes left in the iov adjust it so that the
                next data op starts in the right place */
            len = op_handle->allowed;
        }
        op_handle->allowed -= len;

        op_handle->data = NULL;
        res = op_handle->pass_func(
            data->op,
            (globus_xio_iovec_t *)data->iov,
            data->iovc,
            len,
            globus_l_xio_rate_op_cb,
            data);
        if(res != GLOBUS_SUCCESS)
        {
            /* kick out one shot */
            data->error = globus_error_get(res);
            globus_callback_register_oneshot(
                NULL,
                NULL,
                globus_l_xio_rate_error_cb,
                data);
        }
    }
    GlobusXIORateDebugExit();
}

static
void
l_xio_rate_ticker_cb(
    void *                              user_arg)
{
    l_xio_rate_op_handle_t *    op_handle;
    GlobusXIOName(l_xio_rate_ticker_cb);

    GlobusXIORateDebugEnter();
    op_handle = (l_xio_rate_op_handle_t *) user_arg;

    globus_mutex_lock(&op_handle->mutex);
    {
        op_handle->allowed += op_handle->per_tic;
        if(op_handle->allowed > op_handle->max_allowed &&
            op_handle->max_allowed != -1)
        {
            op_handle->allowed = op_handle->max_allowed;
        }
        l_xio_rate_net_ops(op_handle);
    }
    globus_mutex_unlock(&op_handle->mutex);
    GlobusXIORateDebugExit();
}

/*
 *  check to see if op handle is in table.  if so destroy
 *  passed in one and retrun the one in the table with a
 *  hugher ref count.  If not, keep the new one and start the time
 */
static
l_xio_rate_op_handle_t *
xio_l_rate_start_ticker(
    l_xio_rate_op_handle_t *            handle)
{
    globus_bool_t                       start = GLOBUS_FALSE;

    if(handle == NULL)
    {
        return NULL;
    }

    /* need to lock to up ref for all */
    globus_mutex_lock(&handle->mutex);
    {
        handle->ref++;
        if(handle->ref == 1)
        {
            start = GLOBUS_TRUE;
        }
    }
    globus_mutex_unlock(&handle->mutex);

    if(start)
    {
        globus_callback_register_periodic(
            &handle->cb_handle,
            &handle->us_period,
            &handle->us_period,
            l_xio_rate_ticker_cb,
            handle);
    }
    return handle;
}

static
void
globus_l_xio_rate_open_cb(
    globus_xio_operation_t              op,
    globus_result_t                     result,
    void *                              user_arg)
{
    l_xio_rate_handle_t *       handle;
    GlobusXIOName(globus_l_xio_rate_open_cb);

    GlobusXIORateDebugEnter();
    handle = (l_xio_rate_handle_t *) user_arg;

    globus_xio_driver_finished_open(handle, op, result);

    if(result != GLOBUS_SUCCESS)
    {
        l_xio_rate_destroy_handle(handle);
    }
    else
    {
        globus_mutex_lock(&xio_l_rate_hash_mutex);
        {
            handle->write_handle = xio_l_rate_start_ticker(
                handle->write_handle);
            handle->read_handle = xio_l_rate_start_ticker(
                handle->read_handle);
        }
        globus_mutex_unlock(&xio_l_rate_hash_mutex);
    }
    GlobusXIORateDebugExit();
}

static
l_xio_rate_op_handle_t *
xio_l_rate_attr_to_handle(
    l_xio_rate_handle_t *               daddy,
    l_xio_rate_attr_t *                   attr,
    l_xio_rate_finished_func_t            finished_func,
    l_xio_rate_pass_func_t                pass_func)
{
    l_xio_rate_op_handle_t *            handle;

    if(attr->rate < 0)
    {
        return NULL;
    }
    handle = (l_xio_rate_op_handle_t *) globus_calloc(
        sizeof(l_xio_rate_op_handle_t), 1);
    if(handle == NULL)
    {
        goto error;
    }
    globus_mutex_init(&handle->mutex, NULL);
    handle->finished_func = finished_func;
    handle->pass_func = pass_func;

    if(attr->burst_size == (globus_size_t) -1)
    {
        attr->burst_size = 2 * attr->rate;
    }

    handle->per_tic = (int)((float)attr->rate *
        ((float)attr->us_period / 1000000.0f));
    GlobusTimeReltimeSet(handle->us_period, 0, attr->us_period);
    handle->max_allowed = attr->burst_size;

    return handle;
error:
    return NULL;
}

static
globus_result_t
globus_l_xio_rate_open(
    const globus_xio_contact_t *        contact_info,
    void *                              driver_link,
    void *                              driver_attr,
    globus_xio_operation_t              op)
{
    globus_result_t                     res;
    l_xio_rate_handle_t *       handle;
    l_xio_rate_attr_rw_t *                attr;
    GlobusXIOName(globus_l_xio_rate_open);

    GlobusXIORateDebugEnter();
    if(driver_attr == NULL)
    {
        attr = &l_xio_rate_default_attr;
    }
    else
    {
        attr = (l_xio_rate_attr_rw_t *) driver_attr;
    }

    handle = (l_xio_rate_handle_t *)
        globus_calloc(1, sizeof(l_xio_rate_handle_t));

    handle->read_handle = xio_l_rate_attr_to_handle(
        handle,
        &attr->read_attr,
        globus_xio_driver_finished_read,
        globus_xio_driver_pass_read);

    handle->write_handle = xio_l_rate_attr_to_handle(
        handle,
        &attr->write_attr,
        globus_xio_driver_finished_write,
        globus_xio_driver_pass_write);

    res = globus_xio_driver_pass_open(
        op, contact_info, globus_l_xio_rate_open_cb, handle);
    if(res != GLOBUS_SUCCESS)
    {
        goto error;
    }

    GlobusXIORateDebugExit();
    return GLOBUS_SUCCESS;
error:
    l_xio_rate_destroy_handle(handle);
    return res;

}

static
globus_bool_t
xio_l_rate_ref_dec(
    l_xio_rate_handle_t *               handle,
    l_xio_rate_op_handle_t *            op_handle,
    globus_callback_func_t              cb)
{
    globus_bool_t                       b = GLOBUS_FALSE;

    globus_mutex_lock(&op_handle->mutex);
    {
        op_handle->ref--;
        if(op_handle->ref == 0)
        {
            b = GLOBUS_TRUE;
            globus_callback_unregister(
                op_handle->cb_handle,
                cb,
                handle,
                NULL);
        }
    }
    globus_mutex_unlock(&op_handle->mutex);

    return b;
}

static
void
l_xio_rate_write_unreg(
    void *                              user_arg)
{
    l_xio_rate_handle_t *       handle;
    GlobusXIOName(l_xio_rate_read_unreg);

    GlobusXIORateDebugEnter();
    handle = (l_xio_rate_handle_t *) user_arg;

    l_xio_rate_destroy_op_handle(handle->write_handle);
    globus_xio_driver_finished_close(handle->close_op, handle->close_result);
    globus_free(handle);

    GlobusXIORateDebugExit();

}

static
void
l_xio_rate_read_unreg(
    void *                              user_arg)
{
    globus_bool_t                       b = GLOBUS_FALSE;
    l_xio_rate_handle_t *       handle;
    GlobusXIOName(l_xio_rate_read_unreg);

    GlobusXIORateDebugEnter();
    handle = (l_xio_rate_handle_t *) user_arg;

    globus_mutex_lock(&xio_l_rate_hash_mutex);
    {
        if(handle->write_handle != NULL)
        {
            b = xio_l_rate_ref_dec(handle,
                handle->write_handle, l_xio_rate_write_unreg);
        }
    }
    globus_mutex_unlock(&xio_l_rate_hash_mutex);

    l_xio_rate_destroy_op_handle(handle->read_handle);
    if(!b)
    {
        globus_xio_driver_finished_close(handle->close_op, handle->close_result);
        globus_free(handle);
    }

    GlobusXIORateDebugExit();
}

static
void
globus_l_xio_rate_close_cb(
    globus_xio_operation_t              op,
    globus_result_t                     result,
    void *                              user_arg)
{
    globus_bool_t                       b = GLOBUS_FALSE;
    l_xio_rate_handle_t *       handle;
    GlobusXIOName(globus_l_xio_rate_close_cb);

    GlobusXIORateDebugEnter();
    handle = (l_xio_rate_handle_t *) user_arg;
    handle->close_result = result;

    globus_mutex_lock(&xio_l_rate_hash_mutex);
    {
        if(handle->read_handle != NULL)
        {
            b = xio_l_rate_ref_dec(handle,
                handle->read_handle, l_xio_rate_read_unreg);
        }
        if(!b)
        {
            if(handle->write_handle != NULL)
            {
                b = xio_l_rate_ref_dec(handle,
                    handle->write_handle, l_xio_rate_write_unreg);
            }
        }
    }
    globus_mutex_unlock(&xio_l_rate_hash_mutex);

    if(!b)
    {
        globus_xio_driver_finished_close(op, handle->close_result);
        globus_free(handle);
    }
}
/*
 *  close
 */
static
globus_result_t
globus_l_xio_rate_close(
    void *                              driver_specific_handle,
    void *                              attr,
    globus_xio_operation_t              op)
{
    globus_result_t                     res;
    l_xio_rate_handle_t *       handle;
    GlobusXIOName(globus_l_xio_rate_close);

    GlobusXIORateDebugEnter();
    handle = (l_xio_rate_handle_t *) driver_specific_handle;

    handle->close_op = op;
    res = globus_xio_driver_pass_close(
        op, globus_l_xio_rate_close_cb, handle);
    if(res != GLOBUS_SUCCESS)
    {
        goto error;
    }

    GlobusXIORateDebugExit();

    return GLOBUS_SUCCESS;
error:

    return res;
}

/*
 *  read
 */
static
globus_result_t
globus_l_xio_rate_read(
    void *                              driver_specific_handle,
    const globus_xio_iovec_t *          iovec,
    int                                 iovec_count,
    globus_xio_operation_t              op)
{
    globus_result_t                     res;
    l_xio_rate_handle_t *       handle;
    l_xio_rate_data_t *         data;
    GlobusXIOName(globus_l_xio_rate_read);

    GlobusXIORateDebugEnter();
    handle = (l_xio_rate_handle_t *) driver_specific_handle;

    if(handle->read_handle == NULL)
    {
        globus_size_t wait_for = globus_xio_operation_get_wait_for(op);
        res = globus_xio_driver_pass_read(
            op,
            (globus_xio_iovec_t *)iovec,
            iovec_count,
            wait_for,
            NULL,
            NULL);
        if(res != GLOBUS_SUCCESS)
        {
            goto error;
        }
    }
    else
    {
        data = (l_xio_rate_data_t *) globus_calloc(
            1, sizeof(l_xio_rate_data_t));
        data->op = op;
        data->iovc = iovec_count;
        data->iov = (globus_xio_iovec_t *)
            globus_calloc(iovec_count, sizeof(globus_xio_iovec_t));
        data->op_handle = handle->read_handle;
        data->op_handle->data = data;

        GlobusIXIOUtilTransferIovec(data->iov, iovec, iovec_count);

        globus_mutex_lock(&data->op_handle->mutex);
        {
            l_xio_rate_net_ops(data->op_handle);
        }
        globus_mutex_unlock(&data->op_handle->mutex);
    }
    GlobusXIORateDebugExit();

    return GLOBUS_SUCCESS;
error:
    return res;
}

/*
 *  write
 */
static
globus_result_t
globus_l_xio_rate_write(
    void *                              driver_specific_handle,
    const globus_xio_iovec_t *          iovec,
    int                                 iovec_count,
    globus_xio_operation_t              op)
{
    globus_result_t                     res;
    l_xio_rate_handle_t *       handle;
    l_xio_rate_data_t *         data;
    GlobusXIOName(globus_l_xio_rate_write);

    GlobusXIORateDebugEnter();
    handle = (l_xio_rate_handle_t *) driver_specific_handle;

    if(handle->write_handle == NULL)
    {
        globus_size_t wait_for = globus_xio_operation_get_wait_for(op);
        res = globus_xio_driver_pass_write(
            op,
            (globus_xio_iovec_t *)iovec,
            iovec_count,
            wait_for,
            NULL,
            NULL);
        if(res != GLOBUS_SUCCESS)
        {
            goto error;
        }
    }
    else
    {
        data = (l_xio_rate_data_t *) globus_calloc(
            1, sizeof(l_xio_rate_data_t));
        data->op = op;
        data->iovc = iovec_count;
        data->iov = (globus_xio_iovec_t *)
            globus_calloc(iovec_count, sizeof(globus_xio_iovec_t));
        data->op_handle = handle->write_handle;
        data->op_handle->data = data;

        GlobusIXIOUtilTransferIovec(data->iov, iovec, iovec_count);

        globus_mutex_lock(&data->op_handle->mutex);
        {
            l_xio_rate_net_ops(data->op_handle);
        }
        globus_mutex_unlock(&data->op_handle->mutex);
    }
    GlobusXIORateDebugExit();

    return GLOBUS_SUCCESS;
error:
    return res;
}

static
globus_result_t
globus_l_xio_rate_cntl(
    void *                              driver_specific_handle,
    int                                 cmd,
    va_list                             ap)
{
    return GLOBUS_SUCCESS;
}

static
globus_result_t
globus_l_xio_rate_attr_copy(
    void **                             dst,
    void *                              src)
{
    l_xio_rate_attr_rw_t *                src_attr;
    l_xio_rate_attr_rw_t *                dst_attr;

    src_attr = (l_xio_rate_attr_rw_t *) src;
    dst_attr = (l_xio_rate_attr_rw_t *) globus_calloc(1, sizeof(l_xio_rate_attr_rw_t));

    dst_attr->read_attr.rate = src_attr->read_attr.rate;
    dst_attr->read_attr.burst_size = src_attr->read_attr.burst_size;
    dst_attr->read_attr.us_period = src_attr->read_attr.us_period;
    dst_attr->write_attr.rate = src_attr->write_attr.rate;
    dst_attr->write_attr.us_period = src_attr->write_attr.us_period;
    dst_attr->write_attr.burst_size = src_attr->write_attr.burst_size;

    *dst = dst_attr;

    return GLOBUS_SUCCESS;
}

static
globus_result_t
globus_l_xio_rate_attr_init(
    void **                             out_driver_attr)
{
    l_xio_rate_attr_t *                   attr;

    globus_l_xio_rate_attr_copy((void **)&attr, (void *)&l_xio_rate_default_attr);

    *out_driver_attr = attr;

    return GLOBUS_SUCCESS;
}

static
globus_result_t
globus_l_xio_rate_attr_destroy(
    void *                              driver_attr)
{
    l_xio_rate_attr_rw_t *                attr;

    attr = (l_xio_rate_attr_rw_t *) driver_attr;
    globus_free(attr);

    return GLOBUS_SUCCESS;
}

static globus_xio_string_cntl_table_t  rate_l_string_opts_table[] =
{
    {"rate", GLOBUS_XIO_RATE_SET_RATE, globus_xio_string_cntl_formated_off},
    {"read_rate", GLOBUS_XIO_RATE_SET_READ_RATE, globus_xio_string_cntl_formated_off},
    {"write_rate", GLOBUS_XIO_RATE_SET_WRITE_RATE, globus_xio_string_cntl_formated_off},
    {"period", GLOBUS_XIO_RATE_SET_PERIOD, globus_xio_string_cntl_formated_int},
    {"read_period", GLOBUS_XIO_RATE_SET_READ_PERIOD, globus_xio_string_cntl_formated_int},
    {"write_period", GLOBUS_XIO_RATE_SET_WRITE_PERIOD, globus_xio_string_cntl_formated_int},
    {"burst", GLOBUS_XIO_RATE_SET_BURST, globus_xio_string_cntl_formated_int},
    {"read_burst", GLOBUS_XIO_RATE_SET_READ_BURST, globus_xio_string_cntl_formated_int},
    {"write_burst", GLOBUS_XIO_RATE_SET_WRITE_BURST, globus_xio_string_cntl_formated_int},
    {NULL, 0, NULL}
};

static
globus_result_t
globus_l_xio_rate_attr_cntl(
    void *                              driver_attr,
    int                                 cmd,
    va_list                             ap)
{
    l_xio_rate_attr_rw_t *                attr;
    GlobusXIOName(globus_l_xio_rate_attr_cntl);

    attr = (l_xio_rate_attr_rw_t *) driver_attr;

    switch(cmd)
    {
        case GLOBUS_XIO_RATE_SET_RATE:
            attr->read_attr.rate = va_arg(ap, globus_size_t);
            attr->write_attr.rate = attr->read_attr.rate;
            break;

        case GLOBUS_XIO_RATE_SET_PERIOD:
            attr->read_attr.us_period = va_arg(ap, int);
            attr->write_attr.us_period = attr->read_attr.us_period;
            break;

        case GLOBUS_XIO_RATE_SET_READ_RATE:
            attr->read_attr.rate = va_arg(ap, globus_size_t);
            break;

        case GLOBUS_XIO_RATE_SET_READ_PERIOD:
            attr->read_attr.us_period = va_arg(ap, int);
            break;

        case GLOBUS_XIO_RATE_SET_WRITE_RATE:
            attr->write_attr.rate = va_arg(ap, globus_size_t);
            break;

        case GLOBUS_XIO_RATE_SET_WRITE_PERIOD:
            attr->write_attr.us_period = va_arg(ap, int);
            break;

        case GLOBUS_XIO_RATE_SET_BURST:
            attr->read_attr.burst_size = va_arg(ap, globus_size_t);
            attr->write_attr.burst_size = attr->read_attr.burst_size;
            break;

        case GLOBUS_XIO_RATE_SET_READ_BURST:
            attr->read_attr.burst_size = va_arg(ap, globus_size_t);
            break;

        case GLOBUS_XIO_RATE_SET_WRITE_BURST:
            attr->write_attr.burst_size = va_arg(ap, globus_size_t);
            break;

        default:
            break;
    }

    return GLOBUS_SUCCESS;
}

static globus_result_t
globus_l_xio_rate_init(
    globus_xio_driver_t *               out_driver)
{
    globus_xio_driver_t                 driver;
    globus_result_t                     res;

    res = globus_xio_driver_init(&driver, "rate", NULL);
    if(res != GLOBUS_SUCCESS)
    {
        return res;
    }

    globus_xio_driver_set_transform(
        driver,
        globus_l_xio_rate_open,
        globus_l_xio_rate_close,
        globus_l_xio_rate_read,
        globus_l_xio_rate_write,
        globus_l_xio_rate_cntl,
        NULL);

    globus_xio_driver_set_attr(
        driver,
        globus_l_xio_rate_attr_init,
        globus_l_xio_rate_attr_copy,
        globus_l_xio_rate_attr_cntl,
        globus_l_xio_rate_attr_destroy);

    globus_xio_driver_string_cntl_set_table(driver, rate_l_string_opts_table);

    *out_driver = driver;

    return GLOBUS_SUCCESS;
}

static void
globus_l_xio_rate_destroy(
    globus_xio_driver_t                 driver)
{
    globus_xio_driver_destroy(driver);
}

GlobusXIODefineDriver(
    rate,
    globus_l_xio_rate_init,
    globus_l_xio_rate_destroy);

static
int
globus_l_xio_rate_activate(void)
{
    int                                 rc;

    GlobusDebugInit(GLOBUS_XIO_RATE, TRACE);

    rc = globus_module_activate(GLOBUS_XIO_MODULE);
    if(rc == GLOBUS_SUCCESS)
    {
        GlobusXIORegisterDriver(rate);
    }
    globus_mutex_init(&xio_l_rate_hash_mutex, NULL);

    l_xio_rate_default_attr.read_attr.rate = DEFAULT_RATE;
    l_xio_rate_default_attr.read_attr.us_period = DEFAULT_PERIOD_US;
    l_xio_rate_default_attr.read_attr.burst_size = -1;

    l_xio_rate_default_attr.write_attr.rate = DEFAULT_RATE;
    l_xio_rate_default_attr.write_attr.us_period = DEFAULT_PERIOD_US;
    l_xio_rate_default_attr.write_attr.burst_size = -1;

    return rc;
}

static
int
globus_l_xio_rate_deactivate(void)
{
    globus_mutex_destroy(&xio_l_rate_hash_mutex);

    GlobusXIOUnRegisterDriver(rate);
    return globus_module_deactivate(GLOBUS_XIO_MODULE);
}


text:
/*import MaterialDateTimePicker from 'material-datetime-picker';*/
{

    let dp_soon = moment(Number($('.c-datepicker-input').val()));
    if(!dp_soon._isValid || dp_soon.valueOf() == 0) dp_soon = moment().add(2, 'h').minute(0);
    $('.c-datepicker-input').val( dp_soon.format('HH:mm YYYY/MM/DD') );

    const picker = new MaterialDatetimePicker({defualt: dp_soon, min: moment()}).on('submit', value => {
        if(value.valueOf() < Date.now()) value = moment().add(2, 'h').minute(0);
        $('.c-datepicker-input').val( value.format('HH:mm YYYY/MM/DD') );
    });

    $('.c-datepicker-input').focus( e => {
        e.preventDefault();
        picker.open();
    });

    $('.req-ing-table input[name="req_want"], .req-ing-table input[name="req_have"]').change(function(e){

        if($(this).attr('name') === 'req_want'){ //set the other to false
            $('input[name="req_have"][value="'+$(this).attr('value')+'"]').prop('checked', false);
        } else {
            $('input[name="req_want"][value="'+$(this).attr('value')+'"]').prop('checked', false);
        }

        setTimeout(()=>{
            $('.req-have-table tbody tr, .req-want-table tbody tr').remove();
            $('.req-ing-table input[name="req_want"]:checked').each(function(){
                $('.req-want-table tbody').append('
'+$(this).attr('value')+'
');
            });
            $('.req-ing-table input[name="req_have"]:checked').each(function(){
                $('.req-have-table tbody').append('
'+$(this).attr('value')+'
');
            });
            $('.req-have-table tbody tr td').click(function(){
                $('input[name="req_have"][value="'+$(this).text()+'"]').prop('checked', false);
                $(this).remove();
            });
            $('.req-want-table tbody tr td').click(function(){
                $('input[name="req_want"][value="'+$(this).text()+'"]').prop('checked', false);
                $(this).remove();
            });
        }, 50);
    });

    $('input#req-ing-search').keyup(function(){
        if($(this).val().trim() !== ''){
            $('.req-ing-table tbody tr').hide();
            $('.req-ing-table tbody tr[data-text*="'+$(this).val()+'"]').show();
        } else {
            $('.req-ing-table tbody tr').show();
        }
    });

    $('button[type="submit"]').click(() => {
        $('input#req-end').val(new Date($('input#req-end').val()).getTime());
    });

}

var initMap = function(){

    // setup objects //
    let geocoder = new google.maps.Geocoder();
    let autocomplete = new google.maps.places.Autocomplete(document.getElementById('req-loc'), {componentRestrictions: {country: 'au'}});

    let getLoc = new google.maps.LatLng( -26.0906899, 128.1506632);

    let map = new google.maps.Map(document.getElementById('req_getLocMap'), {
      center: getLoc,
      zoom: 5
    });

    let marker = new google.maps.Marker({
        map,
        position: getLoc
    });

    let circle = new google.maps.Circle({
        map,
        center: getLoc,
        radius: (Number($('input#req-dist').val()) || 2) * 1000,
        fillColor: "#004445",
        fillOpacity: 0.5,
        strokeWeight: 0,
        clickable: false
    });

    // setup helper functions //

    let updatePos = (e, dontName = false)=>{
        if(dontName){
            getLoc = e.latLng;
            marker.setPosition(getLoc);
            circle.setCenter(getLoc);
            map.setCenter(getLoc);
            $('input#req-lat').val(getLoc.lat());
            $('input#req-long').val(getLoc.lng());
        } else {
            geocoder.geocode( { location: e.latLng}, (results, status) => {
                if (status == 'OK') {
                    updatePos({latLng: results[0].geometry.location}, true);
                    $('input#req-loc').val(results[0].formatted_address);
                } else {
                    console.log(status);
                    updatePos({latLng: e.latLng});
                }
                map.setZoom(14);
            });
        }
    };

    let geoErr = (hasGeo) => {
        if(hasGeo) swal('Error', 'You must allow location permission.', 'error');
        else swal('Error', 'Unfortunately your browser does not support getting your location, try using firefox or chrome.', 'error');
    }

    // handle events //

    map.addListener('click', updatePos);

    $('button.getloc').click( e => {
        e.preventDefault();
        if (navigator.geolocation) {
            navigator.geolocation.getCurrentPosition(position => {
                let geoloc = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
                updatePos({latLng: geoloc});
            }, ()=> {
                geoErr(true);
            });
        } else geoErr(false);
    });

    $('input#req-dist').change( () => {
        circle.setRadius((Number($('input#req-dist').val()) || 2) * 1000);
    });

    $('input#req-loc').change( e => {
        setTimeout( ()=>{
            geocoder.geocode( { address: $('input#req-loc').val(), region: 'au'}, (results, status) => {
                if (status == 'OK') {
                    updatePos({latLng: results[0].geometry.location}, true);
                    console.log(results);
                    //$('input#req-loc').val(results[0].formatted_address);
                } else {
                    alert('Adress lookup failed. ' + status);
                }
                map.setZoom(14);
            });
        }, 100);
    });

    // load passed lat-long if passed
    if(
        $('input#req-lat').val() !== "" &&
        !isNaN(Number($('input#req-lat').val())) &&
        $('input#req-long').val() !== "" &&
        !isNaN(Number($('input#req-long').val()))
    ){
        updatePos({
            latLng: new google.maps.LatLng(Number($('input#req-lat').val()), Number($('input#req-long').val()))
        });
    }
};


text:
function [] = cos_recursion_stefan_assignment_1()

% A simple function that recursively calculates cos(N*x)
% and plots the result vs. N. It also plots the error factor
% Nsin(N*x)/sin(x) as well as the ratio between the two.

close all
clear all

% x is the starting value for the recursion.
% Values in N are the number of steps in the recursion.
% cos(N * x) is the final value (approximately) computed.

x = 1e-6;
N = 10.^[2:7];

% Define the iteration operator Mx, which takes us from the
% vector:
%
% [cos(M * x) ; cos((M-1) * x)]
%
% to the vector:
%
% [cos((M+1) * x) ; cos(M * x)]
%
% and which is based on the cosine recursion formula:
%
% cos((M+1) * x) = 2 * cos(x) * cos(M * x) - cos((M-1) * x)

Mx = [2 * cos(x) , -1 ; 1 , 0];

% Perform the calculation for each value n in N, then store
% the result in an array of length(N) called recursionResults

recursionResults = zeros(1,length(N));

% Store the error factor n * sin(n * x) / sin(x) for each n in N

errorFactors = zeros(1,length(N));

k=1;
for n = N

    % Define a vector cx to iterate over; since we are not interested
    % in intermediate steps at the moment, save resources by making
    % it a two-vector with initial value:
    %
    % [cos(x) ; cos(0)]
    %
    % and iterate N-1 times to get final value:
    %
    % [cos(N * x) ; cos((N-1) * x)]

    cx = [cos(x) ; 1];

    % Now, calculate the above result as Mx^(N-1).
    %
    % Since I am not sure how MATLAB implements matrix powers and want
    % to avoid any funny business that would ruin my precious epsilon
    % measurements, I will implement this matrix product with a loop.

    i=1;
    while i < n                    % i and M start at 1...
        cx = Mx * cx;              % ...iterate M by +1...
        i = i + 1;                 % ...iterate i by +1...
    end                            % ...i and M end at n

    recursionResults(k) = cx(1);   % put cos(n * x) in result vector
    errorFactors(k) = n * sin(n * x) / sin(x);
    k = k + 1;

end

% Calculate ratio between recursionResults and errorFactors.

ratios = recursionResults ./ errorFactors;

h = figure('DefaultLineLineWidth', 2,'DefaultLineMarkerSize',15,...
    'DefaultTextFontSize', 18,'DefaultTextFontWeight','bold',...
    'DefaultAxesFontSize', 16);
semilogy(N,recursionResults);
hold all;
semilogy(N,errorFactors);
hold all;
semilogy(N,ratios);

% Legend string

lg = {['recursion results'];['error factor'];['ratio']};

xlabel('Number of iterations, N','FontSize',18);
ylabel('Calculated value of cos(nx)');
legend(lg,'Location','NorthWest');
hold all;

print(h, '-dpdf', [ 'cos_recursion_stefan' '.pdf' ]);


text:
package com.facebook.internal;

import android.content.Context;
import android.graphics.*;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.TextView;
import com.facebook.android.R;

import com.freshplanet.ane.AirFacebook.AirFacebookExtension;

/**
 * com.facebook.internal is solely for the use of other packages within the Facebook SDK for Android. Use of
 * any of the classes in this package is unsupported, and they may be modified or removed without warning at
 * any time.
 */
public class LikeBoxCountView extends FrameLayout {

    public enum LikeBoxCountViewCaretPosition {
        LEFT,
        TOP,
        RIGHT,
        BOTTOM
    }

    private TextView likeCountLabel;
    private LikeBoxCountViewCaretPosition caretPosition = LikeBoxCountViewCaretPosition.LEFT;

    private float caretHeight;
    private float caretWidth;
    private float borderRadius;
    private Paint borderPaint;
    private int textPadding;
    private int additionalTextPadding;

    /**
     * Constructor
     *
     * @param context Context for this View
     */
    public LikeBoxCountView(Context context) {
        super(context);
        initialize(context);
    }

    /**
     * Sets the text for this view
     * @param text
     */
    public void setText(String text) {
        likeCountLabel.setText(text);
    }

    /**
     * Sets the caret's position. This will trigger a layout of the view.
     * @param caretPosition
     */
    public void setCaretPosition(LikeBoxCountViewCaretPosition caretPosition) {
        this.caretPosition = caretPosition;

        // Since the presence of a caret will move that edge closer to the text, let's add
        // some padding (equal to caretHeight) in that same direction
        switch (caretPosition) {
            case LEFT:
                setAdditionalTextPadding(additionalTextPadding, 0, 0, 0);
                break;
            case TOP:
                setAdditionalTextPadding(0, additionalTextPadding, 0, 0);
                break;
            case RIGHT:
                setAdditionalTextPadding(0, 0, additionalTextPadding, 0);
                break;
            case BOTTOM:
                setAdditionalTextPadding(0, 0, 0, additionalTextPadding);
                break;
        }

    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);

        int top = getPaddingTop(), left = getPaddingLeft();
        int right = getWidth() - getPaddingRight(), bottom = getHeight() - getPaddingBottom();

        switch (caretPosition) {
            case BOTTOM:
                bottom -= caretHeight;
                break;
            case LEFT:
                left += caretHeight;
                break;
            case TOP:
                top += caretHeight;
                break;
            case RIGHT:
                right -= caretHeight;
                break;
        }

        drawBorder(canvas, left, top, right, bottom);
    }

    private void initialize(Context context) {
        setWillNotDraw(false); // Required for the onDraw() method to be called on a FrameLayout
        caretHeight = getResources().getDimension(AirFacebookExtension.getResourceId("dimen.com_facebook_likeboxcountview_caret_height"));
        caretWidth = getResources().getDimension(AirFacebookExtension.getResourceId("dimen.com_facebook_likeboxcountview_caret_width"));
        borderRadius = getResources().getDimension(AirFacebookExtension.getResourceId("dimen.com_facebook_likeboxcountview_border_radius"));

        borderPaint = new Paint();
        borderPaint.setColor(getResources().getColor(AirFacebookExtension.getResourceId("color.com_facebook_likeboxcountview_border_color")));
        borderPaint.setStrokeWidth(getResources().getDimension(AirFacebookExtension.getResourceId("dimen.com_facebook_likeboxcountview_border_width")));
        borderPaint.setStyle(Paint.Style.STROKE);

        initializeLikeCountLabel(context);

        addView(likeCountLabel);

        setCaretPosition(this.caretPosition);
    }

    private void initializeLikeCountLabel(Context context) {
        likeCountLabel = new TextView(context);
        LayoutParams likeCountLabelLayoutParams = new LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.MATCH_PARENT);
        likeCountLabel.setLayoutParams(likeCountLabelLayoutParams);
        likeCountLabel.setGravity(Gravity.CENTER);
        likeCountLabel.setTextSize(
                TypedValue.COMPLEX_UNIT_PX,
                getResources().getDimension(AirFacebookExtension.getResourceId("dimen.com_facebook_likeboxcountview_text_size")));
        likeCountLabel.setTextColor(getResources().getColor(AirFacebookExtension.getResourceId("color.com_facebook_likeboxcountview_text_color")));
        textPadding = getResources().getDimensionPixelSize(AirFacebookExtension.getResourceId("dimen.com_facebook_likeboxcountview_text_padding"));

        // Calculate the additional text padding that will be applied in the direction of the caret.
        additionalTextPadding = getResources().getDimensionPixelSize(AirFacebookExtension.getResourceId("dimen.com_facebook_likeboxcountview_caret_height"));
    }

    private void setAdditionalTextPadding(int left, int top, int right, int bottom) {
        likeCountLabel.setPadding(
                textPadding + left,
                textPadding + top,
                textPadding + right,
                textPadding + bottom);
    }

    private void drawBorder(Canvas canvas, float left, float top, float right, float bottom) {
        Path borderPath = new Path();

        float ovalSize = 2.0f * borderRadius;

        // Top left corner
        borderPath.addArc(new RectF(left, top, left + ovalSize, top + ovalSize), -180, 90);

        // Top caret
        if (caretPosition == LikeBoxCountViewCaretPosition.TOP) {
            borderPath.lineTo(left + (right - left - caretWidth) / 2, top);
            borderPath.lineTo(left + (right - left) / 2, top - caretHeight);
            borderPath.lineTo(left + (right - left + caretWidth) / 2, top);
        }

        // Move to top right corner
        borderPath.lineTo(right - borderRadius, top);

        // Top right corner
        borderPath.addArc(new RectF(right - ovalSize, top, right, top + ovalSize), -90, 90);

        // Right caret
        if (caretPosition == LikeBoxCountViewCaretPosition.RIGHT) {
            borderPath.lineTo(right, top + (bottom - top - caretWidth) / 2);
            borderPath.lineTo(right + caretHeight, top + (bottom - top) / 2);
            borderPath.lineTo(right, top + (bottom - top + caretWidth) / 2);
        }

        // Move to bottom right corner
        borderPath.lineTo(right, bottom - borderRadius);

        // Bottom right corner
        borderPath.addArc(new RectF(right - ovalSize, bottom - ovalSize, right, bottom), 0, 90);

        // Bottom caret
        if (caretPosition == LikeBoxCountViewCaretPosition.BOTTOM) {
            borderPath.lineTo(left + (right - left + caretWidth) / 2, bottom);
            borderPath.lineTo(left + (right - left) / 2, bottom + caretHeight);
            borderPath.lineTo(left + (right - left - caretWidth) / 2, bottom);
        }

        // Move to bottom left corner
        borderPath.lineTo(left + borderRadius, bottom);

        // Bottom left corner
        borderPath.addArc(new RectF(left, bottom - ovalSize, left + ovalSize, bottom), 90, 90);

        // Left caret
        if (caretPosition == LikeBoxCountViewCaretPosition.LEFT) {
            borderPath.lineTo(left, top + (bottom - top + caretWidth) / 2);
            borderPath.lineTo(left - caretHeight, top + (bottom - top) / 2);
            borderPath.lineTo(left, top + (bottom - top - caretWidth) / 2);
        }

        // Move back to the beginning
        borderPath.lineTo(left, top + borderRadius);

        canvas.drawPath(borderPath, borderPaint);
    }
}


text:
class AddFollowingActivitiesToUser < ActiveRecord::Migration
  def change
    add_column :users, :following_activities, :integer, array: true, default: '{}'
  end
end


text:
enum class WindowOpenDisposition {
  UNKNOWN,
  CURRENT_TAB,
  // Indicates that only one tab with the url should exist in the same window.
  SINGLETON_TAB,
  NEW_FOREGROUND_TAB,
  NEW_BACKGROUND_TAB,
  NEW_POPUP,
  NEW_WINDOW,
  SAVE_TO_DISK,
  OFF_THE_RECORD,
  IGNORE_ACTION,
  // Activates an existing tab containing the url, rather than navigating.
  // This is similar to SINGLETON_TAB, but searches across all windows from
  // the current profile and anonymity (instead of just the current one);
  // closes the current tab on switching if the current tab was the NTP with
  // no session history; and behaves like CURRENT_TAB instead of
  // NEW_FOREGROUND_TAB when no existing tab is found.
  SWITCH_TO_TAB,
  // Creates a new document picture-in-picture window showing a child WebView.
  NEW_PICTURE_IN_PICTURE,
  // Update when adding a new disposition.
  MAX_VALUE = NEW_PICTURE_IN_PICTURE,
};

namespace ui {

// Translates event flags from a click on a link into the user's desired window
// disposition.  For example, a middle click would mean to open a background
// tab.  |disposition_for_current_tab| is the disposition to return if the flags
// suggest opening in the current tab; for example, a caller could set this to
// NEW_FOREGROUND_TAB to prevent a click from overwriting the current tab by
// default.
COMPONENT_EXPORT(UI_BASE)
WindowOpenDisposition DispositionFromClick(
    bool middle_button,
    bool alt_key,
    bool ctrl_key,
    bool meta_key,
    bool shift_key,
    WindowOpenDisposition disposition_for_current_tab =
        WindowOpenDisposition::CURRENT_TAB);

// As with DispositionFromClick(), but using |event_flags| as in ui::MouseEvent.
COMPONENT_EXPORT(UI_BASE)
WindowOpenDisposition DispositionFromEventFlags(
    int event_flags,
    WindowOpenDisposition disposition_for_current_tab =
        WindowOpenDisposition::CURRENT_TAB);

}  // namespace ui

#endif  // UI_BASE_WINDOW_OPEN_DISPOSITION_H_


text:
We support the following platforms:
- [Linux](#Linux)
- [Windows](#Windows)
- [MacOS](#MacOS)

# Linux

## Prerequisite
- [OpenBLAS](http://www.openblas.net/)
- or [MKL](https://software.intel.com/en-us/intel-mkl)

Our wrapper is able to run without these prerequisites, but may be very slow.

For GPU version, also install
- [CUDA SDK](https://developer.nvidia.com/cuda-75-downloads-archive)

CUDA 7.5 is testified. Try the latest version on your own risk.

## Install torch core
Next we are going to install torch's kernel libraries: TH, THNN, THC, THCUNN. Make sure all the kernel libraries are under the same folder:
```
/usr/local/cpp-torch/ (you can change it to your own location)
├─ torch7 (TH)
├─ nn (THNN)
├─ cutorch (THC, for GPU version)
└─ cunn (THCUNN, for GPU version)
```

### TH
The following commands install a modified version of torch's TH library.
```
git clone https://github.com/tuotuoxp/torch7.git
cd torch7
mkdir build
cd build
cmake -DCMAKE_BUILD_TYPE=Release -DCMAKE_INSTALL_PREFIX=/usr/local/cpp-torch ../lib/TH
make
make install
cd ../../
```
Code and logic of the original library is intact. We only strip its dependency on torch.

### THNN
The following commands install a modified version of torch's THNN library.
```
git clone https://github.com/tuotuoxp/nn.git
cd nn
mkdir build
cd build
cmake -DCMAKE_BUILD_TYPE=Release -DCMAKE_INSTALL_PREFIX=/usr/local/cpp-torch -DCMAKE_PREFIX_PATH=/usr/local/cpp-torch ../lib/THNN
make
make install
cd ../../
```
Same as previous, we only modify the dependency of the library.

### THC
> If only CPU version is required, ignore this step.

The following commands install a modified version of torch's THC library.
```
git clone https://github.com/tuotuoxp/cutorch.git
cd cutorch
mkdir build
cd build
cmake -DCMAKE_BUILD_TYPE=Release -DCMAKE_INSTALL_PREFIX=/usr/local/cpp-torch -DCMAKE_PREFIX_PATH=/usr/local/cpp-torch ../lib/THC
make
make install
cd ../../
```
Same as previous, we only modify the dependency of the library.
It takes about half an hour the finish the compilpation. Please kindly ignore the warnings.

### THCUNN
> If only CPU version is required, ignore this step.

The following commands install a modified version of torch's THCUNN library.
```
git clone https://github.com/tuotuoxp/cunn.git
cd cunn
mkdir build
cd build
cmake -DCMAKE_BUILD_TYPE=Release -DCMAKE_INSTALL_PREFIX=/usr/local/cpp-torch -DCMAKE_PREFIX_PATH=/usr/local/cpp-torch ../lib/THCUNN
make
make install
cd ../../
```
Same as previous, we only modify the dependency of the library.
Please kindly ignore the warnings.

## Install torch wrapper
The following commands install our C++ wrapper: cpp-torch to replace the lua wrapper in original torch.

Wrapper is under the same directory as core libraries.
```
/usr/local/cpp-torch/ (you can change it to your own location)
├─ torch7 (TH)
├─ nn (THNN)
├─ cutorch (THC, for GPU version)
├─ cunn (THCUNN, for GPU version)
└─ cpp-torch (C++ wrapper)
```

For CPU version:
```
git clone https://github.com/tuotuoxp/cpp-torch
cd cpp-torch
mkdir build
cd build
cmake -DCMAKE_INSTALL_PREFIX=/usr/local/cpp-torch -DCMAKE_PREFIX_PATH=/usr/local/cpp-torch ..
make
make install
cd ../../
```

For GPU version, set -DBUILD_CUDA=ON:
```
git clone https://github.com/tuotuoxp/cpp-torch
cd cpp-torch
mkdir build
cd build
cmake -DBUILD_CUDA=ON -DCMAKE_INSTALL_PREFIX=/usr/local/cpp-torch -DCMAKE_PREFIX_PATH=/usr/local/cpp-torch ..
make
make install
cd ../../
```

## Test it!
Use the following commands to create a simple example to test your installation.
```
cd cpp-torch/example/basic
cmake -DCMAKE_PREFIX_PATH=/usr/local/cpp-torch .
make
```
Run the generated demo in command line:
```
./cpptorch_demo
```
It should yield the following output:
```
nn.Linear

 12
 13
[torch.FloatTensor of size 2]

 12
 13
[torch.FloatTensor of size 2]
```

# Windows
## Prerequisite
- [CMake](https://cmake.org/), remember to add CMake to PATH
- [Visual Studio 2015](https://www.visualstudio.com/downloads/)

For GPU version, also install
- [CUDA SDK](https://developer.nvidia.com/cuda-75-downloads-archive)

CUDA 7.5 is testied. Try the latest version on your own risk.

## Install torch core
Next we are going to install torch's kernel libraries: TH, THNN, THC, THCUNN. Make sure all the kernel libraries are under the same folder:
```
D:\cpp-torch\ (you can change it to your own place)
├─ torch7 (TH)
├─ nn (THNN)
├─ cutorch (THC, for GPU version)
└─ cunn (THCUNN, for GPU version)
```
All the following commands are run using `VS2015 x64 Native Tools Command Prompt`.

### TH
The following commands install a modified version of torch's TH library.
```
git clone https://github.com/tuotuoxp/torch7.git
cd torch7
mkdir build
cd build
cmake -G "NMake Makefiles" -DCMAKE_BUILD_TYPE=Release -DCMAKE_INSTALL_PREFIX=..\..\install ..\lib\TH
nmake
nmake install
cd ..\..\
```
Code and logic of the original library is intact. We only strip its dependency on torch.

### THNN
The following commands install a modified version of torch's THNN library.
```
git clone https://github.com/tuotuoxp/nn.git
cd nn
mkdir build
cd build
cmake -G "NMake Makefiles" -DCMAKE_BUILD_TYPE=Release -DCMAKE_INSTALL_PREFIX=..\..\install -DCMAKE_PREFIX_PATH=..\..\install ..\lib\THNN
nmake
nmake install
cd ..\..\
```
Same as previous, we only modify the dependency of the library.

### THC
> If only CPU version is required, ignore this step.

```
git clone https://github.com/tuotuoxp/cutorch.git
cd cutorch
mkdir build
cd build
cmake -G "NMake Makefiles" -DCMAKE_BUILD_TYPE=Release -DCMAKE_INSTALL_PREFIX=..\..\install -DCMAKE_PREFIX_PATH=..\..\install ..\lib\THC
nmake install
cd ..\..\
```
Same as previous, we only modify the dependency of the library. It takes about half an hour the finish the compilpation. Please kindly ignore the warnings.

### THCUNN
> If only CPU version is required, ignore this step.

```
git clone https://github.com/tuotuoxp/cunn.git
cd cunn
mkdir build
cd build
cmake -G "NMake Makefiles" -DCMAKE_BUILD_TYPE=Release -DCMAKE_INSTALL_PREFIX=..\..\install -DCMAKE_PREFIX_PATH=..\..\install ..\lib\THCUNN
nmake install
cd ..\..\
```
Same as previous, we only modify the dependency of the library. Please kindly ignore the warnings.

## Install torch wrapper
The following commands install our C++ wrapper: cpp-torch to replace the lua wrapper in original torch.

Wrapper is under the same directory as core libraries.
```
├─ torch7 (TH)
├─ nn (THNN)
├─ cutorch (THC, for GPU version)
├─ cunn (THCUNN, for GPU version)
└─ cpp-torch (C++ wrapper)
```

For CPU version:
```
git clone https://github.com/tuotuoxp/cpp-torch
cd cpp-torch
mkdir build
cd build
cmake -G "NMake Makefiles" -DCMAKE_INSTALL_PREFIX=..\..\install -DCMAKE_PREFIX_PATH=..\..\install ..
nmake
nmake install
cd ..\..\
```

For GPU version, set -DBUILD_CUDA=ON:
```
git clone https://github.com/tuotuoxp/cpp-torch
cd cpp-torch
mkdir build
cd build
cmake -DBUILD_CUDA=ON -DCMAKE_INSTALL_PREFIX=..\..\install -DCMAKE_PREFIX_PATH=..\..\install ..
make
make install
cd ..\..\
```

## Test it!
Use the following commands to create a simple VS 2015 solution to test your installation.
```
cd cpp-torch\example\basic
cmake -G "Visual Studio 14 2015 Win64" -DCMAKE_PREFIX_PATH=..\..\..\install .
```

Copy TH.dll, THNN.dll and cpptorch.dll from `cpp-torch\install\bin\` to project's binary folder `cpp-torch\example\basic\Debug\` and `cpp-torch\example\basic\Release\`.

Open solution with Visual Studio 2015, run cpptorch_demo project. It should yield the following output:
```
nn.Linear

 12
 13
[torch.FloatTensor of size 2]

 12
 13
[torch.FloatTensor of size 2]
```

# MacOS

## Prerequisite
- [XCode](http://developer.apple.com/xcode/)

## Install
Same as Linux CPU version.

## Test it!
Use the following commands to create a simple XCode solution to test your installation.
```
cd cpp-torch/example/basic
cmake -G "Xcode" -DCMAKE_PREFIX_PATH=../../../install .
```

Open solution with XCode, build and run cpptorch_demo project. It should yield the following output:
```
nn.Linear

 12
 13
[torch.FloatTensor of size 2]

 12
 13
[torch.FloatTensor of size 2]
```