text:
"""
Import a Bugzilla items into a Trac database.

Requires:  Trac 0.9b1 from http://trac.edgewall.org/
           Python 2.3 from http://www.python.org/
           MySQL >= 3.23 from http://www.mysql.org/
           or PostGreSQL 8.4 from http://www.postgresql.org/
           or SQLite 3 from http://www.sqlite.org/

Thanks:    Mark Rowe <mrowe@bluewire.net.nz>
            for original TracDatabase class

Copyright 2004, Dmitry Yusupov <dmitry_yus@yahoo.com>

Many enhancements, Bill Soudan <bill@soudan.net>
Other enhancements, Florent Guillaume <fg@nuxeo.com>
Reworked, Jeroen Ruigrok van der Werven <asmodai@in-nomine.org>
Jeff Moreland <hou5e@hotmail.com>

$Id: bugzilla2trac.py 9298 2010-02-27 09:59:34Z cboos $
"""

from __future__ import with_statement

import re

###
### Conversion Settings -- edit these before running if desired
###

# Bugzilla version.  You can find this in Bugzilla's globals.pl file.
#
# Currently, the following bugzilla versions are known to work:
#   2.11 (2110), 2.16.5 (2165), 2.16.7 (2167),  2.18.3 (2183), 2.19.1 (2191),
#   2.23.3 (2233), 3.04.4 (3044)
#
# If you run this script on a version not listed here and it is successful,
# please file a ticket at http://trac.edgewall.org
#
BZ_VERSION = 3044

# MySQL connection parameters for the Bugzilla database.  These can also
# be specified on the command line.
BZ_DB = ""
BZ_HOST = ""
BZ_USER = ""
BZ_PASSWORD = ""

# Path to the Trac environment.
TRAC_ENV = "/usr/local/trac"

# If true, all existing Trac tickets and attachments will be removed
# prior to import.
TRAC_CLEAN = True

# Enclose imported ticket description and comments in a {{{ }}}
# preformat block?  This formats the text in a fixed-point font.
PREFORMAT_COMMENTS = False

# Replace bug numbers in comments with #xyz
REPLACE_BUG_NO = False

# Severities
SEVERITIES = [
    ("blocker",  "1"),
    ("critical", "2"),
    ("major",    "3"),
    ("normal",   "4"),
    ("minor",    "5"),
    ("trivial",  "6")
]

# Priorities
# If using the default Bugzilla priorities of P1 - P5, do not change anything
# here.
# If you have other priorities defined please change the P1 - P5 mapping to
# the order you want.  You can also collapse multiple priorities on bugzilla's
# side into the same priority on Trac's side, simply adjust PRIORITIES_MAP.
PRIORITIES = [
    ("highest", "1"),
    ("high",    "2"),
    ("normal",  "3"),
    ("low",     "4"),
    ("lowest",  "5")
]

# Bugzilla: Trac
# NOTE: Use lowercase.
PRIORITIES_MAP = {
    "p1": "highest",
    "p2": "high",
    "p3": "normal",
    "p4": "low",
    "p5": "lowest"
}

# By default, all bugs are imported from Bugzilla.  If you add a list
# of products here, only bugs from those products will be imported.
PRODUCTS = []
# These Bugzilla products will be ignored during import.
IGNORE_PRODUCTS = []

# These milestones are ignored
IGNORE_MILESTONES = ["---"]

# Don't import user names and passwords into htpassword if
# user is disabled in bugzilla? (i.e. profiles.DisabledText<>'')
IGNORE_DISABLED_USERS = True

# These logins are converted to these user ids
LOGIN_MAP = {
    #'some.user@example.com': 'someuser',
}

# These emails are removed from CC list
IGNORE_CC = [
    #'loser@example.com',
]

# The 'component' field in Trac can come either from the Product or
# or from the Component field of Bugzilla. COMPONENTS_FROM_PRODUCTS
# switches the behavior.
# If COMPONENTS_FROM_PRODUCTS is True:
# - Bugzilla Product -> Trac Component
# - Bugzilla Component -> Trac Keyword
# IF COMPONENTS_FROM_PRODUCTS is False:
# - Bugzilla Product -> Trac Keyword
# - Bugzilla Component -> Trac Component
COMPONENTS_FROM_PRODUCTS = False

# If COMPONENTS_FROM_PRODUCTS is True, the default owner for each
# Trac component is inferred from a default Bugzilla component.
DEFAULT_COMPONENTS = ["default", "misc", "main"]

# This mapping can assign keywords in the ticket entry to represent
# products or components (depending on COMPONENTS_FROM_PRODUCTS).
# The keyword will be ignored if empty.
KEYWORDS_MAPPING = {
    #'Bugzilla_product_or_component': 'Keyword',
    "default": "",
    "misc": "",
    }

# If this is True, products or components are all set as keywords
# even if not mentionned in KEYWORDS_MAPPING.
MAP_ALL_KEYWORDS = True

# Custom field mappings
CUSTOMFIELD_MAP = {
    #'Bugzilla_field_name': 'Trac_customfield_name',
    #'op_sys': 'os',
    #'cf_featurewantedby': 'wanted_by',
    #'product': 'product'
}

# Bug comments that should not be imported.  Each entry in list should
# be a regular expression.
IGNORE_COMMENTS = [
   "^Created an attachment \(id="
]

###########################################################################
### You probably don't need to change any configuration past this line. ###
###########################################################################

# Bugzilla status to Trac status translation map.
#
# NOTE: bug activity is translated as well, which may cause bug
# activity to be deleted (e.g. resolved -> closed in Bugzilla
# would translate into closed -> closed in Trac, so we just ignore the
# change).
#
# There is some special magic for open in the code:  if there is no
# Bugzilla owner, open is mapped to 'new' instead.
STATUS_TRANSLATE = {
  "unconfirmed": "new",
  "open":        "assigned",
  "resolved":    "closed",
  "verified":    "closed",
  "released":    "closed"
}

# Translate Bugzilla statuses into Trac keywords.  This provides a way
# to retain the Bugzilla statuses in Trac.  e.g. when a bug is marked
# 'verified' in Bugzilla it will be assigned a VERIFIED keyword.
STATUS_KEYWORDS = {
  "verified": "VERIFIED",
  "released": "RELEASED"
}

# Some fields in Bugzilla do not have equivalents in Trac.  Changes in
# fields listed here will not be imported into the ticket change history,
# otherwise you'd see changes for fields that don't exist in Trac.
IGNORED_ACTIVITY_FIELDS = ["everconfirmed"]

# Regular expression and its replacement
# this expression will update references to bugs 1 - 99999 that
# have the form "bug 1" or "bug #1"
BUG_NO_RE = re.compile(r"\b(bug #?)([0-9]{1,5})\b", re.I)
BUG_NO_REPL = r"#\2"

###
### Script begins here
###

import os
import sys
import string
import StringIO

import MySQLdb
import MySQLdb.cursors
from trac.attachment import Attachment
from trac.env import Environment

if not hasattr(sys, 'setdefaultencoding'):
    reload(sys)

sys.setdefaultencoding('latin1')

# simulated Attachment class for trac.add
#class Attachment:
#    def __init__(self, name, data):
#        self.filename = name
#        self.file = StringIO.StringIO(data.tostring())

# simple field translation mapping.  if string not in
# mapping, just return string, otherwise return value
class FieldTranslator(dict):
    def __getitem__(self, item):
        if not dict.has_key(self, item):
            return item

        return dict.__getitem__(self, item)

statusXlator = FieldTranslator(STATUS_TRANSLATE)

class TracDatabase(object):
    def __init__(self, path):
        self.env = Environment(path)
        self.loginNameCache = {}
        self.fieldNameCache = {}
        from trac.db.api import DatabaseManager
	self.using_postgres = \
                DatabaseManager(self.env).connection_uri.startswith("postgres:")

    def hasTickets(self):
        return int(self.env.db_query("SELECT count(*) FROM ticket")[0][0] > 0)

    def assertNoTickets(self):
        if self.hasTickets():
            raise Exception("Will not modify database with existing tickets!")

    def setSeverityList(self, s):
        """Remove all severities, set them to `s`"""
        self.assertNoTickets()

        with self.env.db_transaction as db:
            db("DELETE FROM enum WHERE type='severity'")
            for value, i in s:
                print "  inserting severity '%s' - '%s'" % (value, i)
                db("""INSERT INTO enum (type, name, value)
                      VALUES (%s, %s, %s)""",
                   ("severity", value, i))

    def setPriorityList(self, s):
        """Remove all priorities, set them to `s`"""
        self.assertNoTickets()

        with self.env.db_transaction as db:
            db("DELETE FROM enum WHERE type='priority'")
            for value, i in s:
                print "  inserting priority '%s' - '%s'" % (value, i)
                db("INSERT INTO enum (type, name, value) VALUES (%s, %s, %s)",
                   ("priority", value, i))

    def setComponentList(self, l, key):
        """Remove all components, set them to `l`"""
        self.assertNoTickets()

        with self.env.db_transaction as db:
            db("DELETE FROM component")
            for comp in l:
                print "  inserting component '%s', owner '%s'" % \
                                (comp[key], comp['owner'])
                db("INSERT INTO component (name, owner) VALUES (%s, %s)",
                   (comp[key], comp['owner']))

    def setVersionList(self, v, key):
        """Remove all versions, set them to `v`"""
        self.assertNoTickets()

        with self.env.db_transaction as db:
            db("DELETE FROM version")
            for vers in v:
                print "  inserting version '%s'" % (vers[key])
                db("INSERT INTO version (name) VALUES (%s)",
                   (vers[key],))

    def setMilestoneList(self, m, key):
        """Remove all milestones, set them to `m`"""
        self.assertNoTickets()

        with self.env.db_transaction as db:
            db("DELETE FROM milestone")
            for ms in m:
                milestone = ms[key]
                print "  inserting milestone '%s'" % (milestone)
                db("INSERT INTO milestone (name) VALUES (%s)",
                   (milestone,))

    def addTicket(self, id, time, changetime, component, severity, priority,
                  owner, reporter, cc, version, milestone, status, resolution,
                  summary, description, keywords, customfields):

        desc = description
        type = "defect"

        if SEVERITIES:
            if severity.lower() == "enhancement":
                severity = "minor"
                type = "enhancement"

        else:
            if priority.lower() == "enhancement":
                priority = "minor"
                type = "enhancement"

        if PREFORMAT_COMMENTS:
            desc = '{{{\n%s\n}}}' % desc

        if REPLACE_BUG_NO:
            if BUG_NO_RE.search(desc):
                desc = re.sub(BUG_NO_RE, BUG_NO_REPL, desc)

        if PRIORITIES_MAP.has_key(priority):
            priority = PRIORITIES_MAP[priority]

        print "  inserting ticket %s -- %s" % (id, summary)

        with self.env.db_transaction as db:
            db("""INSERT INTO ticket (id, type, time, changetime, component,
                                      severity, priority, owner, reporter, cc,
                                      version, milestone, status, resolution,
                                      summary, description, keywords)
                  VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s,
                          %s, %s, %s, %s)
                  """, (id, type, datetime2epoch(time),
                        datetime2epoch(changetime), component, severity,
                        priority, owner, reporter, cc, version, milestone,
                        status.lower(), resolution, summary, desc, keywords))

        if self.using_postgres:
            with self.env.db_transaction as db:
                c = db.cursor()
                c.execute("""
                    SELECT SETVAL('ticket_id_seq', MAX(id)) FROM ticket;
                    SELECT SETVAL('report_id_seq', MAX(id)) FROM report""")
                ticket_id = db.get_last_id(c, 'ticket')

        # add all custom fields to ticket
        for name, value in customfields.iteritems():
            self.addTicketCustomField(ticket_id, name, value)

        return ticket_id

    def addTicketCustomField(self, ticket_id, field_name, field_value):
        if field_value == None:
            return
        self.env.db_transaction("""
            INSERT INTO ticket_custom (ticket, name, value) VALUES (%s, %s, %s)
            """, (ticket_id, field_name, field_value))

    def addTicketComment(self, ticket, time, author, value):
        comment = value

        if PREFORMAT_COMMENTS:
          comment = '{{{\n%s\n}}}' % comment

        if REPLACE_BUG_NO:
            if BUG_NO_RE.search(comment):
                comment = re.sub(BUG_NO_RE, BUG_NO_REPL, comment)

        with self.env.db_transaction as db:
            db("""INSERT INTO ticket_change (ticket, time, author, field,
                                             oldvalue, newvalue)
                  VALUES (%s, %s, %s, %s, %s, %s)
                  """, (ticket, datetime2epoch(time), author, 'comment', '',
                        comment))

    def addTicketChange(self, ticket, time, author, field, oldvalue, newvalue):

        if field == "owner":
            if LOGIN_MAP.has_key(oldvalue):
                oldvalue = LOGIN_MAP[oldvalue]
            if LOGIN_MAP.has_key(newvalue):
                newvalue = LOGIN_MAP[newvalue]

        if field == "priority":
            if PRIORITIES_MAP.has_key(oldvalue.lower()):
                oldvalue = PRIORITIES_MAP[oldvalue.lower()]
            if PRIORITIES_MAP.has_key(newvalue.lower()):
                newvalue = PRIORITIES_MAP[newvalue.lower()]

        # Doesn't make sense if we go from highest -> highest, for example.
        if oldvalue == newvalue:
            return

        with self.env.db_transaction as db:
            db("""INSERT INTO ticket_change (ticket, time, author, field,
                                             oldvalue, newvalue)
                  VALUES (%s, %s, %s, %s, %s, %s)
                  """, (ticket, datetime2epoch(time), author, field,
                        oldvalue, newvalue))

    def addAttachment(self, author, a):
        if a['filename'] != '':
            description = a['description']
            id = a['bug_id']
            filename = a['filename']
            filedata = StringIO.StringIO(a['thedata'])
            filesize = len(filedata.getvalue())
            time = a['creation_ts']
            print "    ->inserting attachment '%s' for ticket %s -- %s" % \
                    (filename, id, description)
            attachment = Attachment(self.env, 'ticket', id)
            attachment.author = author
            attachment.description = description
            attachment.insert(filename, filedata, filesize,
                              datetime2epoch(time))
            del attachment

    def getLoginName(self, cursor, userid):
        if userid not in self.loginNameCache:
            cursor.execute("SELECT * FROM profiles WHERE userid = %s", (userid))
            loginName = cursor.fetchall()

            if loginName:
                loginName = loginName[0]['login_name']
            else:
                print """WARNING: unknown bugzilla userid %d, recording as
                         anonymous""" % (userid)
                loginName = "anonymous"

            loginName = LOGIN_MAP.get(loginName, loginName)

            self.loginNameCache[userid] = loginName

        return self.loginNameCache[userid]

    def getFieldName(self, cursor, fieldid):
        if fieldid not in self.fieldNameCache:
            # fielddefs.fieldid got changed to fielddefs.id in Bugzilla
            # 2.23.3.
            if BZ_VERSION >= 2233:
                cursor.execute("SELECT * FROM fielddefs WHERE id = %s",
                               (fieldid))
            else:
                cursor.execute("SELECT * FROM fielddefs WHERE fieldid = %s",
                               (fieldid))
            fieldName = cursor.fetchall()

            if fieldName:
                fieldName = fieldName[0]['name'].lower()
            else:
                print "WARNING: unknown bugzilla fieldid %d, \
                                recording as unknown" % (userid)
                fieldName = "unknown"

            self.fieldNameCache[fieldid] = fieldName

        return self.fieldNameCache[fieldid]

