Extract metatdata property from a module
761707
def extract_attribute(module_name, attribute_name):
    """"""
    with open('%s/__init__.py' % module_name) as input_file:
        for line in input_file:
            if line.startswith(attribute_name):
                return ast.literal_eval(line.split('=')[1].strip())
1118387
function __debugMeta( object, type, meta ) {
	// Dont' re-define meta
	if ((object !== undefined) && (object.__meta === undefined)) {
		if (typeof object === 'object')
			Object.defineProperty(
				object, "__meta", {
					enumerable: false,
					value: {
						'type': type,
						'meta': meta,
					},
				}
			);
	}

	// Return object for return calls
	return object;
}
1012635
def find_val_for_first_bf_l_meta(d, prop_name):
    
    m_list = d.get('meta')
    if not m_list:
        return None
    if not isinstance(m_list, list):
        m_list = [m_list]
    for m_el in m_list:
        if m_el.get('@property') == prop_name:
            return extract_meta(m_el)
    return None
226141
function validateSetData (module, newData) {
    // require valid data
    if (typeof newData !== 'object' || newData === null) {
        throw new Error(`invalid data for ${module.meta.name}`)
    }
    // get data id
    var dataId = stableId(newData)
    // if data has not changed do not set
    if (dataId === module.meta.dataId) {
        return
    }
    // freeze data
    if (module.meta.options.freezeData) {
        deepFreeze(newData)
    }
    // set data id
    module.meta.dataId = dataId
    // log data set
    if (defined(module.meta.options.logClient)) {
        module.meta.options.logClient.log('setData', {
            data: newData,
            dataCreateTime: microTimestamp(),
            dataId: dataId,
            instanceId: instanceId.id,
            moduleName: module.meta.name,
        })
    }
    // return validated data
    return newData
}
737871
def _attr_to_property(self, attr):
        """"""

        # get the property
        prop = self._properties.get(attr)
        if not prop:
            raise PropertyError(attr)

        # found it
        return prop
622035
function addPropertyToModelMeta(modelName, property, meta) {
    if (!exports.propertiesByModel[modelName]) {
        exports.propertiesByModel[modelName] = {};
    }
    // TODO: investigate why we need to genericize to model (from <T>)
    exports.propertiesByModel[modelName][property] = meta;
}
778157
def getMetadata(L):
    
    _l = {}
    try:
        # Create a copy. Do not affect the original data.
        _l = copy.deepcopy(L)
        # Remove values fields
        _l = rm_values_fields(_l)
    except Exception as e:
        # Input likely not formatted correctly, though other problems can occur.
        print("Error: Unable to get data. Please check that input is LiPD data: {}".format(e))
    return _l
637142
def _to_meta_data(pif_obj, dataset_hit, mdf_acl):
    """"""
    pif = pif_obj.as_dictionary()
    dataset = dataset_hit.as_dictionary()
    mdf = {}
    try:
        if pif.get("names"):
            mdf["title"] = pif["names"][0]
        else:
            mdf["title"] = "Citrine PIF " + str(pif["uid"])

        if pif.get("chemicalFormula"):
            mdf["composition"] = pif["chemicalFormula"]
        elif pif.get("composition"):
            mdf["composition"] = ''.join([comp["element"] for comp in pif["composition"] if comp["element"]])
        if not mdf["composition"]:
            mdf.pop("composition")

        mdf["acl"] = mdf_acl
        mdf["source_name"] = _construct_new_key(dataset["name"])

        if pif.get("contacts"):
            mdf["data_contact"] = []
            for contact in pif["contacts"]:
                data_c = {
                    "given_name": contact["name"]["given"],  #REQ
                    "family_name": contact["name"]["family"]  #REQ
                    }
                if contact.get("email"):
                    data_c["email"] = contact.get("email", "")
                if contact.get("orcid"):
                    data_c["orcid"] = contact.get("orcid", "")
                mdf["data_contact"].append(data_c)
            if not mdf["data_contact"]:
                mdf.pop("data_contact")
        
        mdf["data_contributor"] = [{}] 
        if "owner" in dataset:
            name = dataset["owner"].split()
            contributor = {
                "given_name": name[0],
                "family_name": name[1],
                "email": dataset["email"]
            }
            mdf["data_contributor"] = [contributor]

        mdf["links"] = {
            "landing_page": "https://citrination.com/datasets/{}".format(dataset["id"]),
            "publication": []
            }
        if pif.get("references"):
            mdf["author"] = []
            mdf["citation"] = []
            for ref in pif["references"]:
                if ref.get("doi"):
                    mdf["citation"].append(ref["doi"]) #TODO: Make actual citation
                    mdf["links"]["publication"].append(ref["doi"])
                if ref.get("authors"):
                    for author in ref["authors"]:
                        if author.get("given") and author.get("family"):
                            mdf["author"].append({
                                "given_name": author["given"],
                                "family_name": author["family"]
                                })
            # Remove fields if blank
            if not mdf["author"]:
                mdf.pop("author")
            if not mdf["citation"]:
                mdf.pop("citation")
        if not mdf["links"]["publication"]:
            mdf["links"].pop("publication")

        if pif.get("licenses", [{}])[0].get("url"):
            mdf["license"] = pif["licenses"][0]["url"]
        if pif.get("tags"):
            mdf["tags"] = pif["tags"]

    # If required MDF metadata is missing from PIF, abort
    except KeyError as e:
        print("Error: Required MDF metadata", str(e), "not found in PIF", pif["uid"])
        return None

    return mdf
