Print out YAML using the block mode
344457
def format_return_text(self, data, function, **kwargs):  # pylint: disable=unused-argument
        '''
        
        '''
        # emulate the yaml_out output formatter. It relies on a global __opts__ object which
        # we can't obviously pass in
        try:
            try:
                outputter = data[next(iter(data))].get('out')
            except (StopIteration, AttributeError):
                outputter = None
            return salt.output.string_format(
                {x: y['return'] for x, y in six.iteritems(data)},
                out=outputter,
                opts=__opts__,
            )
        except Exception as exc:
            import pprint
            log.exception(
                'Exception encountered when trying to serialize %s',
                pprint.pformat(data)
            )
            return 'Got an error trying to serialze/clean up the response'
580893
def write_yaml(data, out_path, Dumper=yaml.Dumper, **kwds):
    ''''''
    import errno
    import os

    class OrderedDumper(Dumper):
        pass
    def _dict_representer(dumper, data):
        return dumper.represent_mapping(
            yaml.resolver.BaseResolver.DEFAULT_MAPPING_TAG,
            data.items())

    OrderedDumper.add_representer(OrderedDict, _dict_representer)

    # Make directory for calibration file if does not exist
    base_path, file_name = os.path.split(out_path)
    try:
        os.makedirs(base_path)
    except OSError as exc: # Python >2.5
        if exc.errno == errno.EEXIST and os.path.isdir(base_path):
            pass
        else: raise

    # Write dictionary to YAML
    with open(out_path, 'w') as f:
        return yaml.dump(data, f, OrderedDumper, default_flow_style=False, **kwds)
896589
def yaml_from_file(self, fpath):
        

        lookup = self._load_param_file(fpath)
        if not lookup:
            return

        content = "\n".join(self.content)
        parsed = yaml.safe_load(content)
        # self.app.info("Params loaded is %s" % parsed)
        # self.app.info("Lookup table looks like %s" % lookup)
        new_content = list()
        for paramlist in parsed:
            if not isinstance(paramlist, dict):
                self.app.warn(
                    ("Invalid parameter definition ``%s``. Expected "
                     "format: ``name: reference``. "
                     " Skipping." % paramlist),
                    (self.state_machine.node.source,
                     self.state_machine.node.line))
                continue
            for name, ref in paramlist.items():
                if ref in lookup:
                    new_content.append((name, lookup[ref]))
                else:
                    self.app.warn(
                        ("No field definition for ``%s`` found in ``%s``. "
                         " Skipping." % (ref, fpath)),
                        (self.state_machine.node.source,
                         self.state_machine.node.line))

        # self.app.info("New content %s" % new_content)
        self.yaml = new_content
1283728
def cli(yamlfile, root, format):
    
    print(CsvGenerator(yamlfile, format).serialize(classes=root))
719035
function extractYamlHeader(src, context) {
    var splits = src.split(yamlheadsep), yamlheader, markdown = src;
    // we might have a yaml markdown header
    if (splits.length > 1) {
      grunt.verbose.writeln("");
      grunt.verbose.write("Yaml header detected...");
      try {
        yamlheader = YAML.load(splits[0]);
        grunt.verbose.ok();
      } catch(e) {
        grunt.log.error("Yaml header is probably not valid", e);
        return;
      }

      grunt.verbose.writeln("Exposing header variables to context...");
      Object.keys(yamlheader).forEach(function(key) {
        context[key] = yamlheader[key];
        grunt.verbose.ok("'" + key + "'", '->', yamlheader[key]);
      });

      markdown = splits.splice(2).join("\n"); // The actual markdown to be process
    }
    return markdown;
  }
124687
def yaml(self):
        
        return ordered_dump(OrderedDict(self),
                            Dumper=yaml.SafeDumper,
                            default_flow_style=False)
267418
def to_yaml
      require 'yaml'
      trackers_export = @trackers.reduce({}) do |export, tracker|
        export[tracker.title] = tracker.to_yaml_object; export
      end
      YAML.dump(trackers_export)
    end
41753
def parse_yaml(self, y):
        '''

        '''
        self.name = y['name']
        if 'data' in y:
            self.data = y['data']
        else:
            self.data = ''
        return self
464962
def dump(esp, _efuses, args):
    
    for block in range(len(EFUSE_BLOCK_OFFS)):
        print("EFUSE block %d:" % block)
        offsets = [x + EFUSE_BLOCK_OFFS[block] for x in range(EFUSE_BLOCK_LEN[block])]
        print(" ".join(["%08x" % esp.read_efuse(offs) for offs in offsets]))
