text:
<?php

namespace WebinoDraw\Cache;

use ArrayObject;
use DOMNode;
use WebinoDraw\Dom\Element;
use WebinoDraw\Dom\Text;
use WebinoDraw\Event\DrawEvent;
use Zend\Cache\Storage\StorageInterface;
use Zend\EventManager\EventManagerAwareInterface;
use Zend\EventManager\EventManagerAwareTrait;

/**
 * Class DrawCache
 */
class DrawCache implements EventManagerAwareInterface
{
    use EventManagerAwareTrait;

    /**
     * Cache storage service name
     */
    const STORAGE = 'WebinoDrawCache';

    /**
     * @var StorageInterface
     */
    protected $cache;

    /**
     * @var string
     */
    protected $eventIdentifier = 'WebinoDraw';

    /**
     * @var Element[]|Text[]
     */
    private $nodes;

    /**
     * @param StorageInterface|object $cache
     */
    public function __construct(StorageInterface $cache)
    {
        $this->cache = $cache;
    }

    /**
     * Save nodes XHTML to the cache
     *
     * @todo refactor
     * @param DrawEvent $event
     * @return self
     */
    public function save(DrawEvent $event)
    {
        $spec = $event->getSpec();
        if (empty($spec['cache'])) {
            return $this;
        }

        foreach ($this->nodes as $cacheKey => $node) {
            if (empty($node->ownerDocument)) {
                continue;
            }

            $doc = $node->getOwnerDocument();
            $cachedNode = $doc->getXpath()->query('//*[@__cacheKey="' . $cacheKey . '"]')->item(0);

            if (empty($cachedNode) || !($cachedNode instanceof Element)) {
                // TODO logger should be saved to cache
                //echo 'SHOULD SAVE: ' . print_r($spec['locator'], true);echo  '
';
                continue;
            }

            $cachedNode->removeAttribute('__cacheKey');

            // TODO redesign
            if ($node instanceof Text || 'text' === $cachedNode->getAttribute('__cache')) {
                $cachedNode->removeAttribute('__cache');
                $xhtml = $doc->saveXML($cachedNode->firstChild);
            } else {
                $xhtml = $doc->saveXML($cachedNode);
            }

            // TODO logger saving to cache
            //echo '
SAVE: ' . print_r($spec['cache'], true) . '
' . htmlspecialchars($xhtml) . '
';
            $this->cache->setItem($cacheKey, $xhtml);
            $this->cache->setTags($cacheKey, (array) $spec['cache']);
        }

        $this->nodes = [];
        return $this;
    }

    /**
     * Load nodes XHTML from the cache
     *
     * @todo refactor
     * @param DrawEvent $event
     * @return bool true = loaded
     */
    public function load(DrawEvent $event)
    {
        $spec = $event->getSpec();
        if (empty($spec['cache'])) {
            return false;
        }

        $cached   = true;
        $nodes    = $event->getNodes();
        $newNodes = [];

        foreach ($nodes->toArray() as $_node) {
            $node     = $this->nodeToCache($spec, $_node);
            $cacheKey = $this->createCacheKey($node, $event);
            $xhtml    = $this->cache->getItem($cacheKey);

            if (empty($xhtml)) {
                $cached     = false;
                $newNodes[] = $_node;

                // TODO logger queued to cache
                //echo 'CANNOT LOAD: ' . print_r($spec['locator'], true);echo  '
';
                $this->nodes[$cacheKey] = $node;

                if ($node instanceof Text) {
                    $node->getParentNode()->setAttribute('__cacheKey', $cacheKey);
                    $onReplace = function ($newNode) use ($cacheKey) {
                        $newNode->parentNode->setAttribute('__cacheKey', $cacheKey);
                    };

                } elseif ($node instanceof Element) {
                    $node->setAttribute('__cacheKey', $cacheKey);
                    $onReplace = function (Element $newNode) use ($cacheKey) {
                        $newNode->setAttribute('__cacheKey', $cacheKey);
                    };
                }

                if (isset($onReplace)) {
                    $node->setOnReplace($this->createOnReplaceHandler());
                    $node->setOnReplace($onReplace);
                }
                continue;
            }

            // TODO logger loading cached
            //echo '
LOAD: ' . print_r($spec['cache'], true) . '
' . htmlspecialchars($xhtml) . '
';
            $frag = $node->ownerDocument->createDocumentFragment();
            $frag->appendXml($xhtml);
            $node->parentNode->replaceChild($frag, $node);
        }

        $nodes->setNodes($newNodes);
        return $cached;
    }

    /**
     * Select node to cache
     *
     * @param ArrayObject $spec
     * @param Element|Text $node
     * @return DomNode
     */
    private function nodeToCache(ArrayObject $spec, $node)
    {
        if (isset($spec['cache_node_xpath'])) {
            // TODO cache node not found exception
            return $node->getOwnerDocument()->getXpath()->query($spec['cache_node_xpath'], $node)->item(0);
        }
        return $node;
    }

    /**
     * @param DOMNode $node
     * @param DrawEvent $event
     * @return string
     */
    protected function createCacheKey(DOMNode $node, DrawEvent $event)
    {
        $spec     = $event->getSpec();
        $cacheKey = $node->getNodePath();

        if (!empty($spec['cache_key'])) {
            // replace vars in the cache key settings
            $specCacheKey = $spec['cache_key'];
            $helper       = $event->getHelper();

            /** @var \WebinoDraw\VarTranslator\Translation $translation */
            $translation = clone $helper->getVarTranslator()->getTranslation();
            $translation->merge($helper->getVars());
            $translation->getVarTranslation()->translate($specCacheKey);

            $cacheKey .= join('', $specCacheKey);
        }

        empty($spec['cache_key_trigger'])
            or $cacheKey .= $this->cacheKeyTrigger((array) $spec['cache_key_trigger'], $event);

        return md5($cacheKey);
    }

    /**
     * @param array $triggers
     * @param DrawEvent $event
     * @return string
     */
    protected function cacheKeyTrigger(array $triggers, DrawEvent $event)
    {
        $spec     = $event->getSpec();
        $helper   = $event->getHelper();
        $cacheKey = '';

        foreach ($triggers as $eventName) {
            $results = $this->getEventManager()->trigger($eventName, $helper, ['spec' => $spec]);
            foreach ($results as $result) {
                $cacheKey .= $result;
            }
        }

        return $cacheKey;
    }

    /**
     * @return \Closure
     */
    private function createOnReplaceHandler()
    {
        return function ($newNode, $oldNode, $frag) {
            $self = ($oldNode instanceof Text) ? $oldNode->getParentNode() : $oldNode;
            if ($self->hasAttribute('__cacheKey')) {
                $cacheKey = $self->getAttributeNode('__cacheKey');

                if ($newNode instanceof Text) {
                    $newParentNode = $newNode->getParentNode();
                    $newParentNode->setAttributeNode($cacheKey);
                    $newParentNode->setAttribute('__cache', 'text');

                } elseif ($newNode instanceof Element) {
                    if ($frag->childNodes->length <= 1) {
                        // has wrapper
                        $newNode->setAttributeNode($cacheKey);
                    } else {
                        $newNode->parentNode->setAttributeNode($cacheKey);
                    }
                }
                $self->removeAttribute('__cacheKey');
            }
        };
    }
}


text:
using System;
using System.Diagnostics;
using System.Collections.Generic;
using System.Globalization;
using System.Text;
using System.Xml;
using System.IO;
using PdfSharp.Xps.XpsModel;

namespace PdfSharp.Xps.Parsing
{
  partial class XpsParser
  {
    /// <summary>
    /// Parses an ImageBrush element.
    /// </summary>
    ImageBrush ParseImageBrush()
    {
      Debug.Assert(this.reader.Name == "ImageBrush");
      bool isEmptyElement = this.reader.IsEmptyElement;
      ImageBrush brush = new ImageBrush();
      while (MoveToNextAttribute())
      {
        switch (this.reader.Name)
        {
          //case "Name":
          //  //brush.Name = this.rdr.Value;
          //  break;

          case "Opacity":
            brush.Opacity = ParseDouble(this.reader.Value);
            break;

          case "Transform":
            brush.Transform = ParseMatrixTransform(this.reader.Value);
            break;

          case "ViewboxUnits":
            brush.ViewboxUnits = ParseEnum<ViewUnits>(this.reader.Value);
            break;

          case "ViewportUnits":
            brush.ViewportUnits = ParseEnum<ViewUnits>(this.reader.Value);
            break;

          case "TileMode":
            brush.TileMode = ParseEnum<TileMode>(this.reader.Value);
            break;

          case "Viewbox":
            brush.Viewbox = Rect.Parse(this.reader.Value);
            break;

          case "Viewport":
            brush.Viewport = Rect.Parse(this.reader.Value);
            break;

          case "ImageSource":
            brush.ImageSource = this.reader.Value;
            break;

          case "x:Key":
            brush.Key = this.reader.Value;
            break;

          default:
            Debugger.Break();
            break;
        }
      }
      if (!isEmptyElement)
      {
        MoveToNextElement();
        while (this.reader.IsStartElement())
        {
          switch (this.reader.Name)
          {
            case "ImageBrush.Transform":
              MoveToNextElement();
              brush.Transform = ParseMatrixTransform();
              MoveToNextElement();
              break;

            default:
              Debugger.Break();
              break;
          }
        }
      }
      MoveToNextElement();
      return brush;
    }
  }
}

redpajama_set_name: RedPajamaGithub


text:
/*
 * multiword_types.h
 *
 * Code generation for model "Ver002".
 *
 * Model version              : 1.15
 * Simulink Coder version : 8.12 (R2017a) 16-Feb-2017
 * C source code generated on : Thu Nov 16 10:56:49 2017
 *
 * Target selection: sldrtert.tlc
 * Embedded hardware selection: Intel->x86-64 (Windows64)
 * Code generation objectives: Unspecified
 * Validation result: Not run
 */

#ifndef MULTIWORD_TYPES_H
#define MULTIWORD_TYPES_H
#include "rtwtypes.h"

/*
 * Definitions supporting external data access
 */
typedef int32_T chunk_T;
typedef uint32_T uchunk_T;

#endif                                 /* MULTIWORD_TYPES_H */


text:
package org.apache.felix.dm.runtime.itest.components;

import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.util.Map;

import org.apache.felix.dm.annotation.api.Component;
import org.apache.felix.dm.annotation.api.PropertyType;
import org.apache.felix.dm.annotation.api.ServiceDependency;
import org.apache.felix.dm.itest.util.Ensure;

/**
 * @author Felix Project Team
 */
public class ComponentDMSingleValuedPropertyTypeAnnotation {
    public final static String ENSURE = "ComponentDMSingleValuedPropertyTypeAnnotation";

    @PropertyType
    @Retention(RetentionPolicy.CLASS)
    @interface MyProperty1 {
        String PREFIX_ = "prefix1.";
        String value() default "defval1"; // derived property name is prefix1.my.property1;
    }

    @PropertyType
    @Retention(RetentionPolicy.CLASS)
    @interface MyProperty2 {
        String PREFIX_ = "prefix2.";
        String value() default "defval2"; // derived property name is prefix2.my.propert2;
    }

	@Component(provides=MyComponent.class)
	@MyProperty1("val1")
	@MyProperty2
    public static class MyComponent {
    }

    @Component
    public static class MyConsumer {
        @ServiceDependency(filter = "(name=" + ENSURE + ")")
        volatile Ensure m_ensure;

        @ServiceDependency
        void bind(MyComponent comp, Map<String, Object> props) {
        	m_ensure.step(1);
        	if ("val1".equals(props.get("prefix1.my.property1"))) {
        		m_ensure.step(2);
        	}
            if ("defval2".equals(props.get("prefix2.my.property2"))) {
        		m_ensure.step(3);
        	}
        }
    }

}


text:
NS_ASSUME_NONNULL_BEGIN

@class MWKSection;

