text:
namespace Lucene
{
    /// Implements the policy for breaking text into multiple fragments for consideration by the
    /// {@link Highlighter} class. A sophisticated implementation may do this on the basis of
    /// detecting end of sentences in the text.
    class LPPCONTRIBAPI Fragmenter
    {
    public:
        virtual ~Fragmenter();
        LUCENE_INTERFACE(Fragmenter);

    public:
        /// Initializes the Fragmenter. You can grab references to the Attributes you are
        /// interested in from tokenStream and then access the values in {@link #isNewFragment()}.
        /// @param originalText the original source text.
        /// @param tokenStream the {@link TokenStream} to be fragmented.
        virtual void start(const String& originalText, TokenStreamPtr tokenStream);

        /// Test to see if this token from the stream should be held in a new TextFragment.
        /// Every time this is called, the TokenStream passed to start(String, TokenStream)
        /// will have been incremented.
        virtual bool isNewFragment();
    };
}

#endif


text:
/* eslint-disable ember/no-new-mixins */
import { find, visit } from '@ember/test-helpers';
import Mixin from '@ember/object/mixin';
import Component from '@ember/component';
import { inspect } from '@ember/debug';
import { run } from '@ember/runloop';
import { guidFor } from '@ember/object/internals';
import EmberObject, { computed } from '@ember/object';
import MutableArray from '@ember/array/mutable';
import ArrayProxy from '@ember/array/proxy';
import ObjectProxy from '@ember/object/proxy';
import Service from '@ember/service';
import { VERSION } from '@ember/version';
import { tracked } from '@glimmer/tracking';
import { module, skip, test } from 'qunit';
import { hbs } from 'ember-cli-htmlbars';
import require from 'require';
import hasEmberVersion from '@ember/test-helpers/has-ember-version';
import { compareVersion } from 'ember-debug/utils/version';
import EmberDebug from 'ember-debug/main';
import setupEmberDebugTest from '../helpers/setup-ember-debug-test';
import EmberRoute from '@ember/routing/route';
import Controller from '@ember/controller';

const GlimmerComponent = (function () {
  try {
    return require('@glimmer/component').default;
  } catch (e) {
    // ignore, return undefined
  }
})();

let objectInspector;

// TODO switch to an adapter architecture, similar to the acceptance tests
async function captureMessage(type, callback) {
  if (!EmberDebug.port) {
    throw new Error('Cannot call captureMessage without a port');
  }

  let send = EmberDebug.port.send;

  try {
    let captured;

    EmberDebug.port.send = (name, message) => {
      if (!captured && name === type) {
        captured = message;
      } else {
        send.call(EmberDebug.port, name, message);
      }
    };

    await callback();

    if (captured) {
      return captured;
    } else {
      throw new Error(`Did not send a message of type ${type}`);
    }
  } finally {
    EmberDebug.port.send = send;
  }
}

async function inspectObject(object) {
  if (!objectInspector) {
    throw new Error('Cannot call captureMessage without objectInspector');
  }

  return captureMessage('objectInspector:updateObject', () => {
    objectInspector.sendObject(object);
  });
}

