text:
var env, store, User, Message, Post, Contact, Comment, Book, Chapter, Author, NewMessage;
var get = Ember.get;
var run = Ember.run;

var attr = DS.attr;
var hasMany = DS.hasMany;
var belongsTo = DS.belongsTo;
var hash = Ember.RSVP.hash;

// Before https://github.com/emberjs/ember.js/pull/10323 the computed
// property descriptor was stored on the ember meta object. After that
// pr it was moved to the ember object. This code normalized that
// lookup because the Ember Data ci tests run against diferent version
// of Ember. Once that code reaches the release branch this code can
// be removed.
function getComputedPropertyDesc(model, key) {
  if (Ember.meta(model).descs) {
    return Ember.meta(model).descs[key];
  }
  var possibleDesc = model[key];
  var desc = (possibleDesc !== null && typeof possibleDesc === 'object' && possibleDesc.isDescriptor) ? possibleDesc : undefined;
  return desc;
}

module("integration/relationship/belongs_to Belongs-To Relationships", {
  setup: function() {
    User = DS.Model.extend({
      name: attr('string'),
      messages: hasMany('message', { polymorphic: true }),
      favouriteMessage: belongsTo('message', { polymorphic: true, inverse: null })
    });

    Message = DS.Model.extend({
      user: belongsTo('user', { inverse: 'messages' }),
      created_at: attr('date')
    });

    Post = Message.extend({
      title: attr('string'),
      comments: hasMany('comment')
    });

    Comment = Message.extend({
      body: DS.attr('string'),
      message: DS.belongsTo('message', { polymorphic: true })
    });

    Book = DS.Model.extend({
      name: attr('string'),
      author: belongsTo('author'),
      chapters: hasMany('chapters')
    });

    Chapter = DS.Model.extend({
      title: attr('string'),
      belongsTo: belongsTo('book')
    });

    Author = DS.Model.extend({
      name: attr('string'),
      books: hasMany('books')
    });

    env = setupStore({
      user: User,
      post: Post,
      comment: Comment,
      message: Message,
      book: Book,
      chapter: Chapter,
      author: Author
    });

    env.registry.optionsForType('serializer', { singleton: false });
    env.registry.optionsForType('adapter', { singleton: false });

    env.registry.register('serializer:user', DS.JSONSerializer.extend({
      attrs: {
        favouriteMessage: { embedded: 'always' }
      }
    }));

    store = env.store;

    User    = store.modelFor('user');
    Post    = store.modelFor('post');
    Comment = store.modelFor('comment');
    Message = store.modelFor('message');
    Book    = store.modelFor('book');
    Chapter = store.modelFor('chapter');
    Author  = store.modelFor('author');
  },

  teardown: function() {
    run(env.container, 'destroy');
  }
});

test("The store can materialize a non loaded monomorphic belongsTo association", function() {
  expect(1);

  env.store.modelFor('post').reopen({
    user: DS.belongsTo('user', {
      async: true,
      inverse: 'messages'
    })
  });

  env.adapter.find = function(store, type, id, snapshot) {
    ok(true, "The adapter's find method should be called");
    return Ember.RSVP.resolve({
      id: 1
    });
  };

  run(function() {
    env.store.push('post', {
      id: 1,
      user: 2
    });
  });

  run(function() {
    env.store.find('post', 1).then(function(post) {
      post.get('user');
    });
  });
});

test("Only a record of the same type can be used with a monomorphic belongsTo relationship", function() {
  expect(1);

  run(function() {
    store.push('post', { id: 1 });
    store.push('comment', { id: 2 });
  });

  run(function() {
    hash({
      post: store.find('post', 1),
      comment: store.find('comment', 2)
    }).then(function(records) {
      expectAssertion(function() {
        records.post.set('user', records.comment);
      }, /You can only add a 'user' record to this relationship/);
    });
  });
});

test("Only a record of the same base type can be used with a polymorphic belongsTo relationship", function() {
  expect(1);
  run(function() {
    store.push('comment', { id: 1 });
    store.push('comment', { id: 2 });
    store.push('post', { id: 1 });
    store.push('user', { id: 3 });
  });

  run(function() {
    var asyncRecords = hash({
      user: store.find('user', 3),
      post: store.find('post', 1),
      comment: store.find('comment', 1),
      anotherComment: store.find('comment', 2)
    });

    asyncRecords.then(function(records) {
      var comment = records.comment;

      comment.set('message', records.anotherComment);
      comment.set('message', records.post);
      comment.set('message', null);

      expectAssertion(function() {
        comment.set('message', records.user);
      }, /You cannot add a 'user' record to the 'comment.message'. You can only add a 'message' record to this relationship./);
    });
  });
});

test("The store can load a polymorphic belongsTo association", function() {
  run(function() {
    env.store.push('post', { id: 1 });
    env.store.push('comment', { id: 2, message: 1, messageType: 'post' });
  });

  run(function() {
    hash({
      message: store.find('post', 1),
      comment: store.find('comment', 2)
    }).then(function(records) {
      equal(records.comment.get('message'), records.message);
    });
  });
});

test("The store can serialize a polymorphic belongsTo association", function() {
  var serializerInstance = store.serializerFor('comment');

  serializerInstance.serializePolymorphicType = function(record, json, relationship) {
    ok(true, "The serializer's serializePolymorphicType method should be called");
    json["message_type"] = "post";
  };
  run(function() {
    env.store.push('post', { id: 1 });
    env.store.push('comment', { id: 2, message: 1, messageType: 'post' });

    store.find('comment', 2).then(function(comment) {
      var serialized = store.serialize(comment, { includeId: true });
      equal(serialized['message'], 1);
      equal(serialized['message_type'], 'post');
    });
  });
});

test("A serializer can materialize a belongsTo as a link that gets sent back to findBelongsTo", function() {
  var Group = DS.Model.extend({
    people: DS.hasMany()
  });

  var Person = DS.Model.extend({
    group: DS.belongsTo({ async: true })
  });

  env.registry.register('model:group', Group);
  env.registry.register('model:person', Person);

  run(function() {
    store.push('person', { id: 1, links: { group: '/people/1/group' } });
  });

  env.adapter.find = function(store, type, id, snapshot) {
    throw new Error("Adapter's find method should not be called");
  };

  env.adapter.findBelongsTo = async(function(store, snapshot, link, relationship) {
    equal(relationship.type, 'group');
    equal(relationship.key, 'group');
    equal(link, "/people/1/group");

    return Ember.RSVP.resolve({ id: 1, people: [1] });
  });

  run(function() {
    env.store.find('person', 1).then(function(person) {
      return person.get('group');
    }).then(function(group) {
      ok(group instanceof Group, "A group object is loaded");
      ok(group.get('id') === '1', 'It is the group we are expecting');
    });
  });
});

test('A record with an async belongsTo relationship always returns a promise for that relationship', function () {
  var Seat = DS.Model.extend({
    person: DS.belongsTo('person')
  });

  var Person = DS.Model.extend({
    seat: DS.belongsTo('seat', { async: true })
  });

  env.registry.register('model:seat', Seat);
  env.registry.register('model:person', Person);

  run(function() {
    store.push('person', { id: 1, links: { seat: '/people/1/seat' } });
  });

  env.adapter.find = function(store, type, id, snapshot) {
    throw new Error("Adapter's find method should not be called");
  };

  env.adapter.findBelongsTo = async(function(store, snapshot, link, relationship) {
    return Ember.RSVP.resolve({ id: 1 });
  });

  run(function() {
    env.store.find('person', 1).then(function(person) {
      person.get('seat').then(function(seat) {
        // this assertion fails too
        // ok(seat.get('person') === person, 'parent relationship should be populated');
        seat.set('person', person);
        ok(person.get('seat').then, 'seat should be a PromiseObject');
      });
    });
  });
});

test("A record with an async belongsTo relationship returning null should resolve null", function() {
  expect(1);

  var Group = DS.Model.extend({
    people: DS.hasMany()
  });

  var Person = DS.Model.extend({
    group: DS.belongsTo({ async: true })
  });

  env.registry.register('model:group', Group);
  env.registry.register('model:person', Person);

  run(function() {
    store.push('person', { id: 1, links: { group: '/people/1/group' } });
  });

  env.adapter.find = function(store, type, id, snapshot) {
    throw new Error("Adapter's find method should not be called");
  };

  env.adapter.findBelongsTo = async(function(store, snapshot, link, relationship) {
    return Ember.RSVP.resolve(null);
  });

  env.store.find('person', 1).then(async(function(person) {
    return person.get('group');
  })).then(async(function(group) {
    ok(group === null, "group should be null");
  }));
});

test("A record can be created with a resolved belongsTo promise", function() {
  expect(1);

  var Group = DS.Model.extend({
    people: DS.hasMany()
  });

  var Person = DS.Model.extend({
    group: DS.belongsTo({ async: true })
  });

  env.registry.register('model:group', Group);
  env.registry.register('model:person', Person);

  var group;
  run(function() {
    group = store.push('group', { id: 1 });
  });

  var groupPromise = store.find('group', 1);
  groupPromise.then(async(function(group) {
    var person = env.store.createRecord('person', {
      group: groupPromise
    });
    equal(person.get('group.content'), group);
  }));
});

test("polymorphic belongsTo type-checks check the superclass when MODEL_FACTORY_INJECTIONS is enabled", function() {
  expect(1);

  var injectionValue = Ember.MODEL_FACTORY_INJECTIONS;
  Ember.MODEL_FACTORY_INJECTIONS = true;

  try {
    run(function () {
      var igor = env.store.createRecord('user', { name: 'Igor' });
      var post = env.store.createRecord('post', { title: "Igor's unimaginative blog post" });

      igor.set('favouriteMessage', post);

      equal(igor.get('favouriteMessage.title'), "Igor's unimaginative blog post");
    });
  } finally {
    Ember.MODEL_FACTORY_INJECTIONS = injectionValue;
  }
});

test("the subclass in a polymorphic belongsTo relationship is an instanceof its superclass", function() {
  expect(1);

  var injectionValue = Ember.MODEL_FACTORY_INJECTIONS;
  Ember.MODEL_FACTORY_INJECTIONS = true;

  try {
    run(function () {
      var message = env.store.createRecord('message', { id: 1 });
      var comment = env.store.createRecord('comment', { id: 2, message: message });
      ok(comment instanceof Message, 'a comment is an instance of a message');
    });

  } finally {
    Ember.MODEL_FACTORY_INJECTIONS = injectionValue;
  }
});

test("relationshipsByName does not cache a factory", function() {

  // The model is loaded up via a container. It has relationshipsByName
  // called on it.
  var modelViaFirstFactory = store.modelFor('user');
  get(modelViaFirstFactory, 'relationshipsByName');

  // An app is reset, or the container otherwise destroyed.
  run(env.container, 'destroy');

  // A new model for a relationship is created. Note that this may happen
  // due to an extend call internal to MODEL_FACTORY_INJECTIONS.
  NewMessage = Message.extend();

  // A new store is created.
  env = setupStore({
    user: User,
    message: NewMessage
  });
  store = env.store;

  // relationshipsByName is called again.
  var modelViaSecondFactory = store.modelFor('user');
  var relationshipsByName   = get(modelViaSecondFactory, 'relationshipsByName');
  var messageType           = relationshipsByName.get('messages').type;

  // A model is looked up in the store based on a string, via user input
  var messageModelFromStore        = store.modelFor('message');
  // And the model is lookup up internally via the relationship type
  var messageModelFromRelationType = store.modelFor(messageType);

  equal(messageModelFromRelationType, messageModelFromStore,
        "model factory based on relationship type matches the model based on store.modelFor");
});

test("relationshipsByName is cached in production", function() {
  var model = store.modelFor('user');
  var oldTesting = Ember.testing;
  //We set the cacheable to true because that is the default state for any CP and then assert that it
  //did not get dynamically changed when accessed
  var relationshipsByName = getComputedPropertyDesc(model, 'relationshipsByName');
  var oldCacheable = relationshipsByName._cacheable;
  relationshipsByName._cacheable = true;
  Ember.testing = false;
  try {
    equal(get(model, 'relationshipsByName'), get(model, 'relationshipsByName'), 'relationshipsByName are cached');
    equal(get(model, 'relationshipsByName'), get(model, 'relationshipsByName'), 'relationshipsByName are cached');
  } finally {
    Ember.testing = oldTesting;
    relationshipsByName._cacheable = oldCacheable;
  }
});

test("relatedTypes is cached in production", function() {
  var model = store.modelFor('user');
  var oldTesting = Ember.testing;
  //We set the cacheable to true because that is the default state for any CP and then assert that it
  //did not get dynamically changed when accessed
  var relatedTypes = getComputedPropertyDesc(model, 'relatedTypes');
  var oldCacheable = relatedTypes._cacheable;
  relatedTypes._cacheable = true;
  Ember.testing = false;
  try {
    equal(get(model, 'relatedTypes'), get(model, 'relatedTypes'), 'relatedTypes are cached');
    equal(get(model, 'relatedTypes'), get(model, 'relatedTypes'), 'relatedTypes are cached');
  } finally {
    Ember.testing = oldTesting;
    relatedTypes._cacheable = oldCacheable;
  }
});