typedef NS_ENUM(NSInteger, WikiTextFetcherErrorType) {
    WikiTextFetcherErrorTypeUnknown = 0,
    WikiTextFetcherErrorTypeAPI = 1,
    WikiTextFetcherErrorTypeIncomplete = 2
};

extern NSString *const WikiTextSectionFetcherErrorDomain;

@interface WikiTextSectionFetcher : WMFLegacyFetcher

- (void)fetchSection:(MWKSection *)section completion:(void (^)(NSDictionary *_Nullable result, NSError *_Nullable error))completion;

@end

NS_ASSUME_NONNULL_END


text:
<xml>
		<compilerflag value="-I${haxelib:duell_opengl}/backends/openglcontext_ios/project/include" />
</xml>


text:
<search model="country">
    <field name="name"/>
    <field name="code"/>
</search>


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Bot. Mater. Otd. Sporov. Rast. Bot. Inst. Komarova Akad. Nauk S. S. S. R. 8: (1952)

#### Original name
Pleosphaerellula cornicola Naumov & Czerepan., 1952

### Remarks
null


text:
ALTER TABLE {$NAMESPACE}_harbormaster.harbormaster_build
  ADD buildParameters LONGTEXT COLLATE {$COLLATE_TEXT} NOT NULL;

UPDATE {$NAMESPACE}_harbormaster.harbormaster_build
  SET buildParameters = '{}' WHERE buildParameters = '';


text:
            {{ processInstance.id }}

          {{ processInstance.startTime | camDate }}

          {{ processInstance.businessKey }}


text:
module Freshdesk
  #
  class Agent < Freshdesk::Base
    def initialize(attributes)
      attributes.each do |(attr, value)|
        unless respond_to?(attr)
          value = attr == 'user' ? User.new(value) : value
          set_variable(attr, value)
        end
      end
    end

    class << self
      def find_by_email(email)
        url = endpoint.list_agents_path("email is #{email}")
        response = get_request(url)
        with_error_handling(response) do |parsed|
          agents = parsed.map { |agent| new(agent['agent']) }
          if agents.size > 1
            raise "More than one agent with the same email?"
          else
            return agents.first
          end
        end
      end
    end
  end
end


text:
package aos.data.comparator;

import java.io.Serializable;
import java.util.Collection;
import java.util.Comparator;
import java.util.Iterator;
import java.util.TreeSet;

public class ComparatorSample{
    public static void main(
            String args[]){
        new Worker().doIt();
    }// end main()
}// end class Comparator04

class Worker{
    public void doIt(){
        Iterator iter;
        Collection ref;

        ref = new TreeSet(new TheComparator());
        Populator.fillIt(ref);
        iter = ref.iterator();
        while(iter.hasNext()){
            System.out.print(
                    iter.next() + " ");
        }// end while loop
        System.out.println();

    }// end doIt()
}// end class Worker

class Populator{
    public static void fillIt(
            Collection ref){
        ref.add("Joe");
        ref.add("Bill");
        ref.add("Tom");
        ref.add("JOE");
        ref.add("BILL");
        ref.add("TOM");
    }// end fillIt()
}// end class Populator

class TheComparator
implements Comparator,Serializable{

    public int compare(
            Object o1,Object o2){
        if(!(o1 instanceof String))
            throw new ClassCastException();
        if(!(o2 instanceof String))
            throw new ClassCastException();

        int result = ((String)o1).
        compareTo(((String)o2));
        return result*(-1);
    }// end compare()

    public boolean equals(Object o){
        if(!(o instanceof TheComparator))
            return false;
        else return true;
    }// end overridden equals()
}// end class TheComparator


text:
/* crypto/ui/ui_lib.c */
/*
 * Written by Richard Levitte (richard@levitte.org) for the OpenSSL project
 * 2001.
 */
/* ====================================================================
 * Copyright (c) 2001 The OpenSSL Project.  All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 *
 * 3. All advertising materials mentioning features or use of this
 *    software must display the following acknowledgment:
 *    "This product includes software developed by the OpenSSL Project
 *    for use in the OpenSSL Toolkit. (http://www.openssl.org/)"
 *
 * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
 *    endorse or promote products derived from this software without
 *    prior written permission. For written permission, please contact
 *    openssl-core@openssl.org.
 *
 * 5. Products derived from this software may not be called "OpenSSL"
 *    nor may "OpenSSL" appear in their names without prior written
 *    permission of the OpenSSL Project.
 *
 * 6. Redistributions of any form whatsoever must retain the following
 *    acknowledgment:
 *    "This product includes software developed by the OpenSSL Project
 *    for use in the OpenSSL Toolkit (http://www.openssl.org/)"
 *
 * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
 * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE OpenSSL PROJECT OR
 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
 * OF THE POSSIBILITY OF SUCH DAMAGE.
 * ====================================================================
 *
 * This product includes cryptographic software written by Eric Young
 * (eay@cryptsoft.com).  This product includes software written by Tim
 * Hudson (tjh@cryptsoft.com).
 *
 */

#include <string.h>
#include "cryptlib.h"
#include <openssl/e_os2.h>
#include <openssl/buffer.h>
#include <openssl/ui.h>
#include <openssl/err.h>
#include "ui_locl.h"

IMPLEMENT_STACK_OF(UI_STRING_ST)

static const UI_METHOD *default_UI_meth = NULL;

UI *UI_new(void)
{
    return (UI_new_method(NULL));
}

UI *UI_new_method(const UI_METHOD *method)
{
    UI *ret;

    ret = (UI *)OPENSSL_malloc(sizeof(UI));
    if (ret == NULL) {
        UIerr(UI_F_UI_NEW_METHOD, ERR_R_MALLOC_FAILURE);
        return NULL;
    }
    if (method == NULL)
        ret->meth = UI_get_default_method();
    else
        ret->meth = method;

    ret->strings = NULL;
    ret->user_data = NULL;
    ret->flags = 0;
    CRYPTO_new_ex_data(CRYPTO_EX_INDEX_UI, ret, &ret->ex_data);
    return ret;
}

static void free_string(UI_STRING *uis)
{
    if (uis->flags & OUT_STRING_FREEABLE) {
        OPENSSL_free((char *)uis->out_string);
        switch (uis->type) {
        case UIT_BOOLEAN:
            OPENSSL_free((char *)uis->_.boolean_data.action_desc);
            OPENSSL_free((char *)uis->_.boolean_data.ok_chars);
            OPENSSL_free((char *)uis->_.boolean_data.cancel_chars);
            break;
        default:
            break;
        }
    }
    OPENSSL_free(uis);
}

void UI_free(UI *ui)
{
    if (ui == NULL)
        return;
    sk_UI_STRING_pop_free(ui->strings, free_string);
    CRYPTO_free_ex_data(CRYPTO_EX_INDEX_UI, ui, &ui->ex_data);
    OPENSSL_free(ui);
}

static int allocate_string_stack(UI *ui)
{
    if (ui->strings == NULL) {
        ui->strings = sk_UI_STRING_new_null();
        if (ui->strings == NULL) {
            return -1;
        }
    }
    return 0;
}

static UI_STRING *general_allocate_prompt(UI *ui, const char *prompt,
                                          int prompt_freeable,
                                          enum UI_string_types type,
                                          int input_flags, char *result_buf)
{
    UI_STRING *ret = NULL;

    if (prompt == NULL) {
        UIerr(UI_F_GENERAL_ALLOCATE_PROMPT, ERR_R_PASSED_NULL_PARAMETER);
    } else if ((type == UIT_PROMPT || type == UIT_VERIFY
                || type == UIT_BOOLEAN) && result_buf == NULL) {
        UIerr(UI_F_GENERAL_ALLOCATE_PROMPT, UI_R_NO_RESULT_BUFFER);
    } else if ((ret = (UI_STRING *)OPENSSL_malloc(sizeof(UI_STRING)))) {
        ret->out_string = prompt;
        ret->flags = prompt_freeable ? OUT_STRING_FREEABLE : 0;
        ret->input_flags = input_flags;
        ret->type = type;
        ret->result_buf = result_buf;
    }
    return ret;
}

static int general_allocate_string(UI *ui, const char *prompt,
                                   int prompt_freeable,
                                   enum UI_string_types type, int input_flags,
                                   char *result_buf, int minsize, int maxsize,
                                   const char *test_buf)
{
    int ret = -1;
    UI_STRING *s = general_allocate_prompt(ui, prompt, prompt_freeable,
                                           type, input_flags, result_buf);

    if (s) {
        if (allocate_string_stack(ui) >= 0) {
            s->_.string_data.result_minsize = minsize;
            s->_.string_data.result_maxsize = maxsize;
            s->_.string_data.test_buf = test_buf;
            ret = sk_UI_STRING_push(ui->strings, s);
            /* sk_push() returns 0 on error.  Let's addapt that */
            if (ret <= 0)
                ret--;
        } else
            free_string(s);
    }
    return ret;
}

static int general_allocate_boolean(UI *ui,
                                    const char *prompt,
                                    const char *action_desc,
                                    const char *ok_chars,
                                    const char *cancel_chars,
                                    int prompt_freeable,
                                    enum UI_string_types type,
                                    int input_flags, char *result_buf)
{
    int ret = -1;
    UI_STRING *s;
    const char *p;

    if (ok_chars == NULL) {
        UIerr(UI_F_GENERAL_ALLOCATE_BOOLEAN, ERR_R_PASSED_NULL_PARAMETER);
    } else if (cancel_chars == NULL) {
        UIerr(UI_F_GENERAL_ALLOCATE_BOOLEAN, ERR_R_PASSED_NULL_PARAMETER);
    } else {
        for (p = ok_chars; *p; p++) {
            if (strchr(cancel_chars, *p)) {
                UIerr(UI_F_GENERAL_ALLOCATE_BOOLEAN,
                      UI_R_COMMON_OK_AND_CANCEL_CHARACTERS);
            }
        }

        s = general_allocate_prompt(ui, prompt, prompt_freeable,
                                    type, input_flags, result_buf);

        if (s) {
            if (allocate_string_stack(ui) >= 0) {
                s->_.boolean_data.action_desc = action_desc;
                s->_.boolean_data.ok_chars = ok_chars;
                s->_.boolean_data.cancel_chars = cancel_chars;
                ret = sk_UI_STRING_push(ui->strings, s);
                /*
                 * sk_push() returns 0 on error. Let's addapt that
                 */
                if (ret <= 0)
                    ret--;
            } else
                free_string(s);
        }
    }
    return ret;
}

/*
 * Returns the index to the place in the stack or -1 for error.  Uses a
 * direct reference to the prompt.
 */
int UI_add_input_string(UI *ui, const char *prompt, int flags,
                        char *result_buf, int minsize, int maxsize)
{
    return general_allocate_string(ui, prompt, 0,
                                   UIT_PROMPT, flags, result_buf, minsize,
                                   maxsize, NULL);
}

/* Same as UI_add_input_string(), excepts it takes a copy of the prompt */
int UI_dup_input_string(UI *ui, const char *prompt, int flags,
                        char *result_buf, int minsize, int maxsize)
{
    char *prompt_copy = NULL;

    if (prompt) {
        prompt_copy = BUF_strdup(prompt);
        if (prompt_copy == NULL) {
            UIerr(UI_F_UI_DUP_INPUT_STRING, ERR_R_MALLOC_FAILURE);
            return 0;
        }
    }

    return general_allocate_string(ui, prompt_copy, 1,
                                   UIT_PROMPT, flags, result_buf, minsize,
                                   maxsize, NULL);
}

int UI_add_verify_string(UI *ui, const char *prompt, int flags,
                         char *result_buf, int minsize, int maxsize,
                         const char *test_buf)
{
    return general_allocate_string(ui, prompt, 0,
                                   UIT_VERIFY, flags, result_buf, minsize,
                                   maxsize, test_buf);
}

