Write code object as a byte-compiled file

    Arguments:
    codeobject: code object
    filefile: bytecode file to write
    timestamp: timestamp to put in file
    magic: Pyton bytecode magic
496474
def dump_compile(codeobject, filename, timestamp, magic):
    
    # Atomically write the pyc/pyo file.  Issue #13146.
    # id() is used to generate a pseudo-random filename.
    path_tmp = '%s.%s' % (filename, id(filename))
    fc = None
    try:
        fc = open(path_tmp, 'wb')
        if PYTHON3:
            fc.write(bytes([0, 0, 0, 0]))
        else:
            fc.write('\0\0\0\0')
        wr_long(fc, timestamp)
        marshal.dump(codeobject, fc)
        fc.flush()
        fc.seek(0, 0)
        fc.write(magic)
        fc.close()
        os.rename(path_tmp, filename)
    except OSError:
        try:
            os.unlink(path_tmp)
        except OSError:
            pass
        raise
    finally:
        if fc: fc.close()
400812
function saveCodepointsToFile(){
			if (!o.codepointsFile) return;
			var codepointsToString = JSON.stringify(o.codepoints, null, 4);
			try {
				fs.writeFileSync(o.codepointsFile, codepointsToString);
				logger.verbose('Codepoints saved to file "' + o.codepointsFile + '".');
			} catch (err) {
				logger.error(err.message);
			}
		}
920702
public void write(ByteCodeWriter out)
    throws IOException
  {
    out.writeUTF8Const(getName());

    TempOutputStream ts = new TempOutputStream();
    //ts.openWrite();
    //WriteStream ws = new WriteStream(ts);
    ByteCodeWriter o2 = new ByteCodeWriter(ts, out.getJavaClass());
    
    o2.writeShort(_maxStack);
    o2.writeShort(_maxLocals);
    o2.writeInt(_code.length);
    o2.write(_code, 0, _code.length);

    o2.writeShort(_exceptions.size());
    for (int i = 0; i < _exceptions.size(); i++) {
      ExceptionItem exn = _exceptions.get(i);

      o2.writeShort(exn.getStart());
      o2.writeShort(exn.getEnd());
      o2.writeShort(exn.getHandler());
      o2.writeShort(exn.getType());
    }

    o2.writeShort(_attributes.size());
    for (int i = 0; i < _attributes.size(); i++) {
      Attribute attr = _attributes.get(i);

      attr.write(o2);
    }
    
    //ws.close();
    
    out.writeInt(ts.getLength());
    TempBuffer ptr = ts.getHead();

    for (; ptr != null; ptr = ptr.next())
      out.write(ptr.buffer(), 0, ptr.length());

    ts.destroy();
  }
221491
def write temp_object, opts={}
      content_type = opts[:content_type] || opts[:mime_type] || 'application/octet-stream'
      meta = temp_object.meta
      meta = meta.merge(opts[:meta]) if opts[:meta]

      grid_file = session.bucket.open(BSON::ObjectId.new, "w+")
      grid_file.content_type = content_type
      grid_file.metadata = meta
      grid_file.write(temp_object.data)
      grid_file._id
    end
1319722
public static void writeObjectToFile(File file, Object object) throws IOException {
    FileOutputStream fs = new FileOutputStream(file);
    ObjectOutputStream os = new ObjectOutputStream(fs);
    os.writeObject(object);
    os.close();
  }
873041
def compile(file):
    
    log(_("compiling {} into byte code...").format(file))

    try:
        py_compile.compile(file, doraise=True)
    except py_compile.PyCompileError as e:
        log(_("Exception raised: "))
        for line in e.msg.splitlines():
            log(line)

        raise Failure(_("{} raised while compiling {} (rerun with --log for more details)").format(e.exc_type_name, file))
249920
def write_file(self, fileobject, skip_unknown=False):
        """"""
        self.set_metadata_version()

        for field in _version2fieldlist(self['Metadata-Version']):
            values = self.get(field)
            if skip_unknown and values in ('UNKNOWN', [], ['UNKNOWN']):
                continue
            if field in _ELEMENTSFIELD:
                self._write_field(fileobject, field, ','.join(values))
                continue
            if field not in _LISTFIELDS:
                if field == 'Description':
                    if self.metadata_version in ('1.0', '1.1'):
                        values = values.replace('\n', '\n        ')
                    else:
                        values = values.replace('\n', '\n       |')
                values = [values]

            if field in _LISTTUPLEFIELDS:
                values = [','.join(value) for value in values]

            for value in values:
                self._write_field(fileobject, field, value)
444986
def compare_code_with_srcfile(pyc_filename, src_filename, verify):
    
    (version, timestamp, magic_int, code_obj1, is_pypy,
     source_size) = load_module(pyc_filename)
    if magic_int != PYTHON_MAGIC_INT:
        msg = ("Can't compare code - Python is running with magic %s, but code is magic %s "
               % (PYTHON_MAGIC_INT, magic_int))
        return msg
    try:
        code_obj2 = load_file(src_filename)
    except SyntaxError as e:
        # src_filename can be the first of a group sometimes
        return str(e).replace(src_filename, pyc_filename)
    cmp_code_objects(version, is_pypy, code_obj1, code_obj2, verify)
    if verify == 'verify-run':
        try:
            retcode = call("%s %s" % (sys.executable, src_filename), shell=True)
            if retcode != 0:
                return "Child was terminated by signal %d" % retcode
            pass
        except OSError as e:
            return "Execution failed: %s" % e
        pass
    return None