def makeWhereClause(fieldName, values, negative=False):
    if not values:
        return ''
    if negative:
        connector, op = ' AND ', '!='
    else:
        connector, op = ' OR ', '='
    clause = connector.join(["%s %s '%s'" % (fieldName, op, value)
                             for value in values])
    return ' (' + clause + ')'

def convert(_db, _host, _user, _password, _env, _force):
    activityFields = FieldTranslator()

    # account for older versions of bugzilla
    print "Using Bugzilla v%s schema." % BZ_VERSION
    if BZ_VERSION == 2110:
        activityFields['removed'] = "oldvalue"
        activityFields['added'] = "newvalue"

    # init Bugzilla environment
    print "Bugzilla MySQL('%s':'%s':'%s':'%s'): connecting..." % \
            (_db, _host, _user, ("*" * len(_password)))
    mysql_con = MySQLdb.connect(host=_host,
                user=_user, passwd=_password, db=_db, compress=1,
                cursorclass=MySQLdb.cursors.DictCursor,
                charset='utf8')
    mysql_cur = mysql_con.cursor()

    # init Trac environment
    print "Trac SQLite('%s'): connecting..." % (_env)
    trac = TracDatabase(_env)

    # force mode...
    if _force == 1:
        print "\nCleaning all tickets..."
        with trac.env.db_transaction as db:
            db("DELETE FROM ticket_change")
            db("DELETE FROM ticket")
            db("DELETE FROM ticket_custom")
            db("DELETE FROM attachment")
        attachments_dir = os.path.join(os.path.normpath(trac.env.path),
                                       "attachments")
        # Straight from the Python documentation.
        for root, dirs, files in os.walk(attachments_dir, topdown=False):
            for name in files:
                os.remove(os.path.join(root, name))
            for name in dirs:
                os.rmdir(os.path.join(root, name))
        if not os.stat(attachments_dir):
            os.mkdir(attachments_dir)
        print "All tickets cleaned..."

    print "\n0. Filtering products..."
    if BZ_VERSION >= 2180:
        mysql_cur.execute("SELECT name FROM products")
    else:
        mysql_cur.execute("SELECT product AS name FROM products")
    products = []
    for line in mysql_cur.fetchall():
        product = line['name']
        if PRODUCTS and product not in PRODUCTS:
            continue
        if product in IGNORE_PRODUCTS:
            continue
        products.append(product)
    PRODUCTS[:] = products
    print "  Using products", " ".join(PRODUCTS)

    print "\n1. Import severities..."
    trac.setSeverityList(SEVERITIES)

    print "\n2. Import components..."
    if not COMPONENTS_FROM_PRODUCTS:
        if BZ_VERSION >= 2180:
            sql = """SELECT DISTINCT c.name AS name, c.initialowner AS owner
                               FROM components AS c, products AS p
                               WHERE c.product_id = p.id AND"""
            sql += makeWhereClause('p.name', PRODUCTS)
        else:
            sql = "SELECT value AS name, initialowner AS owner FROM components"
            sql += " WHERE" + makeWhereClause('program', PRODUCTS)
        mysql_cur.execute(sql)
        components = mysql_cur.fetchall()
        for component in components:
            component['owner'] = trac.getLoginName(mysql_cur,
                                                   component['owner'])
        trac.setComponentList(components, 'name')
    else:
        if BZ_VERSION >= 2180:
            sql = ("SELECT p.name AS product, c.name AS comp, "
                   " c.initialowner AS owner "
                   "FROM components c, products p "
                   "WHERE c.product_id = p.id AND" +
                   makeWhereClause('p.name', PRODUCTS))
        else:
            sql = ("SELECT program AS product, value AS comp, "
                   " initialowner AS owner "
                   "FROM components WHERE" +
                   makeWhereClause('program', PRODUCTS))
        mysql_cur.execute(sql)
        lines = mysql_cur.fetchall()
        all_components = {} # product -> components
        all_owners = {} # product, component -> owner
        for line in lines:
            product = line['product']
            comp = line['comp']
            owner = line['owner']
            all_components.setdefault(product, []).append(comp)
            all_owners[(product, comp)] = owner
        component_list = []
        for product, components in all_components.items():
            # find best default owner
            default = None
            for comp in DEFAULT_COMPONENTS:
                if comp in components:
                    default = comp
                    break
            if default is None:
                default = components[0]
            owner = all_owners[(product, default)]
            owner_name = trac.getLoginName(mysql_cur, owner)
            component_list.append({'product': product, 'owner': owner_name})
        trac.setComponentList(component_list, 'product')

    print "\n3. Import priorities..."
    trac.setPriorityList(PRIORITIES)

    print "\n4. Import versions..."
    if BZ_VERSION >= 2180:
        sql = """SELECT DISTINCTROW v.value AS value
                               FROM products p, versions v"""
        sql += " WHERE v.product_id = p.id AND"
        sql += makeWhereClause('p.name', PRODUCTS)
    else:
        sql = "SELECT DISTINCTROW value FROM versions"
        sql += " WHERE" + makeWhereClause('program', PRODUCTS)
    mysql_cur.execute(sql)
    versions = mysql_cur.fetchall()
    trac.setVersionList(versions, 'value')

    print "\n5. Import milestones..."
    sql = "SELECT DISTINCT value FROM milestones"
    sql += " WHERE" + makeWhereClause('value', IGNORE_MILESTONES, negative=True)
    mysql_cur.execute(sql)
    milestones = mysql_cur.fetchall()
    trac.setMilestoneList(milestones, 'value')

    print "\n6. Retrieving bugs..."
    if BZ_VERSION >= 2180:
        sql = """SELECT DISTINCT b.*, c.name AS component, p.name AS product
                            FROM bugs AS b, components AS c, products AS p """
        sql += " WHERE" + makeWhereClause('p.name', PRODUCTS)
        sql += " AND b.product_id = p.id"
        sql += " AND b.component_id = c.id"
        sql += " ORDER BY b.bug_id"
    else:
        sql = """SELECT DISTINCT b.*, c.value AS component, p.product AS product
                            FROM bugs AS b, components AS c, products AS p """
        sql += " WHERE" + makeWhereClause('p.product', PRODUCTS)
        sql += " AND b.product = p.product"
        sql += " AND b.component = c.value"
        sql += " ORDER BY b.bug_id"
    mysql_cur.execute(sql)
    bugs = mysql_cur.fetchall()

    print "\n7. Import bugs and bug activity..."
    for bug in bugs:

        bugid = bug['bug_id']

        ticket = {}
        keywords = []
        ticket['id'] = bugid
        ticket['time'] = bug['creation_ts']
        ticket['changetime'] = bug['delta_ts']
        if COMPONENTS_FROM_PRODUCTS:
            ticket['component'] = bug['product']
        else:
            ticket['component'] = bug['component']

        if SEVERITIES:
            ticket['severity'] = bug['bug_severity']
            ticket['priority'] = bug['priority'].lower()
        else:
            # use bugzilla severities as trac priorities, and ignore bugzilla
            # priorities
            ticket['severity'] = ''
            ticket['priority'] = bug['bug_severity']

        ticket['owner'] = trac.getLoginName(mysql_cur, bug['assigned_to'])
        ticket['reporter'] = trac.getLoginName(mysql_cur, bug['reporter'])

        # pack bugzilla fields into dictionary of trac custom field
        # names and values
        customfields = {}
        for bugfield, customfield in CUSTOMFIELD_MAP.iteritems():
            customfields[customfield] = bug[bugfield]
        ticket['customfields'] = customfields

        mysql_cur.execute("SELECT * FROM cc WHERE bug_id = %s", bugid)
        cc_records = mysql_cur.fetchall()
        cc_list = []
        for cc in cc_records:
            cc_list.append(trac.getLoginName(mysql_cur, cc['who']))
        cc_list = [cc for cc in cc_list if cc not in IGNORE_CC]
        ticket['cc'] = string.join(cc_list, ', ')

        ticket['version'] = bug['version']

        target_milestone = bug['target_milestone']
        if target_milestone in IGNORE_MILESTONES:
            target_milestone = ''
        ticket['milestone'] = target_milestone

        bug_status = bug['bug_status'].lower()
        ticket['status'] = statusXlator[bug_status]
        ticket['resolution'] = bug['resolution'].lower()

        # a bit of extra work to do open tickets
        if bug_status == 'open':
            if owner != '':
                ticket['status'] = 'assigned'
            else:
                ticket['status'] = 'new'

        ticket['summary'] = bug['short_desc']

        mysql_cur.execute("SELECT * FROM longdescs WHERE bug_id = %s" % bugid)
        longdescs = list(mysql_cur.fetchall())

        # check for empty 'longdescs[0]' field...
        if len(longdescs) == 0:
            ticket['description'] = ''
        else:
            ticket['description'] = longdescs[0]['thetext']
            del longdescs[0]

        for desc in longdescs:
            ignore = False
            for comment in IGNORE_COMMENTS:
                if re.match(comment, desc['thetext']):
                    ignore = True

            if ignore:
                    continue

            trac.addTicketComment(ticket=bugid,
                time = desc['bug_when'],
                author=trac.getLoginName(mysql_cur, desc['who']),
                value = desc['thetext'])

        mysql_cur.execute("""SELECT * FROM bugs_activity WHERE bug_id = %s
                             ORDER BY bug_when""" % bugid)
        bugs_activity = mysql_cur.fetchall()
        resolution = ''
        ticketChanges = []
        keywords = []
        for activity in bugs_activity:
            field_name = trac.getFieldName(mysql_cur, activity['fieldid']).lower()

            removed = activity[activityFields['removed']]
            added = activity[activityFields['added']]

            # statuses and resolutions are in lowercase in trac
            if field_name == "resolution" or field_name == "bug_status":
                removed = removed.lower()
                added = added.lower()

            # remember most recent resolution, we need this later
            if field_name == "resolution":
                resolution = added.lower()

            add_keywords = []
            remove_keywords = []

            # convert bugzilla field names...
            if field_name == "bug_severity":
                if SEVERITIES:
                    field_name = "severity"
                else:
                    field_name = "priority"
            elif field_name == "assigned_to":
                field_name = "owner"
            elif field_name == "bug_status":
                field_name = "status"
                if removed in STATUS_KEYWORDS:
                    remove_keywords.append(STATUS_KEYWORDS[removed])
                if added in STATUS_KEYWORDS:
                    add_keywords.append(STATUS_KEYWORDS[added])
                added = statusXlator[added]
                removed = statusXlator[removed]
            elif field_name == "short_desc":
                field_name = "summary"
            elif field_name == "product" and COMPONENTS_FROM_PRODUCTS:
                field_name = "component"
            elif ((field_name == "product" and not COMPONENTS_FROM_PRODUCTS) or
                  (field_name == "component" and COMPONENTS_FROM_PRODUCTS)):
                if MAP_ALL_KEYWORDS or removed in KEYWORDS_MAPPING:
                    kw = KEYWORDS_MAPPING.get(removed, removed)
                    if kw:
                        remove_keywords.append(kw)
                if MAP_ALL_KEYWORDS or added in KEYWORDS_MAPPING:
                    kw = KEYWORDS_MAPPING.get(added, added)
                    if kw:
                        add_keywords.append(kw)
                if field_name == "component":
                    # just keep the keyword change
                    added = removed = ""
            elif field_name == "target_milestone":
                field_name = "milestone"
                if added in IGNORE_MILESTONES:
                    added = ""
                if removed in IGNORE_MILESTONES:
                    removed = ""

            ticketChange = {}
            ticketChange['ticket'] = bugid
            ticketChange['time'] = activity['bug_when']
            ticketChange['author'] = trac.getLoginName(mysql_cur,
                                                       activity['who'])
            ticketChange['field'] = field_name
            ticketChange['oldvalue'] = removed
            ticketChange['newvalue'] = added

            if add_keywords or remove_keywords:
                # ensure removed ones are in old
                old_keywords = keywords + [kw for kw in remove_keywords if kw
                                           not in keywords]
                # remove from new
                keywords = [kw for kw in keywords if kw not in remove_keywords]
                # add to new
                keywords += [kw for kw in add_keywords if kw not in keywords]
                if old_keywords != keywords:
                    ticketChangeKw = ticketChange.copy()
                    ticketChangeKw['field'] = "keywords"
                    ticketChangeKw['oldvalue'] = ' '.join(old_keywords)
                    ticketChangeKw['newvalue'] = ' '.join(keywords)
                    ticketChanges.append(ticketChangeKw)

            if field_name in IGNORED_ACTIVITY_FIELDS:
                continue

            # Skip changes that have no effect (think translation!).
            if added == removed:
                continue

            # Bugzilla splits large summary changes into two records.
            for oldChange in ticketChanges:
              if (field_name == "summary"
                  and oldChange['field'] == ticketChange['field']
                  and oldChange['time'] == ticketChange['time']
                  and oldChange['author'] == ticketChange['author']):
                  oldChange['oldvalue'] += " " + ticketChange['oldvalue']
                  oldChange['newvalue'] += " " + ticketChange['newvalue']
                  break
              # cc and attachments.isobsolete sometime appear
              # in different activities with same time
              if ((field_name == "cc" or field_name == "attachments.isobsolete") \
                  and oldChange['time'] == ticketChange['time']):
                  oldChange['newvalue'] += ", " + ticketChange['newvalue']
                  break
            else:
                ticketChanges.append (ticketChange)

        for ticketChange in ticketChanges:
            trac.addTicketChange (**ticketChange)

        # For some reason, bugzilla v2.11 seems to clear the resolution
        # when you mark a bug as closed.  Let's remember it and restore
        # it if the ticket is closed but there's no resolution.
        if not ticket['resolution'] and ticket['status'] == "closed":
            ticket['resolution'] = resolution

        bug_status = bug['bug_status']
        if bug_status in STATUS_KEYWORDS:
            kw = STATUS_KEYWORDS[bug_status]
            if kw not in keywords:
                keywords.append(kw)

        product = bug['product']
        if product in KEYWORDS_MAPPING and not COMPONENTS_FROM_PRODUCTS:
            kw = KEYWORDS_MAPPING.get(product, product)
            if kw and kw not in keywords:
                keywords.append(kw)

        component = bug['component']
        if (COMPONENTS_FROM_PRODUCTS and \
            (MAP_ALL_KEYWORDS or component in KEYWORDS_MAPPING)):
            kw = KEYWORDS_MAPPING.get(component, component)
            if kw and kw not in keywords:
                keywords.append(kw)

        ticket['keywords'] = string.join(keywords)
        ticketid = trac.addTicket(**ticket)

        if BZ_VERSION >= 2210:
            mysql_cur.execute("SELECT attachments.*, attach_data.thedata "
                              "FROM attachments, attach_data "
                              "WHERE attachments.bug_id = %s AND "
                              "attachments.attach_id = attach_data.id" % bugid)
        else:
            mysql_cur.execute("SELECT * FROM attachments WHERE bug_id = %s" %
                              bugid)
        attachments = mysql_cur.fetchall()
        for a in attachments:
            author = trac.getLoginName(mysql_cur, a['submitter_id'])
            trac.addAttachment(author, a)

    print "\n8. Importing users and passwords..."
    if BZ_VERSION >= 2164:
        selectlogins = "SELECT login_name, cryptpassword FROM profiles";
        if IGNORE_DISABLED_USERS:
            selectlogins = selectlogins + " WHERE disabledtext=''"
        mysql_cur.execute(selectlogins)
        users = mysql_cur.fetchall()
    else:
        users = ()
    htpasswd = file("htpasswd", 'w')
    for user in users:
        if LOGIN_MAP.has_key(user['login_name']):
            login = LOGIN_MAP[user['login_name']]
        else:
            login = user['login_name']

        htpasswd.write(login + ":" + user['cryptpassword'] + "\n")

    htpasswd.close()
    print "  Bugzilla users converted to htpasswd format, see 'htpasswd'."

    print "\nAll tickets converted."