int UI_dup_verify_string(UI *ui, const char *prompt, int flags,
                         char *result_buf, int minsize, int maxsize,
                         const char *test_buf)
{
    char *prompt_copy = NULL;

    if (prompt) {
        prompt_copy = BUF_strdup(prompt);
        if (prompt_copy == NULL) {
            UIerr(UI_F_UI_DUP_VERIFY_STRING, ERR_R_MALLOC_FAILURE);
            return -1;
        }
    }

    return general_allocate_string(ui, prompt_copy, 1,
                                   UIT_VERIFY, flags, result_buf, minsize,
                                   maxsize, test_buf);
}

int UI_add_input_boolean(UI *ui, const char *prompt, const char *action_desc,
                         const char *ok_chars, const char *cancel_chars,
                         int flags, char *result_buf)
{
    return general_allocate_boolean(ui, prompt, action_desc,
                                    ok_chars, cancel_chars, 0, UIT_BOOLEAN,
                                    flags, result_buf);
}

int UI_dup_input_boolean(UI *ui, const char *prompt, const char *action_desc,
                         const char *ok_chars, const char *cancel_chars,
                         int flags, char *result_buf)
{
    char *prompt_copy = NULL;
    char *action_desc_copy = NULL;
    char *ok_chars_copy = NULL;
    char *cancel_chars_copy = NULL;

    if (prompt) {
        prompt_copy = BUF_strdup(prompt);
        if (prompt_copy == NULL) {
            UIerr(UI_F_UI_DUP_INPUT_BOOLEAN, ERR_R_MALLOC_FAILURE);
            goto err;
        }
    }

    if (action_desc) {
        action_desc_copy = BUF_strdup(action_desc);
        if (action_desc_copy == NULL) {
            UIerr(UI_F_UI_DUP_INPUT_BOOLEAN, ERR_R_MALLOC_FAILURE);
            goto err;
        }
    }

    if (ok_chars) {
        ok_chars_copy = BUF_strdup(ok_chars);
        if (ok_chars_copy == NULL) {
            UIerr(UI_F_UI_DUP_INPUT_BOOLEAN, ERR_R_MALLOC_FAILURE);
            goto err;
        }
    }

    if (cancel_chars) {
        cancel_chars_copy = BUF_strdup(cancel_chars);
        if (cancel_chars_copy == NULL) {
            UIerr(UI_F_UI_DUP_INPUT_BOOLEAN, ERR_R_MALLOC_FAILURE);
            goto err;
        }
    }

    return general_allocate_boolean(ui, prompt_copy, action_desc_copy,
                                    ok_chars_copy, cancel_chars_copy, 1,
                                    UIT_BOOLEAN, flags, result_buf);
 err:
    if (prompt_copy)
        OPENSSL_free(prompt_copy);
    if (action_desc_copy)
        OPENSSL_free(action_desc_copy);
    if (ok_chars_copy)
        OPENSSL_free(ok_chars_copy);
    if (cancel_chars_copy)
        OPENSSL_free(cancel_chars_copy);
    return -1;
}

int UI_add_info_string(UI *ui, const char *text)
{
    return general_allocate_string(ui, text, 0, UIT_INFO, 0, NULL, 0, 0,
                                   NULL);
}

int UI_dup_info_string(UI *ui, const char *text)
{
    char *text_copy = NULL;

    if (text) {
        text_copy = BUF_strdup(text);
        if (text_copy == NULL) {
            UIerr(UI_F_UI_DUP_INFO_STRING, ERR_R_MALLOC_FAILURE);
            return -1;
        }
    }

    return general_allocate_string(ui, text_copy, 1, UIT_INFO, 0, NULL,
                                   0, 0, NULL);
}

int UI_add_error_string(UI *ui, const char *text)
{
    return general_allocate_string(ui, text, 0, UIT_ERROR, 0, NULL, 0, 0,
                                   NULL);
}

int UI_dup_error_string(UI *ui, const char *text)
{
    char *text_copy = NULL;

    if (text) {
        text_copy = BUF_strdup(text);
        if (text_copy == NULL) {
            UIerr(UI_F_UI_DUP_ERROR_STRING, ERR_R_MALLOC_FAILURE);
            return -1;
        }
    }
    return general_allocate_string(ui, text_copy, 1, UIT_ERROR, 0, NULL,
                                   0, 0, NULL);
}

char *UI_construct_prompt(UI *ui, const char *object_desc,
                          const char *object_name)
{
    char *prompt = NULL;

    if (ui->meth->ui_construct_prompt)
        prompt = ui->meth->ui_construct_prompt(ui, object_desc, object_name);
    else {
        char prompt1[] = "Enter ";
        char prompt2[] = " for ";
        char prompt3[] = ":";
        int len = 0;

        if (object_desc == NULL)
            return NULL;
        len = sizeof(prompt1) - 1 + strlen(object_desc);
        if (object_name)
            len += sizeof(prompt2) - 1 + strlen(object_name);
        len += sizeof(prompt3) - 1;

        prompt = (char *)OPENSSL_malloc(len + 1);
        BUF_strlcpy(prompt, prompt1, len + 1);
        BUF_strlcat(prompt, object_desc, len + 1);
        if (object_name) {
            BUF_strlcat(prompt, prompt2, len + 1);
            BUF_strlcat(prompt, object_name, len + 1);
        }
        BUF_strlcat(prompt, prompt3, len + 1);
    }
    return prompt;
}

void *UI_add_user_data(UI *ui, void *user_data)
{
    void *old_data = ui->user_data;
    ui->user_data = user_data;
    return old_data;
}

void *UI_get0_user_data(UI *ui)
{
    return ui->user_data;
}

const char *UI_get0_result(UI *ui, int i)
{
    if (i < 0) {
        UIerr(UI_F_UI_GET0_RESULT, UI_R_INDEX_TOO_SMALL);
        return NULL;
    }
    if (i >= sk_UI_STRING_num(ui->strings)) {
        UIerr(UI_F_UI_GET0_RESULT, UI_R_INDEX_TOO_LARGE);
        return NULL;
    }
    return UI_get0_result_string(sk_UI_STRING_value(ui->strings, i));
}

static int print_error(const char *str, size_t len, UI *ui)
{
    UI_STRING uis;

    memset(&uis, 0, sizeof(uis));
    uis.type = UIT_ERROR;
    uis.out_string = str;

    if (ui->meth->ui_write_string && !ui->meth->ui_write_string(ui, &uis))
        return -1;
    return 0;
}

int UI_process(UI *ui)
{
    int i, ok = 0;

    if (ui->meth->ui_open_session && !ui->meth->ui_open_session(ui))
        return -1;

    if (ui->flags & UI_FLAG_PRINT_ERRORS)
        ERR_print_errors_cb((int (*)(const char *, size_t, void *))
                            print_error, (void *)ui);

    for (i = 0; i < sk_UI_STRING_num(ui->strings); i++) {
        if (ui->meth->ui_write_string
            && !ui->meth->ui_write_string(ui,
                                          sk_UI_STRING_value(ui->strings, i)))
        {
            ok = -1;
            goto err;
        }
    }

    if (ui->meth->ui_flush)
        switch (ui->meth->ui_flush(ui)) {
        case -1:               /* Interrupt/Cancel/something... */
            ok = -2;
            goto err;
        case 0:                /* Errors */
            ok = -1;
            goto err;
        default:               /* Success */
            ok = 0;
            break;
        }

    for (i = 0; i < sk_UI_STRING_num(ui->strings); i++) {
        if (ui->meth->ui_read_string) {
            switch (ui->meth->ui_read_string(ui,
                                             sk_UI_STRING_value(ui->strings,
                                                                i))) {
            case -1:           /* Interrupt/Cancel/something... */
                ok = -2;
                goto err;
            case 0:            /* Errors */
                ok = -1;
                goto err;
            default:           /* Success */
                ok = 0;
                break;
            }
        }
    }
 err:
    if (ui->meth->ui_close_session && !ui->meth->ui_close_session(ui))
        return -1;
    return ok;
}

int UI_ctrl(UI *ui, int cmd, long i, void *p, void (*f) (void))
{
    if (ui == NULL) {
        UIerr(UI_F_UI_CTRL, ERR_R_PASSED_NULL_PARAMETER);
        return -1;
    }
    switch (cmd) {
    case UI_CTRL_PRINT_ERRORS:
        {
            int save_flag = ! !(ui->flags & UI_FLAG_PRINT_ERRORS);
            if (i)
                ui->flags |= UI_FLAG_PRINT_ERRORS;
            else
                ui->flags &= ~UI_FLAG_PRINT_ERRORS;
            return save_flag;
        }
    case UI_CTRL_IS_REDOABLE:
        return ! !(ui->flags & UI_FLAG_REDOABLE);
    default:
        break;
    }
    UIerr(UI_F_UI_CTRL, UI_R_UNKNOWN_CONTROL_COMMAND);
    return -1;
}

int UI_get_ex_new_index(long argl, void *argp, CRYPTO_EX_new *new_func,
                        CRYPTO_EX_dup *dup_func, CRYPTO_EX_free *free_func)
{
    return CRYPTO_get_ex_new_index(CRYPTO_EX_INDEX_UI, argl, argp,
                                   new_func, dup_func, free_func);
}

int UI_set_ex_data(UI *r, int idx, void *arg)
{
    return (CRYPTO_set_ex_data(&r->ex_data, idx, arg));
}

void *UI_get_ex_data(UI *r, int idx)
{
    return (CRYPTO_get_ex_data(&r->ex_data, idx));
}

void UI_set_default_method(const UI_METHOD *meth)
{
    default_UI_meth = meth;
}

const UI_METHOD *UI_get_default_method(void)
{
    if (default_UI_meth == NULL) {
        default_UI_meth = UI_OpenSSL();
    }
    return default_UI_meth;
}

const UI_METHOD *UI_get_method(UI *ui)
{
    return ui->meth;
}

const UI_METHOD *UI_set_method(UI *ui, const UI_METHOD *meth)
{
    ui->meth = meth;
    return ui->meth;
}

UI_METHOD *UI_create_method(char *name)
{
    UI_METHOD *ui_method = (UI_METHOD *)OPENSSL_malloc(sizeof(UI_METHOD));

    if (ui_method) {
        memset(ui_method, 0, sizeof(*ui_method));
        ui_method->name = BUF_strdup(name);
    }
    return ui_method;
}

/*
 * BIG FSCKING WARNING!!!! If you use this on a statically allocated method
 * (that is, it hasn't been allocated using UI_create_method(), you deserve
 * anything Murphy can throw at you and more! You have been warned.
 */
void UI_destroy_method(UI_METHOD *ui_method)
{
    OPENSSL_free(ui_method->name);
    ui_method->name = NULL;
    OPENSSL_free(ui_method);
}

int UI_method_set_opener(UI_METHOD *method, int (*opener) (UI *ui))
{
    if (method) {
        method->ui_open_session = opener;
        return 0;
    } else
        return -1;
}

int UI_method_set_writer(UI_METHOD *method,
                         int (*writer) (UI *ui, UI_STRING *uis))
{
    if (method) {
        method->ui_write_string = writer;
        return 0;
    } else
        return -1;
}

int UI_method_set_flusher(UI_METHOD *method, int (*flusher) (UI *ui))
{
    if (method) {
        method->ui_flush = flusher;
        return 0;
    } else
        return -1;
}

int UI_method_set_reader(UI_METHOD *method,
                         int (*reader) (UI *ui, UI_STRING *uis))
{
    if (method) {
        method->ui_read_string = reader;
        return 0;
    } else
        return -1;
}

int UI_method_set_closer(UI_METHOD *method, int (*closer) (UI *ui))
{
    if (method) {
        method->ui_close_session = closer;
        return 0;
    } else
        return -1;
}

int UI_method_set_prompt_constructor(UI_METHOD *method,
                                     char *(*prompt_constructor) (UI *ui,
                                                                  const char
                                                                  *object_desc,
                                                                  const char
                                                                  *object_name))
{
    if (method) {
        method->ui_construct_prompt = prompt_constructor;
        return 0;
    } else
        return -1;
}

