Create a metadata dict from a MetatabDoc, for Document conversion
497623
def doc_metadata(doc):
    """"""

    r = doc['Root'].as_dict()
    r.update(doc['Contacts'].as_dict())
    r['author'] = r.get('author', r.get('creator', r.get('wrangler')))

    return r
734911
def table_metadata(self, database, table):
        ""
        return (self.metadata("databases") or {}).get(database, {}).get(
            "tables", {}
        ).get(
            table, {}
        )
792756
def metadata(self, key=None, database=None, table=None, fallback=True):
        
        assert not (database is None and table is not None), \
            "Cannot call metadata() with table= specified but not database="
        databases = self._metadata.get("databases") or {}
        search_list = []
        if database is not None:
            search_list.append(databases.get(database) or {})
        if table is not None:
            table_metadata = (
                (databases.get(database) or {}).get("tables") or {}
            ).get(table) or {}
            search_list.insert(0, table_metadata)
        search_list.append(self._metadata)
        if not fallback:
            # No fallback allowed, so just use the first one in the list
            search_list = search_list[:1]
        if key is not None:
            for item in search_list:
                if key in item:
                    return item[key]
            return None
        else:
            # Return the merged list
            m = {}
            for item in search_list:
                m.update(item)
            return m
651797
def metadata():
    """"""
    with open(os.path.join(charm_dir(), 'metadata.yaml')) as md:
        return yaml.safe_load(md)
325542
def decorate_with_metadata(obj, result):
    """"""
    # Create es_meta object with Elasticsearch metadata about this
    # search result
    obj.es_meta = Metadata(
        # Elasticsearch id
        id=result.get('_id', 0),
        # Source data
        source=result.get('_source', {}),
        # The search result score
        score=result.get('_score', None),
        # The document type
        type=result.get('_type', None),
        # Explanation of score
        explanation=result.get('_explanation', {}),
        # Highlight bits
        highlight=result.get('highlight', {})
    )
    # Put the id on the object for convenience
    obj._id = result.get('_id', 0)
    return obj
1045098
def _get_metadata_as_string(self):
        """"""
        metalist = []
        for metaname, meta in iteritems(self.metadata):
            message = "Single value in metadata dictionary should be a list!"
            assert isinstance(meta, list), message
            for data in meta:
                if data:
                    metalist.append("!%s_%s = %s" % (self.geotype.capitalize(),
                                                     metaname, data))
        return "\n".join(metalist)
1218724
def create_metadata(*args, **kwargs):  # pylint: disable=unused-argument
        """"""
        json_filename = kwargs.get('json_filename', 'kytos.json')
        readme_filename = kwargs.get('readme_filename', 'README.rst')
        ignore_json = kwargs.get('ignore_json', False)
        metadata = {}

        if not ignore_json:
            try:
                with open(json_filename) as json_file:
                    metadata = json.load(json_file)
            except FileNotFoundError:
                print("ERROR: Could not access kytos.json file.")
                sys.exit(1)

        try:
            with open(readme_filename) as readme_file:
                metadata['readme'] = readme_file.read()
        except FileNotFoundError:
            metadata['readme'] = ''

        try:
            yaml = YAML(typ='safe')
            openapi_dict = yaml.load(Path('openapi.yml').open())
            openapi = json.dumps(openapi_dict)
        except FileNotFoundError:
            openapi = ''
        metadata['OpenAPI_Spec'] = openapi

        return metadata