31864
def pycbc_compile_function(code,arg_names,local_dict,global_dict,
                     module_dir,
                     compiler='',
                     verbose=1,
                     support_code=None,
                     headers=None,
                     customize=None,
                     type_converters=None,
                     auto_downcast=1,
                     **kw):
    
    headers = [] if headers is None else headers
    lockfile_dir = os.environ['PYTHONCOMPILED']
    lockfile_name = os.path.join(lockfile_dir, 'code_lockfile')
    logging.info("attempting to aquire lock '%s' for "
                 "compiling code" % lockfile_name)
    if not os.path.exists(lockfile_dir):
        os.makedirs(lockfile_dir)
    lockfile = open(lockfile_name, 'w')
    fcntl.lockf(lockfile, fcntl.LOCK_EX)
    logging.info("we have aquired the lock")

    func = _compile_function(code,arg_names, local_dict, global_dict,
                     module_dir, compiler, verbose,
                     support_code, headers, customize,
                     type_converters,
                     auto_downcast, **kw)

    fcntl.lockf(lockfile, fcntl.LOCK_UN)
    logging.info("the lock has been released")

    return func
924995
def write_thrift(fobj, thrift):
    
    t0 = fobj.tell()
    pout = TCompactProtocol(fobj)
    try:
        thrift.write(pout)
        fail = False
    except TProtocolException as e:
        typ, val, tb = sys.exc_info()
        frames = []
        while tb is not None:
            frames.append(tb)
            tb = tb.tb_next
        frame = [tb for tb in frames if 'write_struct' in str(tb.tb_frame.f_code)]
        variables = frame[0].tb_frame.f_locals
        obj = variables['obj']
        name = variables['fname']
        fail = True
    if fail:
        raise ParquetException('Thrift parameter validation failure %s'
                               ' when writing: %s-> Field: %s' % (
            val.args[0], obj, name
        ))
    return fobj.tell() - t0
1235181
def _make_rewritten_pyc(state, fn, pyc, co):
    """"""
    if sys.platform.startswith("win"):
        # Windows grants exclusive access to open files and doesn't have atomic
        # rename, so just write into the final file.
        _write_pyc(state, co, fn, pyc)
    else:
        # When not on windows, assume rename is atomic. Dump the code object
        # into a file specific to this process and atomically replace it.
        proc_pyc = pyc + "." + str(os.getpid())
        if _write_pyc(state, co, fn, proc_pyc):
            os.rename(proc_pyc, pyc)
630201
def to_code(self, context: Context =None):
        
        # Do not override this method!

        context = context or Context()
        for imp in self.imports:
            if imp not in context.imports:
                context.imports.append(imp)

        counter = Counter()
        lines = list(self.to_lines(context=context, counter=counter))

        if counter.num_indented_non_doc_blocks == 0:
            if self.expects_body_or_pass:
                lines.append("    pass")
            elif self.closed_by:
                lines[-1] += self.closed_by
        else:
            if self.closed_by:
                lines.append(self.closed_by)

        return join_lines(*lines) + self._suffix
706831
def writeBinary (self, filename=None):
    
    if filename is None:
      filename = self.binpath

    with open(filename, 'wb') as output:
      # Magic Number
      output.write( struct.pack('>H', Seq.Magic          )  )
      # Upload Type
      output.write( struct.pack('B', 9                   )  )
      # Version
      output.write( struct.pack('B', self.version        )  )
      # Number of Commands
      output.write( struct.pack('>H', len(self.commands) )  )
      # Sequence ID
      output.write( struct.pack('>H', self.seqid         )  )
      # CRC Placeholder
      output.write( struct.pack('>I', 0                  ) )

      pad = struct.pack('B', 0)
      for n in range(20):
        output.write(pad)

      for line in self.lines:
        output.write( line.encode() )

    self.crc32 = util.crc32File(filename, 0)

    with open(filename, 'r+b') as output:
      output.seek(28)
      output.write( struct.pack('>I', self.crc32) )
1140799
def __write(self, s):
        
        self.buf += s
        while len(self.buf) > self.bufsize:
            self.fileobj.write(self.buf[:self.bufsize])
            self.buf = self.buf[self.bufsize:]
1305154
def serialize(self, sw, **kw):
        '''
        
        '''
        for pyobj in self.header_pyobjs:
            if hasattr(pyobj, 'typecode') is False:
                raise RuntimeError, 'all header pyobjs must have a typecode attribute'

            sw.serialize_header(pyobj, **kw)
882416
def write(obj, filepath):
    
    if not isinstance(obj, Multitrack):
        raise TypeError("Support only `pypianoroll.Multitrack` class objects")
    obj.write(filepath)
51805
def _append_object(self, value, _file):
        
        _labs = ' {'
        _file.write(_labs)
        self._tctr += 1

        for (_item, _text) in value.items():
            _tabs = '\t' * self._tctr
            _cmma = ',' if self._vctr[self._tctr] else ''
            _keys = '{cmma}\n{tabs}"{item}" :'.format(cmma=_cmma, tabs=_tabs, item=_item)
            _file.write(_keys)

            self._vctr[self._tctr] += 1

            _text = self.object_hook(_text)
            _type = type(_text).__name__
            _MAGIC_TYPES[_type](self, _text, _file)

        self._vctr[self._tctr] = 0
        self._tctr -= 1
        _tabs = '\t' * self._tctr
        _labs = '\n{tabs}{}'.format('}', tabs=_tabs)
        _file.write(_labs)