# Path: canary/gazeteer.py
# class Feature (DTable):
# 
#     def __init__ (self, context=None, uid=-1):
#         self.uid = uid
#         self.data_source = ''
#         self.latitude = 0.0
#         self.longitude = 0.0
#         self.dms_latitude = 0
#         self.dms_longitude = 0
#         self.feature_type = ''
#         self.country_code = ''
#         self.adm1 = 0
#         self.adm2 = ''
#         self.name = ''
#         
#     def load (self, context):
#         cursor = context.get_cursor()
#         cursor.execute("""
#             SELECT *
#             FROM gazeteer
#             WHERE uid = %s
#             """, self.uid)
#         fields = [d[0] for d in cursor.description]
#         desc = dtuple.TupleDescriptor([[f] for f in fields])
#         row = cursor.fetchone()
#         if row:
#             row = dtuple.DatabaseTuple(desc, row)
#             for field in fields:
#                 self.set(field, row[field])
# 
# Path: canary/qx_defs.py
# class MyForm (Form):
#     """
#     Automatically creates a logger instance on any arbitrary Form.
#     """
#     def __init__ (self, context, *args, **kwargs):
#         Form.__init__(self, *args, **kwargs)
#         self.logger = logging.getLogger(str(self.__class__))
# 
# Path: canary/utils.py
# class DTable:
#     """
#     Convenience class for rdbms-persisted object types.  Allows simple
#     loading of data for single-valued fields using set() and for multi-valued
#     fields using append().
#     """
#     
#     def set (self, field, value):
#         """
#         Dynamic field setting for simpler database lookups
#         """
#         if value == None:
#             setattr(self, str(field), str(''))
#         else:
#             setattr(self, str(field), value)
#        
#     #def append (self, field, value):
#     #    list_attr = getattr(self, str(field))
#     #    if not value in list_attr:
#     #        list_attr.append(value)
#     
#        
#     def get_new_uid (self, context):
#         cursor = context.get_cursor()
#         try:
#             cursor.execute('SELECT LAST_INSERT_ID() AS new_uid')
#             row = cursor.fetchone()
#             new_uid = int(row[0])
#         except:
#             new_uid = -1
#         return new_uid
#     
# 
#     def load (self, context):
#         cursor = context.get_cursor()
#         if self.uid:
#             cursor.execute("""SELECT * FROM """ + self.TABLE_NAME +
#                 """
#                 WHERE uid LIKE %s
#                 """, (self.uid))
#             fields = [d[0] for d in cursor.description]
#             desc = dtuple.TupleDescriptor([[f] for f in fields])
#             row = cursor.fetchone()
#             if row:
#                 row = dtuple.DatabaseTuple(desc, row)
#                 for field in fields:
#                     self.set(field, row[field])
#             else:
#                 context.logger.debug('No %s "%s"', self.TABLE_NAME, self.uid)
#                 print 'No %s "%s"' % (self.TABLE_NAME, self.uid)
#                 raise 'InvalidId'
#                 
# 
#     def delete (self, context):
#         cursor = context.get_cursor()
#         try:
#             if self.uid >= 0:
#                 cursor.execute("""DELETE FROM """ + self.TABLE_NAME +
#                     """
#                     WHERE uid = %s
#                     """, self.uid)
#         except Exception, e:
#             context.logger.error(e)
# 
# def render_capitalized (term):
#     stop_words = ['of', 'the']
#     old_terms = str(term).split(' ')
#     new_terms = []
#     for t in term.split(' '):
#         if t in stop_words:
#             new_terms.append(t)
#         else:
#             new_terms.append(t.lower().capitalize())
#     return ' '.join(new_terms)


import copy
import logging
import time
import traceback
import types
import canary.context
import dtuple
from quixote import form2
from quixote.html import htmltext
from canary.gazeteer import Feature
from canary.qx_defs import MyForm
from canary.utils import DTable, render_capitalized
        desc = dtuple.TupleDescriptor([[f] for f in fields])
        rows = cursor.fetchall()
        for row in rows:
            row = dtuple.DatabaseTuple(desc, row)
            if not species_map.has_key((row['umls_concept_id'], row['umls_source_id'])):
                spec = Species()
                spec.concept_source_id = row['umls_source_id']
                spec.concept_id = row['umls_concept_id']
                spec.term = row['preferred_name']
                spec.synonyms.append(row['term'])
                species_map[(spec.concept_id, spec.concept_source_id)] = spec
            else:
                spec = species_map[(row['umls_concept_id'], row['umls_source_id'])]
                if not row['term'] in spec.synonyms:
                    spec.synonyms.append(row['term'])
                species_map[(spec.concept_id, spec.concept_source_id)] = spec
        
        # Try to bump up coarse "relevance" of exact matches
        species_ranked = species_map.values()
        for spec in species_ranked:
            if spec.term.lower() == search_term.lower()\
                or search_term.lower() in [syn.lower() for syn in spec.synonyms]:
                species_ranked.remove(spec)
                species_ranked.insert(0, spec)
        return species_ranked
    
    else:
        return species_map.values()