test("relationships is cached in production", function() {
  var model = store.modelFor('user');
  var oldTesting = Ember.testing;
  //We set the cacheable to true because that is the default state for any CP and then assert that it
  //did not get dynamically changed when accessed
  var relationships = getComputedPropertyDesc(model, 'relationships');
  var oldCacheable = relationships._cacheable;
  relationships._cacheable = true;
  Ember.testing = false;
  try {
    equal(get(model, 'relationships'), get(model, 'relationships'), 'relationships are cached');
    equal(get(model, 'relationships'), get(model, 'relationships'), 'relationships are cached');
  } finally {
    Ember.testing = oldTesting;
    relationships._cacheable = oldCacheable;
  }
});

test("relationship changes shouldn't cause async fetches", function() {
  expect(2);

  /*  Scenario:
   *  ---------
   *
   *    post HM async comments
   *    comments bt sync post
   *
   *    scenario:
   *     - post hm C [1,2,3]
   *     - post has a partially realized comments array comment#1 has been realized
   *     - comment has not yet realized its post relationship
   *     - comment is destroyed
   */

  env.store.modelFor('post').reopen({
    comments: DS.hasMany('comment', {
      async: true,
      inverse: 'post'
    })
  });

  env.store.modelFor('comment').reopen({
    post: DS.belongsTo('post', {
    })
  });
  var post, comment;
  run(function() {
    post = env.store.push('post', {
      id: 1,
      comments: [1, 2, 3]
    });

    comment = env.store.push('comment', {
      id:   1,
      post: 1
    });
  });

  env.adapter.deleteRecord = function(store, type, snapshot) {
    ok(snapshot.record instanceof type);
    equal(snapshot.id, 1, 'should first comment');
    return snapshot.record.toJSON({ includeId: true });
  };

  env.adapter.findMany = function(store, type, ids, snapshots) {
    ok(false, 'should not need to findMay more comments, but attempted to anyways');
  };

  run(comment, 'destroyRecord');
});

test("Destroying a record with an unloaded aync belongsTo association does not fetch the record", function() {
  expect(2);
  var post;

  env.store.modelFor('message').reopen({
    user: DS.hasMany('user', {
      async: true
    })
  });

  env.store.modelFor('post').reopen({
    user: DS.belongsTo('user', {
      async: true,
      inverse: 'messages'
    })
  });

  run(function() {
    post = env.store.push('post', {
      id: 1,
      user: 2
    });
  });

  env.adapter.find = function(store, type, id, snapshot) {
    throw new Error("Adapter's find method should not be called");
  };

  env.adapter.deleteRecord = function(store, type, snapshot) {
    ok(snapshot.record instanceof type);
    equal(snapshot.id, 1, 'should first post');
    return {
      id: "1",
      title: null,
      created_at: null,
      user: "2"
    };
  };

  run(post, 'destroyRecord');
});

test("A sync belongsTo errors out if the record is unlaoded", function() {
  var message;
  run(function() {
    message = env.store.push('message', { id: 1, user: 2 });
  });

  expectAssertion(function() {
    message.get('user');
  }, /You looked up the 'user' relationship on a 'message' with id 1 but some of the associated records were not loaded. Either make sure they are all loaded together with the parent record, or specify that the relationship is async \(`DS.belongsTo\({ async: true }\)`\)/);
});

test("Rollbacking a deleted record restores implicit relationship - async", function () {
  Book.reopen({
    author: DS.belongsTo('author', { async: true })
  });
  var book, author;
  run(function() {
    book = env.store.push('book', { id: 1, name: "Stanley's Amazing Adventures", author: 2 });
    author = env.store.push('author', { id: 2, name: 'Stanley' });
  });
  run(function() {
    author.deleteRecord();
    author.rollback();
    book.get('author').then(function(fetchedAuthor) {
      equal(fetchedAuthor, author, 'Book has an author after rollback');
    });
  });
});

test("Rollbacking a deleted record restores implicit relationship - sync", function () {
  var book, author;
  run(function() {
    book = env.store.push('book', { id: 1, name: "Stanley's Amazing Adventures", author: 2 });
    author = env.store.push('author', { id: 2, name: 'Stanley' });
  });
  run(function() {
    author.deleteRecord();
    author.rollback();
  });
  equal(book.get('author'), author, 'Book has an author after rollback');
});

test("Passing a model as type to belongsTo should not work", function () {
  expect(1);

  expectAssertion(function() {
    User = DS.Model.extend();

    Contact = DS.Model.extend({
      user: belongsTo(User)
    });
  }, /The first argument to DS.belongsTo must be a string/);
});

test("belongsTo hasData async loaded", function () {
  expect(1);

  Book.reopen({
    author: belongsTo('author', { async: true })
  });

  env.adapter.find = function(store, type, id, snapshot) {
    return Ember.RSVP.resolve({ id: 1, name: 'The Greatest Book', author: 2 });
  };

  run(function() {
    store.find('book', 1).then(function(book) {
      var relationship = book._internalModel._relationships.get('author');
      equal(relationship.hasData, true, 'relationship has data');
    });
  });
});

test("belongsTo hasData sync loaded", function () {
  expect(1);

  env.adapter.find = function(store, type, id, snapshot) {
    return Ember.RSVP.resolve({ id: 1, name: 'The Greatest Book', author: 2 });
  };

  run(function() {
    store.find('book', 1).then(function(book) {
      var relationship = book._internalModel._relationships.get('author');
      equal(relationship.hasData, true, 'relationship has data');
    });
  });
});

test("belongsTo hasData async not loaded", function () {
  expect(1);

  Book.reopen({
    author: belongsTo('author', { async: true })
  });

  env.adapter.find = function(store, type, id, snapshot) {
    return Ember.RSVP.resolve({ id: 1, name: 'The Greatest Book', links: { author: 'author' } });
  };

  run(function() {
    store.find('book', 1).then(function(book) {
      var relationship = book._internalModel._relationships.get('author');
      equal(relationship.hasData, false, 'relationship does not have data');
    });
  });
});

test("belongsTo hasData sync not loaded", function () {
  expect(1);

  env.adapter.find = function(store, type, id, snapshot) {
    return Ember.RSVP.resolve({ id: 1, name: 'The Greatest Book' });
  };

  run(function() {
    store.find('book', 1).then(function(book) {
      var relationship = book._internalModel._relationships.get('author');
      equal(relationship.hasData, false, 'relationship does not have data');
    });
  });
});

test("belongsTo hasData async created", function () {
  expect(1);

  Book.reopen({
    author: belongsTo('author', { async: true })
  });

  run(function() {
    var book = store.createRecord('book', { name: 'The Greatest Book' });
    var relationship = book._internalModel._relationships.get('author');
    equal(relationship.hasData, true, 'relationship has data');
  });
});

test("belongsTo hasData sync created", function () {
  expect(1);

  run(function() {
    var book = store.createRecord('book', { name: 'The Greatest Book' });
    var relationship = book._internalModel._relationships.get('author');
    equal(relationship.hasData, true, 'relationship has data');
  });
});

test("Model's belongsTo relationship should not be created during model creation", function () {
  var user;
  run(function () {
    user = env.store.push('user', { id: 1 });
    ok(!user._internalModel._relationships.has('favouriteMessage'), 'Newly created record should not have relationships');
  });
});

test("Model's belongsTo relationship should be created during model creation if relationship passed in constructor", function () {
  var user, message;
  run(function () {
    message = env.store.createRecord('message');
    user = env.store.createRecord('user', {
      name: 'John Doe',
      favouriteMessage: message
    });
    ok(user._internalModel._relationships.has('favouriteMessage'), "Newly created record with relationships in params passed in its constructor should have relationships");
  });
});

test("Model's belongsTo relationship should be created during 'set' method", function () {
  var user, message;
  run(function () {
    message = env.store.createRecord('message');
    user = env.store.createRecord('user');
    user.set('favouriteMessage', message);
    ok(user._internalModel._relationships.has('favouriteMessage'), "Newly created record with relationships in params passed in its constructor should have relationships");
  });
});

test("Model's belongsTo relationship should be created during 'get' method", function () {
  var user;
  run(function () {
    user = env.store.createRecord('user');
    user.get('favouriteMessage');
    ok(user._internalModel._relationships.has('favouriteMessage'), "Newly created record with relationships in params passed in its constructor should have relationships");
  });
});


text:
"""
An in memory implementation of the trusts API.
only to be used for testing purposes
"""
import copy

from oslo.utils import timeutils

from keystone.common import kvs
from keystone import exception
from keystone import trust as keystone_trust

def _filter_trust(ref):
    if ref['deleted']:
        return None
    if ref.get('expires_at') and timeutils.utcnow() > ref['expires_at']:
        return None
    remaining_uses = ref.get('remaining_uses')
    # Do not return trusts that can't be used anymore
    if remaining_uses is not None:
        if remaining_uses <= 0:
            return None
    ref = copy.deepcopy(ref)
    return ref

class Trust(kvs.Base, keystone_trust.Driver):
    def create_trust(self, trust_id, trust, roles):
        trust_ref = copy.deepcopy(trust)
        trust_ref['id'] = trust_id
        trust_ref['deleted'] = False
        trust_ref['roles'] = roles
        if (trust_ref.get('expires_at') and
                trust_ref['expires_at'].tzinfo is not None):
                    trust_ref['expires_at'] = (timeutils.normalize_time
                                               (trust_ref['expires_at']))

        self.db.set('trust-%s' % trust_id, trust_ref)
        trustee_user_id = trust_ref['trustee_user_id']
        trustee_list = self.db.get('trustee-%s' % trustee_user_id, [])
        trustee_list.append(trust_id)
        self.db.set('trustee-%s' % trustee_user_id, trustee_list)
        trustor_user_id = trust_ref['trustor_user_id']
        trustor_list = self.db.get('trustor-%s' % trustor_user_id, [])
        trustor_list.append(trust_id)
        self.db.set('trustor-%s' % trustor_user_id, trustor_list)
        return trust_ref

    def consume_use(self, trust_id):
        try:
            orig_ref = self.db.get('trust-%s' % trust_id)
        except exception.NotFound:
            raise exception.TrustNotFound(trust_id=trust_id)
        remaining_uses = orig_ref.get('remaining_uses')
        if remaining_uses is None:
            # unlimited uses, do nothing
            return
        elif remaining_uses > 0:
            ref = copy.deepcopy(orig_ref)
            ref['remaining_uses'] -= 1
            self.db.set('trust-%s' % trust_id, ref)
        else:
            raise exception.TrustUseLimitReached(trust_id=trust_id)

    def get_trust(self, trust_id):
        try:
            ref = self.db.get('trust-%s' % trust_id)
            return _filter_trust(ref)
        except exception.NotFound:
            return None

    def delete_trust(self, trust_id):
        try:
            ref = self.db.get('trust-%s' % trust_id)
        except exception.NotFound:
            raise exception.TrustNotFound(trust_id=trust_id)
        ref['deleted'] = True
        self.db.set('trust-%s' % trust_id, ref)

    def list_trusts(self):
        trusts = []
        for key, value in self.db.items():
            if key.startswith("trust-") and not value['deleted']:
                trusts.append(value)
        return trusts

    def list_trusts_for_trustee(self, trustee_user_id):
        trusts = []
        for trust in self.db.get('trustee-%s' % trustee_user_id, []):
            trusts.append(self.get_trust(trust))
        return trusts

    def list_trusts_for_trustor(self, trustor_user_id):
        trusts = []
        for trust in self.db.get('trustor-%s' % trustor_user_id, []):
            trusts.append(self.get_trust(trust))
        return trusts

redpajama_set_name: RedPajamaGithub


text:
<!doctype html>

	<meta charset="utf-8">
	<meta http-equiv="X-UA-Compatible" content="IE=edge">
	<title>"tournament/match/game/Game" | @socialgorithm/uttt</title>
	<meta name="description" content="">
	<meta name="viewport" content="width=device-width, initial-scale=1">
	<link rel="stylesheet" href="../assets/css/main.css">

						Search
						<input id="tsd-search-field" type="text" />

Preparing search index...

The search index is not available

					@socialgorithm/uttt

						Options

								All

Public

Public/Protected

All

							<input type="checkbox" id="tsd-filter-inherited" checked />
							Inherited
							<input type="checkbox" id="tsd-filter-externals" checked />
							Externals
							<input type="checkbox" id="tsd-filter-only-exported" />
							Only exported

					Menu

					Globals

					"tournament/match/game/Game"

External module "tournament/match/game/Game"

Index

Classes

Game

Variables

AFTER_<wbr>TIMEOUT_<wbr>DELAY

Variables

Const AFTER_<wbr>TIMEOUT_<wbr>DELAY

AFTER_<wbr>TIMEOUT_<wbr>DELAY: 100 = 100

Defined in tournament/match/game/Game.ts:15