def log(msg):
    print "DEBUG: %s" % (msg)

def datetime2epoch(dt) :
    import time
    return time.mktime(dt.timetuple()) * 1000000

def usage():
    print """bugzilla2trac - Imports a bug database from Bugzilla into Trac.

Usage: bugzilla2trac.py [options]

Available Options:
  --db <MySQL dbname>              - Bugzilla's database name
  --tracenv /path/to/trac/env      - Full path to Trac db environment
  -h | --host <MySQL hostname>     - Bugzilla's DNS host name
  -u | --user <MySQL username>     - Effective Bugzilla's database user
  -p | --passwd <MySQL password>   - Bugzilla's user password
  -c | --clean                     - Remove current Trac tickets before
                                     importing
  -n | --noseverities              - import Bugzilla severities as Trac
                                     priorities and forget Bugzilla priorities
  --help | help                    - This help info

Additional configuration options can be defined directly in the script.
"""
    sys.exit(0)

def main():
    global BZ_DB, BZ_HOST, BZ_USER, BZ_PASSWORD, TRAC_ENV, TRAC_CLEAN
    global SEVERITIES, PRIORITIES, PRIORITIES_MAP
    if len (sys.argv) > 1:
    	if sys.argv[1] in ['--help','help'] or len(sys.argv) < 4:
    	    usage()
    	iter = 1
    	while iter < len(sys.argv):
    	    if sys.argv[iter] in ['--db'] and iter+1 < len(sys.argv):
    	        BZ_DB = sys.argv[iter+1]
    	        iter = iter + 1
    	    elif sys.argv[iter] in ['-h', '--host'] and iter+1 < len(sys.argv):
    	        BZ_HOST = sys.argv[iter+1]
    	        iter = iter + 1
    	    elif sys.argv[iter] in ['-u', '--user'] and iter+1 < len(sys.argv):
    	        BZ_USER = sys.argv[iter+1]
    	        iter = iter + 1
    	    elif sys.argv[iter] in ['-p', '--passwd'] and iter+1 < len(sys.argv):
    	        BZ_PASSWORD = sys.argv[iter+1]
    	        iter = iter + 1
    	    elif sys.argv[iter] in ['--tracenv'] and iter+1 < len(sys.argv):
    	        TRAC_ENV = sys.argv[iter+1]
    	        iter = iter + 1
    	    elif sys.argv[iter] in ['-c', '--clean']:
    	        TRAC_CLEAN = 1
            elif sys.argv[iter] in ['-n', '--noseverities']:
                # treat Bugzilla severites as Trac priorities
                PRIORITIES = SEVERITIES
                SEVERITIES = []
                PRIORITIES_MAP = {}
    	    else:
    	        print "Error: unknown parameter: " + sys.argv[iter]
    	        sys.exit(0)
    	    iter = iter + 1

    convert(BZ_DB, BZ_HOST, BZ_USER, BZ_PASSWORD, TRAC_ENV, TRAC_CLEAN)

if __name__ == '__main__':
    main()


text:
package fakes

