desc stringlengths 3 26.7k | decl stringlengths 11 7.89k | bodies stringlengths 8 553k |
|---|---|---|
'Tells whether or not this result was a success'
| def wasSuccessful(self):
| return ((len(self.failures) + len(self.errors)) == 0)
|
'Indicates that the tests should be aborted'
| def stop(self):
| self.shouldStop = True
|
'Converts a sys.exc_info()-style tuple of values into a string.'
| def _exc_info_to_string(self, err, test):
| (exctype, value, tb) = err
while (tb and self._is_relevant_tb_level(tb)):
tb = tb.tb_next
if (exctype is test.failureException):
length = self._count_relevant_tb_levels(tb)
msgLines = traceback.format_exception(exctype, value, tb, length)
else:
msgLines = traceback.format... |
'Run the given test case or test suite.'
| def run(self, test):
| result = self._makeResult()
result.failfast = self.failfast
result.buffer = self.buffer
registerResult(result)
startTime = time.time()
startTestRun = getattr(result, 'startTestRun', None)
if (startTestRun is not None):
startTestRun()
try:
test(result)
finally:
... |
'Return a suite of all tests cases contained in testCaseClass'
| def loadTestsFromTestCase(self, testCaseClass):
| if issubclass(testCaseClass, suite.TestSuite):
raise TypeError('Test cases should not be derived from TestSuite. Maybe you meant to derive from TestCase?')
testCaseNames = self.getTestCaseNames(testCaseClass)
if ((not testCaseNames) and hasattr(testCaseClass... |
'Return a suite of all tests cases contained in the given module'
| def loadTestsFromModule(self, module, use_load_tests=True):
| tests = []
for name in dir(module):
obj = getattr(module, name)
if (isinstance(obj, type) and issubclass(obj, unittest.TestCase)):
tests.append(self.loadTestsFromTestCase(obj))
load_tests = getattr(module, 'load_tests', None)
tests = self.suiteClass(tests)
if (use_load_te... |
'Return a suite of all tests cases given a string specifier.
The name may resolve either to a module, a test case class, a
test method within a test case class, or a callable object which
returns a TestCase or TestSuite instance.
The method optionally resolves the names relative to a given module.'
| def loadTestsFromName(self, name, module=None):
| parts = name.split('.')
if (module is None):
parts_copy = parts[:]
while parts_copy:
try:
module = __import__('.'.join(parts_copy))
break
except ImportError:
del parts_copy[(-1)]
if (not parts_copy):
... |
'Return a suite of all tests cases found using the given sequence
of string specifiers. See \'loadTestsFromName()\'.'
| def loadTestsFromNames(self, names, module=None):
| suites = [self.loadTestsFromName(name, module) for name in names]
return self.suiteClass(suites)
|
'Return a sorted sequence of method names found within testCaseClass'
| def getTestCaseNames(self, testCaseClass):
| def isTestMethod(attrname, testCaseClass=testCaseClass, prefix=self.testMethodPrefix):
return (attrname.startswith(prefix) and hasattr(getattr(testCaseClass, attrname), '__call__'))
testFnNames = filter(isTestMethod, dir(testCaseClass))
if self.sortTestMethodsUsing:
testFnNames.sort(key=_Cmp... |
'Find and return all test modules from the specified start
directory, recursing into subdirectories to find them. Only test files
that match the pattern will be loaded. (Using shell style pattern
matching.)
All test modules must be importable from the top level of the project.
If the start directory is not the top leve... | def discover(self, start_dir, pattern='test*.py', top_level_dir=None):
| set_implicit_top = False
if ((top_level_dir is None) and (self._top_level_dir is not None)):
top_level_dir = self._top_level_dir
elif (top_level_dir is None):
set_implicit_top = True
top_level_dir = start_dir
top_level_dir = os.path.abspath(top_level_dir)
if (not (top_level_d... |
'Used by discovery. Yields test suites it loads.'
| def _find_tests(self, start_dir, pattern):
| paths = os.listdir(start_dir)
for path in paths:
full_path = os.path.join(start_dir, path)
if os.path.isfile(full_path):
if (not VALID_MODULE_NAME.match(path)):
continue
if (not self._match_path(path, full_path, pattern)):
continue
... |
'Run the tests without collecting errors in a TestResult'
| def debug(self):
| for test in self:
test.debug()
|
'Run the tests without collecting errors in a TestResult'
| def debug(self):
| debug = _DebugResult()
self._wrapped_run(debug, True)
self._tearDownPreviousClass(None, debug)
self._handleModuleTearDown(debug)
|
'Concatenating a safe string with another safe string or safe unicode
object is safe. Otherwise, the result is no longer safe.'
| def __add__(self, rhs):
| t = super(SafeString, self).__add__(rhs)
if isinstance(rhs, SafeUnicode):
return SafeUnicode(t)
elif isinstance(rhs, SafeString):
return SafeString(t)
return t
|
'Wrap a call to a normal unicode method up so that we return safe
results. The method that is being wrapped is passed in the \'method\'
argument.'
| def _proxy_method(self, *args, **kwargs):
| method = kwargs.pop('method')
data = method(self, *args, **kwargs)
if isinstance(data, str):
return SafeString(data)
else:
return SafeUnicode(data)
|
'Concatenating a safe unicode object with another safe string or safe
unicode object is safe. Otherwise, the result is no longer safe.'
| def __add__(self, rhs):
| t = super(SafeUnicode, self).__add__(rhs)
if isinstance(rhs, SafeData):
return SafeUnicode(t)
return t
|
'Wrap a call to a normal unicode method up so that we return safe
results. The method that is being wrapped is passed in the \'method\'
argument.'
| def _proxy_method(self, *args, **kwargs):
| method = kwargs.pop('method')
data = method(self, *args, **kwargs)
if isinstance(data, str):
return SafeString(data)
else:
return SafeUnicode(data)
|
'Resolve strings to objects using standard import and attribute
syntax.'
| def resolve(self, s):
| name = s.split('.')
used = name.pop(0)
try:
found = self.importer(used)
for frag in name:
used += ('.' + frag)
try:
found = getattr(found, frag)
except AttributeError:
self.importer(used)
found = getattr(foun... |
'Default converter for the ext:// protocol.'
| def ext_convert(self, value):
| return self.resolve(value)
|
'Default converter for the cfg:// protocol.'
| def cfg_convert(self, value):
| rest = value
m = self.WORD_PATTERN.match(rest)
if (m is None):
raise ValueError(('Unable to convert %r' % value))
else:
rest = rest[m.end():]
d = self.config[m.groups()[0]]
while rest:
m = self.DOT_PATTERN.match(rest)
if m:
... |
'Convert values to an appropriate type. dicts, lists and tuples are
replaced by their converting alternatives. Strings are checked to
see if they have a conversion format and are converted if they do.'
| def convert(self, value):
| if ((not isinstance(value, ConvertingDict)) and isinstance(value, dict)):
value = ConvertingDict(value)
value.configurator = self
elif ((not isinstance(value, ConvertingList)) and isinstance(value, list)):
value = ConvertingList(value)
value.configurator = self
elif ((not isi... |
'Configure an object with a user-supplied factory.'
| def configure_custom(self, config):
| c = config.pop('()')
if ((not hasattr(c, '__call__')) and hasattr(types, 'ClassType') and (type(c) != types.ClassType)):
c = self.resolve(c)
props = config.pop('.', None)
kwargs = dict([(k, config[k]) for k in config if valid_ident(k)])
result = c(**kwargs)
if props:
for (name, v... |
'Utility function which converts lists to tuples.'
| def as_tuple(self, value):
| if isinstance(value, list):
value = tuple(value)
return value
|
'Do the configuration.'
| def configure(self):
| config = self.config
if ('version' not in config):
raise ValueError("dictionary doesn't specify a version")
if (config['version'] != 1):
raise ValueError(('Unsupported version: %s' % config['version']))
incremental = config.pop('incremental', False)
EMPTY_DICT = {}
... |
'Configure a formatter from a dictionary.'
| def configure_formatter(self, config):
| if ('()' in config):
factory = config['()']
try:
result = self.configure_custom(config)
except TypeError as te:
if ("'format'" not in str(te)):
raise
config['fmt'] = config.pop('format')
config['()'] = factory
result... |
'Configure a filter from a dictionary.'
| def configure_filter(self, config):
| if ('()' in config):
result = self.configure_custom(config)
else:
name = config.get('name', '')
result = logging.Filter(name)
return result
|
'Add filters to a filterer from a list of names.'
| def add_filters(self, filterer, filters):
| for f in filters:
try:
filterer.addFilter(self.config['filters'][f])
except StandardError as e:
raise ValueError(('Unable to add filter %r: %s' % (f, e)))
|
'Configure a handler from a dictionary.'
| def configure_handler(self, config):
| formatter = config.pop('formatter', None)
if formatter:
try:
formatter = self.config['formatters'][formatter]
except StandardError as e:
raise ValueError(('Unable to set formatter %r: %s' % (formatter, e)))
level = config.pop('level', None)
filters ... |
'Add handlers to a logger from a list of names.'
| def add_handlers(self, logger, handlers):
| for h in handlers:
try:
logger.addHandler(self.config['handlers'][h])
except StandardError as e:
raise ValueError(('Unable to add handler %r: %s' % (h, e)))
|
'Perform configuration which is common to root and non-root loggers.'
| def common_logger_config(self, logger, config, incremental=False):
| level = config.get('level', None)
if (level is not None):
logger.setLevel(_checkLevel(level))
if (not incremental):
for h in logger.handlers[:]:
logger.removeHandler(h)
handlers = config.get('handlers', None)
if handlers:
self.add_handlers(logger, hand... |
'Configure a non-root logger from a dictionary.'
| def configure_logger(self, name, config, incremental=False):
| logger = logging.getLogger(name)
self.common_logger_config(logger, config, incremental)
propagate = config.get('propagate', None)
if (propagate is not None):
logger.propagate = propagate
|
'Configure a root logger from a dictionary.'
| def configure_root(self, config, incremental=False):
| root = logging.getLogger()
self.common_logger_config(root, config, incremental)
|
'Returns a copy of this object.'
| def copy(self):
| return self.__copy__()
|
'Returns something like
"{\'key1\': \'val1\', \'key2\': \'val2\', \'key3\': \'val3\'}"
instead of the generic "<object meta-data>" inherited from object.'
| def __str__(self):
| return str(dict(self.items()))
|
'Returns something like
MergeDict({\'key1\': \'val1\', \'key2\': \'val2\'}, {\'key3\': \'val3\'})
instead of generic "<object meta-data>" inherited from object.'
| def __repr__(self):
| dictreprs = ', '.join((repr(d) for d in self.dicts))
return ('%s(%s)' % (self.__class__.__name__, dictreprs))
|
'Returns the value of the item at the given zero-based index.'
| def value_for_index(self, index):
| return self[self.keyOrder[index]]
|
'Inserts the key, value pair before the item with the given index.'
| def insert(self, index, key, value):
| if (key in self.keyOrder):
n = self.keyOrder.index(key)
del self.keyOrder[n]
if (n < index):
index -= 1
self.keyOrder.insert(index, key)
super(SortedDict, self).__setitem__(key, value)
|
'Returns a copy of this object.'
| def copy(self):
| obj = self.__class__(self)
obj.keyOrder = self.keyOrder[:]
return obj
|
'Replaces the normal dict.__repr__ with a version that returns the keys
in their sorted order.'
| def __repr__(self):
| return ('{%s}' % ', '.join([('%r: %r' % (k, v)) for (k, v) in self.items()]))
|
'Returns the last data value for this key, or [] if it\'s an empty list;
raises KeyError if not found.'
| def __getitem__(self, key):
| try:
list_ = super(MultiValueDict, self).__getitem__(key)
except KeyError:
raise MultiValueDictKeyError(('Key %r not found in %r' % (key, self)))
try:
return list_[(-1)]
except IndexError:
return []
|
'Returns the last data value for the passed key. If key doesn\'t exist
or value is an empty list, then default is returned.'
| def get(self, key, default=None):
| try:
val = self[key]
except KeyError:
return default
if (val == []):
return default
return val
|
'Returns the list of values for the passed key. If key doesn\'t exist,
then a default value is returned.'
| def getlist(self, key, default=None):
| try:
return super(MultiValueDict, self).__getitem__(key)
except KeyError:
if (default is None):
return []
return default
|
'Appends an item to the internal list associated with key.'
| def appendlist(self, key, value):
| self.setlistdefault(key).append(value)
|
'Returns a list of (key, value) pairs, where value is the last item in
the list associated with the key.'
| def items(self):
| return [(key, self[key]) for key in self.keys()]
|
'Yields (key, value) pairs, where value is the last item in the list
associated with the key.'
| def iteritems(self):
| for key in self.keys():
(yield (key, self[key]))
|
'Returns a list of (key, list) pairs.'
| def lists(self):
| return super(MultiValueDict, self).items()
|
'Yields (key, list) pairs.'
| def iterlists(self):
| return super(MultiValueDict, self).iteritems()
|
'Returns a list of the last value on every key list.'
| def values(self):
| return [self[key] for key in self.keys()]
|
'Yield the last value on every key list.'
| def itervalues(self):
| for key in self.iterkeys():
(yield self[key])
|
'Returns a shallow copy of this object.'
| def copy(self):
| return copy.copy(self)
|
'update() extends rather than replaces existing key lists.
Also accepts keyword args.'
| def update(self, *args, **kwargs):
| if (len(args) > 1):
raise TypeError(('update expected at most 1 arguments, got %d' % len(args)))
if args:
other_dict = args[0]
if isinstance(other_dict, MultiValueDict):
for (key, value_list) in other_dict.lists():
self.setlistdefault(key)... |
'Returns current object as a dict with singular values.'
| def dict(self):
| return dict(((key, self[key]) for key in self))
|
'Retrieves the real value after stripping the prefix string (if
present). If the prefix is present, pass the value through self.func
before returning, otherwise return the raw value.'
| def __getitem__(self, key):
| if key.startswith(self.prefix):
use_func = True
key = key[len(self.prefix):]
else:
use_func = False
value = super(DictWrapper, self).__getitem__(key)
if use_func:
return self.func(value)
return value
|
'Returns true if all the paths have the same leading path name
(i.e., everything is in one subdirectory in an archive)'
| def has_leading_dir(self, paths):
| common_prefix = None
for path in paths:
(prefix, rest) = self.split_leading_dir(path)
if (not prefix):
return False
elif (common_prefix is None):
common_prefix = prefix
elif (prefix != common_prefix):
return False
return True
|
'Convenience method for adding an element with no children'
| def addQuickElement(self, name, contents=None, attrs=None):
| if (attrs is None):
attrs = {}
self.startElement(name, attrs)
if (contents is not None):
self.characters(contents)
self.endElement(name)
|
'Returns the text truncated to be no longer than the specified number
of characters.
Takes an optional argument of what should be used to notify that the
string has been truncated, defaulting to a translatable string of an
ellipsis (...).'
| def chars(self, num, truncate=None):
| length = int(num)
text = unicodedata.normalize('NFC', self._wrapped)
truncate_len = length
for char in self.add_truncation_text('', truncate):
if (not unicodedata.combining(char)):
truncate_len -= 1
if (truncate_len == 0):
break
s_len = 0
end_index... |
'Truncates a string after a certain number of words. Takes an optional
argument of what should be used to notify that the string has been
truncated, defaulting to ellipsis (...).'
| def words(self, num, truncate=None, html=False):
| length = int(num)
if html:
return self._html_words(length, truncate)
return self._text_words(length, truncate)
|
'Truncates a string after a certain number of words.
Newlines in the string will be stripped.'
| def _text_words(self, length, truncate):
| words = self._wrapped.split()
if (len(words) > length):
words = words[:length]
return self.add_truncation_text(u' '.join(words), truncate)
return u' '.join(words)
|
'Truncates HTML to a certain number of words (not counting tags and
comments). Closes opened tags if they were correctly closed in the
given HTML.
Newlines in the HTML are preserved.'
| def _html_words(self, length, truncate):
| if (length <= 0):
return u''
html4_singlets = ('br', 'col', 'link', 'base', 'img', 'param', 'area', 'hr', 'input')
pos = 0
end_text_pos = 0
words = 0
open_tags = []
while (words <= length):
m = re_words.search(self._wrapped, pos)
if (not m):
break
... |
'Constructs a new Node. If no connector is given, the default will be
used.
Warning: You probably don\'t want to pass in the \'negated\' parameter. It
is NOT the same as constructing a node and calling negate() on the
result.'
| def __init__(self, children=None, connector=None, negated=False):
| self.children = ((children and children[:]) or [])
self.connector = (connector or self.default)
self.subtree_parents = []
self.negated = negated
|
'This is called to create a new instance of this class when we need new
Nodes (or subclasses) in the internal code in this class. Normally, it
just shadows __init__(). However, subclasses with an __init__ signature
that is not an extension of Node.__init__ might need to implement this
method to allow a Node to create a... | def _new_instance(cls, children=None, connector=None, negated=False):
| obj = Node(children, connector, negated)
obj.__class__ = cls
return obj
|
'Utility method used by copy.deepcopy().'
| def __deepcopy__(self, memodict):
| obj = Node(connector=self.connector, negated=self.negated)
obj.__class__ = self.__class__
obj.children = copy.deepcopy(self.children, memodict)
obj.subtree_parents = copy.deepcopy(self.subtree_parents, memodict)
return obj
|
'The size of a node if the number of children it has.'
| def __len__(self):
| return len(self.children)
|
'For truth value testing.'
| def __nonzero__(self):
| return bool(self.children)
|
'Returns True is \'other\' is a direct child of this instance.'
| def __contains__(self, other):
| return (other in self.children)
|
'Adds a new node to the tree. If the conn_type is the same as the root\'s
current connector type, the node is added to the first level.
Otherwise, the whole tree is pushed down one level and a new root
connector is created, connecting the existing tree and the new node.'
| def add(self, node, conn_type):
| if ((node in self.children) and (conn_type == self.connector)):
return
if (len(self.children) < 2):
self.connector = conn_type
if (self.connector == conn_type):
if (isinstance(node, Node) and ((node.connector == conn_type) or (len(node) == 1))):
self.children.extend(node.... |
'Negate the sense of the root connector. This reorganises the children
so that the current node has a single child: a negated node containing
all the previous children. This slightly odd construction makes adding
new children behave more intuitively.
Interpreting the meaning of this negate is up to client code. This
me... | def negate(self):
| self.children = [self._new_instance(self.children, self.connector, (not self.negated))]
self.connector = self.default
|
'Sets up internal state so that new nodes are added to a subtree of the
current node. The conn_type specifies how the sub-tree is joined to the
existing children.'
| def start_subtree(self, conn_type):
| if (len(self.children) == 1):
self.connector = conn_type
elif (self.connector != conn_type):
self.children = [self._new_instance(self.children, self.connector, self.negated)]
self.connector = conn_type
self.negated = False
self.subtree_parents.append(self.__class__(self.child... |
'Closes off the most recently unmatched start_subtree() call.
This puts the current state into a node of the parent tree and returns
the current instances state to be the parent.'
| def end_subtree(self):
| obj = self.subtree_parents.pop()
node = self.__class__(self.children, self.connector)
self.connector = obj.connector
self.negated = obj.negated
self.children = obj.children
self.children.append(node)
|
'Lexically analyze `text`.
Yields pairs (`name`, `tokentext`).'
| def lex(self, text):
| end = len(text)
state = self.state
regexes = self.regexes
toks = self.toks
start = 0
while (start < end):
for match in regexes[state].finditer(text, start):
name = match.lastgroup
tok = toks[name]
toktext = match.group(name)
start += len(to... |
'Must be implemented by subclasses to initialise the wrapped object.'
| def _setup(self):
| raise NotImplementedError
|
'Pass in a callable that returns the object to be wrapped.
If copies are made of the resulting SimpleLazyObject, which can happen
in various circumstances within Django, then you must ensure that the
callable can be safely run more than once and will return the same
value.'
| def __init__(self, func):
| self.__dict__['_setupfunc'] = func
super(SimpleLazyObject, self).__init__()
|
'Constructor for JSONEncoder, with sensible defaults.
If skipkeys is False, then it is a TypeError to attempt
encoding of keys that are not str, int, long, float or None. If
skipkeys is True, such items are simply skipped.
If ensure_ascii is True, the output is guaranteed to be str
objects with all incoming unicode ch... | def __init__(self, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, sort_keys=False, indent=None, separators=None, encoding='utf-8', default=None):
| self.skipkeys = skipkeys
self.ensure_ascii = ensure_ascii
self.check_circular = check_circular
self.allow_nan = allow_nan
self.sort_keys = sort_keys
self.indent = indent
if (separators is not None):
(self.item_separator, self.key_separator) = separators
if (default is not None):
... |
'Implement this method in a subclass such that it returns
a serializable object for ``o``, or calls the base implementation
(to raise a ``TypeError``).
For example, to support arbitrary iterators, you could
implement default like this::
def default(self, o):
try:
iterable = iter(o)
except TypeError:
pass
else:
return l... | def default(self, o):
| raise TypeError(('%r is not JSON serializable' % (o,)))
|
'Return a JSON string representation of a Python data structure.
>>> JSONEncoder().encode({"foo": ["bar", "baz"]})
\'{"foo": ["bar", "baz"]}\''
| def encode(self, o):
| if isinstance(o, basestring):
if isinstance(o, str):
_encoding = self.encoding
if ((_encoding is not None) and (not (_encoding == 'utf-8'))):
o = o.decode(_encoding)
if self.ensure_ascii:
return encode_basestring_ascii(o)
else:
... |
'Encode the given object and yield each string
representation as available.
For example::
for chunk in JSONEncoder().iterencode(bigobject):
mysocket.write(chunk)'
| def iterencode(self, o, _one_shot=False):
| if self.check_circular:
markers = {}
else:
markers = None
if self.ensure_ascii:
_encoder = encode_basestring_ascii
else:
_encoder = encode_basestring
if (self.encoding != 'utf-8'):
def _encoder(o, _orig_encoder=_encoder, _encoding=self.encoding):
i... |
'``encoding`` determines the encoding used to interpret any ``str``
objects decoded by this instance (utf-8 by default). It has no
effect when decoding ``unicode`` objects.
Note that currently only encodings that are a superset of ASCII work,
strings of other encodings should be passed in as ``unicode``.
``object_hook... | def __init__(self, encoding=None, object_hook=None, parse_float=None, parse_int=None, parse_constant=None, strict=True):
| self.encoding = encoding
self.object_hook = object_hook
self.parse_float = (parse_float or float)
self.parse_int = (parse_int or int)
self.parse_constant = (parse_constant or _CONSTANTS.__getitem__)
self.strict = strict
self.parse_object = JSONObject
self.parse_array = JSONArray
self... |
'Return the Python representation of ``s`` (a ``str`` or ``unicode``
instance containing a JSON document)'
| def decode(self, s, _w=WHITESPACE.match):
| (obj, end) = self.raw_decode(s, idx=_w(s, 0).end())
end = _w(s, end).end()
if (end != len(s)):
raise ValueError(errmsg('Extra data', s, end, len(s)))
return obj
|
'Decode a JSON document from ``s`` (a ``str`` or ``unicode`` beginning
with a JSON document) and return a 2-tuple of the Python
representation and the index in ``s`` where the document ended.
This can be used to decode a JSON document from a string that may
have extraneous data at the end.'
| def raw_decode(self, s, idx=0):
| try:
(obj, end) = self.scan_once(s, idx)
except StopIteration:
raise ValueError('No JSON object could be decoded')
return (obj, end)
|
'\'a.m.\' or \'p.m.\''
| def a(self):
| if (self.data.hour > 11):
return _('p.m.')
return _('a.m.')
|
'\'AM\' or \'PM\''
| def A(self):
| if (self.data.hour > 11):
return _('PM')
return _('AM')
|
'Swatch Internet time'
| def B(self):
| raise NotImplementedError
|
'Time, in 12-hour hours and minutes, with minutes left off if they\'re
zero.
Examples: \'1\', \'1:30\', \'2:05\', \'2\'
Proprietary extension.'
| def f(self):
| if (self.data.minute == 0):
return self.g()
return (u'%s:%s' % (self.g(), self.i()))
|
'Hour, 12-hour format without leading zeros; i.e. \'1\' to \'12\''
| def g(self):
| if (self.data.hour == 0):
return 12
if (self.data.hour > 12):
return (self.data.hour - 12)
return self.data.hour
|
'Hour, 24-hour format without leading zeros; i.e. \'0\' to \'23\''
| def G(self):
| return self.data.hour
|
'Hour, 12-hour format; i.e. \'01\' to \'12\''
| def h(self):
| return (u'%02d' % self.g())
|
'Hour, 24-hour format; i.e. \'00\' to \'23\''
| def H(self):
| return (u'%02d' % self.G())
|
'Minutes; i.e. \'00\' to \'59\''
| def i(self):
| return (u'%02d' % self.data.minute)
|
'Time, in 12-hour hours, minutes and \'a.m.\'/\'p.m.\', with minutes left off
if they\'re zero and the strings \'midnight\' and \'noon\' if appropriate.
Examples: \'1 a.m.\', \'1:30 p.m.\', \'midnight\', \'noon\', \'12:30 p.m.\'
Proprietary extension.'
| def P(self):
| if ((self.data.minute == 0) and (self.data.hour == 0)):
return _('midnight')
if ((self.data.minute == 0) and (self.data.hour == 12)):
return _('noon')
return (u'%s %s' % (self.f(), self.a()))
|
'Seconds; i.e. \'00\' to \'59\''
| def s(self):
| return (u'%02d' % self.data.second)
|
'Microseconds'
| def u(self):
| return self.data.microsecond
|
'Month, textual, 3 letters, lowercase; e.g. \'jan\''
| def b(self):
| return MONTHS_3[self.data.month]
|
'ISO 8601 Format
Example : \'2008-01-02T10:30:00.000123\''
| def c(self):
| return self.data.isoformat()
|
'Day of the month, 2 digits with leading zeros; i.e. \'01\' to \'31\''
| def d(self):
| return (u'%02d' % self.data.day)
|
'Day of the week, textual, 3 letters; e.g. \'Fri\''
| def D(self):
| return WEEKDAYS_ABBR[self.data.weekday()]
|
'Timezone name if available'
| def e(self):
| try:
if (hasattr(self.data, 'tzinfo') and self.data.tzinfo):
return (self.data.tzinfo.tzname(self.data) or '')
except NotImplementedError:
pass
return ''
|
'Alternative month names as required by some locales. Proprietary extension.'
| def E(self):
| return MONTHS_ALT[self.data.month]
|
'Month, textual, long; e.g. \'January\''
| def F(self):
| return MONTHS[self.data.month]
|
'\'1\' if Daylight Savings Time, \'0\' otherwise.'
| def I(self):
| if (self.timezone and self.timezone.dst(self.data)):
return u'1'
else:
return u'0'
|
'Day of the month without leading zeros; i.e. \'1\' to \'31\''
| def j(self):
| return self.data.day
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.