Get a list of parsed recipes from BeerXML input
2112
def parse(self, xml_file):
        ""

        recipes = []

        with open(xml_file, "rt") as f:
            tree = ElementTree.parse(f)

        for recipeNode in tree.iter():
            if self.to_lower(recipeNode.tag) != "recipe":
                continue

            recipe = Recipe()
            recipes.append(recipe)

            for recipeProperty in list(recipeNode):
                tag_name = self.to_lower(recipeProperty.tag)

                if tag_name == "fermentables":
                    for fermentable_node in list(recipeProperty):
                        fermentable = Fermentable()
                        self.nodes_to_object(fermentable_node, fermentable)
                        recipe.fermentables.append(fermentable)

                elif tag_name == "yeasts":
                    for yeast_node in list(recipeProperty):
                        yeast = Yeast()
                        self.nodes_to_object(yeast_node, yeast)
                        recipe.yeasts.append(yeast)

                elif tag_name == "hops":
                    for hop_node in list(recipeProperty):
                        hop = Hop()
                        self.nodes_to_object(hop_node, hop)
                        recipe.hops.append(hop)

                elif tag_name == "miscs":
                    for misc_node in list(recipeProperty):
                        misc = Misc()
                        self.nodes_to_object(misc_node, misc)
                        recipe.miscs.append(misc)

                elif tag_name == "style":
                    style = Style()
                    recipe.style = style
                    self.nodes_to_object(recipeProperty, style)

                elif tag_name == "mash":

                    for mash_node in list(recipeProperty):
                        mash = Mash()
                        recipe.mash = mash

                        if self.to_lower(mash_node.tag) == "mash_steps":
                            for mash_step_node in list(mash_node):
                                mash_step = MashStep()
                                self.nodes_to_object(mash_step_node, mash_step)
                                mash.steps.append(mash_step)
                        else:
                            self.nodes_to_object(mash_node, mash)

                else:
                    self.node_to_object(recipeProperty, recipe)

        return recipes
322589
def get_dependency_tuple_list_for_recipe(recipe, blacklist=None):
    
    if blacklist is None:
        blacklist = set()
    assert(type(blacklist) == set)
    if recipe.depends is None:
        dependencies = []
    else:
        # Turn all dependencies into tuples so that product will work
        dependencies = fix_deplist(recipe.depends)

        # Filter out blacklisted items and turn lowercase:
        dependencies = [
            tuple(set(deptuple) - blacklist)
            for deptuple in dependencies
            if tuple(set(deptuple) - blacklist)
        ]
    return dependencies
679488
def p_simple_list(p):
    ''''''
    tok = p.lexer
    heredoc.gatherheredocuments(tok)

    if len(p) == 3 or len(p[1]) > 1:
        parts = p[1]
        if len(p) == 3:
            parts.append(ast.node(kind='operator', op=p[2], pos=p.lexspan(2)))
        p[0] = ast.node(kind='list', parts=parts, pos=_partsspan(parts))
    else:
        assert len(p[1]) == 1
        p[0] = p[1][0]

    if (len(p) == 2 and p.lexer._parserstate & flags.parser.CMDSUBST and
            p.lexer._current_token.nopos() == p.lexer._shell_eof_token):
        # accept the input
        p.accept()
896610
private Bom parse(StreamSource streamSource) throws ParseException {
        try {
            final Schema schema = getXmlSchema(CycloneDxSchema.Version.VERSION_11);
            final XmlMapper mapper = new XmlMapper();

            // Prevent XML External Entity Injection
            final XMLInputFactory xif = XMLInputFactory.newFactory();
            xif.setProperty(XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES, false);
            xif.setProperty(XMLInputFactory.SUPPORT_DTD, false);
            final XMLStreamReader xsr = new NamespaceStreamReaderDelegate(
                    xif.createXMLStreamReader(streamSource));
            final Bom bom = mapper.readValue(xsr, Bom.class);
            xsr.close();
            return bom;
        } catch (IOException | XMLStreamException | SAXException e) {
            throw new ParseException(e);
        }
    }