import (
	bosherr "github.com/cloudfoundry/bosh-utils/errors"

	bideplmanifest "github.com/cloudfoundry/bosh-init/deployment/manifest"
	biinstall "github.com/cloudfoundry/bosh-init/installation"
	birelsetmanifest "github.com/cloudfoundry/bosh-init/release/set/manifest"
)

type FakeValidator struct {
	ValidateInputs             []ValidateInput
	ValidateReleaseJobsInputs  []ValidateReleaseJobsInput
	validateOutputs            []ValidateOutput
	validateReleaseJobsOutputs []ValidateReleaseJobsOutput
}

func NewFakeValidator() *FakeValidator {
	return &FakeValidator{
		ValidateInputs:             []ValidateInput{},
		ValidateReleaseJobsInputs:  []ValidateReleaseJobsInput{},
		validateOutputs:            []ValidateOutput{},
		validateReleaseJobsOutputs: []ValidateReleaseJobsOutput{},
	}
}

type ValidateInput struct {
	Manifest           bideplmanifest.Manifest
	ReleaseSetManifest birelsetmanifest.Manifest
}

type ValidateReleaseJobsInput struct {
	Manifest       bideplmanifest.Manifest
	ReleaseManager biinstall.ReleaseManager
}

type ValidateOutput struct {
	Err error
}

type ValidateReleaseJobsOutput struct {
	Err error
}

func (v *FakeValidator) Validate(manifest bideplmanifest.Manifest, releaseSetManifest birelsetmanifest.Manifest) error {
	v.ValidateInputs = append(v.ValidateInputs, ValidateInput{
		Manifest:           manifest,
		ReleaseSetManifest: releaseSetManifest,
	})

	if len(v.validateOutputs) == 0 {
		return bosherr.Errorf("Unexpected FakeValidator.Validate(manifest, releaseSetManifest) called with manifest: %#v", manifest)
	}
	validateOutput := v.validateOutputs[0]
	v.validateOutputs = v.validateOutputs[1:]
	return validateOutput.Err
}

func (v *FakeValidator) ValidateReleaseJobs(manifest bideplmanifest.Manifest, releaseManager biinstall.ReleaseManager) error {
	v.ValidateReleaseJobsInputs = append(v.ValidateReleaseJobsInputs, ValidateReleaseJobsInput{
		Manifest:       manifest,
		ReleaseManager: releaseManager,
	})

	if len(v.validateReleaseJobsOutputs) == 0 {
		return bosherr.Errorf("Unexpected FakeValidator.ValidateReleaseJobs(manifest, releaseManager) called with manifest: %#v", manifest)
	}
	validateReleaseJobsOutput := v.validateReleaseJobsOutputs[0]
	v.validateReleaseJobsOutputs = v.validateReleaseJobsOutputs[1:]
	return validateReleaseJobsOutput.Err
}

func (v *FakeValidator) SetValidateBehavior(outputs []ValidateOutput) {
	v.validateOutputs = outputs
}

func (v *FakeValidator) SetValidateReleaseJobsBehavior(outputs []ValidateReleaseJobsOutput) {
	v.validateReleaseJobsOutputs = outputs
}

redpajama_set_name: RedPajamaGithub


text:
/*	$NetBSD: zone2bdb.c,v 1.3 2012/06/05 00:40:02 christos Exp $	*/

/*
 * Copyright (C) 2002  Nuno M. Rodrigues.
 *
 * Permission to use, copy, modify, and distribute this software for any
 * purpose with or without fee is hereby granted, provided that the above
 * copyright notice and this permission notice appear in all copies.
 *
 * THE SOFTWARE IS PROVIDED "AS IS" AND NUNO M. RODRIGUES
 * DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL
 * INTERNET SOFTWARE CONSORTIUM BE LIABLE FOR ANY SPECIAL, DIRECT,
 * INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING
 * FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
 * NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
 * WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 */

/* Id: zone2bdb.c,v 1.3 2009/09/01 00:22:26 jinmei Exp  */

#include <stdio.h>

#include <isc/mem.h>
#include <isc/result.h>
#include <isc/types.h>
#include <isc/util.h>

#include <dns/db.h>
#include <dns/dbiterator.h>
#include <dns/fixedname.h>
#include <dns/name.h>
#include <dns/rdata.h>
#include <dns/rdataset.h>
#include <dns/rdatasetiter.h>
#include <dns/rdatatype.h>
#include <dns/ttl.h>
#include <dns/types.h>

#include <db.h>

#define MAX_RDATATEXT	63 + 4 + 65535 + 2	/* ttl + type + rdata + sep */

/*
 * Returns a valid 'DB' handle.
 *
 * Requires:
 *	'file' is a valid non-existant path.
 */
DB *
bdb_init(const char *file)
{
	DB *db;

	REQUIRE(db_create(&db, NULL, 0) == 0);
	REQUIRE(db->set_flags(db, DB_DUP) == 0);
	REQUIRE(db->open(db, file, NULL, DB_HASH, DB_CREATE | DB_EXCL, 0) == 0);

	return db;
}

/*
 * Puts resource record data on 'db'.
 */
isc_result_t
bdb_putrdata(DB *db, dns_name_t *name, dns_ttl_t ttl, dns_rdata_t *rdata)
{
	static DBT key, data;
	isc_buffer_t keybuf, databuf;
	char nametext[DNS_NAME_MAXTEXT];
	char rdatatext[MAX_RDATATEXT];

	isc_buffer_init(&keybuf, nametext, DNS_NAME_MAXTEXT);

	dns_name_totext(name, ISC_TRUE, &keybuf);

	key.data = isc_buffer_base(&keybuf);
	key.size = isc_buffer_usedlength(&keybuf);

	isc_buffer_init(&databuf, rdatatext, MAX_RDATATEXT);

	dns_ttl_totext(ttl, ISC_FALSE, &databuf);
	*(char *)isc_buffer_used(&databuf) = ' ';
	isc_buffer_add(&databuf, 1);

	dns_rdatatype_totext(rdata->type, &databuf);	/* XXX private data */
	*(char *)isc_buffer_used(&databuf) = ' ';
	isc_buffer_add(&databuf, 1);

	dns_rdata_totext(rdata, NULL, &databuf);

	data.data = isc_buffer_base(&databuf);
	data.size = isc_buffer_usedlength(&databuf);

	REQUIRE(db->put(db, NULL, &key, &data, 0) == 0);

	return ISC_R_SUCCESS;
}

isc_result_t
bdb_destroy(DB *db)
{

	return (db->close(db, 0) == 0) ? ISC_R_SUCCESS : ISC_R_FAILURE;
}

void
usage(const char *prog)
{

	fprintf(stderr, "Usage: %s <origin> <zonefile> <db>\n", prog);
	exit(1);
}

int
main(int argc, char *argv[])
{
	isc_mem_t *mctx = NULL;
	isc_buffer_t b;
	int n;
	dns_fixedname_t origin, name;
	dns_db_t *db = NULL;
	dns_dbiterator_t *dbiter = NULL;
	isc_result_t res;
	dns_dbnode_t *node = NULL;
	dns_rdataset_t rdataset;
	dns_rdatasetiter_t *rdatasetiter = NULL;
	dns_rdata_t rdata;
	DB *bdb;

	if (argc != 4) usage(*argv);

	REQUIRE(isc_mem_create(0, 0, &mctx) == ISC_R_SUCCESS);

	n = strlen(argv[1]);
	isc_buffer_init(&b, argv[1], n);
	isc_buffer_add(&b, n);

	dns_fixedname_init(&origin);

	REQUIRE(dns_name_fromtext(dns_fixedname_name(&origin), &b, dns_rootname,
				  0, NULL) == ISC_R_SUCCESS);
	REQUIRE(dns_db_create(mctx, "rbt", dns_fixedname_name(&origin),
			      dns_dbtype_zone, dns_rdataclass_in, 0, NULL,
			      &db) == ISC_R_SUCCESS);

	REQUIRE(dns_db_load(db, argv[2]) == ISC_R_SUCCESS);

	REQUIRE(dns_db_createiterator(db, 0, &dbiter) == ISC_R_SUCCESS);

	dns_rdataset_init(&rdataset);
	dns_rdata_init(&rdata);
	dns_fixedname_init(&name);
	bdb = bdb_init(argv[3]);

	for (res = dns_dbiterator_first(dbiter); res == ISC_R_SUCCESS;
	    res = dns_dbiterator_next(dbiter)) {
		dns_dbiterator_current(dbiter, &node, dns_fixedname_name(&name));
		REQUIRE(dns_db_allrdatasets(db, node, NULL, 0, &rdatasetiter)
		    == ISC_R_SUCCESS);

		for (res = dns_rdatasetiter_first(rdatasetiter);
		    res == ISC_R_SUCCESS;
		    res = dns_rdatasetiter_next(rdatasetiter)) {
			dns_rdatasetiter_current(rdatasetiter, &rdataset);

			res = dns_rdataset_first(&rdataset);
			while (res == ISC_R_SUCCESS) {
				dns_rdataset_current(&rdataset, &rdata);
				REQUIRE(bdb_putrdata(bdb,
						     dns_fixedname_name(&name),
						     rdataset.ttl, &rdata)
					== ISC_R_SUCCESS);

				dns_rdata_reset(&rdata);
				res = dns_rdataset_next(&rdataset);
			}

			dns_rdataset_disassociate(&rdataset);
		}
		dns_rdatasetiter_destroy(&rdatasetiter);
		dns_db_detachnode(db, &node);
	}
	dns_dbiterator_destroy(&dbiter);

	REQUIRE(bdb_destroy(bdb) == ISC_R_SUCCESS);

	return 0;
}


text:
include Nanoc::Helpers::Blogging
include Nanoc::Helpers::Rendering
include Nanoc::Helpers::LinkTo
include Nanoc::Helpers::Tagging
require 'fileutils'
require 'redcarpet'

def blog_route(item)
  if not item.identifier.match(/\d{4}-\d{2}-\d{2}-/)
    raise "Ill-formed blog date."
  end
  year, name = item.identifier[0..11], item.identifier[12..-1]
  year.gsub('-', '/') + name.chop + '.html'
end

def item_url(item, site=@site.config[:base_url])
  [site,  blog_route(item)].join
end

def item_title(item)
  item.attributes[:title] || "(No title - man, that's odd)"
end


text:
require 'yt/models/base'

module Yt
  module Models
    class DeviceFlow < Base
      def initialize(options = {})
        @data = options[:data]
      end

      def device_code
        @device_code ||= @data['device_code']
      end

      def user_code
        @user_code ||= @data['user_code']
      end

      def verification_url
        @verification_url ||= @data['verification_url']
      end
    end
  end
end


text:
//---------------------------------------------------------------------
// <copyright file="ClrPerspective.cs" company="Microsoft">
//      Copyright (c) Microsoft Corporation.  All rights reserved.
// </copyright>
//
// @owner       [....]
// @backupOwner [....]
//---------------------------------------------------------------------

namespace System.Data.Metadata.Edm
{
    using System.Collections.Generic;
    using System.Data.Mapping;
    using System.Diagnostics;

    /// <summary>
    /// Internal helper class for query
    /// </summary>
    internal sealed class ClrPerspective : Perspective
    {
        private EntityContainer _defaultContainer;

        #region Constructors
        /// <summary>
        /// Creates a new instance of perspective class so that query can work
        /// ignorant of all spaces
        /// </summary>
        /// <param name="metadataWorkspace"></param>
        internal ClrPerspective(MetadataWorkspace metadataWorkspace)
            : base(metadataWorkspace, DataSpace.CSpace)
        {
        }
        #endregion //Constructors

