Write association table to a file.
342087
def write(self, output=None):
        
        if not output:
            outfile = self['output']+'_asn.fits'
            output = self['output']
        else:
            outfile = output

        # Delete the file if it exists.
        if os.path.exists(outfile):
            warningmsg =  "\n#########################################\n"
            warningmsg += "#                                       #\n"
            warningmsg += "# WARNING:                              #\n"
            warningmsg += "#  The existing association table,      #\n"
            warningmsg += "           " + str(outfile) + '\n'
            warningmsg += "#  is being replaced.                   #\n"
            warningmsg += "#                                       #\n"
            warningmsg += "#########################################\n\n"
        fasn = fits.HDUList()

        # Compute maximum length of MEMNAME for table column definition
        _maxlen = 0
        for _fname in self['order']:
            if len(_fname) > _maxlen: _maxlen = len(_fname)
        # Enforce a mimimum size of 24
        if _maxlen < 24: _maxlen = 24
        namelen_str = str(_maxlen+2)+'A'
        self.buildPrimary(fasn, output=output)

        mname = self['order'][:]
        mname.append(output)
        mtype = ['EXP-DTH' for l in self['order']]
        mtype.append('PROD-DTH')
        mprsn = [True for l in self['order']]
        mprsn.append(False)
        xoff = [self['members'][l]['xoff'] for l in self['order']]
        xoff.append(0.0)
        yoff = [self['members'][l]['yoff'] for l in self['order']]
        yoff.append(0.0)
        xsh = [self['members'][l]['xshift'] for l in self['order']]
        xsh.append(0.0)
        ysh = [self['members'][l]['yshift'] for l in self['order']]
        ysh.append(0.0)
        rot = [self['members'][l]['rot'] for l in self['order']]
        rot.append(0.0)
        scl = [self['members'][l]['scale'] for l in self['order']]
        scl.append(1.0)

        memname = fits.Column(name='MEMNAME',format=namelen_str,array=N.char.array(mname))
        memtype = fits.Column(name='MEMTYPE',format='14A',array=N.char.array(mtype))
        memprsn = fits.Column(name='MEMPRSNT', format='L', array=N.array(mprsn).astype(N.uint8))
        xoffset = fits.Column(name='XOFFSET', format='E', array=N.array(xoff))
        yoffset = fits.Column(name='YOFFSET', format='E', array=N.array(yoff))
        xdelta = fits.Column(name='XDELTA', format='E', array=N.array(xsh))
        ydelta = fits.Column(name='YDELTA', format='E', array=N.array(ysh))
        rotation = fits.Column(name='ROTATION', format='E', array=N.array(rot))
        scale = fits.Column(name='SCALE', format='E', array=N.array(scl))
        cols = fits.ColDefs([memname,memtype,memprsn,xoffset,yoffset,xdelta,ydelta,rotation,scale])
        hdu = fits.BinTableHDU.from_columns(cols)
        fasn.append(hdu)
        if ASTROPY_VER_GE13:
            fasn.writeto(outfile, overwrite=True)
        else:
            fasn.writeto(outfile, clobber=True)
        fasn.close()
        mem0 = self['order'][0]
        refimg = self['members'][mem0]['refimage']
        if refimg is not None:
            whdu = wcsutil.WCSObject(refimg)
            whdu.createReferenceWCS(outfile,overwrite=False)
            ftab = fits.open(outfile)
            ftab['primary'].header['refimage'] = outfile+"[wcs]"
            ftab.close()
        del whdu
588414
def write_union(fo, datum, schema):
    """"""

    if isinstance(datum, tuple):
        (name, datum) = datum
        for index, candidate in enumerate(schema):
            if extract_record_type(candidate) == 'record':
                schema_name = candidate['name']
            else:
                schema_name = candidate
            if name == schema_name:
                break
        else:
            msg = 'provided union type name %s not found in schema %s' \
              % (name, schema)
            raise ValueError(msg)
    else:
        pytype = type(datum)
        best_match_index = -1
        most_fields = -1
        for index, candidate in enumerate(schema):
            if validate(datum, candidate, raise_errors=False):
                if extract_record_type(candidate) == 'record':
                    fields = len(candidate['fields'])
                    if fields > most_fields:
                        best_match_index = index
                        most_fields = fields
                else:
                    best_match_index = index
                    break
        if best_match_index < 0:
            msg = '%r (type %s) do not match %s' % (datum, pytype, schema)
            raise ValueError(msg)
        index = best_match_index

    # write data
    write_long(fo, index)
    write_data(fo, datum, schema[index])
