Save ID3v2 data to the DSF file
354432
def save(self, filething=None, v2_version=4, v23_sep='/', padding=None):
        """"""

        fileobj = filething.fileobj
        fileobj.seek(0)

        dsd_header = DSDChunk(fileobj)
        if dsd_header.offset_metdata_chunk == 0:
            # create a new ID3 chunk at the end of the file
            fileobj.seek(0, 2)

            # store reference to ID3 location
            dsd_header.offset_metdata_chunk = fileobj.tell()
            dsd_header.write()

        try:
            data = self._prepare_data(
                fileobj, dsd_header.offset_metdata_chunk, self.size,
                v2_version, v23_sep, padding)
        except ID3Error as e:
            reraise(error, e, sys.exc_info()[2])

        fileobj.seek(dsd_header.offset_metdata_chunk)
        fileobj.write(data)
        fileobj.truncate()

        # Update total file size
        dsd_header.total_size = fileobj.tell()
        dsd_header.write()
197505
def SaveName_Conv(Mod=None, Cls=None, Type=None, Name=None, Deg=None,
                      Exp=None, Diag=None, shot=None, version=None, usr=None,
                      include=None):
        
        Modstr = ID._dModes[Mod] if Mod is not None else None
        include = ID._defInclude if include is None else include
        if Cls is not None and Type is not None and 'Type' in include:
            Clsstr = Cls+Type
        else:
            Clsstr = Cls
        Dict = {'Mod':Modstr, 'Cls':Clsstr, 'Name':Name}
        for ii in include:
            if not ii in ['Mod','Cls','Type','Name']:
                Dict[ii] = None
            if ii=='Deg' and Deg is not None:
                Dict[ii] = ID._dPref[ii]+'{0:02.0f}'.format(Deg)
            elif ii=='shot' and shot is not None:
                Dict[ii] = ID._dPref[ii]+'{0:05.0f}'.format(shot)
            elif not (ii in ['Mod','Cls','Type','Name'] or eval(ii+' is None')):
                Dict[ii] = ID._dPref[ii]+eval(ii)
        if 'Data' in Cls:
            Order = ['Mod','Cls','Exp','Deg','Diag','shot',
                     'Name','version','usr']
        else:
            Order = ['Mod','Cls','Exp','Deg','Diag','Name',
                     'shot','version','usr']

        SVN = ""
        for ii in range(0,len(Order)):
            if Order[ii] in include and Dict[Order[ii]] is not None:
                SVN += '_' + Dict[Order[ii]]
        SVN = SVN.replace('__','_')
        if SVN[0]=='_':
            SVN = SVN[1:]
        return SVN
499703
function (sLayer, sNameSpace, sFileName, sFileType, sData, sTransportId, sPackageName) {
			return LRepConnector.saveFile(sLayer, sNameSpace, sFileName, sFileType, sData, sTransportId, sPackageName).then(this._navToDisplayMode.bind(this));
		}
68516
private void save(OutputStream os, String id, SessionData data) throws IOException {
        DataOutputStream out = new DataOutputStream(os);
        out.writeUTF(id);
        out.writeLong(data.getCreationTime());
        out.writeLong(data.getAccessedTime());
        out.writeLong(data.getLastAccessedTime());
        out.writeLong(data.getExpiryTime());
        out.writeLong(data.getMaxInactiveInterval());

        List<String> keys = new ArrayList<>(data.getKeys());
        out.writeInt(keys.size());
        ObjectOutputStream oos = new ObjectOutputStream(out);
        for (String name : keys) {
            oos.writeUTF(name);
            oos.writeObject(data.getAttribute(name));
        }
    }
1022036
private File getFile(String pid, String dsId, String dsVersionId) {
        File dir = new File(baseDir, getPath(pid));
        String filename = encode(pid, dsId, dsVersionId);
        return new File(dir, filename);
    }