int (*UI_method_get_opener(UI_METHOD *method)) (UI *) {
    if (method)
        return method->ui_open_session;
    else
        return NULL;
}

int (*UI_method_get_writer(UI_METHOD *method)) (UI *, UI_STRING *) {
    if (method)
        return method->ui_write_string;
    else
        return NULL;
}

int (*UI_method_get_flusher(UI_METHOD *method)) (UI *) {
    if (method)
        return method->ui_flush;
    else
        return NULL;
}

int (*UI_method_get_reader(UI_METHOD *method)) (UI *, UI_STRING *) {
    if (method)
        return method->ui_read_string;
    else
        return NULL;
}

int (*UI_method_get_closer(UI_METHOD *method)) (UI *) {
    if (method)
        return method->ui_close_session;
    else
        return NULL;
}

char *(*UI_method_get_prompt_constructor(UI_METHOD *method)) (UI *,
                                                              const char *,
                                                              const char *) {
    if (method)
        return method->ui_construct_prompt;
    else
        return NULL;
}

enum UI_string_types UI_get_string_type(UI_STRING *uis)
{
    if (!uis)
        return UIT_NONE;
    return uis->type;
}

int UI_get_input_flags(UI_STRING *uis)
{
    if (!uis)
        return 0;
    return uis->input_flags;
}

const char *UI_get0_output_string(UI_STRING *uis)
{
    if (!uis)
        return NULL;
    return uis->out_string;
}

const char *UI_get0_action_string(UI_STRING *uis)
{
    if (!uis)
        return NULL;
    switch (uis->type) {
    case UIT_PROMPT:
    case UIT_BOOLEAN:
        return uis->_.boolean_data.action_desc;
    default:
        return NULL;
    }
}

const char *UI_get0_result_string(UI_STRING *uis)
{
    if (!uis)
        return NULL;
    switch (uis->type) {
    case UIT_PROMPT:
    case UIT_VERIFY:
        return uis->result_buf;
    default:
        return NULL;
    }
}

const char *UI_get0_test_string(UI_STRING *uis)
{
    if (!uis)
        return NULL;
    switch (uis->type) {
    case UIT_VERIFY:
        return uis->_.string_data.test_buf;
    default:
        return NULL;
    }
}

int UI_get_result_minsize(UI_STRING *uis)
{
    if (!uis)
        return -1;
    switch (uis->type) {
    case UIT_PROMPT:
    case UIT_VERIFY:
        return uis->_.string_data.result_minsize;
    default:
        return -1;
    }
}

int UI_get_result_maxsize(UI_STRING *uis)
{
    if (!uis)
        return -1;
    switch (uis->type) {
    case UIT_PROMPT:
    case UIT_VERIFY:
        return uis->_.string_data.result_maxsize;
    default:
        return -1;
    }
}

int UI_set_result(UI *ui, UI_STRING *uis, const char *result)
{
    int l = strlen(result);

    ui->flags &= ~UI_FLAG_REDOABLE;

    if (!uis)
        return -1;
    switch (uis->type) {
    case UIT_PROMPT:
    case UIT_VERIFY:
        {
            char number1[DECIMAL_SIZE(uis->_.string_data.result_minsize) + 1];
            char number2[DECIMAL_SIZE(uis->_.string_data.result_maxsize) + 1];

            BIO_snprintf(number1, sizeof(number1), "%d",
                         uis->_.string_data.result_minsize);
            BIO_snprintf(number2, sizeof(number2), "%d",
                         uis->_.string_data.result_maxsize);

            if (l < uis->_.string_data.result_minsize) {
                ui->flags |= UI_FLAG_REDOABLE;
                UIerr(UI_F_UI_SET_RESULT, UI_R_RESULT_TOO_SMALL);
                ERR_add_error_data(5, "You must type in ",
                                   number1, " to ", number2, " characters");
                return -1;
            }
            if (l > uis->_.string_data.result_maxsize) {
                ui->flags |= UI_FLAG_REDOABLE;
                UIerr(UI_F_UI_SET_RESULT, UI_R_RESULT_TOO_LARGE);
                ERR_add_error_data(5, "You must type in ",
                                   number1, " to ", number2, " characters");
                return -1;
            }
        }

        if (!uis->result_buf) {
            UIerr(UI_F_UI_SET_RESULT, UI_R_NO_RESULT_BUFFER);
            return -1;
        }

        BUF_strlcpy(uis->result_buf, result,
                    uis->_.string_data.result_maxsize + 1);
        break;
    case UIT_BOOLEAN:
        {
            const char *p;

            if (!uis->result_buf) {
                UIerr(UI_F_UI_SET_RESULT, UI_R_NO_RESULT_BUFFER);
                return -1;
            }

            uis->result_buf[0] = '\0';
            for (p = result; *p; p++) {
                if (strchr(uis->_.boolean_data.ok_chars, *p)) {
                    uis->result_buf[0] = uis->_.boolean_data.ok_chars[0];
                    break;
                }
                if (strchr(uis->_.boolean_data.cancel_chars, *p)) {
                    uis->result_buf[0] = uis->_.boolean_data.cancel_chars[0];
                    break;
                }
            }
        }
    default:
        break;
    }
    return 0;
}


text:
package alluxio.exception;

import alluxio.Constants;

import com.google.common.base.Preconditions;

import java.text.MessageFormat;
import javax.annotation.concurrent.ThreadSafe;

/**
 * Exception messages used across Alluxio.
 *
 * Note: To minimize merge conflicts, please sort alphabetically in this section.
 */
@ThreadSafe
public enum ExceptionMessage {
  // general
  INVALID_PREFIX("Parent path \"{0}\" is not a prefix of child {1}."),
  NOT_SUPPORTED("This method is not supported."),
  PATH_DOES_NOT_EXIST("Path \"{0}\" does not exist."),
  PATH_MUST_BE_FILE("Path \"{0}\" must be a file."),
  PATH_MUST_BE_MOUNT_POINT("Path \"{0}\" must be a mount point."),
  PATH_INVALID("Path \"{0}\" is invalid."),
  STATE_LOCK_TIMED_OUT("Failed to acquire the lock after {0}ms"),

  // general block
  BLOCK_UNAVAILABLE("Block {0} is unavailable in both Alluxio and UFS."),
  BLOCK_SIZE_INVALID("Block size of {0} is invalid. Block size must be > 0 bytes."),
  CANNOT_REQUEST_SPACE("Not enough space left on worker {0} to store blockId {1,number,#}."),
  NO_SPACE_FOR_BLOCK_ON_WORKER("There is no worker with enough space for a new block of size {0}"),
  NO_WORKER_AVAILABLE("No available Alluxio worker found"),

  // active sync
  FAILED_INITIAL_SYNC("IOException encountered during initial syncing of sync point {0}"),

  // block lock manager
  LOCK_ID_FOR_DIFFERENT_BLOCK("lockId {0,number,#} is for blockId {1,number,#}, not {2,number,#}"),
  LOCK_ID_FOR_DIFFERENT_SESSION(
      "lockId {0,number,#} is owned by sessionId {1,number,#} not {2,number,#}"),
  LOCK_RECORD_NOT_FOUND_FOR_LOCK_ID("lockId {0,number,#} has no lock record"),
  LOCK_NOT_RELEASED("lockId {0,number,#} is not released."),
  SESSION_NOT_CLOSED("session {0,number,#} is not closed."),

  // block metadata manager and view
  BLOCK_META_NOT_FOUND("BlockMeta not found for blockId {0,number,#}"),
  GET_DIR_FROM_NON_SPECIFIC_LOCATION("Cannot get path from non-specific dir {0}"),
  TEMP_BLOCK_META_NOT_FOUND("TempBlockMeta not found for blockId {0,number,#}"),
  TIER_ALIAS_NOT_FOUND("Tier with alias {0} not found"),
  TIER_VIEW_ALIAS_NOT_FOUND("Tier view with alias {0} not found"),

  // instream/outstream
  FAILED_CACHE("Failed to cache: {0}"),
  READ_CLOSED_STREAM("Cannot read from a closed stream"),

  // meta master
  NO_MASTER_FOUND("No master with masterId {0,number,#} is found"),

  // storageDir
  ADD_EXISTING_BLOCK("blockId {0,number,#} exists in {1}"),
  BLOCK_NOT_FOUND_FOR_SESSION("blockId {0,number,#} in {1} not found for session {2,number,#}"),
  NO_SPACE_FOR_BLOCK_META(
      "blockId {0,number,#} is {1,number,#} bytes, but only {2,number,#} bytes available in {3}"),

  // tieredBlockStore
  BLOCK_ID_FOR_DIFFERENT_SESSION(
      "blockId {0,number,#} is owned by sessionId {1,number,#} not {2,number,#}"),
  BLOCK_NOT_FOUND_AT_LOCATION("blockId {0,number,#} not found at location: {1}"),
  MOVE_UNCOMMITTED_BLOCK("Cannot move uncommitted blockId {0,number,#}"),
  NO_BLOCK_ID_FOUND("blockId {0,number,#} not found"),
  NO_EVICTION_PLAN_TO_FREE_SPACE(
      "Failed to free {0,number,#} bytes space at location {1}"),
  NO_SPACE_FOR_BLOCK_ALLOCATION(
      "Failed to allocate {0,number,#} bytes on {1} to create blockId {2,number,#}"),
  NO_SPACE_FOR_BLOCK_MOVE(
      "Failed to find space in {0} to move blockId {1,number,#}"),
  REMOVE_UNCOMMITTED_BLOCK("Cannot remove uncommitted blockId {0,number,#}"),
  TEMP_BLOCK_ID_COMMITTED(
      "Temp blockId {0,number,#} is not available, because it is already committed"),
  TEMP_BLOCK_ID_EXISTS("Temp blockId {0,number,#} is not available, because it already exists"),

  // ufsBlockStore
  UFS_BLOCK_ALREADY_EXISTS_FOR_SESSION(
      "UFS block {0,number,#} from UFS file {1} exists for session {2,number,#}"),
  UFS_BLOCK_ACCESS_TOKEN_UNAVAILABLE(
      "Failed to acquire an access token for the UFS block {0,number,#} (filename: {1})."),
  UFS_BLOCK_DOES_NOT_EXIST_FOR_SESSION(
      "UFS block {0,number,#} does not exist for session {1,number,#}"),

  // journal
  JOURNAL_WRITE_AFTER_CLOSE("Cannot write entry after closing the stream"),
  JOURNAL_WRITE_FAILURE("Failed to write to journal file ({0}): {1}"),
  JOURNAL_FLUSH_FAILURE("Failed to flush journal file ({0}): {1}"),

  // Raft journal
  FAILED_RAFT_BOOTSTRAP("Failed to bootstrap raft cluster with addresses {0}: {1}"),

  // file
  CANNOT_READ_INCOMPLETE_FILE(
      "Cannot read from {0} because it is incomplete. Wait for the file to be marked as complete "
          + "by the writing thread or application."),
  CANNOT_READ_DIRECTORY("Cannot read from {0} because it is a directory"),
  DELETE_FAILED_DIR_CHILDREN(
      "Cannot delete directory {0}. Failed to delete children: {1}"),
  DELETE_FAILED_DIR_NONEMPTY("Directory not empty"),
  DELETE_FAILED_UFS("Failed to delete {0} from the under file system"),
  DELETE_FAILED_UFS_DIR("UFS delete dir failed"),
  DELETE_FAILED_UFS_FILE("UFS delete file failed"),
  DELETE_FAILED_UFS_NOT_IN_SYNC("UFS dir not in sync. Sync UFS, or delete with unchecked flag."),
  DELETE_FAILED_DIRECTORY_NOT_IN_SYNC(
      "Cannot delete {0} because the UFS has contents not loaded into Alluxio. Sync Alluxio with "
          + "UFS or run delete with unchecked flag to forcibly delete"),
  DELETE_NONEMPTY_DIRECTORY_NONRECURSIVE(
      "Cannot delete non-empty directory {0} because recursive is set to false"),
  DELETE_ROOT_DIRECTORY("Cannot delete the root directory"),
  FILE_CREATE_IS_DIRECTORY("{0} already exists. Directories cannot be overwritten with create"),
  PARENT_CREATION_FAILED("Unable to create parent directories for path {0}"),