module('Ember Debug - Object Inspector', function (hooks) {
  setupEmberDebugTest(hooks, {
    routes() {
      this.route('simple');
    },
  });

  hooks.beforeEach(async function () {
    this.owner.register('route:application', EmberRoute);

    this.owner.register('controller:application', Controller);

    this.owner.register(
      'template:application',
      hbs(
        '
{{outlet}}
',
        { moduleName: 'my-app/templates/application.hbs' }
      )
    );
    this.owner.register('route:simple', EmberRoute);
    this.owner.register('component:x-simple', Component);
    this.owner.register(
      'template:simple',
      hbs`Simple <Input class="simple-input"/> {{x-simple class="simple-view"}}`
    );

    objectInspector = EmberDebug.get('objectInspector');
  });

  test('An Ember Object is correctly transformed into an inspection hash', async function (assert) {
    let date = new Date();

    let Parent = EmberObject.extend({
      id: null,
      name: 'My Object',
    });

    Parent.reopenClass({
      toString() {
        return 'Parent Object';
      },
    });

    let inspected = Parent.create({
      id: 1,
      toString() {
        return `Object:${this.name}`;
      },
      nullVal: null,
      dateVal: date,
    });

    let message = await inspectObject(inspected);

    assert.strictEqual(message.name, 'Object:My Object');

    let firstDetail = message.details[0];
    assert.strictEqual(firstDetail.name, 'Own Properties');

    assert.strictEqual(
      firstDetail.properties.length,
      4,
      'methods are included'
    );

    let idProperty = firstDetail.properties[0];
    assert.strictEqual(idProperty.name, 'id');
    assert.strictEqual(idProperty.value.type, 'type-number');
    assert.strictEqual(idProperty.value.inspect, '1');

    let toStringProperty = firstDetail.properties[1];
    assert.strictEqual(toStringProperty.name, 'toString');
    assert.strictEqual(toStringProperty.value.type, 'type-function');

    let nullProperty = firstDetail.properties[2];
    assert.strictEqual(nullProperty.name, 'nullVal');
    assert.strictEqual(nullProperty.value.type, 'type-null');
    assert.strictEqual(nullProperty.value.inspect, 'null');

    let prop = firstDetail.properties[3];
    assert.strictEqual(prop.name, 'dateVal');
    assert.strictEqual(prop.value.type, 'type-date');
    assert.strictEqual(prop.value.inspect, date.toString());

    let secondDetail = message.details[1];
    assert.ok(secondDetail.name.includes('Parent Object'));

    idProperty = secondDetail.properties[0];
    assert.strictEqual(idProperty.name, 'id');
    assert.strictEqual(idProperty.overridden, 'Own Properties');

    let nameProperty = secondDetail.properties[1];
    assert.strictEqual(nameProperty.name, 'name');
    assert.strictEqual(nameProperty.value.inspect, inspect('My Object'));
  });

  test('An ES6 Class is correctly transformed into an inspection hash', async function (assert) {
    if (compareVersion(VERSION, '3.9.0') === -1) {
      assert.expect(0);
      return;
    }
    let date = new Date();

    class ObjectWithTracked {
      @tracked item1 = 'item1';
      @tracked item2 = 'item2';
    }

    class Parent {
      // eslint-disable-next-line constructor-super
      constructor(param) {
        Object.assign(this, param);
      }

      @tracked trackedProperty = 'tracked';
      objectWithTracked = new ObjectWithTracked();

      id = null;
      name = 'My Object';

      toString() {
        return 'Parent Object';
      }

      get getterWithTracked() {
        const a = this.objectWithTracked.item1 + this.objectWithTracked.item2;
        return a + this.trackedProperty;
      }

      get(k) {
        return this[k];
      }

      @computed
      get aCP() {
        return true;
      }
    }

    let inspected = new Parent({
      id: 1,
      toString() {
        return `Object:${this.name}`;
      },
      nullVal: null,
      dateVal: date,
    });

    let message = await captureMessage('objectInspector:updateObject', () => {
      objectInspector.sendObject(inspected);
    });

    assert.strictEqual(message.name, 'Object:My Object');

    let firstDetail = message.details[0];
    assert.strictEqual(firstDetail.name, 'Own Properties');

    assert.strictEqual(
      firstDetail.properties.length,
      6,
      'methods are included'
    );

    let objectWithTrackedProperty = firstDetail.properties[0];
    assert.strictEqual(objectWithTrackedProperty.name, 'objectWithTracked');
    assert.strictEqual(objectWithTrackedProperty.value.type, 'type-object');
    assert.strictEqual(objectWithTrackedProperty.value.inspect, '{  }');

    let idProperty = firstDetail.properties[1];
    assert.strictEqual(idProperty.name, 'id');
    assert.strictEqual(idProperty.value.type, 'type-number');
    assert.strictEqual(idProperty.value.inspect, '1');

    let nullProperty = firstDetail.properties[2];
    assert.strictEqual(nullProperty.name, 'name');
    assert.strictEqual(nullProperty.value.type, 'type-string');
    assert.strictEqual(nullProperty.value.inspect, '"My Object"');

    let prop = firstDetail.properties[3];

    assert.strictEqual(prop.name, 'toString');
    assert.strictEqual(prop.value.type, 'type-function');

    prop = firstDetail.properties[4];
    assert.strictEqual(prop.name, 'nullVal');
    assert.strictEqual(prop.value.type, 'type-null');
    assert.strictEqual(prop.value.inspect, 'null');

    prop = firstDetail.properties[5];
    assert.strictEqual(prop.name, 'dateVal');
    assert.strictEqual(prop.value.type, 'type-date');
    assert.strictEqual(prop.value.inspect, date.toString());

    let secondDetail = message.details[1];
    prop = secondDetail.properties[0];
    assert.strictEqual(prop.name, 'toString');
    assert.strictEqual(prop.value.type, 'type-function');

    prop = secondDetail.properties[1];
    assert.strictEqual(prop.name, 'getterWithTracked');
    assert.strictEqual(prop.value.type, 'type-string');
    assert.strictEqual(prop.value.inspect, '"item1item2tracked"');
    const dependentKeys =
      compareVersion(VERSION, '3.16.10') === 0
        ? 'item1,item2,trackedProperty'
        : 'ObjectWithTracked,  •  --  item1,  •  --  item2,Object:My Object.trackedProperty';
    assert.strictEqual(prop.dependentKeys.toString(), dependentKeys);

    prop = secondDetail.properties[2];
    assert.strictEqual(prop.name, 'get');
    assert.strictEqual(prop.value.type, 'type-function');

    prop = secondDetail.properties[3];
    assert.strictEqual(prop.name, 'aCP');
    assert.strictEqual(prop.value.type, 'type-boolean');
    assert.strictEqual(prop.dependentKeys.toString(), '');
  });

  skip('Correct mixin order with es6 class', async function (assert) {
    class MyMixinClass extends Mixin {
      toString() {
        return 'MyMixin';
      }
    }
    const MyMixin = MyMixinClass.create({
      a: 'custom',
    });

    class MyMixin2Class extends Mixin {
      toString() {
        return 'MyMixin2';
      }
    }
    const MyMixin2 = MyMixin2Class.create({
      b: 'custom2',
    });

    class Baz extends EmberObject {}
    class Bar extends Baz {}
    class FooBar extends Bar.extend(MyMixin, MyMixin2) {}

    class Foo extends FooBar {
      foobar = 1;
    }

    const inspected = Foo.create({
      ownProp: 'hi',
    });

    let message = await inspectObject(inspected);

    const mixinNames = message.details.map((d) => d.name);
    const expectedMixinNames = [
      'Own Properties',
      'Foo',
      'FooBar',
      'MyMixin',
      'MyMixin2',
      'Bar',
      'Baz',
      'EmberObject',
      'Observable Mixin',
      'CoreObject',
    ];

    expectedMixinNames.forEach((expectedMixinName, i) => {
      assert.ok(
        mixinNames[i].includes(expectedMixinName),
        `${mixinNames[i]} : ${expectedMixinName}`
      );
    });
  });

  test('Proxies are skipped by default', async function (assert) {
    let inspected = EmberObject.extend({
      test: 'a',
      get abc() {
        return 1;
      },
    }).create();
    const proxy = ObjectProxy.create({
      content: inspected,
    });
    let message = await inspectObject(proxy);
    let computedProperty = message.details[1].properties[0];
    assert.strictEqual(computedProperty.name, 'test');
    assert.strictEqual(computedProperty.value.inspect, inspect('a'));

    let getterProperty = message.details[1].properties[1];
    assert.strictEqual(getterProperty.name, 'abc');
    assert.strictEqual(getterProperty.value.inspect, inspect(1));
  });

  test('Object Proxies are not skipped with _showProxyDetails', async function (assert) {
    let inspected = EmberObject.extend({
      test: 'a',
    }).create();
    const proxy = ObjectProxy.create({
      content: inspected,
      _showProxyDetails: true,
      prop: 'b',
    });
    let message = await inspectObject(proxy);
    let computedProperty = message.details[0].properties[1];
    assert.strictEqual(computedProperty.name, 'prop');
    assert.strictEqual(computedProperty.value.inspect, inspect('b'));
  });

  test('Array Proxies show content from toArray', async function (assert) {
    // support ArrayProxy -> MutableArray for ember data many-array
    // https://api.emberjs.com/ember-data/release/classes/ManyArray
    // https://github.com/emberjs/data/blob/master/packages/store/addon/-private/system/promise-proxies.js#L130
    const array = EmberObject.extend(MutableArray, {
      length: 1,
      content: ['internal'],
      objectAt() {
        return 1;
      },
    }).create();

    const proxy = ArrayProxy.create({
      content: array,
    });

    let message = await inspectObject(proxy);

    let property = message.details[0].properties[0];
    assert.strictEqual(property.name, '0');
    assert.strictEqual(property.value.inspect, '1');

    property = message.details[0].properties[1];
    assert.strictEqual(property.name, 'length');
    assert.strictEqual(property.value.inspect, '1');
  });

  skip('Correct mixin properties', async function (assert) {
    class MyMixin extends Mixin {
      toString() {
        return 'MyMixin1';
      }
    }
    class MyMixin2 extends Mixin {
      toString() {
        return 'MyMixin2';
      }
    }

    const mix1 = MyMixin.create({ a: 'custom1' });
    const mix2 = MyMixin2.create({ b: 'custom2' });

    class Foo extends EmberObject.extend(mix1, mix2) {}

    const instance = Foo.create({
      ownProp: 'b',
    });

    let { details } = await inspectObject(instance);

    assert.strictEqual(
      details[0].properties.length,
      1,
      'should not show mixin properties'
    );
    assert.strictEqual(details[0].properties[0].name, 'ownProp');

    assert.strictEqual(details[2].name, 'MyMixin1');
    assert.strictEqual(
      details[2].properties.length,
      1,
      'should only show own mixin properties'
    );
    assert.strictEqual(
      details[2].properties[0].value.inspect,
      inspect('custom1')
    );

    assert.strictEqual(details[3].name, 'MyMixin2');
    assert.strictEqual(
      details[3].properties.length,
      1,
      'should only show own mixin properties'
    );
    assert.strictEqual(
      details[3].properties[0].value.inspect,
      inspect('custom2')
    );
  });

  test('Computed properties are correctly calculated', async function (assert) {
    let inspected = EmberObject.extend({
      hi: computed(function () {
        assert.step('calculating computed');
        return 'Hello';
      }),
      _debugInfo() {
        return {
          propertyInfo: {
            expensiveProperties: ['hi'],
          },
        };
      },
    }).create();

    assert.step('inspector: sendObject');
    let message = await inspectObject(inspected);
    let computedProperty = message.details[1].properties[0];
    assert.strictEqual(computedProperty.name, 'hi');
    assert.ok(computedProperty.isComputed);
    assert.strictEqual(computedProperty.value.type, 'type-descriptor');
    assert.strictEqual(computedProperty.value.inspect, '<computed>');

    let id = message.objectId;

    assert.step('inspector: calculate');
    message = await captureMessage('objectInspector:updateProperty', () => {
      EmberDebug.port.trigger('objectInspector:calculate', {
        objectId: id,
        property: 'hi',
        mixinIndex: 1,
      });
    });
    assert.strictEqual(message.objectId, id);
    assert.strictEqual(message.property, 'hi');
    assert.strictEqual(message.mixinIndex, 1);
    assert.strictEqual(message.value.type, 'type-string');
    assert.strictEqual(message.value.inspect, inspect('Hello'));
    assert.ok(message.value.isCalculated);

    assert.verifySteps([
      'inspector: sendObject',
      'inspector: calculate',
      'calculating computed',
    ]);
  });

  test('Cached Computed properties are pre-calculated', async function (assert) {
    let inspected = EmberObject.extend({
      hi: computed(function () {
        return 'Hello';
      }),
    }).create();

    // pre-calculate CP
    inspected.get('hi');

    let message = await inspectObject(inspected);

    let computedProperty = message.details[1].properties[0];

    assert.strictEqual(computedProperty.name, 'hi');
    assert.ok(computedProperty.value.isCalculated);
    assert.strictEqual(computedProperty.value.type, 'type-string');
    assert.strictEqual(computedProperty.value.inspect, inspect('Hello'));
  });

  test('Properties are correctly bound', async function (assert) {
    let inspected = EmberObject.extend({
      name: 'Teddy',

      hi: computed({
        get() {
          return 'hello';
        },
        set(key, val) {
          return val;
        },
      }),

      _debugInfo() {
        return {
          propertyInfo: {
            expensiveProperties: ['hi'],
          },
        };
      },
    }).create();

    let { objectId } = await inspectObject(inspected);

    let message = await captureMessage('objectInspector:updateProperty', () => {
      run(() => inspected.set('name', 'Alex'));
    });

    assert.strictEqual(message.objectId, objectId);
    assert.strictEqual(message.property, 'name');
    assert.strictEqual(message.mixinIndex, 1);
    assert.true(message.value.isCalculated);
    assert.strictEqual(message.value.inspect, inspect('Alex'));
    assert.strictEqual(message.value.type, 'type-string');

    // un-cached computed properties are not bound until calculated

    message = await captureMessage('objectInspector:updateProperty', () => {
      run(() => inspected.set('hi', 'Hey'));
    });

    assert.strictEqual(message.objectId, objectId);
    assert.strictEqual(message.property, 'hi');
    assert.strictEqual(message.mixinIndex, 1);
    assert.ok(message.value.isCalculated);
    assert.strictEqual(message.value.inspect, inspect('Hey'));
    assert.strictEqual(message.value.type, 'type-string');

    message = await captureMessage('objectInspector:updateProperty', () => {
      EmberDebug.port.trigger('objectInspector:calculate', {
        objectId,
        property: 'hi',
        mixinIndex: 1,
      });
    });

    assert.strictEqual(message.objectId, objectId);
    assert.strictEqual(message.property, 'hi');
    assert.strictEqual(message.mixinIndex, 1);
    assert.ok(message.value.isCalculated);
    assert.strictEqual(message.value.inspect, inspect('Hey'));
    assert.strictEqual(message.value.type, 'type-string');

    message = await captureMessage('objectInspector:updateProperty', () => {
      run(() => inspected.set('hi', 'Hello!'));
    });

    assert.strictEqual(message.objectId, objectId);
    assert.strictEqual(message.property, 'hi');
    assert.strictEqual(message.mixinIndex, 1);
    assert.ok(message.value.isCalculated);
    assert.strictEqual(message.value.inspect, inspect('Hello!'));
    assert.strictEqual(message.value.type, 'type-string');
  });

  test('Properties can be updated through a port message', async function (assert) {
    let inspected = EmberObject.extend({
      name: 'Teddy',
    }).create();

    let { objectId } = await inspectObject(inspected);

    let message = await captureMessage('objectInspector:updateProperty', () => {
      EmberDebug.port.trigger('objectInspector:saveProperty', {
        objectId,
        mixinIndex: 1,
        property: 'name',
        value: 'Alex',
      });
    });

    assert.strictEqual(inspected.get('name'), 'Alex');

    assert.strictEqual(message.property, 'name');
    assert.strictEqual(message.value.inspect, inspect('Alex'));
    assert.strictEqual(message.value.type, 'type-string');
  });

  test('Date properties are converted to dates before being updated', async function (assert) {
    let newDate = new Date(2015, 0, 1);

    let inspected = EmberObject.extend({
      date: null,
    }).create();

    let { objectId } = await inspectObject(inspected);

    let message = await captureMessage('objectInspector:updateProperty', () => {
      EmberDebug.port.trigger('objectInspector:saveProperty', {
        objectId,
        mixinIndex: 1,
        property: 'date',
        value: newDate.getTime(),
        dataType: 'date',
      });
    });

    assert.strictEqual(inspected.get('date').getFullYear(), 2015);
    assert.strictEqual(inspected.get('date').getMonth(), 0);
    assert.strictEqual(inspected.get('date').getDate(), 1);

    assert.strictEqual(message.property, 'date');
    assert.strictEqual(message.value.inspect, inspect(newDate));
    assert.strictEqual(message.value.type, 'type-date');
  });

  test('Property grouping can be customized using _debugInfo', async function (assert) {
    let mixinToSkip = Mixin.create({});

    let Inspected = EmberObject.extend(mixinToSkip, {
      name: 'Teddy',
      gender: 'Male',
      hasChildren: false,
      toString: function () {
        return 'TestObject';
      },
      expensiveProperty: computed(function () {
        return '';
      }),
      _debugInfo() {
        return {
          propertyInfo: {
            includeOtherProperties: true,
            skipProperties: ['propertyToSkip'],
            skipMixins: ['MixinToSkip'],
            expensiveProperties: ['expensiveProperty'],
            groups: [
              {
                name: 'Basic Info',
                properties: ['name', 'gender'],
                expand: true,
              },
              {
                name: 'Family Info',
                properties: ['maritalStatus'],
              },
            ],
          },
        };
      },
    });

    Inspected.reopenClass({
      toString: function () {
        return 'TestObject';
      },
    });

    let inspected = Inspected.create({
      maritalStatus: 'Single',
      propertyToSkip: null,
    });

    let message = await inspectObject(inspected);

    assert.strictEqual(message.name, 'TestObject');

    assert.strictEqual(message.details[0].name, 'Basic Info');
    assert.strictEqual(message.details[0].properties[0].name, 'name');
    assert.strictEqual(message.details[0].properties[1].name, 'gender');
    assert.ok(message.details[0].expand);

    assert.strictEqual(message.details[1].name, 'Family Info');
    assert.strictEqual(message.details[1].properties[0].name, 'maritalStatus');

    assert.strictEqual(message.details[2].name, 'Own Properties');
    assert.strictEqual(
      message.details[2].properties.length,
      0,
      'Correctly skips properties'
    );

    assert.strictEqual(message.details[3].name, 'TestObject');
    assert.strictEqual(
      message.details[3].properties.length,
      3,
      'Correctly merges properties'
    );

    const toString = message.details[3].properties.find(
      (p) => p.name === 'toString'
    );
    const hasChildren = message.details[3].properties.find(
      (p) => p.name === 'hasChildren'
    );
    const expensiveProperty = message.details[3].properties.find(
      (p) => p.name === 'expensiveProperty'
    );
    assert.ok(toString, 'has toString');
    assert.ok(hasChildren, 'has hasChildren');
    assert.strictEqual(
      expensiveProperty.name,
      'expensiveProperty',
      'property name is correct'
    );
    assert.strictEqual(
      expensiveProperty.value.isCalculated,
      undefined,
      'Does not calculate expensive properties'
    );

    assert.notStrictEqual(
      message.details[3].name,
      'MixinToSkip',
      'Correctly skips mixins'
    );
  });

  test('Property grouping can be customized using _debugInfo when using Proxy', async function (assert) {
    class MyMixin extends Mixin {
      toString() {
        return 'MixinToSkip';
      }
    }

    let mixinToSkip = MyMixin.create({});

    let Inspected = EmberObject.extend(mixinToSkip, {
      name: 'Teddy',
      gender: 'Male',
      hasChildren: false,
      toString: function () {
        return 'TestObject';
      },
      expensiveProperty: computed(function () {
        return '';
      }),
      _debugInfo() {
        return {
          propertyInfo: {
            includeOtherProperties: true,
            skipProperties: ['propertyToSkip'],
            skipMixins: ['MixinToSkip'],
            expensiveProperties: ['expensiveProperty'],
            groups: [
              {
                name: 'Basic Info',
                properties: ['name', 'gender'],
                expand: true,
              },
              {
                name: 'Family Info',
                properties: ['maritalStatus'],
              },
            ],
          },
        };
      },
    });

    Inspected.reopenClass({
      toString: function () {
        return 'TestObject';
      },
    });

    let inspected = Inspected.create({
      maritalStatus: 'Single',
      propertyToSkip: null,
    });

    const proxy = ObjectProxy.create({
      content: inspected,
    });

    let message = await inspectObject(proxy);

    assert.ok(
      message.name.includes('ObjectProxy'),
      'object name should start with <ObjectProxy:'
    );

    assert.strictEqual(message.details[0].name, 'Basic Info');
    assert.strictEqual(message.details[0].properties[0].name, 'name');
    assert.strictEqual(message.details[0].properties[1].name, 'gender');
    assert.ok(message.details[0].expand);

    assert.strictEqual(message.details[1].name, 'Family Info');
    assert.strictEqual(message.details[1].properties[0].name, 'maritalStatus');

    assert.strictEqual(message.details[2].name, 'Own Properties');
    assert.strictEqual(
      message.details[2].properties.length,
      0,
      'Correctly skips properties'
    );

    assert.strictEqual(message.details[3].name, 'TestObject');
    assert.strictEqual(
      message.details[3].properties.length,
      3,
      'Correctly merges properties'
    );

    const hasChildren = message.details[3].properties.find(
      (p) => p.name === 'hasChildren'
    );
    const expensiveProperty = message.details[3].properties.find(
      (p) => p.name === 'expensiveProperty'
    );
    assert.strictEqual(hasChildren.name, 'hasChildren');
    assert.strictEqual(
      expensiveProperty.name,
      'expensiveProperty',
      'property name is correct'
    );
    assert.strictEqual(
      expensiveProperty.value.isCalculated,
      undefined,
      'Does not calculate expensive properties'
    );

    assert.notStrictEqual(
      message.details[3].name,
      'MixinToSkip',
      'Correctly skips mixins'
    );
  });

  test('Service should be successfully tagged as service on serialization', async function (assert) {
    let inspectedService = Service.extend({
      fooBoo() {
        return true;
      },
    }).create();

    let inspected = EmberObject.extend({
      service: inspectedService,
    }).create();

    let message = await inspectObject(inspected);

    let serializedServiceProperty = message.details[1].properties[0];

    assert.true(serializedServiceProperty.isService);
  });

  test('Proxy Service should be successfully tagged as service on serialization', async function (assert) {
    let inspectedService = Service.extend({
      unknownProperty() {
        return true;
      },
    }).create();

    let inspected = EmberObject.extend({
      service: inspectedService,
    }).create();

    let message = await inspectObject(inspected);

    let serializedServiceProperty = message.details[1].properties[0];

    assert.true(serializedServiceProperty.isService);
  });

  test('Computed property dependent keys and code should be successfully serialized', async function (assert) {
    let computedFn = function () {
      return this.foo + this.bar;
    };

    let inspected = EmberObject.extend({
      foo: true,
      bar: false,
      fooAndBar: computed('foo', 'bar', computedFn),
    }).create();

    let message = await inspectObject(inspected);
    let serializedComputedProperty = message.details[1].properties[2];

    assert.strictEqual(serializedComputedProperty.code, computedFn.toString());
    assert.strictEqual(serializedComputedProperty.dependentKeys[0], 'foo');
    assert.strictEqual(serializedComputedProperty.dependentKeys[1], 'bar');
  });

  test('Views are correctly handled when destroyed during transitions', async function (assert) {
    let objectId = null;

    await visit('/simple');

    objectId = find('.simple-view').id;
    let view = this.owner.lookup('-view-registry:main')[objectId];
    await inspectObject(view);

    assert.ok(
      objectInspector.sentObjects[objectId],
      'Object successfully retained.'
    );

    await visit('/');

    assert.ok(true, 'No exceptions thrown');
  });

  test('Objects are dropped on destruction', async function (assert) {
    let didDestroy = false;
    let object = EmberObject.create({
      willDestroy() {
        didDestroy = true;
      },
    });
    let objectId = guidFor(object);

    let message = await inspectObject(object);

    assert.strictEqual(message.objectId, objectId, 'objectId matches');

    assert.ok(
      objectInspector.sentObjects[objectId],
      'Object successfully retained.'
    );

    message = await captureMessage('objectInspector:droppedObject', () => {
      run(object, 'destroy');
    });

    assert.ok(didDestroy, 'Original willDestroy is preserved.');
    assert.notOk(objectInspector.sentObjects[objectId], 'Object is dropped');
    assert.deepEqual(message, { objectId });
  });

  // eslint-disable-next-line qunit/require-expect
  test('Properties ending with `Binding` are skipped', async function (assert) {
    let object = EmberObject.create({
      bar: 'test',
      fooBinding: 'bar',
    });

    let message = await inspectObject(object);

    let props = message.details[0].properties;
    if (!hasEmberVersion(3, 0)) {
      assert.strictEqual(
        props.length,
        2,
        'Props should be foo and bar without fooBinding'
      );
      assert.strictEqual(props[1].name, 'foo');
    } else {
      assert.strictEqual(
        props.length,
        1,
        'Props should be only bar without fooBinding, in Ember 3.0+'
      );
    }
    assert.strictEqual(props[0].name, 'bar');
  });

  test("Properties listed in _debugInfo but don't exist should be skipped silently", async function (assert) {
    let object = EmberObject.create({
      foo: 'test',
      _debugInfo() {
        return {
          propertyInfo: {
            groups: [
              {
                name: 'Attributes',
                properties: ['foo', 'bar'],
              },
            ],
          },
        };
      },
    });

    let message = await inspectObject(object);

    let props = message.details[0].properties;
    assert.strictEqual(props.length, 1, 'bar should be silently skipped');
    assert.strictEqual(props[0].name, 'foo');
  });

  test('Errors while computing CPs are handled', async function (assert) {
    let count = 0;
    let object = run(() =>
      EmberObject.extend({
        foo: computed(function () {
          if (count++ < 2) {
            throw new Error('CP Calculation');
          }
          return 'bar';
        }),
      }).create()
    );

    let message = await inspectObject(object);

    let { objectId } = message;
    assert.strictEqual(objectId, guidFor(object), 'objectId matches');

    let errors = message.errors;
    assert.strictEqual(errors.length, 1);
    assert.strictEqual(errors[0].property, 'foo');

    // Calculate CP a second time
    message = await captureMessage('objectInspector:updateErrors', () => {
      EmberDebug.port.trigger('objectInspector:calculate', {
        objectId,
        property: 'foo',
        mixinIndex: 1,
      });
    });

    assert.strictEqual(message.errors.length, 1);
    assert.strictEqual(message.errors[0].property, 'foo');

    // Calculate CP a third time (no error this time)
    message = await captureMessage('objectInspector:updateProperty', () => {
      EmberDebug.port.trigger('objectInspector:calculate', {
        objectId: guidFor(object),
        property: 'foo',
        mixinIndex: 1,
      });
    });

    assert.strictEqual(message.value.inspect, inspect('bar'));
  });

  test('Plain properties work', async function (assert) {
    let inspected = EmberObject.create({ hi: 123 });
    let message = await inspectObject(inspected);

    let plainProperty = message.details[0].properties[0];
    assert.strictEqual(plainProperty.name, 'hi');
    assert.ok(plainProperty.isProperty);
    assert.strictEqual(plainProperty.value.type, 'type-number');
    assert.strictEqual(plainProperty.value.inspect, '123');
  });

  test('Getters work', async function (assert) {
    class Foo {
      get hi() {
        return 123;
      }
    }

    let inspected = new Foo();

    let message = await inspectObject(inspected);
    let getter = message.details[1].properties[0];
    assert.strictEqual(getter.name, 'hi');
    assert.ok(getter.isGetter);
    assert.notOk(getter.isTracked);
    assert.strictEqual(getter.value.type, 'type-number');
    assert.strictEqual(getter.value.inspect, '123');
  });

  if (hasEmberVersion(3, 13)) {
    test('Tracked properties work', async function (assert) {
      class Foo {
        @tracked hi = 123;
      }

      let inspected = new Foo();

      assert.step('inspector: sendObject');
      let message = await inspectObject(inspected);
      let trackedProp = message.details[1].properties[0];
      assert.strictEqual(trackedProp.name, 'hi');
      assert.ok(trackedProp.isTracked);
      assert.strictEqual(trackedProp.value.type, 'type-number');
      assert.strictEqual(trackedProp.value.inspect, '123');

      assert.step('inspector: update value');
      message = await captureMessage('objectInspector:updateProperty', () => {
        run(() => inspected.hi++);
      });

      assert.step('inspector: updateProperty');
      assert.strictEqual(message.property, 'hi');
      assert.strictEqual(message.mixinIndex, 1);
      assert.strictEqual(message.value.type, 'type-number');
      assert.strictEqual(message.value.inspect, inspect(124));
      assert.ok(message.value.isCalculated);

      assert.verifySteps([
        'inspector: sendObject',
        'inspector: update value',
        'inspector: updateProperty',
      ]);
    });

    test('Tracked getters update', async function (assert) {
      class Foo {
        @tracked hi = 123;
      }

      let dataSource = new Foo();

      class Bar {
        get hello() {
          return dataSource.hi;
        }
      }

      let inspected = new Bar();

      assert.step('inspector: sendObject');
      let message = await inspectObject(inspected);
      let trackedProp = message.details[1].properties[0];
      assert.strictEqual(trackedProp.name, 'hello');
      assert.ok(trackedProp.isGetter);
      assert.strictEqual(trackedProp.value.type, 'type-number');
      assert.strictEqual(trackedProp.value.inspect, '123');

      assert.step('inspector: update value');
      message = await captureMessage('objectInspector:updateProperty', () => {
        run(() => dataSource.hi++);
      });

      assert.step('inspector: updateProperty');
      assert.strictEqual(message.property, 'hello');
      assert.strictEqual(message.mixinIndex, 1);
      assert.strictEqual(message.value.type, 'type-number');
      assert.strictEqual(message.value.inspect, inspect(124));
      assert.ok(message.value.isCalculated);

      assert.verifySteps([
        'inspector: sendObject',
        'inspector: update value',
        'inspector: updateProperty',
      ]);
    });
  }

  // @glimmer/component 1.0 doesn't seem to support 3.4, even though it has the manager API
  // Assertion Failed: Could not find custom component manager 'glimmer'
  if (hasEmberVersion(3, 8) && GlimmerComponent) {
    test('Inspecting GlimmerComponent does not cause errors', async function (assert) {
      let instance;

      class Foo extends GlimmerComponent {
        constructor(...args) {
          super(...args);
          instance = this;
        }

        get foo() {
          return 'foo';
        }

        bar = 'bar';

        baz() {
          return 'baz';
        }
      }

      this.owner.register('template:simple', hbs`<Foo />`, {
        moduleName: 'my-app/templates/simple.hbs',
      });

      this.owner.register('component:foo', Foo);
      this.owner.register(
        `template:components/foo`,
        hbs('text only', {
          moduleName: 'my-app/templates/components/foo.hbs',
        })
      );
      await visit('/simple');

      assert.ok(instance instanceof Foo, 'an instance of Foo has been created');

      let { details, errors } = await inspectObject(instance);

      assert.ok(details, 'has details');
      assert.deepEqual(errors, [], 'has no errors');

      let properties = [];

      for (let mixin of details) {
        for (let property of mixin.properties) {
          properties.push(property.name);
        }
      }

      assert.ok(properties.indexOf('args') > -1, 'contains args');
      assert.ok(properties.indexOf('foo') > -1, 'contains foo');
      assert.ok(properties.indexOf('bar') > -1, 'contains bar');
      assert.ok(properties.indexOf('baz') > -1, 'contains baz');

      assert.strictEqual(
        properties.indexOf('bounds'),
        -1,
        'does not contain bounds'
      );
      assert.strictEqual(
        properties.indexOf('element'),
        -1,
        'does not contain element'
      );
      assert.strictEqual(
        properties.indexOf('debugName'),
        -1,
        'does not contain debugName'
      );
    });
  }
});

