Write this workflow to DAX file
512079
def save(self, filename=None, tc=None):
        
        if filename is None:
            filename = self.filename

        for sub in self.sub_workflows:
            sub.save()

        # FIXME this is ugly as pegasus 4.9.0 does not support the full
        # transformation catalog in the DAX. I have asked Karan to fix this so
        # that executables and containers can be specified in the DAX itself.
        # Karan says that XML is going away in Pegasus 5.x and so this code
        # will need to be re-written anyway.
        #
        # the transformation catalog is written in the same directory as the
        # DAX.  pycbc_submit_dax needs to know this so that the right
        # transformation catalog is used when the DAX is planned.
        if tc is None:
            tc = '{}.tc.txt'.format(filename)
        p = os.path.dirname(tc)
        f = os.path.basename(tc)
        if not p:
            p = '.'

        tc = TransformationCatalog(p, f)

        for e in self._adag.executables.copy():
            tc.add(e)
            try:
                tc.add_container(e.container)
            except:
                pass
            self._adag.removeExecutable(e)

        f = open(filename, "w")
        self._adag.writeXML(f)
        tc.write()
156936
def write_main_jobwrappers(self):
        '''
        
        '''
        main_section = ''

        # toil cannot technically start with multiple jobs, so an empty
        # 'initialize_jobs' function is always called first to get around this
        main_section = main_section + '\n        job0 = Job.wrapJobFn(initialize_jobs)\n'

        # declare each job in main as a wrapped toil function in order of priority
        for wf in self.workflows_dictionary:
            for assignment in self.workflows_dictionary[wf]:
                if assignment.startswith('call'):
                    main_section += '        job0 = job0.encapsulate()\n'
                    main_section += self.write_main_jobwrappers_call(self.workflows_dictionary[wf][assignment])
                if assignment.startswith('scatter'):
                    main_section += '        job0 = job0.encapsulate()\n'
                    main_section += self.write_main_jobwrappers_scatter(self.workflows_dictionary[wf][assignment],
                                                                        assignment)
                if assignment.startswith('if'):
                    main_section += '        if {}:\n'.format(self.workflows_dictionary[wf][assignment]['expression'])
                    main_section += self.write_main_jobwrappers_if(self.workflows_dictionary[wf][assignment]['body'])

        main_section += '\n        fileStore.start(job0)\n'

        return main_section