710827
def create_yaml(directory, project_name, board,output_dir):
    # lay out what the common section a project yaml file will look like
    # The value mapped to by each key are the file extensions that will help us get valid files for each section
    logger.debug("Project name: %s, Target: %s"%(project_name,board))
    common_section = {
        'linker_file': FILES_EXTENSIONS['linker_file'],
        'sources': FILES_EXTENSIONS['source_files_c'] + FILES_EXTENSIONS['source_files_cpp'] +
                   FILES_EXTENSIONS['source_files_s'] + FILES_EXTENSIONS['source_files_obj'],
        'includes': FILES_EXTENSIONS['include_files']
    }

    # will be written to projects.yaml
    root = os.path.relpath(directory)
    projects_yaml = {
        'projects': {
            project_name:
                ['project.yaml']
        },
        'settings': {'export_dir': os.path.relpath(output_dir)}
    }

    # will be written to project.yaml
    project_yaml = {
        'common': {},
        'tool_specific': {}
    }
    # iterate over the common section defined above
    for section, extensions in common_section.items():
        # look for files in this directory that have the defined extensions, and add them to our project file
        project_yaml['common'][section] = _scan(section, directory,extensions)

    project_yaml['common']['target'] = [board] # user passes target in command line

    """"""
    tools = _determine_tool(project_yaml['common']['linker_file'])

    linkers = {}   # dictionary containing all linker files in the project directory

    # exhaust the iterator and add its yielded values to linkers
    for (file,tool) in tools:
        if tool in linkers:
            linkers[tool].append(file)
        else:
            linkers[tool] = [file]

    for tool, linker in linkers.items():
        if len(linker) > 1:
            # The project directory defined more than one linker for a tool
            print("\nMultipe linkers found for " + tool + "\n")
            for i, file in enumerate(linker):
                print(str(i) + ": " + file)
            answer = raw_input('\nWhich file do you want? ')
            while int(answer) not in range(0,len(linker)):
                answer = raw_input('Answer not in list. Which file do you want? ')
            project_yaml['tool_specific'][tool] = {'linker_file': [linkers[tool][int(answer)]]}
        else:
            project_yaml['tool_specific'][tool] = {'linker_file': linker}

    # linker file is now in tool_specific section
    del project_yaml['common']['linker_file']

    ret = _generate_file("projects.yaml", projects_yaml)
    if ret < 0: # make sure the first file generated correctly
        return -1
    ret = _generate_file("project.yaml", project_yaml)
    return ret
647287
def write(self, title, data, output=None):
        '''
        
        '''
        if not isinstance(data, (dict, list, tuple)):
            data = {'raw-content': str(data)}
        output = output or self.__default_outputter

        if output != 'null':
            try:
                if isinstance(data, dict) and 'return' in data:
                    data = data['return']
                content = self._printout(data, output)
            except Exception:  # Fall-back to just raw YAML
                content = None
        else:
            content = None

        if content is None:
            data = json.loads(json.dumps(data))
            if isinstance(data, dict) and data.get('return'):
                data = data.get('return')
            content = yaml.safe_dump(data, default_flow_style=False, indent=4)

        self.__current_section.append({title: content})
1010513
def write_example_yaml(cls, dest, skip=()):
        
        # Make sure we can make an instance before we open a file.
        inst = cls.example_instance(skip=skip)
        with open(dest, 'w') as f:
            inst.to_yaml(stream=f, skip=skip)
13245
def _extract_yaml_docstring(stream):
        '''
        
        '''
        comment_lines = []
        lines = stream.read().splitlines()
        for line in lines:
            line_strip = line.strip()
            if not line_strip:
                continue
            if line_strip.startswith('#'):
                comment_lines.append(
                    line_strip.replace('#', '', 1).strip()
                )
            else:
                break
        return ' '.join(comment_lines)