        #region Methods
        /// <summary>
        /// Given a clrType attempt to return the corresponding target type from
        /// the worksapce
        /// </summary>
        /// <param name="clrType">The clr type to resolve</param>
        /// <param name="outTypeUsage">an out param for the typeUsage to be resolved to</param>
        /// <returns>true if a TypeUsage can be found for the target type</returns>
        internal bool TryGetType(Type clrType, out TypeUsage outTypeUsage)
        {
            return TryGetTypeByName(clrType.FullName,
                                    false /*ignoreCase*/,
                                    out outTypeUsage);
        }

        /// <summary>
        /// Given the type in the target space and the member name in the source space,
        /// get the corresponding member in the target space
        /// For e.g.  consider a Conceptual Type Foo with a member bar and a CLR type
        /// XFoo with a member YBar. If one has a reference to Foo one can
        /// invoke GetMember(Foo,"YBar") to retrieve the member metadata for bar
        /// </summary>
        /// <param name="type">The type in the target perspective</param>
        /// <param name="memberName">the name of the member in the source perspective</param>
        /// <param name="ignoreCase">true for case-insensitive lookup</param>
        /// <param name="outMember">returns the edmMember if a match is found</param>
        /// <returns>true if a match is found, otherwise false</returns>
        internal override bool TryGetMember(StructuralType type, String memberName, bool ignoreCase, out EdmMember outMember)
        {
            outMember = null;
            Map map = null;

            if (this.MetadataWorkspace.TryGetMap(type, DataSpace.OCSpace, out map))
            {
                ObjectTypeMapping objectTypeMap = map as ObjectTypeMapping;

                if (objectTypeMap!=null)
                {
                    ObjectMemberMapping objPropertyMapping = objectTypeMap.GetMemberMapForClrMember(memberName, ignoreCase);
                    if (null != objPropertyMapping)
                    {
                        outMember = objPropertyMapping.EdmMember;
                        return true;
                    }
                }
            }
            return false;
        }

        /// <summary>
        /// Look up a type in the target data space based upon the fullName
        /// </summary>
        /// <param name="fullName">fullName</param>
        /// <param name="ignoreCase">true for case-insensitive lookup</param>
        /// <param name="typeUsage">The type usage object to return</param>
        /// <returns>True if the retrieval succeeded</returns>
        internal override bool TryGetTypeByName(string fullName, bool ignoreCase, out TypeUsage typeUsage)
        {
            typeUsage = null;
            Map map = null;

            // From ClrPerspective, we should not allow anything from SSpace. So make sure that the CSpace type does not
            // have the Target attribute
            if (this.MetadataWorkspace.TryGetMap(fullName, DataSpace.OSpace, ignoreCase, DataSpace.OCSpace, out map))
            {
                // Check if it's primitive type, if so, then use the MetadataWorkspace to get the mapped primitive type
                if (map.EdmItem.BuiltInTypeKind == BuiltInTypeKind.PrimitiveType)
                {
                    // Reassign the variable with the provider primitive type, then create the type usage
                    PrimitiveType primitiveType = this.MetadataWorkspace.GetMappedPrimitiveType(((PrimitiveType)map.EdmItem).PrimitiveTypeKind, DataSpace.CSpace);
                    if (primitiveType != null)
                    {
                        typeUsage = EdmProviderManifest.Instance.GetCanonicalModelTypeUsage(primitiveType.PrimitiveTypeKind);
                    }
                }
                else
                {
                    Debug.Assert(((GlobalItem)map.EdmItem).DataSpace == DataSpace.CSpace);
                    typeUsage = GetMappedTypeUsage(map);
                }
            }

            return (null != typeUsage);
        }

        /// <summary>
        /// get the default container
        /// </summary>
        /// <returns>The default container</returns>
        internal override EntityContainer GetDefaultContainer()
        {
            return _defaultContainer;
        }

        internal void SetDefaultContainer(string defaultContainerName)
        {
            EntityContainer container = null;
            if (!String.IsNullOrEmpty(defaultContainerName))
            {
                if (!MetadataWorkspace.TryGetEntityContainer(defaultContainerName, DataSpace.CSpace, out container))
                {
                    throw EntityUtil.InvalidDefaultContainerName("defaultContainerName", defaultContainerName);
                }
            }
            _defaultContainer = container;
        }

        /// <summary>
        /// Given a map, dereference the EdmItem, ensure that it is
        /// an EdmType and return a TypeUsage for the type, otherwise
        /// return null.
        /// </summary>
        /// <param name="map">The OC map to use to get the EdmType</param>
        /// <returns>A TypeUsage for the mapped EdmType or null if no EdmType was mapped</returns>
        private static TypeUsage GetMappedTypeUsage(Map map)
        {
            TypeUsage typeUsage = null;
            if (null != map)
            {
                MetadataItem item = map.EdmItem;
                EdmType edmItem = item as EdmType;
                if (null != item && edmItem!=null)
                {
                    typeUsage = TypeUsage.Create(edmItem);
                }
            }
            return typeUsage;
        }
        #endregion
    }
}


text:
/* flexdef - definitions file for flex */

/*-
 * Copyright (c) 1990 The Regents of the University of California.
 * All rights reserved.
 *
 * This code is derived from software contributed to Berkeley by
 * Vern Paxson.
 *
 * The United States Government has rights in this work pursuant
 * to contract no. DE-AC03-76SF00098 between the United States
 * Department of Energy and the University of California.
 *
 * Redistribution and use in source and binary forms with or without
 * modification are permitted provided that: (1) source distributions retain
 * this entire copyright notice and comment, and (2) distributions including
 * binaries display the following acknowledgement:  ``This product includes
 * software developed by the University of California, Berkeley and its
 * contributors'' in the documentation or other materials provided with the
 * distribution and in all advertising materials mentioning features or use
 * of this software.  Neither the name of the University nor the names of
 * its contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR IMPLIED
 * WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
 */

/* @(#) $Header$ (LBL) */

#include <stdio.h>
#include <ctype.h>

#include "config.h"

#ifdef __TURBOC__
#define HAVE_STRING_H 1
#define MS_DOS 1
#ifndef __STDC__
#define __STDC__ 1
#endif
 #pragma warn -pro
 #pragma warn -rch
 #pragma warn -use
 #pragma warn -aus
 #pragma warn -par
 #pragma warn -pia
#endif

#ifdef HAVE_STRING_H
#include <string.h>
#else
#include <strings.h>
#endif

#ifdef HAVE_SYS_TYPES_H
#include <sys/types.h>
#endif

#ifdef HAVE_MALLOC_H
#include <malloc.h>
#endif

#ifdef STDC_HEADERS
#include <stdlib.h>
#endif

/* As an aid for the internationalization patch to flex, which
 * is maintained outside this distribution for copyright reasons.
 */
#define _(String) (String)

/* Always be prepared to generate an 8-bit scanner. */
#define CSIZE 256
#define Char unsigned char

/* Size of input alphabet - should be size of ASCII set. */
#ifndef DEFAULT_CSIZE
#define DEFAULT_CSIZE 128
#endif

#ifndef PROTO
#if __STDC__
#define PROTO(proto) proto
#else
#define PROTO(proto) ()
#endif
#endif

#ifdef VMS
#ifndef __VMS_POSIX
#define unlink remove
#define SHORT_FILE_NAMES
#endif
#endif

#ifdef MS_DOS
#define SHORT_FILE_NAMES
#endif

/* Maximum line length we'll have to deal with. */
#define MAXLINE 2048

#ifndef MIN
#define MIN(x,y) ((x) < (y) ? (x) : (y))
#endif
#ifndef MAX
#define MAX(x,y) ((x) > (y) ? (x) : (y))
#endif
#ifndef ABS
#define ABS(x) ((x) < 0 ? -(x) : (x))
#endif

/* ANSI C does not guarantee that isascii() is defined */
#ifndef isascii
#define isascii(c) ((c) <= 0177)
#endif

#define true 1
#define false 0
#define unspecified -1

/* Special chk[] values marking the slots taking by end-of-buffer and action
 * numbers.
 */
#define EOB_POSITION -1
#define ACTION_POSITION -2

/* Number of data items per line for -f output. */
#define NUMDATAITEMS 10

/* Number of lines of data in -f output before inserting a blank line for
 * readability.
 */
#define NUMDATALINES 10

/* transition_struct_out() definitions. */
#define TRANS_STRUCT_PRINT_LENGTH 14

/* Returns true if an nfa state has an epsilon out-transition slot
 * that can be used.  This definition is currently not used.
 */
#define FREE_EPSILON(state) \
	(transchar[state] == SYM_EPSILON && \
	 trans2[state] == NO_TRANSITION && \
	 finalst[state] != state)

/* Returns true if an nfa state has an epsilon out-transition character
 * and both slots are free
 */
#define SUPER_FREE_EPSILON(state) \
	(transchar[state] == SYM_EPSILON && \
	 trans1[state] == NO_TRANSITION) \

/* Maximum number of NFA states that can comprise a DFA state.  It's real
 * big because if there's a lot of rules, the initial state will have a
 * huge epsilon closure.
 */
#define INITIAL_MAX_DFA_SIZE 750
#define MAX_DFA_SIZE_INCREMENT 750

/* A note on the following masks.  They are used to mark accepting numbers
 * as being special.  As such, they implicitly limit the number of accepting
 * numbers (i.e., rules) because if there are too many rules the rule numbers
 * will overload the mask bits.  Fortunately, this limit is \large/ (0x2000 ==
 * 8192) so unlikely to actually cause any problems.  A check is made in
 * new_rule() to ensure that this limit is not reached.
 */

/* Mask to mark a trailing context accepting number. */
#define YY_TRAILING_MASK 0x2000

/* Mask to mark the accepting number of the "head" of a trailing context
 * rule.
 */
#define YY_TRAILING_HEAD_MASK 0x4000

/* Maximum number of rules, as outlined in the above note. */
#define MAX_RULE (YY_TRAILING_MASK - 1)

/* NIL must be 0.  If not, its special meaning when making equivalence classes
 * (it marks the representative of a given e.c.) will be unidentifiable.
 */
#define NIL 0

#define JAM -1	/* to mark a missing DFA transition */
#define NO_TRANSITION NIL
#define UNIQUE -1	/* marks a symbol as an e.c. representative */
#define INFINITY -1	/* for x{5,} constructions */

#define INITIAL_MAX_CCLS 100	/* max number of unique character classes */
#define MAX_CCLS_INCREMENT 100

/* Size of table holding members of character classes. */
#define INITIAL_MAX_CCL_TBL_SIZE 500
#define MAX_CCL_TBL_SIZE_INCREMENT 250

#define INITIAL_MAX_RULES 100	/* default maximum number of rules */
#define MAX_RULES_INCREMENT 100

#define INITIAL_MNS 2000	/* default maximum number of nfa states */
#define MNS_INCREMENT 1000	/* amount to bump above by if it's not enough */

#define INITIAL_MAX_DFAS 1000	/* default maximum number of dfa states */
#define MAX_DFAS_INCREMENT 1000

#define JAMSTATE -32766	/* marks a reference to the state that always jams */

/* Maximum number of NFA states. */
#define MAXIMUM_MNS 31999

/* Enough so that if it's subtracted from an NFA state number, the result
 * is guaranteed to be negative.
 */
#define MARKER_DIFFERENCE (MAXIMUM_MNS+2)

/* Maximum number of nxt/chk pairs for non-templates. */
#define INITIAL_MAX_XPAIRS 2000
#define MAX_XPAIRS_INCREMENT 2000

/* Maximum number of nxt/chk pairs needed for templates. */
#define INITIAL_MAX_TEMPLATE_XPAIRS 2500
#define MAX_TEMPLATE_XPAIRS_INCREMENT 2500