1213565
function WorkflowProcessBeginController($state, workorderService, wfmService, $stateParams) {
  var self = this;

  var workorderId = $stateParams.workorderId;
  workorderService.read(workorderId).then(function(workorder) {
    self.workorder = workorder;
    self.workflow = workorder.workflow;
    self.results = workorder.results;
    self.started = !wfmService.isNew(self.workorder);
    self.completed = wfmService.isCompleted(self.workorder);
  });

  self.getStepForResult = function(result) {
    return wfmService.getStepForResult(result, self.workorder);
  };

  self.begin = function() {
    wfmService.begin(self.workorder)
      .then(function() {
        $state.go('app.workflowProcess.steps', {
          workorderId: workorderId
        });
      })
      .catch(console.error.bind(console));
  };
}
731410
def write(self, outfile, encoding):
        
        """
        cal = Calendar()
        cal.add('version', '2.0')
        cal.add('calscale', 'GREGORIAN')

        for ifield, efield in FEED_FIELD_MAP:
            val = self.feed.get(ifield)
            if val is not None:
                cal.add(efield, val)

        self.write_items(cal)

        to_ical = getattr(cal, 'as_string', None)
        if not to_ical:
            to_ical = cal.to_ical
        outfile.write(to_ical())
519332
private void writeWBS(Task mpxj)
   {
      if (mpxj.getUniqueID().intValue() != 0)
      {
         WBSType xml = m_factory.createWBSType();
         m_project.getWBS().add(xml);
         String code = mpxj.getWBS();
         code = code == null || code.length() == 0 ? DEFAULT_WBS_CODE : code;

         Task parentTask = mpxj.getParentTask();
         Integer parentObjectID = parentTask == null ? null : parentTask.getUniqueID();

         xml.setCode(code);
         xml.setGUID(DatatypeConverter.printUUID(mpxj.getGUID()));
         xml.setName(mpxj.getName());

         xml.setObjectId(mpxj.getUniqueID());
         xml.setParentObjectId(parentObjectID);
         xml.setProjectObjectId(PROJECT_OBJECT_ID);
         xml.setSequenceNumber(Integer.valueOf(m_wbsSequence++));

         xml.setStatus("Active");
      }

      writeChildTasks(mpxj);
   }
346456
def to_s
      string =  "Workflow:    #{@name}\n"
      string << "ID:          #{@id}\n"
      string << "Description: #{@description}\n"
      string << "Version:     #{@version}\n"

      string << "\nInput Parameters:\n"
      if @input_parameters.size > 0
        @input_parameters.each_value { |wf_param| string << " #{wf_param}" }
      end

      string << "\nOutput Parameters:" << "\n"
      if @output_parameters.size > 0
        @output_parameters.each_value { |wf_param| string << " #{wf_param}" }
      end

      # Assert
      string
    end
233487
private void writeCostRateTables(Project.Resources.Resource xml, Resource mpx)
   {
      //Rates rates = m_factory.createProjectResourcesResourceRates();
      //xml.setRates(rates);
      //List<Project.Resources.Resource.Rates.Rate> ratesList = rates.getRate();

      List<Project.Resources.Resource.Rates.Rate> ratesList = null;

      for (int tableIndex = 0; tableIndex < 5; tableIndex++)
      {
         CostRateTable table = mpx.getCostRateTable(tableIndex);
         if (table != null)
         {
            Date from = DateHelper.FIRST_DATE;
            for (CostRateTableEntry entry : table)
            {
               if (costRateTableWriteRequired(entry, from))
               {
                  if (ratesList == null)
                  {
                     Rates rates = m_factory.createProjectResourcesResourceRates();
                     xml.setRates(rates);
                     ratesList = rates.getRate();
                  }

                  Project.Resources.Resource.Rates.Rate rate = m_factory.createProjectResourcesResourceRatesRate();
                  ratesList.add(rate);

                  rate.setCostPerUse(DatatypeConverter.printCurrency(entry.getCostPerUse()));
                  rate.setOvertimeRate(DatatypeConverter.printRate(entry.getOvertimeRate()));
                  rate.setOvertimeRateFormat(DatatypeConverter.printTimeUnit(entry.getOvertimeRateFormat()));
                  rate.setRatesFrom(from);
                  from = entry.getEndDate();
                  rate.setRatesTo(from);
                  rate.setRateTable(BigInteger.valueOf(tableIndex));
                  rate.setStandardRate(DatatypeConverter.printRate(entry.getStandardRate()));
                  rate.setStandardRateFormat(DatatypeConverter.printTimeUnit(entry.getStandardRateFormat()));
               }
            }
         }
      }
   }
880349
def write_branch_data(self, file):
        
        # I,J,CKT,R,X,B,RATEA,RATEB,RATEC,GI,BI,GJ,BJ,ST,LEN,O1,F1,...,O4,F4
        branch_attr = ["r", "x", "b", "rate_a", "rate_b", "rate_c"]

        for branch in self.case.branches:
            if feq(branch.ratio, 0.0):
                vals = [getattr(branch, a) for a in branch_attr]
                if float(vals[1])<0.001:
                    vals[1] = 0.001  # small reactance, todo: increase decimal
                vals.insert(0, "1 ")
                vals.insert(0, branch.to_bus._i)
                vals.insert(0, branch.from_bus._i)
                vals.extend([0., 0., 0., 0.])
                vals.append(branch.online)
                vals.extend([0.0, 1, 1.0,])

                file.write("%6d,%6d,'%s',%10.3f,%10.3f,%10.3f,%10.3f,%10.3f,"
                    "%10.3f,%10.3f,%10.3f,%10.3f,%10.3f,%d,%10.3f,%4d,%6.4f\n" %
                    tuple(vals))
        file.write(" 0 / END OF NON-TRANSFORMER BRANCH DATA, BEGIN TRANSFORMER DATA\n")

        # I,J,K,CKT,CW,CZ,CM,MAG1,MAG2,NMETR,'NAME',STAT,O1,F1,...,O4,F4
        # R1-2,X1-2,SBASE1-2
        # WINDV1,NOMV1,ANG1,RATA1,RATB1,RATC1,COD1,CONT1,RMA1,RMI1,VMA1,VMI1,NTP1,TAB1,CR1,CX1
        # WINDV2,NOMV2
        for branch in self.case.branches:
            if not feq(branch.ratio, 0.0):
                vals = []
                vals.append(branch.from_bus._i)
                vals.append(branch.to_bus._i)
                # K,CKT,CW,CZ,CM,MAG1,MAG2,NMETR
                vals.extend([0, "1 ", 1, 1, 1, 0.0, 0.0, 2])
                vals.append(branch.name)
                vals.append(branch.online)
                vals.extend([1, 1.0]) # O1,F1

                file.write("%6d,%6d,%6d,'%2s',%d,%d,%d,%10.3f,%10.3f,%d,"
                           "'%-12s',%d,%4d,%6.4f\n" % tuple(vals))
                file.write("%8.3f,%8.3f,%10.2f\n" % (branch.r, branch.x,
                                                   self.case.base_mva))

                line3 = []
                line3.append(branch.ratio) # Winding-1 RATIO
                line3.append(0.0)
                line3.append(branch.phase_shift)
                line3.append(branch.rate_a)
                line3.append(branch.rate_b)
                line3.append(branch.rate_c)
                # COD1,CONT1,RMA1,RMI1,VMA1,VMI1,NTP1,TAB1,CR1,CX1
                line3.extend([0, 0, 1.1, 0.9, 1.1, 0.9, 33, 0, 0.0, 0.0])

                file.write("%7.5f,%8.3f,%8.3f,%8.2f,%8.2f,%8.2f,%d,%7d,%8.5f,"
                    "%8.5f,%8.5f,%8.5f,%4d,%2d,%8.5f,%8.5f\n" % tuple(line3))

                file.write("%7.5f,%8.3f\n" % (1.0, 0.0))  # Winding-2 RATIO: 1

        file.write(""" 0 / END OF TRANSFORMER DATA, BEGIN AREA INTERCHANGE DATA
 0 / END OF AREA INTERCHANGE DATA, BEGIN TWO-TERMINAL DC DATA
 0 / END OF TWO-TERMINAL DC DATA, BEGIN VSC DC LINE DATA
 0 / END OF VSC DC LINE DATA, BEGIN SWITCHED SHUNT DATA
 0 / END OF SWITCHED SHUNT DATA, BEGIN TRANS. IMP. CORR. TABLE DATA
 0 / END OF TRANS. IMP. CORR. TABLE DATA, BEGIN MULTI-TERMINAL DC LINE DATA
 0 / END OF MULTI-TERMINAL DC LINE DATA, BEGIN MULTI-SECTION LINE DATA
 0 / END OF MULTI-SECTION LINE DATA, BEGIN ZONE DATA
 0 / END OF ZONE DATA, BEGIN INTERAREA TRANSFER DATA
 0 / END OF INTERAREA TRANSFER DATA, BEGIN OWNER DATA
 0 / END OF OWNER DATA, BEGIN FACTS DEVICE DATA
 0 / END OF FACTS DEVICE DATA, END OF CASE DATA
