text:
package consulo.diagram.actions;

import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.CommonDataKeys;
import com.intellij.psi.PsiElement;
import consulo.ui.annotation.RequiredUIAccess;
import consulo.diagram.provider.GraphProvider;
import consulo.ide.eap.EarlyAccessProgramDescriptor;
import consulo.ide.eap.EarlyAccessProgramManager;
import javax.annotation.Nonnull;

/**
 * @author VISTALL
 * @since 22:29/15.10.13
 */
public class ShowDiagramAction extends AnAction {
  public static class DiagramSupport extends EarlyAccessProgramDescriptor {
    @Nonnull
    @Override
    public String getName() {
      return "Diagram Support";
    }

    @Override
    public boolean isAvailable() {
      return false;
    }

    @Nonnull
    @Override
    public String getDescription() {
      return "";
    }
  }

  @RequiredUIAccess
  @Override
  public void actionPerformed(@Nonnull AnActionEvent e) {
  }

  @RequiredUIAccess
  @Override
  public void update(@Nonnull AnActionEvent e) {
    boolean state = EarlyAccessProgramManager.is(DiagramSupport.class);
    if (state) {
      PsiElement psiElement = e.getData(CommonDataKeys.PSI_ELEMENT);
      state = false;
      if (psiElement != null) {
        state = false;
        for (GraphProvider graphProvider : GraphProvider.EP_NAME.getExtensionList()) {
          if (graphProvider.isSupported(psiElement)) {
            state = true;
            break;
          }
        }
      }
    }
    e.getPresentation().setEnabledAndVisible(state);
  }
}


text:
package easy.data.field;

import java.util.HashMap;

public interface IDFVisitor<T> {
	public T defaultVisit(IDataField df);
	public T visitPrimField(PrimField f, String basePath, String description);
	public T visitCompField(CompField f, String basePath, String description, HashMap<String, IDataField> fieldMap);
	public T visitListField(ListField f, String basePath, String description, String elemPath, IDataField elemField);
}

redpajama_set_name: RedPajamaGithub


text:
/*
Problem 160. Intersection of Two Linked Lists

Write a program to find the node at which the intersection of two singly linked lists begins.

For example, the following two linked lists:

A:          a1 → a2
                   ↘
                     c1 → c2 → c3
                   ↗
B:     b1 → b2 → b3

begin to intersect at node c1.

Notes:
If the two linked lists have no intersection at all, return null.
The linked lists must retain their original structure after the function returns.
You may assume there are no cycles anywhere in the entire linked structure.
Your code should preferably run in O(n) time and use only O(1) memory.
*/

/*
 Solution 1: Brute Force (Time Limit Exceeded)
 O(n1*n2) runtime and O(1) space complexities, where n1 is the length of headA and n2 that of headB

 Solution 2: Using a hash:
 Traverse the 1st list and store the address reference to each node in a hash set. Then check every node in the 2nd list;
 if it appears in the hash set, then this node is the intersection node.
 O(n1 + n2) runtime and O(n1) or O(n2) space complexities

 Solution 3: Using 2 pointers:
 1) If either headA or headB is null, we return null
 2) We use 2 pointers node1 and node1 that we initialize to headA and headB respectively.
 3) We make node1 and node2 traverse the lists one step at a time, as long as they are not equal.

 There will be a total of 2 iterations for each of them:
 When node1 (respectively node2) reaches the tail of a list1, we reset it to headB (respectively headA). In total, each
 of them will be reset to the head of the other once, therefore 2 iterations for each of them.
 They will intersect during their 2nd iteration, and at that point, we return one of them.

 Note that if the 2 lists don't intersect, then they both reach the tail nodes at the same time on the 2nd iteration,
 so they both become null. That means they are equal and null is returned.

 Example:
 list1 = {a1, a2, c1, c2} and list2 = {b1, b2, b3, b4, c1, c2}. So headA = a1 and headB = b1.
 Initially, we make node1 points to a1 and node2 points to b1.

 We iterate as long as node1 is not equal to node2, incrementing both of them 1 step at a time.
 Since list1 is the shorter list, node1 will reach the end 1st.
 By the time node1 reaches the end (null), node2 will be at c1. We then reset node1 to point to headB, which is b1.
 Now node1 points to b1 and node2 points to c1.

 We continue the iteration, which corresponds to the 2nd iteration of node1 but still 1st iteration of node2
 By the time node2 reaches the end, node1 will be at b3. We then reset node2 to point to a1.
 Now node1 points to b3 and node2 points to a1.

 We continue the iteration, which corresponds to the 2nd iteration of node1 and 2nd iteration of node2.
 After 2 more steps, both node1 and node2 will meet at c1. We then return this node, which is the point of intersection :)
 */

 public class GetIntersectionNode {

  public static class ListNode {
    int val;
    ListNode next;

    public ListNode(int x) {
      val = x;
      next = null;
    }
  }

  public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
    if (headA == null || headB == null) return null;

    ListNode node1 = headA, node2 = headB;

    while (node1 != node2) {

      if (node1 == null) { // end of 1st iteration of node1, so we reset it to poiint to headB
        node1 = headB;
      } else {
        node1 = node1.next; // otherwise, we increment it by 1 step
      }

      if (node2 == null) { // end of 1st iteration of node2, so we reset it to poiint to headA
        node2 = headA;
      } else {
        node2 = node2.next;  // otherwise, we increment it by 1 step
      }
    }

    return node1;
  }
}


text:
The jwks-server is a server to help with JWT access token authentication testing.
It supports two endpoints: `get-token` and `keys`.

# Usage

To run the server:
```bash
$ lein run <port> <key-file> <settings-file>
```

## Example:

```bash
$ lein run 8080 resources/jwks.json resources/settings.edn
...
jwks-server.main - command-line arguments: [8080 resources/jwks.json resources/settings.edn]
jwks-server.main - port: 8080
jwks-server.main - jwks file: resources/jwks.json
jwks-server.main - settings file: resources/settings.edn
jwks-server.main - starting server on port 8080
...
eclipse.jetty.server.Server - Started @10846ms
```

# Build Uberjar

```bash
$ lein uberjar
...
Created /path-to-waiter-jwks-server/target/uberjar/jwks-server-0.1.0-SNAPSHOT.jar
Created /path-to-waiter-jwks-server/target/uberjar/jwks-server-0.1.0-SNAPSHOT-standalone.jar
```

# JWKS keys