384022
function generateMetadataNoteDocument (options) {
  if (!options) {
    throw new Error('Missing required input: options')
  }
  if (!options.title) {
    throw new Error('Missing required input: options.title')
  }
  if (!options.offTitle) {
    throw new Error('Missing required input: options.offTitle')
  }
  if (!options.personalIdNumber) {
    throw new Error('Missing required input: options.personalIdNumber')
  }
  if (!options.schoolName) {
    throw new Error('Missing required input: options.schoolName')
  }
  if (!options.schoolOrgNumber) {
    throw new Error('Missing required input: options.schoolOrgNumber')
  }
  if (!options.file) {
    throw new Error('Missing required input: options.file')
  }
  if (!options.fileTitle) {
    throw new Error('Missing required input: options.fileTitle')
  }
  if (!options.caseNumber) {
    throw new Error('Missing required input: options.caseNumber')
  }

  var schoolGroup = getSchoolStudentAccessGroup(options)
  var meta = {
    'clientService': 'DocumentService',
    'clientMethod': 'CreateDocument',
    'args': {
      'parameter': {
        'AccessCode': '13', // Codetable: Accesscode
        'AccessGroup': schoolGroup, // Codetable: Tilgangsgruppe navn
        'Category': 'Internt notat / e-post MED oppfølging (N)', // Codetable: Document category
        'Contacts': [
          {
            'DocumentContactParameter': [
              {
                'Role': 'Avsender',
                'ReferenceNumber': options.schoolOrgNumber
              },
              {
                'ReferenceNumber': options.schoolOrgNumber, // Personnummer / orgnr
                'Role': 'Mottaker' // 5: Avsender 6: Mottaker Codetable: Activity - Contact Role
              }
            ]
          }
        ],
        'Files': [
          {
            'CreateFileParameter': {
              'Base64Data': options.file, // Must be base64 encoded
              'Category': 'Brev', // Codetable: File category
              'Format': 'PDF', // Codetable: File format
              'Status': 'F', // Codetable: FileStatus
              'Title': options.fileTitle,
              'VersionFormat': 'A' // Codetable: File status
            }
          }
        ],
        'Paragraph': 'Offl §13 jfr Fvl §13.1', // Codetable: Paragraph
        'ResponsibleEnterpriseNumber': options.schoolOrgNumber, // Recnr ansvarlig virksomhet
        'ResponsiblePersonRecno': config.minelev.main_responsiblePersonRecno,
        'Status': 'J', // Codetable: Document status
        'Title': options.offTitle,
        'UnofficialTitle': options.title,
        'Archive': 'Saksdokument', // Codetable: Document archive
        'CaseNumber': options.caseNumber,
        'SendersReference': ''
      }
    }
  }
  return meta
}
253695
def metadata_filter_as_dict(metadata_config):
    """'"""

    if metadata_config is None:
        return {}

    if metadata_config is True:
        return {'additional': 'all'}

    if metadata_config is False:
        return {'excluded': 'all'}

    if isinstance(metadata_config, dict):
        assert set(metadata_config) <= set(['additional', 'excluded'])
        return metadata_config

    metadata_keys = metadata_config.split(',')

    metadata_config = {}

    for key in metadata_keys:
        key = key.strip()
        if key.startswith('-'):
            metadata_config.setdefault('excluded', []).append(key[1:].strip())
        elif key.startswith('+'):
            metadata_config.setdefault('additional', []).append(key[1:].strip())
        else:
            metadata_config.setdefault('additional', []).append(key)

    for section in metadata_config:
        if 'all' in metadata_config[section]:
            metadata_config[section] = 'all'
        else:
            metadata_config[section] = [key for key in metadata_config[section] if key]

    return metadata_config
1029329
def _parse_metadata(self, meta):
        
        output = {}
        for name, value in meta.items():
            name = name.lower()
            if name == "summary":
                value = textile(value)
            output[name] = self.process_metadata(name, value)
        return output
655095
def get_metadata_as_dict(fname):
    
    imgdict = {}
    try:
        imgdict['filename'] = fname
        imgdict['size'] = str(os.path.getsize(fname)) 
        imgdict['basename'] = os.path.basename(fname)
        imgdict['path'] = os.path.dirname(fname)
        img = Image.open(fname)
        # get the image's width and height in pixels
        width, height = img.size
        imgdict['width'] = str(width)
        imgdict['height'] = str(height)
        imgdict['format'] = str(img.format) 
        imgdict['palette'] = str(img.palette)
        stat = ImageStat.Stat(img)
         
        #res = res + q + str(stat.extrema) + q + d
        imgdict['count'] =  List2String(stat.count, ",")
        imgdict['sum'] =  List2String(stat.sum, ",")
        imgdict['sum2'] =  List2String(stat.sum2, ",")
        imgdict['mean'] =  List2String(stat.mean, ",") 
        imgdict['median'] =  List2String(stat.median, ",") 
        imgdict['rms'] =  List2String(stat.rms, ",") 
        imgdict['var'] =  List2String(stat.var, ",")
        imgdict['stddev'] =  List2String(stat.stddev, ",") 

        exif_data = get_exif_data(img)
        print('exif_data = ', exif_data)
        (lat, lon) = get_lat_lon(exif_data)
        print('(lat, lon)', (lat, lon))
        imgdict['lat'] =  str(lat)
        imgdict['lon'] =  str(lon)
    except Exception as ex:
        print('problem reading image file metadata in ', fname, str(ex))
        imgdict['lat'] =  'ERROR'
        imgdict['lon'] =  'ERROR'
    return imgdict
184747
def convert(self):
        
        try:
            return utils.encode_dict(self.metainfo)
        except ValueError as e:
            raise error.MetainfoError(str(e))