redpajama_set_name: RedPajamaGithub


text:
Back

Side Panels

    Right Panel


text:
<volist name="record_info" id="record_content">
<{/*判断需要需要渲染的信息类型 */}>

<if condition="$record_content['record_flag'] eq 'fq'"><{/* 如果信息record_flag为fq  代表用户发起了问题*/}>
<{/*S 发起了问题循环*/}>
<volist name="record_content['question']" id="record_info_details">

发起了问题<{$record_info_details.action_time|time2Units}>

<a href="<{:U('Home/Question/qindex',array('qid'=>$record_info_details['id']))}>"><{$record_info_details.question_name}>

</volist>
<{/*E 发起了问题循环*/}>

<elseif condition="$record_content['record_flag'] eq 'za'"/><{/*如果信息record_flag为za  代表用户赞同了回答*/}>
<{/*S 赞同了回答循环*/}>
<volist name="record_content['answer']" id="record_info_details">

<{/*S 赞同了回答内容*/}>

赞同了回答<{$record_info_details.add_time|time2Units}>

<a href="<{:U('Home/Question/qindex',array('qid'=>$record_info_details['question_id']))}>"><{$record_info_details.question_name}>

<img src="<{$record_info_details.avatar_file}>" width="50px" height="50px"/> <{$record_info_details.username}>

