Write a single association to a line in the output file
353872
def write_assoc(self, assoc):
        
        # Handle comment 'associations'
        if assoc.get("header", False):

            # Skip incoming gaf-version headers, as we created the version above already
            if re.match("![\s]*gaf.?version", assoc["line"]):
                return

            self._write(assoc["line"] + "\n")
            return

        subj = assoc['subject']

        db, db_object_id = self._split_prefix(subj)

        qualifier = "|".join(assoc["qualifiers"])
        # qualifier is | seperated string, filter on None removes empty strings in case qualifiers is empty
        if assoc['negated']:
            qualifier = "|".join(list(filter(None, ["NOT", qualifier])))

        goid = assoc['object']['id']

        ev = assoc['evidence']
        evidence = ev['type']
        withfrom = "|".join(ev['with_support_from'])
        reference = "|".join(ev['has_supporting_reference'])

        date = assoc['date']
        assigned_by = assoc['provided_by']

        annotation_properties = '' # TODO
        # if we have any subject extensions, list each one that has a "property" equal to "isoform", take the first one, and grab the "filler"
        gene_product_isoform = [e for e in assoc["subject_extensions"] if e["property"] == "isoform"][0]["filler"] if len(assoc["subject_extensions"]) > 0 else ""

        aspect = assoc['aspect']
        interacting_taxon_id = assoc["interacting_taxon"]
        taxon = self._full_taxon_field(self.normalize_taxon(subj['taxon']['id']), self.normalize_taxon(interacting_taxon_id))

        extension_expression = self._extension_expression(assoc['object_extensions'])

        vals = [db,
                db_object_id,
                subj.get('label'),
                qualifier,
                goid,
                reference,
                evidence,
                withfrom,
                aspect,
                subj["fullname"],
                "|".join(subj.get('synonyms',[])),
                subj.get('type'),
                taxon,
                date,
                assigned_by,
                extension_expression,
                gene_product_isoform]

        self._write_row(vals)
1221591
def writeline(self, fmt, *args):
        
        fmt = self.endian + fmt
        size = struct.calcsize(fmt)

        fix = struct.pack(self.endian + 'i', size)
        line = struct.pack(fmt, *args)

        self.write(fix)
        self.write(line)
        self.write(fix)
1242857
def write_file(fname, *lines):
    ''
    yield 'touch {}'.format(fname)
    for line in lines:
        yield "echo {} >> {}".format(line, fname)
146333
def write_output(self, data, args=None, filename=None, label=None):
        """"""
        if args:
            if not args.outlog:
                return 0
        if not filename: filename=args.outlog
        lastpath = ''
        with open(str(filename), 'w') as output_file:
            for entry in data['entries']:
                if args.label:
                    if entry['source_path'] == lastpath:
                        output_file.write(entry['raw_text'] + '\n')
                    elif args.label == 'fname':
                        output_file.write('======== ' + \
                                entry['source_path'].split('/')[-1] + \
                                ' >>>>\n' + entry['raw_text'] + '\n')
                    elif args.label == 'fpath':
                        output_file.write('======== ' + \
                                entry['source_path']  + \
                                ' >>>>\n' + entry['raw_text'] + '\n')
                else: output_file.write(entry['raw_text'] + '\n')
                lastpath = entry['source_path']
168569
def writelines(self, lines):
        """"""
        self.make_dir()
        with open(self.path, "w") as f:
            return f.writelines(lines)
72442
def writeDataTable(self, file, type):
        
        agents = self.experiment.agents
        numAgents = len(self.experiment.agents)

        colWidth = 8
        idxColWidth = 3

        sep = ("=" * idxColWidth) + " " + \
            ("=" * colWidth + " ") * numAgents + "\n"

        file.write(sep)

        # Table column headers.
        file.write("..".rjust(idxColWidth) + " ")
        for agent in agents:
            # The end of the name is typically the unique part.
            file.write(agent.name[-colWidth:].center(colWidth) + " ")
        file.write("\n")

        file.write(sep)

        # Table values.
        if agents:
            rows, _ = agents[0].history.getField( type ).shape
        else:
            rows, _ = (0, 0)

        for sequence in range( min(rows, 999) ):
            file.write( str(sequence + 1).rjust(idxColWidth) + " " )

            for agent in agents:
                field = agent.history.getField( type )
                # FIXME: Handle multiple state values.
                file.write("%8.3f " % field[sequence, 0])

            file.write("\n")

        file.write(sep)