#define SYM_EPSILON (CSIZE + 1)	/* to mark transitions on the symbol epsilon */

#define INITIAL_MAX_SCS 40	/* maximum number of start conditions */
#define MAX_SCS_INCREMENT 40	/* amount to bump by if it's not enough */

#define ONE_STACK_SIZE 500	/* stack of states with only one out-transition */
#define SAME_TRANS -1	/* transition is the same as "default" entry for state */

/* The following percentages are used to tune table compression:

 * The percentage the number of out-transitions a state must be of the
 * number of equivalence classes in order to be considered for table
 * compaction by using protos.
 */
#define PROTO_SIZE_PERCENTAGE 15

/* The percentage the number of homogeneous out-transitions of a state
 * must be of the number of total out-transitions of the state in order
 * that the state's transition table is first compared with a potential
 * template of the most common out-transition instead of with the first
 * proto in the proto queue.
 */
#define CHECK_COM_PERCENTAGE 50

/* The percentage the number of differences between a state's transition
 * table and the proto it was first compared with must be of the total
 * number of out-transitions of the state in order to keep the first
 * proto as a good match and not search any further.
 */
#define FIRST_MATCH_DIFF_PERCENTAGE 10

/* The percentage the number of differences between a state's transition
 * table and the most similar proto must be of the state's total number
 * of out-transitions to use the proto as an acceptable close match.
 */
#define ACCEPTABLE_DIFF_PERCENTAGE 50

/* The percentage the number of homogeneous out-transitions of a state
 * must be of the number of total out-transitions of the state in order
 * to consider making a template from the state.
 */
#define TEMPLATE_SAME_PERCENTAGE 60

/* The percentage the number of differences between a state's transition
 * table and the most similar proto must be of the state's total number
 * of out-transitions to create a new proto from the state.
 */
#define NEW_PROTO_DIFF_PERCENTAGE 20

/* The percentage the total number of out-transitions of a state must be
 * of the number of equivalence classes in order to consider trying to
 * fit the transition table into "holes" inside the nxt/chk table.
 */
#define INTERIOR_FIT_PERCENTAGE 15

/* Size of region set aside to cache the complete transition table of
 * protos on the proto queue to enable quick comparisons.
 */
#define PROT_SAVE_SIZE 2000

#define MSP 50	/* maximum number of saved protos (protos on the proto queue) */

/* Maximum number of out-transitions a state can have that we'll rummage
 * around through the interior of the internal fast table looking for a
 * spot for it.
 */
#define MAX_XTIONS_FULL_INTERIOR_FIT 4

/* Maximum number of rules which will be reported as being associated
 * with a DFA state.
 */
#define MAX_ASSOC_RULES 100

/* Number that, if used to subscript an array, has a good chance of producing
 * an error; should be small enough to fit into a short.
 */
#define BAD_SUBSCRIPT -32767

/* Absolute value of largest number that can be stored in a short, with a
 * bit of slop thrown in for general paranoia.
 */
#define MAX_SHORT 32700

/* Declarations for global variables. */

/* Variables for symbol tables:
 * sctbl - start-condition symbol table
 * ndtbl - name-definition symbol table
 * ccltab - character class text symbol table
 */

struct hash_entry
	{
	struct hash_entry *prev, *next;
	char *name;
	char *str_val;
	int int_val;
	} ;

typedef struct hash_entry **hash_table;

#define NAME_TABLE_HASH_SIZE 101
#define START_COND_HASH_SIZE 101
#define CCL_HASH_SIZE 101

extern struct hash_entry *ndtbl[NAME_TABLE_HASH_SIZE];
extern struct hash_entry *sctbl[START_COND_HASH_SIZE];
extern struct hash_entry *ccltab[CCL_HASH_SIZE];

/* Variables for flags:
 * printstats - if true (-v), dump statistics
 * syntaxerror - true if a syntax error has been found
 * eofseen - true if we've seen an eof in the input file
 * ddebug - if true (-d), make a "debug" scanner
 * trace - if true (-T), trace processing
 * nowarn - if true (-w), do not generate warnings
 * spprdflt - if true (-s), suppress the default rule
 * interactive - if true (-I), generate an interactive scanner
 * caseins - if true (-i), generate a case-insensitive scanner
 * lex_compat - if true (-l), maximize compatibility with AT&T lex
 * do_yylineno - if true, generate code to maintain yylineno
 * useecs - if true (-Ce flag), use equivalence classes
 * fulltbl - if true (-Cf flag), don't compress the DFA state table
 * usemecs - if true (-Cm flag), use meta-equivalence classes
 * fullspd - if true (-F flag), use Jacobson method of table representation
 * gen_line_dirs - if true (i.e., no -L flag), generate #line directives
 * performance_report - if > 0 (i.e., -p flag), generate a report relating
 *   to scanner performance; if > 1 (-p -p), report on minor performance
 *   problems, too
 * backing_up_report - if true (i.e., -b flag), generate "lex.backup" file
 *   listing backing-up states
 * C_plus_plus - if true (i.e., -+ flag), generate a C++ scanner class;
 *   otherwise, a standard C scanner
 * long_align - if true (-Ca flag), favor long-word alignment.
 * use_read - if true (-f, -F, or -Cr) then use read() for scanner input;
 *   otherwise, use fread().
 * yytext_is_array - if true (i.e., %array directive), then declare
 *   yytext as a array instead of a character pointer.  Nice and inefficient.
 * do_yywrap - do yywrap() processing on EOF.  If false, EOF treated as
 *   "no more files".
 * csize - size of character set for the scanner we're generating;
 *   128 for 7-bit chars and 256 for 8-bit
 * yymore_used - if true, yymore() is used in input rules
 * reject - if true, generate back-up tables for REJECT macro
 * real_reject - if true, scanner really uses REJECT (as opposed to just
 *   having "reject" set for variable trailing context)
 * continued_action - true if this rule's action is to "fall through" to
 *   the next rule's action (i.e., the '|' action)
 * in_rule - true if we're inside an individual rule, false if not.
 * yymore_really_used - whether to treat yymore() as really used, regardless
 *   of what we think based on references to it in the user's actions.
 * reject_really_used - same for REJECT
 */

extern int printstats, syntaxerror, eofseen, ddebug, trace, nowarn, spprdflt;
extern int interactive, caseins, lex_compat, do_yylineno;
extern int useecs, fulltbl, usemecs, fullspd;
extern int gen_line_dirs, performance_report, backing_up_report;
extern int C_plus_plus, long_align, use_read, yytext_is_array, do_yywrap;
extern int csize;
extern int yymore_used, reject, real_reject, continued_action, in_rule;

extern int yymore_really_used, reject_really_used;

/* Variables used in the flex input routines:
 * datapos - characters on current output line
 * dataline - number of contiguous lines of data in current data
 * 	statement.  Used to generate readable -f output
 * linenum - current input line number
 * out_linenum - current output line number
 * skelfile - the skeleton file
 * skel - compiled-in skeleton array
 * skel_ind - index into "skel" array, if skelfile is nil
 * yyin - input file
 * backing_up_file - file to summarize backing-up states to
 * infilename - name of input file
 * outfilename - name of output file
 * did_outfilename - whether outfilename was explicitly set
 * prefix - the prefix used for externally visible names ("yy" by default)
 * yyclass - yyFlexLexer subclass to use for YY_DECL
 * do_stdinit - whether to initialize yyin/yyout to stdin/stdout
 * use_stdout - the -t flag
 * input_files - array holding names of input files
 * num_input_files - size of input_files array
 * program_name - name with which program was invoked
 *
 * action_array - array to hold the rule actions
 * action_size - size of action_array
 * defs1_offset - index where the user's section 1 definitions start
 *	in action_array
 * prolog_offset - index where the prolog starts in action_array
 * action_offset - index where the non-prolog starts in action_array
 * action_index - index where the next action should go, with respect
 * 	to "action_array"
 */

extern int datapos, dataline, linenum, out_linenum;
extern FILE *skelfile, *yyin, *backing_up_file;
extern const char *skel[];
extern int skel_ind;
extern char *infilename, *outfilename;
extern int did_outfilename;
extern char *prefix, *yyclass;
extern int do_stdinit, use_stdout;
extern char **input_files;
extern int num_input_files;
extern char *program_name;

extern char *action_array;
extern int action_size;
extern int defs1_offset, prolog_offset, action_offset, action_index;

/* Variables for stack of states having only one out-transition:
 * onestate - state number
 * onesym - transition symbol
 * onenext - target state
 * onedef - default base entry
 * onesp - stack pointer
 */

extern int onestate[ONE_STACK_SIZE], onesym[ONE_STACK_SIZE];
extern int onenext[ONE_STACK_SIZE], onedef[ONE_STACK_SIZE], onesp;

/* Variables for nfa machine data:
 * current_mns - current maximum on number of NFA states
 * num_rules - number of the last accepting state; also is number of
 * 	rules created so far
 * num_eof_rules - number of <<EOF>> rules
 * default_rule - number of the default rule
 * current_max_rules - current maximum number of rules
 * lastnfa - last nfa state number created
 * firstst - physically the first state of a fragment
 * lastst - last physical state of fragment
 * finalst - last logical state of fragment
 * transchar - transition character
 * trans1 - transition state
 * trans2 - 2nd transition state for epsilons
 * accptnum - accepting number
 * assoc_rule - rule associated with this NFA state (or 0 if none)
 * state_type - a STATE_xxx type identifying whether the state is part
 * 	of a normal rule, the leading state in a trailing context
 * 	rule (i.e., the state which marks the transition from
 * 	recognizing the text-to-be-matched to the beginning of
 * 	the trailing context), or a subsequent state in a trailing
 * 	context rule
 * rule_type - a RULE_xxx type identifying whether this a ho-hum
 * 	normal rule or one which has variable head & trailing
 * 	context
 * rule_linenum - line number associated with rule
 * rule_useful - true if we've determined that the rule can be matched
 */

extern int current_mns, current_max_rules;
extern int num_rules, num_eof_rules, default_rule, lastnfa;
extern int *firstst, *lastst, *finalst, *transchar, *trans1, *trans2;
extern int *accptnum, *assoc_rule, *state_type;
extern int *rule_type, *rule_linenum, *rule_useful;

/* Different types of states; values are useful as masks, as well, for
 * routines like check_trailing_context().
 */
#define STATE_NORMAL 0x1
#define STATE_TRAILING_CONTEXT 0x2

/* Global holding current type of state we're making. */

extern int current_state_type;

/* Different types of rules. */
#define RULE_NORMAL 0
#define RULE_VARIABLE 1

/* True if the input rules include a rule with both variable-length head
 * and trailing context, false otherwise.
 */
extern int variable_trailing_context_rules;

/* Variables for protos:
 * numtemps - number of templates created
 * numprots - number of protos created
 * protprev - backlink to a more-recently used proto
 * protnext - forward link to a less-recently used proto
 * prottbl - base/def table entry for proto
 * protcomst - common state of proto
 * firstprot - number of the most recently used proto
 * lastprot - number of the least recently used proto
 * protsave contains the entire state array for protos
 */

extern int numtemps, numprots, protprev[MSP], protnext[MSP], prottbl[MSP];
extern int protcomst[MSP], firstprot, lastprot, protsave[PROT_SAVE_SIZE];

/* Variables for managing equivalence classes:
 * numecs - number of equivalence classes
 * nextecm - forward link of Equivalence Class members
 * ecgroup - class number or backward link of EC members
 * nummecs - number of meta-equivalence classes (used to compress
 *   templates)
 * tecfwd - forward link of meta-equivalence classes members
 * tecbck - backward link of MEC's
 */