1078288
def save(df, path, write_frequency=5000):
        
        assert isinstance(df, DataFlow), type(df)
        isdir = os.path.isdir(path)
        if isdir:
            assert not os.path.isfile(os.path.join(path, 'data.mdb')), "LMDB file exists!"
        else:
            assert not os.path.isfile(path), "LMDB file {} exists!".format(path)
        db = lmdb.open(path, subdir=isdir,
                       map_size=1099511627776 * 2, readonly=False,
                       meminit=False, map_async=True)    # need sync() at the end
        size = _reset_df_and_get_size(df)
        with get_tqdm(total=size) as pbar:
            idx = -1

            # LMDB transaction is not exception-safe!
            # although it has a context manager interface
            txn = db.begin(write=True)
            for idx, dp in enumerate(df):
                txn.put(u'{:08}'.format(idx).encode('ascii'), dumps(dp))
                pbar.update()
                if (idx + 1) % write_frequency == 0:
                    txn.commit()
                    txn = db.begin(write=True)
            txn.commit()

            keys = [u'{:08}'.format(k).encode('ascii') for k in range(idx + 1)]
            with db.begin(write=True) as txn:
                txn.put(b'__keys__', dumps(keys))

            logger.info("Flushing database ...")
            db.sync()
        db.close()
321655
def save(filename=None, family='ipv4'):
    '''
    
    '''
    if _conf() and not filename:
        filename = _conf(family)

    log.debug('Saving rules to %s', filename)

    parent_dir = os.path.dirname(filename)
    if not os.path.isdir(parent_dir):
        os.makedirs(parent_dir)
    cmd = '{0}-save'.format(_iptables_cmd(family))
    ipt = __salt__['cmd.run'](cmd)

    # regex out the output if configured with filters
    if _conf_save_filters():
        ipt = _regex_iptables_save(ipt)

    out = __salt__['file.write'](filename, ipt)
    return out
646394
def copyidfintoidf(toidf, fromidf):
    """"""
    idfobjlst = getidfobjectlist(fromidf)
    for idfobj in idfobjlst:
        toidf.copyidfobject(idfobj)
825243
private synchronized void initFsDataSet(Configuration conf,
      AbstractList<File> dataDirs, int numNamespaces) throws IOException {
    if (data != null) { // Already initialized
      return;
    }

    // get version and id info from the name-node
    boolean simulatedFSDataset = 
      conf.getBoolean("dfs.datanode.simulateddatastorage", false);

    if (simulatedFSDataset) {
      storage.createStorageID(selfAddr.getPort());
      // it would have been better to pass storage as a parameter to
      // constructor below - need to augment ReflectionUtils used below.
      conf.set("dfs.datanode.StorageId", storage.getStorageID());
      try {
        data = (FSDatasetInterface) ReflectionUtils.newInstance(
            Class.forName(
            "org.apache.hadoop.hdfs.server.datanode.SimulatedFSDataset"),
            conf);
      } catch (ClassNotFoundException e) {
        throw new IOException(StringUtils.stringifyException(e));
      }
    } else {
      data = new FSDataset(this, conf, numNamespaces);
    }
  }
480986
public void dumpidToIidDB(String dumpFilename) throws Exception {
		DatabaseEntry foundKey = new DatabaseEntry();
		DatabaseEntry foundData = new DatabaseEntry();

		ForwardCursor cursor = idToIidDB.openCursor(null, null);
		BufferedWriter out = new BufferedWriter(new FileWriter(new File(dumpFilename)));
		while (cursor.getNext(foundKey, foundData, LockMode.DEFAULT) == OperationStatus.SUCCESS) {
			int iid = IntegerBinding.entryToInt(foundData);
			String id = StringBinding.entryToString(foundKey);
			out.write(id + " " + iid + "\n");
		}
		cursor.close();
		out.close();
	}
601330
def save(self, filething=None, v2_version=4, v23_sep='/', padding=None):
        """"""

        fileobj = filething.fileobj

        iff_file = IFFFile(fileobj)

        if u'ID3' not in iff_file:
            iff_file.insert_chunk(u'ID3')

        chunk = iff_file[u'ID3']

        try:
            data = self._prepare_data(
                fileobj, chunk.data_offset, chunk.data_size, v2_version,
                v23_sep, padding)
        except ID3Error as e:
            reraise(error, e, sys.exc_info()[2])

        new_size = len(data)
        new_size += new_size % 2  # pad byte
        assert new_size % 2 == 0
        chunk.resize(new_size)
        data += (new_size - len(data)) * b'\x00'
        assert new_size == len(data)
        chunk.write(data)
1341945
def _write_mef(self, key, extlist, outfile):
        """"""
        channel = self.fv.get_channel(self.chname)
        with fits.open(outfile, mode='update') as pf:
            # Process each modified data extension
            for idx in extlist:
                k = '{0}[{1}]'.format(key, self._format_extname(idx))
                image = channel.datasrc[k]

                # Insert data and header into output HDU
                pf[idx].data = image.get_data()
                self._write_header(image, pf[idx])

            # Write history to PRIMARY
            self._write_history(key, pf['PRIMARY'])