229581
def cigarWrite(fileHandle, pairwiseAlignment, withProbs=True):
    
    if len(pairwiseAlignment.operationList) == 0:
        logger.info("Writing zero length pairwiseAlignment to file!")

    strand1 = "+"
    if not pairwiseAlignment.strand1:
        strand1 = "-"

    strand2 = "+"
    if not pairwiseAlignment.strand2:
        strand2 = "-"

    fileHandle.write("cigar: %s %i %i %s %s %i %i %s %f" % (pairwiseAlignment.contig2, pairwiseAlignment.start2, pairwiseAlignment.end2, strand2,\
                                                            pairwiseAlignment.contig1, pairwiseAlignment.start1, pairwiseAlignment.end1, strand1,\
                                                            pairwiseAlignment.score))
    if withProbs == True:
        hashMap = { PairwiseAlignment.PAIRWISE_INDEL_Y:'Z',PairwiseAlignment.PAIRWISE_INDEL_X:'Y', PairwiseAlignment.PAIRWISE_MATCH:'X' }
        for op in pairwiseAlignment.operationList:
            fileHandle.write(' %s %i %f' % (hashMap[op.type], op.length, op.score))
    else:
        hashMap = { PairwiseAlignment.PAIRWISE_INDEL_Y:'I',PairwiseAlignment.PAIRWISE_INDEL_X:'D', PairwiseAlignment.PAIRWISE_MATCH:'M' }
        for op in pairwiseAlignment.operationList:
            fileHandle.write(' %s %i' % (hashMap[op.type], op.length))
    fileHandle.write("\n")
321012
def write_file(data, outfilename):
    """"""
    if not data:
        return False
    try:
        with open(outfilename, 'w') as outfile:
            for line in data:
                if line:
                    outfile.write(line)
        return True
    except (OSError, IOError) as err:
        sys.stderr.write('An error occurred while writing {0}:\n{1}'
                         .format(outfilename, str(err)))
        return False
53419
def write_text_files(args, infilenames, outfilename):
    
    if not outfilename.endswith('.txt'):
        outfilename = outfilename + '.txt'
    outfilename = overwrite_file_check(args, outfilename)

    all_text = []  # Text must be aggregated if writing to a single output file
    for i, infilename in enumerate(infilenames):
        parsed_text = get_parsed_text(args, infilename)
        if parsed_text:
            if args['multiple']:
                if not args['quiet']:
                    print('Attempting to write to {0}.'.format(outfilename))
                write_file(parsed_text, outfilename)
            elif args['single']:
                all_text += parsed_text
                # Newline added between multiple files being aggregated
                if len(infilenames) > 1 and i < len(infilenames) - 1:
                    all_text.append('\n')

    # Write all text to a single output file
    if args['single'] and all_text:
        if not args['quiet']:
            print('Attempting to write {0} page(s) to {1}.'
                  .format(len(infilenames), outfilename))
        write_file(all_text, outfilename)
58612
def writeFasta(sequence, sequence_name, output_file):
    
    i=0
    f=open(output_file,'w')
    f.write(">"+str(sequence_name)+"\n")
    while i <= len(sequence):
        f.write(sequence[i:i+60]+"\n")
        i=i+60
    f.close()
986899
def write_tsv_line_from_list(linelist, outfp):
    """"""
    line = '\t'.join(linelist)
    outfp.write(line)
    outfp.write('\n')
432891
def write(self, fileobj = sys.stdout, indent = u""):
		
		fileobj.write(self.start_tag(indent))
		fileobj.write(u"\n")
1003961
def storeAssociation(self, server_url, association):
        
        association_s = association.serialize()  # NOTE: UTF-8 encoded bytes
        filename = self.getAssociationFilename(server_url, association.handle)
        tmp_file, tmp = self._mktemp()

        try:
            try:
                tmp_file.write(association_s)
                os.fsync(tmp_file.fileno())
            finally:
                tmp_file.close()

            try:
                os.rename(tmp, filename)
            except OSError as why:
                if why.errno != EEXIST:
                    raise

                # We only expect EEXIST to happen only on Windows. It's
                # possible that we will succeed in unlinking the existing
                # file, but not in putting the temporary file in place.
                try:
                    os.unlink(filename)
                except OSError as why:
                    if why.errno == ENOENT:
                        pass
                    else:
                        raise

                # Now the target should not exist. Try renaming again,
                # giving up if it fails.
                os.rename(tmp, filename)
        except:
            # If there was an error, don't leave the temporary file
            # around.
            _removeIfPresent(tmp)
            raise