  // file system master
  CANNOT_FREE_NON_EMPTY_DIR("Cannot free directory {0} which is not empty. Please set "
      + "the \"recursive\" flag of free operation to true"),
  CANNOT_FREE_NON_PERSISTED_FILE("Cannot free file {0} which is not persisted"),
  CANNOT_FREE_PINNED_FILE("Cannot free file {0} which is pinned. Please unpin it first or"
      + " set the \"forced\" flag of free operation to true"),
  INODE_DOES_NOT_EXIST("inodeId {0,number,#} does not exist"),
  INODE_DOES_NOT_EXIST_RETRIES("inodeId {0,number,#} does not exist; too many retries"),
  NOT_MUTABLE_INODE_PATH("Not a MutableLockedInodePath: {0}"),
  PATH_COMPONENTS_INVALID("Parameter pathComponents is {0}"),
  PATH_COMPONENTS_INVALID_START("Path starts with {0}"),
  PATH_INVALID_CONCURRENT_RENAME("Path is no longer valid, possibly due to a concurrent rename."),
  PATH_INVALID_CONCURRENT_DELETE("Path is no longer valid, possibly due to a concurrent delete."),
  PATH_MUST_HAVE_VALID_PARENT("{0} does not have a valid parent"),
  RENAME_CANNOT_BE_ACROSS_MOUNTS("Renaming {0} to {1} is a cross mount operation"),
  RENAME_CANNOT_BE_ONTO_MOUNT_POINT("{0} is a mount point and cannot be renamed onto"),
  RENAME_CANNOT_BE_TO_ROOT("Cannot rename a path to the root directory"),
  RENAME_CANNOT_BE_TO_SUBDIRECTORY("Cannot rename because {0} is a prefix of {1}"),
  ROOT_CANNOT_BE_RENAMED("The root directory cannot be renamed"),
  JOURNAL_ENTRY_MISSING(
      "Journal entries are missing between sequence number {0} (inclusive) and {1} (exclusive)."),
  JOURNAL_ENTRY_TRUNCATED_UNEXPECTEDLY(
      "Journal entry [sequence number {0}] is truncated unexpectedly."),

  // block master
  NO_WORKER_FOUND("No worker with workerId {0,number,#} is found"),

  // table master
  DATABASE_DOES_NOT_EXIST("Database {0} does not exist"),
  TABLE_DOES_NOT_EXIST("Table {0} does not exist in database {1}"),
  TRANSFORM_WRITE_ACTION_INVALID_NUM_FILES("Write action must have positive number of files"),
  TABLE_BEING_TRANSFORMED("Existing job {0} is transforming table {1} in database {2}"),
  TABLE_ALREADY_TRANSFORMED("Database {0} table {1} has been transformed by definition {2}"),
  TRANSFORM_JOB_DOES_NOT_EXIST("No transformation information for job ID {0}"),
  TRANSFORM_MANAGER_HEARTBEAT_INTERRUPTED("TransformManager's heartbeat was interrupted"),
  TRANSFORM_JOB_ID_NOT_FOUND_IN_JOB_SERVICE("Transformation job {0} for database {1} table {2} "
      + "was not found in job master, maybe the job master was restarted: {3}"),

  // safe mode
  MASTER_IN_SAFEMODE("Alluxio master is in safe mode. Please try again later."),

  // file system master ufs
  FAILED_UFS_CREATE("Failed to create {0} in the under file system"),
  FAILED_UFS_RENAME("Failed to rename {0} to {1} in the under file system"),

  // file system worker
  BAD_WORKER_FILE_ID(
      "Worker fileId {0,number,#} is invalid. The worker may have crashed or cleaned up "
          + "the client state due to a timeout."),

  // cli
  INVALID_ARGS_GENERIC("Invalid args for command {0}"),
  INVALID_ARGS_NULL("Null args for command {0}"),
  INVALID_ARGS_NUM("Command {0} takes {1} arguments, not {2}"),
  INVALID_ARGS_NUM_INSUFFICIENT("Command {0} requires at least {1} arguments ({2} provided)"),
  INVALID_ARGS_NUM_TOO_MANY("Command {0} requires at most {1} arguments ({2} provided)"),
  INVALID_ARGS_SORT_FIELD("Invalid sort option `{0}` for --sort"),
  INVALID_ARG_TYPE("Arg {0} is not type {1}"),
  INVALID_OPTION("Invalid option provided. Supported options: {0}"),
  INVALID_OPTION_COUNT("Invalid option count. Expected: {0}, Found: {1}"),
  INVALID_OPTION_VALUE("Invalid value provided for option: {0}. Supported values: {1}"),
  INVALID_ADDRESS_VALUE("Invalid address provided."),

  // extension shell
  INVALID_EXTENSION_NOT_JAR("File {0} does not have the extension JAR"),

  // fs shell
  DESTINATION_CANNOT_BE_FILE(
      "The destination cannot be an existing file when the source is a directory or a list of "
          + "files."),
  INVALID_TIME("{0} is not valid time"),

  // client
  DIFFERENT_CONNECTION_DETAILS(
      "New connection details are different from that in file system context {0}"),
  INCOMPATIBLE_VERSION("{0} client version {1} is not compatible with server version {2}"),

  // configuration
  UNABLE_TO_DETERMINE_MASTER_HOSTNAME("Cannot run {0}; Unable to determine {1} address. Please "
      + "modify " + Constants.SITE_PROPERTIES + " to either set {2}, configure zookeeper with "
      + "{3}=true and {4}=[comma-separated zookeeper master addresses], or utilize internal HA by "
      + "setting {5}=[comma-separated alluxio {1} addresses]"),
  DEFAULT_PROPERTIES_FILE_DOES_NOT_EXIST("The default Alluxio properties file does not exist"),
  INVALID_CONFIGURATION_KEY("Invalid property key {0}"),
  INVALID_CONFIGURATION_VALUE("Invalid value {0} for configuration key {1}"),
  KEY_NOT_BOOLEAN("Configuration cannot evaluate value {0} as boolean for key {1}"),
  KEY_NOT_BYTES("Configuration cannot evaluate value {0} as bytes for key {1}"),
  KEY_NOT_DOUBLE("Configuration cannot evaluate value {0} as double for key {1}"),
  KEY_NOT_FLOAT("Configuration cannot evaluate value {0} as float for key {1}"),
  KEY_NOT_INTEGER("Configuration cannot evaluate value {0} as integer for key {1}"),
  KEY_NOT_LONG("Configuration cannot evaluate value {0} as long for key {1}"),
  KEY_NOT_MS("Configuration cannot evaluate value {0} as milliseconds for key {1}"),
  KEY_CIRCULAR_DEPENDENCY("Circular dependency found while resolving {0}"),
  UNDEFINED_CONFIGURATION_KEY("No value set for configuration key {0}"),
  UNKNOWN_ENUM("Unrecognized configuration enum value <{0}> for key {1}. Acceptable values: {2}"),
  UNKNOWN_PROPERTY("Unknown property for {0} {1}"),

  // metrics
  INVALID_METRIC_KEY("Invalid metric key {0}"),

  // security
  ACL_BASE_REQUIRED(
      "Replacing ACL entries must include the base entries for 'user', 'group', and 'other'. "
          + "missing: {0}"),
  AUTHENTICATION_IS_NOT_ENABLED("Authentication is not enabled"),
  AUTHORIZED_CLIENT_USER_IS_NULL("The client user is not authorized so as to be null in server"),
  INVALID_SET_ACL_OPTIONS("Invalid set acl options: {0}, {1}, {2}"),
  INVALID_MODE("Invalid mode {0}"),
  INVALID_MODE_SEGMENT("Invalid mode {0} - contains invalid segment {1}"),
  INVALID_MODE_PERMISSIONS(
      "Invalid mode {0} - contains invalid segment {1} which has invalid permissions {2}"),
  INVALID_MODE_TARGETS(
      "Invalid mode {0} - contains invalid segment {1} which has invalid targets {2}"),
  PERMISSION_DENIED("Permission denied: {0}"),
  SECURITY_IS_NOT_ENABLED("Security is not enabled"),

  // yarn
  YARN_NOT_ENOUGH_HOSTS(
      "Not enough usable hosts in the cluster to launch {0} {1} containers. Only {2} hosts "
          + "available"),
  YARN_NOT_ENOUGH_RESOURCES(
      "{0} {1} specified above max threshold of cluster, specified={2}, max={3}"),

  // mounting
  MOUNT_POINT_ALREADY_EXISTS("Mount point target path {0} already exists in Alluxio namespace. "
      + "Try mounting to another path."),
  MOUNT_POINT_PREFIX_OF_ANOTHER("Mount point {0} is a prefix of {1}"),
  MOUNT_PATH_SHADOWS_PARENT_UFS(
      "Mount path {0} shadows an existing path {1} in the parent underlying filesystem"),
  MOUNT_READONLY("A write operation on {0} under a readonly mount point {1} is not allowed"),
  UFS_PATH_DOES_NOT_EXIST("Ufs path {0} does not exist"),
  FOREIGN_URI_NOT_MOUNTED("Foreign URI: {0} is not found on Alluxio mounts."),

  // key-value
  KEY_VALUE_TOO_LARGE("Unable to put key-value pair: key {0} bytes, value {1} bytes"),
  KEY_ALREADY_EXISTS("The input key already exists in the key-value store"),
  INVALID_KEY_VALUE_STORE_URI("The URI {0} exists but is not a key-value store"),

  // migrate job (either move or copy)
  MIGRATE_CANNOT_BE_TO_SUBDIRECTORY("Cannot migrate because {0} is a prefix of {1}"),
  MIGRATE_DIRECTORY("Cannot migrate directory"),
  MIGRATE_FILE_TO_DIRECTORY("Cannot migrate a file ({0}) to a directory ({1})"),
  MIGRATE_NEED_OVERWRITE("Cannot migrate to {0} because it exists and overwrite is set to false"),
  MIGRATE_OVERWRITE_DIRECTORY(
      "{0} already exists. The overwrite flag cannot be used to overwrite directories"),
  MIGRATE_TO_FILE_AS_DIRECTORY("Cannot migrate to {0}. {1} is a file, not a directory"),

  // transform job
  TRANSFORM_TABLE_URI_LACKS_SCHEME("URI {0} lacks scheme"),
  TRANSFORM_TABLE_URI_LACKS_AUTHORITY("URI {0} lacks authority"),

  // job service
  NO_LOCAL_BLOCK_WORKER_LOAD_TASK(
      "Cannot find a local block worker to load blockId {0,number,#}"),

  // job manager
  JOB_DEFINITION_DOES_NOT_EXIST("The job definition for config {0} does not exist"),
  JOB_DOES_NOT_EXIST("The job of id {0} does not exist"),
  JOB_MASTER_FULL_CAPACITY("Job master is at full capacity of {0} jobs"),

  // block worker
  FAILED_COMMIT_BLOCK_TO_MASTER("Failed to commit block with blockId {0,number,#} to master"),
  PINNED_TO_MULTIPLE_MEDIUMTYPES("File {0} pinned to multiple medium types"),

  // ufs maintenance
  UFS_OP_NOT_ALLOWED("Operation {0} not allowed on ufs path {1} under maintenance mode {2}"),

  // SEMICOLON! minimize merge conflicts by putting it on its own line
  ;

  private final MessageFormat mMessage;

  ExceptionMessage(String message) {
    mMessage = new MessageFormat(message);
  }

