Code stringlengths 103 85.9k | Summary listlengths 0 94 |
|---|---|
Please provide a description of the function:def _BacktraceFromFramePtr(self, frame_ptr):
# expects frame_ptr to be a gdb.Value
frame_objs = [PyFrameObjectPtr(frame) for frame
in self._IterateChainedList(frame_ptr, 'f_back')]
# We want to output tracebacks in the same format python u... | [
"Assembles and returns what looks exactly like python's backtraces."
] |
Please provide a description of the function:def Kill(self):
try:
if self.is_running:
self.Detach()
if self._Execute('__kill__') == '__kill_ack__':
# acknowledged, let's give it some time to die in peace
time.sleep(0.1)
except (TimeoutError, ProxyError):
logging.de... | [
"Send death pill to Gdb and forcefully kill it if that doesn't work."
] |
Please provide a description of the function:def Version():
output = subprocess.check_output(['gdb', '--version']).split('\n')[0]
# Example output (Arch linux):
# GNU gdb (GDB) 7.7
# Example output (Debian sid):
# GNU gdb (GDB) 7.6.2 (Debian 7.6.2-1)
# Example output (Debian wheezy):
# ... | [
"Gets the version of gdb as a 3-tuple.\n\n The gdb devs seem to think it's a good idea to make --version\n output multiple lines of welcome text instead of just the actual version,\n so we ignore everything it outputs after the first line.\n Returns:\n The installed version of gdb in the form\n ... |
Please provide a description of the function:def _JsonDecodeDict(self, data):
rv = {}
for key, value in data.iteritems():
if isinstance(key, unicode):
key = self._TryStr(key)
if isinstance(value, unicode):
value = self._TryStr(value)
elif isinstance(value, list):
v... | [
"Json object decode hook that automatically converts unicode objects."
] |
Please provide a description of the function:def _Execute(self, funcname, *args, **kwargs):
wait_for_completion = kwargs.get('wait_for_completion', False)
rpc_dict = {'func': funcname, 'args': args}
self._Send(json.dumps(rpc_dict))
timeout = TIMEOUT_FOREVER if wait_for_completion else TIMEOUT_DEFAU... | [
"Send an RPC request to the gdb-internal python.\n\n Blocks for 3 seconds by default and returns any results.\n Args:\n funcname: the name of the function to call.\n *args: the function's arguments.\n **kwargs: Only the key 'wait_for_completion' is inspected, which decides\n whether to w... |
Please provide a description of the function:def _Recv(self, timeout):
buf = ''
# The messiness of this stems from the "duck-typiness" of this function.
# The timeout parameter of poll has different semantics depending on whether
# it's <=0, >0, or None. Yay.
wait_for_line = timeout is TIMEOU... | [
"Receive output from gdb.\n\n This reads gdb's stdout and stderr streams, returns a single line of gdb's\n stdout or rethrows any exceptions thrown from within gdb as well as it can.\n\n Args:\n timeout: floating point number of seconds after which to abort.\n A value of None or TIMEOUT_FOREV... |
Please provide a description of the function:def needsattached(func):
@functools.wraps(func)
def wrap(self, *args, **kwargs):
if not self.attached:
raise PositionError('Not attached to any process.')
return func(self, *args, **kwargs)
return wrap | [
"Decorator to prevent commands from being used when not attached."
] |
Please provide a description of the function:def Reinit(self, pid, auto_symfile_loading=True):
self.ShutDownGdb()
self.__init__(pid, auto_symfile_loading, architecture=self.arch) | [
"Reinitializes the object with a new pid.\n\n Since all modes might need access to this object at any time, this object\n needs to be long-lived. To make this clear in the API, this shorthand is\n supplied.\n Args:\n pid: the pid of the target process\n auto_symfile_loading: whether the symbol... |
Please provide a description of the function:def StartGdb(self):
if self.attached:
raise GdbProcessError('Gdb is already running.')
self._gdb = GdbProxy(arch=self.arch)
self._gdb.Attach(self.position)
if self.auto_symfile_loading:
try:
self.LoadSymbolFile()
except (ProxyE... | [
"Starts gdb and attempts to auto-load symbol file (unless turned off).\n\n Raises:\n GdbProcessError: if gdb is already running\n "
] |
Please provide a description of the function:def InjectString(self, codestring, wait_for_completion=True):
if self.inferior.is_running and self.inferior.gdb.IsAttached():
try:
self.inferior.gdb.InjectString(
self.inferior.position,
codestring,
wait_for_completi... | [
"Try to inject python code into current thread.\n\n Args:\n codestring: Python snippet to execute in inferior. (may contain newlines)\n wait_for_completion: Block until execution of snippet has completed.\n "
] |
Please provide a description of the function:def _write_instance_repr(out, visited, name, pyop_attrdict, address):
'''Shared code for use by old-style and new-style classes:
write a representation to file-like object "out"'''
out.write('<')
out.write(name)
# Write dictionary of instance attributes:... | [] |
Please provide a description of the function:def move_in_stack(move_up):
'''Move up or down the stack (for the py-up/py-down command)'''
frame = Frame.get_selected_python_frame()
while frame:
if move_up:
iter_frame = frame.older()
else:
iter_frame = frame.newer()
... | [] |
Please provide a description of the function:def field(self, name):
'''
Get the gdb.Value for the given field within the PyObject, coping with
some python 2 versus python 3 differences.
Various libpython types are defined using the "PyObject_HEAD" and
"PyObject_VAR_HEAD" macros.... | [] |
Please provide a description of the function:def write_field_repr(self, name, out, visited):
'''
Extract the PyObject* field named "name", and write its representation
to file-like object "out"
'''
field_obj = self.pyop_field(name)
field_obj.write_repr(out, visited) | [] |
Please provide a description of the function:def get_truncated_repr(self, maxlen):
'''
Get a repr-like string for the data, but truncate it at "maxlen" bytes
(ending the object graph traversal as soon as you do)
'''
out = TruncatedStringIO(maxlen)
try:
self.wr... | [] |
Please provide a description of the function:def proxyval(self, visited):
'''
Scrape a value from the inferior process, and try to represent it
within the gdb process, whilst (hopefully) avoiding crashes when
the remote data is corrupt.
Derived classes will override this.
... | [
"\n Class representing a non-descript PyObject* value in the inferior\n process for when we don't have a custom scraper, intended to have\n a sane repr().\n "
] |
Please provide a description of the function:def write_repr(self, out, visited):
'''
Write a string representation of the value scraped from the inferior
process to "out", a file-like object.
'''
# Default implementation: generate a proxy value and write its repr
# Howeve... | [] |
Please provide a description of the function:def subclass_from_type(cls, t):
'''
Given a PyTypeObjectPtr instance wrapping a gdb.Value that's a
(PyTypeObject*), determine the corresponding subclass of PyObjectPtr
to use
Ideally, we would look up the symbols for the global types,... | [] |
Please provide a description of the function:def from_pyobject_ptr(cls, gdbval):
'''
Try to locate the appropriate derived class dynamically, and cast
the pointer accordingly.
'''
try:
p = PyObjectPtr(gdbval)
cls = cls.subclass_from_type(p.type())
... | [] |
Please provide a description of the function:def get_attr_dict(self):
'''
Get the PyDictObject ptr representing the attribute dictionary
(or None if there's a problem)
'''
try:
typeobj = self.type()
dictoffset = int_from_int(typeobj.field('tp_dictoffset'))... | [] |
Please provide a description of the function:def proxyval(self, visited):
'''
Support for new-style classes.
Currently we just locate the dictionary using a transliteration to
python of _PyObject_GetDictPtr, ignoring descriptors
'''
# Guard against infinite loops:
... | [] |
Please provide a description of the function:def addr2line(self, addrq):
'''
Get the line number for a given bytecode offset
Analogous to PyCode_Addr2Line; translated from pseudocode in
Objects/lnotab_notes.txt
'''
co_lnotab = self.pyop_field('co_lnotab').proxyval(set())... | [] |
Please provide a description of the function:def iteritems(self):
'''
Yields a sequence of (PyObjectPtr key, PyObjectPtr value) pairs,
analagous to dict.iteritems()
'''
for i in safe_range(self.field('ma_mask') + 1):
ep = self.field('ma_table') + i
pyop_va... | [] |
Please provide a description of the function:def proxyval(self, visited):
'''
Python's Include/longobjrep.h has this declaration:
struct _longobject {
PyObject_VAR_HEAD
digit ob_digit[1];
};
with this description:
The absolute valu... | [] |
Please provide a description of the function:def iter_locals(self):
'''
Yield a sequence of (name,value) pairs of PyObjectPtr instances, for
the local variables of this frame
'''
if self.is_optimized_out():
return
f_localsplus = self.field('f_localsplus')
... | [] |
Please provide a description of the function:def get_var_by_name(self, name):
'''
Look for the named local variable, returning a (PyObjectPtr, scope) pair
where scope is a string 'local', 'global', 'builtin'
If not found, return (None, None)
'''
for pyop_name, pyop_value... | [] |
Please provide a description of the function:def current_line(self):
'''Get the text of the current source line as a string, with a trailing
newline character'''
if self.is_optimized_out():
return '(frame information optimized out)'
with open(self.filename(), 'r') as f:
... | [] |
Please provide a description of the function:def select(self):
'''If supported, select this frame and return True; return False if unsupported
Not all builds have a gdb.Frame.select method; seems to be present on Fedora 12
onwards, but absent on Ubuntu buildbot'''
if not hasattr(self._g... | [] |
Please provide a description of the function:def get_index(self):
'''Calculate index of frame, starting at 0 for the newest frame within
this thread'''
index = 0
# Go down until you reach the newest frame:
iter_frame = self
while iter_frame.newer():
index += 1... | [] |
Please provide a description of the function:def is_evalframeex(self):
'''Is this a PyEval_EvalFrameEx frame?'''
if self._gdbframe.name() == 'PyEval_EvalFrameEx':
'''
I believe we also need to filter on the inline
struct frame_id.inline_depth, only regarding frames wi... | [] |
Please provide a description of the function:def get_selected_python_frame(cls):
'''Try to obtain the Frame for the python code in the selected frame,
or None'''
frame = cls.get_selected_frame()
while frame:
if frame.is_evalframeex():
return frame
... | [] |
Please provide a description of the function:def ListCommands(self):
print 'Available commands:'
commands = dict(self.commands)
for plugin in self.plugins:
commands.update(plugin.commands)
for com in sorted(commands):
if not com.startswith('_'):
self.PrintHelpTextLine(com, comma... | [
"Print a list of currently available commands and their descriptions."
] |
Please provide a description of the function:def StatusLine(self):
pid = self.inferior.pid
curthread = None
threadnum = 0
if pid:
if not self.inferior.is_running:
logging.warning('Inferior is not running.')
self.Detach()
pid = None
else:
try:
# ... | [
"Generate the colored line indicating plugin status."
] |
Please provide a description of the function:def Attach(self, pid):
if self.inferior.is_running:
answer = raw_input('Already attached to process ' +
str(self.inferior.pid) +
'. Detach? [y]/n ')
if answer and answer != 'y' and answer != 'yes':
... | [
"Attach to the process with the given pid."
] |
Please provide a description of the function:def Detach(self):
for plugin in self.plugins:
plugin.position = None
self.inferior.Reinit(None) | [
"Detach from the inferior (Will exit current mode)."
] |
Please provide a description of the function:def interact(self, banner=None):
sys.ps1 = getattr(sys, 'ps1', '>>> ')
sys.ps2 = getattr(sys, 'ps2', '... ')
if banner is None:
print ('Pyringe (Python %s.%s.%s) on %s\n%s' %
(sys.version_info.major, sys.version_info.minor,
s... | [
"Closely emulate the interactive Python console.\n\n This method overwrites its superclass' method to specify a different help\n text and to enable proper handling of the debugger status line.\n\n Args:\n banner: Text to be displayed on interpreter startup.\n "
] |
Please provide a description of the function:def StartGdb(self):
if self.inferior.is_running:
self.inferior.ShutDownGdb()
program_arg = 'program %d ' % self.inferior.pid
else:
program_arg = ''
os.system('gdb ' + program_arg + ' '.join(self.gdb_args))
reset_position = raw_input('Re... | [
"Hands control over to a new gdb process."
] |
Please provide a description of the function:def __get_node(self, word):
node = self.root
for c in word:
try:
node = node.children[c]
except KeyError:
return None
return node | [
"\n\t\tPrivate function retrieving a final node of trie\n\t\tfor given word\n\n\t\tReturns node or None, if the trie doesn't contain the word.\n\t\t"
] |
Please provide a description of the function:def get(self, word, default=nil):
node = self.__get_node(word)
output = nil
if node:
output = node.output
if output is nil:
if default is nil:
raise KeyError("no key '%s'" % word)
else:
return default
else:
return output | [
"\n\t\tRetrieves output value associated with word.\n\n\t\tIf there is no word returns default value,\n\t\tand if default is not given rises KeyError.\n\t\t"
] |
Please provide a description of the function:def items(self):
L = []
def aux(node, s):
s = s + node.char
if node.output is not nil:
L.append((s, node.output))
for child in node.children.values():
if child is not node:
aux(child, s)
aux(self.root, '')
return iter(L) | [
"\n\t\tGenerator returning all keys and values stored in a trie.\n\t\t"
] |
Please provide a description of the function:def add_word(self, word, value):
if not word:
return
node = self.root
for c in word:
try:
node = node.children[c]
except KeyError:
n = TrieNode(c)
node.children[c] = n
node = n
node.output = value | [
"\n\t\tAdds word and associated value.\n\n\t\tIf word already exists, its value is replaced.\n\t\t"
] |
Please provide a description of the function:def exists(self, word):
node = self.__get_node(word)
if node:
return bool(node.output != nil)
else:
return False | [
"\n\t\tChecks if whole word is present in the trie.\n\t\t"
] |
Please provide a description of the function:def make_automaton(self):
queue = deque()
# 1.
for i in range(256):
c = chr(i)
if c in self.root.children:
node = self.root.children[c]
node.fail = self.root # f(s) = 0
queue.append(node)
else:
self.root.children[c] = self.root
# 2.
w... | [
"\n\t\tConverts trie to Aho-Corasick automaton.\n\t\t"
] |
Please provide a description of the function:def iter(self, string):
state = self.root
for index, c in enumerate(string):
while c not in state.children:
state = state.fail
state = state.children.get(c, self.root)
tmp = state
output = []
while tmp is not nil:
if tmp.output is not nil:
... | [
"\n\t\tGenerator performs Aho-Corasick search string algorithm, yielding\n\t\ttuples containing two values:\n\t\t- position in string\n\t\t- outputs associated with matched strings\n\t\t"
] |
Please provide a description of the function:def iter_long(self, string):
state = self.root
last = None
index = 0
while index < len(string):
c = string[index]
if c in state.children:
state = state.children[c]
if state.output is not nil:
# save the last node on the path
last = (sta... | [
"\n\t\tGenerator performs a modified Aho-Corasick search string algorithm,\n\t\twhich maches only the longest word.\n\n\t\t"
] |
Please provide a description of the function:def find_all(self, string, callback):
for index, output in self.iter(string):
callback(index, output) | [
"\n\t\tWrapper on iter method, callback gets an iterator result\n\t\t"
] |
Please provide a description of the function:def get_long_description():
import codecs
with codecs.open('README.rst', encoding='UTF-8') as f:
readme = [line for line in f if not line.startswith('.. contents::')]
return ''.join(readme) | [
"\n Strip the content index from the long description.\n "
] |
Please provide a description of the function:def _add_play_button(self, image_url, image_path):
try:
from PIL import Image
from tempfile import NamedTemporaryFile
import urllib
try:
urlretrieve = urllib.request.urlretrieve
exce... | [
"Try to add a play button to the screenshot."
] |
Please provide a description of the function:def process(self):
self.modules.sort(key=lambda x: x.priority)
for module in self.modules:
transforms = module.transform(self.data)
transforms.sort(key=lambda x: x.linenum, reverse=True)
for transform in transfor... | [
"\n This method handles the actual processing of Modules and Transforms\n "
] |
Please provide a description of the function:def _irregular(singular, plural):
def caseinsensitive(string):
return ''.join('[' + char + char.upper() + ']' for char in string)
if singular[0].upper() == plural[0].upper():
PLURALS.insert(0, (
r"(?i)({}){}$".format(singular[0], sin... | [
"\n A convenience function to add appropriate rules to plurals and singular\n for irregular words.\n\n :param singular: irregular word in singular form\n :param plural: irregular word in plural form\n "
] |
Please provide a description of the function:def camelize(string, uppercase_first_letter=True):
if uppercase_first_letter:
return re.sub(r"(?:^|_)(.)", lambda m: m.group(1).upper(), string)
else:
return string[0].lower() + camelize(string)[1:] | [
"\n Convert strings to CamelCase.\n\n Examples::\n\n >>> camelize(\"device_type\")\n \"DeviceType\"\n >>> camelize(\"device_type\", False)\n \"deviceType\"\n\n :func:`camelize` can be thought of as a inverse of :func:`underscore`,\n although there are some cases where that do... |
Please provide a description of the function:def humanize(word):
word = re.sub(r"_id$", "", word)
word = word.replace('_', ' ')
word = re.sub(r"(?i)([a-z\d]*)", lambda m: m.group(1).lower(), word)
word = re.sub(r"^\w", lambda m: m.group(0).upper(), word)
return word | [
"\n Capitalize the first word and turn underscores into spaces and strip a\n trailing ``\"_id\"``, if any. Like :func:`titleize`, this is meant for\n creating pretty output.\n\n Examples::\n\n >>> humanize(\"employee_salary\")\n \"Employee salary\"\n >>> humanize(\"author_id\")\n ... |
Please provide a description of the function:def parameterize(string, separator='-'):
string = transliterate(string)
# Turn unwanted chars into the separator
string = re.sub(r"(?i)[^a-z0-9\-_]+", separator, string)
if separator:
re_sep = re.escape(separator)
# No more than one of th... | [
"\n Replace special characters in a string so that it may be used as part of a\n 'pretty' URL.\n\n Example::\n\n >>> parameterize(u\"Donald E. Knuth\")\n 'donald-e-knuth'\n\n "
] |
Please provide a description of the function:def pluralize(word):
if not word or word.lower() in UNCOUNTABLES:
return word
else:
for rule, replacement in PLURALS:
if re.search(rule, word):
return re.sub(rule, replacement, word)
return word | [
"\n Return the plural form of a word.\n\n Examples::\n\n >>> pluralize(\"post\")\n \"posts\"\n >>> pluralize(\"octopus\")\n \"octopi\"\n >>> pluralize(\"sheep\")\n \"sheep\"\n >>> pluralize(\"CamelOctopus\")\n \"CamelOctopi\"\n\n "
] |
Please provide a description of the function:def singularize(word):
for inflection in UNCOUNTABLES:
if re.search(r'(?i)\b(%s)\Z' % inflection, word):
return word
for rule, replacement in SINGULARS:
if re.search(rule, word):
return re.sub(rule, replacement, word)
... | [
"\n Return the singular form of a word, the reverse of :func:`pluralize`.\n\n Examples::\n\n >>> singularize(\"posts\")\n \"post\"\n >>> singularize(\"octopi\")\n \"octopus\"\n >>> singularize(\"sheep\")\n \"sheep\"\n >>> singularize(\"word\")\n \"word\"... |
Please provide a description of the function:def titleize(word):
return re.sub(
r"\b('?[a-z])",
lambda match: match.group(1).capitalize(),
humanize(underscore(word))
) | [
"\n Capitalize all the words and replace some characters in the string to\n create a nicer looking title. :func:`titleize` is meant for creating pretty\n output.\n\n Examples::\n\n >>> titleize(\"man from the boondocks\")\n \"Man From The Boondocks\"\n >>> titleize(\"x-men: the last stand... |
Please provide a description of the function:def underscore(word):
word = re.sub(r"([A-Z]+)([A-Z][a-z])", r'\1_\2', word)
word = re.sub(r"([a-z\d])([A-Z])", r'\1_\2', word)
word = word.replace("-", "_")
return word.lower() | [
"\n Make an underscored, lowercase form from the expression in the string.\n\n Example::\n\n >>> underscore(\"DeviceType\")\n \"device_type\"\n\n As a rule of thumb you can think of :func:`underscore` as the inverse of\n :func:`camelize`, though there are cases where that does not hold::\n... |
Please provide a description of the function:def print_all(msg):
gc.collect()
logger.debug(msg)
vips_lib.vips_object_print_all()
logger.debug() | [
"Print all objects.\n\n Print a table of all active libvips objects. Handy for debugging.\n\n "
] |
Please provide a description of the function:def get_typeof(self, name):
# logger.debug('VipsObject.get_typeof: self = %s, name = %s',
# str(self), name)
pspec = self._get_pspec(name)
if pspec is None:
# need to clear any error, this is horrible
... | [
"Get the GType of a GObject property.\n\n This function returns 0 if the property does not exist.\n\n "
] |
Please provide a description of the function:def get_blurb(self, name):
c_str = gobject_lib.g_param_spec_get_blurb(self._get_pspec(name))
return _to_string(c_str) | [
"Get the blurb for a GObject property."
] |
Please provide a description of the function:def get(self, name):
logger.debug('VipsObject.get: name = %s', name)
pspec = self._get_pspec(name)
if pspec is None:
raise Error('Property not found.')
gtype = pspec.value_type
gv = pyvips.GValue()
gv.se... | [
"Get a GObject property.\n\n The value of the property is converted to a Python value.\n\n "
] |
Please provide a description of the function:def set(self, name, value):
logger.debug('VipsObject.set: name = %s, value = %s', name, value)
gtype = self.get_typeof(name)
gv = pyvips.GValue()
gv.set_type(gtype)
gv.set(value)
go = ffi.cast('GObject *', self.poin... | [
"Set a GObject property.\n\n The value is converted to the property type, if possible.\n\n "
] |
Please provide a description of the function:def set_string(self, string_options):
vo = ffi.cast('VipsObject *', self.pointer)
cstr = _to_bytes(string_options)
result = vips_lib.vips_object_set_from_string(vo, cstr)
return result == 0 | [
"Set a series of properties using a string.\n\n For example::\n\n 'fred=12, tile'\n '[fred=12]'\n\n "
] |
Please provide a description of the function:def get_description(self):
vo = ffi.cast('VipsObject *', self.pointer)
return _to_string(vips_lib.vips_object_get_description(vo)) | [
"Get the description of a GObject."
] |
Please provide a description of the function:def cdefs(features):
code = ''
# apparently the safest way to do this
is_64bits = sys.maxsize > 2 ** 32
# GType is an int the size of a pointer ... I don't think we can just use
# size_t, sadly
if is_64bits:
code += '''
typ... | [
"Return the C API declarations for libvips.\n\n features is a dict with the features we want. Some features were only\n added in later libvips, for example, and some need to be disabled in\n some FFI modes.\n\n "
] |
Please provide a description of the function:def call(operation_name, *args, **kwargs):
logger.debug('VipsOperation.call: operation_name = %s', operation_name)
# logger.debug('VipsOperation.call: args = %s, kwargs =%s',
# args, kwargs)
# pull out the special strin... | [
"Call a libvips operation.\n\n Use this method to call any libvips operation. For example::\n\n black_image = pyvips.Operation.call('black', 10, 10)\n\n See the Introduction for notes on how this works.\n\n "
] |
Please provide a description of the function:def generate_docstring(operation_name):
if operation_name in Operation._docstring_cache:
return Operation._docstring_cache[operation_name]
op = Operation.new_from_name(operation_name)
if (op.get_flags() & _OPERATION_DEPRECATED) ... | [
"Make a google-style docstring.\n\n This is used to generate help() output.\n\n "
] |
Please provide a description of the function:def generate_sphinx_all():
# generate list of all nicknames we can generate docstrings for
all_nicknames = []
def add_nickname(gtype, a, b):
nickname = nickname_find(gtype)
try:
Operation.generate_sp... | [
"Generate sphinx documentation.\n\n This generates a .rst file for all auto-generated image methods. Use it\n to regenerate the docs with something like::\n\n $ python -c \\\n\"import pyvips; pyvips.Operation.generate_sphinx_all()\" > x\n\n And copy-paste the file contents into doc/v... |
Please provide a description of the function:def new(image):
pointer = vips_lib.vips_region_new(image.pointer)
if pointer == ffi.NULL:
raise Error('unable to make region')
return pyvips.Region(pointer) | [
"Make a region on an image.\n\n Returns:\n A new :class:`.Region`.\n\n Raises:\n :class:`.Error`\n\n "
] |
Please provide a description of the function:def fetch(self, x, y, w, h):
if not at_least_libvips(8, 8):
raise Error('libvips too old')
psize = ffi.new('size_t *')
pointer = vips_lib.vips_region_fetch(self.pointer, x, y, w, h, psize)
if pointer == ffi.NULL:
... | [
"Fill a region with pixel data.\n\n Pixels are filled with data!\n\n Returns:\n Pixel data.\n\n Raises:\n :class:`.Error`\n\n "
] |
Please provide a description of the function:def gtype_to_python(gtype):
fundamental = gobject_lib.g_type_fundamental(gtype)
if gtype in GValue._gtype_to_python:
return GValue._gtype_to_python[gtype]
if fundamental in GValue._gtype_to_python:
return GValue._gty... | [
"Map a gtype to the name of the Python type we use to represent it.\n\n "
] |
Please provide a description of the function:def to_enum(gtype, value):
if isinstance(value, basestring if _is_PY2 else str):
enum_value = vips_lib.vips_enum_from_nick(b'pyvips', gtype,
_to_bytes(value))
if enum_value < 0:
... | [
"Turn a string into an enum value ready to be passed into libvips.\n\n "
] |
Please provide a description of the function:def from_enum(gtype, enum_value):
pointer = vips_lib.vips_enum_nick(gtype, enum_value)
if pointer == ffi.NULL:
raise Error('value not in enum')
return _to_string(pointer) | [
"Turn an int back into an enum string.\n\n "
] |
Please provide a description of the function:def set(self, value):
# logger.debug('GValue.set: value = %s', value)
gtype = self.gvalue.g_type
fundamental = gobject_lib.g_type_fundamental(gtype)
if gtype == GValue.gbool_type:
gobject_lib.g_value_set_boolean(self.gv... | [
"Set a GValue.\n\n The value is converted to the type of the GValue, if possible, and\n assigned.\n\n "
] |
Please provide a description of the function:def get(self):
# logger.debug('GValue.get: self = %s', self)
gtype = self.gvalue.g_type
fundamental = gobject_lib.g_type_fundamental(gtype)
result = None
if gtype == GValue.gbool_type:
result = bool(gobject_lib... | [
"Get the contents of a GValue.\n\n The contents of the GValue are read out as a Python type.\n "
] |
Please provide a description of the function:def to_polar(image):
# xy image, origin in the centre, scaled to fit image to a circle
xy = pyvips.Image.xyz(image.width, image.height)
xy -= [image.width / 2.0, image.height / 2.0]
scale = min(image.width, image.height) / float(image.width)
xy *= 2.... | [
"Transform image coordinates to polar.\n\n The image is transformed so that it is wrapped around a point in the\n centre. Vertical straight lines become circles or segments of circles,\n horizontal straight lines become radial spokes.\n "
] |
Please provide a description of the function:def to_rectangular(image):
# xy image, vertical scaled to 360 degrees
xy = pyvips.Image.xyz(image.width, image.height)
xy *= [1, 360.0 / image.height]
index = xy.rect()
# scale to image rect
scale = min(image.width, image.height) / float(image.... | [
"Transform image coordinates to rectangular.\n\n The image is transformed so that it is unwrapped from a point in the\n centre. Circles or segments of circles become vertical straight lines,\n radial lines become horizontal lines.\n "
] |
Please provide a description of the function:def _to_string(x):
if x == ffi.NULL:
x = 'NULL'
else:
x = ffi.string(x)
if isinstance(x, byte_type):
x = x.decode('utf-8')
return x | [
"Convert to a unicode string.\n\n If x is a byte string, assume it is utf-8 and decode to a Python unicode\n string. You must call this on text strings you get back from libvips.\n\n "
] |
Please provide a description of the function:def new(name):
# logger.debug('VipsInterpolate.new: name = %s', name)
vi = vips_lib.vips_interpolate_new(_to_bytes(name))
if vi == ffi.NULL:
raise Error('no such interpolator {0}'.format(name))
return Interpolate(vi) | [
"Make a new interpolator by name.\n\n Make a new interpolator from the libvips class nickname. For example::\n\n inter = pyvips.Interpolator.new('bicubic')\n\n You can get a list of all supported interpolators from the command-line\n with::\n\n $ vips -l interpolate\n\n ... |
Please provide a description of the function:def _run_cmplx(fn, image):
original_format = image.format
if image.format != 'complex' and image.format != 'dpcomplex':
if image.bands % 2 != 0:
raise Error('not an even number of bands')
if image.format != 'float' and image.format ... | [
"Run a complex function on a non-complex image.\n\n The image needs to be complex, or have an even number of bands. The input\n can be int, the output is always float or double.\n "
] |
Please provide a description of the function:def get_suffixes():
names = []
if at_least_libvips(8, 8):
array = vips_lib.vips_foreign_get_suffixes()
i = 0
while array[i] != ffi.NULL:
name = _to_string(array[i])
if name not in names:
names.app... | [
"Get a list of all the filename suffixes supported by libvips.\n\n Returns:\n [string]\n\n "
] |
Please provide a description of the function:def at_least_libvips(x, y):
major = version(0)
minor = version(1)
return major > x or (major == x and minor >= y) | [
"Is this at least libvips x.y?"
] |
Please provide a description of the function:def type_map(gtype, fn):
cb = ffi.callback('VipsTypeMap2Fn', fn)
return vips_lib.vips_type_map(gtype, cb, ffi.NULL, ffi.NULL) | [
"Map fn over all child types of gtype."
] |
Please provide a description of the function:def values_for_enum(gtype):
g_type_class = gobject_lib.g_type_class_ref(gtype)
g_enum_class = ffi.cast('GEnumClass *', g_type_class)
values = []
# -1 since we always have a "last" member.
for i in range(0, g_enum_class.n_values - 1):
value... | [
"Get all values for a enum (gtype)."
] |
Please provide a description of the function:def main():
formatter = ColoredFormatter(log_colors={'TRACE': 'yellow'})
handler = logging.StreamHandler()
handler.setFormatter(formatter)
logger = logging.getLogger('example')
logger.addHandler(handler)
logger.setLevel('TRACE')
logger.log... | [
"Create and use a logger."
] |
Please provide a description of the function:def basicConfig(**kwargs):
logging.basicConfig(**kwargs)
logging._acquireLock()
try:
stream = logging.root.handlers[0]
stream.setFormatter(
ColoredFormatter(
fmt=kwargs.get('format', BASIC_FORMAT),
... | [
"Call ``logging.basicConfig`` and override the formatter it creates."
] |
Please provide a description of the function:def ensure_configured(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
if len(logging.root.handlers) == 0:
basicConfig()
return func(*args, **kwargs)
return wrapper | [
"Modify a function to call ``basicConfig`` first if no handlers exist."
] |
Please provide a description of the function:def color(self, log_colors, level_name):
if not self.stream.isatty():
log_colors = {}
return ColoredFormatter.color(self, log_colors, level_name) | [
"Only returns colors if STDOUT is a TTY."
] |
Please provide a description of the function:def setup_logger():
formatter = ColoredFormatter(
"%(log_color)s%(levelname)-8s%(reset)s %(blue)s%(message)s",
datefmt=None,
reset=True,
log_colors={
'DEBUG': 'cyan',
'INFO': 'green',
'WARNIN... | [
"Return a logger with a default ColoredFormatter."
] |
Please provide a description of the function:def main():
logger = setup_logger()
logger.debug('a debug message')
logger.info('an info message')
logger.warning('a warning message')
logger.error('an error message')
logger.critical('a critical message') | [
"Create and use a logger."
] |
Please provide a description of the function:def _stub_task(self, description, tags=None, **kw):
# If whitespace is not removed here, TW will do it when we pass the
# task to it.
task = {"description": description.strip()}
# Allow passing "tags" in as part of kw.
if 't... | [
" Given a description, stub out a task dict. "
] |
Please provide a description of the function:def _extract_annotations_from_task(self, task):
annotations = list()
if 'annotations' in task:
existing_annotations = task.pop('annotations')
for v in existing_annotations:
if isinstance(v, dict):
... | [
" Removes annotations from a task and returns a list of annotations\n "
] |
Please provide a description of the function:def task_add(self, description, tags=None, **kw):
task = self._stub_task(description, tags, **kw)
task['status'] = Status.PENDING
# TODO -- check only valid keywords
if not 'entry' in task:
task['entry'] = str(int(time... | [
" Add a new task.\n\n Takes any of the keywords allowed by taskwarrior like proj or prior.\n "
] |
Please provide a description of the function:def task_done(self, **kw):
def validate(task):
if not Status.is_pending(task['status']):
raise ValueError("Task is not pending.")
return self._task_change_status(Status.COMPLETED, validate, **kw) | [
"\n Marks a pending task as done, optionally specifying a completion\n date with the 'end' argument.\n "
] |
Please provide a description of the function:def task_delete(self, **kw):
def validate(task):
if task['status'] == Status.DELETED:
raise ValueError("Task is already deleted.")
return self._task_change_status(Status.DELETED, validate, **kw) | [
"\n Marks a task as deleted, optionally specifying a completion\n date with the 'end' argument.\n "
] |
Please provide a description of the function:def _execute(self, *args):
command = (
[
'task',
'rc:%s' % self.config_filename,
]
+ self.get_configuration_override_args()
+ [six.text_type(arg) for arg in args]
)
... | [
" Execute a given taskwarrior command with arguments\n\n Returns a 2-tuple of stdout and stderr (respectively).\n\n "
] |
Please provide a description of the function:def _stub_task(self, description, tags=None, **kw):
# If whitespace is not removed here, TW will do it when we pass the
# task to it.
task = {"description": description.strip()}
# Allow passing "tags" in as part of kw.
if 't... | [
" Given a description, stub out a task dict. "
] |
Please provide a description of the function:def load_tasks(self, command='all'):
results = dict(
(db, self._get_task_objects('status:%s' % db, 'export'))
for db in Command.files(command)
)
# 'waiting' tasks are returned separately from 'pending' tasks
... | [
" Returns a dictionary of tasks for a list of command."
] |
Please provide a description of the function:def filter_tasks(self, filter_dict):
query_args = taskw.utils.encode_query(filter_dict, self.get_version())
return self._get_task_objects(
'export',
*query_args
) | [
" Return a filtered list of tasks from taskwarrior.\n\n Filter dict should be a dictionary mapping filter constraints\n with their values. For example, to return only pending tasks,\n you could use::\n\n {'status': 'pending'}\n\n Or, to return tasks that have the word \"Abjad... |
Please provide a description of the function:def task_add(self, description, tags=None, **kw):
task = self._stub_task(description, tags, **kw)
# Check if there are annotations, if so remove them from the
# task and add them after we've added the task.
annotations = self._extrac... | [
" Add a new task.\n\n Takes any of the keywords allowed by taskwarrior like proj or prior.\n "
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.