Delay in ms to be used before starting a new game after a player times out.
							The idea is to ensure that the player doesn't respond out of time for the next game.

						Globals

						"index"

						"lib/cli-<wbr>options"

						"lib/funcs"

						"server/<wbr>Server"

						"server/<wbr>Socket<wbr>Server"

						"server/constants"

						"standalone"

						"tournament/<wbr>Tournament"

						"tournament/<wbr>Tournament<wbr>Events"

						"tournament/match/<wbr>Match"

						"tournament/match/<wbr>Match<wbr>Options"

						"tournament/match/game/<wbr>Game"

						"tournament/match/game/<wbr>Game<wbr>Options"

						"tournament/match/game/<wbr>Game<wbr>Stats"

						"tournament/matchmaker/<wbr>Double<wbr>Elimination<wbr>Match"

						"tournament/matchmaker/<wbr>Double<wbr>Elimination<wbr>Matchmaker"

						"tournament/matchmaker/<wbr>Free<wbr>For<wbr>All<wbr>Matchmaker"

						"tournament/matchmaker/<wbr>Matchmaker"

						"tournament/model/<wbr>Channel"

						"tournament/model/<wbr>Lobby"

						"tournament/model/<wbr>Player"

						"tournament/model/<wbr>State"

						"tournament/stats/<wbr>Tournament<wbr>Stats"

						Game

						AFTER_<wbr>TIMEOUT_<wbr>DELAY

Legend

Module

Object literal

Variable

Function

Function with type parameter

Index signature

Type alias

Enumeration

Enumeration member

Property

Method

Interface

Interface with type parameter

Constructor

Property

Method

Index signature

Class

Class with type parameter

Constructor

Property

Method

Accessor

Index signature

Inherited constructor

Inherited property

Inherited method

Inherited accessor

Protected property

Protected method

Protected accessor

Private property

Private method

Private accessor

Static property

Static method

Generated using TypeDoc


text:
#import "ORKPieChartPieView.h"

#import "ORKPieChartView_Internal.h"

#import "ORKHelpers_Internal.h"

static const CGFloat OriginAngle = -M_PI_2;
static const CGFloat PercentageLabelOffset = 10.0;
static const CGFloat InterAnimationDelay = 0.05;

@implementation ORKPieChartPieView {
    __weak ORKPieChartView *_parentPieChartView;

    CAShapeLayer *_circleLayer;
    NSMutableArray<NSNumber *> *_normalizedValues;
    NSMutableArray<CAShapeLayer *> *_segmentLayers;
    NSMutableArray<ORKPieChartSection *> *_pieSections;
}

- (instancetype)initWithFrame:(CGRect)frame {
    ORKThrowMethodUnavailableException();
}

#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wobjc-designated-initializers"
- (instancetype)initWithCoder:(NSCoder *)aDecoder {
    ORKThrowMethodUnavailableException();
}
#pragma clang diagnostic pop

- (instancetype)initWithParentPieChartView:(ORKPieChartView *)parentPieChartView {
    self = [super initWithFrame:CGRectZero];
    if (self) {
        _parentPieChartView = parentPieChartView;
        self.translatesAutoresizingMaskIntoConstraints = NO;

        _circleLayer = [CAShapeLayer layer];
        _circleLayer.fillColor = [UIColor clearColor].CGColor;
        _circleLayer.strokeColor = [UIColor colorWithWhite:0.96 alpha:1.000].CGColor;
        [self.layer addSublayer:_circleLayer];

        _normalizedValues = [NSMutableArray new];
        _segmentLayers = [NSMutableArray new];
        _pieSections = [NSMutableArray new];
        _radiusScaleFactor = 0.5;
    }
    return self;
}

- (void)setPercentageLabelFont:(UIFont *)percentageLabelFont {
    _percentageLabelFont = percentageLabelFont;
    for (ORKPieChartSection *pieSection in _pieSections) {
        pieSection.label.font = percentageLabelFont;
        [pieSection.label sizeToFit];
    }
    [self setNeedsLayout];
}

#pragma mark - Data Normalization

- (CGFloat)normalizeValues {
    [_normalizedValues removeAllObjects];

    CGFloat sumOfValues = 0;
    NSInteger numberOfSegments = [_parentPieChartView.dataSource numberOfSegmentsInPieChartView:_parentPieChartView];
    for (NSInteger idx = 0; idx < numberOfSegments; idx++) {
        CGFloat value = [_parentPieChartView.dataSource pieChartView:_parentPieChartView valueForSegmentAtIndex:idx];
        sumOfValues += value;
    }

    for (NSInteger idx = 0; idx < numberOfSegments; idx++) {
        CGFloat value = 0;
        if (sumOfValues != 0) {
            value = [_parentPieChartView.dataSource pieChartView:_parentPieChartView valueForSegmentAtIndex:idx] / sumOfValues;
        }
        [_normalizedValues addObject:@(value)];
    }
    return sumOfValues;
}

#pragma mark - Layout and drawing

- (void)layoutSubviews {
    [super layoutSubviews];
    CGRect bounds = self.bounds;
    CGFloat startAngle = OriginAngle;
    CGFloat endAngle = startAngle + (2 * M_PI);
    CGFloat outerRadius = bounds.size.height * _radiusScaleFactor;
    CGFloat labelHeight = [@"100%" boundingRectWithSize:CGRectInfinite.size
                                                options:(NSStringDrawingOptions)0
                                             attributes:@{NSFontAttributeName : _percentageLabelFont}
                                                context:nil].size.height;
    CGFloat innerRadius = outerRadius - (labelHeight + PercentageLabelOffset);
    CGFloat targetRadius = _parentPieChartView.showsPercentageLabels ? innerRadius : outerRadius;
    CGFloat lineWidth = MIN(_parentPieChartView.lineWidth, targetRadius);
    _circleLayer.lineWidth = lineWidth;
    CGFloat drawingRadius = targetRadius - (lineWidth * 0.5);

    if (!_parentPieChartView.drawsClockwise) {
        startAngle = 3 * M_PI_2;
        endAngle = -M_PI_2;
    }
    UIBezierPath *circularArcBezierPath = [UIBezierPath bezierPathWithArcCenter:CGPointMake(CGRectGetMidX(bounds),
                                                                                CGRectGetMidY(bounds))
                                                                         radius:drawingRadius
                                                                     startAngle:startAngle
                                                                       endAngle:endAngle
                                                                      clockwise:_parentPieChartView.drawsClockwise];

    _circleLayer.path = circularArcBezierPath.CGPath;

    [self layoutPieChartLayers];
    if (_parentPieChartView.showsPercentageLabels) {
        [self layoutPercentageLabelsWithRadius:innerRadius];
    }
}

- (void)updatePieLayers {
    [_segmentLayers makeObjectsPerformSelector:@selector(removeFromSuperlayer)];
    [_segmentLayers removeAllObjects];

    CGFloat cumulativeValue = 0;
    NSInteger numberOfSegments = [_parentPieChartView.dataSource numberOfSegmentsInPieChartView:_parentPieChartView];
    for (NSInteger idx = 0; idx < numberOfSegments; idx++) {

        CAShapeLayer *segmentLayer = [CAShapeLayer layer];
        segmentLayer.fillColor = [[UIColor clearColor] CGColor];
        segmentLayer.frame = _circleLayer.bounds;
        segmentLayer.path = _circleLayer.path;
        segmentLayer.lineWidth = _circleLayer.lineWidth;
        segmentLayer.strokeColor = [_parentPieChartView colorForSegmentAtIndex:idx].CGColor;
        CGFloat value = _normalizedValues[idx].floatValue;

        segmentLayer.strokeStart = cumulativeValue;
        [_circleLayer addSublayer:segmentLayer];
        [_segmentLayers addObject:segmentLayer];
        segmentLayer.strokeEnd = cumulativeValue + value;

        cumulativeValue += value;
    }
}

- (void)updatePercentageLabels {
    for (ORKPieChartSection *pieSection in _pieSections) {
        [pieSection.label removeFromSuperview];
    }
    [_pieSections removeAllObjects];

    if (_parentPieChartView.showsPercentageLabels) {
        CGFloat cumulativeValue = 0;
        NSInteger numberOfSegments = [_parentPieChartView.dataSource numberOfSegmentsInPieChartView:_parentPieChartView];
        for (NSInteger idx = 0; idx < numberOfSegments; idx++) {
            CGFloat value = _normalizedValues[idx].floatValue;

            // Create a label
            UILabel *label = [UILabel new];
            label.text = [NSString stringWithFormat:@"%0.0f%%", value * 100];
            label.font = _percentageLabelFont;
            label.textColor = [_parentPieChartView colorForSegmentAtIndex:idx];
            [label sizeToFit];

            // Only if there are no legends
            label.isAccessibilityElement = ![_parentPieChartView.dataSource respondsToSelector:@selector(pieChartView:titleForSegmentAtIndex:)];

            // Calculate the angle to the centre of this segment in radians
            CGFloat angle = 0;
            if (_parentPieChartView.drawsClockwise) {
                angle = (value / 2 + cumulativeValue) * M_PI * 2;
            } else {
                angle = (value / 2 + cumulativeValue) * - M_PI * 2;
            }

            cumulativeValue += value;
            ORKPieChartSection *pieSection = [[ORKPieChartSection alloc] initWithLabel:label angle:angle];
            [_pieSections addObject:pieSection];
            [self addSubview:label];
        }
    }
}

- (void)updateColors {
    NSInteger numberOfSegments = [_parentPieChartView.dataSource numberOfSegmentsInPieChartView:_parentPieChartView];
    for (NSInteger idx = 0; idx < numberOfSegments; idx++) {
        if (_segmentLayers.count == numberOfSegments) {
            CAShapeLayer *segmentLayer = _segmentLayers[idx];
            segmentLayer.strokeColor = [_parentPieChartView colorForSegmentAtIndex:idx].CGColor;
        }
        if (_pieSections.count == numberOfSegments) {
            ORKPieChartSection *pieSection = _pieSections[idx];
            UILabel *label = pieSection.label;
            label.textColor = [_parentPieChartView colorForSegmentAtIndex:idx];
        }
    }
}

- (void)layoutPieChartLayers {
    NSInteger numberOfSegments = [_parentPieChartView.dataSource numberOfSegmentsInPieChartView:_parentPieChartView];
    for (NSInteger idx = 0; idx < numberOfSegments; idx++) {
        CAShapeLayer *segmentLayer = _segmentLayers[idx];
        segmentLayer.frame = _circleLayer.bounds;
        segmentLayer.path = _circleLayer.path;
        segmentLayer.lineWidth = _circleLayer.lineWidth;
    }
}

- (void)layoutPercentageLabelsWithRadius:(CGFloat)pieRadius {
    CGFloat cumulativeValue = 0;
    NSInteger numberOfSegments = [_parentPieChartView.dataSource numberOfSegmentsInPieChartView:_parentPieChartView];
    for (NSInteger idx = 0; idx < numberOfSegments; idx++) {
        CGFloat value = _normalizedValues[idx].floatValue;

        // Get a label
        ORKPieChartSection *pieSection = _pieSections[idx];
        UILabel *label = pieSection.label;

        // Calculate the angle to the centre of this segment in radians
        CGFloat angle = (value / 2 + cumulativeValue) * M_PI * 2;
        if (!_parentPieChartView.drawsClockwise) {
            angle = (value / 2 + cumulativeValue) * - M_PI * 2;
        }

        label.center = [self percentageLabel:label calculateCenterForAngle:angle pieRadius:pieRadius];
        cumulativeValue += value;
    }
    [self adjustIntersectionsOfPercentageLabels:_pieSections pieRadius:pieRadius];
}

- (CGPoint)percentageLabel:(UILabel *)label calculateCenterForAngle:(CGFloat)angle pieRadius:(CGFloat)pieRadius {
    // Calculate the desired distance from the circle's centre.
    const CGFloat offset = 10;
    CGFloat length = pieRadius + offset;

    // Calculate x and y coordinates for the point at this distance at the specified angle.
    CGSize size = self.bounds.size;
    CGFloat cosine = cos(angle + OriginAngle);
    CGFloat sine = sin(angle + OriginAngle);
    CGFloat x = cosine * length + size.width / 2;
    CGFloat y = sine *  length + size.height / 2;

    // Offset (x,y) to normalise the spacing from the circle's centre to the intersection with the label's frame rather than its centre.
    CGSize labelSize = [label systemLayoutSizeFittingSize:UILayoutFittingCompressedSize];
    CGFloat xIn = cosine * labelSize.width / 2;
    CGFloat yIn = sine * labelSize.height / 2;
    x += xIn;
    y += yIn;

    return  CGPointMake(x, y);
}

- (void)adjustIntersectionsOfPercentageLabels:(NSArray<ORKPieChartSection *> *)pieSections pieRadius:(CGFloat)pieRadius {
    if (pieSections.count == 0) {
        return;
    }
    // Adjust labels while we have intersections
    BOOL intersections = YES;
    // We alternate directions in each iteration
    BOOL shiftClockwise = NO;
    CGFloat rotateDirection = _parentPieChartView.drawsClockwise ? 1 : -1;
    // We use totalAngle to prevent from infinite loop
    CGFloat totalAngle = 0;
    while (intersections) {
        intersections = NO;
        shiftClockwise = !shiftClockwise;

        if (shiftClockwise) {
            for (NSUInteger idx = 0; idx < (pieSections.count - 1); idx++) {
                // Prevent from infinite loop
                if (!idx) {
                    totalAngle += 0.01;
                    if (totalAngle >= 2 * M_PI) {
                        return;
                    }
                }
                ORKPieChartSection *pieLabel  = pieSections[idx];
                ORKPieChartSection *nextPieLabel = pieSections[(idx + 1)];
                if ([self shiftSectionLabel:nextPieLabel fromSectionLabel:pieLabel direction:rotateDirection pieRadius:pieRadius]) {
                    intersections = YES;
                }
            }
        } else {
            for (NSInteger idx = pieSections.count - 1; idx > 0; idx--) {
                ORKPieChartSection *pieLabel = pieSections[idx];
                ORKPieChartSection *nextPieLabel = pieSections[idx - 1];
                if ([self shiftSectionLabel:nextPieLabel fromSectionLabel:pieLabel direction:-rotateDirection pieRadius:pieRadius]) {
                    intersections = YES;
                }
            }
        }

        // Adjust space between last and first element
        ORKPieChartSection *firstPieLabel = pieSections.firstObject;
        ORKPieChartSection *lastPieLabel = pieSections.lastObject;
        UILabel *firstLabel = firstPieLabel.label;
        UILabel *lastLabel = lastPieLabel.label;
        if (CGRectIntersectsRect(lastLabel.frame, firstLabel.frame)) {
            CGFloat firstLabelAngle = firstPieLabel.angle;
            CGFloat lastLabelAngle = lastPieLabel.angle;
            firstLabelAngle += rotateDirection * 0.01;
            lastLabelAngle -= rotateDirection * 0.01;
            firstPieLabel.angle = firstLabelAngle;
            lastPieLabel.angle = lastLabelAngle;
        }
    }
}