/* Reserve enough room in the equivalence class arrays so that we
 * can use the CSIZE'th element to hold equivalence class information
 * for the NUL character.  Later we'll move this information into
 * the 0th element.
 */
extern int numecs, nextecm[CSIZE + 1], ecgroup[CSIZE + 1], nummecs;

/* Meta-equivalence classes are indexed starting at 1, so it's possible
 * that they will require positions from 1 .. CSIZE, i.e., CSIZE + 1
 * slots total (since the arrays are 0-based).  nextecm[] and ecgroup[]
 * don't require the extra position since they're indexed from 1 .. CSIZE - 1.
 */
extern int tecfwd[CSIZE + 1], tecbck[CSIZE + 1];

/* Variables for start conditions:
 * lastsc - last start condition created
 * current_max_scs - current limit on number of start conditions
 * scset - set of rules active in start condition
 * scbol - set of rules active only at the beginning of line in a s.c.
 * scxclu - true if start condition is exclusive
 * sceof - true if start condition has EOF rule
 * scname - start condition name
 */

extern int lastsc, *scset, *scbol, *scxclu, *sceof;
extern int current_max_scs;
extern char **scname;

/* Variables for dfa machine data:
 * current_max_dfa_size - current maximum number of NFA states in DFA
 * current_max_xpairs - current maximum number of non-template xtion pairs
 * current_max_template_xpairs - current maximum number of template pairs
 * current_max_dfas - current maximum number DFA states
 * lastdfa - last dfa state number created
 * nxt - state to enter upon reading character
 * chk - check value to see if "nxt" applies
 * tnxt - internal nxt table for templates
 * base - offset into "nxt" for given state
 * def - where to go if "chk" disallows "nxt" entry
 * nultrans - NUL transition for each state
 * NUL_ec - equivalence class of the NUL character
 * tblend - last "nxt/chk" table entry being used
 * firstfree - first empty entry in "nxt/chk" table
 * dss - nfa state set for each dfa
 * dfasiz - size of nfa state set for each dfa
 * dfaacc - accepting set for each dfa state (if using REJECT), or accepting
 *	number, if not
 * accsiz - size of accepting set for each dfa state
 * dhash - dfa state hash value
 * numas - number of DFA accepting states created; note that this
 *	is not necessarily the same value as num_rules, which is the analogous
 *	value for the NFA
 * numsnpairs - number of state/nextstate transition pairs
 * jambase - position in base/def where the default jam table starts
 * jamstate - state number corresponding to "jam" state
 * end_of_buffer_state - end-of-buffer dfa state number
 */

extern int current_max_dfa_size, current_max_xpairs;
extern int current_max_template_xpairs, current_max_dfas;
extern int lastdfa, *nxt, *chk, *tnxt;
extern int *base, *def, *nultrans, NUL_ec, tblend, firstfree, **dss, *dfasiz;
extern union dfaacc_union
	{
	int *dfaacc_set;
	int dfaacc_state;
	} *dfaacc;
extern int *accsiz, *dhash, numas;
extern int numsnpairs, jambase, jamstate;
extern int end_of_buffer_state;

/* Variables for ccl information:
 * lastccl - ccl index of the last created ccl
 * current_maxccls - current limit on the maximum number of unique ccl's
 * cclmap - maps a ccl index to its set pointer
 * ccllen - gives the length of a ccl
 * cclng - true for a given ccl if the ccl is negated
 * cclreuse - counts how many times a ccl is re-used
 * current_max_ccl_tbl_size - current limit on number of characters needed
 *	to represent the unique ccl's
 * ccltbl - holds the characters in each ccl - indexed by cclmap
 */

extern int lastccl, *cclmap, *ccllen, *cclng, cclreuse;
extern int current_maxccls, current_max_ccl_tbl_size;
extern Char *ccltbl;

/* Variables for miscellaneous information:
 * nmstr - last NAME scanned by the scanner
 * sectnum - section number currently being parsed
 * nummt - number of empty nxt/chk table entries
 * hshcol - number of hash collisions detected by snstods
 * dfaeql - number of times a newly created dfa was equal to an old one
 * numeps - number of epsilon NFA states created
 * eps2 - number of epsilon states which have 2 out-transitions
 * num_reallocs - number of times it was necessary to realloc() a group
 *	  of arrays
 * tmpuses - number of DFA states that chain to templates
 * totnst - total number of NFA states used to make DFA states
 * peakpairs - peak number of transition pairs we had to store internally
 * numuniq - number of unique transitions
 * numdup - number of duplicate transitions
 * hshsave - number of hash collisions saved by checking number of states
 * num_backing_up - number of DFA states requiring backing up
 * bol_needed - whether scanner needs beginning-of-line recognition
 */

extern char nmstr[MAXLINE];
extern int sectnum, nummt, hshcol, dfaeql, numeps, eps2, num_reallocs;
extern int tmpuses, totnst, peakpairs, numuniq, numdup, hshsave;
extern int num_backing_up, bol_needed;

void *allocate_array PROTO((int, size_t));
void *reallocate_array PROTO((void*, int, size_t));

void *flex_alloc PROTO((size_t));
void *flex_realloc PROTO((void*, size_t));
void flex_free PROTO((void*));

#define allocate_integer_array(size) \
	(int *) allocate_array( size, sizeof( int ) )

#define reallocate_integer_array(array,size) \
	(int *) reallocate_array( (void *) array, size, sizeof( int ) )

#define allocate_int_ptr_array(size) \
	(int **) allocate_array( size, sizeof( int * ) )

#define allocate_char_ptr_array(size) \
	(char **) allocate_array( size, sizeof( char * ) )

#define allocate_dfaacc_union(size) \
	(union dfaacc_union *) \
		allocate_array( size, sizeof( union dfaacc_union ) )

#define reallocate_int_ptr_array(array,size) \
	(int **) reallocate_array( (void *) array, size, sizeof( int * ) )

#define reallocate_char_ptr_array(array,size) \
	(char **) reallocate_array( (void *) array, size, sizeof( char * ) )

#define reallocate_dfaacc_union(array, size) \
	(union dfaacc_union *) \
	reallocate_array( (void *) array, size, sizeof( union dfaacc_union ) )

#define allocate_character_array(size) \
	(char *) allocate_array( size, sizeof( char ) )

#define reallocate_character_array(array,size) \
	(char *) reallocate_array( (void *) array, size, sizeof( char ) )

#define allocate_Character_array(size) \
	(Char *) allocate_array( size, sizeof( Char ) )

#define reallocate_Character_array(array,size) \
	(Char *) reallocate_array( (void *) array, size, sizeof( Char ) )

/* Used to communicate between scanner and parser.  The type should really
 * be YYSTYPE, but we can't easily get our hands on it.
 */
extern int yylval;

/* External functions that are cross-referenced among the flex source files. */

/* from file ccl.c */

extern void ccladd PROTO((int, int));	/* add a single character to a ccl */
extern int cclinit PROTO((void));	/* make an empty ccl */
extern void cclnegate PROTO((int));	/* negate a ccl */

/* List the members of a set of characters in CCL form. */
extern void list_character_set PROTO((FILE*, int[]));

/* from file dfa.c */

/* Check a DFA state for backing up. */
extern void check_for_backing_up PROTO((int, int[]));

/* Check to see if NFA state set constitutes "dangerous" trailing context. */
extern void check_trailing_context PROTO((int*, int, int*, int));

/* Construct the epsilon closure of a set of ndfa states. */
extern int *epsclosure PROTO((int*, int*, int[], int*, int*));

/* Increase the maximum number of dfas. */
extern void increase_max_dfas PROTO((void));

extern void ntod PROTO((void));	/* convert a ndfa to a dfa */

/* Converts a set of ndfa states into a dfa state. */
extern int snstods PROTO((int[], int, int[], int, int, int*));

/* from file ecs.c */

/* Convert character classes to set of equivalence classes. */
extern void ccl2ecl PROTO((void));

/* Associate equivalence class numbers with class members. */
extern int cre8ecs PROTO((int[], int[], int));

/* Update equivalence classes based on character class transitions. */
extern void mkeccl PROTO((Char[], int, int[], int[], int, int));

/* Create equivalence class for single character. */
extern void mkechar PROTO((int, int[], int[]));

/* from file gen.c */

extern void do_indent PROTO((void));	/* indent to the current level */

/* Generate the code to keep backing-up information. */
extern void gen_backing_up PROTO((void));

/* Generate the code to perform the backing up. */
extern void gen_bu_action PROTO((void));

/* Generate full speed compressed transition table. */
extern void genctbl PROTO((void));

/* Generate the code to find the action number. */
extern void gen_find_action PROTO((void));

extern void genftbl PROTO((void));	/* generate full transition table */

/* Generate the code to find the next compressed-table state. */
extern void gen_next_compressed_state PROTO((char*));

/* Generate the code to find the next match. */
extern void gen_next_match PROTO((void));

/* Generate the code to find the next state. */
extern void gen_next_state PROTO((int));

/* Generate the code to make a NUL transition. */
extern void gen_NUL_trans PROTO((void));

/* Generate the code to find the start state. */
extern void gen_start_state PROTO((void));

/* Generate data statements for the transition tables. */
extern void gentabs PROTO((void));

/* Write out a formatted string at the current indentation level. */
extern void indent_put2s PROTO((char[], char[]));

/* Write out a string + newline at the current indentation level. */
extern void indent_puts PROTO((char[]));

extern void make_tables PROTO((void));	/* generate transition tables */

/* from file main.c */

extern void check_options PROTO((void));
extern void flexend PROTO((int));
extern void usage PROTO((void));

/* from file misc.c */

/* Add a #define to the action file. */
extern void action_define PROTO(( char *defname, int value ));

/* Add the given text to the stored actions. */
extern void add_action PROTO(( char *new_text ));

/* True if a string is all lower case. */
extern int all_lower PROTO((register char *));

/* True if a string is all upper case. */
extern int all_upper PROTO((register char *));

/* Bubble sort an integer array. */
extern void bubble PROTO((int [], int));

/* Check a character to make sure it's in the expected range. */
extern void check_char PROTO((int c));

/* Replace upper-case letter to lower-case. */
extern Char clower PROTO((int));

/* Returns a dynamically allocated copy of a string. */
extern char *copy_string PROTO((register const char *));

/* Returns a dynamically allocated copy of a (potentially) unsigned string. */
extern Char *copy_unsigned_string PROTO((register Char *));

/* Shell sort a character array. */
extern void cshell PROTO((Char [], int, int));

/* Finish up a block of data declarations. */
extern void dataend PROTO((void));

/* Flush generated data statements. */
extern void dataflush PROTO((void));

/* Report an error message and terminate. */
extern void flexerror PROTO((const char[]));

/* Report a fatal error message and terminate. */
extern void flexfatal PROTO((const char[]));

/* Convert a hexadecimal digit string to an integer value. */
extern int htoi PROTO((Char[]));

/* Report an error message formatted with one integer argument. */
extern void lerrif PROTO((const char[], int));

/* Report an error message formatted with one string argument. */
extern void lerrsf PROTO((const char[], const char[]));

/* Spit out a "#line" statement. */
extern void line_directive_out PROTO((FILE*, int));

/* Mark the current position in the action array as the end of the section 1
 * user defs.
 */
extern void mark_defs1 PROTO((void));

/* Mark the current position in the action array as the end of the prolog. */
extern void mark_prolog PROTO((void));

/* Generate a data statment for a two-dimensional array. */
extern void mk2data PROTO((int));