<{$record_info_details.answer_content}>

<include file="Profile/answer_just"/>

<{/*E 赞同了回答内容  */}>
</volist>
<{/*E 赞同了回答循环  */}>
<elseif condition="$record_content['record_flag'] eq 'aq'"/><{/*如果信息record_flag为aq  代表用户回答了问题 */}>

<{/* S 回答了问题循环 */}>
<volist name="record_content['answer']" id="record_info_details">
<{/* S 回答了问题内容  */}>

回答了问题<{$record_info_details.create_time|time2Units}>

<a href="<{:U('Home/Question/qindex',array('qid'=>$record_info_details['question_id']))}>"><{$record_info_details.question_name}>

<img src="<{$record_info_details.avatar_file}>" width="50px" height="50px"/> <{$record_info_details.username}>

<{$record_info_details.answer_content}>

问题发布于 <{$record_info_details.create_time|time2Units}>

<include file="Profile/answer_just"/>

<{/*E 回答了问题内容*/}>
</volist>
<{/*E 回答了问题循环*/}>

<elseif condition="$record_content['record_flag'] eq 'gq'"/><{/*如果信息record_flag为gq  代表用户关注了问题 */}>
关注了问题
<elseif condition="$record_content['record_flag'] eq 'gt'"/><{/*如果信息record_flag为gt  代表用户关注了话题  */}>
关注了话题
<elseif condition="$record_content['record_flag'] eq 'sq'"/><{/*如果信息record_flag为sq  代表用户收藏了问题  */}>
收藏了问题
<elseif condition="$record_content['record_flag'] eq 'sa'"/><{/*如果信息record_flag为sa  代表用户收藏了回答  */}>
</if>

</volist>


text:
/* IEEE754 floating point arithmetic
 * single precision
 */
/*
 * MIPS floating point support
 * Copyright (C) 1994-2000 Algorithmics Ltd.
 * http://www.algor.co.uk
 *
 * ########################################################################
 *
 *  This program is free software; you can distribute it and/or modify it
 *  under the terms of the GNU General Public License (Version 2) as
 *  published by the Free Software Foundation.
 *
 *  This program is distributed in the hope it will be useful, but WITHOUT
 *  ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 *  FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 *  for more details.
 *
 *  You should have received a copy of the GNU General Public License along
 *  with this program; if not, write to the Free Software Foundation, Inc.,
 *  59 Temple Place - Suite 330, Boston MA 02111-1307, USA.
 *
 * ########################################################################
 */

#include "ieee754sp.h"

ieee754sp ieee754sp_fdp(ieee754dp x)
{
	COMPXDP;
	ieee754sp nan;

	EXPLODEXDP;

	CLEARCX;

	FLUSHXDP;

	switch (xc) {
	case IEEE754_CLASS_SNAN:
		SETCX(IEEE754_INVALID_OPERATION);
		return ieee754sp_nanxcpt(ieee754sp_indef(), "fdp");
	case IEEE754_CLASS_QNAN:
		nan = buildsp(xs, SP_EMAX + 1 + SP_EBIAS, (u32)
				(xm >> (DP_MBITS - SP_MBITS)));
		if (!ieee754sp_isnan(nan))
			nan = ieee754sp_indef();
		return ieee754sp_nanxcpt(nan, "fdp", x);
	case IEEE754_CLASS_INF:
		return ieee754sp_inf(xs);
	case IEEE754_CLASS_ZERO:
		return ieee754sp_zero(xs);
	case IEEE754_CLASS_DNORM:
		/* can't possibly be sp representable */
		SETCX(IEEE754_UNDERFLOW);
		SETCX(IEEE754_INEXACT);
		if ((ieee754_csr.rm == IEEE754_RU && !xs) ||
				(ieee754_csr.rm == IEEE754_RD && xs))
			return ieee754sp_xcpt(ieee754sp_mind(xs), "fdp", x);
		return ieee754sp_xcpt(ieee754sp_zero(xs), "fdp", x);
	case IEEE754_CLASS_NORM:
		break;
	}

	{
		u32 rm;

		/* convert from DP_MBITS to SP_MBITS+3 with sticky right shift
		 */
		rm = (xm >> (DP_MBITS - (SP_MBITS + 3))) |
		    ((xm << (64 - (DP_MBITS - (SP_MBITS + 3)))) != 0);

		SPNORMRET1(xs, xe, rm, "fdp", x);
	}
}


text:
package com.advancedpwr.record;

import java.util.LinkedHashMap;
import java.util.Map;

import org.junit.jupiter.api.Test;

import com.advancedpwr.samples.MapContainer;
import com.advancedpwr.samples.Person;

public class MapTest extends AbstractRecorderTest {

	@Test
	public void testMap() {
		Person person = Person.createExamplePerson();

		Person cousin = new Person();
		cousin.setName("cousin");

		Map<Object, Person> family = new LinkedHashMap<Object, Person>();
		family.put(person.getName(), person);
		family.put(person.getDad().getName(), person.getDad());
		family.put(person.getMom().getName(), person.getMom());
		family.put(person, cousin);

		MapContainer container = new MapContainer();
		container.setPerson(person);
		container.setMap(family);
		recorder.setClassName("com.example.map.MapFactory1");
		recorder.record(container);
		assertResult();
	}

	public void testMap_2() {
		Person person = Person.createExamplePerson();

		Map<String, Person> family = new LinkedHashMap<String, Person>();
		family.put(person.getName(), person);
		family.put(person.getDad().getName(), person.getDad());
		family.put("alias", person);

		// Don't want to try and write a class into the "java.util" package.
		SimpleClassDescriptor desc = new SimpleClassDescriptor();
		desc.setPackageName("com.example.map");
		desc.setClassName("LinkedHashMapFactory");
		recorder.setDescriptor(desc);
		recorder.record(family);
		assertResult();
	}
}


text:
#include <casper/lp/var.h>
#include <casper/lp/solver.h>

#include <casper/util/exception.h>

namespace Casper {
namespace LP {

Var::Var(Solver& solver) : solver(solver), id(solver,solver.newVar())
{}

const Var& Var::operator=(const Var& s)
{
	if (&s.solver != &solver)
		throw Exception::InvalidOperation("assigning to an LP::Var associated with a distinct LP::Solver object");
	id = s.id;
	return *this;
}

double Var::getCurValue() const
{	return solver.getValue(id);	}

void Var::getActivityRange(double& lb, double& ub) const
{	solver.getActivityRange(id,lb,ub);	}

} // LP
} // Casper

std::ostream& operator<<(std::ostream& os, const Casper::LP::Var& v)
{
	os << v.getCurValue();
	return os;
}


text:
package com.thinkbiganalytics.spark;

import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableMap;
import com.thinkbiganalytics.rest.JerseyClientConfig;
import com.thinkbiganalytics.rest.JerseyRestClient;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;

import java.net.InetAddress;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.UnknownHostException;

import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import javax.ws.rs.core.Response;

/**
 * Registers this Spark Shell client with a remote Kylo services server.
 */
public class RemoteClientRunner implements ApplicationRunner {

    private static final Logger log = LoggerFactory.getLogger(RemoteClientRunner.class);

    /**
     * Password for keystore
     */
    @Nullable
    private final String keystorePassword;

    /**
     * Path to keystore
     */
    @Nullable
    private final String keystorePath;

    /**
     * Spark Shell client port number
     */
    private final int localPort;

    /**
     * Registration URL
     */
    @Nullable
    private final String serverUrl;

    /**
     * Constructs a {@code RemoteClientRunner} with the specified command-line options and port number.
     *
     * @param parameters the command-line options
     * @param serverPort the Spark Shell client port number
     */
    public RemoteClientRunner(@Nonnull final SparkShellOptions parameters, final int serverPort) {
        keystorePassword = parameters.getServerKeystorePassword();
        keystorePath = parameters.getServerKeystorePath();
        serverUrl = parameters.getServerUrl();
        localPort = serverPort;
    }

    /**
     * Registers this Spark Shell client with the remote Kylo services server.
     */
    public void register() {
        Preconditions.checkState(serverUrl != null, "Registration server is not available.");

        // Parse server address
        final URL url;
        try {
            url = new URL(serverUrl);
        } catch (MalformedURLException e) {
            throw new IllegalStateException("Not a valid registration URL: " + serverUrl);
        }

        // Find client id and secret
        final String clientId = System.getenv("KYLO_CLIENT_ID");
        Preconditions.checkNotNull(clientId, "Environment variable is not defined: KYLO_CLIENT_ID");

        final String clientSecret = System.getenv("KYLO_CLIENT_SECRET");
        Preconditions.checkNotNull(clientSecret, "Environment variable is not defined: KYLO_CLIENT_SECRET");

        // Register with server
        final JerseyClientConfig config = new JerseyClientConfig(url.getHost(), clientId, clientSecret.toCharArray(), url.getProtocol().equalsIgnoreCase("https"), false, keystorePath, keystorePassword.toCharArray());
        config.setPort(url.getPort() > 0 ? url.getPort() : url.getDefaultPort());

        final JerseyRestClient client = getRestClient(config);
        final String hostName = getHostName();

        log.info("Registering client {} at {}:{} with server {}.", clientId, hostName, localPort, serverUrl);
        final Response response = client.post(url.getPath(), ImmutableMap.of("host", hostName, "port", localPort));

        if (response != null && response.getStatus() >= 200 && response.getStatus() < 300) {
            log.info("Successfully registered client.");
        } else {
            log.info("Registration failed with response: {}", response);
            throw new IllegalStateException("Failed to register with server");
        }
    }

    @Override
    public void run(@Nonnull final ApplicationArguments args) throws Exception {
        log.trace("run - entry with ({})", args);

        if (serverUrl != null) {
            try {
                register();
            } catch (final Exception e) {
                // Registration failed. No requests will be received so might as well exit.
                log.error("Failed to register Spark Shell client: {}", e.toString(), e);
                Runtime.getRuntime().exit(100);
            }
        } else {
            log.info("Remote server address not set. Skipping registration.");
        }

        log.trace("run - exit");
    }

    /**
     * Gets the hostname of this Spark Shell client.
     *
     * @return the local hostname
     */
    String getHostName() {
        try {
            return InetAddress.getLocalHost().getHostName();
        } catch (final UnknownHostException e) {
            throw new IllegalStateException("Hostname is not available");
        }
    }