""")
367992
def workflow_script_import(self):
        
        bsc = getToolByName(self, 'bika_setup_catalog')
        client = self.aq_parent

        title = _('Submitting Sample Import')
        description = _('Creating and initialising objects')
        bar = ProgressBar(self, self.REQUEST, title, description)
        notify(InitialiseProgressBar(bar))

        profiles = [x.getObject() for x in bsc(portal_type='AnalysisProfile')]

        gridrows = self.schema['SampleData'].get(self)
        row_cnt = 0
        for therow in gridrows:
            row = deepcopy(therow)
            row_cnt += 1

            # Profiles are titles, profile keys, or UIDS: convert them to UIDs.
            newprofiles = []
            for title in row['Profiles']:
                objects = [x for x in profiles
                           if title in (x.getProfileKey(), x.UID(), x.Title())]
                for obj in objects:
                    newprofiles.append(obj.UID())
            row['Profiles'] = newprofiles

            # Same for analyses
            newanalyses = set(self.get_row_services(row) +
                              self.get_row_profile_services(row))
            # get batch
            batch = self.schema['Batch'].get(self)
            if batch:
                row['Batch'] = batch.UID()
            # Add AR fields from schema into this row's data
            row['ClientReference'] = self.getClientReference()
            row['ClientOrderNumber'] = self.getClientOrderNumber()
            contact_uid =\
                self.getContact().UID() if self.getContact() else None
            row['Contact'] = contact_uid
            # Creating analysis request from gathered data
            ar = create_analysisrequest(
                client,
                self.REQUEST,
                row,
                analyses=list(newanalyses),)

            # progress marker update
            progress_index = float(row_cnt) / len(gridrows) * 100
            progress = ProgressState(self.REQUEST, progress_index)
            notify(UpdateProgressEvent(progress))

        # document has been written to, and redirect() fails here
        self.REQUEST.response.write(
            '<script>document.location.href="%s"</script>' % (
                self.absolute_url()))
688581
def write_transforms_to_file(self, fname='ace_transforms.txt'):
        """"""
        self._write_columns(fname, self.x_transforms, self.y_transform)
854307
def write(self, content=None):
        
        if self.system.files.no_output is True:
            return

        t, _ = elapsed()

        if not content:
            logger.warning('report content not specified.')
            return

        self.update(content)

        system = self.system
        file = system.files.output
        export = all_formats.get(system.config.export, 'txt')
        module = importlib.import_module('andes.formats.' + export)
        dump_data = getattr(module, 'dump_data')

        text = list()
        header = list()
        rowname = list()
        data = list()

        text.append(self.info)
        header.append(None)
        rowname.append(None)
        data.append(None)

        if content == 'summary' or 'extended' or 'powerflow':
            text.append(['SUMMARY:\n'])
            header.append(None)
            rowname.append(self._basic_name)
            data.append([self.basic[item] for item in self._basic])

        if content == 'extended' or 'powerflow':
            text.append(['EXTENDED SUMMARY:\n'])
            header.append(['P (pu)', 'Q (pu)'])
            rowname.append(
                ['Generation', 'Load', 'Shunt Inj', 'Losses', 'Line Charging'])
            Pcol = [
                self.extended['Pg'],
                self.extended['Pl'],
                self.extended['Psh'],
                self.extended['Ploss'],
                self.extended['Pch'],
            ]

            Qcol = [
                self.extended['Qg'],
                self.extended['Ql'],
                self.extended['Qsh'],
                self.extended['Qloss'],
                self.extended['Qch'],
            ]

            data.append([Pcol, Qcol])

        if content == 'powerflow' and system.pflow.solved:
            idx, name, Vm, Va, Pg, Qg, Pl, Ql = system.get_busdata()
            Va_unit = 'deg' if system.pflow.config.usedegree else 'rad'
            text.append(['BUS DATA:\n'])
            # todo: consider system.pflow.config.units
            header.append([
                'Vm(pu)', 'Va({:s})'.format(Va_unit), 'Pg (pu)', 'Qg (pu)',
                'Pl (pu)', 'Ql (pu)'
            ])
            name = [str(i) + '-' + j[:8] for i, j in zip(idx, name)]
            rowname.append(name)
            data.append([Vm, Va, Pg, Qg, Pl, Ql])

            # Node data
            if hasattr(system, 'Node') and system.Node.n:
                idx, name, V = system.get_nodedata()
                text.append(['NODE DATA:\n'])
                header.append(['V(pu)'])
                rowname.append(name)
                data.append([V])

            # Line data
            name, fr, to, Pfr, Qfr, Pto, Qto, Ploss, Qloss = \
                system.get_linedata()
            text.append(['LINE DATA:\n'])
            header.append([
                'From Bus', 'To Bus', 'P From (pu)', 'Q From (pu)',
                'P To (pu)', 'Q To(pu)', 'P Loss(pu)', 'Q Loss(pu)'
            ])
            rowname.append(name)
            data.append([fr, to, Pfr, Qfr, Pto, Qto, Ploss, Qloss])

            # Additional Algebraic data
            text.append(['OTHER ALGEBRAIC VARIABLES:\n'])
            header.append([''])
            rowname.append(
                system.varname.unamey[2 * system.Bus.n:system.dae.m])
            data.append([round(i, 5) for i in system.dae.y[2 * system.Bus.n:]])

            # Additional State variable data
            if system.dae.n:
                text.append(['OTHER STATE VARIABLES:\n'])
                header.append([''])
                rowname.append(system.varname.unamex[:])
                data.append([round(i, 5) for i in system.dae.x[:]])

        dump_data(text, header, rowname, data, file)

        _, s = elapsed(t)
        logger.info('report written to <{:s}> in {:s}.'.format(system.files.output, s))
322281
def write_unitth(suites, out_dir):
        
        if not os.path.isdir(out_dir):
            os.mkdir(out_dir)

        for classname, cases in suites.items():
            doc_xml = minidom.Document()

            suite_xml = doc_xml.createElement('testsuite')
            suite_xml.setAttribute('name', classname)
            suite_xml.setAttribute('tests', str(len(cases)))
            suite_xml.setAttribute('errors', str(sum('error' in case for case in cases)))
            suite_xml.setAttribute('failures', str(sum('failure' in case for case in cases)))
            suite_xml.setAttribute('skipped', str(sum('skipped' in case for case in cases)))
            suite_xml.setAttribute('time', '{:.3f}'.format(sum(case['time'] for case in cases)))
            doc_xml.appendChild(suite_xml)

            for case in cases:
                case_xml = doc_xml.createElement('testcase')
                case_xml.setAttribute('classname', classname)
                case_xml.setAttribute('name', case['name'])
                case_xml.setAttribute('time', '{:.3f}'.format(case['time']))
                suite_xml.appendChild(case_xml)

                if 'skipped' in case:
                    skipped_xml = doc_xml.createElement('skipped')
                    skipped_xml.setAttribute('type', case['skipped']['type'])
                    skipped_xml.setAttribute('message', case['skipped']['message'])
                    case_xml.appendChild(skipped_xml)

                    skipped_text_xml = doc_xml.createCDATASection(case['skipped']['text'])
                    skipped_xml.appendChild(skipped_text_xml)

                if 'failure' in case:
                    failure_xml = doc_xml.createElement('failure')
                    failure_xml.setAttribute('type', case['failure']['type'])
                    failure_xml.setAttribute('message', case['failure']['message'])
                    case_xml.appendChild(failure_xml)

                    failure_text_xml = doc_xml.createCDATASection(case['failure']['text'])
                    failure_xml.appendChild(failure_text_xml)

                if 'error' in case:
                    error_xml = doc_xml.createElement('error')
                    error_xml.setAttribute('type', case['error']['type'])
                    error_xml.setAttribute('message', case['error']['message'])
                    case_xml.appendChild(error_xml)

                    error_text_xml = doc_xml.createCDATASection(case['error']['text'])
                    error_xml.appendChild(error_text_xml)

            with open(os.path.join(out_dir, '{}.xml'.format(classname)), 'w') as output:
                doc_xml.writexml(output, encoding='utf-8', addindent='', newl="")
            doc_xml.unlink()
163405
protected void writeSceneData (SparseMisoSceneModel model,
                                   DataWriter writer)
        throws SAXException
    {
        writer.dataElement("swidth", Integer.toString(model.swidth));
        writer.dataElement("sheight", Integer.toString(model.sheight));
        writer.dataElement("defTileSet", Integer.toString(model.defTileSet));

        writer.startElement("sections");
        for (Iterator<Section> iter = model.getSections(); iter.hasNext(); ) {
            Section sect = iter.next();
            if (sect.isBlank()) {
                continue;
            }
            AttributesImpl attrs = new AttributesImpl();
            attrs.addAttribute("", "x", "", "", String.valueOf(sect.x));
            attrs.addAttribute("", "y", "", "", String.valueOf(sect.y));
            attrs.addAttribute("", "width", "", "", String.valueOf(sect.width));
            writer.startElement("", "section", "", attrs);

            writer.dataElement(
                "base", StringUtil.toString(sect.baseTileIds, "", ""));

            // write our uninteresting object tile information
            writer.startElement("objects");
            for (int ii = 0; ii < sect.objectTileIds.length; ii++) {
                attrs = new AttributesImpl();
                attrs.addAttribute("", "tileId", "", "",
                                   String.valueOf(sect.objectTileIds[ii]));
                attrs.addAttribute("", "x", "", "",
                                   String.valueOf(sect.objectXs[ii]));
                attrs.addAttribute("", "y", "", "",
                                   String.valueOf(sect.objectYs[ii]));
                writer.emptyElement("", "object", "", attrs);
            }

            // write our interesting object tile information
            for (ObjectInfo element : sect.objectInfo) {
                writeInterestingObject(element, writer);
            }
            writer.endElement("objects");
            writer.endElement("section");
        }
        writer.endElement("sections");
    }
1364958
def write_workflow(self, request, opts, cwd, wftype='cwl'):
        """"""

        workflow_url = request.get("workflow_url")

        # link the cwl and json into the cwd
        if workflow_url.startswith('file://'):
            os.link(workflow_url[7:], os.path.join(cwd, "wes_workflow." + wftype))
            workflow_url = os.path.join(cwd, "wes_workflow." + wftype)
        os.link(self.input_json, os.path.join(cwd, "wes_input.json"))
        self.input_json = os.path.join(cwd, "wes_input.json")

        extra_options = self.sort_toil_options(opts.getoptlist("extra"))
        if wftype == 'cwl':
            command_args = ['toil-cwl-runner'] + extra_options + [workflow_url, self.input_json]
        elif wftype == 'wdl':
            command_args = ['toil-wdl-runner'] + extra_options + [workflow_url, self.input_json]
        elif wftype == 'py':
            command_args = ['python'] + extra_options + [workflow_url]
        else:
            raise RuntimeError('workflow_type is not "cwl", "wdl", or "py": ' + str(wftype))

        return command_args
856253
def write_krona_plot(self, sample_names, read_taxonomies, output_krona_filename):
        ''''''
        tempfiles = []
        for n in sample_names:
            tempfiles.append(tempfile.NamedTemporaryFile(prefix='GraftMkronaInput', suffix=n))
        
        delim=u'\t'
        for _, tax, counts in self._iterate_otu_table_rows(read_taxonomies):
            for i, c in enumerate(counts):
                if c != 0:
                    tempfiles[i].write(delim.join((str(c),
                                                  delim.join(tax)
                                                  ))+"\n")
                    
        for t in tempfiles:
            t.flush()
        
        cmd = ["ktImportText",'-o',output_krona_filename]
        for i, tmp in enumerate(tempfiles):
            cmd.append(','.join([tmp.name,sample_names[i]]))

        # run the actual krona
        cmd = ' '.join(cmd)
        extern.run(cmd)

        # close tempfiles
        for t in tempfiles:
            t.close()
856628
def write(self, outfile):
        """"""

        hdu_pri = fits.PrimaryHDU()

        hdu_exp = self._create_exp_hdu(self.data)
        hdu_exp.name = 'EXPOSURE'
        hdu_exp_wt = self._create_exp_hdu(self._data_wt)
        hdu_exp_wt.name = 'WEIGHTED_EXPOSURE'

        cols = [Column(name='CTHETA_MIN', dtype='f4',
                       data=self.costh_edges[:-1][::-1]),
                Column(name='CTHETA_MAX',  dtype='f4',
                       data=self.costh_edges[1:][::-1]), ]
        hdu_bnds = fits.table_to_hdu(Table(cols))
        hdu_bnds.name = 'CTHETABOUNDS'

        hdu_gti = fits.table_to_hdu(self._tab_gti)
        hdu_gti.name = 'GTI'

        hdus = [hdu_pri, hdu_exp, hdu_exp_wt,
                hdu_bnds, hdu_gti]

        for hdu in hdus:
            hdu.header['TSTART'] = self.tstart
            hdu.header['TSTOP'] = self.tstop

        with fits.HDUList(hdus) as hdulist:
            hdulist.writeto(outfile, clobber=True)
572968
def write_bus_data(self, file):
        
        report = CaseReport(self.case)
        buses = self.case.buses

        col_width = 8
        col_width_2 = col_width * 2 + 1
        col1_width = 6

        sep = "=" * 6 + " " + ("=" * col_width + " ") * 6 + "\n"

        file.write(sep)
        # Line one of column headers
        file.write("Name".center(col1_width) + " ")
        file.write("Voltage (pu)".center(col_width_2) + " ")
        file.write("Generation".center(col_width_2) + " ")
        file.write("Load".center(col_width_2) + " ")
        file.write("\n")

        file.write("-" * col1_width +" "+ ("-" * col_width_2 + " ") * 3 + "\n")

        # Line two of column header
        file.write("..".ljust(col1_width) + " ")
        file.write("Amp".center(col_width) + " ")
        file.write("Phase".center(col_width) + " ")
        file.write("P (MW)".center(col_width) + " ")
        file.write("Q (MVAr)".center(col_width) + " ")
        file.write("P (MW)".center(col_width) + " ")
        file.write("Q (MVAr)".center(col_width) + " ")
        file.write("\n")

        file.write(sep)

        # Bus rows
        for bus in buses:
            file.write(bus.name[:col1_width].ljust(col1_width))
            file.write(" %8.3f" % bus.v_magnitude)
            file.write(" %8.3f" % bus.v_angle)
            file.write(" %8.2f" % self.case.s_supply(bus).real)
            file.write(" %8.2f" % self.case.s_supply(bus).imag)
            file.write(" %8.2f" % self.case.s_demand(bus).real)
            file.write(" %8.2f" % self.case.s_demand(bus).imag)
            file.write("\n")

        # Totals
#        file.write("..".ljust(col1_width) + " ")
#        file.write(("..".ljust(col_width) + " ")*2)
#        file.write(("_"*col_width + " ")*4 + "\n")
        file.write("..".ljust(col1_width) + " " + "..".ljust(col_width) + " ")
        file.write("*Total:*".rjust(col_width) + " ")
        ptot = report.actual_pgen
        qtot = report.actual_qgen
        file.write("%8.2f " % ptot)
        file.write("%8.2f " % qtot)
        file.write("%8.2f " % report.p_demand)
        file.write("%8.2f " % report.q_demand)
        file.write("\n")
        file.write(sep)
        del report