- (BOOL)shiftSectionLabel:(ORKPieChartSection *)nextPieSection
         fromSectionLabel:(ORKPieChartSection *)fromPieSection
                direction:(CGFloat)direction
                pieRadius:(CGFloat)pieRadius {
    CGFloat shiftStep = 0.01;
    UILabel *label = fromPieSection.label;
    UILabel *nextLabel = nextPieSection.label;
    if (CGRectIntersectsRect(label.frame, nextLabel.frame)) {
        CGFloat nextLabelAngle = nextPieSection.angle;
        nextLabelAngle += direction * shiftStep;
        nextPieSection.angle = nextLabelAngle;
        nextLabel.center = [self percentageLabel:nextLabel calculateCenterForAngle:nextLabelAngle pieRadius:pieRadius];
        return YES;
    }
    return NO;
}

- (void)animateWithDuration:(NSTimeInterval)animationDuration {
    NSUInteger numberOfSegmentLayers  = _segmentLayers.count;
    NSTimeInterval interAnimationDelay = InterAnimationDelay;
    NSTimeInterval singleAnimationDuration = animationDuration - (interAnimationDelay * (numberOfSegmentLayers - 1));
    if (singleAnimationDuration < 0) {
        interAnimationDelay = 0;
        singleAnimationDuration = animationDuration;
    }

    CGFloat cumulativeValue = 0;
    for (NSInteger idx = 0; idx < numberOfSegmentLayers ; idx++) {
        CAShapeLayer *segmentLayer = _segmentLayers[idx];
        CGFloat value = _normalizedValues[idx].floatValue;
        CABasicAnimation *strokeAnimation = [CABasicAnimation animationWithKeyPath:@"strokeEnd"];
        strokeAnimation.fromValue = @(segmentLayer.strokeStart);
        strokeAnimation.toValue = @(cumulativeValue + value);
        strokeAnimation.duration = animationDuration;
        strokeAnimation.removedOnCompletion = NO;
        strokeAnimation.fillMode = kCAFillModeForwards;
        strokeAnimation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
        [segmentLayer addAnimation:strokeAnimation forKey:@"strokeAnimation"];

        if (_parentPieChartView.showsPercentageLabels && _pieSections.count == numberOfSegmentLayers) {
            ORKPieChartSection *pieSection = _pieSections[idx];
            UILabel *label = pieSection.label;
            label.alpha = 0;
            [UIView animateWithDuration:singleAnimationDuration
                                  delay:interAnimationDelay * idx
                                options:(UIViewAnimationOptions)0
                             animations:^{
                                 label.alpha = 1.0;
                             }
                             completion:nil];
        }

        cumulativeValue += value;
    }
}

- (void)setRadiusScaleFactor:(CGFloat)radiusScaleFactor {
    _radiusScaleFactor = radiusScaleFactor;
}

#pragma mark - Accessibility

- (NSArray<id> *)accessibilityElements {
    return _pieSections;
}

@end


text:
import threading
import time

from ritoapi.rate_limit.rate_ticker import RateTicker
from ritoapi.rate_limit.rate_ticker_factory import create_ticker
from ritoapi.logger import log_message

class RateLimit:
    def __init__(self, safety_margin, no_global_limit=False, allow_usage_burst=False):
        self.safety_margin = safety_margin
        self.allow_usage_burst = allow_usage_burst
        self.method_tickers = {}
        self.usage_lock = threading.Lock()
        self.create_tickers_lock = threading.Lock()
        self.global_ticker = None
        if no_global_limit:
            self.global_ticker = RateTicker(1000000, 1, 0, is_global=True, allow_usage_burst=allow_usage_burst)

    def _get_method_ticker(self, method_id):
        if method_id in self.method_tickers and self.method_tickers[method_id] is not None:
            return self.method_tickers[method_id]

    def _create_tickers(self, url, method_id):
        with self.create_tickers_lock:
            if not self.global_ticker:
                self.global_ticker = create_ticker(url, self.safety_margin, is_global=True,
                                                   allow_usage_burst=self.allow_usage_burst)
            if not self._get_method_ticker(method_id):
                if self.global_ticker:
                    self.wait_usage(1)
                self.method_tickers[method_id] = create_ticker(url, self.safety_margin, is_global=False,
                                                               allow_usage_burst=self.allow_usage_burst)

    def check_tickers(self, url, method_id):
        if not self.global_ticker or not self._get_method_ticker(method_id):
            self._create_tickers(url, method_id)
        return self.global_ticker and self._get_method_ticker(method_id)

    def wait_usage(self, count, method_id=None):
        method_ticker = self._get_method_ticker(method_id) if method_id else None
        while True:
            with self.usage_lock:
                if self.global_ticker.check_usage() and (method_ticker is None or method_ticker.check_usage()):
                    self.global_ticker.add_usage(count)
                    if method_ticker:
                        method_ticker.add_usage(count)
                    return True
                else:
                    wait_time = self.global_ticker.get_wait_time()
                    if method_ticker:
                        wait_time = max(wait_time, method_ticker.get_wait_time())
            time.sleep(wait_time)

    def should_retry(self, error, method_id):
        with self.usage_lock:
            error_str = str(error)
            if 'HTTP Error 429' in error_str:
                limit_type = error.headers['X-Rate-Limit-Type']
                if limit_type == 'method':
                    log_message('WARNING: method={0} remote rate limit exceeded with error={1}'.format(method_id, error_str))
                    self._get_method_ticker(method_id).overheat(is_service=False)
                elif limit_type == 'application':
                    log_message('WARNING: application remote rate limit exceeded with error={0}'.format(error_str))
                    self.global_ticker.overheat(is_service=False)
                return True
            elif 'HTTP Error 503' in error_str:
                self.global_ticker.overheat(is_service=True)
                return True
            return 'urlopen error' in error_str


text:
	<?php require('menuHeader.php'); ?>
	<?php $helpLink="http://docs.wordfence.com/en/Blocked_IPs"; $helpLabel="Learn more about Blocked IPs"; $pageTitle = "Wordfence Blocked IPs"; include('pageTitle.php'); ?>

Wordfence Live Activity:

	<?php if(! wfConfig::get('firewallEnabled')){ ?>
Firewall is disabled. You can enable it on the Wordfence Options page at the top.
<?php } ?>

		Clear all blocked IP addresses  |  Clear all locked out IP addresses

		You can manually (and permanently) block an IP by entering the address here: <input type="text" id="wfManualBlock" size="20" maxlength="40" value="" onkeydown="if(event.keyCode == 13){ WFAD.blockIPTwo(jQuery('#wfManualBlock').val(), 'Manual block by administrator', true); return false; }" /> <input type="button" name="but1" value="Manually block IP" onclick="WFAD.blockIPTwo(jQuery('#wfManualBlock').val(), 'Manual block by administrator', true); return false;" />

				IPs that are blocked from accessing the site
				IPs that are Locked Out from Login
				IPs who were recently throttled for accessing the site too frequently


text:
<?php
/**
 * Test Generated example demonstrating the ContributionRecur.create API.
 *
 * @return array
 *   API result array
 */
function contribution_recur_create_example() {
  $params = array(
    'contact_id' => 3,
    'installments' => '12',
    'frequency_interval' => '1',
    'amount' => '500',
    'contribution_status_id' => 1,
    'start_date' => '2012-01-01 00:00:00',
    'currency' => 'USD',
    'frequency_unit' => 'day',
  );

  try{
    $result = civicrm_api3('ContributionRecur', 'create', $params);
  }
  catch (CiviCRM_API3_Exception $e) {
    // Handle error here.
    $errorMessage = $e->getMessage();
    $errorCode = $e->getErrorCode();
    $errorData = $e->getExtraParams();
    return array(
      'error' => $errorMessage,
      'error_code' => $errorCode,
      'error_data' => $errorData,
    );
  }

  return $result;
}

/**
 * Function returns array of result expected from previous function.
 *
 * @return array
 *   API result array
 */
function contribution_recur_create_expectedresult() {

  $expectedResult = array(
    'is_error' => 0,
    'version' => 3,
    'count' => 1,
    'id' => 1,
    'values' => array(
      '1' => array(
        'id' => '1',
        'contact_id' => '3',
        'amount' => '500',
        'currency' => 'USD',
        'frequency_unit' => 'day',
        'frequency_interval' => '1',
        'installments' => '12',
        'start_date' => '2013-07-29 00:00:00',
        'create_date' => '20120130621222105',
        'modified_date' => '',
        'cancel_date' => '',
        'end_date' => '',
        'processor_id' => '',
        'trxn_id' => '',
        'invoice_id' => '',
        'contribution_status_id' => '1',
        'is_test' => '',
        'cycle_day' => '',
        'next_sched_contribution_date' => '',
        'failure_count' => '',
        'failure_retry_date' => '',
        'auto_renew' => '',
        'payment_processor_id' => '',
        'financial_type_id' => '',
        'payment_instrument_id' => '',
        'campaign_id' => '',
        'is_email_receipt' => '',
      ),
    ),
  );

  return $expectedResult;
}

/*
* This example has been generated from the API test suite.
* The test that created it is called "testCreateContributionRecur"
* and can be found at:
* https://github.com/civicrm/civicrm-core/blob/master/tests/phpunit/api/v3/ContributionRecurTest.php
*
* You can see the outcome of the API tests at
* https://test.civicrm.org/job/CiviCRM-master-git/
*
* To Learn about the API read
* http://wiki.civicrm.org/confluence/display/CRMDOC/Using+the+API
*
* Browse the api on your own site with the api explorer
* http://MYSITE.ORG/path/to/civicrm/api
*
* Read more about testing here
* http://wiki.civicrm.org/confluence/display/CRM/Testing
*
* API Standards documentation:
* http://wiki.civicrm.org/confluence/display/CRM/API+Architecture+Standards
*/


text:
namespace BoltEngine
{
namespace Plugin
{

IPlugin::IPlugin(const wstring &name, const wstring &description,
	const CVersion &version) : m_Name(name), m_Description(description), m_Version(version)
{

}

IPlugin::~IPlugin()
{

}

const wstring &IPlugin::GetName() const
{
	return m_Name;
}

const wstring &IPlugin::GetDescription() const
{
	return m_Description;
}

const CVersion &IPlugin::GetVersion() const
{
	return m_Version;
}

}
}


text:
public class Solution {
    /**
     * @param nums: a list of integers
     * @return: find a  majority number
     */
    public int majorityNumber(ArrayList<Integer> nums) {
        // write your code
        // quickSelect solution. O(n) time , inplace. O(1) space.
        int size = nums.size();
        if (size == 0) {
            return 0;
        }

        int start = 0;
        int end = size - 1;
        int median = quickSelet(nums, start, end, (start + end) / 2);
        int majority = nums.get(median);
        return majority;
    }

    public int quickSelet(ArrayList<Integer> nums, int start, int end, int n) {

        while (start <= end) {
            int pivot = (start + end) / 2;
            int relocate = partition(nums, start, end, pivot);
            if (relocate == n) {
                return relocate;
            } else if (relocate < n) {
                start = relocate + 1;
            } else {
                end = relocate - 1;
            }
        }

        return -1;
    }

    public int partition(ArrayList<Integer> nums, int start, int end, int pivot) {
        int pivotal = nums.get(pivot);
        int storedIndex = start;
        swap(nums, end, pivot);

        for (int i = start; i < end; i++) {
            if (nums.get(i) < pivotal) {
                swap(nums, i, storedIndex++);
            }
        }

        swap(nums, end, storedIndex);
        return storedIndex;
    }

    public void swap(ArrayList<Integer> nums, int left, int right) {
        if (nums.get(left) == nums.get(right)) {
            return;
        }
        int temp = nums.get(left);
        nums.set(left, nums.get(right));
        nums.set(right, temp);
    }
}

public class Solution {
    /**
     * @param nums: a list of integers
     * @return: find a  majority number
     */
    public int majorityNumber(ArrayList<Integer> nums) {
        // write your code
        // hashmap solution. O(n) time, O(n) space.
        Map<Integer, Integer> map = new HashMap<Integer, Integer>();

        for (Integer i : nums) {
            map.put(i, map.containsKey(i) ? map.get(i) + 1 : 1);
        }

        int maxValue = 0;
        int maxKey = 0;

        for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
            if (entry.getValue() >= maxValue) {
                maxValue = entry.getValue();
                maxKey = entry.getKey();
            }
        }