    /**
     * Creates a REST client for communicating with the Kylo services server.
     *
     * @param config the REST client configuration
     * @return the REST client
     */
    JerseyRestClient getRestClient(@Nonnull final JerseyClientConfig config) {
        return new JerseyRestClient(config);
    }
}


text:
import re
import urllib.parse
import xml.etree.ElementTree as ElementTree
import asyncio
import dateutil.parser
from slot import requires
from slot.handlers import BaseHandler, MessageHandled, command
import slot.http

link_regex = re.compile("http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+")
info_format = "Видео \"{0}\" опубликовано {1} GMT пользователем {2}. Просмотров: {3:,}."
datetime_format = "%d.%m.%Y %H:%M:%S"

class YouTubeHandler(BaseHandler):
    @asyncio.coroutine
    def on_message(self, msg, mine):
        if mine:
            return
        links = link_regex.findall(msg.text)
        result = []
        for link in map(urllib.parse.urlparse, links):
            if link.scheme in {"http", "https", ""}:
                if link.hostname in {"youtube.com", "www.youtube.com"}:
                    arguments = urllib.parse.parse_qs(link.query)
                    if "v" not in arguments:
                        continue
                    video_id = arguments["v"][0]
                elif link.hostname in {"youtu.be", "www.youtu.be"} and link.path not in {"/", ""}:
                    video_id = link.path[1:]
                else:
                    continue
            else:
                continue
            xml_data = yield from slot.http.get("http://gdata.youtube.com/feeds/api/videos/{0}".format(video_id))
            xml = ElementTree.fromstring(xml_data)
            title = xml.find("{http://www.w3.org/2005/Atom}title").text
            published = dateutil.parser.parse(xml.find("{http://www.w3.org/2005/Atom}published").text)
            author = xml.find("{http://www.w3.org/2005/Atom}author").find("{http://www.w3.org/2005/Atom}name").text
            views = int(xml.find("{http://gdata.youtube.com/schemas/2007}statistics").attrib["viewCount"])
            result.append(info_format.format(msg.protocol().escape_unsafe(title),
                                             published.strftime(datetime_format),
                                             msg.protocol().escape_unsafe(author),
                                             views))
        if len(result) != 0:
            yield from msg.conversation.reply("\n".join(result))
            raise MessageHandled

@requires("API", 1)
def factory(bot, config):
    return YouTubeHandler(bot, config)


text:
package org.achtern.AchternEngine.core.rendering.texture;

/**
 * TODO: add more!
 */
public enum InternalFormat {

    DEPTH_COMPONENT,
    DEPTH_COMPONENT16,
    DEPTH_COMPONENT24,
    DEPTH_COMPONENT32,

    RGBA8
}


text:
@interface RNSharedElementNodeManager : NSObject

- (instancetype)init;
- (RNSharedElementNode*) acquire:(NSNumber*) reactTag view:(UIView*)view isParent:(BOOL)isParent;
- (long) release:(RNSharedElementNode*) node;

@end

#endif


text:
import {
  createModel,
  createSchema,
  DocumentTypeFromSchema,
  FieldsOfDocument,
  ItemTypeFromTypeSchemaFunction,
  ModelTypeFromTypeSchemaFunction,
  MongooseModule,
  ReplaceModelReturnType,
} from "../helpers";
import EsriAuthModule from "./schema/esri-auth";
import EsriErrorModule from "./schema/esri-error";
import EsriMapModule from "./schema/esri-map";
import EsriTokenModule from "./schema/esri-token";
import FireMapperAuthModule from "./schema/firemapper-auth";

export function EsriSchema(mongoose: MongooseModule) {
  const { Schema, Types } = mongoose;
  const EsriAuth = EsriAuthModule(mongoose);
  const EsriError = EsriErrorModule(mongoose);
  const EsriMap = EsriMapModule(mongoose);
  const EsriToken = EsriTokenModule(mongoose);
  const FireMapperAuth = FireMapperAuthModule(mongoose);

  const MapProperties = createSchema(Schema, {
    // ArcGIS Item id
    itemId: {
      type: String,
      default: "",
    },
    download: {
      type: Boolean,
      default: false,
    },
  }, {
    _id: false,
    id: false,
  });

  const modelSchema = createSchema(Schema, {
    _id: {
      type: Types.ObjectId,
      auto: true,
    },

    // last time when cron updated maps
    runAt: {
      type: Date,
      default: "",
    },
    departmentId: {
      type: Types.ObjectId,
      ref: "Department",
      required: true
    },

    tokenDateExpiry: {
      type: Number,
      default: 0,
    },
    tokenExpiry: {
      type: Date,
      default: "",
    },
    token: {
      type: EsriToken,
      default: null,
    },
    tokenError: {
      type: EsriError,
      default: null,
    },

    auth: {
      type: EsriAuth,
      default: null,
    },
    authError: {
      type: EsriError,
      default: null,
    },
    fireMapperAuth: {
      type: FireMapperAuth,
      default: null,
    },

    // Link to ArcGISGroup
    arcGISGroupId: {
      type: String,
      default: null,
    },
    // ArcGIS user used to configure the ArcGIS group and all the users from that group
    arcGISRoot: {
      type: EsriAuth,
      default: null,
    },

    // maps
    maps: {
      type: [EsriMap],
      default: []
    },
    // Properties set by user.
    // These are applied by the sync on top of the EsriMap properties
    // saved as { itemId, download, ... }
    mapsProperties: {
      type: [MapProperties],
      default: [],
    },
    // newest modified for EsriMap
    mapLastUpdated: {
      type: Date,
      default: "",
    },
  }, {
    collection: "massive_esri",
  });
  modelSchema.set("autoIndex", false);

  modelSchema.set("toJSON", {
    virtuals: true,
    versionKey: false,
    // Deprecated. Check which apps rely on .id instead of using ._id.
    transform(doc: DocumentTypeFromSchema<typeof modelSchema>, ret: FieldsOfDocument<DocumentTypeFromSchema<typeof modelSchema>>) {
      ret.id = ret._id;
    },
  });

  // Deprecated. Check which apps rely on .id instead of using ._id.
  modelSchema.virtual("id").get(function(this: DocumentTypeFromSchema<typeof modelSchema>) {
    return this._id.toHexString();
  });
  return modelSchema;
}

export async function EsriModule(mongoose: MongooseModule) {
  const modelSchema = EsriSchema(mongoose);
  return createModel(mongoose, "Esri", modelSchema);
}

export interface Esri extends ItemTypeFromTypeSchemaFunction<typeof EsriModule> { }
export interface EsriModel extends ModelTypeFromTypeSchemaFunction<Esri> { }
export default EsriModule as ReplaceModelReturnType<typeof EsriModule, EsriModel>;


text:
using namespace oclgrind;
using namespace std;

MemCheck::MemCheck(const Context *context)
 : Plugin(context)
{
}

void MemCheck::instructionExecuted(const WorkItem *workItem,
                                   const llvm::Instruction *instruction,
                                   const TypedValue& result)
{
  // Check static array bounds if load or store is executed
  const llvm::Value *PtrOp = nullptr;

  if (auto LI = llvm::dyn_cast<llvm::LoadInst>(instruction))
  {
    PtrOp = LI->getPointerOperand();
  }
  else if (auto SI = llvm::dyn_cast<llvm::StoreInst>(instruction))
  {
    PtrOp = SI->getPointerOperand();
  }
  else
  {
    return;
  }

  if (auto GEPI = llvm::dyn_cast<llvm::GetElementPtrInst>(PtrOp))
  {
    checkArrayAccess(workItem, GEPI);
  }
}

void MemCheck::memoryAtomicLoad(const Memory *memory,
                                const WorkItem *workItem,
                                AtomicOp op, size_t address, size_t size)
{
  checkLoad(memory, address, size);
}

void MemCheck::memoryAtomicStore(const Memory *memory,
                                 const WorkItem *workItem,
                                 AtomicOp op, size_t address, size_t size)
{
  checkStore(memory, address, size);
}

void MemCheck::memoryLoad(const Memory *memory, const WorkItem *workItem,
                          size_t address, size_t size)
{
  checkLoad(memory, address, size);
}

void MemCheck::memoryLoad(const Memory *memory, const WorkGroup *workGroup,
                          size_t address, size_t size)
{
  checkLoad(memory, address, size);
}

void MemCheck::memoryMap(const Memory *memory, size_t address,
                         size_t offset, size_t size, cl_map_flags flags)
{
  MapRegion map =
  {
    address, offset, size, memory->getPointer(address + offset),
    (flags == CL_MAP_READ ? MapRegion::READ : MapRegion::WRITE)
  };
  m_mapRegions.push_back(map);
}

void MemCheck::memoryStore(const Memory *memory, const WorkItem *workItem,
                           size_t address, size_t size,
                           const uint8_t *storeData)
{
  checkStore(memory, address, size);
}

void MemCheck::memoryStore(const Memory *memory, const WorkGroup *workGroup,
                           size_t address, size_t size,
                           const uint8_t *storeData)
{
  checkStore(memory, address, size);
}

void MemCheck::memoryUnmap(const Memory *memory, size_t address,
                           const void *ptr)
{
  for (auto region = m_mapRegions.begin();
            region != m_mapRegions.end();
            region++)
  {
    if (region->ptr == ptr)
    {
      m_mapRegions.erase(region);
      return;
    }
  }
}

void MemCheck::checkArrayAccess(const WorkItem *workItem,
                                const llvm::GetElementPtrInst *GEPI) const
{
  // Iterate through GEPI indices
  const llvm::Type *ptrType = GEPI->getPointerOperandType();

  for (auto opIndex = GEPI->idx_begin(); opIndex != GEPI->idx_end(); opIndex++)
  {
    int64_t index = workItem->getOperand(opIndex->get()).getSInt();

    if (ptrType->isArrayTy())
    {
      // Check index doesn't exceed size of array
      uint64_t size = ptrType->getArrayNumElements();

      if ((uint64_t)index >= size)
      {
        ostringstream info;
        info << "Index ("
             << index << ") exceeds static array size ("
             << size << ")";
        m_context->logError(info.str().c_str());
      }

      ptrType = ptrType->getArrayElementType();
    }
    else if (ptrType->isPointerTy())
    {
      ptrType = ptrType->getPointerElementType();
    }
    else if (ptrType->isVectorTy())
    {
      ptrType = ptrType->getVectorElementType();
    }
    else if (ptrType->isStructTy())
    {
      ptrType = ptrType->getStructElementType(index);
    }
  }
}

void MemCheck::checkLoad(const Memory *memory,
                         size_t address, size_t size) const
{
  if (!memory->isAddressValid(address, size))
  {
    logInvalidAccess(true, memory->getAddressSpace(), address, size);
    return;
  }

  if (memory->getBuffer(address)->flags & CL_MEM_WRITE_ONLY)
  {
    m_context->logError("Invalid read from write-only buffer");
  }

  // Check if memory location is currently mapped for writing
  for (auto region = m_mapRegions.begin();
            region != m_mapRegions.end();
            region++)
  {
    if (region->type == MapRegion::WRITE &&
        address < region->address + region->size &&
        address + size >= region->address)
    {
      m_context->logError("Invalid read from buffer mapped for writing");
    }
  }
}

void MemCheck::checkStore(const Memory *memory,
                          size_t address, size_t size) const
{
  if (!memory->isAddressValid(address, size))
  {
    logInvalidAccess(false, memory->getAddressSpace(), address, size);
    return;
  }

  if (memory->getBuffer(address)->flags & CL_MEM_READ_ONLY)
  {
    m_context->logError("Invalid write to read-only buffer");
  }

  // Check if memory location is currently mapped
  for (auto region = m_mapRegions.begin();
            region != m_mapRegions.end();
            region++)
  {
    if (address < region->address + region->size &&
        address + size >= region->address)
    {
      m_context->logError("Invalid write to mapped buffer");
    }
  }
}