1247918
def dump(output)
      output.name(self)
      output.attribute(:input, input)
      output.nest(:context, context)
    end
437298
def write_file(writer, filename):
  """"""
  for line in txt_line_iterator(filename):
    writer.write(line)
    writer.write("\n")
695925
def write_line(self, d, fmt=SPARSE):
        
        
        def smart_quote(s):
            if isinstance(s, basestring) and ' ' in s and s[0] != '"':
                s = '"%s"' % s
            return s
        
        if fmt == DENSE:
            #TODO:fix
            assert not isinstance(d, dict), NotImplemented
            line = []
            for e, a in zip(d, self.attributes):
                at = self.attribute_types[a]
                if at in NUMERIC_TYPES:
                    line.append(str(e))
                elif at == TYPE_STRING:
                    line.append(self.esc(e))
                elif at == TYPE_NOMINAL:
                    line.append(e)
                else:
                    raise Exception("Type " + at + " not supported for writing!")
            s = ','.join(map(str, line))
            return s
        elif fmt == SPARSE:
            line = []
            
            # Convert flat row into dictionary.
            if isinstance(d, (list, tuple)):
                d = dict(zip(self.attributes, d))
                for k in d:
                    at = self.attribute_types.get(k)
                    if isinstance(d[k], Value):
                        continue
                    elif d[k] == MISSING:
                        d[k] = Str(d[k])
                    elif at in (TYPE_NUMERIC, TYPE_REAL):
                        d[k] = Num(d[k])
                    elif at == TYPE_STRING:
                        d[k] = Str(d[k])
                    elif at == TYPE_INTEGER:
                        d[k] = Int(d[k])
                    elif at == TYPE_NOMINAL:
                        d[k] = Nom(d[k])
                    elif at == TYPE_DATE:
                        d[k] = Date(d[k])
                    else:
                        raise Exception('Unknown type: %s' % at)

            for i, name in enumerate(self.attributes):
                v = d.get(name)
                if v is None:
#                    print 'Skipping attribute with None value:', name
                    continue
                elif v == MISSING or (isinstance(v, Value) and v.value == MISSING):
                    v = MISSING
                elif isinstance(v, String):
                    v = '"%s"' % v.value
                elif isinstance(v, Date):
                    date_format = self.attribute_data.get(name, DEFAULT_DATE_FORMAT)
                    date_format = convert_weka_to_py_date_pattern(date_format)
                    if isinstance(v.value, basestring):
                        _value = dateutil.parser.parse(v.value)
                    else:
                        assert isinstance(v.value, (date, datetime))
                        _value = v.value
                    v.value = v = _value.strftime(date_format)
                elif isinstance(v, Value):
                    v = v.value

                if v != MISSING and self.attribute_types[name] == TYPE_NOMINAL and str(v) not in map(str, self.attribute_data[name]):
                    pass
                else:
                    line.append('%i %s' % (i, smart_quote(v)))

            if len(line) == 1 and MISSING in line[-1]:
                # Skip lines with nothing other than a missing class.
                return
            elif not line:
                # Don't write blank lines.
                return
            return '{' + (', '.join(line)) + '}'
        else:
            raise Exception('Uknown format: %s' % (fmt,))
685337
def write_output_files(self,traj):
        
        try:
            os.chdir("analysis")
        except Exception as e:
            os.mkdir("analysis")
            os.chdir("analysis")
        os.mkdir("pistacking")
        os.chdir("pistacking")
        with open('pistacking_data_total_'+str(traj)+'.csv', 'wb') as outfile:
            hwriter = csv.writer(outfile, delimiter=' ')
            for time in self.pistacking_by_time[traj]:
                hwriter.writerow([time[0],time[1]])
        for bond in self.pistacking_by_type[traj]:
            if bond in self.pi_contacts_for_drawing.keys():
                with open("pi_contact_"+str(traj)+".csv","wb") as outfile:
                    hwriter = csv.writer(outfile, delimiter=' ')
                    for time in self.timesteps:
                        result = [1 if x[0]==time and x["acceptor_idx"]==bond["acceptor_idx"] else 0 for x in self.timeseries][0]
                        hwriter.writerow([time,result])
        os.chdir("../../")