        return maxKey;
    }

}

public class Solution {
    /**
     * @param nums: a list of integers
     * @return: find a  majority number
     */
    public int majorityNumber(ArrayList<Integer> nums) {
        // write your code
        // Use Moore's voting algorithm.
        // Time: O(n), space O(1).

        int size = nums.size();
        if (size == 0) {
            return 0;
        }
        // first find candidate.
        int majorIndex = 0;
        int count = 1;
        for (int i = 1; i < size; i++) {
            if (nums.get(majorIndex) == nums.get(i)) {
                count++;
            } else {
                count--;
            }

            if (count == 0) {
                majorIndex = i;
                count = 1;
            }
        }

        // if solution is not guanranteed to be one,
        // check the count.

        return nums.get(majorIndex);

    }

}


text:
package confighistory

import (
	"fmt"

	"github.com/golang/protobuf/proto"
	"github.com/hyperledger/fabric-protos-go/common"
	"github.com/hyperledger/fabric-protos-go/ledger/rwset/kvrwset"
	"github.com/hyperledger/fabric-protos-go/peer"
	"github.com/hyperledger/fabric/common/flogging"
	"github.com/hyperledger/fabric/core/ledger"
	"github.com/pkg/errors"
)

var logger = flogging.MustGetLogger("confighistory")

const (
	collectionConfigNamespace = "lscc" // lscc namespace was introduced in version 1.2 and we continue to use this in order to be compatible with existing data
)

// Mgr should be registered as a state listener. The state listener builds the history and retriever helps in querying the history
type Mgr interface {
	ledger.StateListener
	GetRetriever(ledgerID string, ledgerInfoRetriever LedgerInfoRetriever) ledger.ConfigHistoryRetriever
	Close()
}

type mgr struct {
	ccInfoProvider ledger.DeployedChaincodeInfoProvider
	dbProvider     *dbProvider
}

// NewMgr constructs an instance that implements interface `Mgr`
func NewMgr(dbPath string, ccInfoProvider ledger.DeployedChaincodeInfoProvider) (Mgr, error) {
	p, err := newDBProvider(dbPath)
	if err != nil {
		return nil, err
	}
	return &mgr{ccInfoProvider, p}, nil
}

func (m *mgr) Initialize(ledgerID string, qe ledger.SimpleQueryExecutor) error {
	// Noop
	return nil
}

// InterestedInNamespaces implements function from the interface ledger.StateListener
func (m *mgr) InterestedInNamespaces() []string {
	return m.ccInfoProvider.Namespaces()
}

// StateCommitDone implements function from the interface ledger.StateListener
func (m *mgr) StateCommitDone(ledgerID string) {
	// Noop
}

// HandleStateUpdates implements function from the interface ledger.StateListener
// In this implementation, the latest collection config package is retrieved via
// ledger.DeployedChaincodeInfoProvider and is persisted as a separate entry in a separate db.
// The composite key for the entry is a tuple of <blockNum, namespace, key>
func (m *mgr) HandleStateUpdates(trigger *ledger.StateUpdateTrigger) error {
	updatedCCs, err := m.ccInfoProvider.UpdatedChaincodes(extractPublicUpdates(trigger.StateUpdates))
	if err != nil {
		return err
	}
	// updated chaincodes can be empty if the invocation to this function is triggered
	// because of state updates that contains only chaincode approval transaction output
	if len(updatedCCs) == 0 {
		return nil
	}
	updatedCollConfigs := map[string]*peer.CollectionConfigPackage{}
	for _, cc := range updatedCCs {
		ccInfo, err := m.ccInfoProvider.ChaincodeInfo(trigger.LedgerID, cc.Name, trigger.PostCommitQueryExecutor)
		if err != nil {
			return err
		}

		// DeployedChaincodeInfoProvider implementation in new lifecycle return an empty 'CollectionConfigPackage'
		// (instead of a nil) to indicate the absence of collection config, so check for both conditions
		if ccInfo.ExplicitCollectionConfigPkg == nil || len(ccInfo.ExplicitCollectionConfigPkg.Config) == 0 {
			continue
		}
		updatedCollConfigs[ccInfo.Name] = ccInfo.ExplicitCollectionConfigPkg
	}
	if len(updatedCollConfigs) == 0 {
		return nil
	}
	batch, err := prepareDBBatch(updatedCollConfigs, trigger.CommittingBlockNum)
	if err != nil {
		return err
	}
	dbHandle := m.dbProvider.getDB(trigger.LedgerID)
	return dbHandle.writeBatch(batch, true)
}

// GetRetriever returns an implementation of `ledger.ConfigHistoryRetriever` for the given ledger id.
func (m *mgr) GetRetriever(ledgerID string, ledgerInfoRetriever LedgerInfoRetriever) ledger.ConfigHistoryRetriever {
	return &retriever{
		ledgerInfoRetriever:    ledgerInfoRetriever,
		ledgerID:               ledgerID,
		deployedCCInfoProvider: m.ccInfoProvider,
		dbHandle:               m.dbProvider.getDB(ledgerID),
	}
}

// Close implements the function in the interface 'Mgr'
func (m *mgr) Close() {
	m.dbProvider.Close()
}

type retriever struct {
	ledgerInfoRetriever    LedgerInfoRetriever
	ledgerID               string
	deployedCCInfoProvider ledger.DeployedChaincodeInfoProvider
	dbHandle               *db
}

// MostRecentCollectionConfigBelow implements function from the interface ledger.ConfigHistoryRetriever
func (r *retriever) MostRecentCollectionConfigBelow(blockNum uint64, chaincodeName string) (*ledger.CollectionConfigInfo, error) {
	compositeKV, err := r.dbHandle.mostRecentEntryBelow(blockNum, collectionConfigNamespace, constructCollectionConfigKey(chaincodeName))
	if err != nil {
		return nil, err
	}
	implicitColls, err := r.getImplicitCollection(chaincodeName)
	if err != nil {
		return nil, err
	}

	return constructCollectionConfigInfo(compositeKV, implicitColls)
}

// CollectionConfigAt implements function from the interface ledger.ConfigHistoryRetriever
func (r *retriever) CollectionConfigAt(blockNum uint64, chaincodeName string) (*ledger.CollectionConfigInfo, error) {
	info, err := r.ledgerInfoRetriever.GetBlockchainInfo()
	if err != nil {
		return nil, err
	}
	maxCommittedBlockNum := info.Height - 1
	if maxCommittedBlockNum < blockNum {
		return nil, &ledger.ErrCollectionConfigNotYetAvailable{MaxBlockNumCommitted: maxCommittedBlockNum,
			Msg: fmt.Sprintf("The maximum block number committed [%d] is less than the requested block number [%d]", maxCommittedBlockNum, blockNum)}
	}

	compositeKV, err := r.dbHandle.entryAt(blockNum, collectionConfigNamespace, constructCollectionConfigKey(chaincodeName))
	if err != nil {
		return nil, err
	}
	implicitColls, err := r.getImplicitCollection(chaincodeName)
	if err != nil {
		return nil, err
	}
	return constructCollectionConfigInfo(compositeKV, implicitColls)
}

func (r *retriever) getImplicitCollection(chaincodeName string) ([]*peer.StaticCollectionConfig, error) {
	qe, err := r.ledgerInfoRetriever.NewQueryExecutor()
	if err != nil {
		return nil, err
	}
	defer qe.Done()
	return r.deployedCCInfoProvider.ImplicitCollections(r.ledgerID, chaincodeName, qe)
}

func prepareDBBatch(chaincodeCollConfigs map[string]*peer.CollectionConfigPackage, committingBlockNum uint64) (*batch, error) {
	batch := newBatch()
	for ccName, collConfig := range chaincodeCollConfigs {
		key := constructCollectionConfigKey(ccName)
		var configBytes []byte
		var err error
		if configBytes, err = proto.Marshal(collConfig); err != nil {
			return nil, errors.WithStack(err)
		}
		batch.add(collectionConfigNamespace, key, committingBlockNum, configBytes)
	}
	return batch, nil
}

func compositeKVToCollectionConfig(compositeKV *compositeKV) (*ledger.CollectionConfigInfo, error) {
	conf := &peer.CollectionConfigPackage{}
	if err := proto.Unmarshal(compositeKV.value, conf); err != nil {
		return nil, errors.Wrap(err, "error unmarshalling compositeKV to collection config")
	}
	return &ledger.CollectionConfigInfo{
		CollectionConfig:   conf,
		CommittingBlockNum: compositeKV.blockNum,
	}, nil
}

func constructCollectionConfigKey(chaincodeName string) string {
	return chaincodeName + "~collection" // collection config key as in version 1.2 and we continue to use this in order to be compatible with existing data
}

func extractPublicUpdates(stateUpdates ledger.StateUpdates) map[string][]*kvrwset.KVWrite {
	m := map[string][]*kvrwset.KVWrite{}
	for ns, updates := range stateUpdates {
		m[ns] = updates.PublicUpdates
	}
	return m
}

func constructCollectionConfigInfo(
	compositeKV *compositeKV,
	implicitColls []*peer.StaticCollectionConfig,
) (*ledger.CollectionConfigInfo, error) {
	var collConf *ledger.CollectionConfigInfo
	var err error

	if compositeKV == nil && len(implicitColls) == 0 {
		return nil, nil
	}

	collConf = &ledger.CollectionConfigInfo{
		CollectionConfig: &peer.CollectionConfigPackage{},
	}
	if compositeKV != nil {
		if collConf, err = compositeKVToCollectionConfig(compositeKV); err != nil {
			return nil, err
		}
	}

	for _, implicitColl := range implicitColls {
		cc := &peer.CollectionConfig{}
		cc.Payload = &peer.CollectionConfig_StaticCollectionConfig{StaticCollectionConfig: implicitColl}
		collConf.CollectionConfig.Config = append(
			collConf.CollectionConfig.Config,
			cc,
		)
	}
	return collConf, nil
}

// LedgerInfoRetriever retrieves the relevant info from ledger
type LedgerInfoRetriever interface {
	GetBlockchainInfo() (*common.BlockchainInfo, error)
	NewQueryExecutor() (ledger.QueryExecutor, error)
}


text:
//
#include "ui_local.h"

// this file is only included when building a dll
// syscalls.asm is included instead when building a qvm
#ifdef Q3_VM
#error "Do not use in VM build"
#endif

static intptr_t (QDECL* syscall)(intptr_t arg, ...) = (intptr_t (QDECL*)(intptr_t, ...)) - 1;

void dllEntry(long (QDECL* syscallptr)(long arg, ...)) {
    syscall = syscallptr;
}

//static intptr_t (QDECL *syscall)( intptr_t arg, ... ) = (intptr_t (QDECL *)( intptr_t, ...))-1;

//void dllEntry( intptr_t (QDECL *syscallptr)( intptr_t arg,... ) ) {
//syscall = syscallptr;
//}

int PASSFLOAT(float x) {
    float floatTemp;
    floatTemp = x;
    return *(int*)&floatTemp;
}

void trap_Print(const char* string) {
    syscall(UI_PRINT, string);
}

void trap_Error(const char* string) {
    syscall(UI_ERROR, string);
    exit(UI_ERROR); //Will never occour but makes compiler happy
}

int trap_Milliseconds(void) {
    return syscall(UI_MILLISECONDS);
}

void trap_Cvar_Register(vmCvar_t* cvar, const char* var_name, const char* value, int flags) {
    syscall(UI_CVAR_REGISTER, cvar, var_name, value, flags);
}

void trap_Cvar_Update(vmCvar_t* cvar) {
    syscall(UI_CVAR_UPDATE, cvar);
}

void trap_Cvar_Set(const char* var_name, const char* value) {
    syscall(UI_CVAR_SET, var_name, value);
}

float trap_Cvar_VariableValue(const char* var_name) {
    int temp;
    temp = syscall(UI_CVAR_VARIABLEVALUE, var_name);
    return (*(float*)&temp);
}

void trap_Cvar_VariableStringBuffer(const char* var_name, char* buffer, int bufsize) {
    syscall(UI_CVAR_VARIABLESTRINGBUFFER, var_name, buffer, bufsize);
}

void trap_Cvar_SetValue(const char* var_name, float value) {
    syscall(UI_CVAR_SETVALUE, var_name, PASSFLOAT(value));
}

void trap_Cvar_Reset(const char* name) {
    syscall(UI_CVAR_RESET, name);
}

void trap_Cvar_Create(const char* var_name, const char* var_value, int flags) {
    syscall(UI_CVAR_CREATE, var_name, var_value, flags);
}

void trap_Cvar_InfoStringBuffer(int bit, char* buffer, int bufsize) {
    syscall(UI_CVAR_INFOSTRINGBUFFER, bit, buffer, bufsize);
}

int trap_Argc(void) {
    return syscall(UI_ARGC);
}

void trap_Argv(int n, char* buffer, int bufferLength) {
    syscall(UI_ARGV, n, buffer, bufferLength);
}

void trap_Cmd_ExecuteText(int exec_when, const char* text) {
    syscall(UI_CMD_EXECUTETEXT, exec_when, text);
}

int trap_FS_FOpenFile(const char* qpath, fileHandle_t* f, fsMode_t mode) {
    return syscall(UI_FS_FOPENFILE, qpath, f, mode);
}