  /**
   * Formats the message of the exception.
   *
   * @param params the parameters for the exception message
   * @return the formatted message
   */
  public String getMessage(Object... params) {
    Preconditions.checkArgument(mMessage.getFormatsByArgumentIndex().length == params.length,
        "The message takes " + mMessage.getFormatsByArgumentIndex().length + " arguments, but is "
            + "given " + params.length);
    // MessageFormat is not thread-safe, so guard it
    synchronized (mMessage) {
      return mMessage.format(params);
    }
  }

  /**
   * Formats the message of the exception with a url to consult.
   *
   * @param url the url to consult
   * @param params the parameters for the exception message
   * @return the formatted message
   */
  public String getMessageWithUrl(String url, Object... params) {
    return getMessage(params) + " Please consult " + url
        + " for common solutions to address this problem.";
  }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<project>
	<!-- _________________________ Application Settings _________________________ -->

	<app title="JellyBlocks" file="JellyBlocks" main="Main" package="com.creativecog.jelly" version="0.0.1" company="Creative Cog Games" />
    <!--<meta title="JellyBlocks" package="com.creativecog.jelly" version="1.0.0" company="Creative Cog Games" />-->
	<!--The flixel preloader is not accurate in Chrome. You can use it regularly if you embed the swf into a html file
		or you can set the actual size of your file manually at "FlxPreloaderBase-onUpdate-bytesTotal"-->
	<app preloader="JellyBlocksPreloader" />

	<!--Minimum without FLX_NO_GAMEPAD: 11.8, without FLX_NO_NATIVE_CURSOR: 11.2-->
	<set name="SWF_VERSION" value="11.8" />

	<!-- ____________________________ Window Settings ___________________________ -->

    <haxedef name="BuildString" value="Jelly Blocks v1.0.8 RC3 - $buildType" />

    <!-- create size vars in project file -->
    <set name="windowWidth" value="600"/>
    <set name="windowHeight" value="800" />

    <set name="windowWidth" value="1280" if="desktop" />
    <set name="windowHeight" value="720" if="desktop" />

    <!-- make above var visible to compiler/show up as constants -->
    <haxedef name="windowWidth" value="${windowWidth}" />
    <haxedef name="windowHeight" value="${windowHeight}" />

	<!--These window settings apply to all targets-->
	<!-- old background was #FFF8E7 -->
    <window width="${windowWidth}" height="${windowHeight}" fps="60" background="#7ADAEA" hardware="true" vsync="true" antialiasing="4"/>

	<!--HTML5-specific-->
	<window if="html5" fullscreen="false" resizable="true"/>

	<!--Desktop-specific-->
	<window if="desktop" orientation="landscape" fullscreen="false" resizable="false" />

	<!--Mobile-specific-->
	<window if="mobile" orientation="portrait" fullscreen="true" width="${windowWidth}" height="${windowHeight}" />

	<!-- _____________________________ Path Settings ____________________________ -->

	<set name="BUILD_DIR" value="export" />
	<classpath name="source" />

    <assets path="assets/widescreen_assets"  if="desktop" rename="assets" include="*" />
    <assets path="assets/narrow_assets"  unless="desktop" rename="assets" include="*" />
    <!--<assets path="assets/assets" rename="assets" include="*.xml" embed="true" />-->

    <assets path="assets/assets" rename="assets" exclude="*.mp3|*.wav|*-emoji.png" />

    <!-- Flixel Safari hack, Safari tries to load mp3 sounds and svg fonts-->
    <assets path="assets/flixel" rename="flixel" if="html5" />

	<haxelib name="textParticles" />
	<haxelib name="jellyPhysics" />
	<haxelib name="flixel" />
	<haxelib name="flixel-addons" />
	<haxelib name="openfl" version="3.6.1" />
	<haxelib name="flixel-ui" />

	<!--In case you want to use nape with flixel-->
	<!--<haxelib name="nape" />-->

	<!-- ______________________________ Haxedefines _____________________________ -->

	<!--Enable the Flixel core recording system-->
	<!--<haxedef name="FLX_RECORD" />-->

	<!--Disable the right and middle mouse buttons-->
	<!--<haxedef name="FLX_NO_MOUSE_ADVANCED" />-->

	<!--Disable the native cursor API on Flash-->
	<!--<haxedef name="FLX_NO_NATIVE_CURSOR" />-->

	<!--Optimise inputs, be careful you will get null errors if you don't use conditionals in your game-->
	<haxedef name="FLX_NO_MOUSE" if="mobile" />
	<haxedef name="FLX_NO_KEYBOARD" if="mobile" />
	<!--<haxedef name="FLX_NO_TOUCH" if="desktop" />-->
    <!--<haxedef name="FLX_NO_GAMEPAD" />-->

	<!--Disable the Flixel core sound tray-->
	<!--<haxedef name="FLX_NO_SOUND_TRAY" if="html5" />-->

	<!--Disable the Flixel sound management code-->
	<!--<haxedef name="FLX_NO_SOUND_SYSTEM" if="html5" />-->

	<!--Disable the Flixel core focus lost screen-->
	<!--<haxedef name="FLX_NO_FOCUS_LOST_SCREEN" />-->

	<!--Disable the Flixel core debugger. Automatically gets set whenever you compile in release mode!-->
	<haxedef name="FLX_NO_DEBUG" unless="debug" />

	<!--Enable this for Nape release builds for a serious peformance improvement-->
	<haxedef name="NAPE_RELEASE_BUILD" unless="debug" />

	<!-- _________________________________ Custom _______________________________ -->

	<!--Place custom nodes like icons here (higher priority to override the HaxeFlixel icon)-->

    <icon path="icon64.png" />
</project>


text:
<!DOCTYPE html>

<title>Sync Project Files</title>
<meta charset="utf-8">

同期を開始しています...


text:
<?php

/**
 * attribute type textarea
 *
 * @category	Ultimate
 * @package		Ultimate_ModuleCreator
 * @author 		Marius Strajeru <marius.strajeru@gmail.com>
 */
class Ultimate_ModuleCreator_Model_Attribute_Type_Textarea extends Ultimate_ModuleCreator_Model_Attribute_Type_Abstract{
	/**
	 * sql colum ddl size
	 * @var string
	 */
	protected $_sizeDdl 	= "'64k'";
	/**
	 * the textarea attributes are not allowed in the admin grid
	 * @access public
	 * @return bool
	 * @see Ultimate_ModuleCreator_Model_Attribute_Type_Abstract::getAdminGrid()
	 * @author Marius Strajeru <marius.strajeru@gmail.com>
	 */
	public function getAdminGrid(){
		return false;
	}
	/**
	 * check if an attribute uses an editor
	 * @access public
	 * @return bool
	 * @author Marius Strajeru <marius.strajeru@gmail.com>
	 */
	public function getEditor(){
		return $this->getAttribute()->getData('editor');
	}
	/**
	 * get the type for the form
	 * @access public
	 * @return string
	 * @author Marius Strajeru <marius.strajeru@gmail.com>
	 */
	public function getFormType(){
		if ($this->getEditor()){
			return 'editor';
		}
		return 'textarea';
	}
	/**
	 * get the options for form input
	 * @access public
	 * @return string
	 * @author Marius Strajeru <marius.strajeru@gmail.com>
	 */
	public function getFormOptions(){
		$options = '';
		if ($this->getEditor() && !$this->getAttribute()->getEntity()->getIsTree()){
			$options = self::OPTION_SEPARATOR."'config'	=> "."$"."wysiwygConfig,\n";
		}
		$options .= parent::getFormOptions();
		return $options;
	}
	/**
	 * get the sql column
	 * @access public
	 * @return string
	 * @author Marius Strajeru <marius.strajeru@gmail.com>
	 */
	public function getSqlColumn(){
		return '`'.$this->getAttribute()->getCode().'` TEXT '.$this->getNullSql().' default \'\',';
	}
}


text:
require 'rails_helper'

require 'xa/ubl/invoice'

describe InvoiceParseService do
  include XA::UBL::Invoice

  it 'should parse existing documents' do
    src = IO.read('./ubl/documents/UBL-Invoice-2.1-Example.xml')
    doc = Document.create(src: src)
    InvoiceParseService.parse(doc.id)

    doc = Document.find(doc.id)
    expect(doc.content).to_not be_nil
    parse(src) do |content|
      ex_doc = Document.create(content: content)
      expect(doc.content).to eql(ex_doc.content)
    end
  end
end


text:
import Ember from 'ember';
import jQuery from 'jquery';
import nextFrame from '../utils/next-frame';

const {
  computed,
  run
  } = Ember;

const STATE_LIST = ['culled', 'hidden', 'visible'];

const STATE_TRANSITIONS_UP = [
  { state: 'culled', method: '' },
  { state: 'hidden', method: '_ov_insert' },
  { state: 'visible', method: '_ov_reveal' }
  ];

const STATE_TRANSITIONS_DOWN = [
  { state: 'visible', method: '' },
  { state: 'hidden', method: '_ov_obscure' },
  { state: 'culled', method: '_ov_teardown' }
  ];

export default Ember.Mixin.create({

  viewState: 'culled',

  contentVisible: false,
  contentHidden: false,
  contentInserted: false,
  contentCulled: false,

  viewStateClass: computed('viewState', function() {
    return 'state-' + this.get('viewState');
  }),

  show() {
    this._setState('visible');
  },

  hide() {
    this._setState('hidden');
  },

  cull() {
    this._setState('culled');
  },

  _setState(toState) {

    var fromState = this.get('viewState');
    var currentState = fromState;

    if (fromState === toState) {
      return;
    }

    var transitionMap = STATE_LIST.indexOf(fromState) < STATE_LIST.indexOf(toState) ? STATE_TRANSITIONS_UP : STATE_TRANSITIONS_DOWN;
    var i;

    for (i = 0; i < transitionMap.length; i++) {
      if (transitionMap[i].state === fromState) {
        break;
      }
    }
    i++;

    while (transitionMap[i] && currentState !== toState) {
      if (transitionMap[i].method) {
        this[transitionMap[i].method]();
        currentState = transitionMap[i].state;
      }
      i++;
    }

    this.set('viewState', toState);
  },

  /**!
   * Destroy the View/Element
   *
   * Unlike the other methods, this method
   * can be called from any state. It is still not valid
   * to transition to it directly, but willDestroy uses it
   * to teardown the instance.
   *
   * @private
   */
  _ov_teardown() {
    let heightProp = this.get('heightProperty');
    if (this.get('contentInserted') && this.element) {
      this.element.style[heightProp] = jQuery(this.element).height() + 'px';
    }
    this.setProperties({ contentCulled: true, contentHidden: false, contentInserted: false });
  },

  /**!
   * Insert the Element into the DOM in a hidden state.
   *
   * @private
   */
  _ov_insert() {
    this.setProperties({ contentHidden: true, contentCulled: false, contentInserted: true });
  },

  /**!
   * Reveal the Element
   *
   * @private
   */
  _ov_reveal() {
    let heightProp = this.get('heightProperty');
    this.setProperties({ contentHidden: false, contentVisible: true, contentInserted: true });
    this.element.style[heightProp] = null;
    this.element.style.visibility = 'visible';
  },

  /**!
   * Hide the Element
   *
   * @private
   */
  _ov_obscure() {
    this.setProperties({ contentHidden: true, contentVisible: false, contentInserted: true });
    this.element.style.visibility = 'hidden';
  }

});


text:
import re

from lxml import etree, isoschematron

import django.utils.copycompat as copy

from django.core.exceptions import ValidationError
from django.utils.encoding import force_unicode

from .descriptors import ImmutableFieldBase, XPathFieldBase, XsltFieldBase
from .exceptions import XmlSchemaValidationError
from .utils import parse_datetime

class NOT_PROVIDED:
    pass

class XmlField(object):

    # These track each time a Field instance is created. Used to retain order.
    creation_counter = 0

    #: If true, the field is the primary xml element
    is_root_field = False