1289636
function normalizeModuleAndLoadMetadata(programPath) {

    nameAnonymousExports(programPath);

    const {local, source} = getModuleMetadata(programPath);

    removeModuleDeclarations(programPath);

    // Reuse the imported namespace name if there is one.
    for (const [, metadata] of source) {
        if (metadata.importsNamespace.size > 0) {
            // This is kind of gross. If we stop using `loose: true` we should
            // just make this destructuring assignment.
            metadata.name = metadata.importsNamespace.values().next().value;
        }
    }

    return {
        exportName: 'exports',
        exportNameListName: null,
        local,
        source
    };
}
870322
def parse_meta(content, meta_name, source_descr, content_attr_name="content"):
    
    dom = dhtmlparser.parseString(content)

    meta_tags = dom.find(
        "meta",
        fn=lambda x: x.params.get("name", "").lower() == meta_name.lower()
    )

    return [
        SourceString(tag.params[content_attr_name], source_descr)
        for tag in meta_tags
        if content_attr_name in tag.params
    ]
1141728
function extractAttribs( def ) {
    var key, val, attribs = { standard: {}, special: {}, implicit: [] };
    for ( key in def ) {
        val = def[ key ];
        if ( RX_INTEGER.test( key ) ) {
            attribs.implicit.push( val );
        } else if ( RX_STD_ATT.test( key ) ) {
            attribs.standard[ key ] = val;
        } else {
            attribs.special[ key ] = val;
        }
    }
    return attribs;
}
799536
@Override
    public ModuleMetaData createModuleMetaData(ExtendedModuleInfo moduleInfo) throws MetaDataException {
        WebModuleInfo webModule = (WebModuleInfo) moduleInfo;
        if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
            Tr.debug(tc, "createModuleMetaData: " + webModule.getName() + " " + webModule.getContextRoot());
        }
        try {
            com.ibm.wsspi.adaptable.module.Container webModuleContainer = webModule.getContainer();
            WebAppConfiguration appConfig = webModuleContainer.adapt(WebAppConfiguration.class);
            String appName = appConfig.getApplicationName();
            String j2eeModuleName = appConfig.getJ2EEModuleName();
            WebModuleMetaDataImpl wmmd = (WebModuleMetaDataImpl) appConfig.getMetaData();
            wmmd.setJ2EEName(j2eeNameFactory.create(appName, j2eeModuleName, null));
            appConfig.setWebApp(createWebApp(moduleInfo, appConfig));
            return wmmd;
        }
        catch (Throwable e) {
            Throwable cause = e.getCause();
            MetaDataException m;
            if ((cause!=null) && (cause instanceof MetaDataException)) {
                m = (MetaDataException) cause;
                //don't log a FFDC here as we already logged an exception
            } else {
                m = new MetaDataException(e);
                FFDCWrapper.processException(e, getClass().getName(), "createModuleMetaData", new Object[] { webModule, this });//this throws the exception
            }
            if (TraceComponent.isAnyTracingEnabled() && tc.isEventEnabled()) {
                Tr.event(tc, "createModuleMetaData: " + webModule.getName() + "; " + e);
            }
            throw m;
        }
    }
234231
def get_module_doc(module, config=default_config, already_met=None):
    """"""
    # Avoid recursion loops (init)
    if already_met is None:
        already_met = set()

    if config.exclude_module:
        for ex in config.exclude_module:
            if ex.match(module.__name__):
                return None

    # Force load submodules into module's dict
    if hasattr(module, '__path__'):
        subm = [
            modname for importer, modname, ispkg
            in pkgutil.iter_modules(module.__path__)
        ]
        __import__(module.__name__, fromlist=subm)

    # We don't want to include imported items,
    # so we parse the code to blacklist them.

    # Be sure to parse .py and not .pyc file on Python 2.X
    if hasattr(module, '__file__'):
        module_file = module.__file__
    else:
        module_file = inspect.getsourcefile(module)
    path, ext = os.path.splitext(module_file)
    if ext == '.pyc':
        module_file = path + '.py'

    try:
        code = open(module_file).read()
        body = ast.parse(code).body
    except SyntaxError:
        code = open(module_file).read().encode('utf-8')
        body = ast.parse(code).body

    imported = []
    for node in body:
        if isinstance(node, (ast.Import, ast.ImportFrom)):
            imported.extend([n.name for n in node.names])

    nested_doc = []
    module_dict = module.__dict__

    for item in dir(module):
        if item not in imported and item in module_dict.keys():
            # Avoid recursion loops
            if id(item) in already_met:
                continue
            already_met.add(id(item))

            appended = None
            if isinstance(module_dict[item], types.ModuleType):
                appended = get_module_doc(module_dict[item], config, already_met)  # noqa
            elif isinstance(module_dict[item], type):
                appended = get_class_doc(module_dict[item], config)
            elif isinstance(module_dict[item], types.FunctionType):
                appended = get_function_doc(module_dict[item], config)
            if appended is not None:
                nested_doc.append(appended)

    return _doc_object(module, 'module', nested_doc, config)