void trap_FS_Read(void* buffer, int len, fileHandle_t f) {
    syscall(UI_FS_READ, buffer, len, f);
}

void trap_FS_Write(const void* buffer, int len, fileHandle_t f) {
    syscall(UI_FS_WRITE, buffer, len, f);
}

void trap_FS_FCloseFile(fileHandle_t f) {
    syscall(UI_FS_FCLOSEFILE, f);
}

int trap_FS_GetFileList(const char* path, const char* extension, char* listbuf, int bufsize) {
    return syscall(UI_FS_GETFILELIST, path, extension, listbuf, bufsize);
}

int trap_FS_Seek(fileHandle_t f, long offset, int origin) {
    return syscall(UI_FS_SEEK, f, offset, origin);
}

qhandle_t trap_R_RegisterModel(const char* name) {
    return syscall(UI_R_REGISTERMODEL, name);
}

qhandle_t trap_R_RegisterSkin(const char* name) {
    return syscall(UI_R_REGISTERSKIN, name);
}

void trap_R_RegisterFont(const char* fontName, int pointSize, fontInfo_t* font) {
    syscall(UI_R_REGISTERFONT, fontName, pointSize, font);
}

qhandle_t trap_R_RegisterShaderNoMip(const char* name) {
    return syscall(UI_R_REGISTERSHADERNOMIP, name);
}

void trap_R_ClearScene(void) {
    syscall(UI_R_CLEARSCENE);
}

void trap_R_AddRefEntityToScene(const refEntity_t* re) {
    syscall(UI_R_ADDREFENTITYTOSCENE, re);
}

void trap_R_AddPolyToScene(qhandle_t hShader, int numVerts, const polyVert_t* verts) {
    syscall(UI_R_ADDPOLYTOSCENE, hShader, numVerts, verts);
}

void trap_R_AddLightToScene(const vec3_t org, float intensity, float r, float g, float b) {
    syscall(UI_R_ADDLIGHTTOSCENE, org, PASSFLOAT(intensity), PASSFLOAT(r), PASSFLOAT(g), PASSFLOAT(b));
}

void trap_R_RenderScene(const refdef_t* fd) {
    syscall(UI_R_RENDERSCENE, fd);
}

void trap_R_SetColor(const float* rgba) {
    syscall(UI_R_SETCOLOR, rgba);
}

void trap_R_DrawStretchPic(float x, float y, float w, float h, float s1, float t1, float s2, float t2, qhandle_t hShader) {
    syscall(UI_R_DRAWSTRETCHPIC, PASSFLOAT(x), PASSFLOAT(y), PASSFLOAT(w), PASSFLOAT(h), PASSFLOAT(s1), PASSFLOAT(t1), PASSFLOAT(s2), PASSFLOAT(t2), hShader);
}

void trap_R_ModelBounds(clipHandle_t model, vec3_t mins, vec3_t maxs) {
    syscall(UI_R_MODELBOUNDS, model, mins, maxs);
}

void trap_UpdateScreen(void) {
    syscall(UI_UPDATESCREEN);
}

int trap_CM_LerpTag(orientation_t* tag, clipHandle_t mod, int startFrame, int endFrame, float frac, const char* tagName) {
    return syscall(UI_CM_LERPTAG, tag, mod, startFrame, endFrame, PASSFLOAT(frac), tagName);
}

void trap_S_StartLocalSound(sfxHandle_t sfx, int channelNum) {
    syscall(UI_S_STARTLOCALSOUND, sfx, channelNum);
}

sfxHandle_t trap_S_RegisterSound(const char* sample, qboolean compressed) {
    return syscall(UI_S_REGISTERSOUND, sample, compressed);
}

void trap_Key_KeynumToStringBuf(int keynum, char* buf, int buflen) {
    syscall(UI_KEY_KEYNUMTOSTRINGBUF, keynum, buf, buflen);
}

void trap_Key_GetBindingBuf(int keynum, char* buf, int buflen) {
    syscall(UI_KEY_GETBINDINGBUF, keynum, buf, buflen);
}

void trap_Key_SetBinding(int keynum, const char* binding) {
    syscall(UI_KEY_SETBINDING, keynum, binding);
}

qboolean trap_Key_IsDown(int keynum) {
    return syscall(UI_KEY_ISDOWN, keynum);
}

qboolean trap_Key_GetOverstrikeMode(void) {
    return syscall(UI_KEY_GETOVERSTRIKEMODE);
}

void trap_Key_SetOverstrikeMode(qboolean state) {
    syscall(UI_KEY_SETOVERSTRIKEMODE, state);
}

void trap_Key_ClearStates(void) {
    syscall(UI_KEY_CLEARSTATES);
}

int trap_Key_GetCatcher(void) {
    return syscall(UI_KEY_GETCATCHER);
}

void trap_Key_SetCatcher(int catcher) {
    syscall(UI_KEY_SETCATCHER, catcher);
}

void trap_GetClipboardData(char* buf, int bufsize) {
    syscall(UI_GETCLIPBOARDDATA, buf, bufsize);
}

void trap_GetClientState(uiClientState_t* state) {
    syscall(UI_GETCLIENTSTATE, state);
}

void trap_GetGlconfig(glconfig_t* glconfig) {
    syscall(UI_GETGLCONFIG, glconfig);
}

int trap_GetConfigString(int index, char* buff, int buffsize) {
    return syscall(UI_GETCONFIGSTRING, index, buff, buffsize);
}

int trap_LAN_GetServerCount(int source) {
    return syscall(UI_LAN_GETSERVERCOUNT, source);
}

void trap_LAN_GetServerAddressString(int source, int n, char* buf, int buflen) {
    syscall(UI_LAN_GETSERVERADDRESSSTRING, source, n, buf, buflen);
}

void trap_LAN_GetServerInfo(int source, int n, char* buf, int buflen) {
    syscall(UI_LAN_GETSERVERINFO, source, n, buf, buflen);
}

int trap_LAN_GetServerPing(int source, int n) {
    return syscall(UI_LAN_GETSERVERPING, source, n);
}

int trap_LAN_GetPingQueueCount(void) {
    return syscall(UI_LAN_GETPINGQUEUECOUNT);
}

int trap_LAN_ServerStatus(const char* serverAddress, char* serverStatus, int maxLen) {
    return syscall(UI_LAN_SERVERSTATUS, serverAddress, serverStatus, maxLen);
}

void trap_LAN_SaveCachedServers(void) {
    syscall(UI_LAN_SAVECACHEDSERVERS);
}

void trap_LAN_LoadCachedServers(void) {
    syscall(UI_LAN_LOADCACHEDSERVERS);
}

void trap_LAN_ResetPings(int n) {
    syscall(UI_LAN_RESETPINGS, n);
}

void trap_LAN_ClearPing(int n) {
    syscall(UI_LAN_CLEARPING, n);
}

void trap_LAN_GetPing(int n, char* buf, int buflen, int* pingtime) {
    syscall(UI_LAN_GETPING, n, buf, buflen, pingtime);
}

void trap_LAN_GetPingInfo(int n, char* buf, int buflen) {
    syscall(UI_LAN_GETPINGINFO, n, buf, buflen);
}

void trap_LAN_MarkServerVisible(int source, int n, qboolean visible) {
    syscall(UI_LAN_MARKSERVERVISIBLE, source, n, visible);
}

int trap_LAN_ServerIsVisible(int source, int n) {
    return syscall(UI_LAN_SERVERISVISIBLE, source, n);
}

qboolean trap_LAN_UpdateVisiblePings(int source) {
    return syscall(UI_LAN_UPDATEVISIBLEPINGS, source);
}

int trap_LAN_AddServer(int source, const char* name, const char* addr) {
    return syscall(UI_LAN_ADDSERVER, source, name, addr);
}

void trap_LAN_RemoveServer(int source, const char* addr) {
    syscall(UI_LAN_REMOVESERVER, source, addr);
}

int trap_LAN_CompareServers(int source, int sortKey, int sortDir, int s1, int s2) {
    return syscall(UI_LAN_COMPARESERVERS, source, sortKey, sortDir, s1, s2);
}

int trap_MemoryRemaining(void) {
    return syscall(UI_MEMORY_REMAINING);
}

void trap_GetCDKey(char* buf, int buflen) {
    syscall(UI_GET_CDKEY, buf, buflen);
}

void trap_SetCDKey(char* buf) {
    syscall(UI_SET_CDKEY, buf);
}

int trap_PC_AddGlobalDefine(char* define) {
    return syscall(UI_PC_ADD_GLOBAL_DEFINE, define);
}

int trap_PC_LoadSource(const char* filename) {
    return syscall(UI_PC_LOAD_SOURCE, filename);
}

int trap_PC_FreeSource(int handle) {
    return syscall(UI_PC_FREE_SOURCE, handle);
}

int trap_PC_ReadToken(int handle, pc_token_t* pc_token) {
    return syscall(UI_PC_READ_TOKEN, handle, pc_token);
}

int trap_PC_SourceFileAndLine(int handle, char* filename, int* line) {
    return syscall(UI_PC_SOURCE_FILE_AND_LINE, handle, filename, line);
}

void trap_S_StopBackgroundTrack(void) {
    syscall(UI_S_STOPBACKGROUNDTRACK);
}

void trap_S_StartBackgroundTrack(const char* intro, const char* loop) {
    syscall(UI_S_STARTBACKGROUNDTRACK, intro, loop);
}

int trap_RealTime(qtime_t* qtime) {
    return syscall(UI_REAL_TIME, qtime);
}

// this returns a handle. arg0 is the name in the format "idlogo.roq", set arg1 to NULL, alteredstates to qfalse (do not alter gamestate)
int trap_CIN_PlayCinematic(const char* arg0, int xpos, int ypos, int width, int height, int bits) {
    return syscall(UI_CIN_PLAYCINEMATIC, arg0, xpos, ypos, width, height, bits);
}

// stops playing the cinematic and ends it. should always return FMV_EOF
// cinematics must be stopped in reverse order of when they are started
e_status trap_CIN_StopCinematic(int handle) {
    return syscall(UI_CIN_STOPCINEMATIC, handle);
}

// will run a frame of the cinematic but will not draw it. Will return FMV_EOF if the end of the cinematic has been reached.
e_status trap_CIN_RunCinematic(int handle) {
    return syscall(UI_CIN_RUNCINEMATIC, handle);
}

// draws the current frame
void trap_CIN_DrawCinematic(int handle) {
    syscall(UI_CIN_DRAWCINEMATIC, handle);
}

// allows you to resize the animation dynamically
void trap_CIN_SetExtents(int handle, int x, int y, int w, int h) {
    syscall(UI_CIN_SETEXTENTS, handle, x, y, w, h);
}

void trap_R_RemapShader(const char* oldShader, const char* newShader, const char* timeOffset) {
    syscall(UI_R_REMAP_SHADER, oldShader, newShader, timeOffset);
}

qboolean trap_VerifyCDKey(const char* key, const char* chksum) {
    return syscall(UI_VERIFY_CDKEY, key, chksum);
}

void trap_SetPbClStatus(int status) {
    syscall(UI_SET_PBCLSTATUS, status);
}


text:
<component name="libraryTable">
  <library name="Gradle: org.springframework.cloud:spring-cloud-starter-consul-discovery:1.1.2.RELEASE">
    <CLASSES>
      <root url="jar://$USER_HOME$/.gradle/caches/modules-2/files-2.1/org.springframework.cloud/spring-cloud-starter-consul-discovery/1.1.2.RELEASE/23ed8d8e7c08e5aae2e128d09619c659470573ef/spring-cloud-starter-consul-discovery-1.1.2.RELEASE.jar!/" />
    </CLASSES>
    <JAVADOC />
    <SOURCES>
      <root url="jar://$USER_HOME$/.gradle/caches/modules-2/files-2.1/org.springframework.cloud/spring-cloud-starter-consul-discovery/1.1.2.RELEASE/acc124debc42a9c52fa45b5e5af782808fd2bd84/spring-cloud-starter-consul-discovery-1.1.2.RELEASE-sources.jar!/" />
    </SOURCES>
  </library>
</component>


text:
package com.planet_ink.coffee_mud.core.intermud;
import com.planet_ink.coffee_mud.core.intermud.imc2.*;
import com.planet_ink.coffee_mud.core.intermud.i3.packets.*;
import com.planet_ink.coffee_mud.core.intermud.i3.persist.*;
import com.planet_ink.coffee_mud.core.intermud.i3.server.*;
import com.planet_ink.coffee_mud.core.intermud.i3.net.*;
import com.planet_ink.coffee_mud.core.intermud.*;
import com.planet_ink.coffee_mud.core.*;
import com.planet_ink.coffee_mud.core.CMSecurity.DisFlag;
import com.planet_ink.coffee_mud.core.collections.*;
import com.planet_ink.coffee_mud.Libraries.interfaces.*;
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.core.interfaces.*;
import com.planet_ink.coffee_mud.Items.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.*;
import java.net.*;