1098921
def write(file_name, data):
    """"""
    with open(file_name, 'w') as f:
        f.write(encode(data))
950530
function storeAssociation($server_url, $association)
    {
        if (!$this->active) {
            trigger_error("FileStore no longer active", E_USER_ERROR);
            return false;
        }

        $association_s = $association->serialize();
        $filename = $this->getAssociationFilename($server_url,
                                                  $association->handle);
        list($tmp_file, $tmp) = $this->_mktemp();

        if (!$tmp_file) {
            trigger_error("_mktemp didn't return a valid file descriptor",
                          E_USER_WARNING);
            return false;
        }

        fwrite($tmp_file, $association_s);

        fflush($tmp_file);

        fclose($tmp_file);

        if (@rename($tmp, $filename)) {
            return true;
        } else {
            // In case we are running on Windows, try unlinking the
            // file in case it exists.
            @unlink($filename);

            // Now the target should not exist. Try renaming again,
            // giving up if it fails.
            if (@rename($tmp, $filename)) {
                return true;
            }
        }

        // If there was an error, don't leave the temporary file
        // around.
        Auth_OpenID_FileStore::_removeIfPresent($tmp);
        return false;
    }
778923
def write_files(text, where='.'):
    """"""
    for filename in text:
        target = os.path.join(where, filename)
        write_file(target, text[filename])
1013501
def _write(self, session, openFile, replaceParamFile):
        
        ## TODO: Ensure Other HMET Formats are supported
        hmetRecords = self.hmetRecords

        for record in hmetRecords:
            openFile.write('%s\t%s\t%s\t%s\t%.3f\t%s\t%s\t%s\t%s\t%.2f\t%.2f\n' % (
                record.hmetDateTime.year,
                record.hmetDateTime.month,
                record.hmetDateTime.day,
                record.hmetDateTime.hour,
                record.barometricPress,
                record.relHumidity,
                record.totalSkyCover,
                record.windSpeed,
                record.dryBulbTemp,
                record.directRad,
                record.globalRad))
698906
def dump_database(self, file_path, database=None, tables=None):
        
        # Change database if needed
        if database:
            self.change_db(database)

        # Set table
        if not tables:
            tables = self.tables

        # Retrieve and join dump statements
        statements = [self.dump_table(table) for table in tqdm(tables, total=len(tables), desc='Generating dump files')]
        dump = 'SET FOREIGN_KEY_CHECKS=0;' + '\n'.join(statements) + '\nSET FOREIGN_KEY_CHECKS=1;'

        # Write dump statements to sql file
        file_path = file_path if file_path.endswith('.sql') else file_path + '.sql'
        write_text(dump, file_path)
        return file_path
419257
def _write_to_file(self, filename, bytesvalue):
        """"""
        fh, tmp = tempfile.mkstemp()
        with os.fdopen(fh, self._flag) as f:
            f.write(self._dumps(bytesvalue))
        rename(tmp, filename)
        os.chmod(filename, self._mode)
1350396
def _assemble_association(stmt):
    """"""
    member_strs = [_assemble_agent_str(m.concept) for m in stmt.members]
    stmt_str = member_strs[0] + ' is associated with ' + \
        _join_list(member_strs[1:])
    return _make_sentence(stmt_str)