    #: an instance of lxml.etree.XMLParser, to override the default
    parser = None

    #: Used by immutable descriptors to
    value_initialized = False

    def __init__(self, name=None, required=False, default=NOT_PROVIDED, parser=None):
        self.name = name
        self.required = required
        self.default = default
        self.parser = parser

        # Adjust the appropriate creation counter, and save our local copy.
        self.creation_counter = XmlField.creation_counter
        XmlField.creation_counter += 1

    def __cmp__(self, other):
        # This is needed because bisect does not take a comparison function.
        return cmp(self.creation_counter, other.creation_counter)

    def __deepcopy__(self, memodict):
        # We don't have to deepcopy very much here, since most things are not
        # intended to be altered after initial creation.
        obj = copy.copy(self)
        memodict[id(self)] = obj
        return obj

    def to_python(self, value):
        """
        Converts the input value into the expected Python data type, raising
        django.core.exceptions.ValidationError if the data can't be converted.
        Returns the converted value. Subclasses should override this.
        """
        return value

    def run_validators(self, value):
        pass

    def validate(self, value, model_instance):
        pass

    def clean(self, value, model_instance):
        """
        Convert the value's type and run validation. Validation errors from
        to_python and validate are propagated. The correct value is returned
        if no error is raised.
        """
        value = self.to_python(value)
        self.validate(value, model_instance)
        self.run_validators(value)
        return value

    def set_attributes_from_name(self, name):
        self.name = name
        self.attname = self.get_attname()

    def contribute_to_class(self, cls, name):
        self.set_attributes_from_name(name)
        self.model = cls
        cls._meta.add_field(self)

    def get_attname(self):
        return self.name

    def get_cache_name(self):
        return '_%s_cache' % self.name

    def has_default(self):
        """Returns a boolean of whether this field has a default value."""
        return self.default is not NOT_PROVIDED

    def get_default(self):
        """Returns the default value for this field."""
        if self.has_default():
            if callable(self.default):
                return self.default()
            return force_unicode(self.default, strings_only=True)
        return None

class XmlElementField(XmlField):

    __metaclass__ = ImmutableFieldBase

    def validate(self, value, model_instance):
        if value is None:
            if not self.value_initialized or not self.required:
                return

        if not isinstance(value, etree._Element):

            if hasattr(value, 'getroot'):
                try:
                    value = value.getroot()
                except:
                    pass
                else:
                    if isinstance(value, etree._Element):
                        return

            opts = model_instance._meta
            raise ValidationError(("Field %(field_name)r on xml model "
                                   "%(app_label)s.%(object_name)s is not an"
                                   " instance of lxml.etree._Element") % {
                                        "field_name":  self.name,
                                        "app_label":   opts.app_label,
                                        "object_name": opts.object_name,})

class XmlPrimaryElementField(XmlElementField):

    is_root_field = True

    def validate(self, value, model_instance):
        if model_instance._meta.xsd_schema is not None:
            try:
                model_instance._meta.xsd_schema.assertValid(value)
            except Exception, e:
                raise XmlSchemaValidationError(unicode(e))

    def contribute_to_class(self, cls, name):
        assert not cls._meta.has_root_field, \
            "An xml model can't have more than one XmlPrimaryElementField"
        super(XmlPrimaryElementField, self).contribute_to_class(cls, name)
        cls._meta.has_root_field = True
        cls._meta.root_field = self

class XPathField(XmlField):
    """
    Base field for abstracting the retrieval of node results from the xpath
    evaluation of an xml etree.
    """

    __metaclass__ = XPathFieldBase

    #: XPath query string
    xpath_query = None

    #: Dict of extra prefix/uri namespaces pairs to pass to xpath()
    extra_namespaces = {}

    #: Extra extensions to pass on to lxml.etree.XPathEvaluator()
    extensions = {}

    required = True

    def __init__(self, xpath_query, extra_namespaces=None, extensions=None,
                 **kwargs):
        if isinstance(self.__class__, XPathField):
            raise RuntimeError("%r is an abstract field type.")

        self.xpath_query = xpath_query
        if extra_namespaces is not None:
            self.extra_namespaces = extra_namespaces
        if extensions is not None:
            self.extensions = extensions

        super(XPathField, self).__init__(**kwargs)

    def validate(self, nodes, model_instance):
        super(XPathField, self).validate(nodes, model_instance)
        if nodes is None:
            if not self.value_initialized or not self.required:
                return nodes
        num_nodes = len(nodes)
        if self.required and num_nodes == 0:
            msg = u"XPath query %r did not match any nodes" % self.xpath_query
            raise model_instance.DoesNotExist(msg)

    def clean(self, value, model_instance):
        """
        Run validators on raw value, not the value returned from
        self.to_python(value) (as it is in the parent clean() method)
        """
        self.validate(value, model_instance)
        self.run_validators(value)
        value = self.to_python(value)
        return value

    def get_default(self):
        value = super(XPathField, self).get_default()
        if value is None:
            return value
        else:
            return [value]

    def __unicode__(self):
        return (u"%(field_name)s[%(xpath_query)r]" % {
            "field_name": self.name,
            "xpath_query": self.xpath_query,})

    def __repr__(self):
        return ("<%(cls)s: %(field)s>" % {
            "cls": self.__class__.__name__,
            "field": self.__unicode__().encode('raw_unicode_escape'),})

class XPathListField(XPathField):
    """
    Field which abstracts retrieving a list of nodes from the xpath evaluation
    of an xml etree.
    """

    def to_python(self, value):
        if value is None:
            return value
        if isinstance(value, list):
            return value
        else:
            return list(value)

class XPathSingleNodeField(XPathField):
    """
    Field which abstracts retrieving the first node result from the xpath
    evaluation of an xml etree.
    """

    #: Whether to ignore extra nodes and return the first node if the xpath
    #: evaluates to more than one node.
    #:
    #: To return the full list of nodes, Use XPathListField
    ignore_extra_nodes = False

    def __init__(self, xpath_query, ignore_extra_nodes=False, **kwargs):
        self.ignore_extra_nodes = ignore_extra_nodes
        super(XPathSingleNodeField, self).__init__(xpath_query, **kwargs)

    def validate(self, nodes, model_instance):
        super(XPathSingleNodeField, self).validate(nodes, model_instance)
        if nodes is None:
            if not self.value_initialized or not self.required:
                return nodes
        if not self.ignore_extra_nodes and len(nodes) > 1:
            msg = u"XPath query %r matched more than one node" \
                % self.xpath_query
            raise model_instance.MultipleObjectsReturned(msg)

    def to_python(self, value):
        if value is None:
            return value
        if isinstance(value, list):
            if len(value) == 0:
                return None
            else:
                return value[0]
        elif isinstance(value, basestring):
            return value
        else:
            # Possible throw exception here
            return value

class XPathTextField(XPathSingleNodeField):

    #: A tuple of strings which should be interpreted as None.
    none_vals = ()

    def __init__(self, *args, **kwargs):
        none_vals = kwargs.pop('none_vals', None)
        if none_vals is not None:
            self.none_vals = [force_unicode(v) for v in none_vals]
        super(XPathTextField, self).__init__(*args, **kwargs)

    def validate(self, value, model_instance):
        super(XPathTextField, self).validate(value, model_instance)
        if len(self.none_vals):
            value = self.to_python(value)
            if self.required and value in self.none_vals:
                error_msg = (u"%(field)s is required, but value %(value)r is "
                             u"mapped to None") % {
                                "field": unicode(self),
                                "value": value,}
                raise model_instance.DoesNotExist(error_msg)

    def to_python(self, value):
        value = super(XPathTextField, self).to_python(value)
        if value is None:
            return value
        if isinstance(value, etree._Element):
            return force_unicode(value.text)
        else:
            return force_unicode(value)

class XPathIntegerField(XPathTextField):

    def to_python(self, value):
        value = super(XPathIntegerField, self).to_python(value)
        if value is None:
            return value
        else:
            return int(value)

class XPathFloatField(XPathTextField):

    def to_python(self, value):
        value = super(XPathFloatField, self).to_python(value)
        if value is None:
            return value
        else:
            return float(value)

class XPathDateTimeField(XPathTextField):

    def to_python(self, value):
        value = super(XPathDateTimeField, self).to_python(value)
        if value is None:
            return value
        else:
            return parse_datetime(value)

class XPathBooleanField(XPathTextField):

    true_vals = ('true',)
    false_vals = ('false',)

    def __init__(self, *args, **kwargs):
        true_vals = kwargs.pop('true_vals', None)
        if true_vals is not None:
            self.true_vals = true_vals
        false_vals = kwargs.pop('false_vals', None)
        if false_vals is not None:
            self.false_vals = false_vals
        super(XPathBooleanField, self).__init__(*args, **kwargs)

    def validate(self, value, model_instance):
        if value is True or value is False:
            return
        super(XPathBooleanField, self).validate(value, model_instance)
        if value is None:
            return
        value = XPathTextField.to_python(self, value)
        if value is None:
            return
        if value not in self.true_vals and value not in self.false_vals:
            opts = model_instance._meta
            exc_msg = (u"%(field)s on xmlmodel %(app_label)s.%(object_name)s "
                       u"has value %(val)r not in true_vals or false_vals" % {
                            "field": repr(self).decode('raw_unicode_escape'),
                            "app_label": opts.app_label,
                            "object_name": opts.object_name,
                            "val": value,})
            raise ValidationError(exc_msg)

    def to_python(self, value):
        if value is None or value is True or value is False:
            return value
        value = super(XPathBooleanField, self).to_python(value)
        if value in self.true_vals:
            return True
        elif value in self.false_vals:
            return False
        else:
            return value

class XPathTextListField(XPathListField):

    def to_python(self, value):
        value = super(XPathTextListField, self).to_python(value)
        if value is None:
            return value
        else:
            return [force_unicode(getattr(v, "text", v)) for v in value]

class XPathIntegerListField(XPathTextListField):

    def to_python(self, value):
        value = super(XPathIntegerListField, self).to_python(value)
        if value is None:
            return value
        else:
            return [int(v) for v in value]

class XPathFloatListField(XPathTextListField):

    def to_python(self, value):
        value = super(XPathFloatListField, self).to_python(value)
        if value is None:
            return value
        else:
            return [float(v) for v in value]

class XPathDateTimeListField(XPathTextListField):

    def to_python(self, value):
        value = super(XPathDateTimeListField, self).to_python(value)
        if value is None:
            return value
        else:
            return [parse_datetime(v) for v in value]

class XPathBooleanListField(XPathTextListField):

    true_vals = ('true',)
    false_vals = ('false',)

    def __init__(self, *args, **kwargs):
        true_vals = kwargs.pop('true_vals', None)
        if true_vals is not None:
            self.true_vals = true_vals
        false_vals = kwargs.pop('false_vals', None)
        if false_vals is not None:
            self.false_vals = false_vals
        super(XPathBooleanField, self).__init__(*args, **kwargs)

    def validate(self, value, model_instance):
        super(XPathBooleanField, self).validate(value, model_instance)
        values = super(XPathBooleanListField, self).to_python(value)
        if values is None:
            return
        for value in values:
            if value not in self.true_vals and value not in self.false_vals:
                opts = model_instance._meta
                raise ValidationError(("XPathBooleanListField %(field)r on "
                                       " xml model %(app_label)s.%(object_name)s"
                                       " has value %(value)r not in 'true_vals'"
                                       " or 'false_vals'") % {
                                            "field":       self.name,
                                            "app_label":   opts.app_label,
                                            "object_name": opts.object_name,
                                            "value":       value,})

    def to_python(self, value):
        value = super(XPathBooleanField, self).to_python(value)
        if value is None:
            return value
        elif value in self.true_vals:
            return True
        elif value in self.false_vals:
            return False
        else:
            return value

class XPathHtmlField(XPathSingleNodeField):
    """
    Differs from XPathTextField in that it serializes mixed content to a
    unicode string, rather than simply returning the first text node.
    """
    #: Whether to strip the 'xmlns="http://www.w3.org/1999/xhtml"' from
    #: the serialized html strings
    strip_xhtml_ns = True