574429
def __parseThunks(self, thunkRVA, importSection):
        """"""
        offset = to_offset(thunkRVA, importSection)
        table_offset = 0
        thunks = []
        while True:
            thunk = IMAGE_THUNK_DATA.from_buffer(importSection.raw, offset)
            offset += sizeof(IMAGE_THUNK_DATA)
            if thunk.Ordinal == 0:
                break
            thunkData = ThunkData(header=thunk, rva=table_offset+thunkRVA,ordinal=None, importByName=None)
            if to_offset(thunk.AddressOfData, importSection) > 0 and to_offset(thunk.AddressOfData, importSection) < len(self._bytes):
                self.__parseThunkData(thunkData, importSection)
            thunks.append(thunkData)
            table_offset += 4
        return thunks
741104
def get_recipe_env(self, arch=None, with_flags_in_cc=True):
        
        env = super(GeventRecipe, self).get_recipe_env(arch, with_flags_in_cc)
        # CFLAGS may only be used to specify C compiler flags, for macro definitions use CPPFLAGS
        regex = re.compile(r'(?:\s|^)-[DI][\S]+')
        env['CPPFLAGS'] = ''.join(re.findall(regex, env['CFLAGS'])).strip()
        env['CFLAGS'] = re.sub(regex, '', env['CFLAGS'])
        info('Moved "{}" from CFLAGS to CPPFLAGS.'.format(env['CPPFLAGS']))
        # LDFLAGS may only be used to specify linker flags, for libraries use LIBS
        regex = re.compile(r'(?:\s|^)-l[\w\.]+')
        env['LIBS'] = ''.join(re.findall(regex, env['LDFLAGS'])).strip()
        env['LDFLAGS'] = re.sub(regex, '', env['LDFLAGS'])
        info('Moved "{}" from LDFLAGS to LIBS.'.format(env['LIBS']))
        return env
207333
def check_recipe_choices(self):
        ''''''
        recipes = []
        built_recipes = self.ctx.recipe_build_order
        for recipe in self.recipe_depends:
            if isinstance(recipe, (tuple, list)):
                for alternative in recipe:
                    if alternative in built_recipes:
                        recipes.append(alternative)
                        break
        return sorted(recipes)
395305
def _parse_references(xml):
    """"""
    references = []
    ref_finder = HTMLReferenceFinder(xml)
    for elm, uri_attr in ref_finder:
        type_ = _discover_uri_type(elm.get(uri_attr))
        references.append(Reference(elm, type_, uri_attr))
    return references
1342147
def get_nodes_with_recipe(recipe_name, environment=None):
    
    prefix_search = recipe_name.endswith("*")
    if prefix_search:
        recipe_name = recipe_name.rstrip("*")
    for n in get_nodes(environment):
        recipes = get_recipes_in_node(n)
        for role in get_roles_in_node(n, recursive=True):
            recipes.extend(get_recipes_in_role(role))
        if prefix_search:
            if any(recipe.startswith(recipe_name) for recipe in recipes):
                yield n
        else:
            if recipe_name in recipes:
                yield n
929801
def get_nodes(environment=None):
    """"""
    if not os.path.exists('nodes'):
        return []
    nodes = []
    for filename in sorted(
            [f for f in os.listdir('nodes')
             if (not os.path.isdir(f)
                 and f.endswith(".json") and not f.startswith('.'))]):
        fqdn = ".".join(filename.split('.')[:-1])  # Remove .json from name
        node = get_node(fqdn)
        if environment is None or node.get('chef_environment') == environment:
            nodes.append(node)
    return nodes