168782
@Override
    public ModuleMetaData createModuleMetaData(ExtendedModuleInfo moduleInfo) throws MetaDataException {
        Container container = moduleInfo.getContainer();
        ConnectorModuleMetaData cmmd;
        try {
            cmmd = container.adapt(ConnectorModuleMetaData.class);
        } catch (UnableToAdaptException e) {
            throw new MetaDataException(e);
        }
        return cmmd;
    }
478438
def extract_meta(cls, serializer, resource):
        
        if hasattr(serializer, 'child'):
            meta = getattr(serializer.child, 'Meta', None)
        else:
            meta = getattr(serializer, 'Meta', None)
        meta_fields = getattr(meta, 'meta_fields', [])
        data = OrderedDict()
        for field_name in meta_fields:
            data.update({
                field_name: resource.get(field_name)
            })
        return data
920910
function parse(meta) {
  if (typeof meta !== 'string') {
    throw new Error('`Parse`\'s first argument should be a string')
  }

  return meta.split(/[\r\n]/)
    .filter(function (line) { // remove blank line
      return /\S+/.test(line) &&
        line.indexOf('==UserScript==') === -1 &&
        line.indexOf('==/UserScript==') === -1
    })
    .reduce(function (obj, line) {
      var arr = line.trim().replace(/^\/\//, '').trim().split(/\s+/)
      var key = arr[0].slice(1)
      var value = arr.slice(1).join(' ')

      if (isUndefined(obj[key])) {
        obj[key] = value
      } else if (Array.isArray(obj[key])) {
        obj[key].push(value)
      } else {
        obj[key] = [obj[key], value]
      }

      return obj
    }, {})
}
1115380
private function getMetadata()
    {
        $this->logger->debug('[Metadata] Retrieving metadata...');

        $values = [];
        // property is a space-separated list of values
        $propertyPattern = '/\s*(dc|dcterm|og|twitter)\s*:\s*(author|creator|description|title|image)\s*/i';

        // name is a single value
        $namePattern = '/^\s*(?:(dc|dcterm|og|twitter|weibo:(article|webpage))\s*[\.:]\s*)?(author|creator|description|title|image)\s*$/i';

        // Find description tags.
        foreach ($this->dom->getElementsByTagName('meta') as $meta) {
            /* @var DOMNode $meta */
            $elementName = $meta->getAttribute('name');
            $elementProperty = $meta->getAttribute('property');
            $content = $meta->getAttribute('content');
            $matches = null;
            $name = null;

            if ($elementProperty) {
                if (preg_match($propertyPattern, $elementProperty, $matches)) {
                    for ($i = count($matches) - 1; $i >= 0; $i--) {
                        // Convert to lowercase, and remove any whitespace
                        // so we can match below.
                        $name = preg_replace('/\s/', '', mb_strtolower($matches[$i]));
                        // multiple authors
                        $values[$name] = trim($content);
                    }
                }
            }

            if (!$matches && $elementName && preg_match($namePattern, $elementName)) {
                $name = $elementName;
                if ($content) {
                    // Convert to lowercase, remove any whitespace, and convert dots
                    // to colons so we can match below.
                    $name = preg_replace(['/\s/', '/\./'], ['', ':'], mb_strtolower($name));
                    $values[$name] = trim($content);
                }
            }
        }

        // get title
        /*
         * This is a very convoluted way of extracting the first matching key of the $values array
         * against a set of options.
         *
         * This could be easily replaced with an ugly set of isset($values['key']) or a bunch of ??s.
         * Will probably replace it with ??s after dropping support of PHP5.6
         */

        $key = current(array_intersect([
            'dc:title',
            'dcterm:title',
            'og:title',
            'weibo:article:title',
            'weibo:webpage:title',
            'title',
            'twitter:title'
        ], array_keys($values)));

        $this->setTitle(isset($values[$key]) ? trim($values[$key]) : null);

        if (!$this->getTitle()) {
            $this->setTitle($this->getArticleTitle());
        }

        // get author
        $key = current(array_intersect([
            'dc:creator',
            'dcterm:creator',
            'author'
        ], array_keys($values)));

        $this->setAuthor(isset($values[$key]) ? $values[$key] : null);

        // get description
        $key = current(array_intersect([
            'dc:description',
            'dcterm:description',
            'og:description',
            'weibo:article:description',
            'weibo:webpage:description',
            'description',
            'twitter:description'
        ], array_keys($values)));

        $this->setExcerpt(isset($values[$key]) ? $values[$key] : null);

        // get main image
        $key = current(array_intersect([
            'og:image',
            'twitter:image'
        ], array_keys($values)));

        $this->setImage(isset($values[$key]) ? $values[$key] : null);
    }