void MemCheck::logInvalidAccess(bool read, unsigned addrSpace,
                                size_t address, size_t size) const
{
  Context::Message msg(ERROR, m_context);
  msg << "Invalid " << (read ? "read" : "write")
      << " of size " << size
      << " at " << getAddressSpaceName(addrSpace)
      << " memory address 0x" << hex << address << endl
      << msg.INDENT
      << "Kernel: " << msg.CURRENT_KERNEL << endl
      << "Entity: " << msg.CURRENT_ENTITY << endl
      << msg.CURRENT_LOCATION << endl;
  msg.send();
}


text:
package org.broadleafcommerce.common.jmx;

import org.springframework.beans.factory.FactoryBean;

/**
 *
 * @author jfischer
 *
 */
public class ExplicitNameFactoryBean implements FactoryBean {

    private final String name;
    private final String suffix;

    public ExplicitNameFactoryBean(String name, String suffix) {
        this.name = name;
        this.suffix = suffix;
    }

    public Object getObject() throws Exception {
        return name + "-" + suffix;
    }

    @SuppressWarnings("unchecked")
    public Class getObjectType() {
        return String.class;
    }

    public boolean isSingleton() {
        return false;
    }

}


text:
/**
 * @fileoverview Vizi scene utilities
 * @author Tony Parisi
 */
goog.provide('Vizi.SceneUtils');

// Compute the bounding box of an object or hierarchy of objects
Vizi.SceneUtils.computeBoundingBox = function(obj) {

	var computeBoundingBox = function(obj) {
		if (obj instanceof THREE.Mesh && !obj.ignoreBounds) {
			var geometry = obj.geometry;
			if (geometry) {
				if (!geometry.boundingBox) {
					geometry.computeBoundingBox();
				}

				var geometryBBox = geometry.boundingBox.clone();
				obj.updateMatrix();
				geometryBBox.applyMatrix4(obj.matrix);
				return geometryBBox;
			}
			else {
				return new THREE.Box3(new THREE.Vector3, new THREE.Vector3);
			}
		}
		else {
			var i, len = obj.children.length;

			var boundingBox = new THREE.Box3; // (new THREE.Vector3, new THREE.Vector3);

			for (i = 0; i < len; i++) {
				var bbox = computeBoundingBox(obj.children[i]);
				if ( bbox.min.x < boundingBox.min.x ) {

					boundingBox.min.x = bbox.min.x;

				}

				if ( bbox.max.x > boundingBox.max.x ) {

					boundingBox.max.x = bbox.max.x;

				}

				if ( bbox.min.y < boundingBox.min.y ) {

					boundingBox.min.y = bbox.min.y;

				}

				if ( bbox.max.y > boundingBox.max.y ) {

					boundingBox.max.y = bbox.max.y;

				}

				if ( bbox.min.z < boundingBox.min.z ) {

					boundingBox.min.z = bbox.min.z;

				}

				if ( bbox.max.z > boundingBox.max.z ) {

					boundingBox.max.z = bbox.max.z;

				}
			}

			if (isFinite(boundingBox.min.x)) {
				obj.updateMatrix();
				boundingBox.applyMatrix4(obj.matrix);
			}
			return boundingBox;
		}
	}

	if (obj instanceof Vizi.Object) {
		return computeBoundingBox(obj.transform.object);
	}
	else if (obj instanceof Vizi.Visual) {
		return computeBoundingBox(obj.object);
	}
	else {
		return new THREE.Box3(new THREE.Vector3, new THREE.Vector3);
	}
}


text:
namespace galaxy
{
	void CollisionContact::BeginContact(b2Contact* contact)
	{
		// Get colliding fixtures from contact.
		b2Fixture* fixtureA = contact->GetFixtureA();
		b2Fixture* fixtureB = contact->GetFixtureB();

		if ((fixtureA) && (fixtureB))
		{
			// Retrieve the entity the fixtures belong to.
			entt::DefaultRegistry::entity_type a = *static_cast<entt::DefaultRegistry::entity_type*>(fixtureA->GetUserData());
			entt::DefaultRegistry::entity_type b = *static_cast<entt::DefaultRegistry::entity_type*>(fixtureB->GetUserData());

			// Emit the collision event based off of the info provided.
			Locator::dispatcher->trigger<CollisionEvent>(a, b, fixtureA->GetFilterData().categoryBits, fixtureB->GetFilterData().categoryBits);
		}
		else
		{
			LOG_S(WARNING) << "NULL fixture(s)!";
		}
	}

	void CollisionContact::EndContact(b2Contact* contact)
	{
		// At the moment we don't care what happens when a collision ends.
		// This would be implemented later tho.
	}
}


text:
from __future__ import (absolute_import, division, print_function,
                        unicode_literals)
import six
from collections import defaultdict
from .util import mapping_mixin
from .. import QtCore, QtGui

import logging
logger = logging.getLogger(__name__)

_defaults = {
    "check_box_hover_text": "Enable this widget",
    "check_box_state": True,
}

class UtilsWidget(QtGui.QWidget):
    """
    `UtilsWidget` has a `QHBoxLayout`, an en/disable checkbox and a label
    with hover text.  Daughter classes of `UtilsWidget` just need to
    add their respective input box to self._layout and set the layout with
    :code:`to self.setLayout(self._layout)`

    """
    def __init__(self, label_text, hover_text=None, has_check_box=False):
        super(UtilsWidget, self).__init__()
        # set the defaults
        if hover_text is None:
            hover_text = label_text
        # make the label
        self._lab = QtGui.QLabel(label_text)
        # set the text to display on mouse cursor hover
        self._lab.setToolTip(hover_text)

        # make layout
        self._layout = QtGui.QHBoxLayout()

        # make the check box if it is needed
        self._has_check_box = has_check_box
        if self._has_check_box:
            self._check_box = QtGui.QCheckBox()
            self._check_box.setToolTip(_defaults["check_box_hover_text"])
            self._check_box.setChecked(_defaults["check_box_state"])
            # todo disable input when the check_box is not checked
            self._layout.addWidget(self._check_box)

        self._layout.addWidget(self._lab)

class Slider(UtilsWidget):
    """
    Fancier version of a slider which includes a label and
    a spinbox
    """
    # export sub-set of slider signals
    # this should be exhaustive eventually
    valueChanged = QtCore.Signal(int)
    rangeChanged = QtCore.Signal(int, int)

    # todo make more things configurable
    def __init__(self, label_text, min_v, max_v, tracking=True,
                 hover_text=None, has_check_box=False):
        super(Slider, self).__init__(label_text=label_text,
                                     hover_text=hover_text,
                                     has_check_box=has_check_box)

        # set up slider
        self._slider = QtGui.QSlider(parent=self)
        self._slider.setRange(min_v, max_v)
        self._slider.setTracking(tracking)
        self._slider.setSingleStep(1)
        self._slider.setOrientation(QtCore.Qt.Horizontal)
        # internal connections
        self._slider.valueChanged.connect(self.valueChanged)
        self._slider.rangeChanged.connect(self.rangeChanged)
        # make buddy with label
        self._label.setBuddy(self._slider)

        # and its spin box
        self._spinbox = QtGui.QSpinBox(parent=self)
        self._spinbox.setRange(self._slider.minimum(), self._slider.maximum())
        self._spinbox.valueChanged.connect(self._slider.setValue)
        self._slider.valueChanged.connect(self._spinbox.setValue)
        self._slider.rangeChanged.connect(self._spinbox.setRange)

        # add widegts
        self._layout.addWidget(self._slider)
        self._layout.addWidget(self._spinbox)

        self.setLayout(self._layout)

    # TODO make sure all the slots are included
    @QtCore.Slot(int)
    def setValue(self, val):
        # internal call backs will take care of the spinbox
        self._slider.setValue(val)

class DateTimeBox(UtilsWidget):
    dateChanged = QtCore.Signal(QtCore.QDate)
    dateTimeChanged = QtCore.Signal(QtCore.QDateTime)
    timeChanged = QtCore.Signal(QtCore.QTime)

    # todo make more things configurable
    def __init__(self, label_text, hover_text=None, has_check_box=False):
        # pass up the stack
        super(DateTimeBox, self).__init__(label_text=label_text,
                                          hover_text=hover_text,
                                          has_check_box=has_check_box)
        # make the date time box
        self._datetime = QtGui.QDateTimeEdit(QtCore.QDate.currentDate())
        self._datetime.setCalendarPopup(True)
        self._datetime.setDisplayFormat("yyyy-MM-dd hh:mm:ss")
        # buddy them up
        self._lab.setBuddy(self._datetime)
        # add the datetime widget to the layout
        self._layout.addWidget(self._datetime)

        # set the widget's layout
        self.setLayout(self._layout)

        # connect the signals
        self._datetime.dateChanged.connect(self.dateChanged)
        self._datetime.dateTimeChanged.connect(self.dateTimeChanged)
        self._datetime.timeChanged.connect(self.timeChanged)

    # forward the slots
    @QtCore.Slot(QtCore.QDate)
    def setDate(self, date):
        self._datetime.setDate(date)

    @QtCore.Slot(QtCore.QDateTime)
    def setDateTime(self, dateTime):
        self._datetime.setDateTime(dateTime)

    @QtCore.Slot(QtCore.QTime)
    def setTime(self, time):
        self._datetime.setTime(time)

    def getValue(self):
        if self._has_check_box and self._check_box.isChecked():
            try:
                return self._datetime.dateTime().toPython()
            except AttributeError :
                return self._datetime.dateTime().toPyDateTime()

        return None

class ComboBox(UtilsWidget):
    activated = QtCore.Signal(str)
    currentIndexChanged = QtCore.Signal(str)
    editTextChanged = QtCore.Signal(str)
    highlighted = QtCore.Signal(str)

    # todo make more things configurable
    def __init__(self, label_text, list_of_strings, hover_text=None,
                 default_entry=0, editable=True, has_check_box=False):
        # pass up the stack
        super(ComboBox, self).__init__(label_text=label_text,
                                       hover_text=hover_text,
                                       has_check_box=has_check_box)
        # make the cb
        self._cb = QtGui.QComboBox()
        self._cb.setEditable(editable)
        # stash the text
        self._list_of_strings = list_of_strings
        # shove in the text
        self._cb.addItems(list_of_strings)
        # buddy them up
        self._lab.setBuddy(self._cb)
        # make and set the layout
        # add the combo box to the layout defined in UtilsWidget
        self._layout.addWidget(self._cb)
        self.setLayout(self._layout)

        # connect on the signals
        self._cb.activated[str].connect(self.activated)
        self._cb.currentIndexChanged[str].connect(self.currentIndexChanged)
        self._cb.editTextChanged[str].connect(self.editTextChanged)
        self._cb.highlighted[str].connect(self.highlighted)

    # forward the slots
    @QtCore.Slot()
    def clear(self):
        self._cb.clear()

    @QtCore.Slot(int)
    def setCurrentIndex(self, in_val):
        self._cb.setCurrentIndex(in_val)

    @QtCore.Slot(str)
    def setEditText(self, in_str):
        self._cb.setEditText(in_str)

    def getValue(self):
        if self._has_check_box and self._check_box.isChecked():
            return self._list_of_strings[self._cb.currentIndex()]

        return None