1261124
def build_recipe_input(self, ob, dal):
        """"""

        result = {}
        # We have to decide if the ob input
        # is a plain description (ObservingBlock)
        # or if it contains the nested results (Obsres)
        #
        # it has to contain the tags corresponding to the observing modes...
        ob_query_skip = False
        ob_query_field = 'obresult'

        if isinstance(ob, ObservingBlock):
            import numina.types.obsresult as obtype
            # We have to build an Obsres
            for key, req in self.requirements().items():
                if isinstance(req.type, obtype.ObservationResultType):
                    ob_query_field = key
                    ob_query_skip = True
                    query_option = self.query_options.get(key)

                    # print('req for ob is named', key, query_option)
                    new_or = ObservationResult()
                    new_or.__dict__ = ob.__dict__
                    obsres = req.query(dal, new_or, options=query_option)
                    tagger = self.mode.tagger
                    if tagger is not None:
                        self.logger.debug('Use mode tagger to fill tags in OB')
                        obsres.tags = tagger(obsres)
                    else:
                        obsres.tags = None
                    break
            else:
                # nothing to do
                obsres = ob
        else:
            obsres = ob

        # Get tags_names per REQ
        self.logger.debug('getting query fields per REQ')
        qfields = set()
        for key, req in self.requirements().items():
            tag_n = req.tag_names()
            self.logger.debug("%s has these query fields %s", key, tag_n)
            qfields.update(tag_n)

        if obsres.tags is None:
            self.logger.debug('running recipe tagger')
            self.logger.debug('with query fields %s', qfields)
            if qfields:
                obsres.tags = self.obsres_extractor(obsres, qfields)
            else:
                obsres.tags = {}

        for key, req in self.requirements().items():

            try:
                query_option = self.query_options.get(key)
                if key == ob_query_field and ob_query_skip:
                    result[key] = obsres
                else:
                    result[key] = req.query(dal, obsres, options=query_option)
            except NoResultFound as notfound:
                req.on_query_not_found(notfound)

        return self.create_input(**result)
716026
def get_trees(self, data, showerrors = False): # -> list:
        
        if showerrors:
            raise NotImplementedError("This parser doesn't implement errors")
        self.data = data
        self.index = 0
        try:
            return [self.__aux_parser(self._productionset.initialsymbol)]
        except (IndexError, ParseError):
            return []
185257
def create_recipe_file_logger(logger, logfile, logformat):
    """"""
    recipe_formatter = logging.Formatter(logformat)
    fh = logging.FileHandler(logfile, mode='w')
    fh.setLevel(logging.DEBUG)
    fh.setFormatter(recipe_formatter)
    return fh
631792
public List<XLog> parse(InputStream is) throws Exception {
		BufferedInputStream bis = new BufferedInputStream(is);
		// set up a specialized SAX2 handler to fill the container
		MxmlHandler handler = new MxmlHandler();
		// set up SAX parser and parse provided log file into the container
		SAXParserFactory parserFactory = SAXParserFactory.newInstance();
		SAXParser parser = parserFactory.newSAXParser();
		parser.parse(bis, handler);
		bis.close();
		return handler.getLogs();
	}
1157615
def asList( self ):
        """"""
        out = []
        for res in self.__toklist:
            if isinstance(res,ParseResults):
                out.append( res.asList() )
            else:
                out.append( res )
        return out
886381
def get_bootstrap_from_recipes(cls, recipes, ctx):
        ''''''
        info('Trying to find a bootstrap that matches the given recipes.')
        bootstraps = [cls.get_bootstrap(name, ctx)
                      for name in cls.list_bootstraps()]
        acceptable_bootstraps = []
        for bs in bootstraps:
            if not bs.can_be_chosen_automatically:
                continue
            possible_dependency_lists = expand_dependencies(bs.recipe_depends)
            for possible_dependencies in possible_dependency_lists:
                ok = True
                for recipe in possible_dependencies:
                    recipe = Recipe.get_recipe(recipe, ctx)
                    if any([conflict in recipes for conflict in recipe.conflicts]):
                        ok = False
                        break
                for recipe in recipes:
                    try:
                        recipe = Recipe.get_recipe(recipe, ctx)
                    except ValueError:
                        conflicts = []
                    else:
                        conflicts = recipe.conflicts
                    if any([conflict in possible_dependencies
                            for conflict in conflicts]):
                        ok = False
                        break
                if ok and bs not in acceptable_bootstraps:
                    acceptable_bootstraps.append(bs)
        info('Found {} acceptable bootstraps: {}'.format(
            len(acceptable_bootstraps),
            [bs.name for bs in acceptable_bootstraps]))
        if acceptable_bootstraps:
            info('Using the first of these: {}'
                 .format(acceptable_bootstraps[0].name))
            return acceptable_bootstraps[0]
        return None
578561
def generate_help():
  """"""
  help_text = '\nAvailable recipes:\n\n'
  recipes = config.Config.get_registered_recipes()
  for contents, _, _ in sorted(recipes, key=lambda k: k[0]['name']):
    help_text += ' {0:<35s}{1:s}\n'.format(
        contents['name'], contents.get('short_description', 'No description'))
  return help_text