552677
def MakeID3v1(id3):
    """"""

    v1 = {}

    for v2id, name in {"TIT2": "title", "TPE1": "artist",
                       "TALB": "album"}.items():
        if v2id in id3:
            text = id3[v2id].text[0].encode('latin1', 'replace')[:30]
        else:
            text = b""
        v1[name] = text + (b"\x00" * (30 - len(text)))

    if "COMM" in id3:
        cmnt = id3["COMM"].text[0].encode('latin1', 'replace')[:28]
    else:
        cmnt = b""
    v1["comment"] = cmnt + (b"\x00" * (29 - len(cmnt)))

    if "TRCK" in id3:
        try:
            v1["track"] = chr_(+id3["TRCK"])
        except ValueError:
            v1["track"] = b"\x00"
    else:
        v1["track"] = b"\x00"

    if "TCON" in id3:
        try:
            genre = id3["TCON"].genres[0]
        except IndexError:
            pass
        else:
            if genre in TCON.GENRES:
                v1["genre"] = chr_(TCON.GENRES.index(genre))
    if "genre" not in v1:
        v1["genre"] = b"\xff"

    if "TDRC" in id3:
        year = text_type(id3["TDRC"]).encode('ascii')
    elif "TYER" in id3:
        year = text_type(id3["TYER"]).encode('ascii')
    else:
        year = b""
    v1["year"] = (year + b"\x00\x00\x00\x00")[:4]

    return (
        b"TAG" +
        v1["title"] +
        v1["artist"] +
        v1["album"] +
        v1["year"] +
        v1["comment"] +
        v1["track"] +
        v1["genre"]
    )
1251643
def saveHdlFiles(self, srcDir):
        
        path = os.path.join(srcDir, self.name)
        try:
            os.makedirs(path)
        except OSError:
            # wipe if exists
            shutil.rmtree(path)
            os.makedirs(path)

        files = self.hdlFiles
        self.hdlFiles = self.toHdlConversion(self.top, self.name, path)
        for srcF in files:
            dst = os.path.join(path,
                               os.path.relpath(srcF, srcDir).replace('../', '')
                               )
            os.makedirs(os.path.dirname(dst), exist_ok=True)
            shutil.copy(srcF, dst)
            self.hdlFiles.append(dst)
1165923
private void writeToFile(List<DomainControllerData> data, String domainName) throws IOException {
        if(domainName == null || data == null) {
            return;
        }

        if (conn == null) {
            init();
        }

        try {
            String key = S3Util.sanitize(domainName) + "/" + S3Util.sanitize(DC_FILE_NAME);
            byte[] buf = S3Util.domainControllerDataToByteBuffer(data);
            S3Object val = new S3Object(buf, null);
            if (usingPreSignedUrls()) {
                Map headers = new TreeMap();
                headers.put("x-amz-acl", Arrays.asList("public-read"));
                conn.put(pre_signed_put_url, val, headers).connection.getResponseMessage();
            } else {
                Map headers = new TreeMap();
                headers.put("Content-Type", Arrays.asList("text/plain"));
                conn.put(location, key, val, headers).connection.getResponseMessage();
            }
        }
        catch(Exception e) {
            throw HostControllerLogger.ROOT_LOGGER.cannotWriteToS3File(e.getLocalizedMessage());
        }
    }