The keys stored in [jwks.json](resources/jwks.json) were obtained as follows:
- EdDSA keys were generated [uisng nimbus library's OctetKeyPair](https://connect2id.com/blog/nimbus-jose-jwt-6).
- The RS256 key was obtained from [buddy tests](https://github.com/funcool/buddy-sign/blob/master/test/buddy/sign/jwk_tests.clj).


text:
var iweblog = {};
iweblog.application = function() {

	// @sumamary: format flickr results for display
	function _display_images(data, count) {
		var htmlString = "", cnt = 0;

		$.each(data.items, function(i,item){
			if (cnt == count) return;

			var image = item.media.m;
      		var smallImage = image.replace("_m.jpg", "_s.jpg");
      		var largeImage = image.replace("_m.jpg", "_b.jpg");
			htmlString += "";
			htmlString += "";
			htmlString += "";
			cnt++;
		});

    $('#photos').html(htmlString);
		$('#photos').lightGallery();
	}

	return {
		displayImages: function(data, count) { _display_images(data, count); }
	}
}();


text:
'use strict'

const _ = require('lodash')
const Base = require('./base')

/**
 * Directors provide conversation firewalls, allowing listed users to be
 * authorised or blocked from entering scenes or preventing listeners from
 * firing.
 *
 * Access is determined by blacklist or whitelist, or if defined, a custom
 * fallback function can determine to allow or deny anyone not on the list.
 *
 * A director can be attached to whole scenes or dialogues, or even specific
 * listeners.
 *
 * _Authorise_ function is given the user or room name (depending on the scope
 * configured for the direcrot) and response object. It must return a boolean to
 * determine access.
 *
 * `config.deniedReply` can be set globally with environment var `DENIED_REPLY`
 *
 * Environment vars can also provide global default lists:
 * - `WHITELIST_USERNAMES` for whitelist type and username scope directors
 * - `WHITELIST_ROOMS` for whitelist type and room scope directors
 * - `BLACKLIST_USERNAMES` for blacklist type and username scope directors
 * - `BLACKLIST_ROOMS` for blacklist type and room scope directors
 *
 * @param {Robot}    robot               Hubot Robot instance
 * @param {Function} [authorise]         Function to determine access (as fallback)
 * @param {Object} [options]             Key/val options for config
 * @param {string} [options.type]        'whitelist' (default) or 'blacklist'
 * @param {string} [options.scope]       'username' (default) or 'room'
 * @param {string} [options.deniedReply] Sent when denied access
 * @param {string} [key]                 Key name for this instance
 *
 *
 * @example
check if user has a particular role in platform

 * let adminsOnly = new Director(robot, (username) => {
 *   return chatPlatform.userHasPermission(username, 'admin')
 * })
 * // ...when directing a scene, will only allow platform admins to enter.
*/
class Director extends Base {
  constructor (robot, ...args) {
    let authArg = _.isFunction(args[0]) ? args.shift() : null
    super('director', robot, ...args)
    this.defaults({
      type: 'whitelist',
      scope: 'username',
      deniedReply: process.env.DENIED_REPLY || null
    })
    this.authorise = authArg

    if (!_.includes(['whitelist', 'blacklist'], this.config.type)) this.error('Invalid type')
    if (!_.includes(['username', 'room'], this.config.scope)) this.error('Invalid scope')
    this.log.info(`New ${this.config.scope} Director ${this.config.type}`)

    const listEnv = this.config.type.toUpperCase()
    switch (this.config.scope) {
      case 'username': this.names = process.env[`${listEnv}_USERNAMES`]
        break
      case 'room': this.names = process.env[`${listEnv}_ROOMS`]
    }
    if (this.names != null) this.names = this.names.split(',')
    if (this.names == null) this.names = []
  }

  /**
   * Add new usernames/rooms to list.
   *
   * @param  {string/array} names Usernames or Room names (depending on scope)
   * @return {Director}           Self, for chaining methods
  */
  add (names) {
    this.log.info(`Adding ${names.toString()} to ${this.id} ${this.config.type}`)
    this.names = _.union(this.names, _.castArray(names))
    return this
  }

  /**
   * Remove new usernames/rooms from list.
   *
   * @param  {string/array} names Usernames or Room names (depending on scope)
   * @return {Director}           Self, for chaining methods
  */
  remove (names) {
    this.log.info(`Removing ${names.toString()} from ${this.id} ${this.config.type}`)
    this.names = _.without(this.names, ..._.castArray(names))
    return this
  }

  /**
   * Determine if user has access, checking usernames/rooms against lists.
   *
   * _Blacklist_ blocks names on list, let anyone else through. _Whitelist_ lets
   * names on list through, block anyone else. Whitelist is default behaviour.
   *
   * @param  {Response} res    Hubot Response object
   * @return {Boolean/Promise} Access allowed - should wrap in resolve
   *
   * @example
assumes res1, res2 are valid Response objects

   * let noHomers = new Director(robot, { type: 'blacklist' }).add('homer')
   * res1.message.user.name = 'homer'
   * res2.message.user.name = 'marge'
   * noHomers.isAllowed(res1) // false
   * noHomers.isAllowed(res2) // true
  */
  isAllowed (res) {
    let name
    switch (this.config.scope) {
      case 'username': name = res.message.user.name
        break
      case 'room': name = res.message.room
    }

    if (this.config.type === 'blacklist') {
      if (_.includes(this.names, name)) return false
      if (this.authorise == null) return true
    } else {
      if (_.includes(this.names, name)) return true
      if (this.authorise == null) return false
    }
    return this.authorise(name, res)
  }

  /**
   * Process access or denial (either silently or with reply, as configured).
   *
   * @param  {Response} res Hubot Response object
   * @return {Promise}      Resolves with boolean, access allowed/denied
  */
  process (res) {
    const isAllowed = Promise.resolve(this.isAllowed(res))
    const user = res.message.user.name
    const message = res.message.text
    return isAllowed.then((allowed) => {
      if (allowed) {
        this.log.debug(`${this.id} allowed ${user} on receiving ${message}`)
        this.emit('allow', res)
      } else {
        this.log.info(`${this.id} denied ${user} on receiving: ${message}`)
        this.emit('deny', res)
        if (!_.includes(['', null], this.config.deniedReply)) res.reply(this.config.deniedReply)
      }
      return allowed
    })
  }

  /**
   * Let this director control access to any listener matching regex.
   *
   * @param  {Regex}  regex Listener match pattern
   * @return {Director}     Self, for chaining methods
  */
  directMatch (regex) {
    this.log.info(`Now directing access to listeners matching ${regex}`)
    this.robot.listenerMiddleware((context, next, done) => {
      if (!context.response.message.text.match(regex)) return next(done)
      this.process(context.response).then((allowed) => {
        if (allowed) return next(done)
        context.response.message.finish() // don't process this message further
        return done() // don't process further middleware
      })
    }) // nothing matched or user allowed
    return this
  }

  /**
   * Let this director control access to a listener by listener ID.
   *
   * If multiple listeners use the same ID, it's assumed to deny all of them.
   *
   * @param  {string}   id Listener ID (may be multiple for scene)
   * @return {Director}    Self, for chaining methods
  */
  directListener (id) {
    this.log.info(`Now directing access to listener ${id}`)
    this.robot.listenerMiddleware((context, next, done) => {
      if (context.listener.options.id !== id) return next(done)
      this.process(context.response).then((allowed) => {
        if (allowed) return next(done)
        context.response.message.finish() // don't process this message further
        return done() // don't process further middleware
      })
    }) // nothing matched or user allowed
    return this
  }

  /**
   * Let this director control access to a given scene's listener.
   *
   * Also hooks into `Scene.enter` to control access to manually entered scenes.
   *
   * @param  {Scene} scene The Scene instance
   * @return {Director}    Self, for chaining methods
  */
  directScene (scene) {
    this.log.info(`Now directing access to ${scene.id} ${scene.key}`)
    const director = this
    scene.registerMiddleware((context, next, done) => {
      director.process(context.response).then((allowed) => {
        if (allowed) next(done)
        else done()
      })
    })
    return this
  }
}

module.exports = Director


text:
<?php

namespace Doctrine\Tests\ORM\Mapping;

use Doctrine\ORM\Mapping\ClassMetadata,
    Doctrine\ORM\Mapping\ClassMetadataInfo,
    Doctrine\ORM\Mapping\Driver\XmlDriver,
    Doctrine\ORM\Mapping\Driver\YamlDriver;

require_once __DIR__ . '/../../TestInit.php';

abstract class AbstractMappingDriverTest extends \Doctrine\Tests\OrmTestCase
{
    abstract protected function _loadDriver();

    public function createClassMetadata($entityClassName)
    {
        $mappingDriver = $this->_loadDriver();

        $class = new ClassMetadata($entityClassName);
        $class->initializeReflection(new \Doctrine\Common\Persistence\Mapping\RuntimeReflectionService);
        $mappingDriver->loadMetadataForClass($entityClassName, $class);

        return $class;
    }

    /**
     * @param \Doctrine\ORM\EntityManager $entityClassName
     * @return \Doctrine\ORM\Mapping\ClassMetadataFactory
     */
    protected function createClassMetadataFactory(\Doctrine\ORM\EntityManager $em = null)
    {
        $driver     = $this->_loadDriver();
        $em         = $em ?: $this->_getTestEntityManager();
        $factory    = new \Doctrine\ORM\Mapping\ClassMetadataFactory();
        $em->getConfiguration()->setMetadataDriverImpl($driver);
        $factory->setEntityManager($em);

        return $factory;
    }

    public function testLoadMapping()
    {
        $entityClassName = 'Doctrine\Tests\ORM\Mapping\User';
        return $this->createClassMetadata($entityClassName);
    }

    /**
     * @depends testLoadMapping
     * @param ClassMetadata $class
     */
    public function testEntityTableNameAndInheritance($class)
    {
        $this->assertEquals('cms_users', $class->getTableName());
        $this->assertEquals(ClassMetadata::INHERITANCE_TYPE_NONE, $class->inheritanceType);

        return $class;
    }

    /**
     * @depends testEntityTableNameAndInheritance
     * @param ClassMetadata $class
     */
    public function testEntityIndexes($class)
    {
        $this->assertArrayHasKey('indexes', $class->table, 'ClassMetadata should have indexes key in table property.');
        $this->assertEquals(array(
            'name_idx' => array('columns' => array('name')),
            0 => array('columns' => array('user_email'))
        ), $class->table['indexes']);

        return $class;
    }

    /**
     * @depends testEntityTableNameAndInheritance
     * @param ClassMetadata $class
     */
    public function testEntityUniqueConstraints($class)
    {
        $this->assertArrayHasKey('uniqueConstraints', $class->table,
            'ClassMetadata should have uniqueConstraints key in table property when Unique Constraints are set.');

        $this->assertEquals(array(
            "search_idx" => array("columns" => array("name", "user_email"))
        ), $class->table['uniqueConstraints']);

        return $class;
    }

    /**
     * @depends testEntityTableNameAndInheritance
     * @param ClassMetadata $class
     */
    public function testEntityOptions($class)
    {
        $this->assertArrayHasKey('options', $class->table, 'ClassMetadata should have options key in table property.');

        $this->assertEquals(array(
            'foo' => 'bar', 'baz' => array('key' => 'val')
        ), $class->table['options']);

        return $class;
    }

    /**
     * @depends testEntityOptions
     * @param ClassMetadata $class
     */
    public function testEntitySequence($class)
    {
        $this->assertInternalType('array', $class->sequenceGeneratorDefinition, 'No Sequence Definition set on this driver.');
        $this->assertEquals(
            array(
                'sequenceName' => 'tablename_seq',
                'allocationSize' => 100,
                'initialValue' => 1,
            ),
            $class->sequenceGeneratorDefinition
        );
    }

    public function testEntityCustomGenerator()
    {
        $class = $this->createClassMetadata('Doctrine\Tests\ORM\Mapping\Animal');

        $this->assertEquals(ClassMetadata::GENERATOR_TYPE_CUSTOM,
            $class->generatorType, "Generator Type");
        $this->assertEquals(
            array("class" => "stdClass"),
            $class->customGeneratorDefinition,
            "Custom Generator Definition");
    }

    /**
     * @depends testEntityTableNameAndInheritance
     * @param ClassMetadata $class
     */
    public function testFieldMappings($class)
    {
        $this->assertEquals(4, count($class->fieldMappings));
        $this->assertTrue(isset($class->fieldMappings['id']));
        $this->assertTrue(isset($class->fieldMappings['name']));
        $this->assertTrue(isset($class->fieldMappings['email']));
        $this->assertTrue(isset($class->fieldMappings['version']));

        return $class;
    }

    /**
     * @depends testFieldMappings
     * @param ClassMetadata $class
     */
    public function testVersionedField($class)
    {
        $this->assertTrue($class->isVersioned);
        $this->assertEquals("version", $class->versionField);

        $this->assertFalse(isset($class->fieldMappings['version']['version']));
    }

    /**
     * @depends testEntityTableNameAndInheritance
     * @param ClassMetadata $class
     */
    public function testFieldMappingsColumnNames($class)
    {
        $this->assertEquals("id", $class->fieldMappings['id']['columnName']);
        $this->assertEquals("name", $class->fieldMappings['name']['columnName']);
        $this->assertEquals("user_email", $class->fieldMappings['email']['columnName']);

        return $class;
    }

    /**
     * @depends testEntityTableNameAndInheritance
     * @param ClassMetadata $class
     */
    public function testStringFieldMappings($class)
    {
        $this->assertEquals('string', $class->fieldMappings['name']['type']);
        $this->assertEquals(50, $class->fieldMappings['name']['length']);
        $this->assertTrue($class->fieldMappings['name']['nullable']);
        $this->assertTrue($class->fieldMappings['name']['unique']);

        $expected = array('foo' => 'bar', 'baz' => array('key' => 'val'));
        $this->assertEquals($expected, $class->fieldMappings['name']['options']);

        return $class;
    }

    /**
     * @depends testFieldMappings
     * @param ClassMetadata $class
     */
    public function testIdentifier($class)
    {
        $this->assertEquals(array('id'), $class->identifier);
        $this->assertEquals('integer', $class->fieldMappings['id']['type']);
        $this->assertEquals(ClassMetadata::GENERATOR_TYPE_AUTO, $class->generatorType, "ID-Generator is not ClassMetadata::GENERATOR_TYPE_AUTO");

        return $class;
    }

    /**
     * @depends testIdentifier
     * @param ClassMetadata $class
     */
    public function testAssocations($class)
    {
        $this->assertEquals(3, count($class->associationMappings));

        return $class;
    }

    /**
     * @depends testAssocations
     * @param ClassMetadata $class
     */
    public function testOwningOneToOneAssocation($class)
    {
        $this->assertTrue(isset($class->associationMappings['address']));
        $this->assertTrue($class->associationMappings['address']['isOwningSide']);
        $this->assertEquals('user', $class->associationMappings['address']['inversedBy']);
        // Check cascading
        $this->assertTrue($class->associationMappings['address']['isCascadeRemove']);
        $this->assertFalse($class->associationMappings['address']['isCascadePersist']);
        $this->assertFalse($class->associationMappings['address']['isCascadeRefresh']);
        $this->assertFalse($class->associationMappings['address']['isCascadeDetach']);
        $this->assertFalse($class->associationMappings['address']['isCascadeMerge']);

        return $class;
    }

    /**
     * @depends testOwningOneToOneAssocation
     * @param ClassMetadata $class
     */
    public function testInverseOneToManyAssociation($class)
    {
        $this->assertTrue(isset($class->associationMappings['phonenumbers']));
        $this->assertFalse($class->associationMappings['phonenumbers']['isOwningSide']);
        $this->assertTrue($class->associationMappings['phonenumbers']['isCascadePersist']);
        $this->assertTrue($class->associationMappings['phonenumbers']['isCascadeRemove']);
        $this->assertFalse($class->associationMappings['phonenumbers']['isCascadeRefresh']);
        $this->assertFalse($class->associationMappings['phonenumbers']['isCascadeDetach']);
        $this->assertFalse($class->associationMappings['phonenumbers']['isCascadeMerge']);
        $this->assertTrue($class->associationMappings['phonenumbers']['orphanRemoval']);

        // Test Project By
        $this->assertEquals(array('number' => 'ASC'), $class->associationMappings['phonenumbers']['orderBy']);

        return $class;
    }

    /**
     * @depends testInverseOneToManyAssociation
     * @param ClassMetadata $class
     */
    public function testManyToManyAssociationWithCascadeAll($class)
    {
        $this->assertTrue(isset($class->associationMappings['groups']));
        $this->assertTrue($class->associationMappings['groups']['isOwningSide']);
        // Make sure that cascade-all works as expected
        $this->assertTrue($class->associationMappings['groups']['isCascadeRemove']);
        $this->assertTrue($class->associationMappings['groups']['isCascadePersist']);
        $this->assertTrue($class->associationMappings['groups']['isCascadeRefresh']);
        $this->assertTrue($class->associationMappings['groups']['isCascadeDetach']);
        $this->assertTrue($class->associationMappings['groups']['isCascadeMerge']);

        $this->assertFalse(isset($class->associationMappings['groups']['orderBy']));

        return $class;
    }

    /**
     * @depends testManyToManyAssociationWithCascadeAll
     * @param ClassMetadata $class
     */
    public function testLifecycleCallbacks($class)
    {
        $this->assertEquals(count($class->lifecycleCallbacks), 2);
        $this->assertEquals($class->lifecycleCallbacks['prePersist'][0], 'doStuffOnPrePersist');
        $this->assertEquals($class->lifecycleCallbacks['postPersist'][0], 'doStuffOnPostPersist');

        return $class;
    }

    /**
     * @depends testManyToManyAssociationWithCascadeAll
     * @param ClassMetadata $class
     */
    public function testLifecycleCallbacksSupportMultipleMethodNames($class)
    {
        $this->assertEquals(count($class->lifecycleCallbacks['prePersist']), 2);
        $this->assertEquals($class->lifecycleCallbacks['prePersist'][1], 'doOtherStuffOnPrePersistToo');

        return $class;
    }

    /**
     * @depends testLifecycleCallbacksSupportMultipleMethodNames
     * @param ClassMetadata $class
     */
    public function testJoinColumnUniqueAndNullable($class)
    {
        // Non-Nullability of Join Column
        $this->assertFalse($class->associationMappings['groups']['joinTable']['joinColumns'][0]['nullable']);
        $this->assertFalse($class->associationMappings['groups']['joinTable']['joinColumns'][0]['unique']);

        return $class;
    }

    /**
     * @depends testJoinColumnUniqueAndNullable
     * @param ClassMetadata $class
     */
    public function testColumnDefinition($class)
    {
        $this->assertEquals("CHAR(32) NOT NULL", $class->fieldMappings['email']['columnDefinition']);
        $this->assertEquals("INT NULL", $class->associationMappings['groups']['joinTable']['inverseJoinColumns'][0]['columnDefinition']);

        return $class;
    }

    /**
     * @depends testColumnDefinition
     * @param ClassMetadata $class
     */
    public function testJoinColumnOnDelete($class)
    {
        $this->assertEquals('CASCADE', $class->associationMappings['address']['joinColumns'][0]['onDelete']);

        return $class;
    }

    /**
     * @group DDC-514
     */
    public function testDiscriminatorColumnDefaults()
    {
        if (strpos(get_class($this), 'PHPMappingDriver') !== false) {
            $this->markTestSkipped('PHP Mapping Drivers have no defaults.');
        }

        $class = $this->createClassMetadata('Doctrine\Tests\ORM\Mapping\Animal');

        $this->assertEquals(
            array('name' => 'discr', 'type' => 'string', 'length' => '32', 'fieldName' => 'discr', 'columnDefinition' => null),
            $class->discriminatorColumn
        );
    }

    /**
     * @group DDC-869
     */
    public function testMappedSuperclassWithRepository()
    {
        $em         = $this->_getTestEntityManager();
        $factory    = $this->createClassMetadataFactory($em);

        $class = $factory->getMetadataFor('Doctrine\Tests\Models\DDC869\DDC869CreditCardPayment');

        $this->assertTrue(isset($class->fieldMappings['id']));
        $this->assertTrue(isset($class->fieldMappings['value']));
        $this->assertTrue(isset($class->fieldMappings['creditCardNumber']));
        $this->assertEquals($class->customRepositoryClassName, "Doctrine\Tests\Models\DDC869\DDC869PaymentRepository");
        $this->assertInstanceOf("Doctrine\Tests\Models\DDC869\DDC869PaymentRepository",
             $em->getRepository("Doctrine\Tests\Models\DDC869\DDC869CreditCardPayment"));
        $this->assertTrue($em->getRepository("Doctrine\Tests\Models\DDC869\DDC869ChequePayment")->isTrue());

        $class = $factory->getMetadataFor('Doctrine\Tests\Models\DDC869\DDC869ChequePayment');

        $this->assertTrue(isset($class->fieldMappings['id']));
        $this->assertTrue(isset($class->fieldMappings['value']));
        $this->assertTrue(isset($class->fieldMappings['serialNumber']));
        $this->assertEquals($class->customRepositoryClassName, "Doctrine\Tests\Models\DDC869\DDC869PaymentRepository");
        $this->assertInstanceOf("Doctrine\Tests\Models\DDC869\DDC869PaymentRepository",
             $em->getRepository("Doctrine\Tests\Models\DDC869\DDC869ChequePayment"));
        $this->assertTrue($em->getRepository("Doctrine\Tests\Models\DDC869\DDC869ChequePayment")->isTrue());
    }

    /**
     * @group DDC-1476
     */
    public function testDefaultFieldType()
    {
        $factory    = $this->createClassMetadataFactory();
        $class      = $factory->getMetadataFor('Doctrine\Tests\Models\DDC1476\DDC1476EntityWithDefaultFieldType');

        $this->assertArrayHasKey('id', $class->fieldMappings);
        $this->assertArrayHasKey('name', $class->fieldMappings);

        $this->assertArrayHasKey('type', $class->fieldMappings['id']);
        $this->assertArrayHasKey('type', $class->fieldMappings['name']);

        $this->assertEquals('string', $class->fieldMappings['id']['type']);
        $this->assertEquals('string', $class->fieldMappings['name']['type']);

        $this->assertArrayHasKey('fieldName', $class->fieldMappings['id']);
        $this->assertArrayHasKey('fieldName', $class->fieldMappings['name']);

        $this->assertEquals('id', $class->fieldMappings['id']['fieldName']);
        $this->assertEquals('name', $class->fieldMappings['name']['fieldName']);

        $this->assertArrayHasKey('columnName', $class->fieldMappings['id']);
        $this->assertArrayHasKey('columnName', $class->fieldMappings['name']);

        $this->assertEquals('id', $class->fieldMappings['id']['columnName']);
        $this->assertEquals('name', $class->fieldMappings['name']['columnName']);

        $this->assertEquals(ClassMetadataInfo::GENERATOR_TYPE_NONE, $class->generatorType);
    }

    /**
     * @group DDC-1170
     */
    public function testIdentifierColumnDefinition()
    {
        $class = $this->createClassMetadata(__NAMESPACE__ . '\DDC1170Entity');

        $this->assertArrayHasKey('id', $class->fieldMappings);
        $this->assertArrayHasKey('value', $class->fieldMappings);

        $this->assertArrayHasKey('columnDefinition', $class->fieldMappings['id']);
        $this->assertArrayHasKey('columnDefinition', $class->fieldMappings['value']);

        $this->assertEquals("INT unsigned NOT NULL", $class->fieldMappings['id']['columnDefinition']);
        $this->assertEquals("VARCHAR(255) NOT NULL", $class->fieldMappings['value']['columnDefinition']);
    }

    /**
     * @group DDC-559
     */
    public function testNamingStrategy()
    {
        $em         = $this->_getTestEntityManager();
        $factory    = $this->createClassMetadataFactory($em);

        $this->assertInstanceOf('Doctrine\ORM\Mapping\DefaultNamingStrategy', $em->getConfiguration()->getNamingStrategy());
        $em->getConfiguration()->setNamingStrategy(new \Doctrine\ORM\Mapping\UnderscoreNamingStrategy(CASE_UPPER));
        $this->assertInstanceOf('Doctrine\ORM\Mapping\UnderscoreNamingStrategy', $em->getConfiguration()->getNamingStrategy());

        $class = $factory->getMetadataFor('Doctrine\Tests\Models\DDC1476\DDC1476EntityWithDefaultFieldType');

        $this->assertEquals('ID', $class->columnNames['id']);
        $this->assertEquals('NAME', $class->columnNames['name']);
        $this->assertEquals('DDC1476ENTITY_WITH_DEFAULT_FIELD_TYPE', $class->table['name']);
    }

    /**
     * @group DDC-807
     * @group DDC-553
     */
    public function testDiscriminatorColumnDefinition()
    {
        $class = $this->createClassMetadata(__NAMESPACE__ . '\DDC807Entity');

        $this->assertArrayHasKey('columnDefinition', $class->discriminatorColumn);
        $this->assertArrayHasKey('name', $class->discriminatorColumn);

        $this->assertEquals("ENUM('ONE','TWO')", $class->discriminatorColumn['columnDefinition']);
        $this->assertEquals("dtype", $class->discriminatorColumn['name']);
    }

    /**
     * @group DDC-889
     */
    public function testInvalidEntityOrMappedSuperClassShouldMentionParentClasses()
    {
        $this->setExpectedException('Doctrine\ORM\Mapping\MappingException', 'Class "Doctrine\Tests\Models\DDC889\DDC889Class" sub class of "Doctrine\Tests\Models\DDC889\DDC889SuperClass" is not a valid entity or mapped super class.');

        $this->createClassMetadata('Doctrine\Tests\Models\DDC889\DDC889Class');
    }

    /**
     * @group DDC-889
     */
    public function testIdentifierRequiredShouldMentionParentClasses()
    {
        $factory = $this->createClassMetadataFactory();

        $this->setExpectedException('Doctrine\ORM\Mapping\MappingException', 'No identifier/primary key specified for Entity "Doctrine\Tests\Models\DDC889\DDC889Entity" sub class of "Doctrine\Tests\Models\DDC889\DDC889SuperClass". Every Entity must have an identifier/primary key.');
        $factory->getMetadataFor('Doctrine\Tests\Models\DDC889\DDC889Entity');
    }

    public function testNamedQuery()
    {
        $driver = $this->_loadDriver();
        $class = $this->createClassMetadata(__NAMESPACE__.'\User');

        $this->assertCount(1, $class->getNamedQueries(), sprintf("Named queries not processed correctly by driver %s", get_class($driver)));
    }

    /**
     * @group DDC-1663
     */
    public function testNamedNativeQuery()
    {

        $class = $this->createClassMetadata('Doctrine\Tests\Models\CMS\CmsAddress');

        //named native query
        $this->assertCount(3, $class->namedNativeQueries);
        $this->assertArrayHasKey('find-all', $class->namedNativeQueries);
        $this->assertArrayHasKey('find-by-id', $class->namedNativeQueries);

        $findAllQuery = $class->getNamedNativeQuery('find-all');
        $this->assertEquals('find-all', $findAllQuery['name']);
        $this->assertEquals('mapping-find-all', $findAllQuery['resultSetMapping']);
        $this->assertEquals('SELECT id, country, city FROM cms_addresses', $findAllQuery['query']);

        $findByIdQuery = $class->getNamedNativeQuery('find-by-id');
        $this->assertEquals('find-by-id', $findByIdQuery['name']);
        $this->assertEquals('Doctrine\Tests\Models\CMS\CmsAddress',$findByIdQuery['resultClass']);
        $this->assertEquals('SELECT * FROM cms_addresses WHERE id = ?',  $findByIdQuery['query']);

        $countQuery = $class->getNamedNativeQuery('count');
        $this->assertEquals('count', $countQuery['name']);
        $this->assertEquals('mapping-count', $countQuery['resultSetMapping']);
        $this->assertEquals('SELECT COUNT(*) AS count FROM cms_addresses',  $countQuery['query']);

        // result set mapping
        $this->assertCount(3, $class->sqlResultSetMappings);
        $this->assertArrayHasKey('mapping-count', $class->sqlResultSetMappings);
        $this->assertArrayHasKey('mapping-find-all', $class->sqlResultSetMappings);
        $this->assertArrayHasKey('mapping-without-fields', $class->sqlResultSetMappings);

        $findAllMapping = $class->getSqlResultSetMapping('mapping-find-all');
        $this->assertEquals('mapping-find-all', $findAllMapping['name']);
        $this->assertEquals('Doctrine\Tests\Models\CMS\CmsAddress', $findAllMapping['entities'][0]['entityClass']);
        $this->assertEquals(array('name'=>'id','column'=>'id'), $findAllMapping['entities'][0]['fields'][0]);
        $this->assertEquals(array('name'=>'city','column'=>'city'), $findAllMapping['entities'][0]['fields'][1]);
        $this->assertEquals(array('name'=>'country','column'=>'country'), $findAllMapping['entities'][0]['fields'][2]);

        $withoutFieldsMapping = $class->getSqlResultSetMapping('mapping-without-fields');
        $this->assertEquals('mapping-without-fields', $withoutFieldsMapping['name']);
        $this->assertEquals('Doctrine\Tests\Models\CMS\CmsAddress', $withoutFieldsMapping['entities'][0]['entityClass']);
        $this->assertEquals(array(), $withoutFieldsMapping['entities'][0]['fields']);

        $countMapping = $class->getSqlResultSetMapping('mapping-count');
        $this->assertEquals('mapping-count', $countMapping['name']);
        $this->assertEquals(array('name'=>'count'), $countMapping['columns'][0]);

    }

    /**
     * @group DDC-1663
     */
    public function testSqlResultSetMapping()
    {

        $userMetadata   = $this->createClassMetadata('Doctrine\Tests\Models\CMS\CmsUser');
        $personMetadata = $this->createClassMetadata('Doctrine\Tests\Models\Company\CompanyPerson');

        // user asserts
        $this->assertCount(4, $userMetadata->getSqlResultSetMappings());

        $mapping = $userMetadata->getSqlResultSetMapping('mappingJoinedAddress');
        $this->assertEquals(array(),$mapping['columns']);
        $this->assertEquals('mappingJoinedAddress', $mapping['name']);
        $this->assertNull($mapping['entities'][0]['discriminatorColumn']);
        $this->assertEquals(array('name'=>'id','column'=>'id'),                     $mapping['entities'][0]['fields'][0]);
        $this->assertEquals(array('name'=>'name','column'=>'name'),                 $mapping['entities'][0]['fields'][1]);
        $this->assertEquals(array('name'=>'status','column'=>'status'),             $mapping['entities'][0]['fields'][2]);
        $this->assertEquals(array('name'=>'address.zip','column'=>'zip'),           $mapping['entities'][0]['fields'][3]);
        $this->assertEquals(array('name'=>'address.city','column'=>'city'),         $mapping['entities'][0]['fields'][4]);
        $this->assertEquals(array('name'=>'address.country','column'=>'country'),   $mapping['entities'][0]['fields'][5]);
        $this->assertEquals(array('name'=>'address.id','column'=>'a_id'),           $mapping['entities'][0]['fields'][6]);
        $this->assertEquals($userMetadata->name,                                    $mapping['entities'][0]['entityClass']);

        $mapping = $userMetadata->getSqlResultSetMapping('mappingJoinedPhonenumber');
        $this->assertEquals(array(),$mapping['columns']);
        $this->assertEquals('mappingJoinedPhonenumber', $mapping['name']);
        $this->assertNull($mapping['entities'][0]['discriminatorColumn']);
        $this->assertEquals(array('name'=>'id','column'=>'id'),                             $mapping['entities'][0]['fields'][0]);
        $this->assertEquals(array('name'=>'name','column'=>'name'),                         $mapping['entities'][0]['fields'][1]);
        $this->assertEquals(array('name'=>'status','column'=>'status'),                     $mapping['entities'][0]['fields'][2]);
        $this->assertEquals(array('name'=>'phonenumbers.phonenumber','column'=>'number'),   $mapping['entities'][0]['fields'][3]);
        $this->assertEquals($userMetadata->name,                                            $mapping['entities'][0]['entityClass']);

        $mapping = $userMetadata->getSqlResultSetMapping('mappingUserPhonenumberCount');
        $this->assertEquals(array('name'=>'numphones'),$mapping['columns'][0]);
        $this->assertEquals('mappingUserPhonenumberCount', $mapping['name']);
        $this->assertNull($mapping['entities'][0]['discriminatorColumn']);
        $this->assertEquals(array('name'=>'id','column'=>'id'),         $mapping['entities'][0]['fields'][0]);
        $this->assertEquals(array('name'=>'name','column'=>'name'),     $mapping['entities'][0]['fields'][1]);
        $this->assertEquals(array('name'=>'status','column'=>'status'), $mapping['entities'][0]['fields'][2]);
        $this->assertEquals($userMetadata->name,                        $mapping['entities'][0]['entityClass']);

        $mapping = $userMetadata->getSqlResultSetMapping('mappingMultipleJoinsEntityResults');
        $this->assertEquals(array('name'=>'numphones'),$mapping['columns'][0]);
        $this->assertEquals('mappingMultipleJoinsEntityResults', $mapping['name']);
        $this->assertNull($mapping['entities'][0]['discriminatorColumn']);
        $this->assertEquals(array('name'=>'id','column'=>'u_id'),           $mapping['entities'][0]['fields'][0]);
        $this->assertEquals(array('name'=>'name','column'=>'u_name'),       $mapping['entities'][0]['fields'][1]);
        $this->assertEquals(array('name'=>'status','column'=>'u_status'),   $mapping['entities'][0]['fields'][2]);
        $this->assertEquals($userMetadata->name,                            $mapping['entities'][0]['entityClass']);
        $this->assertNull($mapping['entities'][1]['discriminatorColumn']);
        $this->assertEquals(array('name'=>'id','column'=>'a_id'),           $mapping['entities'][1]['fields'][0]);
        $this->assertEquals(array('name'=>'zip','column'=>'a_zip'),         $mapping['entities'][1]['fields'][1]);
        $this->assertEquals(array('name'=>'country','column'=>'a_country'), $mapping['entities'][1]['fields'][2]);
        $this->assertEquals('Doctrine\Tests\Models\CMS\CmsAddress',         $mapping['entities'][1]['entityClass']);

        //person asserts
        $this->assertCount(1, $personMetadata->getSqlResultSetMappings());

        $mapping = $personMetadata->getSqlResultSetMapping('mappingFetchAll');
        $this->assertEquals(array(),$mapping['columns']);
        $this->assertEquals('mappingFetchAll', $mapping['name']);
        $this->assertEquals('discriminator',                            $mapping['entities'][0]['discriminatorColumn']);
        $this->assertEquals(array('name'=>'id','column'=>'id'),         $mapping['entities'][0]['fields'][0]);
        $this->assertEquals(array('name'=>'name','column'=>'name'),     $mapping['entities'][0]['fields'][1]);
        $this->assertEquals($personMetadata->name,                      $mapping['entities'][0]['entityClass']);
    }

     /*
     * @group DDC-964
     */
    public function testAssociationOverridesMapping()
    {

        $factory        = $this->createClassMetadataFactory();
        $adminMetadata  = $factory->getMetadataFor('Doctrine\Tests\Models\DDC964\DDC964Admin');
        $guestMetadata  = $factory->getMetadataFor('Doctrine\Tests\Models\DDC964\DDC964Guest');

        // assert groups association mappings
        $this->assertArrayHasKey('groups', $guestMetadata->associationMappings);
        $this->assertArrayHasKey('groups', $adminMetadata->associationMappings);

        $guestGroups = $guestMetadata->associationMappings['groups'];
        $adminGroups = $adminMetadata->associationMappings['groups'];

        // assert not override attributes
        $this->assertEquals($guestGroups['fieldName'], $adminGroups['fieldName']);
        $this->assertEquals($guestGroups['type'], $adminGroups['type']);
        $this->assertEquals($guestGroups['mappedBy'], $adminGroups['mappedBy']);
        $this->assertEquals($guestGroups['inversedBy'], $adminGroups['inversedBy']);
        $this->assertEquals($guestGroups['isOwningSide'], $adminGroups['isOwningSide']);
        $this->assertEquals($guestGroups['fetch'], $adminGroups['fetch']);
        $this->assertEquals($guestGroups['isCascadeRemove'], $adminGroups['isCascadeRemove']);
        $this->assertEquals($guestGroups['isCascadePersist'], $adminGroups['isCascadePersist']);
        $this->assertEquals($guestGroups['isCascadeRefresh'], $adminGroups['isCascadeRefresh']);
        $this->assertEquals($guestGroups['isCascadeMerge'], $adminGroups['isCascadeMerge']);
        $this->assertEquals($guestGroups['isCascadeDetach'], $adminGroups['isCascadeDetach']);

         // assert not override attributes
        $this->assertEquals('ddc964_users_groups', $guestGroups['joinTable']['name']);
        $this->assertEquals('user_id', $guestGroups['joinTable']['joinColumns'][0]['name']);
        $this->assertEquals('group_id', $guestGroups['joinTable']['inverseJoinColumns'][0]['name']);

        $this->assertEquals(array('user_id'=>'id'), $guestGroups['relationToSourceKeyColumns']);
        $this->assertEquals(array('group_id'=>'id'), $guestGroups['relationToTargetKeyColumns']);
        $this->assertEquals(array('user_id','group_id'), $guestGroups['joinTableColumns']);

        $this->assertEquals('ddc964_users_admingroups', $adminGroups['joinTable']['name']);
        $this->assertEquals('adminuser_id', $adminGroups['joinTable']['joinColumns'][0]['name']);
        $this->assertEquals('admingroup_id', $adminGroups['joinTable']['inverseJoinColumns'][0]['name']);

        $this->assertEquals(array('adminuser_id'=>'id'), $adminGroups['relationToSourceKeyColumns']);
        $this->assertEquals(array('admingroup_id'=>'id'), $adminGroups['relationToTargetKeyColumns']);
        $this->assertEquals(array('adminuser_id','admingroup_id'), $adminGroups['joinTableColumns']);

        // assert address association mappings
        $this->assertArrayHasKey('address', $guestMetadata->associationMappings);
        $this->assertArrayHasKey('address', $adminMetadata->associationMappings);

        $guestAddress = $guestMetadata->associationMappings['address'];
        $adminAddress = $adminMetadata->associationMappings['address'];

        // assert not override attributes
        $this->assertEquals($guestAddress['fieldName'], $adminAddress['fieldName']);
        $this->assertEquals($guestAddress['type'], $adminAddress['type']);
        $this->assertEquals($guestAddress['mappedBy'], $adminAddress['mappedBy']);
        $this->assertEquals($guestAddress['inversedBy'], $adminAddress['inversedBy']);
        $this->assertEquals($guestAddress['isOwningSide'], $adminAddress['isOwningSide']);
        $this->assertEquals($guestAddress['fetch'], $adminAddress['fetch']);
        $this->assertEquals($guestAddress['isCascadeRemove'], $adminAddress['isCascadeRemove']);
        $this->assertEquals($guestAddress['isCascadePersist'], $adminAddress['isCascadePersist']);
        $this->assertEquals($guestAddress['isCascadeRefresh'], $adminAddress['isCascadeRefresh']);
        $this->assertEquals($guestAddress['isCascadeMerge'], $adminAddress['isCascadeMerge']);
        $this->assertEquals($guestAddress['isCascadeDetach'], $adminAddress['isCascadeDetach']);

        // assert override
        $this->assertEquals('address_id', $guestAddress['joinColumns'][0]['name']);
        $this->assertEquals(array('address_id'=>'id'), $guestAddress['sourceToTargetKeyColumns']);
        $this->assertEquals(array('address_id'=>'address_id'), $guestAddress['joinColumnFieldNames']);
        $this->assertEquals(array('id'=>'address_id'), $guestAddress['targetToSourceKeyColumns']);

        $this->assertEquals('adminaddress_id', $adminAddress['joinColumns'][0]['name']);
        $this->assertEquals(array('adminaddress_id'=>'id'), $adminAddress['sourceToTargetKeyColumns']);
        $this->assertEquals(array('adminaddress_id'=>'adminaddress_id'), $adminAddress['joinColumnFieldNames']);
        $this->assertEquals(array('id'=>'adminaddress_id'), $adminAddress['targetToSourceKeyColumns']);
    }

    /**
     * @group DDC-964
     */
    public function testAttributeOverridesMapping()
    {

        $factory       = $this->createClassMetadataFactory();
        $guestMetadata = $factory->getMetadataFor('Doctrine\Tests\Models\DDC964\DDC964Guest');
        $adminMetadata = $factory->getMetadataFor('Doctrine\Tests\Models\DDC964\DDC964Admin');

        $this->assertTrue($adminMetadata->fieldMappings['id']['id']);
        $this->assertEquals('id', $adminMetadata->fieldMappings['id']['fieldName']);
        $this->assertEquals('user_id', $adminMetadata->fieldMappings['id']['columnName']);
        $this->assertEquals(array('user_id'=>'id','user_name'=>'name'), $adminMetadata->fieldNames);
        $this->assertEquals(array('id'=>'user_id','name'=>'user_name'), $adminMetadata->columnNames);
        $this->assertEquals(150, $adminMetadata->fieldMappings['id']['length']);

        $this->assertEquals('name', $adminMetadata->fieldMappings['name']['fieldName']);
        $this->assertEquals('user_name', $adminMetadata->fieldMappings['name']['columnName']);
        $this->assertEquals(250, $adminMetadata->fieldMappings['name']['length']);
        $this->assertTrue($adminMetadata->fieldMappings['name']['nullable']);
        $this->assertFalse($adminMetadata->fieldMappings['name']['unique']);

        $this->assertTrue($guestMetadata->fieldMappings['id']['id']);
        $this->assertEquals('guest_id', $guestMetadata->fieldMappings['id']['columnName']);
        $this->assertEquals('id', $guestMetadata->fieldMappings['id']['fieldName']);
        $this->assertEquals(array('guest_id'=>'id','guest_name'=>'name'), $guestMetadata->fieldNames);
        $this->assertEquals(array('id'=>'guest_id','name'=>'guest_name'), $guestMetadata->columnNames);
        $this->assertEquals(140, $guestMetadata->fieldMappings['id']['length']);

        $this->assertEquals('name', $guestMetadata->fieldMappings['name']['fieldName']);
        $this->assertEquals('guest_name', $guestMetadata->fieldMappings['name']['columnName']);
        $this->assertEquals(240, $guestMetadata->fieldMappings['name']['length']);
        $this->assertFalse($guestMetadata->fieldMappings['name']['nullable']);
        $this->assertTrue($guestMetadata->fieldMappings['name']['unique']);
    }

}

/**
 * @Entity
 * @HasLifecycleCallbacks
 * @Table(
 *  name="cms_users",
 *  uniqueConstraints={@UniqueConstraint(name="search_idx", columns={"name", "user_email"})},
 *  indexes={@Index(name="name_idx", columns={"name"}), @Index(name="0", columns={"user_email"})},
 *  options={"foo": "bar", "baz": {"key": "val"}}
 * )
 * @NamedQueries({@NamedQuery(name="all", query="SELECT u FROM __CLASS__ u")})
 */
class User
{
    /**
     * @Id
     * @Column(type="integer")
     * @generatedValue(strategy="AUTO")
     * @SequenceGenerator(sequenceName="tablename_seq", initialValue=1, allocationSize=100)
     **/
    public $id;

    /**
     * @Column(length=50, nullable=true, unique=true, options={"foo": "bar", "baz": {"key": "val"}})
     */
    public $name;

    /**
     * @Column(name="user_email", columnDefinition="CHAR(32) NOT NULL")
     */
    public $email;

    /**
     * @OneToOne(targetEntity="Address", cascade={"remove"}, inversedBy="user")
     * @JoinColumn(onDelete="CASCADE")
     */
    public $address;

    /**
     * @OneToMany(targetEntity="Phonenumber", mappedBy="user", cascade={"persist"}, orphanRemoval=true)
     * @OrderBy({"number"="ASC"})
     */
    public $phonenumbers;

    /**
     * @ManyToMany(targetEntity="Group", cascade={"all"})
     * @JoinTable(name="cms_user_groups",
     *    joinColumns={@JoinColumn(name="user_id", referencedColumnName="id", nullable=false, unique=false)},
     *    inverseJoinColumns={@JoinColumn(name="group_id", referencedColumnName="id", columnDefinition="INT NULL")}
     * )
     */
    public $groups;

    /**
     * @Column(type="integer")
     * @Version
     */
    public $version;

    /**
     * @PrePersist
     */
    public function doStuffOnPrePersist()
    {
    }

    /**
     * @PrePersist
     */
    public function doOtherStuffOnPrePersistToo() {
    }

    /**
     * @PostPersist
     */
    public function doStuffOnPostPersist()
    {

    }

    public static function loadMetadata(ClassMetadataInfo $metadata)
    {
        $metadata->setInheritanceType(ClassMetadataInfo::INHERITANCE_TYPE_NONE);
        $metadata->setPrimaryTable(array(
           'name' => 'cms_users',
           'options' => array('foo' => 'bar', 'baz' => array('key' => 'val')),
          ));
        $metadata->setChangeTrackingPolicy(ClassMetadataInfo::CHANGETRACKING_DEFERRED_IMPLICIT);
        $metadata->addLifecycleCallback('doStuffOnPrePersist', 'prePersist');
        $metadata->addLifecycleCallback('doOtherStuffOnPrePersistToo', 'prePersist');
        $metadata->addLifecycleCallback('doStuffOnPostPersist', 'postPersist');
        $metadata->mapField(array(
           'id' => true,
           'fieldName' => 'id',
           'type' => 'integer',
           'columnName' => 'id',
          ));
        $metadata->mapField(array(
           'fieldName' => 'name',
           'type' => 'string',
           'length' => 50,
           'unique' => true,
           'nullable' => true,
           'columnName' => 'name',
           'options' => array('foo' => 'bar', 'baz' => array('key' => 'val')),
          ));
        $metadata->mapField(array(
           'fieldName' => 'email',
           'type' => 'string',
           'columnName' => 'user_email',
           'columnDefinition' => 'CHAR(32) NOT NULL',
          ));
        $mapping = array('fieldName' => 'version', 'type' => 'integer');
        $metadata->setVersionMapping($mapping);
        $metadata->mapField($mapping);
        $metadata->setIdGeneratorType(ClassMetadataInfo::GENERATOR_TYPE_AUTO);
        $metadata->mapOneToOne(array(
           'fieldName' => 'address',
           'targetEntity' => 'Doctrine\\Tests\\ORM\\Mapping\\Address',
           'cascade' =>
           array(
           0 => 'remove',
           ),
           'mappedBy' => NULL,
           'inversedBy' => 'user',
           'joinColumns' =>
           array(
           0 =>
           array(
            'name' => 'address_id',
            'referencedColumnName' => 'id',
            'onDelete' => 'CASCADE',
           ),
           ),
           'orphanRemoval' => false,
          ));
        $metadata->mapOneToMany(array(
           'fieldName' => 'phonenumbers',
           'targetEntity' => 'Doctrine\\Tests\\ORM\\Mapping\\Phonenumber',
           'cascade' =>
           array(
           1 => 'persist',
           ),
           'mappedBy' => 'user',
           'orphanRemoval' => true,
           'orderBy' =>
           array(
           'number' => 'ASC',
           ),
          ));
        $metadata->mapManyToMany(array(
           'fieldName' => 'groups',
           'targetEntity' => 'Doctrine\\Tests\\ORM\\Mapping\\Group',
           'cascade' =>
           array(
           0 => 'remove',
           1 => 'persist',
           2 => 'refresh',
           3 => 'merge',
           4 => 'detach',
           ),
           'mappedBy' => NULL,
           'joinTable' =>
           array(
           'name' => 'cms_users_groups',
           'joinColumns' =>
           array(
            0 =>
            array(
            'name' => 'user_id',
            'referencedColumnName' => 'id',
            'unique' => false,
            'nullable' => false,
            ),
           ),
           'inverseJoinColumns' =>
           array(
            0 =>
            array(
            'name' => 'group_id',
            'referencedColumnName' => 'id',
            'columnDefinition' => 'INT NULL',
            ),
           ),
           ),
           'orderBy' => NULL,
          ));
        $metadata->table['uniqueConstraints'] = array(
            'search_idx' => array('columns' => array('name', 'user_email')),
        );
        $metadata->table['indexes'] = array(
            'name_idx' => array('columns' => array('name')), 0 => array('columns' => array('user_email'))
        );
        $metadata->setSequenceGeneratorDefinition(array(
                'sequenceName' => 'tablename_seq',
                'allocationSize' => 100,
                'initialValue' => 1,
            ));
        $metadata->addNamedQuery(array(
                'name' => 'all',
                'query' => 'SELECT u FROM __CLASS__ u'
            ));
    }
}

/**
 * @Entity
 * @InheritanceType("SINGLE_TABLE")
 * @DiscriminatorMap({"cat" = "Cat", "dog" = "Dog"})
 * @DiscriminatorColumn(name="discr", length=32, type="string")
 */
abstract class Animal
{
    /**
     * @Id @Column(type="string") @GeneratedValue(strategy="CUSTOM")
     * @CustomIdGenerator(class="stdClass")
     */
    public $id;

    public static function loadMetadata(ClassMetadataInfo $metadata)
    {
        $metadata->setIdGeneratorType(ClassMetadataInfo::GENERATOR_TYPE_CUSTOM);
        $metadata->setCustomGeneratorDefinition(array("class" => "stdClass"));
    }
}

/** @Entity */
class Cat extends Animal
{
    public static function loadMetadata(ClassMetadataInfo $metadata)
    {

    }
}

/** @Entity */
class Dog extends Animal
{
    public static function loadMetadata(ClassMetadataInfo $metadata)
    {

    }
}

/**
 * @Entity
 */
class DDC1170Entity
{

    /**
     * @param string $value
     */
    function __construct($value = null)
    {
        $this->value = $value;
    }

    /**
     * @Id
     * @GeneratedValue(strategy="NONE")
     * @Column(type="integer", columnDefinition = "INT unsigned NOT NULL")
     **/
    private $id;

    /**
     * @Column(columnDefinition = "VARCHAR(255) NOT NULL")
     */
    private $value;

    /**
     * @return integer
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * @return string
     */
    public function getValue()
    {
        return $this->value;
    }

    public static function loadMetadata(ClassMetadataInfo $metadata)
    {
        $metadata->mapField(array(
           'id'                 => true,
           'fieldName'          => 'id',
           'columnDefinition'   => 'INT unsigned NOT NULL',
        ));

        $metadata->mapField(array(
            'fieldName'         => 'value',
            'columnDefinition'  => 'VARCHAR(255) NOT NULL'
        ));

        $metadata->setIdGeneratorType(ClassMetadataInfo::GENERATOR_TYPE_NONE);
    }

}

/**
 * @Entity
 * @InheritanceType("SINGLE_TABLE")
 * @DiscriminatorMap({"ONE" = "DDC807SubClasse1", "TWO" = "DDC807SubClasse2"})
 * @DiscriminatorColumn(name = "dtype", columnDefinition="ENUM('ONE','TWO')")
 */
class DDC807Entity
{
    /**
     * @Id
     * @Column(type="integer")
     * @GeneratedValue(strategy="NONE")
     **/
   public $id;

   public static function loadMetadata(ClassMetadataInfo $metadata)
    {
         $metadata->mapField(array(
           'id'                 => true,
           'fieldName'          => 'id',
        ));

        $metadata->setDiscriminatorColumn(array(
            'name'              => "dtype",
            'type'              => "string",
            'columnDefinition'  => "ENUM('ONE','TWO')"
        ));

        $metadata->setIdGeneratorType(ClassMetadataInfo::GENERATOR_TYPE_NONE);
    }
}

class DDC807SubClasse1 {}
class DDC807SubClasse2 {}

class Address {}
class Phonenumber {}
class Group {}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Mycotaxon 77: 332 (2001)

#### Original name
Taeniolella caespitosa M.S. Cole & D. Hawksw.

### Remarks
null


text:
module Quark
require "quark"
def self.implicit_self; ImplicitSelf; end
module ImplicitSelf
require 'quark' # .../reflect
require_relative 'implicit_self_md' # 0 () ()

def self.Foo; Foo; end
class Foo < ::DatawireQuarkCore::QuarkObject
    extend ::DatawireQuarkCore::Static

    static implicit_self_Foo_ref: -> { ::Quark.implicit_self_md.Root.implicit_self_Foo_md }

    def initialize()
        self.__init_fields__

        nil
    end

    def next_()

        nil

        nil
    end

    def test()

        self.next_()

        nil
    end

    def _getClass()

        return "implicit_self.Foo"

        nil
    end

    def _getField(name)

        return nil

        nil
    end

    def _setField(name, value)

        nil

        nil
    end

    def __init_fields__()

        nil
    end

end
Foo.unlazy_statics
end # module ImplicitSelf
end # module Quark


text:
using System;
using System.Collections;
using System.IO;
using System.Reflection;

using Reporting.Rdl;

namespace Reporting.Rdl
{
	/// <summary>
	/// Unary minus operator with a decimal operand
	/// </summary>
	[Serializable]
	internal class FunctionUnaryMinusDecimal : IExpr
	{
		IExpr _rhs;			// rhs

		/// <summary>
		/// Do minus on decimal data type
		/// </summary>
		public FunctionUnaryMinusDecimal()
		{
			_rhs = null;
		}

		public FunctionUnaryMinusDecimal(IExpr r)
		{
			_rhs = r;
		}

		public TypeCode GetTypeCode()
		{
			return TypeCode.Decimal;
		}

		public bool IsConstant()
		{
			return _rhs.IsConstant();
		}

		public IExpr ConstantOptimization()
		{
			_rhs = _rhs.ConstantOptimization();
			if (_rhs.IsConstant())
			{
				decimal d = EvaluateDecimal(null, null);
				return new Constant<decimal>(d);
			}

			return this;
		}

		// Evaluate is for interpretation  (and is relatively slow)
		public object Evaluate(Report rpt, Row row)
		{
			return EvaluateDecimal(rpt, row);
		}

		public double EvaluateDouble(Report rpt, Row row)
		{
			decimal result = EvaluateDecimal(rpt, row);

			return Convert.ToDouble(result);
		}

        public int EvaluateInt32(Report rpt, Row row)
        {
            decimal result = EvaluateDecimal(rpt, row);

            return Convert.ToInt32(result);
        }

		public decimal EvaluateDecimal(Report rpt, Row row)
		{
			decimal rhs = _rhs.EvaluateDecimal(rpt, row);

			return (decimal) (-rhs);
		}

		public string EvaluateString(Report rpt, Row row)
		{
			decimal result = EvaluateDecimal(rpt, row);
			return result.ToString();
		}

		public DateTime EvaluateDateTime(Report rpt, Row row)
		{
			decimal result = EvaluateDecimal(rpt, row);
			return Convert.ToDateTime(result);
		}

		public bool EvaluateBoolean(Report rpt, Row row)
		{
			return false;
		}

		public IExpr Rhs
		{
			get { return  _rhs; }
			set {  _rhs = value; }
		}

	}
}


text:
@extends('core::admin.master')

@section('title', trans('coupons::global.New'))

@section('main')

    @include('core::admin._button-back', ['module' => 'coupons'])
    <h1>
        @lang('coupons::global.New')
    </h1>

    {!! BootForm::open()->action(route('admin::index-coupons'))->multipart()->role('form') !!}
        @include('coupons::admin._form')
    {!! BootForm::close() !!}

@endsection


text:
package fr.paris.lutece.util.jpa;

import javax.persistence.EntityManagerFactory;

final class TestJPAGenericDAO extends JPAGenericDAO<Integer, Integer>
{
    @Override
    public EntityManagerFactory getEntityManagerFactory( )
    {
        return new TestEntityManagerFactory( );
    }
}


text:
package io.cdep.cdep.generator;

import io.cdep.annotations.NotNull;
import io.cdep.cdep.RewritingVisitor;
import io.cdep.cdep.ast.finder.*;
import io.cdep.cdep.yml.cdepmanifest.CxxLanguageFeatures;

import java.util.ArrayList;
import java.util.List;

import static io.cdep.cdep.ast.finder.ExpressionBuilder.*;

/**
 * Expand module requires into logic for setting the compiler standard that should be used.
 */
public class CxxLanguageStandardRewritingVisitor extends RewritingVisitor {

  @Override
  protected Expression visitGlobalBuildEnvironmentExpression(GlobalBuildEnvironmentExpression expr) {
    return super.visitGlobalBuildEnvironmentExpression(expr);
  }

  @Override
  protected Expression visitModuleExpression(@NotNull ModuleExpression expr) {
    ModuleArchiveExpression archive = expr.archive;
    CxxLanguageFeatures requires[] = archive.requires;
    if (requires.length == 0) {
      return super.visitModuleExpression(expr);
    }

    // Get rid of requires in ModuleArchiveExpression
    archive = new ModuleArchiveExpression(archive.file,
        archive.sha256,
        archive.size,
        archive.include,
        archive.includePath,
        archive.libs,
        archive.libraryPaths,
        new CxxLanguageFeatures[0]);

    // Make constant expression of requires
    List<ConstantExpression> features = new ArrayList<>();
    for (CxxLanguageFeatures require : requires) {
      features.add(constant(require));
    }

    // Find the minimum language standard to support all the requirements
    int minimumLanguageStandard = 0;
    for (CxxLanguageFeatures require : requires) {
      minimumLanguageStandard = Math.max(
          minimumLanguageStandard,
          require.standard);
    }

    List<StatementExpression> exprs = new ArrayList<>();
    exprs.add(
        ifSwitch(
            // If build system (CMake or ndk-build) supports compiler feature requirements
            supportsCompilerFeatures(),
            // The build system supports compiler features so request the features from the manifest
            requiresCompilerFeatures(array(features.toArray(new ConstantExpression[requires.length]))),
            // Otherwise, require the lowest compiler standard that supports the listed features
            requireMinimumCxxCompilerStandard(constant(minimumLanguageStandard))));
    exprs.add(archive);

    return new MultiStatementExpression(exprs.toArray(new StatementExpression[exprs.size()]));
  }
}


text:
package org.apache.activemq.artemis.core.management.impl;

import javax.management.MBeanAttributeInfo;
import javax.management.MBeanInfo;
import javax.management.MBeanOperationInfo;
import javax.management.NotCompliantMBeanException;
import javax.management.StandardMBean;

import org.apache.activemq.artemis.core.persistence.StorageManager;

public abstract class AbstractControl extends StandardMBean {

   // Constants -----------------------------------------------------

   // Attributes ----------------------------------------------------

   protected final StorageManager storageManager;

   // Static --------------------------------------------------------

   // Constructors --------------------------------------------------

   public AbstractControl(final Class<?> clazz, final StorageManager storageManager) throws NotCompliantMBeanException {
      super(clazz);
      this.storageManager = storageManager;
   }

   // Public --------------------------------------------------------

   // Package protected ---------------------------------------------

   // Protected -----------------------------------------------------

   protected void clearIO() {
      // the storage manager could be null on the backup on certain components
      if (storageManager != null) {
         storageManager.clearContext();
      }
   }

   protected void blockOnIO() {
      // the storage manager could be null on the backup on certain components
      if (storageManager != null) {
         try {
            storageManager.waitOnOperations();
            storageManager.clearContext();
         } catch (Exception e) {
            throw new RuntimeException(e.getMessage(), e);
         }
      }

   }

   protected abstract MBeanOperationInfo[] fillMBeanOperationInfo();

   protected abstract MBeanAttributeInfo[] fillMBeanAttributeInfo();

   @Override
   public MBeanInfo getMBeanInfo() {
      MBeanInfo info = super.getMBeanInfo();
      return new MBeanInfo(info.getClassName(), info.getDescription(), fillMBeanAttributeInfo(), info.getConstructors(), fillMBeanOperationInfo(), info.getNotifications());
   }

   // Private -------------------------------------------------------

   // Inner classes -------------------------------------------------

}


text:
<!DOCTYPE html>

  <meta charset="UTF-8">
  <title>Markdown Previewer</title>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel='stylesheet prefetch' href='https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css'>
  <link rel="stylesheet" href="css/style.css">


text:
package org.elasticsearch.xpack.core.transform.transforms;

import org.elasticsearch.Version;
import org.elasticsearch.common.Strings;
import org.elasticsearch.common.io.stream.Writeable.Reader;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.common.xcontent.DeprecationHandler;
import org.elasticsearch.common.xcontent.ToXContent;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentFactory;
import org.elasticsearch.common.xcontent.XContentParser;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.xpack.core.transform.transforms.pivot.PivotConfigTests;
import org.junit.Before;

import java.io.IOException;
import java.time.Instant;
import java.util.HashMap;
import java.util.Map;

import static org.elasticsearch.test.TestMatchers.matchesPattern;
import static org.elasticsearch.xpack.core.transform.transforms.DestConfigTests.randomDestConfig;
import static org.elasticsearch.xpack.core.transform.transforms.SourceConfigTests.randomInvalidSourceConfig;
import static org.elasticsearch.xpack.core.transform.transforms.SourceConfigTests.randomSourceConfig;
import static org.hamcrest.Matchers.equalTo;

public class TransformConfigTests extends AbstractSerializingTransformTestCase<TransformConfig> {

    private String transformId;
    private boolean runWithHeaders;

    public static TransformConfig randomDataFrameTransformConfigWithoutHeaders() {
        return randomDataFrameTransformConfigWithoutHeaders(randomAlphaOfLengthBetween(1, 10));
    }

    public static TransformConfig randomTransformConfig() {
        return randomTransformConfig(randomAlphaOfLengthBetween(1, 10));
    }

    public static TransformConfig randomDataFrameTransformConfigWithoutHeaders(String id) {
        return new TransformConfig(id,
            randomSourceConfig(),
            randomDestConfig(),
            randomBoolean() ? null : TimeValue.timeValueMillis(randomIntBetween(1_000, 3_600_000)),
            randomBoolean() ? null : randomSyncConfig(),
            null,
            PivotConfigTests.randomPivotConfig(),
            randomBoolean() ? null : randomAlphaOfLengthBetween(1, 1000),
            null,
            null);
    }

    public static TransformConfig randomTransformConfig(String id) {
        return new TransformConfig(id,
            randomSourceConfig(),
            randomDestConfig(),
            randomBoolean() ? null : TimeValue.timeValueMillis(randomIntBetween(1_000, 3_600_000)),
            randomBoolean() ? null : randomSyncConfig(),
            randomHeaders(),
            PivotConfigTests.randomPivotConfig(),
            randomBoolean() ? null : randomAlphaOfLengthBetween(1, 1000),
            randomBoolean() ? null : Instant.now(),
            randomBoolean() ? null : Version.CURRENT.toString());
    }

    public static TransformConfig randomInvalidDataFrameTransformConfig() {
        if (randomBoolean()) {
            return new TransformConfig(randomAlphaOfLengthBetween(1, 10), randomInvalidSourceConfig(), randomDestConfig(),
                    null, randomBoolean() ? randomSyncConfig() : null, randomHeaders(), PivotConfigTests.randomPivotConfig(),
                    randomBoolean() ? null : randomAlphaOfLengthBetween(1, 1000));
        } // else
        return new TransformConfig(randomAlphaOfLengthBetween(1, 10), randomSourceConfig(), randomDestConfig(),
                null, randomBoolean() ? randomSyncConfig() : null, randomHeaders(), PivotConfigTests.randomInvalidPivotConfig(),
                randomBoolean() ? null : randomAlphaOfLengthBetween(1, 1000));
    }

    public static SyncConfig randomSyncConfig() {
        return TimeSyncConfigTests.randomTimeSyncConfig();
    }

    @Before
    public void setUpOptionalId() {
        transformId = randomAlphaOfLengthBetween(1, 10);
        runWithHeaders = randomBoolean();
    }

    @Override
    protected TransformConfig doParseInstance(XContentParser parser) throws IOException {
        if (randomBoolean()) {
            return TransformConfig.fromXContent(parser, transformId, runWithHeaders);
        } else {
            return TransformConfig.fromXContent(parser, null, runWithHeaders);
        }
    }

    @Override
    protected TransformConfig createTestInstance() {
        return runWithHeaders ? randomTransformConfig(transformId) : randomDataFrameTransformConfigWithoutHeaders(transformId);
    }

    @Override
    protected Reader<TransformConfig> instanceReader() {
        return TransformConfig::new;
    }

    @Override
    protected ToXContent.Params getToXContentParams() {
        return TO_XCONTENT_PARAMS;
    }

    private static Map<String, String> randomHeaders() {
        Map<String, String> headers = new HashMap<>(1);
        headers.put("key", "value");

        return headers;
    }

    public void testDefaultMatchAll() throws IOException {
        String pivotTransform = "{"
                + " \"source\" : {\"index\":\"src\"},"
                + " \"dest\" : {\"index\": \"dest\"},"
                + " \"pivot\" : {"
                + " \"group_by\": {"
                + "   \"id\": {"
                + "     \"terms\": {"
                + "       \"field\": \"id\""
                + "} } },"
                + " \"aggs\": {"
                + "   \"avg\": {"
                + "     \"avg\": {"
                + "       \"field\": \"points\""
                + "} } } } }";

        TransformConfig dataFrameTransformConfig = createDataFrameTransformConfigFromString(pivotTransform, "test_match_all");
        assertNotNull(dataFrameTransformConfig.getSource().getQueryConfig());
        assertTrue(dataFrameTransformConfig.getSource().getQueryConfig().isValid());

        try (XContentBuilder xContentBuilder = XContentFactory.jsonBuilder()) {
            XContentBuilder content = dataFrameTransformConfig.toXContent(xContentBuilder, ToXContent.EMPTY_PARAMS);
            String pivotTransformWithIdAndDefaults = Strings.toString(content);

            assertThat(pivotTransformWithIdAndDefaults, matchesPattern(".*\"match_all\"\\s*:\\s*\\{\\}.*"));
        }
    }

    public void testPreventHeaderInjection() {
        String pivotTransform = "{"
                + " \"headers\" : {\"key\" : \"value\" },"
                + " \"source\" : {\"index\":\"src\"},"
                + " \"dest\" : {\"index\": \"dest\"},"
                + " \"pivot\" : {"
                + " \"group_by\": {"
                + "   \"id\": {"
                + "     \"terms\": {"
                + "       \"field\": \"id\""
                + "} } },"
                + " \"aggs\": {"
                + "   \"avg\": {"
                + "     \"avg\": {"
                + "       \"field\": \"points\""
                + "} } } } }";

        expectThrows(IllegalArgumentException.class,
                () -> createDataFrameTransformConfigFromString(pivotTransform, "test_header_injection"));
    }

    public void testPreventCreateTimeInjection() {
        String pivotTransform = "{"
            + " \"create_time\" : " + Instant.now().toEpochMilli() + " },"
            + " \"source\" : {\"index\":\"src\"},"
            + " \"dest\" : {\"index\": \"dest\"},"
            + " \"pivot\" : {"
            + " \"group_by\": {"
            + "   \"id\": {"
            + "     \"terms\": {"
            + "       \"field\": \"id\""
            + "} } },"
            + " \"aggs\": {"
            + "   \"avg\": {"
            + "     \"avg\": {"
            + "       \"field\": \"points\""
            + "} } } } }";

        expectThrows(IllegalArgumentException.class,
            () -> createDataFrameTransformConfigFromString(pivotTransform, "test_createTime_injection"));
    }

    public void testPreventVersionInjection() {
        String pivotTransform = "{"
            + " \"version\" : \"7.3.0\","
            + " \"source\" : {\"index\":\"src\"},"
            + " \"dest\" : {\"index\": \"dest\"},"
            + " \"pivot\" : {"
            + " \"group_by\": {"
            + "   \"id\": {"
            + "     \"terms\": {"
            + "       \"field\": \"id\""
            + "} } },"
            + " \"aggs\": {"
            + "   \"avg\": {"
            + "     \"avg\": {"
            + "       \"field\": \"points\""
            + "} } } } }";

        expectThrows(IllegalArgumentException.class,
            () -> createDataFrameTransformConfigFromString(pivotTransform, "test_createTime_injection"));
    }

    public void testXContentForInternalStorage() throws IOException {
        TransformConfig dataFrameTransformConfig = randomTransformConfig();

        try (XContentBuilder xContentBuilder = XContentFactory.jsonBuilder()) {
            XContentBuilder content = dataFrameTransformConfig.toXContent(xContentBuilder, getToXContentParams());
            String doc = Strings.toString(content);

            assertThat(doc, matchesPattern(".*\"doc_type\"\\s*:\\s*\"data_frame_transform_config\".*"));
        }

        try (XContentBuilder xContentBuilder = XContentFactory.jsonBuilder()) {
            XContentBuilder content = dataFrameTransformConfig.toXContent(xContentBuilder, ToXContent.EMPTY_PARAMS);
            String doc = Strings.toString(content);

            assertFalse(doc.contains("doc_type"));
        }
    }

    public void testMaxLengthDescription() {
        IllegalArgumentException exception = expectThrows(IllegalArgumentException.class, () -> new TransformConfig("id",
            randomSourceConfig(), randomDestConfig(), null, null, null, PivotConfigTests.randomPivotConfig(), randomAlphaOfLength(1001)));
        assertThat(exception.getMessage(), equalTo("[description] must be less than 1000 characters in length."));
        String description = randomAlphaOfLength(1000);
        TransformConfig config = new TransformConfig("id",
            randomSourceConfig(), randomDestConfig(), null, null, null, PivotConfigTests.randomPivotConfig(), description);
        assertThat(description, equalTo(config.getDescription()));
    }

    public void testSetIdInBody() throws IOException {
        String pivotTransform = "{"
                + " \"id\" : \"body_id\","
                + " \"source\" : {\"index\":\"src\"},"
                + " \"dest\" : {\"index\": \"dest\"},"
                + " \"pivot\" : {"
                + " \"group_by\": {"
                + "   \"id\": {"
                + "     \"terms\": {"
                + "       \"field\": \"id\""
                + "} } },"
                + " \"aggs\": {"
                + "   \"avg\": {"
                + "     \"avg\": {"
                + "       \"field\": \"points\""
                + "} } } } }";

        TransformConfig dataFrameTransformConfig = createDataFrameTransformConfigFromString(pivotTransform, "body_id");
        assertEquals("body_id", dataFrameTransformConfig.getId());

        IllegalArgumentException ex = expectThrows(IllegalArgumentException.class,
                () -> createDataFrameTransformConfigFromString(pivotTransform, "other_id"));

        assertEquals("Inconsistent id; 'body_id' specified in the body differs from 'other_id' specified as a URL argument",
                ex.getCause().getMessage());
    }

    private TransformConfig createDataFrameTransformConfigFromString(String json, String id) throws IOException {
        final XContentParser parser = XContentType.JSON.xContent().createParser(xContentRegistry(),
                DeprecationHandler.THROW_UNSUPPORTED_OPERATION, json);
        return TransformConfig.fromXContent(parser, id, false);
    }
}


text:
package org.jboss.pnc.rest.restmodel;

import java.util.Date;

import org.jboss.pnc.model.BuildConfigurationAudited;

import javax.xml.bind.annotation.XmlRootElement;

import static org.jboss.pnc.rest.utils.Utility.performIfNotNull;

@XmlRootElement(name = "BuildConfigurationAudited")
public class BuildConfigurationAuditedRest {

    private Integer id;

    private Integer rev;

    private String name;

    private String description;

    private String buildScript;

    private String scmRepoURL;

    private String scmRevision;

    private Date creationTime;

    private Date lastModificationTime;

    private String repositories;

    private Integer projectId;

    private Integer environmentId;

    public BuildConfigurationAuditedRest() {
    }

    public BuildConfigurationAuditedRest(BuildConfigurationAudited buildConfigurationAudited) {
        this.id = buildConfigurationAudited.getId().getId();
        this.rev = buildConfigurationAudited.getRev();
        this.name = buildConfigurationAudited.getName();
        this.description = buildConfigurationAudited.getDescription();
        this.buildScript = buildConfigurationAudited.getBuildScript();
        this.scmRepoURL = buildConfigurationAudited.getScmRepoURL();
        this.scmRevision = buildConfigurationAudited.getScmRevision();
        performIfNotNull(buildConfigurationAudited.getProject() != null, () -> this.projectId = buildConfigurationAudited.getProject()
                .getId());
        performIfNotNull(buildConfigurationAudited.getEnvironment() != null, () -> this.environmentId = buildConfigurationAudited.getEnvironment().getId());
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public Integer getRev() {
        return rev;
    }

    public void setRev(Integer rev) {
        this.rev = rev;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public String getBuildScript() {
        return buildScript;
    }

    public void setBuildScript(String buildScript) {
        this.buildScript = buildScript;
    }

    public String getScmRepoURL() {
        return scmRepoURL;
    }

    public void setScmRepoURL(String scmRepoURL) {
        this.scmRepoURL = scmRepoURL;
    }

    public String getScmRevision() {
        return scmRevision;
    }

    public void setScmRevision(String scmRevision) {
        this.scmRevision = scmRevision;
    }

    public Date getCreationTime() {
        return creationTime;
    }

    public void setCreationTime(Date creationTime) {
        this.creationTime = creationTime;
    }

    public Date getLastModificationTime() {
        return lastModificationTime;
    }

    public void setLastModificationTime(Date lastModificationTime) {
        this.lastModificationTime = lastModificationTime;
    }

    public String getRepositories() {
        return repositories;
    }

    public void setRepositories(String repositories) {
        this.repositories = repositories;
    }

    public Integer getProjectId() {
        return projectId;
    }

    public void setProjectId(Integer projectId) {
        this.projectId = projectId;
    }

    public Integer getEnvironmentId() {
        return environmentId;
    }

    public void setEnvironmentId(Integer environmentId) {
        this.environmentId = environmentId;
    }

}


text:
import {
  it,
  describe,
  expect,
  beforeEach,
  inject,
  fakeAsync,
  flushMicrotasks,
} from '@angular/core/testing';
import {GlobalPositionStrategy} from './global-position-strategy';

export function main() {
  describe('GlobalPositonStrategy', () => {
    let element: HTMLElement;
    let strategy: GlobalPositionStrategy;

    beforeEach(() => {
      element = document.createElement('div');
      strategy = new GlobalPositionStrategy();
    });

    it('should set explicit (top, left) position to the element', fakeAsyncTest(() => {
      strategy.top('10px').left('40%').apply(element);

      flushMicrotasks();

      expect(element.style.top).toBe('10px');
      expect(element.style.left).toBe('40%');
      expect(element.style.bottom).toBe('');
      expect(element.style.right).toBe('');
    }));

    it('should set explicit (bottom, right) position to the element', fakeAsyncTest(() => {
      strategy.bottom('70px').right('15em').apply(element);

      flushMicrotasks();

      expect(element.style.top).toBe('');
      expect(element.style.left).toBe('');
      expect(element.style.bottom).toBe('70px');
      expect(element.style.right).toBe('15em');
    }));

    it('should overwrite previously applied positioning', fakeAsyncTest(() => {
      strategy.centerHorizontally().centerVertically().apply(element);
      flushMicrotasks();

      strategy.top('10px').left('40%').apply(element);
      flushMicrotasks();

      expect(element.style.top).toBe('10px');
      expect(element.style.left).toBe('40%');
      expect(element.style.bottom).toBe('');
      expect(element.style.right).toBe('');
      expect(element.style.transform).not.toContain('translate');

      strategy.bottom('70px').right('15em').apply(element);

      flushMicrotasks();

      expect(element.style.top).toBe('');
      expect(element.style.left).toBe('');
      expect(element.style.bottom).toBe('70px');
      expect(element.style.right).toBe('15em');
      expect(element.style.transform).not.toContain('translate');
    }));

    it('should center the element', fakeAsyncTest(() => {
      strategy.centerHorizontally().centerVertically().apply(element);

      flushMicrotasks();

      expect(element.style.top).toBe('50%');
      expect(element.style.left).toBe('50%');
      expect(element.style.transform).toContain('translateX(-50%)');
      expect(element.style.transform).toContain('translateY(-50%)');
    }));

    it('should center the element with an offset', fakeAsyncTest(() => {
      strategy.centerHorizontally('10px').centerVertically('15px').apply(element);

      flushMicrotasks();

      expect(element.style.top).toBe('50%');
      expect(element.style.left).toBe('50%');
      expect(element.style.transform).toContain('translateX(-50%)');
      expect(element.style.transform).toContain('translateX(10px)');
      expect(element.style.transform).toContain('translateY(-50%)');
      expect(element.style.transform).toContain('translateY(15px)');
    }));

    it('should default the element to position: absolute', fakeAsyncTest(() => {
      strategy.apply(element);

      flushMicrotasks();

      expect(element.style.position).toBe('absolute');
    }));

    it('should make the element position: fixed', fakeAsyncTest(() => {
      strategy.fixed().apply(element);

      flushMicrotasks();

      expect(element.style.position).toBe('fixed');
    }));
  });
}

function fakeAsyncTest(fn: () => void) {
  return inject([], fakeAsync(fn));
}


text:
package com.spotify.heroic.statistics;

/*
 * Keep track of amount of expected in-memory data. One instance of this class per operation (i.e.
 * a query).
 */
public interface DataInMemoryReporter {
    /**
     * report that rows in metric backend has been accessed
     *
     * @param n amount of rows
     */
    void reportRowsAccessed(long n);

    /**
     * report the density of a row that was read from the metric backend
     *
     * @param samplesPerSecond density, average number of samples per second
     */
    void reportRowDensity(double samplesPerSecond);

    /**
     * report that data has been read into memory
     *
     * @param n amount of data
     */
    void reportDataHasBeenRead(long n);

    /**
     * report that data is no longer needed in memory
     * <p>
     * The data in question is expected to be garbage collected. If it isn't, then something else is
     * unexpectantly having a reference to it, which could indicate a problem/bug.
     *
     * @param n amount of data
     */
    void reportDataNoLongerNeeded(long n);

    /**
     * report that the whole operation is done, meaning that all data referenced in this
     * DataInMemory instance is expected to be garbage collected.
     */
    void reportOperationEnded();
}


text:
Workflow finished

  Workflow variables:
<?php var_dump($variables); ?>

  <?php echo link_to('Go to demonstration index','sfEzcWorkflowDemo/index') ?>


text:
package org.apache.metron.rest.service;

import org.apache.metron.rest.model.AlertProfile;

public interface AlertsProfileService {

  AlertProfile get();

  Iterable<AlertProfile> findAll();

  AlertProfile save(AlertProfile alertsProfile);

  boolean delete(String user);
}


text:
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE html
     PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
     "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

  <title>Module: Algorithms::Rank::Elo</title>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  <meta http-equiv="Content-Script-Type" content="text/javascript" />
  <link rel="stylesheet" href="../../.././rdoc-style.css" type="text/css" media="screen" />

          Module
          Algorithms::Rank::Elo

            In:

                lib/algorithms/rank/elo.rb

Methods

      adjust_elo
      expected_score
      k_value
      score

Constants

          START_RATING
          =
          1400

          K_VALUE
          =
          32

          DRAW_SCORE
          =
          0.5

          LOSS_SCORE
          =
          0

          WIN_SCORE
          =
          1

Public Instance methods

          adjust_elo(score, r_A, r_B)

This value is added to the previous Elo score to obtain the current score.

Return

Integer which is the amount by which to adjust the Elo score

Parameters

score<int>:	The adjustment value for a win, loss, or draw.

r_A<int>:	The Elo score of the
item whose score to be adjusted.

r_B<int>:	The Elo score of the
item whhose score is not being adjusted.

[Source]

    # File lib/algorithms/rank/elo.rb, line 75
75:   def adjust_elo(score, r_A, r_B)
76:     k_value(r_A) * (score - expected_score(r_A, r_B))
77:   end

          expected_score(r_A, r_B)

The score if A plays B.

Return

Integer of the expected score.

Parameters

r_A<int>:	The Elo score of item
A.

r_B<int>:	The Elo score of item
B.

[Source]

    # File lib/algorithms/rank/elo.rb, line 85
85:   def expected_score(r_A, r_B)
86:     1 / (1 + 10**((r_B - r_A) / 400.0))
87:   end

          k_value(r_A)

Calculate the K value for an item based on if an adjusted algorithm is
being used and the score of the item

Return

The K value for an item.

Parameters

r_A<int>:	The score of the item whose K value is to be
generated.

[Source]

     # File lib/algorithms/rank/elo.rb, line 95
 95:   def k_value(r_A)
 96:     if !@adj || r_A < 2100
 97:       K_VALUE
 98:     elsif r_A > 2400
 99:       16
100:     else
101:       24
102:     end
103:   end

          score(user_id, order, question_id, limit, adj=true)

Calculate Elo score
for all items given a user and question.

Return

Array of item IDs, followed by an array of Elo
scores matching to the item with the same array index.

Parameters

user_id<int>:	Get Elo scores for user with this ID.

order<string>:	If ‘asc’ return Elo scores in ascending
order, otherwise

return Elo scores in descending order.

question_id<int>:	Get Elo scores for items in this question.

limit<int>:	Truncate scores returned to this number of items.

adj<bool>:	Use an adjusted Elo algorithm. Default true.

[Source]

    # File lib/algorithms/rank/elo.rb, line 19
19:   def score(user_id, order, question_id, limit, adj=true)
20:     joins = "INNER JOIN users ON items.user_id=#{user_id}"
21:     joins += " INNER JOIN items_questions ON (items_questions.question_id=#{question_id} AND items_questions.item_id=items.id)" if question_id.to_i > 0
22:     conditions = {
23:       :joins => joins,
24:       :group => 'items.id'
25:     }
26:     items = Item.find(:all, conditions)
27:
28:     conditions = {
29:       :conditions => { :active => false },
30:       :order => 'prompts.created_at',
31:       :include => [:items, :votes],
32:       :group => 'prompts.id'
33:     }
34:     conditions[:conditions].merge!(:question_id => question_id) if question_id > 0
35:     prompts = Prompt.all(conditions)
36:
37:     elo = {}
38:     items.each { |item| elo[item] = START_RATING }
39:     @adj = adj
40:     prompts.each do |prompt|
41:       prompt.votes.each do |vote|
42:         # elo values static during update
43:         old_elo = elo.clone
44:         # if vote has items it has winner(s)
45:         unless vote.items.empty?
46:           vote.items.each do |item|
47:             lost_items = prompt.items - vote.items
48:             lost_items.each do |loser|
49:               elo[item] += adjust_elo(WIN_SCORE, old_elo[item], elo[loser])
50:               elo[loser] += adjust_elo(LOSS_SCORE, elo[loser], old_elo[item])
51:             end
52:           end
53:         else
54:           # otherwise consider as draw between all prompt items
55:           prompt.items.each do |item|
56:             (prompt.items - [item]).each do |other|
57:               elo[item] += adjust_elo(DRAW_SCORE, elo[item], old_elo[other])
58:             end
59:           end # item_ids each
60:         end # else
61:       end # votes each
62:     end # prompts each
63:     elo = (order == "asc") ? elo.sort_by { |k, v| v } : elo.sort_by { |k, v| -v }
64:     elo = elo.first(limit) if limit > 0
65:     elo.transpose
66:   end

[Validate]


text:
package edu.sdsu.its.fit_welcome_tests;

import edu.sdsu.its.Blackboard.Models.DataSource;
import edu.sdsu.its.Blackboard.Models.User;
import edu.sdsu.its.Blackboard.Users;
import edu.sdsu.its.Vault;
import edu.sdsu.its.Welcome.DB;
import org.apache.log4j.Logger;
import org.junit.Before;
import org.junit.Test;

import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assume.assumeTrue;

/**
 * Test Blackboard Integration
 *
 * @author Tom Paulus
 *         Created on 3/24/17.
 */
public class TestBbUsers {
    private static final Logger LOGGER = Logger.getLogger(TestBbUsers.class);

    @Before
    public void setUp() throws Exception {
        assumeTrue(Boolean.parseBoolean(Vault.getParam("syncEnable")));
    }

    @Test
    public void getAllUsers() throws Exception {
        LOGGER.info("Retrieving All Users from DB");

        Users.UserReport userReport = Users.getAllUsers(0, 250);
        assertNotNull(userReport);
        assertNotNull(userReport.users);
        assertTrue("No Users Returned", userReport.users.length > 0);
        LOGGER.info(String.format("Retrieved %d users from Bb", userReport.users.length));

        for (User user : userReport.users) {
            assertNotNull(user.externalId);
            assertNotNull(user.dataSourceId);
            assertNotNull(user.DSK);
            if (user.studentId == null)
                LOGGER.warn("Student ID is not defined for " + user.externalId);
            assertNotNull(user.name);
            assertNotNull("No First Name", user.name.get("given"));
            assertNotNull("No Last Name", user.name.get("family"));
            if (user.contact == null || user.contact.get("email") == null)
                LOGGER.warn("Email is not defined for " + user.externalId);
        }
    }

    @Test
    public void testSync() throws Exception {
        DB.syncUser(TestDB.TEST_USER_ID,
                "Test",
                "User",
                "fitcenter+tests@mail.sdsu.edu",
                new DataSource("EXTERNAL"),
                "NULL");
    }
}


text:
import { PlaywrightTestConfig, devices } from '@playwright/test'

const config: PlaywrightTestConfig = {
  projects: [
    {
      name: 'chromium',
      use: { ...devices['Desktop Chrome'] },
    },
    {
      name: 'firefox',
      use: { ...devices['Desktop Firefox'] },
    },
    {
      name: 'webkit',
      use: { ...devices['Desktop Safari'] },
    },
    {
      name: 'iPhone 13',
      use: {
        browserName: 'webkit',
        ...devices['iPhone 13'],
      },
    },
  ],
  // Look for test files in the "tests" directory, relative to this configuration file
  testDir: 'e2e',

  // Each test is given 30 seconds
  timeout: 30000,

  // Two retries for each test
  retries: 2,

  // Forbid test.only on CI
  forbidOnly: !!process.env.CI,

  // Limit the number of workers on CI, use default locally
  workers: process.env.CI ? 2 : undefined,

  use: {
    // Record trace for each test, but remove it from successful test runs
    trace: 'retain-on-failure',

    // Record video only when retrying a test for the first time.
    video: 'on-first-retry',
  },
}
export default config