@SuppressWarnings({"unchecked","rawtypes"})
public class IMudClient implements I3Interface
{
	@Override public String ID(){return "IMudClient";}
	@Override public String name() { return ID();}
	@Override public CMObject newInstance(){try{return getClass().newInstance();}catch(final Exception e){return new IMudClient();}}
	@Override public void initializeClass(){}
	@Override public CMObject copyOf(){try{return (CMObject)this.clone();}catch(final Exception e){return newInstance();}}
	@Override public String L(final String str, final String ... xs) { return CMLib.lang().fullSessionTranslation(str, xs); }
	@Override public int compareTo(CMObject o){ return CMClass.classID(this).compareToIgnoreCase(CMClass.classID(o));}
	@Override public boolean activate(){ return true;}
	@Override public boolean shutdown(){ return true;}
	@Override public void propertiesLoaded(){}
	@Override public TickClient getServiceClient() { return null;}

	public IMC2Driver imc2=null;
	@Override
	public void registerIMC2(Object O)
	{
		if(O instanceof IMC2Driver)
			imc2=(IMC2Driver)O;
	}

	@Override
	public void i3who(MOB mob, String mudName)
	{
		if(mob==null)
			return;
		if((!i3online())&&(!imc2online()))
			return;
		if((mudName==null)||(mudName.length()==0))
		{
			mob.tell(L("You must specify a mud name."));
			return;
		}
		if(i3online()&&Intermud.isAPossibleMUDName(mudName))
		{
			mudName=Intermud.translateName(mudName);
			if(!Intermud.isUp(mudName))
			{
				mob.tell(L("@x1 is not available.",mudName));
				return;
			}
			final WhoPacket wk=new WhoPacket();
			wk.type=Packet.WHO_REQUEST;
			wk.sender_name=mob.Name();
			wk.target_mud=mudName;
			wk.who=new Vector();
			try
			{
			wk.send();
			}catch(final Exception e){Log.errOut("IMudClient",e);}
		}
		else
		if(imc2online()&&(imc2.getIMC2Mud(mudName)!=null))
			imc2.imc_send_who(mob.name(),imc2.getIMC2Mud(mudName).name,"who",mob.phyStats().level(),0);
		else
		{
			mob.tell(L("'@x1' is not a mud name.",mudName));
			return;
		}
	}

	@Override
	public boolean i3online()
	{
		return Intermud.isConnected() && (!CMSecurity.isDisabled(DisFlag.I3));
	}

	@Override
	public boolean imc2online()
	{
		if((imc2==null)||(CMSecurity.isDisabled(DisFlag.IMC2)))
			return false;
		return imc2.imc_active==IMC2Driver.IA_UP;
	}
	@Override
	public void imc2mudInfo(MOB mob, String parms)
	{
		if((mob==null)||(!imc2online()))
			return;
		if((parms==null)||(parms.length()==0)||(imc2.getIMC2Mud(parms)==null))
		{
			mob.tell(L("You must specify a mud name."));
			return;
		}
		imc2.imc_send_who(mob.name(),imc2.getIMC2Mud(parms).name,"info",mob.phyStats().level(),0);
	}

	@Override
	public void i3chanwho(MOB mob, String channel, String mudName)
	{
		if((mob==null)||(!i3online()))
			return;
		if((mudName==null)||(mudName.length()==0))
		{
			mob.tell(L("You must specify a mud name."));
			return;
		}
		if((channel==null)||(channel.length()==0)||(Intermud.getRemoteChannel(channel).length()==0))
		{
			mob.tell(L("You must specify an InterMud 3 channel name."));
			return;
		}
		if(!Intermud.isAPossibleMUDName(mudName))
		{
			mob.tell(L("'@x1' is an unknown mud.",mudName));
			return;
		}
		mudName=Intermud.translateName(mudName);
		if(!Intermud.isUp(mudName))
		{
			mob.tell(L("@x1 is not available.",mudName));
			return;
		}
		final ChannelWhoRequest ck=new ChannelWhoRequest();
		ck.sender_name=mob.Name();
		ck.target_mud=mudName;
		ck.channel=channel;
		try
		{
		ck.send();
		}catch(final Exception e){Log.errOut("IMudClient",e);}
	}

	@Override
	public void i3channelAdd(MOB mob, String channel)
	{
		if((mob==null)||(!i3online()))
			return;
		if((channel==null)||(channel.length()==0)||(Intermud.getLocalChannel(channel).length()==0))
		{
			mob.tell(L("You must specify an existing channel to add it to the i3 network."));
			return;
		}

		final ChannelAdd ck=new ChannelAdd();
		ck.sender_name=mob.Name();
		ck.channel=channel;
		try
		{
		ck.send();
		}catch(final Exception e){Log.errOut("IMudClient",e);}
	}

	@Override
	public void i3channelListen(MOB mob, String channel)
	{
		if((mob==null)||(!i3online()))
			return;
		if((channel==null)||(channel.length()==0))
		{
			mob.tell(L("You must specify a channel name listed in your INI file."));
			return;
		}
		if(Intermud.getLocalChannel(channel).length()==0)
		{
			if(Intermud.registerFakeChannel(channel).length()>0)
				mob.tell(L("Channel was not officially registered."));
			else
				mob.tell(L("Channel listen failed."));
		}
		final ChannelListen ck=new ChannelListen();
		ck.sender_name=mob.Name();
		ck.channel=channel;
		ck.onoff="1";
		try
		{
		ck.send();
		}catch(final Exception e){Log.errOut("IMudClient",e);}
	}

	@Override
	public void i3channelSilence(MOB mob, String channel)
	{
		if((mob==null)||(!i3online()))
			return;
		if((channel==null)
		   ||(channel.length()==0)
		   ||(Intermud.getLocalChannel(channel).length()==0))
		{
			mob.tell(L("You must specify an actual channel name."));
			return;
		}
		if(Intermud.removeFakeChannel(channel).length()>0)
			mob.tell(L("Unofficial channel closed."));

		final ChannelListen ck=new ChannelListen();
		ck.sender_name=mob.Name();
		ck.channel=channel;
		ck.onoff="0";
		try
		{
		ck.send();
		}catch(final Exception e){Log.errOut("IMudClient",e);}
	}

	@Override
	public void i3channelRemove(MOB mob, String channel)
	{
		if((mob==null)||(!i3online()))
			return;
		if((channel==null)||(channel.length()==0)||(Intermud.getRemoteChannel(channel).length()==0))
		{
			mob.tell(L("You must specify a valid InterMud 3 channel name."));
			return;
		}
		final ChannelDelete ck=new ChannelDelete();
		ck.sender_name=mob.Name();
		ck.channel=channel;
		try
		{
		ck.send();
		}catch(final Exception e){Log.errOut("IMudClient",e);}
	}

	@Override
	public void i3tell(MOB mob, String tellName, String mudName, String message)
	{
		if(mob==null)
			return;
		if((!i3online())&&(!imc2online()))
			return;
		if((mudName==null)||(mudName.length()==0))
		{
			mob.tell(L("You must specify a mud name."));
			return;
		}
		if((tellName==null)||(tellName.length()<1))
		{
			mob.tell(L("You must specify someone to talk to."));
			return;
		}
		if((message==null)||(message.length()<1))
		{
			mob.tell(L("You must enter a message!"));
			return;
		}
		if(i3online()&&Intermud.isAPossibleMUDName(mudName))
		{
			mudName=Intermud.translateName(mudName);
			if(!Intermud.isUp(mudName))
			{
				mob.tell(L("@x1 is not available.",mudName));
				return;
			}
			mob.tell(L("You tell @x1 '@x2'",tellName,message));
			final TellPacket tk=new TellPacket();
			tk.sender_name=mob.Name();
			tk.sender_visible_name=mob.Name();
			tk.target_mud=mudName;
			tk.target_name=tellName;
			tk.message=message;
			if(mob.playerStats()!=null)
				mob.playerStats().addTellStack("You tell "+tellName+" '"+message+"'");
			try
			{
			tk.send();
			}catch(final Exception e){Log.errOut("IMudClient",e);}
		}
		else
		if(imc2online()&&(imc2.getIMC2Mud(mudName)!=null))
		{
			tellName=CMStrings.capitalizeAndLower(tellName)+"@"+imc2.getIMC2Mud(mudName).name;
			mob.tell(L("^CYou tell @x1 '@x2'^?",tellName,message));
			if(mob.playerStats()!=null)
				mob.playerStats().addTellStack("You tell "+tellName+" '"+message+"'");
			imc2.imc_send_tell(mob.name(),tellName,message,0,CMLib.flags().isInvisible(mob)?1:0);
		}
		else
		{
			mob.tell(L("@x1 is an unknown mud.",mudName));
			return;
		}
	}

	public void destroymob(MOB mob)
	{
		if(mob==null)
			return;
		final Room R=mob.location();
		mob.destroy();
		if(R!=null)
			R.destroy();
	}

	@Override
	public void i3channel(MOB mob, String channelName, String message)
	{
		if(mob==null)
			return;
		if((!i3online())&&(!imc2online()))
			return;
		if((channelName==null)||(channelName.length()==0))
		{
			mob.tell(L("You must specify a channel name."));
			return;
		}
		if((message==null)||(message.length()<1))
		{
			mob.tell(L("You must enter a message!"));
			return;
		}
		if(i3online()&&Intermud.getRemoteChannel(channelName).length()>0)
		{
			final ChannelPacket ck=new ChannelPacket();
			ck.channel=channelName; // ck will translate it for us
			ck.sender_name=mob.Name();
			ck.sender_visible_name=mob.Name();
			if((message.startsWith(":")||message.startsWith(","))&&(message.trim().length()>1))
			{
				String msgstr=message.substring(1);
				final Vector<String> V=CMParms.parse(msgstr);
				Social S=CMLib.socials().fetchSocial(V,true,false);
				if(S==null)
					S=CMLib.socials().fetchSocial(V,false,false);
				CMMsg msg=null;
				if(S!=null)
				{
					msg=S.makeChannelMsg(mob,0,channelName,V,true);
					if((msg.target()!=null)&&(msg.target().name().indexOf('@')>=0))
					{
						final int x=msg.target().name().indexOf('@');
						String mudName=msg.target().name().substring(x+1);
						final String tellName=msg.target().name().substring(0,x);
						if((mudName==null)||(mudName.length()==0))
						{
							mob.tell(L("You must specify a mud name."));
							return;
						}
						if((tellName==null)||(tellName.length()<1))
						{
							mob.tell(L("You must specify someone to emote to."));
							return;
						}
						if(!Intermud.isAPossibleMUDName(mudName))
						{
							mob.tell(L("'@x1' is an unknown mud.",mudName));
							return;
						}
						mudName=Intermud.translateName(mudName);
						if(!Intermud.isUp(mudName))
						{
							mob.tell(L("@x1 is not available.",mudName));
							return;
						}
						ck.target_mud=mudName;
						ck.target_name=tellName;
						ck.target_visible_name=tellName;
					}
					else
					if(msg.target()!=null)
					{
						ck.target_name=msg.target().name();
						ck.target_visible_name=msg.target().name();
					}
					if((msg.target()!=null)&&(msg.targetMessage()!=null)&&(msg.targetMessage().length()>0))
						ck.message_target=socialFixOut(CMStrings.removeColors(msg.targetMessage()));
					if((msg.othersMessage()!=null)&&(msg.othersMessage().length()>0))
						ck.message=socialFixOut(CMStrings.removeColors(msg.othersMessage()));
					else
						ck.message=socialFixOut(CMStrings.removeColors(msg.sourceMessage()));
				}
				else
				{
					if(msgstr.trim().startsWith("'")||msgstr.trim().startsWith("`"))
						msgstr=msgstr.trim();
					else
						msgstr=" "+msgstr.trim();
					ck.message=socialFixOut("<S-NAME>"+msgstr);
				}
				if((ck.target_name!=null)&&(ck.target_name.length()>0))
					ck.type=Packet.CHAN_TARGET;
				else
					ck.type=Packet.CHAN_EMOTE;
			}
			else
				ck.message=message;
			try
			{
				ck.send();
			}catch(final Exception e){Log.errOut("IMudClient",e);}
		}
		else
		if(imc2online()&&(imc2.getAnIMC2Channel(channelName)!=null))
		{
			int emote=0;
			if((message.startsWith(":")||message.startsWith(","))&&(message.trim().length()>1))
			{
				message=message.substring(1);
				final MOB mob2=CMClass.getFactoryMOB();
				mob2.setName(mob.Name()+"@"+imc2.imc_name);
				mob2.setLocation(CMClass.getLocale("StdRoom"));
				final Vector<String> V=CMParms.parse(message);
				Social S=CMLib.socials().fetchSocial(V,true,false);
				if(S==null)
					S=CMLib.socials().fetchSocial(V,false,false);
				CMMsg msg=null;
				if(S!=null)
				{
					msg=S.makeChannelMsg(mob,0,channelName,V,true);
					if((msg.target()!=null)&&(msg.target().name().indexOf('@')>=0))
					{
						final int x=msg.target().name().indexOf('@');
						final String mudName=msg.target().name().substring(x+1);
						final String tellName=msg.target().name().substring(0,x);
						if((mudName==null)||(mudName.length()==0))
						{
							mob.tell(L("You must specify a mud name."));
							destroymob(mob2);
							return;
						}
						if((tellName==null)||(tellName.length()<1))
						{
							mob.tell(L("You must specify someone to emote to."));
							destroymob(mob2);
							return;
						}
						if(imc2.getIMC2Mud(mudName)==null)
						{
							mob.tell(L("@x1 is not available.",mudName));
							destroymob(mob2);
							return;
						}
					}

					if((msg.othersMessage()!=null)&&(msg.othersMessage().length()>0))
						message=CMLib.coffeeFilter().fullOutFilter(null,CMClass.sampleMOB(),mob2,msg.target(),null,CMStrings.removeColors(msg.othersMessage()),false);
					else
						message=CMLib.coffeeFilter().fullOutFilter(null,CMClass.sampleMOB(),mob2,msg.target(),null,CMStrings.removeColors(msg.sourceMessage()),false);
					if(message.toUpperCase().startsWith((mob.Name()+"@"+imc2.imc_name).toUpperCase()))
						message=message.substring((mob.Name()+"@"+imc2.imc_name).length()).trim();
					emote=2;
				}
				emote=1;
				destroymob(mob2);
			}
			final IMC_CHANNEL c=imc2.getAnIMC2Channel(channelName);
			imc2.imc_send_chat(mob.name(),c.name,message,c.level,emote);
		}
		else
		{
			mob.tell(L("You must specify a channel name."));
			return;
		}
	}