537588
def save(self, path=None, complevel=1, complib='zlib'):
        
        if path is None:
            path = self.hexuid + '.hdf5'
        elif os.path.isdir(path):
            path += os.sep + self.hexuid + '.hdf5'
        elif not (path.endswith('.hdf5') or path.endswith('.hdf')):
            raise ValueError('File path must have a ".hdf5" or ".hdf" extension.')
        with pd.HDFStore(path, 'w', complevel=complevel, complib=complib) as store:
            store['kwargs'] = pd.Series()
            store.get_storer('kwargs').attrs.metadata = self._rel()
            fc = 0    # Field counter (see special handling of fields below)
            for name, data in self._data().items():
                if hasattr(data, '_revert_categories'):
                    data._revert_categories()
                name = name[1:] if name.startswith('_') else name
                if isinstance(data, Field):    # Fields are handled separately
                    fname = 'FIELD{}_'.format(fc) + name + '/'
                    store[fname + 'data'] = pd.DataFrame(data)
                    for i, field in enumerate(data.field_values):
                        ffname = fname + 'values' + str(i)
                        if isinstance(field, pd.Series):
                            store[ffname] = pd.Series(field)
                        else:
                            store[ffname] = pd.DataFrame(field)
                    fc += 1
                elif isinstance(data, Series):
                    s = pd.Series(data)
                    if isinstance(data.dtype, pd.types.dtypes.CategoricalDtype):
                        s = s.astype('O')
                    store[name] = s
                elif isinstance(data, DataFrame):
                    store[name] = pd.DataFrame(data)
                elif isinstance(data, SparseSeries):
                    s = pd.SparseSeries(data)
                    if isinstance(data.dtype, pd.types.dtypes.CategoricalDtype):
                        s = s.astype('O')
                    store[name] = s
                elif isinstance(data, SparseDataFrame):
                    store[name] = pd.SparseDataFrame(data)
                else:
                    if hasattr(data, 'dtype') and isinstance(data.dtype, pd.types.dtypes.CategoricalDtype):
                        data = data.astype('O')
                    else:
                        for col in data:
                            if isinstance(data[col].dtype, pd.types.dtypes.CategoricalDtype):
                                data[col] = data[col].astype('O')
                    store[name] = data
                if hasattr(data, '_set_categories'):
                    data._set_categories()
1106463
def object_data(self):
        '''
        '''
        self.foxml_buffer = io.BytesIO()

        if self.progress_bar:
            self.progress_bar.start()

        previous_section = None
        while True:
            try:
                section = self.get_next_section()
            except StopIteration:
                break

            if section == BINARY_CONTENT_START:
                self.within_file = True

                # get datastream info from the end of the section just before this one
                # (needed to provide size to upload request)
                dsinfo = self.get_datastream_info(previous_section)
                if dsinfo:
                    logger.info('Found encoded datastream %(id)s (%(mimetype)s, size %(size)s, %(type)s %(digest)s)',
                                dsinfo)
                else:
                    # error if datastream info is not found, because either
                    # size or version date is required to handle content
                    raise Exception('Failed to find datastream information for %s from \n%s' \
                        % (self.obj.pid, previous_section))

                if self.xml_only and not \
                   dsinfo['mimetype'] in ['text/xml', 'application/rdf+xml',
                                          'application/xml']:
                    # possibly other mimetypes also?
                    try:
                        dsid = dsinfo['id'].split('.')[0]
                    except ValueError:
                        # if dsid doesn't include a .# (for versioning),
                        # use the id as is.
                        dsid = dsinfo['id']

                    if self.url_credentials:
                        # if url credentials are set, parse the base fedora api
                        # url so they can be inserted at the right place
                        parsed_url = urlparse(self.obj.api.base_url)
                        # reassemble base url, adding in credentials
                        base_url = ''.join([parsed_url.scheme, '://',
                            self.url_credentials, parsed_url.netloc,
                            parsed_url.path])
                    else:
                        base_url = self.obj.api.base_url

                    # versioned datastream dissemination url
                    content_location = '%sobjects/%s/datastreams/%s/content?asOfDateTime=%s' % \
                        (base_url, self.obj.pid, dsid, dsinfo['created'])
                else:
                    upload_args = {}
                    if self.progress_bar:
                        def upload_callback(monitor):
                            self.progress_bar.upload = monitor.bytes_read
                        upload_args = {'callback': upload_callback}

                    # use upload id as content location
                    content_location = self.dest_repo.api.upload(self.encoded_datastream(),
                        size=int(dsinfo['size']), **upload_args)

                self.foxml_buffer.write(force_bytes('<foxml:contentLocation REF="%s" TYPE="URL"/>' \
                    % content_location))

            elif section == BINARY_CONTENT_END:
                # should not occur here; this section will be processed by
                # encoded_datastream method
                self.within_file = False

            elif self.within_file:
                # should not occur here; this section will be pulled by
                # encoded_datastream method

                # binary content within a file - ignore here
                # (handled by encoded_datastream method)
                continue

            else:
                # not start or end of binary content, and not
                # within a file, so yield as is (e.g., datastream tags
                # between small files)
                self.foxml_buffer.write(section)

            previous_section = section

        return self.foxml_buffer