76699
def _write_header(data, fp, relation_name, index):
    """"""
    fp.write("@relation {0}\n\n".format(relation_name))

    if index:
        data = data.reset_index()

    attribute_names = _sanitize_column_names(data)

    for column, series in data.iteritems():
        name = attribute_names[column]
        fp.write("@attribute {0}\t".format(name))

        if is_categorical_dtype(series) or is_object_dtype(series):
            _write_attribute_categorical(series, fp)
        elif numpy.issubdtype(series.dtype, numpy.floating):
            fp.write("real")
        elif numpy.issubdtype(series.dtype, numpy.integer):
            fp.write("integer")
        elif numpy.issubdtype(series.dtype, numpy.datetime64):
            fp.write("date 'yyyy-MM-dd HH:mm:ss'")
        else:
            raise TypeError('unsupported type %s' % series.dtype)

        fp.write("\n")
    return data
587463
def write_data_set(file_path, dataset, output_dir, color_array_info, new_name=None, compress=True):
    """"""
    fileName = new_name if new_name else os.path.basename(file_path)
    dataset_dir = os.path.join(output_dir, fileName)
    data_dir = os.path.join(dataset_dir, 'data')

    if not os.path.exists(data_dir):
        os.makedirs(data_dir)

    root = {}
    root['metadata'] = {}
    root['metadata']['name'] = fileName

    writer = writer_mapping[dataset.GetClassName()]
    if writer:
        writer(dataset_dir, data_dir, dataset, color_array_info, root, compress)
    else:
        print(dataObject.GetClassName(), 'is not supported')

    with open(os.path.join(dataset_dir, "index.json"), 'w') as f:
        f.write(json.dumps(root, indent=2))

    return dataset_dir
407365
def _create(self, cache_file):
        """"""
        conn = sqlite3.connect(cache_file)
        cur = conn.cursor()
        cur.execute("PRAGMA foreign_keys = ON")
        cur.execute('''
            CREATE TABLE jobs(
                hash TEXT NOT NULL UNIQUE PRIMARY KEY, description TEXT NOT NULL,
                last_run REAL, next_run REAL, last_run_result INTEGER)''')

        cur.execute('''
            CREATE TABLE history(
                hash TEXT, description TEXT, time REAL, result INTEGER,
                FOREIGN KEY(hash) REFERENCES jobs(hash))''')

        conn.commit()
        conn.close()
905035
def write_file(self, fp, data):
        """"""
        with open(fp, 'w') as f:
            f.write(data)
665781
def write_array(self, data):
        """"""
        try:
            data.tofile(self._fh)
        except Exception:
            # BytesIO
            self._fh.write(data.tostring())
1208448
private function writeColumns(): void
  {
    $content = '';
    foreach ($this->columns as $table)
    {
      $width1 = 0;
      $width2 = 0;
      foreach ($table as $column)
      {
        $width1 = max(mb_strlen($column['column_name']), $width1);
        $width2 = max(mb_strlen((string)$column['length']), $width2);
      }

      foreach ($table as $column)
      {
        if (isset($column['length']))
        {
          if (isset($column['constant_name']))
          {
            $line_format = sprintf("%%s.%%-%ds %%%dd %%s\n", $width1, $width2);
            $content     .= sprintf($line_format,
                                    $column['table_name'],
                                    $column['column_name'],
                                    $column['length'],
                                    $column['constant_name']);
          }
          else
          {
            $line_format = sprintf("%%s.%%-%ds %%%dd\n", $width1, $width2);
            $content     .= sprintf($line_format,
                                    $column['table_name'],
                                    $column['column_name'],
                                    $column['length']);
          }
        }
      }

      $content .= "\n";
    }

    // Save the columns, width and constants to the filesystem.
    $this->writeTwoPhases($this->constantsFilename, $content);
  }
882737
def writeTable(self, tableName):
        
        lock_and_call(
            lambda: self._impl.writeTable(tableName),
            self._lock
        )
456969
void writeAssocBean() throws IOException {

    writingAssocBean = true;
    origDestPackage = destPackage;
    destPackage = destPackage + ".assoc";
    origShortName = shortName;
    shortName = "Assoc" + shortName;

    prepareAssocBeanImports();

    writer = new Append(createFileWriter());

    writePackage();
    writeImports();
    writeClass();
    writeFields();
    writeConstructors();
    writeClassEnd();

    writer.close();
  }