desc
stringlengths 3
26.7k
| decl
stringlengths 11
7.89k
| bodies
stringlengths 8
553k
|
---|---|---|
'Return a file-like representation or raise a KeyError.'
| def get_file(self, key):
| try:
f = open(os.path.join(self._path, str(key)), 'rb')
except IOError as e:
if (e.errno == errno.ENOENT):
raise KeyError(('No message with key: %s' % key))
else:
raise
return _ProxyFile(f)
|
'Return an iterator over keys.'
| def iterkeys(self):
| return iter(sorted((int(entry) for entry in os.listdir(self._path) if entry.isdigit())))
|
'Return True if the keyed message exists, False otherwise.'
| def has_key(self, key):
| return os.path.exists(os.path.join(self._path, str(key)))
|
'Return a count of messages in the mailbox.'
| def __len__(self):
| return len(list(self.iterkeys()))
|
'Lock the mailbox.'
| def lock(self):
| if (not self._locked):
self._file = open(os.path.join(self._path, '.mh_sequences'), 'rb+')
_lock_file(self._file)
self._locked = True
|
'Unlock the mailbox if it is locked.'
| def unlock(self):
| if self._locked:
_unlock_file(self._file)
_sync_close(self._file)
del self._file
self._locked = False
|
'Write any pending changes to the disk.'
| def flush(self):
| return
|
'Flush and close the mailbox.'
| def close(self):
| if self._locked:
self.unlock()
|
'Return a list of folder names.'
| def list_folders(self):
| result = []
for entry in os.listdir(self._path):
if os.path.isdir(os.path.join(self._path, entry)):
result.append(entry)
return result
|
'Return an MH instance for the named folder.'
| def get_folder(self, folder):
| return MH(os.path.join(self._path, folder), factory=self._factory, create=False)
|
'Create a folder and return an MH instance representing it.'
| def add_folder(self, folder):
| return MH(os.path.join(self._path, folder), factory=self._factory)
|
'Delete the named folder, which must be empty.'
| def remove_folder(self, folder):
| path = os.path.join(self._path, folder)
entries = os.listdir(path)
if (entries == ['.mh_sequences']):
os.remove(os.path.join(path, '.mh_sequences'))
elif (entries == []):
pass
else:
raise NotEmptyError(('Folder not empty: %s' % self._path))
os.rmdir(path)
|
'Return a name-to-key-list dictionary to define each sequence.'
| def get_sequences(self):
| results = {}
f = open(os.path.join(self._path, '.mh_sequences'), 'r')
try:
all_keys = set(self.keys())
for line in f:
try:
(name, contents) = line.split(':')
keys = set()
for spec in contents.split():
if spec.isdigit():
keys.add(int(spec))
else:
(start, stop) = (int(x) for x in spec.split('-'))
keys.update(range(start, (stop + 1)))
results[name] = [key for key in sorted(keys) if (key in all_keys)]
if (len(results[name]) == 0):
del results[name]
except ValueError:
raise FormatError(('Invalid sequence specification: %s' % line.rstrip()))
finally:
f.close()
return results
|
'Set sequences using the given name-to-key-list dictionary.'
| def set_sequences(self, sequences):
| f = open(os.path.join(self._path, '.mh_sequences'), 'r+')
try:
os.close(os.open(f.name, (os.O_WRONLY | os.O_TRUNC)))
for (name, keys) in sequences.iteritems():
if (len(keys) == 0):
continue
f.write(('%s:' % name))
prev = None
completing = False
for key in sorted(set(keys)):
if ((key - 1) == prev):
if (not completing):
completing = True
f.write('-')
elif completing:
completing = False
f.write(('%s %s' % (prev, key)))
else:
f.write((' %s' % key))
prev = key
if completing:
f.write((str(prev) + '\n'))
else:
f.write('\n')
finally:
_sync_close(f)
|
'Re-name messages to eliminate numbering gaps. Invalidates keys.'
| def pack(self):
| sequences = self.get_sequences()
prev = 0
changes = []
for key in self.iterkeys():
if ((key - 1) != prev):
changes.append((key, (prev + 1)))
if hasattr(os, 'link'):
os.link(os.path.join(self._path, str(key)), os.path.join(self._path, str((prev + 1))))
os.unlink(os.path.join(self._path, str(key)))
else:
os.rename(os.path.join(self._path, str(key)), os.path.join(self._path, str((prev + 1))))
prev += 1
self._next_key = (prev + 1)
if (len(changes) == 0):
return
for (name, key_list) in sequences.items():
for (old, new) in changes:
if (old in key_list):
key_list[key_list.index(old)] = new
self.set_sequences(sequences)
|
'Inspect a new MHMessage and update sequences appropriately.'
| def _dump_sequences(self, message, key):
| pending_sequences = message.get_sequences()
all_sequences = self.get_sequences()
for (name, key_list) in all_sequences.iteritems():
if (name in pending_sequences):
key_list.append(key)
elif (key in key_list):
del key_list[key_list.index(key)]
for sequence in pending_sequences:
if (sequence not in all_sequences):
all_sequences[sequence] = [key]
self.set_sequences(all_sequences)
|
'Initialize a Babyl mailbox.'
| def __init__(self, path, factory=None, create=True):
| _singlefileMailbox.__init__(self, path, factory, create)
self._labels = {}
|
'Add message and return assigned key.'
| def add(self, message):
| key = _singlefileMailbox.add(self, message)
if isinstance(message, BabylMessage):
self._labels[key] = message.get_labels()
return key
|
'Remove the keyed message; raise KeyError if it doesn\'t exist.'
| def remove(self, key):
| _singlefileMailbox.remove(self, key)
if (key in self._labels):
del self._labels[key]
|
'Replace the keyed message; raise KeyError if it doesn\'t exist.'
| def __setitem__(self, key, message):
| _singlefileMailbox.__setitem__(self, key, message)
if isinstance(message, BabylMessage):
self._labels[key] = message.get_labels()
|
'Return a Message representation or raise a KeyError.'
| def get_message(self, key):
| (start, stop) = self._lookup(key)
self._file.seek(start)
self._file.readline()
original_headers = StringIO.StringIO()
while True:
line = self._file.readline()
if ((line == ('*** EOOH ***' + os.linesep)) or (line == '')):
break
original_headers.write(line.replace(os.linesep, '\n'))
visible_headers = StringIO.StringIO()
while True:
line = self._file.readline()
if ((line == os.linesep) or (line == '')):
break
visible_headers.write(line.replace(os.linesep, '\n'))
body = self._file.read((stop - self._file.tell())).replace(os.linesep, '\n')
msg = BabylMessage((original_headers.getvalue() + body))
msg.set_visible(visible_headers.getvalue())
if (key in self._labels):
msg.set_labels(self._labels[key])
return msg
|
'Return a string representation or raise a KeyError.'
| def get_string(self, key):
| (start, stop) = self._lookup(key)
self._file.seek(start)
self._file.readline()
original_headers = StringIO.StringIO()
while True:
line = self._file.readline()
if ((line == ('*** EOOH ***' + os.linesep)) or (line == '')):
break
original_headers.write(line.replace(os.linesep, '\n'))
while True:
line = self._file.readline()
if ((line == os.linesep) or (line == '')):
break
return (original_headers.getvalue() + self._file.read((stop - self._file.tell())).replace(os.linesep, '\n'))
|
'Return a file-like representation or raise a KeyError.'
| def get_file(self, key):
| return StringIO.StringIO(self.get_string(key).replace('\n', os.linesep))
|
'Return a list of user-defined labels in the mailbox.'
| def get_labels(self):
| self._lookup()
labels = set()
for label_list in self._labels.values():
labels.update(label_list)
labels.difference_update(self._special_labels)
return list(labels)
|
'Generate key-to-(start, stop) table of contents.'
| def _generate_toc(self):
| (starts, stops) = ([], [])
self._file.seek(0)
next_pos = 0
label_lists = []
while True:
line_pos = next_pos
line = self._file.readline()
next_pos = self._file.tell()
if (line == ('\x1f\x0c' + os.linesep)):
if (len(stops) < len(starts)):
stops.append((line_pos - len(os.linesep)))
starts.append(next_pos)
labels = [label.strip() for label in self._file.readline()[1:].split(',') if (label.strip() != '')]
label_lists.append(labels)
elif ((line == '\x1f') or (line == ('\x1f' + os.linesep))):
if (len(stops) < len(starts)):
stops.append((line_pos - len(os.linesep)))
elif (line == ''):
stops.append((line_pos - len(os.linesep)))
break
self._toc = dict(enumerate(zip(starts, stops)))
self._labels = dict(enumerate(label_lists))
self._next_key = len(self._toc)
self._file.seek(0, 2)
self._file_length = self._file.tell()
|
'Called before writing the mailbox to file f.'
| def _pre_mailbox_hook(self, f):
| f.write(('BABYL OPTIONS:%sVersion: 5%sLabels:%s%s\x1f' % (os.linesep, os.linesep, ','.join(self.get_labels()), os.linesep)))
|
'Called before writing each message to file f.'
| def _pre_message_hook(self, f):
| f.write(('\x0c' + os.linesep))
|
'Called after writing each message to file f.'
| def _post_message_hook(self, f):
| f.write((os.linesep + '\x1f'))
|
'Write message contents and return (start, stop).'
| def _install_message(self, message):
| start = self._file.tell()
if isinstance(message, BabylMessage):
special_labels = []
labels = []
for label in message.get_labels():
if (label in self._special_labels):
special_labels.append(label)
else:
labels.append(label)
self._file.write('1')
for label in special_labels:
self._file.write((', ' + label))
self._file.write(',,')
for label in labels:
self._file.write(((' ' + label) + ','))
self._file.write(os.linesep)
else:
self._file.write(('1,,' + os.linesep))
if isinstance(message, email.message.Message):
orig_buffer = StringIO.StringIO()
orig_generator = email.generator.Generator(orig_buffer, False, 0)
orig_generator.flatten(message)
orig_buffer.seek(0)
while True:
line = orig_buffer.readline()
self._file.write(line.replace('\n', os.linesep))
if ((line == '\n') or (line == '')):
break
self._file.write(('*** EOOH ***' + os.linesep))
if isinstance(message, BabylMessage):
vis_buffer = StringIO.StringIO()
vis_generator = email.generator.Generator(vis_buffer, False, 0)
vis_generator.flatten(message.get_visible())
while True:
line = vis_buffer.readline()
self._file.write(line.replace('\n', os.linesep))
if ((line == '\n') or (line == '')):
break
else:
orig_buffer.seek(0)
while True:
line = orig_buffer.readline()
self._file.write(line.replace('\n', os.linesep))
if ((line == '\n') or (line == '')):
break
while True:
buffer = orig_buffer.read(4096)
if (buffer == ''):
break
self._file.write(buffer.replace('\n', os.linesep))
elif isinstance(message, str):
body_start = (message.find('\n\n') + 2)
if ((body_start - 2) != (-1)):
self._file.write(message[:body_start].replace('\n', os.linesep))
self._file.write(('*** EOOH ***' + os.linesep))
self._file.write(message[:body_start].replace('\n', os.linesep))
self._file.write(message[body_start:].replace('\n', os.linesep))
else:
self._file.write((('*** EOOH ***' + os.linesep) + os.linesep))
self._file.write(message.replace('\n', os.linesep))
elif hasattr(message, 'readline'):
original_pos = message.tell()
first_pass = True
while True:
line = message.readline()
self._file.write(line.replace('\n', os.linesep))
if ((line == '\n') or (line == '')):
self._file.write(('*** EOOH ***' + os.linesep))
if first_pass:
first_pass = False
message.seek(original_pos)
else:
break
while True:
buffer = message.read(4096)
if (buffer == ''):
break
self._file.write(buffer.replace('\n', os.linesep))
else:
raise TypeError(('Invalid message type: %s' % type(message)))
stop = self._file.tell()
return (start, stop)
|
'Initialize a Message instance.'
| def __init__(self, message=None):
| if isinstance(message, email.message.Message):
self._become_message(copy.deepcopy(message))
if isinstance(message, Message):
message._explain_to(self)
elif isinstance(message, str):
self._become_message(email.message_from_string(message))
elif hasattr(message, 'read'):
self._become_message(email.message_from_file(message))
elif (message is None):
email.message.Message.__init__(self)
else:
raise TypeError(('Invalid message type: %s' % type(message)))
|
'Assume the non-format-specific state of message.'
| def _become_message(self, message):
| for name in ('_headers', '_unixfrom', '_payload', '_charset', 'preamble', 'epilogue', 'defects', '_default_type'):
self.__dict__[name] = message.__dict__[name]
|
'Copy format-specific state to message insofar as possible.'
| def _explain_to(self, message):
| if isinstance(message, Message):
return
else:
raise TypeError('Cannot convert to specified type')
|
'Initialize a MaildirMessage instance.'
| def __init__(self, message=None):
| self._subdir = 'new'
self._info = ''
self._date = time.time()
Message.__init__(self, message)
|
'Return \'new\' or \'cur\'.'
| def get_subdir(self):
| return self._subdir
|
'Set subdir to \'new\' or \'cur\'.'
| def set_subdir(self, subdir):
| if ((subdir == 'new') or (subdir == 'cur')):
self._subdir = subdir
else:
raise ValueError(("subdir must be 'new' or 'cur': %s" % subdir))
|
'Return as a string the flags that are set.'
| def get_flags(self):
| if self._info.startswith('2,'):
return self._info[2:]
else:
return ''
|
'Set the given flags and unset all others.'
| def set_flags(self, flags):
| self._info = ('2,' + ''.join(sorted(flags)))
|
'Set the given flag(s) without changing others.'
| def add_flag(self, flag):
| self.set_flags(''.join((set(self.get_flags()) | set(flag))))
|
'Unset the given string flag(s) without changing others.'
| def remove_flag(self, flag):
| if (self.get_flags() != ''):
self.set_flags(''.join((set(self.get_flags()) - set(flag))))
|
'Return delivery date of message, in seconds since the epoch.'
| def get_date(self):
| return self._date
|
'Set delivery date of message, in seconds since the epoch.'
| def set_date(self, date):
| try:
self._date = float(date)
except ValueError:
raise TypeError(("can't convert to float: %s" % date))
|
'Get the message\'s "info" as a string.'
| def get_info(self):
| return self._info
|
'Set the message\'s "info" string.'
| def set_info(self, info):
| if isinstance(info, str):
self._info = info
else:
raise TypeError(('info must be a string: %s' % type(info)))
|
'Copy Maildir-specific state to message insofar as possible.'
| def _explain_to(self, message):
| if isinstance(message, MaildirMessage):
message.set_flags(self.get_flags())
message.set_subdir(self.get_subdir())
message.set_date(self.get_date())
elif isinstance(message, _mboxMMDFMessage):
flags = set(self.get_flags())
if ('S' in flags):
message.add_flag('R')
if (self.get_subdir() == 'cur'):
message.add_flag('O')
if ('T' in flags):
message.add_flag('D')
if ('F' in flags):
message.add_flag('F')
if ('R' in flags):
message.add_flag('A')
message.set_from('MAILER-DAEMON', time.gmtime(self.get_date()))
elif isinstance(message, MHMessage):
flags = set(self.get_flags())
if ('S' not in flags):
message.add_sequence('unseen')
if ('R' in flags):
message.add_sequence('replied')
if ('F' in flags):
message.add_sequence('flagged')
elif isinstance(message, BabylMessage):
flags = set(self.get_flags())
if ('S' not in flags):
message.add_label('unseen')
if ('T' in flags):
message.add_label('deleted')
if ('R' in flags):
message.add_label('answered')
if ('P' in flags):
message.add_label('forwarded')
elif isinstance(message, Message):
pass
else:
raise TypeError(('Cannot convert to specified type: %s' % type(message)))
|
'Initialize an mboxMMDFMessage instance.'
| def __init__(self, message=None):
| self.set_from('MAILER-DAEMON', True)
if isinstance(message, email.message.Message):
unixfrom = message.get_unixfrom()
if ((unixfrom is not None) and unixfrom.startswith('From ')):
self.set_from(unixfrom[5:])
Message.__init__(self, message)
|
'Return contents of "From " line.'
| def get_from(self):
| return self._from
|
'Set "From " line, formatting and appending time_ if specified.'
| def set_from(self, from_, time_=None):
| if (time_ is not None):
if (time_ is True):
time_ = time.gmtime()
from_ += (' ' + time.asctime(time_))
self._from = from_
|
'Return as a string the flags that are set.'
| def get_flags(self):
| return (self.get('Status', '') + self.get('X-Status', ''))
|
'Set the given flags and unset all others.'
| def set_flags(self, flags):
| flags = set(flags)
(status_flags, xstatus_flags) = ('', '')
for flag in ('R', 'O'):
if (flag in flags):
status_flags += flag
flags.remove(flag)
for flag in ('D', 'F', 'A'):
if (flag in flags):
xstatus_flags += flag
flags.remove(flag)
xstatus_flags += ''.join(sorted(flags))
try:
self.replace_header('Status', status_flags)
except KeyError:
self.add_header('Status', status_flags)
try:
self.replace_header('X-Status', xstatus_flags)
except KeyError:
self.add_header('X-Status', xstatus_flags)
|
'Set the given flag(s) without changing others.'
| def add_flag(self, flag):
| self.set_flags(''.join((set(self.get_flags()) | set(flag))))
|
'Unset the given string flag(s) without changing others.'
| def remove_flag(self, flag):
| if (('Status' in self) or ('X-Status' in self)):
self.set_flags(''.join((set(self.get_flags()) - set(flag))))
|
'Copy mbox- or MMDF-specific state to message insofar as possible.'
| def _explain_to(self, message):
| if isinstance(message, MaildirMessage):
flags = set(self.get_flags())
if ('O' in flags):
message.set_subdir('cur')
if ('F' in flags):
message.add_flag('F')
if ('A' in flags):
message.add_flag('R')
if ('R' in flags):
message.add_flag('S')
if ('D' in flags):
message.add_flag('T')
del message['status']
del message['x-status']
maybe_date = ' '.join(self.get_from().split()[(-5):])
try:
message.set_date(calendar.timegm(time.strptime(maybe_date, '%a %b %d %H:%M:%S %Y')))
except (ValueError, OverflowError):
pass
elif isinstance(message, _mboxMMDFMessage):
message.set_flags(self.get_flags())
message.set_from(self.get_from())
elif isinstance(message, MHMessage):
flags = set(self.get_flags())
if ('R' not in flags):
message.add_sequence('unseen')
if ('A' in flags):
message.add_sequence('replied')
if ('F' in flags):
message.add_sequence('flagged')
del message['status']
del message['x-status']
elif isinstance(message, BabylMessage):
flags = set(self.get_flags())
if ('R' not in flags):
message.add_label('unseen')
if ('D' in flags):
message.add_label('deleted')
if ('A' in flags):
message.add_label('answered')
del message['status']
del message['x-status']
elif isinstance(message, Message):
pass
else:
raise TypeError(('Cannot convert to specified type: %s' % type(message)))
|
'Initialize an MHMessage instance.'
| def __init__(self, message=None):
| self._sequences = []
Message.__init__(self, message)
|
'Return a list of sequences that include the message.'
| def get_sequences(self):
| return self._sequences[:]
|
'Set the list of sequences that include the message.'
| def set_sequences(self, sequences):
| self._sequences = list(sequences)
|
'Add sequence to list of sequences including the message.'
| def add_sequence(self, sequence):
| if isinstance(sequence, str):
if (not (sequence in self._sequences)):
self._sequences.append(sequence)
else:
raise TypeError(('sequence must be a string: %s' % type(sequence)))
|
'Remove sequence from the list of sequences including the message.'
| def remove_sequence(self, sequence):
| try:
self._sequences.remove(sequence)
except ValueError:
pass
|
'Copy MH-specific state to message insofar as possible.'
| def _explain_to(self, message):
| if isinstance(message, MaildirMessage):
sequences = set(self.get_sequences())
if ('unseen' in sequences):
message.set_subdir('cur')
else:
message.set_subdir('cur')
message.add_flag('S')
if ('flagged' in sequences):
message.add_flag('F')
if ('replied' in sequences):
message.add_flag('R')
elif isinstance(message, _mboxMMDFMessage):
sequences = set(self.get_sequences())
if ('unseen' not in sequences):
message.add_flag('RO')
else:
message.add_flag('O')
if ('flagged' in sequences):
message.add_flag('F')
if ('replied' in sequences):
message.add_flag('A')
elif isinstance(message, MHMessage):
for sequence in self.get_sequences():
message.add_sequence(sequence)
elif isinstance(message, BabylMessage):
sequences = set(self.get_sequences())
if ('unseen' in sequences):
message.add_label('unseen')
if ('replied' in sequences):
message.add_label('answered')
elif isinstance(message, Message):
pass
else:
raise TypeError(('Cannot convert to specified type: %s' % type(message)))
|
'Initialize an BabylMessage instance.'
| def __init__(self, message=None):
| self._labels = []
self._visible = Message()
Message.__init__(self, message)
|
'Return a list of labels on the message.'
| def get_labels(self):
| return self._labels[:]
|
'Set the list of labels on the message.'
| def set_labels(self, labels):
| self._labels = list(labels)
|
'Add label to list of labels on the message.'
| def add_label(self, label):
| if isinstance(label, str):
if (label not in self._labels):
self._labels.append(label)
else:
raise TypeError(('label must be a string: %s' % type(label)))
|
'Remove label from the list of labels on the message.'
| def remove_label(self, label):
| try:
self._labels.remove(label)
except ValueError:
pass
|
'Return a Message representation of visible headers.'
| def get_visible(self):
| return Message(self._visible)
|
'Set the Message representation of visible headers.'
| def set_visible(self, visible):
| self._visible = Message(visible)
|
'Update and/or sensibly generate a set of visible headers.'
| def update_visible(self):
| for header in self._visible.keys():
if (header in self):
self._visible.replace_header(header, self[header])
else:
del self._visible[header]
for header in ('Date', 'From', 'Reply-To', 'To', 'CC', 'Subject'):
if ((header in self) and (header not in self._visible)):
self._visible[header] = self[header]
|
'Copy Babyl-specific state to message insofar as possible.'
| def _explain_to(self, message):
| if isinstance(message, MaildirMessage):
labels = set(self.get_labels())
if ('unseen' in labels):
message.set_subdir('cur')
else:
message.set_subdir('cur')
message.add_flag('S')
if (('forwarded' in labels) or ('resent' in labels)):
message.add_flag('P')
if ('answered' in labels):
message.add_flag('R')
if ('deleted' in labels):
message.add_flag('T')
elif isinstance(message, _mboxMMDFMessage):
labels = set(self.get_labels())
if ('unseen' not in labels):
message.add_flag('RO')
else:
message.add_flag('O')
if ('deleted' in labels):
message.add_flag('D')
if ('answered' in labels):
message.add_flag('A')
elif isinstance(message, MHMessage):
labels = set(self.get_labels())
if ('unseen' in labels):
message.add_sequence('unseen')
if ('answered' in labels):
message.add_sequence('replied')
elif isinstance(message, BabylMessage):
message.set_visible(self.get_visible())
for label in self.get_labels():
message.add_label(label)
elif isinstance(message, Message):
pass
else:
raise TypeError(('Cannot convert to specified type: %s' % type(message)))
|
'Initialize a _ProxyFile.'
| def __init__(self, f, pos=None):
| self._file = f
if (pos is None):
self._pos = f.tell()
else:
self._pos = pos
|
'Read bytes.'
| def read(self, size=None):
| return self._read(size, self._file.read)
|
'Read a line.'
| def readline(self, size=None):
| return self._read(size, self._file.readline)
|
'Read multiple lines.'
| def readlines(self, sizehint=None):
| result = []
for line in self:
result.append(line)
if (sizehint is not None):
sizehint -= len(line)
if (sizehint <= 0):
break
return result
|
'Iterate over lines.'
| def __iter__(self):
| return iter(self.readline, '')
|
'Return the position.'
| def tell(self):
| return self._pos
|
'Change position.'
| def seek(self, offset, whence=0):
| if (whence == 1):
self._file.seek(self._pos)
self._file.seek(offset, whence)
self._pos = self._file.tell()
|
'Close the file.'
| def close(self):
| del self._file
|
'Read size bytes using read_method.'
| def _read(self, size, read_method):
| if (size is None):
size = (-1)
self._file.seek(self._pos)
result = read_method(size)
self._pos = self._file.tell()
return result
|
'Initialize a _PartialFile.'
| def __init__(self, f, start=None, stop=None):
| _ProxyFile.__init__(self, f, start)
self._start = start
self._stop = stop
|
'Return the position with respect to start.'
| def tell(self):
| return (_ProxyFile.tell(self) - self._start)
|
'Change position, possibly with respect to start or stop.'
| def seek(self, offset, whence=0):
| if (whence == 0):
self._pos = self._start
whence = 1
elif (whence == 2):
self._pos = self._stop
whence = 1
_ProxyFile.seek(self, offset, whence)
|
'Read size bytes using read_method, honoring start and stop.'
| def _read(self, size, read_method):
| remaining = (self._stop - self._pos)
if (remaining <= 0):
return ''
if ((size is None) or (size < 0) or (size > remaining)):
size = remaining
return _ProxyFile._read(self, size, read_method)
|
'Run the module after setting up the environment.
First check the syntax. If OK, make sure the shell is active and
then transfer the arguments, set the run environment\'s working
directory to the directory of the module being executed and also
add that directory to its sys.path if not already included.'
| def run_module_event(self, event):
| filename = self.getfilename()
if (not filename):
return 'break'
code = self.checksyntax(filename)
if (not code):
return 'break'
if (not self.tabnanny(filename)):
return 'break'
shell = self.shell
interp = shell.interp
if PyShell.use_subprocess:
shell.restart_shell()
dirname = os.path.dirname(filename)
interp.runcommand(('if 1:\n _filename = %r\n import sys as _sys\n from os.path import basename as _basename\n if (not _sys.argv or\n _basename(_sys.argv[0]) != _basename(_filename)):\n _sys.argv = [_filename]\n import os as _os\n _os.chdir(%r)\n del _filename, _sys, _basename, _os\n \n' % (filename, dirname)))
interp.prepend_syspath(filename)
interp.runcode(code)
return 'break'
|
'Get source filename. If not saved, offer to save (or create) file
The debugger requires a source file. Make sure there is one, and that
the current version of the source buffer has been saved. If the user
declines to save or cancels the Save As dialog, return None.
If the user has configured IDLE for Autosave, the file will be
silently saved if it already exists and is dirty.'
| def getfilename(self):
| filename = self.editwin.io.filename
if (not self.editwin.get_saved()):
autosave = idleConf.GetOption('main', 'General', 'autosave', type='bool')
if (autosave and filename):
self.editwin.io.save(None)
else:
confirm = self.ask_save_dialog()
self.editwin.text.focus_set()
if confirm:
self.editwin.io.save(None)
filename = self.editwin.io.filename
else:
filename = None
return filename
|
'Load PyShellEditorWindow breakpoints into subprocess debugger'
| def load_breakpoints(self):
| pyshell_edit_windows = self.pyshell.flist.inversedict.keys()
for editwin in pyshell_edit_windows:
filename = editwin.io.filename
try:
for lineno in editwin.breakpoints:
self.set_breakpoint_here(filename, lineno)
except AttributeError:
continue
|
'override base method'
| def popup_event(self, event):
| if self.stack:
return ScrolledList.popup_event(self, event)
|
'override base method'
| def fill_menu(self):
| menu = self.menu
menu.add_command(label='Go to source line', command=self.goto_source_line)
menu.add_command(label='Show stack frame', command=self.show_stack_frame)
|
'override base method'
| def on_select(self, index):
| if (0 <= index < len(self.stack)):
self.gui.show_frame(self.stack[index])
|
'override base method'
| def on_double(self, index):
| self.show_source(index)
|
'Create a Unicode string
If that fails, let Tcl try its best'
| def decode(self, chars):
| if chars.startswith(BOM_UTF8):
try:
chars = chars[3:].decode('utf-8')
except UnicodeError:
return chars
else:
self.fileencoding = BOM_UTF8
return chars
try:
enc = coding_spec(chars)
except LookupError as name:
tkMessageBox.showerror(title='Error loading the file', message=("The encoding '%s' is not known to this Python installation. The file may not display correctly" % name), master=self.text)
enc = None
if enc:
try:
return unicode(chars, enc)
except UnicodeError:
pass
try:
return unicode(chars, 'ascii')
except UnicodeError:
pass
try:
chars = unicode(chars, encoding)
self.fileencoding = encoding
except UnicodeError:
pass
return chars
|
'Update recent file list on all editor windows'
| def updaterecentfileslist(self, filename):
| self.editwin.update_recent_files_list(filename)
|
'Constructor arguments:
select_command -- A callable which will be called when a tab is
selected. It is called with the name of the selected tab as an
argument.
tabs -- A list of strings, the names of the tabs. Should be specified in
the desired tab order. The first tab will be the default and first
active tab. If tabs is None or empty, the TabSet will be initialized
empty.
n_rows -- Number of rows of tabs to be shown. If n_rows <= 0 or is
None, then the number of rows will be decided by TabSet. See
_arrange_tabs() for details.
max_tabs_per_row -- Used for deciding how many rows of tabs are needed,
when the number of rows is not constant. See _arrange_tabs() for
details.'
| def __init__(self, page_set, select_command, tabs=None, n_rows=1, max_tabs_per_row=5, expand_tabs=False, **kw):
| Frame.__init__(self, page_set, **kw)
self.select_command = select_command
self.n_rows = n_rows
self.max_tabs_per_row = max_tabs_per_row
self.expand_tabs = expand_tabs
self.page_set = page_set
self._tabs = {}
self._tab2row = {}
if tabs:
self._tab_names = list(tabs)
else:
self._tab_names = []
self._selected_tab = None
self._tab_rows = []
self.padding_frame = Frame(self, height=2, borderwidth=0, relief=FLAT, background=self.cget('background'))
self.padding_frame.pack(side=TOP, fill=X, expand=False)
self._arrange_tabs()
|
'Add a new tab with the name given in tab_name.'
| def add_tab(self, tab_name):
| if (not tab_name):
raise InvalidNameError(("Invalid Tab name: '%s'" % tab_name))
if (tab_name in self._tab_names):
raise AlreadyExistsError(("Tab named '%s' already exists" % tab_name))
self._tab_names.append(tab_name)
self._arrange_tabs()
|
'Remove the tab named <tab_name>'
| def remove_tab(self, tab_name):
| if (not (tab_name in self._tab_names)):
raise KeyError(("No such Tab: '%s" % page_name))
self._tab_names.remove(tab_name)
self._arrange_tabs()
|
'Show the tab named <tab_name> as the selected one'
| def set_selected_tab(self, tab_name):
| if (tab_name == self._selected_tab):
return
if ((tab_name is not None) and (tab_name not in self._tabs)):
raise KeyError(("No such Tab: '%s" % page_name))
if (self._selected_tab is not None):
self._tabs[self._selected_tab].set_normal()
self._selected_tab = None
if (tab_name is not None):
self._selected_tab = tab_name
tab = self._tabs[tab_name]
tab.set_selected()
tab_row = self._tab2row[tab]
tab_row.pack_forget()
tab_row.pack(side=TOP, fill=X, expand=0)
|
'Arrange the tabs in rows, in the order in which they were added.
If n_rows >= 1, this will be the number of rows used. Otherwise the
number of rows will be calculated according to the number of tabs and
max_tabs_per_row. In this case, the number of rows may change when
adding/removing tabs.'
| def _arrange_tabs(self):
| for tab_name in self._tabs.keys():
self._tabs.pop(tab_name).destroy()
self._reset_tab_rows()
if (not self._tab_names):
return
if ((self.n_rows is not None) and (self.n_rows > 0)):
n_rows = self.n_rows
else:
n_rows = (((len(self._tab_names) - 1) // self.max_tabs_per_row) + 1)
expand_tabs = (self.expand_tabs or (n_rows > 1))
i = 0
for row_index in xrange(n_rows):
n_tabs = ((((len(self._tab_names) - i) - 1) // (n_rows - row_index)) + 1)
tab_names = self._tab_names[i:(i + n_tabs)]
i += n_tabs
self._add_tab_row(tab_names, expand_tabs)
selected = self._selected_tab
self.set_selected_tab(None)
if (selected in self._tab_names):
self.set_selected_tab(selected)
|
'Constructor arguments:
name -- The tab\'s name, which will appear in its button.
select_command -- The command to be called upon selection of the
tab. It is called with the tab\'s name as an argument.'
| def __init__(self, name, select_command, tab_row, tab_set):
| Frame.__init__(self, tab_row, borderwidth=self.bw, relief=RAISED)
self.name = name
self.select_command = select_command
self.tab_set = tab_set
self.is_last_in_row = False
self.button = Radiobutton(self, text=name, command=self._select_event, padx=5, pady=1, takefocus=FALSE, indicatoron=FALSE, highlightthickness=0, selectcolor='', borderwidth=0)
self.button.pack(side=LEFT, fill=X, expand=True)
self._init_masks()
self.set_normal()
|
'Event handler for tab selection.
With TabbedPageSet, this calls TabbedPageSet.change_page, so that
selecting a tab changes the page.
Note that this does -not- call set_selected -- it will be called by
TabSet.set_selected_tab, which should be called when whatever the
tabs are related to changes.'
| def _select_event(self, *args):
| self.select_command(self.name)
return
|
'Assume selected look'
| def set_selected(self):
| self._place_masks(selected=True)
|
'Assume normal look'
| def set_normal(self):
| self._place_masks(selected=False)
|
'Constructor arguments:
page_names -- A list of strings, each will be the dictionary key to a
page\'s widget, and the name displayed on the page\'s tab. Should be
specified in the desired page order. The first page will be the default
and first active page. If page_names is None or empty, the
TabbedPageSet will be initialized empty.
n_rows, max_tabs_per_row -- Parameters for the TabSet which will
manage the tabs. See TabSet\'s docs for details.
page_class -- Pages can be shown/hidden using three mechanisms:
* PageLift - All pages will be rendered one on top of the other. When
a page is selected, it will be brought to the top, thus hiding all
other pages. Using this method, the TabbedPageSet will not be resized
when pages are switched. (It may still be resized when pages are
added/removed.)
* PageRemove - When a page is selected, the currently showing page is
hidden, and the new page shown in its place. Using this method, the
TabbedPageSet may resize when pages are changed.
* PagePackForget - This mechanism uses the pack placement manager.
When a page is shown it is packed, and when it is hidden it is
unpacked (i.e. pack_forget). This mechanism may also cause the
TabbedPageSet to resize when the page is changed.'
| def __init__(self, parent, page_names=None, page_class=PageLift, n_rows=1, max_tabs_per_row=5, expand_tabs=False, **kw):
| Frame.__init__(self, parent, **kw)
self.page_class = page_class
self.pages = {}
self._pages_order = []
self._current_page = None
self._default_page = None
self.columnconfigure(0, weight=1)
self.rowconfigure(1, weight=1)
self.pages_frame = Frame(self)
self.pages_frame.grid(row=1, column=0, sticky=NSEW)
if self.page_class.uses_grid:
self.pages_frame.columnconfigure(0, weight=1)
self.pages_frame.rowconfigure(0, weight=1)
self._tab_set = TabSet(self, self.change_page, n_rows=n_rows, max_tabs_per_row=max_tabs_per_row, expand_tabs=expand_tabs)
if page_names:
for name in page_names:
self.add_page(name)
self._tab_set.grid(row=0, column=0, sticky=NSEW)
self.change_page(self._default_page)
|
'Add a new page with the name given in page_name.'
| def add_page(self, page_name):
| if (not page_name):
raise InvalidNameError(("Invalid TabPage name: '%s'" % page_name))
if (page_name in self.pages):
raise AlreadyExistsError(("TabPage named '%s' already exists" % page_name))
self.pages[page_name] = self.page_class(self.pages_frame)
self._pages_order.append(page_name)
self._tab_set.add_tab(page_name)
if (len(self.pages) == 1):
self._default_page = page_name
self.change_page(page_name)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.