Return correct str_presenter to write multiple lines to a yaml field.


    Source: http://stackoverflow.com/a/33300001
496153
def str_presenter(dmpr, data):
    
    if is_multiline(data):
        return dmpr.represent_scalar('tag:yaml.org,2002:str', data, style='|')
    return dmpr.represent_scalar('tag:yaml.org,2002:str', data)
114581
def save_yamlf(data: Union[list, dict], fpath: str, encoding: str) -> str:
    
    with codecs.open(fpath, mode='w', encoding=encoding) as f:
        f.write(dump_yaml(data))
        return fpath
163272
def yaml(self):
        
        if self._yaml_adapter is None:
            self._yaml_adapter = ConfigPersistenceAdapter(
                config=self,
                reader_writer=YamlReaderWriter(),
            )
        return self._yaml_adapter
983019
def YamlLoader(string):
  """"""
  representation = yaml.Parse(string)
  result_cls = aff4.FACTORY.AFF4Object(representation["aff4_class"])
  aff4_attributes = {}
  for predicate, values in iteritems(representation["attributes"]):
    attribute = aff4.Attribute.PREDICATES[predicate]
    tmp = aff4_attributes[attribute] = []

    for rdfvalue_cls_name, value, age in values:
      rdfvalue_cls = aff4.FACTORY.RDFValue(rdfvalue_cls_name)
      value = rdfvalue_cls(value, age=rdfvalue.RDFDatetime(age))
      tmp.append(value)

  # Ensure the object is dirty so when we save it, it can be written to the data
  # store.
  result = result_cls(
      urn=representation["_urn"],
      clone=aff4_attributes,
      mode="rw",
      age=representation["age_policy"])

  result.new_attributes, result.synced_attributes = result.synced_attributes, {}

  result._dirty = True  # pylint: disable=protected-access

  return result
686541
def ystr(args):
    
    from jcvi.utils.table import write_csv

    p = OptionParser(ystr.__doc__)
    p.set_home("lobstr")
    opts, args = p.parse_args(args)

    if len(args) != 1:
        sys.exit(not p.print_help())

    vcffile, = args
    si = STRFile(opts.lobstr_home, db="hg38-named")
    register = si.register

    header = "Marker|Reads|Ref|Genotype|Motif".split("|")
    contents = []
    fp = must_open(vcffile)
    reader = vcf.Reader(fp)
    simple_register = {}
    for record in reader:
        name = register[(record.CHROM, record.POS)]
        info = record.INFO
        ref = int(float(info["REF"]))
        rpa = info.get("RPA", ref)
        if isinstance(rpa, list):
            rpa = "|".join(str(int(float(x))) for x in rpa)
        ru = info["RU"]
        simple_register[name] = rpa
        for sample in record.samples:
            contents.append((name, sample["ALLREADS"], ref, rpa, ru))

    # Multi-part markers
    a, b, c = "DYS389I", "DYS389B.1", "DYS389B"
    if a in simple_register and b in simple_register:
        simple_register[c] = int(simple_register[a]) + int(simple_register[b])

    # Multi-copy markers
    mm = ["DYS385", "DYS413", "YCAII"]
    for m in mm:
        ma, mb = m + 'a', m + 'b'
        if ma not in simple_register or mb not in simple_register:
            simple_register[ma] = simple_register[mb] = None
            del simple_register[ma]
            del simple_register[mb]
            continue
        if simple_register[ma] > simple_register[mb]:
            simple_register[ma], simple_register[mb] = \
                    simple_register[mb], simple_register[ma]

    write_csv(header, contents, sep=" ")
    print("[YSEARCH]")
    build_ysearch_link(simple_register)
    print("[YFILER]")
    build_yhrd_link(simple_register, panel=YHRD_YFILER)
    print("[YFILERPLUS]")
    build_yhrd_link(simple_register, panel=YHRD_YFILERPLUS)
    print("[YSTR-ALL]")
    build_yhrd_link(simple_register, panel=USYSTR_ALL)
435930
def yaml_to_param(obj, name):
	
	return from_pyvalue(u"yaml:%s" % name, unicode(yaml.dump(obj)))
785948
def format_config_for_editing(data):
    """"""
    return yaml.safe_dump(data, default_flow_style=False, encoding=None, allow_unicode=True)
708418
def write_field_repr(self, name, out, visited):
        '''
        
        '''
        field_obj = self.pyop_field(name)
        field_obj.write_repr(out, visited)
937053
def model_yaml(self, **kwargs):
        
        kwargs_copy = self.base_dict.copy()
        kwargs_copy.update(**kwargs)
        self._replace_none(kwargs_copy)        
        localpath = NameFactory.model_yaml_format.format(**kwargs_copy)
        if kwargs.get('fullpath', False):
            return self.fullpath(localpath=localpath)
        return localpath
961146
def YamlDumper(aff4object):
  """"""
  aff4object.Flush()

  result = {}
  for attribute, values in iteritems(aff4object.synced_attributes):
    result[attribute.predicate] = []
    for value in values:
      # This value is really a LazyDecoder() instance. We need to get at the
      # real data here.
      value = value.ToRDFValue()

      result[attribute.predicate].append(
          [value.__class__.__name__,
           value.SerializeToString(),
           str(value.age)])

  return yaml.Dump({
      "aff4_class": compatibility.GetName(aff4object),
      "_urn": aff4object.urn.SerializeToString(),
      "attributes": result,
      "age_policy": aff4object.age_policy,
  })
1082748
def write_yaml(filename, content):
    '''
    
    '''

    y = _yaml.dump(content, indent=4, default_flow_style=False)
    if y:
        return write_file(filename, y)
677327
def serialize(obj, **options):
    '''
    
    '''

    options.setdefault('Dumper', Dumper)
    try:
        response = yaml.dump(obj, **options)
        if response.endswith('\n...\n'):
            return response[:-5]
        if response.endswith('\n'):
            return response[:-1]
        return response
    except Exception as error:
        log.exception('Error encountered while serializing')
        raise SerializationError(error)
1202677
def dump_yaml(data):
    
    return yaml.dump(data,
                     indent=2,
                     encoding=None,
                     allow_unicode=True,
                     default_flow_style=False,
                     Dumper=MyDumper)
1115615
public function toString()
    {
        $result = false;

        if ($encoder = $this->getEncoder())
        {
            $data   = $this->toArray();
            $result = call_user_func($encoder, $data);
        }
        else throw new RuntimeException("No Yaml encoder specified");

        return $result;
    }
733125
def safe_dump(data, stream=None, **kwargs):
    '''
    
    '''
    if 'allow_unicode' not in kwargs:
        kwargs['allow_unicode'] = True
    return yaml.dump(data, stream, Dumper=SafeOrderedDumper, **kwargs)
955659
def dump(config):
    

    return yaml.safe_dump(
        config.to_primitive(),
        default_flow_style=False,
        encoding='utf-8',
        allow_unicode=True)
1045529
def get_yaml_parser_roundtrip_for_context():
    
    yaml_writer = get_yaml_parser_roundtrip()

    # Context is a dict data structure, so can just use a dict representer
    yaml_writer.Representer.add_representer(
        Context,
        yamler.representer.RoundTripRepresenter.represent_dict)

    return yaml_writer