extern void mkdata PROTO((int));	/* generate a data statement */

/* Return the integer represented by a string of digits. */
extern int myctoi PROTO((char []));

/* Return character corresponding to escape sequence. */
extern Char myesc PROTO((Char[]));

/* Convert an octal digit string to an integer value. */
extern int otoi PROTO((Char [] ));

/* Output a (possibly-formatted) string to the generated scanner. */
extern void out PROTO((const char []));
extern void out_dec PROTO((const char [], int));
extern void out_dec2 PROTO((const char [], int, int));
extern void out_hex PROTO((const char [], unsigned int));
extern void out_line_count PROTO((const char []));
extern void out_str PROTO((const char [], const char []));
extern void out_str3
	PROTO((const char [], const char [], const char [], const char []));
extern void out_str_dec PROTO((const char [], const char [], int));
extern void outc PROTO((int));
extern void outn PROTO((const char []));

/* Return a printable version of the given character, which might be
 * 8-bit.
 */
extern char *readable_form PROTO((int));

/* Write out one section of the skeleton file. */
extern void skelout PROTO((void));

/* Output a yy_trans_info structure. */
extern void transition_struct_out PROTO((int, int));

/* Only needed when using certain broken versions of bison to build parse.c. */
extern void *yy_flex_xmalloc PROTO(( int ));

/* Set a region of memory to 0. */
extern void zero_out PROTO((char *, size_t));

/* from file nfa.c */

/* Add an accepting state to a machine. */
extern void add_accept PROTO((int, int));

/* Make a given number of copies of a singleton machine. */
extern int copysingl PROTO((int, int));

/* Debugging routine to write out an nfa. */
extern void dumpnfa PROTO((int));

/* Finish up the processing for a rule. */
extern void finish_rule PROTO((int, int, int, int));

/* Connect two machines together. */
extern int link_machines PROTO((int, int));

/* Mark each "beginning" state in a machine as being a "normal" (i.e.,
 * not trailing context associated) state.
 */
extern void mark_beginning_as_normal PROTO((register int));

/* Make a machine that branches to two machines. */
extern int mkbranch PROTO((int, int));

extern int mkclos PROTO((int));	/* convert a machine into a closure */
extern int mkopt PROTO((int));	/* make a machine optional */

/* Make a machine that matches either one of two machines. */
extern int mkor PROTO((int, int));

/* Convert a machine into a positive closure. */
extern int mkposcl PROTO((int));

extern int mkrep PROTO((int, int, int));	/* make a replicated machine */

/* Create a state with a transition on a given symbol. */
extern int mkstate PROTO((int));

extern void new_rule PROTO((void));	/* initialize for a new rule */

/* from file parse.y */

/* Build the "<<EOF>>" action for the active start conditions. */
extern void build_eof_action PROTO((void));

/* Write out a message formatted with one string, pinpointing its location. */
extern void format_pinpoint_message PROTO((char[], char[]));

/* Write out a message, pinpointing its location. */
extern void pinpoint_message PROTO((char[]));

/* Write out a warning, pinpointing it at the given line. */
extern void line_warning PROTO(( char[], int ));

/* Write out a message, pinpointing it at the given line. */
extern void line_pinpoint PROTO(( char[], int ));

/* Report a formatted syntax error. */
extern void format_synerr PROTO((char [], char[]));
extern void synerr PROTO((char []));	/* report a syntax error */
extern void format_warn PROTO((char [], char[]));
extern void warn PROTO((char []));	/* report a warning */
extern void yyerror PROTO((char []));	/* report a parse error */
extern int yyparse PROTO((void));	/* the YACC parser */

/* from file scan.l */

/* The Flex-generated scanner for flex. */
extern int flexscan PROTO((void));

/* Open the given file (if NULL, stdin) for scanning. */
extern void set_input_file PROTO((char*));

/* Wrapup a file in the lexical analyzer. */
extern int yywrap PROTO((void));

/* from file sym.c */

/* Add symbol and definitions to symbol table. */
extern int addsym PROTO((register char[], char*, int, hash_table, int));

/* Save the text of a character class. */
extern void cclinstal PROTO ((Char [], int));

/* Lookup the number associated with character class. */
extern int ccllookup PROTO((Char []));

/* Find symbol in symbol table. */
extern struct hash_entry *findsym PROTO((register char[], hash_table, int ));

extern void ndinstal PROTO((char[], Char[]));	/* install a name definition */
extern Char *ndlookup PROTO((char[]));	/* lookup a name definition */

/* Increase maximum number of SC's. */
extern void scextend PROTO((void));
extern void scinstal PROTO((char[], int));	/* make a start condition */

/* Lookup the number associated with a start condition. */
extern int sclookup PROTO((char[]));

/* from file tblcmp.c */

/* Build table entries for dfa state. */
extern void bldtbl PROTO((int[], int, int, int, int));

extern void cmptmps PROTO((void));	/* compress template table entries */
extern void expand_nxt_chk PROTO((void));	/* increase nxt/chk arrays */
/* Finds a space in the table for a state to be placed. */
extern int find_table_space PROTO((int*, int));
extern void inittbl PROTO((void));	/* initialize transition tables */
/* Make the default, "jam" table entries. */
extern void mkdeftbl PROTO((void));

/* Create table entries for a state (or state fragment) which has
 * only one out-transition.
 */
extern void mk1tbl PROTO((int, int, int, int));

/* Place a state into full speed transition table. */
extern void place_state PROTO((int*, int, int));

/* Save states with only one out-transition to be processed later. */
extern void stack1 PROTO((int, int, int, int));

/* from file yylex.c */

extern int yylex PROTO((void));


text:
/**
 * @class Oskari.harava.bundle.haravaInfobox.InfoBoxBundle
 *
 * Definition for bundle. See source for details.
 */
Oskari.clazz.define("Oskari.harava.bundle.haravaSearchByGeometry.SearchByGeometryBundle",

function() {

}, {
	"create" : function() {
		var me = this;
		var inst =
		  Oskari.clazz.create("Oskari.harava.bundle.haravaSearchByGeometry.SearchByGeometryBundleInstance");
		return inst;

	},
	"update" : function(manager, bundle, bi, info) {

	}
}, {

	"protocol" : [ "Oskari.bundle.Bundle",
	               "Oskari.mapframework.bundle.extension.ExtensionBundle" ],
	"source" : {

		"scripts" : [{
			"type" : "text/javascript",
			"src" : "../../../../bundles/harava/bundle/harava-search-by-geometry/instance.js"
		}, {
            "type" : "text/javascript",
            "src" : "../../../../bundles/harava/bundle/harava-search-by-geometry/plugin/drawsearchgeometry/HaravaDrawSearchGeometryPlugin.js"
        },
        /*
         * Requests and handlers
         **/
        {
            "type" : "text/javascript",
            "src" : "../../../../bundles/harava/bundle/harava-search-by-geometry/request/StartGeometrySearchRequest.js"
        },
        {
            "type" : "text/javascript",
            "src" : "../../../../bundles/harava/bundle/harava-search-by-geometry/request/StartGeometrySearchRequestHandler.js"
        },
        {
            "type" : "text/javascript",
            "src" : "../../../../bundles/harava/bundle/harava-search-by-geometry/request/StopGeometrySearchRequest.js"
        },
        {
            "type" : "text/javascript",
            "src" : "../../../../bundles/harava/bundle/harava-search-by-geometry/request/StopGeometrySearchRequestHandler.js"
        },
        {
            "type" : "text/javascript",
            "src" : "../../../../bundles/harava/bundle/harava-search-by-geometry/request/ToggleVisibilityGeometrySearchRequest.js"
        },
        {
            "type" : "text/javascript",
            "src" : "../../../../bundles/harava/bundle/harava-search-by-geometry/request/ToggleVisibilityGeometrySearchRequestHandler.js"
        },
        /* Resources */
        {
		    "type" : "text/css",
		    "src" : "../../../../resources/harava/bundle/harava-search-by-geometry/css/style.css"
		}],
		/* Locales */
		"locales" : [{
			"lang" : "fi",
			"type" : "text/javascript",
			"src" : "../../../../bundles/harava/bundle/harava-search-by-geometry/locale/fi.js"
		}, {
			"lang" : "sv",
			"type" : "text/javascript",
			"src" : "../../../../bundles/harava/bundle/harava-search-by-geometry/locale/sv.js"
		}, {
			"lang" : "en",
			"type" : "text/javascript",
			"src" : "../../../../bundles/harava/bundle/harava-search-by-geometry/locale/en.js"
		}
		]
	},
	"bundle" : {
		"manifest" : {
			"Bundle-Identifier" : "harava-search-by-geometry",
			"Bundle-Name" : "harava-search-by-geometry",
			"Bundle-Author" : [{
				"Name" : "MK",
				"Organisation" : "Dimenteq Oy",
				"Temporal" : {
					"Start" : "2012",
					"End" : "2013"
				},
				"Copyleft" : {
					"License" : {
						"License-Name" : "EUPL",
						"License-Online-Resource" :
						  "http://www.paikkatietoikkuna.fi/license"
					}
				}
			}],
			"Bundle-Name-Locale" : {
				"fi" : {
					"Name" : " style-1",
					"Title" : " style-1"
				},
				"en" : {}
			},
			"Bundle-Version" : "1.0.0",
			"Import-Namespace" : ["Oskari"],
			"Import-Bundle" : {}

		}
	},

	/**
	 * @static
	 * @property dependencies
	 */
	"dependencies" : [ "jquery" ]

});

Oskari.bundle_manager.installBundleClass("harava-search-by-geometry",
         "Oskari.harava.bundle.haravaSearchByGeometry.SearchByGeometryBundle");


text:
class ConsulTemplate < Formula
  desc "Generic template rendering and notifications with Consul"
  homepage "https://github.com/hashicorp/consul-template"
  url "https://github.com/hashicorp/consul-template.git",
      :tag => "v0.19.4",
      :revision => "111a80441153783544817b7c6a9c08633308b9a8"
  head "https://github.com/hashicorp/consul-template.git"

  bottle do
    cellar :any_skip_relocation
    sha256 "5edefad550b7fa2c86b7d0484cae79b3b49b7b89c402f38f2b341ea948150410" => :high_sierra
    sha256 "55b7eb1dd13f7fb4a4285a14e3effe27a33667352aee2b3dd1f87dd91b037e7a" => :sierra
    sha256 "0ba3259f899d530ec583de3a10a421fefce9641dc118f59b2c89354ad1cd56bc" => :el_capitan
  end

  depends_on "go" => :build

  def install
    ENV["GOPATH"] = buildpath
    arch = MacOS.prefer_64_bit? ? "amd64" : "386"
    ENV["XC_OS"] = "darwin"
    ENV["XC_ARCH"] = arch
    dir = buildpath/"src/github.com/hashicorp/consul-template"
    dir.install buildpath.children - [buildpath/".brew_home"]

    cd dir do
      project = "github.com/hashicorp/consul-template"
      commit = Utils.popen_read("git rev-parse --short HEAD").chomp
      ldflags = ["-X #{project}/version.Name=consul-template",
                 "-X #{project}/version.GitCommit=#{commit}"]
      system "go", "build", "-o", bin/"consul-template", "-ldflags",
             ldflags.join(" ")
      prefix.install_metafiles
    end
  end

  test do
    (testpath/"template").write <<~EOS
      {{"homebrew" | toTitle}}
    EOS
    system bin/"consul-template", "-once", "-template", "template:test-result"
    assert_equal "Homebrew", (testpath/"test-result").read.chomp
  end
end