class LineEdit(UtilsWidget):
    cursorPositionChanged = QtCore.Signal(int, int)
    editingFinished = QtCore.Signal()
    returnPressed = QtCore.Signal()
    selectionChanged = QtCore.Signal()
    textChanged = QtCore.Signal(str)
    textEdited = QtCore.Signal(str)

    def __init__(self, label_text, hover_text=None, editable=True,
                 has_check_box=False):
        # pass up the stack
        super(LineEdit, self).__init__(label_text=label_text,
                                       hover_text=hover_text,
                                       has_check_box=has_check_box)
        # make the line edit box
        self._line_editor = QtGui.QLineEdit()
        # buddy them up
        self._lab.setBuddy(self._line_editor)
        # add the line edit widget to the layout
        self._layout.addWidget(self._line_editor)
        self.setLayout(self._layout)

        # connect the signals
        self._line_editor.cursorPositionChanged.connect(self.cursorPositionChanged)
        self._line_editor.editingFinished.connect(self.editingFinished)
        self._line_editor.returnPressed.connect(self.returnPressed)
        self._line_editor.selectionChanged.connect(self.selectionChanged)
        self._line_editor.textChanged.connect(self.textChanged)
        self._line_editor.textEdited.connect(self.textEdited)

    # forward the slots
    @QtCore.Slot()
    def clear(self):
        self._line_editor.clear()

    @QtCore.Slot()
    def copy(self):
        self._line_editor.copy()

    @QtCore.Slot()
    def cut(self):
        self._line_editor.cut()

    @QtCore.Slot()
    def paste(self):
        self._line_editor.paste()

    @QtCore.Slot()
    def redo(self):
        self._line_editor.redo()

    @QtCore.Slot()
    def selectAll(self):
        self._line_editor.selectAll()

    @QtCore.Slot()
    def setText(self, str):
        self._line_editor.setText(str)

    @QtCore.Slot()
    def undo(self):
        self._line_editor.undo()

    def getValue(self):
        if self._has_check_box and self._check_box.isChecked():
            # returned as a QString
            text = str(self._line_editor.text())
            # check to see if it empty
            if text == '':
                return None
            return text
        return None

class CheckBox(UtilsWidget):
    stateChanged = QtCore.Signal()

    # todo make more things configurable
    def __init__(self, label_text, hover_text=None, editable=True,
                 has_check_box=False):
        # pass up the stack
        super(CheckBox, self).__init__(label_text=label_text,
                                       hover_text=hover_text,
                                       has_check_box=has_check_box)
        # make the check box
        self._check = QtGui.QCheckBox()
        # buddy them up
        self._lab.setBuddy(self._check)

        self._layout.addWidget(self._check)
        self.setLayout(self._layout)

        # connect the signal
        self._check.stateChanged.connect(self.stateChanged)

    # forward the slots
    # no slots to forward

    def getValue(self):
        if self._has_check_box and self._check_box.isChecked():
            return self._check.isChecked()
        return None

class TripleSpinner(QtGui.QGroupBox):
    """
    A class to wrap up the logic for dealing with a min/max/step
    triple spin box.
    """
    # signal to be emitted when the spin boxes are changed
    # and settled
    valueChanged = QtCore.Signal(float, float)

    def __init__(self, title='', parent=None):
        QtGui.QGroupBox.__init__(self, title, parent=parent)

        self._spinbox_min_intensity = QtGui.QDoubleSpinBox(parent=self)
        self._spinbox_max_intensity = QtGui.QDoubleSpinBox(parent=self)
        self._spinbox_intensity_step = QtGui.QDoubleSpinBox(parent=self)

        ispiner_form = QtGui.QFormLayout()
        ispiner_form.addRow("min", self._spinbox_min_intensity)
        ispiner_form.addRow("max", self._spinbox_max_intensity)
        ispiner_form.addRow("step", self._spinbox_intensity_step)
        self.setLayout(ispiner_form)

    # TODO

    @QtCore.Slot(float, float)
    def setValues(self, bottom, top):
        """
        """
        pass

    @QtCore.Slot(float, float)
    def setLimits(self, bottom, top):
        """
        """
        pass

    @QtCore.Slot(float)
    def setStep(self, step):
        """
        """
        pass

    @property
    def values(self):
        return (self._spinbox_min_intensity.value,
                self._spinbox_max_intensity.value)

class PairSpinner(QtGui.QGroupBox):
    valueChanged = QtCore.Signal(float)
    rangeChanged = QtCore.Signal(float, float)

    def __init__(self, init_min, init_max,
                 init_step, parent=None, title='',
                 value_str=None, step_str=None):
        QtGui.QGroupBox.__init__(self, title, parent=parent)

        if value_str is None:
            value_str = 'value'
        if step_str is None:
            step_str = 'step'

        self._spinbox_value = QtGui.QDoubleSpinBox(parent=self)
        self._spinbox_step = QtGui.QDoubleSpinBox(parent=self)
        self._spinbox_step.valueChanged.connect(
            self._spinbox_value.setSingleStep)

        self._spinbox_value.valueChanged.connect(
            self.valueChanged)

        ispiner_form = QtGui.QFormLayout()
        ispiner_form.addRow(value_str, self._spinbox_value)
        ispiner_form.addRow(step_str, self._spinbox_step)
        self.setLayout(ispiner_form)
        self.setStep(init_step)
        self.setRange(init_min, init_max)

    @QtCore.Slot(float)
    def setStep(self, new_step):
        self._spinbox_step.setValue(new_step)

    @QtCore.Slot(float, float)
    def setRange(self, new_min, new_max):
        self._spinbox_value.setMinimum(new_min)
        self._spinbox_value.setMaximum(new_max)
        self.rangeChanged.emit(new_min, new_max)

class ControlContainer(QtGui.QGroupBox, mapping_mixin):
    _delim = '.'
    _dispatch_map = {'slider': 'create_slider'}

    def create_widget(self, key, type_str, param_dict):
        create_fun_name = self._dispatch_map[type_str]
        create_fun = getattr(self, create_fun_name)
        return create_fun(key, **param_dict)

    def __len__(self):
        print('len')
        return len(list(iter(self)))

    def __contains__(self, key):
        print('contains')
        return key in iter(self)

    def __init__(self, title, parent=None):
        # call parent constructor
        QtGui.QGroupBox.__init__(self, title, parent=parent)

        # nested containers
        self._containers = dict()
        # all non-container contents of this container
        self._contents = dict()

        # specialized listings
        # this is a dict keyed on type of dicts
        # The inner dicts are keyed on name
        self._by_type = defaultdict(dict)

        # make the layout
        self._layout = QtGui.QVBoxLayout()
        # add it to self
        self.setLayout(self._layout)

    def __getitem__(self, key):
        print(key)
        # TODO make this sensible un-wrap KeyException errors
        try:
            # split the key
            split_key = key.strip(self._delim).split(self._delim, 1)
        except TypeError:
            raise KeyError("key is not a string")
        # if one element back -> no splitting needed
        if len(split_key) == 1:
            return self._contents[split_key[0]]
        # else, at least one layer of testing
        else:
            # unpack the key parts
            outer, inner = split_key
            # get the container and pass through the remaining key
            return self._containers[outer][inner]

    def create_container(self, key, container_title=None):
        """
        Create a nested container with in this container

        TODO : add rest of GroupBox parameters

        Parameters
        ----------
        key : str
            The key used to identify this container

        container_title : str or None
            The title of the container.
            If None, defaults to the key.
            If you want to title, use ''

        Returns
        -------
        control_container : ControlContainer
           The container created.
        """
        if container_title is None:
            container_title = key
        control_container = ControlContainer(container_title, parent=self)
        self._layout.addWidget(control_container)
        self._containers[key] = control_container
        return control_container

    def create_button(self, key):
        pass

    def create_checkbox(self, key):
        pass

    def create_combobox(self, key, key_list, editable=True, title=None):
        if title is None:
            title = key
        cb = ComboBox(title, key_list, editable=editable)
        self._add_widget(key, cb)
        return cb

    def create_dict_display(self, key, input_dict):
        pass

    def create_pairspinner(self, key, *args, **kwargs):
        ds = PairSpinner(*args, **kwargs)
        self._add_widget(key, ds)
        return ds

    def create_text(self, key, text):
        """
        Create and add a text label to the control panel
        """
        # create text
        tmp_label = QtGui.QLabel(text)
        self._add_widget(key, tmp_label)

    def create_radiobuttons(self, key):
        pass

    def create_slider(self, key, min_val, max_val, label=None):
        """

        Parameters
        ----------
        """
        if label is None:
            label = key
        # set up slider
        slider = Slider(label, min_val, max_val)
        self._add_widget(key, slider)
        return slider

    def create_triplespinbox(self, key):
        pass

    def _add_widget(self, key, in_widget):
        split_key = key.strip(self._delim).rsplit(self._delim, 1)
        # key is not nested, add to this object
        if len(split_key) == 1:
            key = split_key[0]
            # add to the type dict
            self._by_type[type(in_widget)][key] = in_widget
            # add to the contents list
            self._contents[key] = in_widget
            # add to layout
            self._layout.addWidget(in_widget)
        # else, grab the nested container and add it to that
        else:
            container, key = split_key
            self[container]._add_widget(key, in_widget)

    def iter_containers(self):
        return self._iter_helper_container([])

    def get_container(self, key):
        """
        Get a (possibly nested) container (the normal
        iterator skips these).  We may end up with two
        parallel sets of mapping functions.
        """
        split_key = key.strip(self._delim).rsplit(self._delim, 1)
        if len(split_key) == 1:
            return self._containers[split_key[0]]
        return self._containers[split_key[0]].get_containers(split_key[1])

    def _iter_helper(self, cur_path_list):
        """
        Recursively (depth-first) walk the tree and return the names
        of the leaves

        Parameters
        ----------
        cur_path_list : list of str
            A list of the current path
        """
        for k, v in six.iteritems(self._containers):
            for inner_v in v._iter_helper(cur_path_list + [k]):
                yield inner_v
        for k in six.iterkeys(self._contents):
            yield self._delim.join(cur_path_list + [k])

    def _iter_helper_container(self, cur_path_list):
        """
        Recursively (depth-first) walk the tree and return the names
        of the containers

        Parameters
        ----------
        cur_path_list : list of str
            A list of the current path
        """
        for k, v in six.iteritems(self._containers):
            for inner_v in v._iter_helper_container(cur_path_list + [k]):
                yield inner_v
        if len(cur_path_list):
            yield self._delim.join(cur_path_list)

    def __iter__(self):
        return self._iter_helper([])

    def addStretch(self):
        self._layout.addStretch()

class DictDisplay(QtGui.QGroupBox):
    """
    A generic widget for displaying dictionaries

    Parameters
    ----------
    title : string
       Widget title

    ignore_list : iterable or None
        keys to ignore

    parent : QWidget or None
        Parent widget, passed up stack
    """
    def __init__(self, title, ignore_list=None, parent=None):
        # pass up the stack, GroupBox takes care of the title
        QtGui.QGroupBox.__init__(self, title, parent=parent)

        if ignore_list is None:
            ignore_list = ()
        # make layout
        self.full_layout = QtGui.QVBoxLayout()
        # set layout
        self.setLayout(self.full_layout)
        # make a set of the ignore list
        self._ignore = set(ignore_list)
        self._disp_table = []

    @QtCore.Slot(dict)
    def update(self, in_dict):
        """
        updates the table

        Parameters
        ----------
        in_dict : dict
            The dictionary to display
        """
        # remove everything that is there
        for c in self._disp_table:
            c.deleteLater()

        # make a new list
        self._disp_table = []

        # add the keys alphabetically
        for k, v in sorted(list(in_dict.iteritems())):
            # if key in the ignore list, continue
            if k in self._ignore:
                continue
            self._add_row(k, v)

    def _add_row(self, k, v):
        """
        Private function

        Adds a row to the table

        Parameters
        ----------
        k : object
           The key

        v : object
           The value
        """
        # make a widget for our row
        tmp_widget = QtGui.QWidget(self)
        tmp_layout = QtGui.QHBoxLayout()
        tmp_widget.setLayout(tmp_layout)

        # add the key and value to the row widget
        tmp_layout.addWidget(QtGui.QLabel(str(k) + ':'))
        tmp_layout.addStretch()
        tmp_layout.addWidget(QtGui.QLabel(str(v)))

        # add the row widget to the full layout
        self.full_layout.addWidget(tmp_widget)
        # add the row widget to
        self._disp_table.append(tmp_widget)