    def __init__(self, xpath_query, strip_xhtml_ns=True, **kwargs):
        self.strip_xhtml_ns = strip_xhtml_ns
        super(XPathHtmlField, self).__init__(xpath_query, **kwargs)

    def format_value(self, value):
        formatted = etree.tostring(value, encoding='unicode', method='html')
        if self.strip_xhtml_ns:
            formatted = formatted.replace(u' xmlns="http://www.w3.org/1999/xhtml"', '')
        return formatted

    def to_python(self, value):
        value = super(XPathHtmlField, self).to_python(value)
        if value is None:
            return value
        if isinstance(value, etree._Element):
            return self.format_value(value)

class XPathHtmlListField(XPathListField):
    """
    Differs from XPathHtmlListField in that it serializes mixed content to
    a unicode string, rather than simply returning the first text node for
    each node in the result.
    """
    #: Whether to strip the 'xmlns="http://www.w3.org/1999/xhtml"' from
    #: the serialized html strings
    strip_xhtml_ns = True

    def __init__(self, xpath_query, strip_xhtml_ns=True, **kwargs):
        self.strip_xhtml_ns = strip_xhtml_ns
        super(XPathHtmlListField, self).__init__(xpath_query, **kwargs)

    def format_value(self, value):
        formatted = etree.tostring(value, encoding='unicode', method='html')
        if self.strip_xhtml_ns:
            formatted = formatted.replace(u' xmlns="http://www.w3.org/1999/xhtml"', '')
        return formatted

    def to_python(self, value):
        value = super(XPathHtmlListField, self).to_python(value)
        if value is None:
            return value
        else:
            return [self.format_value(v) for v in value]

class XPathInnerHtmlMixin(object):

    self_closing_re = re.compile(
        ur'<(area|base(?:font)?|frame|col|br|hr|input|img|link|meta|param)'
        ur'([^/>]*?)></\1>')

    def get_inner_html(self, value):
        if not isinstance(value, basestring):
            return value
        # Strip surrounding tag
        value = re.sub(r"^(?s)<([^>\s]*)(?:[^>]*>|>)(.*)</\1>$", r'\2', value)
        # Replace open-close tags into self-closing where appropriate
        # e.g. "

" => "
"
        value = self.self_closing_re.sub(ur'<\1\2/>', value)
        # Remove leading and trailing whitespace
        value = value.strip()
        return value

class XPathInnerHtmlField(XPathInnerHtmlMixin, XPathHtmlField):

    def to_python(self, value):
        if value is None:
            return value
        value = super(XPathInnerHtmlField, self).to_python(value)
        return self.get_inner_html(value)

class XPathInnerHtmlListField(XPathInnerHtmlMixin, XPathHtmlListField):

    def to_python(self, value):
        if value is None:
            return value
        value = super(XPathInnerHtmlListField, self).to_python(value)
        return [self.get_inner_html(v) for v in value]

class XsltField(XmlField):

    __metaclass__ = XsltFieldBase

    #: Instance of lxml.etree.XMLParser
    parser = None

    #: Extra extensions to pass on to lxml.etree.XSLT()
    extensions = {}

    xslt_file = None
    xslt_string = None

    _xslt_tree = None

    def __init__(self, xslt_file=None, xslt_string=None, parser=None,
                 extensions=None, **kwargs):
        super(XsltField, self).__init__(**kwargs)

        if xslt_file is None and xslt_string is None:
            raise ValidationError("XsltField requires either xslt_file or "
                                  "xslt_string")
        elif xslt_file is not None and xslt_string is not None:
            raise ValidationError("XsltField.__init__() accepts either "
                                  "xslt_file or xslt_string as keyword "
                                  "arguments, not both")

        self.xslt_file = xslt_file
        self.xslt_string = xslt_string
        self.parser = parser
        if extensions is not None:
            self.extensions = extensions

    def get_xslt_tree(self, model_instance):
        if self._xslt_tree is None:
            parser = self.parser
            if parser is None:
                parser = model_instance._meta.get_parser()
            if self.xslt_file is not None:
                self._xslt_tree = etree.parse(self.xslt_file, parser)
            elif self.xslt_string is not None:
                self._xslt_tree = etree.XML(self.xslt_string, parser)
        return self._xslt_tree

class SchematronField(XmlField):

    __metaclass__ = XsltFieldBase

    #: Instance of lxml.etree.XMLParser
    parser = None

    #: Extra extensions to pass on to lxml.etree.XSLT()
    extensions = {}

    schematron_file = None
    schematron_string = None

    _schematron = None
    _schematron_tree = None
    _schematron_xslt = None

    def __init__(self, schematron_file=None, schematron_string=None, parser=None,
                 extensions=None, **kwargs):
        self.schematron_kwargs = {
            'compile_params': kwargs.pop('compile_params', None),
            'include_params': kwargs.pop('include_params', None),
            'expand_params': kwargs.pop('expand_params', None),
            'phase': kwargs.pop('phase', None),
            'store_xslt': True,
            'store_report': True,
            'store_schematron': True,
        }

        for k in self.schematron_kwargs.keys():
            if self.schematron_kwargs[k] is None:
                del self.schematron_kwargs[k]

        super(SchematronField, self).__init__(**kwargs)

        if schematron_file is None and schematron_string is None:
            raise ValidationError("SchematronField requires either "
                                  "schematron_file or schematron_string")
        elif schematron_file is not None and schematron_string is not None:
            raise ValidationError("SchematronField.__init__() accepts either "
                                  "schematron_file or schematron_string as "
                                  "keyword arguments, not both")

        self.schematron_file = schematron_file
        self.schematron_string = schematron_string
        self.parser = parser
        if extensions is not None:
            self.extensions = extensions

    def get_xslt_tree(self, model_instance):
        if self._schematron_xslt is None:
            schematron_tree = self.get_schematron_tree(model_instance)
            self._schematron = isoschematron.Schematron(schematron_tree, **self.schematron_kwargs)
            self._schematron_xslt = self._schematron.validator_xslt.getroot()
        return self._schematron_xslt

    def get_schematron_tree(self, model_instance):
        if self._schematron_tree is None:
            parser = self.parser
            if parser is None:
                parser = model_instance._meta.get_parser()
            if self.schematron_file is not None:
                self._schematron_tree = etree.parse(self.schematron_file, parser)
            elif self.schematron_string is not None:
                self._schematron_tree = etree.XML(self.schematron_string, parser)
        return self._schematron_tree

# Extra imports so that these can be used via xmlmodels.fields
from .related import (EmbeddedXPathField, EmbeddedXPathListField,
                      EmbeddedXsltField, EmbeddedSchematronField,)


text:
var mysql          = require('../');
var Connection     = require('./Connection');
var EventEmitter   = require('events').EventEmitter;
var Util           = require('util');
var PoolConnection = require('./PoolConnection');

module.exports = Pool;

Util.inherits(Pool, EventEmitter);
function Pool(options) {
  EventEmitter.call(this);
  this.config = options.config;
  this.config.connectionConfig.pool = this;

  this._allConnections   = [];
  this._freeConnections  = [];
  this._connectionQueue  = [];
  this._closed           = false;
}

Pool.prototype.getConnection = function (cb) {

  if (this._closed) {
    return process.nextTick(function(){
      return cb(new Error('Pool is closed.'));
    });
  }

  var connection;

  if (this._freeConnections.length > 0) {
    connection = this._freeConnections.shift();

    return this.acquireConnection(connection, cb);
  }

  if (this.config.connectionLimit === 0 || this._allConnections.length < this.config.connectionLimit) {
    connection = new PoolConnection(this, { config: this.config.newConnectionConfig() });

    this._allConnections.push(connection);

    return connection.connect({timeout: this.config.acquireTimeout}, function (err) {
      if (this._closed) {
        return cb(new Error('Pool is closed.'));
      }
      if (err) {
        return cb(err);
      }

      this.emit('connection', connection);
      return cb(null, connection);
    }.bind(this));
  }

  if (!this.config.waitForConnections) {
    return process.nextTick(function(){
      return cb(new Error('No connections available.'));
    });
  }

  if (this.config.queueLimit && this._connectionQueue.length >= this.config.queueLimit) {
    return cb(new Error('Queue limit reached.'));
  }

  if (cb && process.domain)
    cb = process.domain.bind(cb);
  this._connectionQueue.push(cb);
};

Pool.prototype.acquireConnection = function acquireConnection(connection, cb) {
  if (connection._pool !== this) {
    throw new Error('Connection acquired from wrong pool.');
  }

  var pool = this;

  connection._pool = null;
  connection.ping({timeout: this.config.acquireTimeout}, function(err) {
    if (!err) {
      connection._pool = pool;
      cb(null, connection);
      return;
    }

    connection.destroy();
    pool._connectionQueue.unshift(cb);
    pool._removeConnection(connection);
  });
};

Pool.prototype.releaseConnection = function releaseConnection(connection) {
  var cb;

  if (connection._pool) {
    if (connection._pool !== this) {
      throw new Error('Connection released to wrong pool');
    }

    if (connection._purge) {
      // purge connection from pool
      this._purgeConnection(connection);
      return;
    } else if (this._freeConnections.indexOf(connection) !== -1) {
      // connection already in free connection pool
      // this won't catch all double-release cases
      throw new Error('Connection already released');
    } else {
      // add connection to end of free queue
      this._freeConnections.push(connection);
    }
  }

  while (this._closed && this._connectionQueue.length) {
    // empty the connection queue
    cb = this._connectionQueue.shift();

    process.nextTick(cb.bind(null, new Error('Pool is closed.')));
  }

  if (this._connectionQueue.length) {
    cb = this._connectionQueue.shift();

    this.getConnection(cb);
  }
};

Pool.prototype.end = function (cb) {
  this._closed = true;

  if (typeof cb != "function") {
    cb = function (err) {
      if (err) throw err;
    };
  }

  var calledBack        = false;
  var closedConnections = 0;
  var connection;

  var endCB = function(err) {
    if (calledBack) {
      return;
    }

    if (err || ++closedConnections >= this._allConnections.length) {
      calledBack = true;
      return cb(err);
    }
  }.bind(this);

  if (this._allConnections.length === 0) {
    return process.nextTick(endCB);
  }

  while (this._allConnections.length) {
    connection = this._allConnections[0];
    connection._pool = null;
    connection._realEnd(endCB);
    this._removeConnection(connection);
  }
};

Pool.prototype.query = function (sql, values, cb) {
  var query = Connection.createQuery(sql, values, cb);

  if (this.config.connectionConfig.trace) {
    // Long stack trace support
    query._callSite = new Error;
  }

  this.getConnection(function (err, conn) {
    if (err) {
      var cb = query._callback;
      cb && cb(err);
      return;
    }

    // Release connection based off event
    query.once('end', function() {
      conn.release();
    });

    conn.query(query);
  });

  return query;
};

Pool.prototype._purgeConnection = function _purgeConnection(connection) {
  var pool = this;

  connection._realEnd(function(err) {
    if (err) {
      connection.destroy();
    }

    pool._removeConnection(connection);
  });
};

Pool.prototype._removeConnection = function(connection) {
  var index;

  connection._pool = null;

  if ((index = this._allConnections.indexOf(connection)) !== -1) {
    // Remove connection from all connections
    this._allConnections.splice(index, 1);
  }

  if ((index = this._freeConnections.indexOf(connection)) !== -1) {
    // Remove connection from free connections
    this._freeConnections.splice(index, 1);
  }

  this.releaseConnection(connection);
};

Pool.prototype.escape = function(value) {
  return mysql.escape(value, this.config.connectionConfig.stringifyObjects, this.config.connectionConfig.timezone);
};

Pool.prototype.escapeId = function escapeId(value) {
  return mysql.escapeId(value, false);
};