	@Override
	public void i3locate(MOB mob, String mobName)
	{
		if(mob==null)
			return;
		if((!i3online())&&(!imc2online()))
			return;

		if((mobName==null)||(mobName.length()==0))
		{
			mob.tell(L("You must specify a name."));
			return;
		}

		if(i3online())
		{
			final LocateQueryPacket ck=new LocateQueryPacket();
			ck.sender_name=mob.Name();
			ck.user_name=mobName;
			try
			{
			ck.send();
			}catch(final Exception e){Log.errOut("IMudClient",e);}
		}
		if(imc2online())
			imc2.imc_send_whois(mob.Name(),mobName,mob.phyStats().level());
	}

	@Override
	public void i3pingRouter(MOB mob)
	{
		if(mob==null)
			return;
		if((!i3online())&&(!imc2online()))
			return;
		if(i3online())
		{
			final PingPacket ck=new PingPacket(I3Server.getMudName());
			try
			{
			ck.send();
			}catch(final Exception e){Log.errOut("IMudClient",e);}
		}
	}

	@Override
	public void i3finger(MOB mob, String mobName, String mudName)
	{
		if(mob==null)
			return;
		if((!i3online())&&(!imc2online()))
			return;

		if((mobName==null)||(mobName.length()==0))
		{
			mob.tell(L("You must specify a name."));
			return;
		}

		if(i3online())
		{
			final FingerRequest ck=new FingerRequest();
			ck.sender_name=mob.Name();
			ck.target_name=mobName;
			ck.target_mud=mudName;
			try
			{
			ck.send();
			}catch(final Exception e){Log.errOut("IMudClient",e);}
		}
		if(imc2online())
			imc2.imc_send_whois(mob.Name(),mobName,mob.phyStats().level());
	}

	public String getMudInfo(I3Mud mudToShow)
	{
		final StringBuilder buf=new StringBuilder("");
		buf.append(CMStrings.padRight(L("Name"),10)+": "+mudToShow.mud_name+"\n\r");
		buf.append(CMStrings.padRight(L("Address"),10)+": "+mudToShow.address+"\n\r");
		buf.append(CMStrings.padRight(L("Port"),10)+": "+mudToShow.player_port+"\n\r");
		buf.append(CMStrings.padRight(L("Admin@"),10)+": "+mudToShow.admin_email+"\n\r");
		buf.append(CMStrings.padRight(L("Base"),10)+": "+mudToShow.base_mudlib+"\n\r");
		buf.append(CMStrings.padRight(L("MudLib"),10)+": "+mudToShow.mudlib+"\n\r");
		buf.append(CMStrings.padRight(L("Type"),10)+": "+mudToShow.mud_type+"\n\r");
		buf.append(CMStrings.padRight(L("Driver"),10)+": "+mudToShow.driver+"\n\r");
		buf.append(CMStrings.padRight(L("Status"),10)+": "+mudToShow.status+"\n\r");
		return buf.toString();
	}

	public List<I3Mud> mudFinder(String parms)
	{
		final MudList list=Intermud.getAllMudsList();
		if(list==null)
			return null;
		final Map<String,I3Mud> l=list.getMuds();
		for(final I3Mud m : l.values())
		{
			if(m.mud_name.equals(parms))
				return new XVector<I3Mud>(m);
		}
		for(final I3Mud m : l.values())
		{
			if(m.mud_name.equalsIgnoreCase(parms))
				return new XVector<I3Mud>(m);
		}
		if(parms.startsWith("*")&&(!parms.endsWith("*")))
		{
			final List<I3Mud> muds=new XVector<I3Mud>();
			for(final I3Mud m : l.values())
			{
				if(m.mud_name.toLowerCase().endsWith(parms.toLowerCase()))
					muds.add(m);
			}
			return muds;
		}
		if(parms.endsWith("*")&&(!parms.startsWith("*")))
		{
			final List<I3Mud> muds=new XVector<I3Mud>();
			for(final I3Mud m : l.values())
			{
				if(m.mud_name.toLowerCase().startsWith(parms.toLowerCase()))
					muds.add(m);
			}
			return muds;
		}
		if(parms.endsWith("*")&&(parms.startsWith("*")))
		{
			final List<I3Mud> muds=new XVector<I3Mud>();
			for(final I3Mud m : l.values())
			{
				if(m.mud_name.toLowerCase().indexOf(parms.toLowerCase())>=0)
					muds.add(m);
			}
			return muds;
		}
		final List<I3Mud> muds=new XVector<I3Mud>();
		for(final I3Mud m : l.values())
		{
			if((m.state<0)&&(CMLib.english().containsString(m.mud_name,parms)))
				muds.add(m);
		}
		return muds;
	}

	@Override
	public void i3mudInfo(MOB mob, String parms)
	{
		if((mob==null)||(!i3online()))
			return;
		if(mob.isMonster())
			return;
		final StringBuffer buf=new StringBuffer("\n\r");
		final List<I3Mud> muds=this.mudFinder(parms);
		if(muds.size()==0)
			buf.append("Not found!");
		else
		for(final I3Mud mudToShow : muds)
		{
			buf.append(CMStrings.padRight(L("Name"),10)+": "+mudToShow.mud_name+"\n\r");
			buf.append(CMStrings.padRight(L("Address"),10)+": "+mudToShow.address+"\n\r");
			buf.append(CMStrings.padRight(L("Port"),10)+": "+mudToShow.player_port+"\n\r");
			buf.append(CMStrings.padRight(L("Admin@"),10)+": "+mudToShow.admin_email+"\n\r");
			buf.append(CMStrings.padRight(L("Base"),10)+": "+mudToShow.base_mudlib+"\n\r");
			buf.append(CMStrings.padRight(L("MudLib"),10)+": "+mudToShow.mudlib+"\n\r");
			buf.append(CMStrings.padRight(L("Type"),10)+": "+mudToShow.mud_type+"\n\r");
			buf.append(CMStrings.padRight(L("Driver"),10)+": "+mudToShow.driver+"\n\r");
			buf.append(CMStrings.padRight(L("Status"),10)+": "+mudToShow.status+"\n\r");
		}
		mob.session().wraplessPrintln(buf.toString());
	}

	@Override
	public void giveIMC2MudList(MOB mob)
	{
		if((mob==null)||(!imc2online()))
			return;
		if(mob.isMonster())
			return;
		final Hashtable l=imc2.query_muds();
		final Vector V=new Vector();
		for(final Enumeration e=l.elements();e.hasMoreElements();)
		{
			final REMOTEINFO m=(REMOTEINFO)e.nextElement();
			boolean done=false;
			for(int v=0;v<V.size();v++)
			{
				final REMOTEINFO m2=(REMOTEINFO)V.elementAt(v);
				if(m2.name.toUpperCase().compareTo(m.name.toUpperCase())>0)
				{
					V.insertElementAt(m,v);
					done=true;
					break;
				}
			}
			if(!done)
				V.addElement(m);
		}
		final StringBuffer buf=new StringBuffer("\n\rIMC2 Mud List:\n\r");
		for(int v=0;v<V.size();v++)
		{
			final REMOTEINFO m=(REMOTEINFO)V.elementAt(v);
			buf.append("["+CMStrings.padRight(m.name,15)+"]["+CMStrings.padRight(m.version,30)+"] "+CMStrings.padRight(m.network,13)+" ("+CMStrings.padRight(m.hub,10)+")\n\r");
		}
		mob.session().wraplessPrintln(buf.toString());
	}

	@Override
	public void giveI3MudList(MOB mob)
	{
		if((mob==null)||(!i3online()))
			return;
		if(mob.isMonster())
			return;
		final StringBuffer buf=new StringBuffer("\n\rI3 Mud List:\n\r");
		final MudList list=Intermud.getAllMudsList();
		final Vector V=new Vector();
		int col1Width=ListingLibrary.ColFixer.fixColWidth(25, mob);
		int col2Width=ListingLibrary.ColFixer.fixColWidth(25, mob);
		if(list!=null)
		{
			for(final I3Mud m : list.getMuds().values())
			{
				if(m.state<0)
				{
					boolean done=false;
					for(int v=0;v<V.size();v++)
					{
						final I3Mud m2=(I3Mud)V.elementAt(v);
						if(m2.mud_name.toUpperCase().compareTo(m.mud_name.toUpperCase())>0)
						{
							V.insertElementAt(m,v);
							done=true;
							break;
						}
					}
					if(!done)
						V.addElement(m);
				}
			}
			for(int v=0;v<V.size();v++)
			{
				final I3Mud m=(I3Mud)V.elementAt(v);
				if((m!=null)&&(m.base_mudlib!=null))
				{
					final String mudlib = m.base_mudlib.startsWith("CoffeeMud") ? "^H"+m.base_mudlib+"^?" : m.base_mudlib;
					buf.append("["+CMStrings.padRight(m.mud_name,col1Width)+"]["+CMStrings.padRight(mudlib,col2Width)+"] "+m.address+" ("+m.player_port+")\n\r");
				}
			}
		}
		mob.session().wraplessPrintln(buf.toString());
	}

	@Override
	public void giveI3ChannelsList(MOB mob)
	{
		if((mob==null)||(!i3online()))
			return;
		if(mob.isMonster())
			return;
		final StringBuffer buf=new StringBuffer("\n\rI3 Channels List:\n\r");
		final ChannelList list=Intermud.getAllChannelList();
		if(list!=null)
		{
			final Hashtable l=list.getChannels();
			for(final Enumeration e=l.elements();e.hasMoreElements();)
			{
				final Channel c=(Channel)e.nextElement();
				if(c.type==0)
					buf.append("["+CMStrings.padRight(c.channel,20)+"] "+c.owner+"\n\r");
			}
		}
		mob.session().wraplessPrintln(buf.toString());
	}

	@Override
	public void giveIMC2ChannelsList(MOB mob)
	{
		if((mob==null)||(!imc2online()))
			return;
		if(mob.isMonster())
			return;
		final StringBuffer buf=new StringBuffer("\n\rIMC2 Channels List:\n\r");
		final Hashtable channels=imc2.query_channels();
		buf.append(CMStrings.padRight(L("Name"), 22)+CMStrings.padRight(L("Policy"),25)+CMStrings.padRight(L("Owner"),20)+"\n\r");
		final Enumeration e = channels.keys();
		while (e.hasMoreElements())
		{
			final String key = (String) e.nextElement();
			final IMC_CHANNEL r = (IMC_CHANNEL) channels.get(key);
			if (r != null)
			{
				String policy = "final public";
				if (r.policy == IMC2Driver.CHAN_PRIVATE)
					policy = "(private)";
				else
				if (r.policy == IMC2Driver.CHAN_COPEN)
					policy = "open";
				else
				if (r.policy == IMC2Driver.CHAN_CPRIVATE)
					policy = "(cprivate)";

				buf.append(CMStrings.padRight(key, 22)+
						   CMStrings.padRight(policy+"("+r.level+")",25)+
						   r.owner+"\n\r");
			}
		}
		mob.session().wraplessPrintln(buf.toString());
	}

	@Override
	public boolean isIMC2channel(String channelName)
	{
		if(!imc2online())
			return false;
		final Object remote=imc2.getAnIMC2Channel(channelName);
		if(remote==null)
			return false;
		return true;
	}

	@Override
	public boolean isI3channel(String channelName)
	{
		if(!i3online())
			return false;
		final String remote=Intermud.getRemoteChannel(channelName);
		if(remote.length()==0)
			return false;
		return true;
	}

	public String socialFixOut(String str)
	{
		str=CMStrings.replaceAll(str,"<S-NAME>","$N");
		str=CMStrings.replaceAll(str,"<T-NAME>","$O");
		str=CMStrings.replaceAll(str,"<T-NAMESELF>","$O");
		str=CMStrings.replaceAll(str,"<S-HIM-HER>","$m");
		str=CMStrings.replaceAll(str,"<T-HIM-HER>","$M");
		str=CMStrings.replaceAll(str,"<S-HIS-HER>","$s");
		str=CMStrings.replaceAll(str,"<T-HIS-HER>","$S");
		str=CMStrings.replaceAll(str,"<S-HE-SHE>","$e");
		str=CMStrings.replaceAll(str,"<T-HE-SHE>","$E");
		str=CMStrings.replaceAll(str,"\'","`");
		if(str.equals(""))
			return "$";
		return str.trim();
	}

}