text:
<?php
/* @var $this SowGiltsController */
/* @var $model SowGilts */
/* @var $form CActiveForm */
?>

<?php $form=$this->beginWidget('CActiveForm', array(
	'action'=>Yii::app()->createUrl($this->route),
	'method'=>'get',
)); ?>

		<?php echo $form->label($model,'sow_gilts_id'); ?>
		<?php echo $form->textField($model,'sow_gilts_id'); ?>

		<?php echo $form->label($model,'date_bred'); ?>
		<?php echo $form->textField($model,'date_bred',array('size'=>10,'maxlength'=>10)); ?>

		<?php echo $form->label($model,'sire_ear_notch'); ?>
		<?php echo $form->textField($model,'sire_ear_notch',array('size'=>20,'maxlength'=>20)); ?>

		<?php echo $form->label($model,'service_type'); ?>
		<?php echo $form->textField($model,'service_type',array('size'=>5,'maxlength'=>5)); ?>

		<?php echo $form->label($model,'comments'); ?>
		<?php echo $form->textArea($model,'comments',array('rows'=>6, 'cols'=>50)); ?>

		<?php echo $form->label($model,'passover_date'); ?>
		<?php echo $form->textField($model,'passover_date',array('size'=>10,'maxlength'=>10)); ?>

		<?php echo $form->label($model,'due_date'); ?>
		<?php echo $form->textField($model,'due_date',array('size'=>10,'maxlength'=>10)); ?>

		<?php echo $form->label($model,'days_between'); ?>
		<?php echo $form->textField($model,'days_between',array('size'=>10,'maxlength'=>10)); ?>

		<?php echo $form->label($model,'settled'); ?>
		<?php echo $form->textField($model,'settled',array('size'=>1,'maxlength'=>1)); ?>

		<?php echo $form->label($model,'farrowed'); ?>
		<?php echo $form->textField($model,'farrowed',array('size'=>1,'maxlength'=>1)); ?>

		<?php echo $form->label($model,'date_modified'); ?>
		<?php echo $form->textField($model,'date_modified'); ?>

		<?php echo CHtml::submitButton('Search'); ?>

<?php $this->endWidget(); ?>


text:
using Lucene.Net.QueryParsers.Flexible.Core.Config;
using Lucene.Net.QueryParsers.Flexible.Core.Nodes;
using Lucene.Net.QueryParsers.Flexible.Core.Processors;
using Lucene.Net.QueryParsers.Flexible.Standard.Config;
using Lucene.Net.QueryParsers.Flexible.Standard.Nodes;
using System;
using System.Collections.Generic;
using Operator = Lucene.Net.QueryParsers.Flexible.Standard.Config.StandardQueryConfigHandler.Operator;

namespace Lucene.Net.QueryParsers.Flexible.Standard.Processors
{

    ///
    /// This processor is used to apply the correct <see cref="ModifierQueryNode"/> to
    /// <see cref="BooleanQueryNode"/>s children. This is a variant of
    /// <see cref="Precedence.Processors.BooleanModifiersQueryNodeProcessor"/> which ignores precedence.
    /// <para/>
    /// The <see cref="Parser.StandardSyntaxParser"/> knows the rules of precedence, but lucene
    /// does not. e.g. (A AND B OR C AND D) ist treated like
    /// (+A +B +C +D).
    /// <para/>
    /// This processor walks through the query node tree looking for
    /// <see cref="BooleanQueryNode"/>s. If an <see cref="AndQueryNode"/> is found, every child,
    /// which is not a <see cref="ModifierQueryNode"/> or the <see cref="ModifierQueryNode"/> is
    /// <see cref="Modifier.MOD_NONE"/>, becomes a <see cref="Modifier.MOD_REQ"/>. For default
    /// <see cref="BooleanQueryNode"/>, it checks the default operator is
    /// <see cref="Operator.AND"/>, if it is, the same operation when an
    /// <see cref="AndQueryNode"/> is found is applied to it. Each <see cref="BooleanQueryNode"/>
    /// which direct parent is also a <see cref="BooleanQueryNode"/> is removed (to ignore
    /// the rules of precedence).
    ///
    /// <seealso cref="ConfigurationKeys.DEFAULT_OPERATOR"/>
    /// <seealso cref="Precedence.Processors.BooleanModifiersQueryNodeProcessor"/>
    public class BooleanQuery2ModifierNodeProcessor : IQueryNodeProcessor
    {
        internal readonly static string TAG_REMOVE = "remove";
        internal readonly static string TAG_MODIFIER = "wrapWithModifier";
        internal readonly static string TAG_BOOLEAN_ROOT = "booleanRoot";

        QueryConfigHandler queryConfigHandler;

        private readonly List<IQueryNode> childrenBuffer = new List<IQueryNode>();

        private bool usingAnd = false;

        public BooleanQuery2ModifierNodeProcessor()
        {
            // empty constructor
        }

        public virtual IQueryNode Process(IQueryNode queryTree)
        {
            Operator? op = GetQueryConfigHandler().Get(
                ConfigurationKeys.DEFAULT_OPERATOR);

            if (op == null)
            {
                throw new ArgumentException(
                    "StandardQueryConfigHandler.ConfigurationKeys.DEFAULT_OPERATOR should be set on the QueryConfigHandler");
            }

            this.usingAnd = Operator.AND == op;

            return ProcessIteration(queryTree);
        }

        protected virtual void ProcessChildren(IQueryNode queryTree)
        {
            IList<IQueryNode> children = queryTree.GetChildren();
            if (children != null && children.Count > 0)
            {
                foreach (IQueryNode child in children)
                {
                    /*child = */
                    ProcessIteration(child);
                }
            }
        }

        private IQueryNode ProcessIteration(IQueryNode queryTree)
        {
            queryTree = PreProcessNode(queryTree);

            ProcessChildren(queryTree);

            queryTree = PostProcessNode(queryTree);

            return queryTree;
        }

        protected virtual void FillChildrenBufferAndApplyModifiery(IQueryNode parent)
        {
            foreach (IQueryNode node in parent.GetChildren())
            {
                if (node.ContainsTag(TAG_REMOVE))
                {
                    FillChildrenBufferAndApplyModifiery(node);
                }
                else if (node.ContainsTag(TAG_MODIFIER))
                {
                    childrenBuffer.Add(ApplyModifier(node,
                        (Modifier)node.GetTag(TAG_MODIFIER)));
                }
                else
                {
                    childrenBuffer.Add(node);
                }
            }
        }

        protected virtual IQueryNode PostProcessNode(IQueryNode node)
        {
            if (node.ContainsTag(TAG_BOOLEAN_ROOT))
            {
                this.childrenBuffer.Clear();
                FillChildrenBufferAndApplyModifiery(node);
                node.Set(childrenBuffer);
            }
            return node;
        }

        protected virtual IQueryNode PreProcessNode(IQueryNode node)
        {
            IQueryNode parent = node.Parent;
            if (node is BooleanQueryNode)
            {
                if (parent is BooleanQueryNode)
                {
                    node.SetTag(TAG_REMOVE, true); // no precedence
                }
                else
                {
                    node.SetTag(TAG_BOOLEAN_ROOT, true);
                }
            }
            else if (parent is BooleanQueryNode)
            {
                if ((parent is AndQueryNode)
                    || (usingAnd && IsDefaultBooleanQueryNode(parent)))
                {
                    TagModifierButDoNotOverride(node, Modifier.MOD_REQ);
                }
            }
            return node;
        }

        protected virtual bool IsDefaultBooleanQueryNode(IQueryNode toTest)
        {
            return toTest != null && typeof(BooleanQueryNode).Equals(toTest.GetType());
        }

        private IQueryNode ApplyModifier(IQueryNode node, Modifier mod)
        {
            // check if modifier is not already defined and is default
            if (!(node is ModifierQueryNode))
            {
                return new BooleanModifierNode(node, mod);
            }
            else
            {
                ModifierQueryNode modNode = (ModifierQueryNode)node;

                if (modNode.Modifier == Modifier.MOD_NONE)
                {
                    return new ModifierQueryNode(modNode.GetChild(), mod);
                }
            }

            return node;
        }

        protected virtual void TagModifierButDoNotOverride(IQueryNode node, Modifier mod)
        {
            if (node is ModifierQueryNode)
            {
                ModifierQueryNode modNode = (ModifierQueryNode)node;
                if (modNode.Modifier == Modifier.MOD_NONE)
                {
                    node.SetTag(TAG_MODIFIER, mod);
                }
            }
            else
            {
                node.SetTag(TAG_MODIFIER, Modifier.MOD_REQ);
            }
        }

        public virtual void SetQueryConfigHandler(QueryConfigHandler queryConfigHandler)
        {
            this.queryConfigHandler = queryConfigHandler;
        }

        public virtual QueryConfigHandler GetQueryConfigHandler()
        {
            return queryConfigHandler;
        }
    }
}


text:
package org.kvj.bravo7.form.impl.bundle;

import android.os.Bundle;

import org.kvj.bravo7.form.BundleAdapter;

public class LongBundleAdapter extends BundleAdapter<Long> {

	@Override
	public Long get(Bundle bundle, String name, Long def) {
		return bundle.getLong(name, def);
	}

	@Override
	public void set(Bundle bundle, String name, Long value) {
		bundle.putLong(name, value);
	}

}


text:
@implementation UIBarButtonItem (navItem)

+ (instancetype)navItemWithImage:(UIImage *)image highlightImage:(UIImage *)highlightImage addTarget:(id)target action:(SEL)action {

    UIButton *itemButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [itemButton setImage:image forState:UIControlStateNormal];
    [itemButton setImage:highlightImage forState:UIControlStateHighlighted];
    [itemButton sizeToFit];
    [itemButton addTarget:target action:action forControlEvents:UIControlEventTouchUpInside];

    UIView *containView = [[UIView alloc] initWithFrame:itemButton.bounds];
    [containView addSubview:itemButton];
    return [[UIBarButtonItem alloc] initWithCustomView:containView];
}

+ (instancetype)navItemWithImage:(UIImage *)image selImage:(UIImage *)selImage addTarget:(id)target action:(SEL)action {

    UIButton *itemButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [itemButton setImage:image forState:UIControlStateNormal];
    [itemButton setImage:selImage forState:UIControlStateSelected];
    [itemButton sizeToFit];
    [itemButton addTarget:target action:action forControlEvents:UIControlEventTouchUpInside];

    UIView *containView = [[UIView alloc] initWithFrame:itemButton.bounds];

    [containView addSubview:itemButton];
    return [[UIBarButtonItem alloc] initWithCustomView:containView];
}

@end


text:
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;

namespace Aurora.Utils {

    public static class CollectionUtils {

        /// <summary>
        /// Creates a deep clone of an observable collection by cloning all individual items in the collection also.
        /// </summary>
        public static ObservableCollection<T> Clone<T>(this ObservableCollection<T> source) where T : ICloneable =>
            new ObservableCollection<T>(
                source.Select(c => (T)c.Clone())
            );

        /// <summary>
        /// Gets the element at the given index in the non-generic <see cref="IEnumerable"/>.
        /// </summary>
        /// <exception cref="IndexOutOfRangeException" />
        /// <remarks>Not called 'ElementAt' as this causes issues with <see cref="Enumerable.ElementAt{TSource}(System.Collections.Generic.IEnumerable{TSource}, int)"/>,
        /// where this method usually takes priority over the better generic method if the generic type parameter is missing.</remarks>
        public static object ElementAtIndex(this IEnumerable source, int index) {
            var i = 0;
            foreach (var item in source)
                if (index == i++)
                    return item;
            throw new IndexOutOfRangeException();
        }

        /// <summary>
        /// Deconstructor for a KeyValuePair.
        /// </summary>
        public static void Deconstruct<TKey, TValue>(this KeyValuePair<TKey, TValue> kvp, out TKey key, out TValue value) {
            key = kvp.Key;
            value = kvp.Value;
        }
    }
}