1068670
def _convert_to_db_tc_metadata(tc_metadata):
        
        db_meta = copy.deepcopy(tc_metadata)

        # tcid is a mandatory field, it should throw an error if it is missing
        db_meta['tcid'] = db_meta['name']
        del db_meta['name']

        # Encapsulate current status inside dictionary
        if 'status' in db_meta:
            status = db_meta['status']
            del db_meta['status']
            db_meta['status'] = {'value': status}

        # Node and dut information
        if 'requirements' in db_meta:
            db_meta['requirements']['node'] = {'count': 1}
            try:
                count = db_meta['requirements']['duts']['*']['count']
                db_meta['requirements']['node']['count'] = count
            except KeyError:
                pass

        # Collect and pack other info from meta
        db_meta['other_info'] = {}
        if 'title' in db_meta:
            db_meta['other_info']['title'] = db_meta['title']
            del db_meta['title']

        if 'feature' in db_meta:
            db_meta['other_info']['features'] = db_meta['feature']
            del db_meta['feature']
        else:
            db_meta['other_info']['features'] = ['unknown']

        if 'component' in db_meta:
            db_meta['other_info']['components'] = db_meta["component"]
            del db_meta['component']

        return db_meta
1366216
def get_meta(self, key=None):
        """"""
        if self.is_fake:
            return {}

        if key == "tag":
            return self.tag
        elif key is None:
            ret = {}
            for key in self.journal.info.keys():
                ret[key] = self.meta_mappings.map_get(self.journal.info, key)[1]
            return ret
        else:
            key, value = self.meta_mappings.map_get(self.journal.info, key)
            return value
1075860
def _set_metadata(self):
        
        meta = QueryDbMeta()
        with self._engine.connect() as conn:
            meta.bind = conn
            meta.reflect()
            self._meta = meta

        # Set an inspect attribute, whose subattributes
        # return individual tables / columns. Tables and columns
        # are special classes with .last() and other convenience methods
        self.inspect = QueryDbAttributes()
        for table in self._meta.tables:
            setattr(self.inspect, table,
                    QueryDbOrm(self._meta.tables[table], self))

            table_attr = getattr(self.inspect, table)
            table_cols = table_attr.table.columns

            for col in table_cols.keys():
                setattr(table_attr, col,
                        QueryDbOrm(table_cols[col], self))

            # Finally add some summary info:
            #   Table name
            #   Primary Key item or list
            #   N of Cols
            #   Distinct Col Values (class so NVARCHAR(20) and NVARCHAR(30) are not different)
            primary_keys = table_attr.table.primary_key.columns.keys()
            self._summary_info.append((
                table,
                primary_keys[0] if len(primary_keys) == 1 else primary_keys,
                len(table_cols),
                len(set([x.type.__class__ for x in table_cols.values()])),
                ))
550590
def _to_dict(self):
        """"""
        _dict = {}
        if hasattr(self, 'document_id') and self.document_id is not None:
            _dict['document_id'] = self.document_id
        if hasattr(self, 'field') and self.field is not None:
            _dict['field'] = self.field
        if hasattr(self, 'start_offset') and self.start_offset is not None:
            _dict['start_offset'] = self.start_offset
        if hasattr(self, 'end_offset') and self.end_offset is not None:
            _dict['end_offset'] = self.end_offset
        if hasattr(self, 'entities') and self.entities is not None:
            _dict['entities'] = [x._to_dict() for x in self.entities]
        return _dict
597340
def _from_dict(cls, _dict):
        """"""
        args = {}
        if 'collection_id' in _dict:
            args['collection_id'] = _dict.get('collection_id')
        if 'name' in _dict:
            args['name'] = _dict.get('name')
        if 'description' in _dict:
            args['description'] = _dict.get('description')
        if 'created' in _dict:
            args['created'] = string_to_datetime(_dict.get('created'))
        if 'updated' in _dict:
            args['updated'] = string_to_datetime(_dict.get('updated'))
        if 'status' in _dict:
            args['status'] = _dict.get('status')
        if 'configuration_id' in _dict:
            args['configuration_id'] = _dict.get('configuration_id')
        if 'language' in _dict:
            args['language'] = _dict.get('language')
        if 'document_counts' in _dict:
            args['document_counts'] = DocumentCounts._from_dict(
                _dict.get('document_counts'))
        if 'disk_usage' in _dict:
            args['disk_usage'] = CollectionDiskUsage._from_dict(
                _dict.get('disk_usage'))
        if 'training_status' in _dict:
            args['training_status'] = TrainingStatus._from_dict(
                _dict.get('training_status'))
        if 'source_crawl' in _dict:
            args['source_crawl'] = SourceStatus._from_dict(
                _dict.get('source_crawl'))
        return cls(**args)