275082
def yamline_read(lines = nil, loaded = true)
      lines = file_lines unless lines
      return unless lines
      matcher = %r{^#{Regexp.escape(@yamline_settings[:prefix] + @yamline_settings[:name])}(.*?)#{Regexp.escape(@yamline_settings[:postfix])}$}
      line_l = []
      line_s = lines.select {|line| line_l << YAML::load($1) if line =~ matcher }
      return if line_s.empty?
      loaded ? line_l : line_s
    end
1082884
def ordered_yaml_dump(data, stream=None, Dumper=None, **kwds):
    """"""
    Dumper = Dumper or yaml.Dumper

    class OrderedDumper(Dumper):
        pass

    def _dict_representer(dumper, data):
        return dumper.represent_mapping(
            yaml.resolver.BaseResolver.DEFAULT_MAPPING_TAG,
            data.items())
    OrderedDumper.add_representer(OrderedDict, _dict_representer)
    return yaml.dump(data, stream, OrderedDumper, **kwds)
342898
def main(args):  ## pylint: disable=too-many-branches
    """"""

    EXNAME = os.path.basename(__file__ if WIN32 else sys.argv[0])

    for ext in (".py", ".pyc", ".exe", "-script.py", "-script.pyc"):  ## pragma: no cover
        if EXNAME.endswith(ext):  ## pragma: no cover
            EXNAME = EXNAME[:-len(ext)]
            break

    USAGE = """\
    Usage:

        %(exname)s {-h|--help}
        %(exname)s {-V|--version}
        %(exname)s [-y|--yaml] [-q|--quiet] ACTION KEY [DEFAULT]
    """ % {"exname": EXNAME}

    HELP = """
    Parses and output chosen subpart or values from YAML input.
    It reads YAML in stdin and will output on stdout it's return value.

%(usage)s

    Options:

        -y, --yaml
                  Output only YAML safe value, more precisely, even
                  literal values will be YAML quoted. This behavior
                  is required if you want to output YAML subparts and
                  further process it. If you know you have are dealing
                  with safe literal value, then you don't need this.
                  (Default: no safe YAML output)

        -q, --quiet
                  In case KEY value queried is an invalid path, quiet
                  mode will prevent the writing of an error message on
                  standard error.
                  (Default: no quiet mode)

        -L, --line-buffer
                  Force parsing stdin line by line allowing to process
                  streamed YAML as it is fed instead of buffering
                  input and treating several YAML streamed document
                  at once. This is likely to have some small performance
                  hit if you have a huge stream of YAML document, but
                  then you probably don't really care about the
                  line-buffering.
                  (Default: no line buffering)

        ACTION    Depending on the type of data you've targetted
                  thanks to the KEY, ACTION can be:

                  These ACTIONs applies to any YAML type:

                    get-type          ## returns a short string
                    get-value         ## returns YAML

                  These ACTIONs applies to 'sequence' and 'struct' YAML type:

                    get-values{,-0}   ## returns list of YAML
                    get-length        ## returns an integer

                  These ACTION applies to 'struct' YAML type:

                    keys{,-0}         ## returns list of YAML
                    values{,-0}       ## returns list of YAML
                    key-values,{,-0}  ## returns list of YAML

                  Note that any value returned is returned on stdout, and
                  when returning ``list of YAML``, it'll be separated by
                  a newline or ``NUL`` char depending of you've used the
                  ``-0`` suffixed ACTION.

        KEY       Identifier to browse and target subvalues into YAML
                  structure. Use ``.`` to parse a subvalue. If you need
                  to use a literal ``.`` or ``\\``, use ``\\`` to quote it.

                  Use struct keyword to browse ``struct`` YAML data and use
                  integers to browse ``sequence`` YAML data.

        DEFAULT   if not provided and given KEY do not match any value in
                  the provided YAML, then DEFAULT will be returned. If no
                  default is provided and the KEY do not match any value
                  in the provided YAML, %(exname)s will fail with an error
                  message.

    Examples:

         ## get last grocery
         cat recipe.yaml       | %(exname)s get-value groceries.-1

         ## get all words of my french dictionary
         cat dictionaries.yaml | %(exname)s keys-0 french.dictionary

         ## get YAML config part of 'myhost'
         cat hosts_config.yaml | %(exname)s get-value cfgs.myhost

    """ % {"exname": EXNAME, "usage": USAGE}

    USAGE = textwrap.dedent(USAGE)
    HELP = textwrap.dedent(HELP)

    opts = _parse_args(args, USAGE, HELP)
    quiet = opts.pop("quiet")

    try:
        first = True
        for output in do(stream=sys.stdin, **opts):
            if first:
                first = False
            else:
                if opts["action"] not in ACTION_SUPPORTING_STREAMING:
                    die("Source YAML is multi-document, "
                        "which doesn't support any other action than %s"
                        % ", ".join(ACTION_SUPPORTING_STREAMING))
                if opts["dump"] is yaml_dump:
                    print("---\n", end="")
                else:
                    print("\0", end="")
                if opts.get("loader") is LineLoader:
                    sys.stdout.flush()

            print(output, end="")
            if opts.get("loader") is LineLoader:
                sys.stdout.flush()
    except (InvalidPath, ActionTypeError) as e:
        if quiet:
            exit(1)
        else:
            die(str(e))
    except InvalidAction as e:
        die("'%s' is not a valid action.\n%s"
            % (e.args[0], USAGE))
975048
def build_from_yamlstr(cls, yamlstr):
        
        top_dict = yaml.safe_load(yamlstr)
        coordsys = top_dict.pop('coordsys')
        output_list = []
        for e_key, e_dict in sorted(top_dict.items()):
            if e_key == 'coordsys':
                continue
            e_dict = top_dict[e_key]
            e_dict['coordsys'] = coordsys
            output_list += cls.build_from_energy_dict(e_key, e_dict)
        return output_list