# Path: canary/gazeteer.py
# class Feature (DTable):
# 
#     def __init__ (self, context=None, uid=-1):
#         self.uid = uid
#         self.data_source = ''
#         self.latitude = 0.0
#         self.longitude = 0.0
#         self.dms_latitude = 0
#         self.dms_longitude = 0
#         self.feature_type = ''
#         self.country_code = ''
#         self.adm1 = 0
#         self.adm2 = ''
#         self.name = ''
#         
#     def load (self, context):
#         cursor = context.get_cursor()
#         cursor.execute("""
#             SELECT *
#             FROM gazeteer
#             WHERE uid = %s
#             """, self.uid)
#         fields = [d[0] for d in cursor.description]
#         desc = dtuple.TupleDescriptor([[f] for f in fields])
#         row = cursor.fetchone()
#         if row:
#             row = dtuple.DatabaseTuple(desc, row)
#             for field in fields:
#                 self.set(field, row[field])
# 
# Path: canary/qx_defs.py
# class MyForm (Form):
#     """
#     Automatically creates a logger instance on any arbitrary Form.
#     """
#     def __init__ (self, context, *args, **kwargs):
#         Form.__init__(self, *args, **kwargs)
#         self.logger = logging.getLogger(str(self.__class__))
# 
# Path: canary/utils.py
# class DTable:
#     """
#     Convenience class for rdbms-persisted object types.  Allows simple
#     loading of data for single-valued fields using set() and for multi-valued
#     fields using append().
#     """
#     
#     def set (self, field, value):
#         """
#         Dynamic field setting for simpler database lookups
#         """
#         if value == None:
#             setattr(self, str(field), str(''))
#         else:
#             setattr(self, str(field), value)
#        
#     #def append (self, field, value):
#     #    list_attr = getattr(self, str(field))
#     #    if not value in list_attr:
#     #        list_attr.append(value)
#     
#        
#     def get_new_uid (self, context):
#         cursor = context.get_cursor()
#         try:
#             cursor.execute('SELECT LAST_INSERT_ID() AS new_uid')
#             row = cursor.fetchone()
#             new_uid = int(row[0])
#         except:
#             new_uid = -1
#         return new_uid
#     
# 
#     def load (self, context):
#         cursor = context.get_cursor()
#         if self.uid:
#             cursor.execute("""SELECT * FROM """ + self.TABLE_NAME +
#                 """
#                 WHERE uid LIKE %s
#                 """, (self.uid))
#             fields = [d[0] for d in cursor.description]
#             desc = dtuple.TupleDescriptor([[f] for f in fields])
#             row = cursor.fetchone()
#             if row:
#                 row = dtuple.DatabaseTuple(desc, row)
#                 for field in fields:
#                     self.set(field, row[field])
#             else:
#                 context.logger.debug('No %s "%s"', self.TABLE_NAME, self.uid)
#                 print 'No %s "%s"' % (self.TABLE_NAME, self.uid)
#                 raise 'InvalidId'
#                 
# 
#     def delete (self, context):
#         cursor = context.get_cursor()
#         try:
#             if self.uid >= 0:
#                 cursor.execute("""DELETE FROM """ + self.TABLE_NAME +
#                     """
#                     WHERE uid = %s
#                     """, self.uid)
#         except Exception, e:
#             context.logger.error(e)
# 
# def render_capitalized (term):
#     stop_words = ['of', 'the']
#     old_terms = str(term).split(' ')
#     new_terms = []
#     for t in term.split(' '):
#         if t in stop_words:
#             new_terms.append(t)
#         else:
#             new_terms.append(t.lower().capitalize())
#     return ' '.join(new_terms)


# Path: canary/study.py
import copy
import logging
import time
import traceback
import types
import canary.context
import dtuple
from quixote import form2
from quixote.html import htmltext
from canary.gazeteer import Feature
from canary.qx_defs import MyForm
from canary.utils import DTable, render_capitalized

        desc = dtuple.TupleDescriptor([[f] for f in fields])
        rows = cursor.fetchall()
        for row in rows:
            row = dtuple.DatabaseTuple(desc, row)
            if not species_map.has_key((row['umls_concept_id'], row['umls_source_id'])):
                spec = Species()
                spec.concept_source_id = row['umls_source_id']
                spec.concept_id = row['umls_concept_id']
                spec.term = row['preferred_name']
                spec.synonyms.append(row['term'])
                species_map[(spec.concept_id, spec.concept_source_id)] = spec
            else:
                spec = species_map[(row['umls_concept_id'], row['umls_source_id'])]
                if not row['term'] in spec.synonyms:
                    spec.synonyms.append(row['term'])
                species_map[(spec.concept_id, spec.concept_source_id)] = spec
        
        # Try to bump up coarse "relevance" of exact matches
        species_ranked = species_map.values()
        for spec in species_ranked:
            if spec.term.lower() == search_term.lower()\
                or search_term.lower() in [syn.lower() for syn in spec.synonyms]:
                species_ranked.remove(spec)
                species_ranked.insert(0, spec)
        return species_ranked
    
    else:
        return species_map.values()



class Species (DTable):