id
int32 0
252k
| repo
stringlengths 7
55
| path
stringlengths 4
127
| func_name
stringlengths 1
88
| original_string
stringlengths 75
19.8k
| language
stringclasses 1
value | code
stringlengths 75
19.8k
| code_tokens
list | docstring
stringlengths 3
17.3k
| docstring_tokens
list | sha
stringlengths 40
40
| url
stringlengths 87
242
|
|---|---|---|---|---|---|---|---|---|---|---|---|
10,700
|
google/pyringe
|
pyringe/payload/libpython.py
|
Frame.is_evalframeex
|
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 with
an inline depth of 0 as actually being this function
So we reject those with type gdb.INLINE_FRAME
'''
if self._gdbframe.type() == gdb.NORMAL_FRAME:
# We have a PyEval_EvalFrameEx frame:
return True
return False
|
python
|
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 with
an inline depth of 0 as actually being this function
So we reject those with type gdb.INLINE_FRAME
'''
if self._gdbframe.type() == gdb.NORMAL_FRAME:
# We have a PyEval_EvalFrameEx frame:
return True
return False
|
[
"def",
"is_evalframeex",
"(",
"self",
")",
":",
"if",
"self",
".",
"_gdbframe",
".",
"name",
"(",
")",
"==",
"'PyEval_EvalFrameEx'",
":",
"'''\n I believe we also need to filter on the inline\n struct frame_id.inline_depth, only regarding frames with\n an inline depth of 0 as actually being this function\n\n So we reject those with type gdb.INLINE_FRAME\n '''",
"if",
"self",
".",
"_gdbframe",
".",
"type",
"(",
")",
"==",
"gdb",
".",
"NORMAL_FRAME",
":",
"# We have a PyEval_EvalFrameEx frame:",
"return",
"True",
"return",
"False"
] |
Is this a PyEval_EvalFrameEx frame?
|
[
"Is",
"this",
"a",
"PyEval_EvalFrameEx",
"frame?"
] |
76dff5d1ac29cd5e7bf32677654a83291a15ad8a
|
https://github.com/google/pyringe/blob/76dff5d1ac29cd5e7bf32677654a83291a15ad8a/pyringe/payload/libpython.py#L1196-L1210
|
10,701
|
google/pyringe
|
pyringe/payload/libpython.py
|
Frame.get_selected_python_frame
|
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
frame = frame.older()
# Not found:
return None
|
python
|
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
frame = frame.older()
# Not found:
return None
|
[
"def",
"get_selected_python_frame",
"(",
"cls",
")",
":",
"frame",
"=",
"cls",
".",
"get_selected_frame",
"(",
")",
"while",
"frame",
":",
"if",
"frame",
".",
"is_evalframeex",
"(",
")",
":",
"return",
"frame",
"frame",
"=",
"frame",
".",
"older",
"(",
")",
"# Not found:",
"return",
"None"
] |
Try to obtain the Frame for the python code in the selected frame,
or None
|
[
"Try",
"to",
"obtain",
"the",
"Frame",
"for",
"the",
"python",
"code",
"in",
"the",
"selected",
"frame",
"or",
"None"
] |
76dff5d1ac29cd5e7bf32677654a83291a15ad8a
|
https://github.com/google/pyringe/blob/76dff5d1ac29cd5e7bf32677654a83291a15ad8a/pyringe/payload/libpython.py#L1240-L1251
|
10,702
|
google/pyringe
|
pyringe/repl.py
|
DebuggingConsole.ListCommands
|
def ListCommands(self):
"""Print a list of currently available commands and their descriptions."""
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, commands[com])
|
python
|
def ListCommands(self):
"""Print a list of currently available commands and their descriptions."""
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, commands[com])
|
[
"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",
",",
"commands",
"[",
"com",
"]",
")"
] |
Print a list of currently available commands and their descriptions.
|
[
"Print",
"a",
"list",
"of",
"currently",
"available",
"commands",
"and",
"their",
"descriptions",
"."
] |
76dff5d1ac29cd5e7bf32677654a83291a15ad8a
|
https://github.com/google/pyringe/blob/76dff5d1ac29cd5e7bf32677654a83291a15ad8a/pyringe/repl.py#L102-L110
|
10,703
|
google/pyringe
|
pyringe/repl.py
|
DebuggingConsole.StatusLine
|
def StatusLine(self):
"""Generate the colored line indicating plugin status."""
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:
# get a gdb running if it wasn't already.
if not self.inferior.attached:
self.inferior.StartGdb()
curthread = self.inferior.current_thread
threadnum = len(self.inferior.threads)
except (inferior.ProxyError,
inferior.TimeoutError,
inferior.PositionError) as err:
# This is not the kind of thing we want to be held up by
logging.debug('Error while getting information in status line:%s'
% err.message)
pass
status = ('==> pid:[%s] #threads:[%s] current thread:[%s]' %
(pid, threadnum, curthread))
return status
|
python
|
def StatusLine(self):
"""Generate the colored line indicating plugin status."""
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:
# get a gdb running if it wasn't already.
if not self.inferior.attached:
self.inferior.StartGdb()
curthread = self.inferior.current_thread
threadnum = len(self.inferior.threads)
except (inferior.ProxyError,
inferior.TimeoutError,
inferior.PositionError) as err:
# This is not the kind of thing we want to be held up by
logging.debug('Error while getting information in status line:%s'
% err.message)
pass
status = ('==> pid:[%s] #threads:[%s] current thread:[%s]' %
(pid, threadnum, curthread))
return status
|
[
"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",
":",
"# get a gdb running if it wasn't already.",
"if",
"not",
"self",
".",
"inferior",
".",
"attached",
":",
"self",
".",
"inferior",
".",
"StartGdb",
"(",
")",
"curthread",
"=",
"self",
".",
"inferior",
".",
"current_thread",
"threadnum",
"=",
"len",
"(",
"self",
".",
"inferior",
".",
"threads",
")",
"except",
"(",
"inferior",
".",
"ProxyError",
",",
"inferior",
".",
"TimeoutError",
",",
"inferior",
".",
"PositionError",
")",
"as",
"err",
":",
"# This is not the kind of thing we want to be held up by",
"logging",
".",
"debug",
"(",
"'Error while getting information in status line:%s'",
"%",
"err",
".",
"message",
")",
"pass",
"status",
"=",
"(",
"'==> pid:[%s] #threads:[%s] current thread:[%s]'",
"%",
"(",
"pid",
",",
"threadnum",
",",
"curthread",
")",
")",
"return",
"status"
] |
Generate the colored line indicating plugin status.
|
[
"Generate",
"the",
"colored",
"line",
"indicating",
"plugin",
"status",
"."
] |
76dff5d1ac29cd5e7bf32677654a83291a15ad8a
|
https://github.com/google/pyringe/blob/76dff5d1ac29cd5e7bf32677654a83291a15ad8a/pyringe/repl.py#L121-L147
|
10,704
|
google/pyringe
|
pyringe/repl.py
|
DebuggingConsole.Attach
|
def Attach(self, pid):
"""Attach to the process with the given 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':
return None
self.Detach()
# Whatever position we had before will not make any sense now
for plugin in self.plugins:
plugin.position = None
self.inferior.Reinit(pid)
|
python
|
def Attach(self, pid):
"""Attach to the process with the given 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':
return None
self.Detach()
# Whatever position we had before will not make any sense now
for plugin in self.plugins:
plugin.position = None
self.inferior.Reinit(pid)
|
[
"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'",
":",
"return",
"None",
"self",
".",
"Detach",
"(",
")",
"# Whatever position we had before will not make any sense now",
"for",
"plugin",
"in",
"self",
".",
"plugins",
":",
"plugin",
".",
"position",
"=",
"None",
"self",
".",
"inferior",
".",
"Reinit",
"(",
"pid",
")"
] |
Attach to the process with the given pid.
|
[
"Attach",
"to",
"the",
"process",
"with",
"the",
"given",
"pid",
"."
] |
76dff5d1ac29cd5e7bf32677654a83291a15ad8a
|
https://github.com/google/pyringe/blob/76dff5d1ac29cd5e7bf32677654a83291a15ad8a/pyringe/repl.py#L149-L161
|
10,705
|
google/pyringe
|
pyringe/plugins/gdb_shell.py
|
GdbPlugin.StartGdb
|
def StartGdb(self):
"""Hands control over to a new gdb process."""
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('Reset debugger position? [y]/n ')
if not reset_position or reset_position == 'y' or reset_position == 'yes':
self.position = None
|
python
|
def StartGdb(self):
"""Hands control over to a new gdb process."""
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('Reset debugger position? [y]/n ')
if not reset_position or reset_position == 'y' or reset_position == 'yes':
self.position = None
|
[
"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",
"(",
"'Reset debugger position? [y]/n '",
")",
"if",
"not",
"reset_position",
"or",
"reset_position",
"==",
"'y'",
"or",
"reset_position",
"==",
"'yes'",
":",
"self",
".",
"position",
"=",
"None"
] |
Hands control over to a new gdb process.
|
[
"Hands",
"control",
"over",
"to",
"a",
"new",
"gdb",
"process",
"."
] |
76dff5d1ac29cd5e7bf32677654a83291a15ad8a
|
https://github.com/google/pyringe/blob/76dff5d1ac29cd5e7bf32677654a83291a15ad8a/pyringe/plugins/gdb_shell.py#L38-L48
|
10,706
|
WojciechMula/pyahocorasick
|
py/pyahocorasick.py
|
Trie.__get_node
|
def __get_node(self, word):
"""
Private function retrieving a final node of trie
for given word
Returns node or None, if the trie doesn't contain the word.
"""
node = self.root
for c in word:
try:
node = node.children[c]
except KeyError:
return None
return node
|
python
|
def __get_node(self, word):
"""
Private function retrieving a final node of trie
for given word
Returns node or None, if the trie doesn't contain the word.
"""
node = self.root
for c in word:
try:
node = node.children[c]
except KeyError:
return None
return node
|
[
"def",
"__get_node",
"(",
"self",
",",
"word",
")",
":",
"node",
"=",
"self",
".",
"root",
"for",
"c",
"in",
"word",
":",
"try",
":",
"node",
"=",
"node",
".",
"children",
"[",
"c",
"]",
"except",
"KeyError",
":",
"return",
"None",
"return",
"node"
] |
Private function retrieving a final node of trie
for given word
Returns node or None, if the trie doesn't contain the word.
|
[
"Private",
"function",
"retrieving",
"a",
"final",
"node",
"of",
"trie",
"for",
"given",
"word"
] |
53842f783fbe3fa77d53cde1ac251b23c3cbed02
|
https://github.com/WojciechMula/pyahocorasick/blob/53842f783fbe3fa77d53cde1ac251b23c3cbed02/py/pyahocorasick.py#L55-L70
|
10,707
|
WojciechMula/pyahocorasick
|
py/pyahocorasick.py
|
Trie.get
|
def get(self, word, default=nil):
"""
Retrieves output value associated with word.
If there is no word returns default value,
and if default is not given rises KeyError.
"""
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
|
python
|
def get(self, word, default=nil):
"""
Retrieves output value associated with word.
If there is no word returns default value,
and if default is not given rises KeyError.
"""
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
|
[
"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"
] |
Retrieves output value associated with word.
If there is no word returns default value,
and if default is not given rises KeyError.
|
[
"Retrieves",
"output",
"value",
"associated",
"with",
"word",
"."
] |
53842f783fbe3fa77d53cde1ac251b23c3cbed02
|
https://github.com/WojciechMula/pyahocorasick/blob/53842f783fbe3fa77d53cde1ac251b23c3cbed02/py/pyahocorasick.py#L73-L92
|
10,708
|
WojciechMula/pyahocorasick
|
py/pyahocorasick.py
|
Trie.items
|
def items(self):
"""
Generator returning all keys and values stored in a trie.
"""
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)
|
python
|
def items(self):
"""
Generator returning all keys and values stored in a trie.
"""
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)
|
[
"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",
")"
] |
Generator returning all keys and values stored in a trie.
|
[
"Generator",
"returning",
"all",
"keys",
"and",
"values",
"stored",
"in",
"a",
"trie",
"."
] |
53842f783fbe3fa77d53cde1ac251b23c3cbed02
|
https://github.com/WojciechMula/pyahocorasick/blob/53842f783fbe3fa77d53cde1ac251b23c3cbed02/py/pyahocorasick.py#L113-L129
|
10,709
|
WojciechMula/pyahocorasick
|
py/pyahocorasick.py
|
Trie.add_word
|
def add_word(self, word, value):
"""
Adds word and associated value.
If word already exists, its value is replaced.
"""
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
|
python
|
def add_word(self, word, value):
"""
Adds word and associated value.
If word already exists, its value is replaced.
"""
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
|
[
"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"
] |
Adds word and associated value.
If word already exists, its value is replaced.
|
[
"Adds",
"word",
"and",
"associated",
"value",
"."
] |
53842f783fbe3fa77d53cde1ac251b23c3cbed02
|
https://github.com/WojciechMula/pyahocorasick/blob/53842f783fbe3fa77d53cde1ac251b23c3cbed02/py/pyahocorasick.py#L151-L169
|
10,710
|
WojciechMula/pyahocorasick
|
py/pyahocorasick.py
|
Trie.exists
|
def exists(self, word):
"""
Checks if whole word is present in the trie.
"""
node = self.__get_node(word)
if node:
return bool(node.output != nil)
else:
return False
|
python
|
def exists(self, word):
"""
Checks if whole word is present in the trie.
"""
node = self.__get_node(word)
if node:
return bool(node.output != nil)
else:
return False
|
[
"def",
"exists",
"(",
"self",
",",
"word",
")",
":",
"node",
"=",
"self",
".",
"__get_node",
"(",
"word",
")",
"if",
"node",
":",
"return",
"bool",
"(",
"node",
".",
"output",
"!=",
"nil",
")",
"else",
":",
"return",
"False"
] |
Checks if whole word is present in the trie.
|
[
"Checks",
"if",
"whole",
"word",
"is",
"present",
"in",
"the",
"trie",
"."
] |
53842f783fbe3fa77d53cde1ac251b23c3cbed02
|
https://github.com/WojciechMula/pyahocorasick/blob/53842f783fbe3fa77d53cde1ac251b23c3cbed02/py/pyahocorasick.py#L180-L189
|
10,711
|
WojciechMula/pyahocorasick
|
py/pyahocorasick.py
|
Trie.make_automaton
|
def make_automaton(self):
"""
Converts trie to Aho-Corasick automaton.
"""
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.
while queue:
r = queue.popleft()
for node in r.children.values():
queue.append(node)
state = r.fail
while node.char not in state.children:
state = state.fail
node.fail = state.children.get(node.char, self.root)
|
python
|
def make_automaton(self):
"""
Converts trie to Aho-Corasick automaton.
"""
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.
while queue:
r = queue.popleft()
for node in r.children.values():
queue.append(node)
state = r.fail
while node.char not in state.children:
state = state.fail
node.fail = state.children.get(node.char, self.root)
|
[
"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.",
"while",
"queue",
":",
"r",
"=",
"queue",
".",
"popleft",
"(",
")",
"for",
"node",
"in",
"r",
".",
"children",
".",
"values",
"(",
")",
":",
"queue",
".",
"append",
"(",
"node",
")",
"state",
"=",
"r",
".",
"fail",
"while",
"node",
".",
"char",
"not",
"in",
"state",
".",
"children",
":",
"state",
"=",
"state",
".",
"fail",
"node",
".",
"fail",
"=",
"state",
".",
"children",
".",
"get",
"(",
"node",
".",
"char",
",",
"self",
".",
"root",
")"
] |
Converts trie to Aho-Corasick automaton.
|
[
"Converts",
"trie",
"to",
"Aho",
"-",
"Corasick",
"automaton",
"."
] |
53842f783fbe3fa77d53cde1ac251b23c3cbed02
|
https://github.com/WojciechMula/pyahocorasick/blob/53842f783fbe3fa77d53cde1ac251b23c3cbed02/py/pyahocorasick.py#L200-L226
|
10,712
|
WojciechMula/pyahocorasick
|
py/pyahocorasick.py
|
Trie.iter_long
|
def iter_long(self, string):
"""
Generator performs a modified Aho-Corasick search string algorithm,
which maches only the longest word.
"""
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 = (state.output, index)
index += 1
else:
if last:
# return the saved match
yield last
# and start over, as we don't want overlapped results
# Note: this leads to quadratic complexity in the worst case
index = last[1] + 1
state = self.root
last = None
else:
# if no output, perform classic Aho-Corasick algorithm
while c not in state.children:
state = state.fail
# corner case
if last:
yield last
|
python
|
def iter_long(self, string):
"""
Generator performs a modified Aho-Corasick search string algorithm,
which maches only the longest word.
"""
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 = (state.output, index)
index += 1
else:
if last:
# return the saved match
yield last
# and start over, as we don't want overlapped results
# Note: this leads to quadratic complexity in the worst case
index = last[1] + 1
state = self.root
last = None
else:
# if no output, perform classic Aho-Corasick algorithm
while c not in state.children:
state = state.fail
# corner case
if last:
yield last
|
[
"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",
"=",
"(",
"state",
".",
"output",
",",
"index",
")",
"index",
"+=",
"1",
"else",
":",
"if",
"last",
":",
"# return the saved match",
"yield",
"last",
"# and start over, as we don't want overlapped results",
"# Note: this leads to quadratic complexity in the worst case",
"index",
"=",
"last",
"[",
"1",
"]",
"+",
"1",
"state",
"=",
"self",
".",
"root",
"last",
"=",
"None",
"else",
":",
"# if no output, perform classic Aho-Corasick algorithm",
"while",
"c",
"not",
"in",
"state",
".",
"children",
":",
"state",
"=",
"state",
".",
"fail",
"# corner case",
"if",
"last",
":",
"yield",
"last"
] |
Generator performs a modified Aho-Corasick search string algorithm,
which maches only the longest word.
|
[
"Generator",
"performs",
"a",
"modified",
"Aho",
"-",
"Corasick",
"search",
"string",
"algorithm",
"which",
"maches",
"only",
"the",
"longest",
"word",
"."
] |
53842f783fbe3fa77d53cde1ac251b23c3cbed02
|
https://github.com/WojciechMula/pyahocorasick/blob/53842f783fbe3fa77d53cde1ac251b23c3cbed02/py/pyahocorasick.py#L254-L292
|
10,713
|
WojciechMula/pyahocorasick
|
py/pyahocorasick.py
|
Trie.find_all
|
def find_all(self, string, callback):
"""
Wrapper on iter method, callback gets an iterator result
"""
for index, output in self.iter(string):
callback(index, output)
|
python
|
def find_all(self, string, callback):
"""
Wrapper on iter method, callback gets an iterator result
"""
for index, output in self.iter(string):
callback(index, output)
|
[
"def",
"find_all",
"(",
"self",
",",
"string",
",",
"callback",
")",
":",
"for",
"index",
",",
"output",
"in",
"self",
".",
"iter",
"(",
"string",
")",
":",
"callback",
"(",
"index",
",",
"output",
")"
] |
Wrapper on iter method, callback gets an iterator result
|
[
"Wrapper",
"on",
"iter",
"method",
"callback",
"gets",
"an",
"iterator",
"result"
] |
53842f783fbe3fa77d53cde1ac251b23c3cbed02
|
https://github.com/WojciechMula/pyahocorasick/blob/53842f783fbe3fa77d53cde1ac251b23c3cbed02/py/pyahocorasick.py#L294-L299
|
10,714
|
WojciechMula/pyahocorasick
|
setup.py
|
get_long_description
|
def get_long_description():
"""
Strip the content index from the 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)
|
python
|
def get_long_description():
"""
Strip the content index from the 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)
|
[
"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",
")"
] |
Strip the content index from the long description.
|
[
"Strip",
"the",
"content",
"index",
"from",
"the",
"long",
"description",
"."
] |
53842f783fbe3fa77d53cde1ac251b23c3cbed02
|
https://github.com/WojciechMula/pyahocorasick/blob/53842f783fbe3fa77d53cde1ac251b23c3cbed02/setup.py#L19-L26
|
10,715
|
jreese/markdown-pp
|
MarkdownPP/Modules/YoutubeEmbed.py
|
YoutubeEmbed._add_play_button
|
def _add_play_button(self, image_url, image_path):
"""Try to add a play button to the screenshot."""
try:
from PIL import Image
from tempfile import NamedTemporaryFile
import urllib
try:
urlretrieve = urllib.request.urlretrieve
except ImportError:
urlretrieve = urllib.urlretrieve
# create temporary files for image operations
with NamedTemporaryFile(suffix=".jpg") as screenshot_img:
with NamedTemporaryFile(suffix=".jpg") as button_img:
# grab screenshot and button image
urlretrieve(image_url, screenshot_img.name)
urlretrieve(play_button_url, button_img.name)
# layer the images using PIL and save
with Image.open(screenshot_img.name) as background:
with Image.open(button_img.name) as foreground:
background.paste(foreground, (90, 65), foreground)
background.save(image_path)
except ImportError as e:
print(e)
except Exception as e:
print('Unable to add play button to YouTube '
'screenshot (%s). Using the screenshot '
'on its own instead.' % e)
|
python
|
def _add_play_button(self, image_url, image_path):
"""Try to add a play button to the screenshot."""
try:
from PIL import Image
from tempfile import NamedTemporaryFile
import urllib
try:
urlretrieve = urllib.request.urlretrieve
except ImportError:
urlretrieve = urllib.urlretrieve
# create temporary files for image operations
with NamedTemporaryFile(suffix=".jpg") as screenshot_img:
with NamedTemporaryFile(suffix=".jpg") as button_img:
# grab screenshot and button image
urlretrieve(image_url, screenshot_img.name)
urlretrieve(play_button_url, button_img.name)
# layer the images using PIL and save
with Image.open(screenshot_img.name) as background:
with Image.open(button_img.name) as foreground:
background.paste(foreground, (90, 65), foreground)
background.save(image_path)
except ImportError as e:
print(e)
except Exception as e:
print('Unable to add play button to YouTube '
'screenshot (%s). Using the screenshot '
'on its own instead.' % e)
|
[
"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",
"except",
"ImportError",
":",
"urlretrieve",
"=",
"urllib",
".",
"urlretrieve",
"# create temporary files for image operations",
"with",
"NamedTemporaryFile",
"(",
"suffix",
"=",
"\".jpg\"",
")",
"as",
"screenshot_img",
":",
"with",
"NamedTemporaryFile",
"(",
"suffix",
"=",
"\".jpg\"",
")",
"as",
"button_img",
":",
"# grab screenshot and button image",
"urlretrieve",
"(",
"image_url",
",",
"screenshot_img",
".",
"name",
")",
"urlretrieve",
"(",
"play_button_url",
",",
"button_img",
".",
"name",
")",
"# layer the images using PIL and save",
"with",
"Image",
".",
"open",
"(",
"screenshot_img",
".",
"name",
")",
"as",
"background",
":",
"with",
"Image",
".",
"open",
"(",
"button_img",
".",
"name",
")",
"as",
"foreground",
":",
"background",
".",
"paste",
"(",
"foreground",
",",
"(",
"90",
",",
"65",
")",
",",
"foreground",
")",
"background",
".",
"save",
"(",
"image_path",
")",
"except",
"ImportError",
"as",
"e",
":",
"print",
"(",
"e",
")",
"except",
"Exception",
"as",
"e",
":",
"print",
"(",
"'Unable to add play button to YouTube '",
"'screenshot (%s). Using the screenshot '",
"'on its own instead.'",
"%",
"e",
")"
] |
Try to add a play button to the screenshot.
|
[
"Try",
"to",
"add",
"a",
"play",
"button",
"to",
"the",
"screenshot",
"."
] |
fba644c08176abef4ea5ad36b5b60d32379bddac
|
https://github.com/jreese/markdown-pp/blob/fba644c08176abef4ea5ad36b5b60d32379bddac/MarkdownPP/Modules/YoutubeEmbed.py#L71-L101
|
10,716
|
jreese/markdown-pp
|
MarkdownPP/Processor.py
|
Processor.process
|
def process(self):
"""
This method handles the actual processing of Modules and Transforms
"""
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 transforms:
linenum = transform.linenum
if isinstance(transform.data, basestring):
transform.data = [transform.data]
if transform.oper == "prepend":
self.data[linenum:linenum] = transform.data
elif transform.oper == "append":
self.data[linenum+1:linenum+1] = transform.data
elif transform.oper == "swap":
self.data[linenum:linenum+1] = transform.data
elif transform.oper == "drop":
self.data[linenum:linenum+1] = []
elif transform.oper == "noop":
pass
|
python
|
def process(self):
"""
This method handles the actual processing of Modules and Transforms
"""
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 transforms:
linenum = transform.linenum
if isinstance(transform.data, basestring):
transform.data = [transform.data]
if transform.oper == "prepend":
self.data[linenum:linenum] = transform.data
elif transform.oper == "append":
self.data[linenum+1:linenum+1] = transform.data
elif transform.oper == "swap":
self.data[linenum:linenum+1] = transform.data
elif transform.oper == "drop":
self.data[linenum:linenum+1] = []
elif transform.oper == "noop":
pass
|
[
"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",
"transforms",
":",
"linenum",
"=",
"transform",
".",
"linenum",
"if",
"isinstance",
"(",
"transform",
".",
"data",
",",
"basestring",
")",
":",
"transform",
".",
"data",
"=",
"[",
"transform",
".",
"data",
"]",
"if",
"transform",
".",
"oper",
"==",
"\"prepend\"",
":",
"self",
".",
"data",
"[",
"linenum",
":",
"linenum",
"]",
"=",
"transform",
".",
"data",
"elif",
"transform",
".",
"oper",
"==",
"\"append\"",
":",
"self",
".",
"data",
"[",
"linenum",
"+",
"1",
":",
"linenum",
"+",
"1",
"]",
"=",
"transform",
".",
"data",
"elif",
"transform",
".",
"oper",
"==",
"\"swap\"",
":",
"self",
".",
"data",
"[",
"linenum",
":",
"linenum",
"+",
"1",
"]",
"=",
"transform",
".",
"data",
"elif",
"transform",
".",
"oper",
"==",
"\"drop\"",
":",
"self",
".",
"data",
"[",
"linenum",
":",
"linenum",
"+",
"1",
"]",
"=",
"[",
"]",
"elif",
"transform",
".",
"oper",
"==",
"\"noop\"",
":",
"pass"
] |
This method handles the actual processing of Modules and Transforms
|
[
"This",
"method",
"handles",
"the",
"actual",
"processing",
"of",
"Modules",
"and",
"Transforms"
] |
fba644c08176abef4ea5ad36b5b60d32379bddac
|
https://github.com/jreese/markdown-pp/blob/fba644c08176abef4ea5ad36b5b60d32379bddac/MarkdownPP/Processor.py#L42-L71
|
10,717
|
jpvanhal/inflection
|
inflection.py
|
_irregular
|
def _irregular(singular, plural):
"""
A convenience function to add appropriate rules to plurals and singular
for irregular words.
:param singular: irregular word in singular form
:param plural: irregular word in plural form
"""
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], singular[1:]),
r'\1' + plural[1:]
))
PLURALS.insert(0, (
r"(?i)({}){}$".format(plural[0], plural[1:]),
r'\1' + plural[1:]
))
SINGULARS.insert(0, (
r"(?i)({}){}$".format(plural[0], plural[1:]),
r'\1' + singular[1:]
))
else:
PLURALS.insert(0, (
r"{}{}$".format(singular[0].upper(),
caseinsensitive(singular[1:])),
plural[0].upper() + plural[1:]
))
PLURALS.insert(0, (
r"{}{}$".format(singular[0].lower(),
caseinsensitive(singular[1:])),
plural[0].lower() + plural[1:]
))
PLURALS.insert(0, (
r"{}{}$".format(plural[0].upper(), caseinsensitive(plural[1:])),
plural[0].upper() + plural[1:]
))
PLURALS.insert(0, (
r"{}{}$".format(plural[0].lower(), caseinsensitive(plural[1:])),
plural[0].lower() + plural[1:]
))
SINGULARS.insert(0, (
r"{}{}$".format(plural[0].upper(), caseinsensitive(plural[1:])),
singular[0].upper() + singular[1:]
))
SINGULARS.insert(0, (
r"{}{}$".format(plural[0].lower(), caseinsensitive(plural[1:])),
singular[0].lower() + singular[1:]
))
|
python
|
def _irregular(singular, plural):
"""
A convenience function to add appropriate rules to plurals and singular
for irregular words.
:param singular: irregular word in singular form
:param plural: irregular word in plural form
"""
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], singular[1:]),
r'\1' + plural[1:]
))
PLURALS.insert(0, (
r"(?i)({}){}$".format(plural[0], plural[1:]),
r'\1' + plural[1:]
))
SINGULARS.insert(0, (
r"(?i)({}){}$".format(plural[0], plural[1:]),
r'\1' + singular[1:]
))
else:
PLURALS.insert(0, (
r"{}{}$".format(singular[0].upper(),
caseinsensitive(singular[1:])),
plural[0].upper() + plural[1:]
))
PLURALS.insert(0, (
r"{}{}$".format(singular[0].lower(),
caseinsensitive(singular[1:])),
plural[0].lower() + plural[1:]
))
PLURALS.insert(0, (
r"{}{}$".format(plural[0].upper(), caseinsensitive(plural[1:])),
plural[0].upper() + plural[1:]
))
PLURALS.insert(0, (
r"{}{}$".format(plural[0].lower(), caseinsensitive(plural[1:])),
plural[0].lower() + plural[1:]
))
SINGULARS.insert(0, (
r"{}{}$".format(plural[0].upper(), caseinsensitive(plural[1:])),
singular[0].upper() + singular[1:]
))
SINGULARS.insert(0, (
r"{}{}$".format(plural[0].lower(), caseinsensitive(plural[1:])),
singular[0].lower() + singular[1:]
))
|
[
"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",
"]",
",",
"singular",
"[",
"1",
":",
"]",
")",
",",
"r'\\1'",
"+",
"plural",
"[",
"1",
":",
"]",
")",
")",
"PLURALS",
".",
"insert",
"(",
"0",
",",
"(",
"r\"(?i)({}){}$\"",
".",
"format",
"(",
"plural",
"[",
"0",
"]",
",",
"plural",
"[",
"1",
":",
"]",
")",
",",
"r'\\1'",
"+",
"plural",
"[",
"1",
":",
"]",
")",
")",
"SINGULARS",
".",
"insert",
"(",
"0",
",",
"(",
"r\"(?i)({}){}$\"",
".",
"format",
"(",
"plural",
"[",
"0",
"]",
",",
"plural",
"[",
"1",
":",
"]",
")",
",",
"r'\\1'",
"+",
"singular",
"[",
"1",
":",
"]",
")",
")",
"else",
":",
"PLURALS",
".",
"insert",
"(",
"0",
",",
"(",
"r\"{}{}$\"",
".",
"format",
"(",
"singular",
"[",
"0",
"]",
".",
"upper",
"(",
")",
",",
"caseinsensitive",
"(",
"singular",
"[",
"1",
":",
"]",
")",
")",
",",
"plural",
"[",
"0",
"]",
".",
"upper",
"(",
")",
"+",
"plural",
"[",
"1",
":",
"]",
")",
")",
"PLURALS",
".",
"insert",
"(",
"0",
",",
"(",
"r\"{}{}$\"",
".",
"format",
"(",
"singular",
"[",
"0",
"]",
".",
"lower",
"(",
")",
",",
"caseinsensitive",
"(",
"singular",
"[",
"1",
":",
"]",
")",
")",
",",
"plural",
"[",
"0",
"]",
".",
"lower",
"(",
")",
"+",
"plural",
"[",
"1",
":",
"]",
")",
")",
"PLURALS",
".",
"insert",
"(",
"0",
",",
"(",
"r\"{}{}$\"",
".",
"format",
"(",
"plural",
"[",
"0",
"]",
".",
"upper",
"(",
")",
",",
"caseinsensitive",
"(",
"plural",
"[",
"1",
":",
"]",
")",
")",
",",
"plural",
"[",
"0",
"]",
".",
"upper",
"(",
")",
"+",
"plural",
"[",
"1",
":",
"]",
")",
")",
"PLURALS",
".",
"insert",
"(",
"0",
",",
"(",
"r\"{}{}$\"",
".",
"format",
"(",
"plural",
"[",
"0",
"]",
".",
"lower",
"(",
")",
",",
"caseinsensitive",
"(",
"plural",
"[",
"1",
":",
"]",
")",
")",
",",
"plural",
"[",
"0",
"]",
".",
"lower",
"(",
")",
"+",
"plural",
"[",
"1",
":",
"]",
")",
")",
"SINGULARS",
".",
"insert",
"(",
"0",
",",
"(",
"r\"{}{}$\"",
".",
"format",
"(",
"plural",
"[",
"0",
"]",
".",
"upper",
"(",
")",
",",
"caseinsensitive",
"(",
"plural",
"[",
"1",
":",
"]",
")",
")",
",",
"singular",
"[",
"0",
"]",
".",
"upper",
"(",
")",
"+",
"singular",
"[",
"1",
":",
"]",
")",
")",
"SINGULARS",
".",
"insert",
"(",
"0",
",",
"(",
"r\"{}{}$\"",
".",
"format",
"(",
"plural",
"[",
"0",
"]",
".",
"lower",
"(",
")",
",",
"caseinsensitive",
"(",
"plural",
"[",
"1",
":",
"]",
")",
")",
",",
"singular",
"[",
"0",
"]",
".",
"lower",
"(",
")",
"+",
"singular",
"[",
"1",
":",
"]",
")",
")"
] |
A convenience function to add appropriate rules to plurals and singular
for irregular words.
:param singular: irregular word in singular form
:param plural: irregular word in plural form
|
[
"A",
"convenience",
"function",
"to",
"add",
"appropriate",
"rules",
"to",
"plurals",
"and",
"singular",
"for",
"irregular",
"words",
"."
] |
ad195ab72b193b57bb4cf68396c4cd8a62f1fe6c
|
https://github.com/jpvanhal/inflection/blob/ad195ab72b193b57bb4cf68396c4cd8a62f1fe6c/inflection.py#L89-L139
|
10,718
|
jpvanhal/inflection
|
inflection.py
|
camelize
|
def camelize(string, uppercase_first_letter=True):
"""
Convert strings to CamelCase.
Examples::
>>> camelize("device_type")
"DeviceType"
>>> camelize("device_type", False)
"deviceType"
:func:`camelize` can be thought of as a inverse of :func:`underscore`,
although there are some cases where that does not hold::
>>> camelize(underscore("IOError"))
"IoError"
:param uppercase_first_letter: if set to `True` :func:`camelize` converts
strings to UpperCamelCase. If set to `False` :func:`camelize` produces
lowerCamelCase. Defaults to `True`.
"""
if uppercase_first_letter:
return re.sub(r"(?:^|_)(.)", lambda m: m.group(1).upper(), string)
else:
return string[0].lower() + camelize(string)[1:]
|
python
|
def camelize(string, uppercase_first_letter=True):
"""
Convert strings to CamelCase.
Examples::
>>> camelize("device_type")
"DeviceType"
>>> camelize("device_type", False)
"deviceType"
:func:`camelize` can be thought of as a inverse of :func:`underscore`,
although there are some cases where that does not hold::
>>> camelize(underscore("IOError"))
"IoError"
:param uppercase_first_letter: if set to `True` :func:`camelize` converts
strings to UpperCamelCase. If set to `False` :func:`camelize` produces
lowerCamelCase. Defaults to `True`.
"""
if uppercase_first_letter:
return re.sub(r"(?:^|_)(.)", lambda m: m.group(1).upper(), string)
else:
return string[0].lower() + camelize(string)[1:]
|
[
"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",
":",
"]"
] |
Convert strings to CamelCase.
Examples::
>>> camelize("device_type")
"DeviceType"
>>> camelize("device_type", False)
"deviceType"
:func:`camelize` can be thought of as a inverse of :func:`underscore`,
although there are some cases where that does not hold::
>>> camelize(underscore("IOError"))
"IoError"
:param uppercase_first_letter: if set to `True` :func:`camelize` converts
strings to UpperCamelCase. If set to `False` :func:`camelize` produces
lowerCamelCase. Defaults to `True`.
|
[
"Convert",
"strings",
"to",
"CamelCase",
"."
] |
ad195ab72b193b57bb4cf68396c4cd8a62f1fe6c
|
https://github.com/jpvanhal/inflection/blob/ad195ab72b193b57bb4cf68396c4cd8a62f1fe6c/inflection.py#L142-L166
|
10,719
|
jpvanhal/inflection
|
inflection.py
|
parameterize
|
def parameterize(string, separator='-'):
"""
Replace special characters in a string so that it may be used as part of a
'pretty' URL.
Example::
>>> parameterize(u"Donald E. Knuth")
'donald-e-knuth'
"""
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 the separator in a row.
string = re.sub(r'%s{2,}' % re_sep, separator, string)
# Remove leading/trailing separator.
string = re.sub(r"(?i)^{sep}|{sep}$".format(sep=re_sep), '', string)
return string.lower()
|
python
|
def parameterize(string, separator='-'):
"""
Replace special characters in a string so that it may be used as part of a
'pretty' URL.
Example::
>>> parameterize(u"Donald E. Knuth")
'donald-e-knuth'
"""
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 the separator in a row.
string = re.sub(r'%s{2,}' % re_sep, separator, string)
# Remove leading/trailing separator.
string = re.sub(r"(?i)^{sep}|{sep}$".format(sep=re_sep), '', string)
return string.lower()
|
[
"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 the separator in a row.",
"string",
"=",
"re",
".",
"sub",
"(",
"r'%s{2,}'",
"%",
"re_sep",
",",
"separator",
",",
"string",
")",
"# Remove leading/trailing separator.",
"string",
"=",
"re",
".",
"sub",
"(",
"r\"(?i)^{sep}|{sep}$\"",
".",
"format",
"(",
"sep",
"=",
"re_sep",
")",
",",
"''",
",",
"string",
")",
"return",
"string",
".",
"lower",
"(",
")"
] |
Replace special characters in a string so that it may be used as part of a
'pretty' URL.
Example::
>>> parameterize(u"Donald E. Knuth")
'donald-e-knuth'
|
[
"Replace",
"special",
"characters",
"in",
"a",
"string",
"so",
"that",
"it",
"may",
"be",
"used",
"as",
"part",
"of",
"a",
"pretty",
"URL",
"."
] |
ad195ab72b193b57bb4cf68396c4cd8a62f1fe6c
|
https://github.com/jpvanhal/inflection/blob/ad195ab72b193b57bb4cf68396c4cd8a62f1fe6c/inflection.py#L258-L279
|
10,720
|
jpvanhal/inflection
|
inflection.py
|
pluralize
|
def pluralize(word):
"""
Return the plural form of a word.
Examples::
>>> pluralize("post")
"posts"
>>> pluralize("octopus")
"octopi"
>>> pluralize("sheep")
"sheep"
>>> pluralize("CamelOctopus")
"CamelOctopi"
"""
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
|
python
|
def pluralize(word):
"""
Return the plural form of a word.
Examples::
>>> pluralize("post")
"posts"
>>> pluralize("octopus")
"octopi"
>>> pluralize("sheep")
"sheep"
>>> pluralize("CamelOctopus")
"CamelOctopi"
"""
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
|
[
"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"
] |
Return the plural form of a word.
Examples::
>>> pluralize("post")
"posts"
>>> pluralize("octopus")
"octopi"
>>> pluralize("sheep")
"sheep"
>>> pluralize("CamelOctopus")
"CamelOctopi"
|
[
"Return",
"the",
"plural",
"form",
"of",
"a",
"word",
"."
] |
ad195ab72b193b57bb4cf68396c4cd8a62f1fe6c
|
https://github.com/jpvanhal/inflection/blob/ad195ab72b193b57bb4cf68396c4cd8a62f1fe6c/inflection.py#L282-L304
|
10,721
|
jpvanhal/inflection
|
inflection.py
|
underscore
|
def underscore(word):
"""
Make an underscored, lowercase form from the expression in the string.
Example::
>>> underscore("DeviceType")
"device_type"
As a rule of thumb you can think of :func:`underscore` as the inverse of
:func:`camelize`, though there are cases where that does not hold::
>>> camelize(underscore("IOError"))
"IoError"
"""
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()
|
python
|
def underscore(word):
"""
Make an underscored, lowercase form from the expression in the string.
Example::
>>> underscore("DeviceType")
"device_type"
As a rule of thumb you can think of :func:`underscore` as the inverse of
:func:`camelize`, though there are cases where that does not hold::
>>> camelize(underscore("IOError"))
"IoError"
"""
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()
|
[
"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",
"(",
")"
] |
Make an underscored, lowercase form from the expression in the string.
Example::
>>> underscore("DeviceType")
"device_type"
As a rule of thumb you can think of :func:`underscore` as the inverse of
:func:`camelize`, though there are cases where that does not hold::
>>> camelize(underscore("IOError"))
"IoError"
|
[
"Make",
"an",
"underscored",
"lowercase",
"form",
"from",
"the",
"expression",
"in",
"the",
"string",
"."
] |
ad195ab72b193b57bb4cf68396c4cd8a62f1fe6c
|
https://github.com/jpvanhal/inflection/blob/ad195ab72b193b57bb4cf68396c4cd8a62f1fe6c/inflection.py#L395-L414
|
10,722
|
libvips/pyvips
|
pyvips/vobject.py
|
VipsObject.print_all
|
def print_all(msg):
"""Print all objects.
Print a table of all active libvips objects. Handy for debugging.
"""
gc.collect()
logger.debug(msg)
vips_lib.vips_object_print_all()
logger.debug()
|
python
|
def print_all(msg):
"""Print all objects.
Print a table of all active libvips objects. Handy for debugging.
"""
gc.collect()
logger.debug(msg)
vips_lib.vips_object_print_all()
logger.debug()
|
[
"def",
"print_all",
"(",
"msg",
")",
":",
"gc",
".",
"collect",
"(",
")",
"logger",
".",
"debug",
"(",
"msg",
")",
"vips_lib",
".",
"vips_object_print_all",
"(",
")",
"logger",
".",
"debug",
"(",
")"
] |
Print all objects.
Print a table of all active libvips objects. Handy for debugging.
|
[
"Print",
"all",
"objects",
"."
] |
f4d9334d2e3085b4b058129f14ac17a7872b109b
|
https://github.com/libvips/pyvips/blob/f4d9334d2e3085b4b058129f14ac17a7872b109b/pyvips/vobject.py#L22-L32
|
10,723
|
libvips/pyvips
|
pyvips/vobject.py
|
VipsObject.get_typeof
|
def get_typeof(self, name):
"""Get the GType of a GObject property.
This function returns 0 if the property does not exist.
"""
# 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
Error('')
return 0
return pspec.value_type
|
python
|
def get_typeof(self, name):
"""Get the GType of a GObject property.
This function returns 0 if the property does not exist.
"""
# 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
Error('')
return 0
return pspec.value_type
|
[
"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",
"Error",
"(",
"''",
")",
"return",
"0",
"return",
"pspec",
".",
"value_type"
] |
Get the GType of a GObject property.
This function returns 0 if the property does not exist.
|
[
"Get",
"the",
"GType",
"of",
"a",
"GObject",
"property",
"."
] |
f4d9334d2e3085b4b058129f14ac17a7872b109b
|
https://github.com/libvips/pyvips/blob/f4d9334d2e3085b4b058129f14ac17a7872b109b/pyvips/vobject.py#L52-L68
|
10,724
|
libvips/pyvips
|
pyvips/vobject.py
|
VipsObject.get_blurb
|
def get_blurb(self, name):
"""Get the blurb for a GObject property."""
c_str = gobject_lib.g_param_spec_get_blurb(self._get_pspec(name))
return _to_string(c_str)
|
python
|
def get_blurb(self, name):
"""Get the blurb for a GObject property."""
c_str = gobject_lib.g_param_spec_get_blurb(self._get_pspec(name))
return _to_string(c_str)
|
[
"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.
|
[
"Get",
"the",
"blurb",
"for",
"a",
"GObject",
"property",
"."
] |
f4d9334d2e3085b4b058129f14ac17a7872b109b
|
https://github.com/libvips/pyvips/blob/f4d9334d2e3085b4b058129f14ac17a7872b109b/pyvips/vobject.py#L70-L74
|
10,725
|
libvips/pyvips
|
pyvips/vobject.py
|
VipsObject.get
|
def get(self, name):
"""Get a GObject property.
The value of the property is converted to a Python value.
"""
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.set_type(gtype)
go = ffi.cast('GObject *', self.pointer)
gobject_lib.g_object_get_property(go, _to_bytes(name), gv.pointer)
return gv.get()
|
python
|
def get(self, name):
"""Get a GObject property.
The value of the property is converted to a Python value.
"""
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.set_type(gtype)
go = ffi.cast('GObject *', self.pointer)
gobject_lib.g_object_get_property(go, _to_bytes(name), gv.pointer)
return gv.get()
|
[
"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",
".",
"set_type",
"(",
"gtype",
")",
"go",
"=",
"ffi",
".",
"cast",
"(",
"'GObject *'",
",",
"self",
".",
"pointer",
")",
"gobject_lib",
".",
"g_object_get_property",
"(",
"go",
",",
"_to_bytes",
"(",
"name",
")",
",",
"gv",
".",
"pointer",
")",
"return",
"gv",
".",
"get",
"(",
")"
] |
Get a GObject property.
The value of the property is converted to a Python value.
|
[
"Get",
"a",
"GObject",
"property",
"."
] |
f4d9334d2e3085b4b058129f14ac17a7872b109b
|
https://github.com/libvips/pyvips/blob/f4d9334d2e3085b4b058129f14ac17a7872b109b/pyvips/vobject.py#L76-L95
|
10,726
|
libvips/pyvips
|
pyvips/vobject.py
|
VipsObject.set
|
def set(self, name, value):
"""Set a GObject property.
The value is converted to the property type, if possible.
"""
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.pointer)
gobject_lib.g_object_set_property(go, _to_bytes(name), gv.pointer)
|
python
|
def set(self, name, value):
"""Set a GObject property.
The value is converted to the property type, if possible.
"""
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.pointer)
gobject_lib.g_object_set_property(go, _to_bytes(name), gv.pointer)
|
[
"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",
".",
"pointer",
")",
"gobject_lib",
".",
"g_object_set_property",
"(",
"go",
",",
"_to_bytes",
"(",
"name",
")",
",",
"gv",
".",
"pointer",
")"
] |
Set a GObject property.
The value is converted to the property type, if possible.
|
[
"Set",
"a",
"GObject",
"property",
"."
] |
f4d9334d2e3085b4b058129f14ac17a7872b109b
|
https://github.com/libvips/pyvips/blob/f4d9334d2e3085b4b058129f14ac17a7872b109b/pyvips/vobject.py#L97-L112
|
10,727
|
libvips/pyvips
|
pyvips/vobject.py
|
VipsObject.set_string
|
def set_string(self, string_options):
"""Set a series of properties using a string.
For example::
'fred=12, tile'
'[fred=12]'
"""
vo = ffi.cast('VipsObject *', self.pointer)
cstr = _to_bytes(string_options)
result = vips_lib.vips_object_set_from_string(vo, cstr)
return result == 0
|
python
|
def set_string(self, string_options):
"""Set a series of properties using a string.
For example::
'fred=12, tile'
'[fred=12]'
"""
vo = ffi.cast('VipsObject *', self.pointer)
cstr = _to_bytes(string_options)
result = vips_lib.vips_object_set_from_string(vo, cstr)
return result == 0
|
[
"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.
For example::
'fred=12, tile'
'[fred=12]'
|
[
"Set",
"a",
"series",
"of",
"properties",
"using",
"a",
"string",
"."
] |
f4d9334d2e3085b4b058129f14ac17a7872b109b
|
https://github.com/libvips/pyvips/blob/f4d9334d2e3085b4b058129f14ac17a7872b109b/pyvips/vobject.py#L114-L128
|
10,728
|
libvips/pyvips
|
pyvips/vobject.py
|
VipsObject.get_description
|
def get_description(self):
"""Get the description of a GObject."""
vo = ffi.cast('VipsObject *', self.pointer)
return _to_string(vips_lib.vips_object_get_description(vo))
|
python
|
def get_description(self):
"""Get the description of a GObject."""
vo = ffi.cast('VipsObject *', self.pointer)
return _to_string(vips_lib.vips_object_get_description(vo))
|
[
"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.
|
[
"Get",
"the",
"description",
"of",
"a",
"GObject",
"."
] |
f4d9334d2e3085b4b058129f14ac17a7872b109b
|
https://github.com/libvips/pyvips/blob/f4d9334d2e3085b4b058129f14ac17a7872b109b/pyvips/vobject.py#L130-L134
|
10,729
|
libvips/pyvips
|
pyvips/voperation.py
|
Operation.generate_sphinx_all
|
def generate_sphinx_all():
"""Generate sphinx documentation.
This generates a .rst file for all auto-generated image methods. Use it
to regenerate the docs with something like::
$ python -c \
"import pyvips; pyvips.Operation.generate_sphinx_all()" > x
And copy-paste the file contents into doc/vimage.rst in the appropriate
place.
"""
# 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_sphinx(nickname)
all_nicknames.append(nickname)
except Error:
pass
type_map(gtype, add_nickname)
return ffi.NULL
type_map(type_from_name('VipsOperation'), add_nickname)
all_nicknames.sort()
# remove operations we have to wrap by hand
exclude = ['scale', 'ifthenelse', 'bandjoin', 'bandrank']
all_nicknames = [x for x in all_nicknames if x not in exclude]
# Output summary table
print('.. class:: pyvips.Image\n')
print(' .. rubric:: Methods\n')
print(' .. autosummary::')
print(' :nosignatures:\n')
for nickname in all_nicknames:
print(' ~{0}'.format(nickname))
print()
# Output docs
print()
for nickname in all_nicknames:
docstr = Operation.generate_sphinx(nickname)
docstr = docstr.replace('\n', '\n ')
print(' ' + docstr)
|
python
|
def generate_sphinx_all():
"""Generate sphinx documentation.
This generates a .rst file for all auto-generated image methods. Use it
to regenerate the docs with something like::
$ python -c \
"import pyvips; pyvips.Operation.generate_sphinx_all()" > x
And copy-paste the file contents into doc/vimage.rst in the appropriate
place.
"""
# 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_sphinx(nickname)
all_nicknames.append(nickname)
except Error:
pass
type_map(gtype, add_nickname)
return ffi.NULL
type_map(type_from_name('VipsOperation'), add_nickname)
all_nicknames.sort()
# remove operations we have to wrap by hand
exclude = ['scale', 'ifthenelse', 'bandjoin', 'bandrank']
all_nicknames = [x for x in all_nicknames if x not in exclude]
# Output summary table
print('.. class:: pyvips.Image\n')
print(' .. rubric:: Methods\n')
print(' .. autosummary::')
print(' :nosignatures:\n')
for nickname in all_nicknames:
print(' ~{0}'.format(nickname))
print()
# Output docs
print()
for nickname in all_nicknames:
docstr = Operation.generate_sphinx(nickname)
docstr = docstr.replace('\n', '\n ')
print(' ' + docstr)
|
[
"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_sphinx",
"(",
"nickname",
")",
"all_nicknames",
".",
"append",
"(",
"nickname",
")",
"except",
"Error",
":",
"pass",
"type_map",
"(",
"gtype",
",",
"add_nickname",
")",
"return",
"ffi",
".",
"NULL",
"type_map",
"(",
"type_from_name",
"(",
"'VipsOperation'",
")",
",",
"add_nickname",
")",
"all_nicknames",
".",
"sort",
"(",
")",
"# remove operations we have to wrap by hand",
"exclude",
"=",
"[",
"'scale'",
",",
"'ifthenelse'",
",",
"'bandjoin'",
",",
"'bandrank'",
"]",
"all_nicknames",
"=",
"[",
"x",
"for",
"x",
"in",
"all_nicknames",
"if",
"x",
"not",
"in",
"exclude",
"]",
"# Output summary table",
"print",
"(",
"'.. class:: pyvips.Image\\n'",
")",
"print",
"(",
"' .. rubric:: Methods\\n'",
")",
"print",
"(",
"' .. autosummary::'",
")",
"print",
"(",
"' :nosignatures:\\n'",
")",
"for",
"nickname",
"in",
"all_nicknames",
":",
"print",
"(",
"' ~{0}'",
".",
"format",
"(",
"nickname",
")",
")",
"print",
"(",
")",
"# Output docs",
"print",
"(",
")",
"for",
"nickname",
"in",
"all_nicknames",
":",
"docstr",
"=",
"Operation",
".",
"generate_sphinx",
"(",
"nickname",
")",
"docstr",
"=",
"docstr",
".",
"replace",
"(",
"'\\n'",
",",
"'\\n '",
")",
"print",
"(",
"' '",
"+",
"docstr",
")"
] |
Generate sphinx documentation.
This generates a .rst file for all auto-generated image methods. Use it
to regenerate the docs with something like::
$ python -c \
"import pyvips; pyvips.Operation.generate_sphinx_all()" > x
And copy-paste the file contents into doc/vimage.rst in the appropriate
place.
|
[
"Generate",
"sphinx",
"documentation",
"."
] |
f4d9334d2e3085b4b058129f14ac17a7872b109b
|
https://github.com/libvips/pyvips/blob/f4d9334d2e3085b4b058129f14ac17a7872b109b/pyvips/voperation.py#L482-L535
|
10,730
|
libvips/pyvips
|
pyvips/vregion.py
|
Region.new
|
def new(image):
"""Make a region on an image.
Returns:
A new :class:`.Region`.
Raises:
:class:`.Error`
"""
pointer = vips_lib.vips_region_new(image.pointer)
if pointer == ffi.NULL:
raise Error('unable to make region')
return pyvips.Region(pointer)
|
python
|
def new(image):
"""Make a region on an image.
Returns:
A new :class:`.Region`.
Raises:
:class:`.Error`
"""
pointer = vips_lib.vips_region_new(image.pointer)
if pointer == ffi.NULL:
raise Error('unable to make region')
return pyvips.Region(pointer)
|
[
"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.
Returns:
A new :class:`.Region`.
Raises:
:class:`.Error`
|
[
"Make",
"a",
"region",
"on",
"an",
"image",
"."
] |
f4d9334d2e3085b4b058129f14ac17a7872b109b
|
https://github.com/libvips/pyvips/blob/f4d9334d2e3085b4b058129f14ac17a7872b109b/pyvips/vregion.py#L21-L36
|
10,731
|
libvips/pyvips
|
pyvips/vregion.py
|
Region.fetch
|
def fetch(self, x, y, w, h):
"""Fill a region with pixel data.
Pixels are filled with data!
Returns:
Pixel data.
Raises:
:class:`.Error`
"""
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:
raise Error('unable to fetch from region')
pointer = ffi.gc(pointer, glib_lib.g_free)
return ffi.buffer(pointer, psize[0])
|
python
|
def fetch(self, x, y, w, h):
"""Fill a region with pixel data.
Pixels are filled with data!
Returns:
Pixel data.
Raises:
:class:`.Error`
"""
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:
raise Error('unable to fetch from region')
pointer = ffi.gc(pointer, glib_lib.g_free)
return ffi.buffer(pointer, psize[0])
|
[
"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",
":",
"raise",
"Error",
"(",
"'unable to fetch from region'",
")",
"pointer",
"=",
"ffi",
".",
"gc",
"(",
"pointer",
",",
"glib_lib",
".",
"g_free",
")",
"return",
"ffi",
".",
"buffer",
"(",
"pointer",
",",
"psize",
"[",
"0",
"]",
")"
] |
Fill a region with pixel data.
Pixels are filled with data!
Returns:
Pixel data.
Raises:
:class:`.Error`
|
[
"Fill",
"a",
"region",
"with",
"pixel",
"data",
"."
] |
f4d9334d2e3085b4b058129f14ac17a7872b109b
|
https://github.com/libvips/pyvips/blob/f4d9334d2e3085b4b058129f14ac17a7872b109b/pyvips/vregion.py#L52-L74
|
10,732
|
libvips/pyvips
|
pyvips/gvalue.py
|
GValue.gtype_to_python
|
def gtype_to_python(gtype):
"""Map a gtype to the name of the Python type we use to represent it.
"""
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._gtype_to_python[fundamental]
return '<unknown type>'
|
python
|
def gtype_to_python(gtype):
"""Map a gtype to the name of the Python type we use to represent it.
"""
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._gtype_to_python[fundamental]
return '<unknown type>'
|
[
"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",
".",
"_gtype_to_python",
"[",
"fundamental",
"]",
"return",
"'<unknown type>'"
] |
Map a gtype to the name of the Python type we use to represent it.
|
[
"Map",
"a",
"gtype",
"to",
"the",
"name",
"of",
"the",
"Python",
"type",
"we",
"use",
"to",
"represent",
"it",
"."
] |
f4d9334d2e3085b4b058129f14ac17a7872b109b
|
https://github.com/libvips/pyvips/blob/f4d9334d2e3085b4b058129f14ac17a7872b109b/pyvips/gvalue.py#L75-L86
|
10,733
|
libvips/pyvips
|
pyvips/gvalue.py
|
GValue.to_enum
|
def to_enum(gtype, value):
"""Turn a string into an enum value ready to be passed into libvips.
"""
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:
raise Error('no value {0} in gtype {1} ({2})'.
format(value, type_name(gtype), gtype))
else:
enum_value = value
return enum_value
|
python
|
def to_enum(gtype, value):
"""Turn a string into an enum value ready to be passed into libvips.
"""
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:
raise Error('no value {0} in gtype {1} ({2})'.
format(value, type_name(gtype), gtype))
else:
enum_value = value
return enum_value
|
[
"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",
":",
"raise",
"Error",
"(",
"'no value {0} in gtype {1} ({2})'",
".",
"format",
"(",
"value",
",",
"type_name",
"(",
"gtype",
")",
",",
"gtype",
")",
")",
"else",
":",
"enum_value",
"=",
"value",
"return",
"enum_value"
] |
Turn a string into an enum value ready to be passed into libvips.
|
[
"Turn",
"a",
"string",
"into",
"an",
"enum",
"value",
"ready",
"to",
"be",
"passed",
"into",
"libvips",
"."
] |
f4d9334d2e3085b4b058129f14ac17a7872b109b
|
https://github.com/libvips/pyvips/blob/f4d9334d2e3085b4b058129f14ac17a7872b109b/pyvips/gvalue.py#L89-L103
|
10,734
|
libvips/pyvips
|
pyvips/gvalue.py
|
GValue.from_enum
|
def from_enum(gtype, enum_value):
"""Turn an int back into an enum string.
"""
pointer = vips_lib.vips_enum_nick(gtype, enum_value)
if pointer == ffi.NULL:
raise Error('value not in enum')
return _to_string(pointer)
|
python
|
def from_enum(gtype, enum_value):
"""Turn an int back into an enum string.
"""
pointer = vips_lib.vips_enum_nick(gtype, enum_value)
if pointer == ffi.NULL:
raise Error('value not in enum')
return _to_string(pointer)
|
[
"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.
|
[
"Turn",
"an",
"int",
"back",
"into",
"an",
"enum",
"string",
"."
] |
f4d9334d2e3085b4b058129f14ac17a7872b109b
|
https://github.com/libvips/pyvips/blob/f4d9334d2e3085b4b058129f14ac17a7872b109b/pyvips/gvalue.py#L106-L115
|
10,735
|
libvips/pyvips
|
pyvips/gvalue.py
|
GValue.set
|
def set(self, value):
"""Set a GValue.
The value is converted to the type of the GValue, if possible, and
assigned.
"""
# 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.gvalue, value)
elif gtype == GValue.gint_type:
gobject_lib.g_value_set_int(self.gvalue, int(value))
elif gtype == GValue.guint64_type:
gobject_lib.g_value_set_uint64(self.gvalue, value)
elif gtype == GValue.gdouble_type:
gobject_lib.g_value_set_double(self.gvalue, value)
elif fundamental == GValue.genum_type:
gobject_lib.g_value_set_enum(self.gvalue,
GValue.to_enum(gtype, value))
elif fundamental == GValue.gflags_type:
gobject_lib.g_value_set_flags(self.gvalue, value)
elif gtype == GValue.gstr_type:
gobject_lib.g_value_set_string(self.gvalue, _to_bytes(value))
elif gtype == GValue.refstr_type:
vips_lib.vips_value_set_ref_string(self.gvalue, _to_bytes(value))
elif fundamental == GValue.gobject_type:
gobject_lib.g_value_set_object(self.gvalue, value.pointer)
elif gtype == GValue.array_int_type:
if isinstance(value, numbers.Number):
value = [value]
array = ffi.new('int[]', value)
vips_lib.vips_value_set_array_int(self.gvalue, array, len(value))
elif gtype == GValue.array_double_type:
if isinstance(value, numbers.Number):
value = [value]
array = ffi.new('double[]', value)
vips_lib.vips_value_set_array_double(self.gvalue, array,
len(value))
elif gtype == GValue.array_image_type:
if isinstance(value, pyvips.Image):
value = [value]
vips_lib.vips_value_set_array_image(self.gvalue, len(value))
array = vips_lib.vips_value_get_array_image(self.gvalue, ffi.NULL)
for i, image in enumerate(value):
gobject_lib.g_object_ref(image.pointer)
array[i] = image.pointer
elif gtype == GValue.blob_type:
# we need to set the blob to a copy of the string that vips_lib
# can own
memory = glib_lib.g_malloc(len(value))
ffi.memmove(memory, value, len(value))
# this is horrible!
#
# * in API mode, we must have 8.6+ and use set_blob_free to
# attach the metadata to avoid leaks
# * pre-8.6, we just pass a NULL free pointer and live with the
# leak
#
# this is because in API mode you can't pass a builtin (what
# vips_lib.g_free() becomes) as a parameter to ffi.callback(), and
# vips_value_set_blob() needs a callback for arg 2
#
# additionally, you can't make a py def which calls g_free() and
# then use the py def in the callback, since libvips will trigger
# these functions during cleanup, and py will have shut down by
# then and you'll get a segv
if at_least_libvips(8, 6):
vips_lib.vips_value_set_blob_free(self.gvalue,
memory, len(value))
else:
if pyvips.API_mode:
vips_lib.vips_value_set_blob(self.gvalue,
ffi.NULL, memory, len(value))
else:
vips_lib.vips_value_set_blob(self.gvalue,
glib_lib.g_free,
memory, len(value))
else:
raise Error('unsupported gtype for set {0}, fundamental {1}'.
format(type_name(gtype), type_name(fundamental)))
|
python
|
def set(self, value):
"""Set a GValue.
The value is converted to the type of the GValue, if possible, and
assigned.
"""
# 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.gvalue, value)
elif gtype == GValue.gint_type:
gobject_lib.g_value_set_int(self.gvalue, int(value))
elif gtype == GValue.guint64_type:
gobject_lib.g_value_set_uint64(self.gvalue, value)
elif gtype == GValue.gdouble_type:
gobject_lib.g_value_set_double(self.gvalue, value)
elif fundamental == GValue.genum_type:
gobject_lib.g_value_set_enum(self.gvalue,
GValue.to_enum(gtype, value))
elif fundamental == GValue.gflags_type:
gobject_lib.g_value_set_flags(self.gvalue, value)
elif gtype == GValue.gstr_type:
gobject_lib.g_value_set_string(self.gvalue, _to_bytes(value))
elif gtype == GValue.refstr_type:
vips_lib.vips_value_set_ref_string(self.gvalue, _to_bytes(value))
elif fundamental == GValue.gobject_type:
gobject_lib.g_value_set_object(self.gvalue, value.pointer)
elif gtype == GValue.array_int_type:
if isinstance(value, numbers.Number):
value = [value]
array = ffi.new('int[]', value)
vips_lib.vips_value_set_array_int(self.gvalue, array, len(value))
elif gtype == GValue.array_double_type:
if isinstance(value, numbers.Number):
value = [value]
array = ffi.new('double[]', value)
vips_lib.vips_value_set_array_double(self.gvalue, array,
len(value))
elif gtype == GValue.array_image_type:
if isinstance(value, pyvips.Image):
value = [value]
vips_lib.vips_value_set_array_image(self.gvalue, len(value))
array = vips_lib.vips_value_get_array_image(self.gvalue, ffi.NULL)
for i, image in enumerate(value):
gobject_lib.g_object_ref(image.pointer)
array[i] = image.pointer
elif gtype == GValue.blob_type:
# we need to set the blob to a copy of the string that vips_lib
# can own
memory = glib_lib.g_malloc(len(value))
ffi.memmove(memory, value, len(value))
# this is horrible!
#
# * in API mode, we must have 8.6+ and use set_blob_free to
# attach the metadata to avoid leaks
# * pre-8.6, we just pass a NULL free pointer and live with the
# leak
#
# this is because in API mode you can't pass a builtin (what
# vips_lib.g_free() becomes) as a parameter to ffi.callback(), and
# vips_value_set_blob() needs a callback for arg 2
#
# additionally, you can't make a py def which calls g_free() and
# then use the py def in the callback, since libvips will trigger
# these functions during cleanup, and py will have shut down by
# then and you'll get a segv
if at_least_libvips(8, 6):
vips_lib.vips_value_set_blob_free(self.gvalue,
memory, len(value))
else:
if pyvips.API_mode:
vips_lib.vips_value_set_blob(self.gvalue,
ffi.NULL, memory, len(value))
else:
vips_lib.vips_value_set_blob(self.gvalue,
glib_lib.g_free,
memory, len(value))
else:
raise Error('unsupported gtype for set {0}, fundamental {1}'.
format(type_name(gtype), type_name(fundamental)))
|
[
"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",
".",
"gvalue",
",",
"value",
")",
"elif",
"gtype",
"==",
"GValue",
".",
"gint_type",
":",
"gobject_lib",
".",
"g_value_set_int",
"(",
"self",
".",
"gvalue",
",",
"int",
"(",
"value",
")",
")",
"elif",
"gtype",
"==",
"GValue",
".",
"guint64_type",
":",
"gobject_lib",
".",
"g_value_set_uint64",
"(",
"self",
".",
"gvalue",
",",
"value",
")",
"elif",
"gtype",
"==",
"GValue",
".",
"gdouble_type",
":",
"gobject_lib",
".",
"g_value_set_double",
"(",
"self",
".",
"gvalue",
",",
"value",
")",
"elif",
"fundamental",
"==",
"GValue",
".",
"genum_type",
":",
"gobject_lib",
".",
"g_value_set_enum",
"(",
"self",
".",
"gvalue",
",",
"GValue",
".",
"to_enum",
"(",
"gtype",
",",
"value",
")",
")",
"elif",
"fundamental",
"==",
"GValue",
".",
"gflags_type",
":",
"gobject_lib",
".",
"g_value_set_flags",
"(",
"self",
".",
"gvalue",
",",
"value",
")",
"elif",
"gtype",
"==",
"GValue",
".",
"gstr_type",
":",
"gobject_lib",
".",
"g_value_set_string",
"(",
"self",
".",
"gvalue",
",",
"_to_bytes",
"(",
"value",
")",
")",
"elif",
"gtype",
"==",
"GValue",
".",
"refstr_type",
":",
"vips_lib",
".",
"vips_value_set_ref_string",
"(",
"self",
".",
"gvalue",
",",
"_to_bytes",
"(",
"value",
")",
")",
"elif",
"fundamental",
"==",
"GValue",
".",
"gobject_type",
":",
"gobject_lib",
".",
"g_value_set_object",
"(",
"self",
".",
"gvalue",
",",
"value",
".",
"pointer",
")",
"elif",
"gtype",
"==",
"GValue",
".",
"array_int_type",
":",
"if",
"isinstance",
"(",
"value",
",",
"numbers",
".",
"Number",
")",
":",
"value",
"=",
"[",
"value",
"]",
"array",
"=",
"ffi",
".",
"new",
"(",
"'int[]'",
",",
"value",
")",
"vips_lib",
".",
"vips_value_set_array_int",
"(",
"self",
".",
"gvalue",
",",
"array",
",",
"len",
"(",
"value",
")",
")",
"elif",
"gtype",
"==",
"GValue",
".",
"array_double_type",
":",
"if",
"isinstance",
"(",
"value",
",",
"numbers",
".",
"Number",
")",
":",
"value",
"=",
"[",
"value",
"]",
"array",
"=",
"ffi",
".",
"new",
"(",
"'double[]'",
",",
"value",
")",
"vips_lib",
".",
"vips_value_set_array_double",
"(",
"self",
".",
"gvalue",
",",
"array",
",",
"len",
"(",
"value",
")",
")",
"elif",
"gtype",
"==",
"GValue",
".",
"array_image_type",
":",
"if",
"isinstance",
"(",
"value",
",",
"pyvips",
".",
"Image",
")",
":",
"value",
"=",
"[",
"value",
"]",
"vips_lib",
".",
"vips_value_set_array_image",
"(",
"self",
".",
"gvalue",
",",
"len",
"(",
"value",
")",
")",
"array",
"=",
"vips_lib",
".",
"vips_value_get_array_image",
"(",
"self",
".",
"gvalue",
",",
"ffi",
".",
"NULL",
")",
"for",
"i",
",",
"image",
"in",
"enumerate",
"(",
"value",
")",
":",
"gobject_lib",
".",
"g_object_ref",
"(",
"image",
".",
"pointer",
")",
"array",
"[",
"i",
"]",
"=",
"image",
".",
"pointer",
"elif",
"gtype",
"==",
"GValue",
".",
"blob_type",
":",
"# we need to set the blob to a copy of the string that vips_lib",
"# can own",
"memory",
"=",
"glib_lib",
".",
"g_malloc",
"(",
"len",
"(",
"value",
")",
")",
"ffi",
".",
"memmove",
"(",
"memory",
",",
"value",
",",
"len",
"(",
"value",
")",
")",
"# this is horrible!",
"#",
"# * in API mode, we must have 8.6+ and use set_blob_free to",
"# attach the metadata to avoid leaks",
"# * pre-8.6, we just pass a NULL free pointer and live with the",
"# leak",
"#",
"# this is because in API mode you can't pass a builtin (what",
"# vips_lib.g_free() becomes) as a parameter to ffi.callback(), and",
"# vips_value_set_blob() needs a callback for arg 2",
"#",
"# additionally, you can't make a py def which calls g_free() and",
"# then use the py def in the callback, since libvips will trigger",
"# these functions during cleanup, and py will have shut down by",
"# then and you'll get a segv",
"if",
"at_least_libvips",
"(",
"8",
",",
"6",
")",
":",
"vips_lib",
".",
"vips_value_set_blob_free",
"(",
"self",
".",
"gvalue",
",",
"memory",
",",
"len",
"(",
"value",
")",
")",
"else",
":",
"if",
"pyvips",
".",
"API_mode",
":",
"vips_lib",
".",
"vips_value_set_blob",
"(",
"self",
".",
"gvalue",
",",
"ffi",
".",
"NULL",
",",
"memory",
",",
"len",
"(",
"value",
")",
")",
"else",
":",
"vips_lib",
".",
"vips_value_set_blob",
"(",
"self",
".",
"gvalue",
",",
"glib_lib",
".",
"g_free",
",",
"memory",
",",
"len",
"(",
"value",
")",
")",
"else",
":",
"raise",
"Error",
"(",
"'unsupported gtype for set {0}, fundamental {1}'",
".",
"format",
"(",
"type_name",
"(",
"gtype",
")",
",",
"type_name",
"(",
"fundamental",
")",
")",
")"
] |
Set a GValue.
The value is converted to the type of the GValue, if possible, and
assigned.
|
[
"Set",
"a",
"GValue",
"."
] |
f4d9334d2e3085b4b058129f14ac17a7872b109b
|
https://github.com/libvips/pyvips/blob/f4d9334d2e3085b4b058129f14ac17a7872b109b/pyvips/gvalue.py#L139-L228
|
10,736
|
libvips/pyvips
|
pyvips/gvalue.py
|
GValue.get
|
def get(self):
"""Get the contents of a GValue.
The contents of the GValue are read out as a Python type.
"""
# 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.g_value_get_boolean(self.gvalue))
elif gtype == GValue.gint_type:
result = gobject_lib.g_value_get_int(self.gvalue)
elif gtype == GValue.guint64_type:
result = gobject_lib.g_value_get_uint64(self.gvalue)
elif gtype == GValue.gdouble_type:
result = gobject_lib.g_value_get_double(self.gvalue)
elif fundamental == GValue.genum_type:
return GValue.from_enum(gtype,
gobject_lib.g_value_get_enum(self.gvalue))
elif fundamental == GValue.gflags_type:
result = gobject_lib.g_value_get_flags(self.gvalue)
elif gtype == GValue.gstr_type:
pointer = gobject_lib.g_value_get_string(self.gvalue)
if pointer != ffi.NULL:
result = _to_string(pointer)
elif gtype == GValue.refstr_type:
psize = ffi.new('size_t *')
pointer = vips_lib.vips_value_get_ref_string(self.gvalue, psize)
# psize[0] will be number of bytes in string, but just assume it's
# NULL-terminated
result = _to_string(pointer)
elif gtype == GValue.image_type:
# g_value_get_object() will not add a ref ... that is
# held by the gvalue
go = gobject_lib.g_value_get_object(self.gvalue)
vi = ffi.cast('VipsImage *', go)
# we want a ref that will last with the life of the vimage:
# this ref is matched by the unref that's attached to finalize
# by Image()
gobject_lib.g_object_ref(go)
result = pyvips.Image(vi)
elif gtype == GValue.array_int_type:
pint = ffi.new('int *')
array = vips_lib.vips_value_get_array_int(self.gvalue, pint)
result = []
for i in range(0, pint[0]):
result.append(array[i])
elif gtype == GValue.array_double_type:
pint = ffi.new('int *')
array = vips_lib.vips_value_get_array_double(self.gvalue, pint)
result = []
for i in range(0, pint[0]):
result.append(array[i])
elif gtype == GValue.array_image_type:
pint = ffi.new('int *')
array = vips_lib.vips_value_get_array_image(self.gvalue, pint)
result = []
for i in range(0, pint[0]):
vi = array[i]
gobject_lib.g_object_ref(vi)
image = pyvips.Image(vi)
result.append(image)
elif gtype == GValue.blob_type:
psize = ffi.new('size_t *')
array = vips_lib.vips_value_get_blob(self.gvalue, psize)
buf = ffi.cast('char*', array)
result = ffi.unpack(buf, psize[0])
else:
raise Error('unsupported gtype for get {0}'.
format(type_name(gtype)))
return result
|
python
|
def get(self):
"""Get the contents of a GValue.
The contents of the GValue are read out as a Python type.
"""
# 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.g_value_get_boolean(self.gvalue))
elif gtype == GValue.gint_type:
result = gobject_lib.g_value_get_int(self.gvalue)
elif gtype == GValue.guint64_type:
result = gobject_lib.g_value_get_uint64(self.gvalue)
elif gtype == GValue.gdouble_type:
result = gobject_lib.g_value_get_double(self.gvalue)
elif fundamental == GValue.genum_type:
return GValue.from_enum(gtype,
gobject_lib.g_value_get_enum(self.gvalue))
elif fundamental == GValue.gflags_type:
result = gobject_lib.g_value_get_flags(self.gvalue)
elif gtype == GValue.gstr_type:
pointer = gobject_lib.g_value_get_string(self.gvalue)
if pointer != ffi.NULL:
result = _to_string(pointer)
elif gtype == GValue.refstr_type:
psize = ffi.new('size_t *')
pointer = vips_lib.vips_value_get_ref_string(self.gvalue, psize)
# psize[0] will be number of bytes in string, but just assume it's
# NULL-terminated
result = _to_string(pointer)
elif gtype == GValue.image_type:
# g_value_get_object() will not add a ref ... that is
# held by the gvalue
go = gobject_lib.g_value_get_object(self.gvalue)
vi = ffi.cast('VipsImage *', go)
# we want a ref that will last with the life of the vimage:
# this ref is matched by the unref that's attached to finalize
# by Image()
gobject_lib.g_object_ref(go)
result = pyvips.Image(vi)
elif gtype == GValue.array_int_type:
pint = ffi.new('int *')
array = vips_lib.vips_value_get_array_int(self.gvalue, pint)
result = []
for i in range(0, pint[0]):
result.append(array[i])
elif gtype == GValue.array_double_type:
pint = ffi.new('int *')
array = vips_lib.vips_value_get_array_double(self.gvalue, pint)
result = []
for i in range(0, pint[0]):
result.append(array[i])
elif gtype == GValue.array_image_type:
pint = ffi.new('int *')
array = vips_lib.vips_value_get_array_image(self.gvalue, pint)
result = []
for i in range(0, pint[0]):
vi = array[i]
gobject_lib.g_object_ref(vi)
image = pyvips.Image(vi)
result.append(image)
elif gtype == GValue.blob_type:
psize = ffi.new('size_t *')
array = vips_lib.vips_value_get_blob(self.gvalue, psize)
buf = ffi.cast('char*', array)
result = ffi.unpack(buf, psize[0])
else:
raise Error('unsupported gtype for get {0}'.
format(type_name(gtype)))
return result
|
[
"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",
".",
"g_value_get_boolean",
"(",
"self",
".",
"gvalue",
")",
")",
"elif",
"gtype",
"==",
"GValue",
".",
"gint_type",
":",
"result",
"=",
"gobject_lib",
".",
"g_value_get_int",
"(",
"self",
".",
"gvalue",
")",
"elif",
"gtype",
"==",
"GValue",
".",
"guint64_type",
":",
"result",
"=",
"gobject_lib",
".",
"g_value_get_uint64",
"(",
"self",
".",
"gvalue",
")",
"elif",
"gtype",
"==",
"GValue",
".",
"gdouble_type",
":",
"result",
"=",
"gobject_lib",
".",
"g_value_get_double",
"(",
"self",
".",
"gvalue",
")",
"elif",
"fundamental",
"==",
"GValue",
".",
"genum_type",
":",
"return",
"GValue",
".",
"from_enum",
"(",
"gtype",
",",
"gobject_lib",
".",
"g_value_get_enum",
"(",
"self",
".",
"gvalue",
")",
")",
"elif",
"fundamental",
"==",
"GValue",
".",
"gflags_type",
":",
"result",
"=",
"gobject_lib",
".",
"g_value_get_flags",
"(",
"self",
".",
"gvalue",
")",
"elif",
"gtype",
"==",
"GValue",
".",
"gstr_type",
":",
"pointer",
"=",
"gobject_lib",
".",
"g_value_get_string",
"(",
"self",
".",
"gvalue",
")",
"if",
"pointer",
"!=",
"ffi",
".",
"NULL",
":",
"result",
"=",
"_to_string",
"(",
"pointer",
")",
"elif",
"gtype",
"==",
"GValue",
".",
"refstr_type",
":",
"psize",
"=",
"ffi",
".",
"new",
"(",
"'size_t *'",
")",
"pointer",
"=",
"vips_lib",
".",
"vips_value_get_ref_string",
"(",
"self",
".",
"gvalue",
",",
"psize",
")",
"# psize[0] will be number of bytes in string, but just assume it's",
"# NULL-terminated",
"result",
"=",
"_to_string",
"(",
"pointer",
")",
"elif",
"gtype",
"==",
"GValue",
".",
"image_type",
":",
"# g_value_get_object() will not add a ref ... that is",
"# held by the gvalue",
"go",
"=",
"gobject_lib",
".",
"g_value_get_object",
"(",
"self",
".",
"gvalue",
")",
"vi",
"=",
"ffi",
".",
"cast",
"(",
"'VipsImage *'",
",",
"go",
")",
"# we want a ref that will last with the life of the vimage:",
"# this ref is matched by the unref that's attached to finalize",
"# by Image()",
"gobject_lib",
".",
"g_object_ref",
"(",
"go",
")",
"result",
"=",
"pyvips",
".",
"Image",
"(",
"vi",
")",
"elif",
"gtype",
"==",
"GValue",
".",
"array_int_type",
":",
"pint",
"=",
"ffi",
".",
"new",
"(",
"'int *'",
")",
"array",
"=",
"vips_lib",
".",
"vips_value_get_array_int",
"(",
"self",
".",
"gvalue",
",",
"pint",
")",
"result",
"=",
"[",
"]",
"for",
"i",
"in",
"range",
"(",
"0",
",",
"pint",
"[",
"0",
"]",
")",
":",
"result",
".",
"append",
"(",
"array",
"[",
"i",
"]",
")",
"elif",
"gtype",
"==",
"GValue",
".",
"array_double_type",
":",
"pint",
"=",
"ffi",
".",
"new",
"(",
"'int *'",
")",
"array",
"=",
"vips_lib",
".",
"vips_value_get_array_double",
"(",
"self",
".",
"gvalue",
",",
"pint",
")",
"result",
"=",
"[",
"]",
"for",
"i",
"in",
"range",
"(",
"0",
",",
"pint",
"[",
"0",
"]",
")",
":",
"result",
".",
"append",
"(",
"array",
"[",
"i",
"]",
")",
"elif",
"gtype",
"==",
"GValue",
".",
"array_image_type",
":",
"pint",
"=",
"ffi",
".",
"new",
"(",
"'int *'",
")",
"array",
"=",
"vips_lib",
".",
"vips_value_get_array_image",
"(",
"self",
".",
"gvalue",
",",
"pint",
")",
"result",
"=",
"[",
"]",
"for",
"i",
"in",
"range",
"(",
"0",
",",
"pint",
"[",
"0",
"]",
")",
":",
"vi",
"=",
"array",
"[",
"i",
"]",
"gobject_lib",
".",
"g_object_ref",
"(",
"vi",
")",
"image",
"=",
"pyvips",
".",
"Image",
"(",
"vi",
")",
"result",
".",
"append",
"(",
"image",
")",
"elif",
"gtype",
"==",
"GValue",
".",
"blob_type",
":",
"psize",
"=",
"ffi",
".",
"new",
"(",
"'size_t *'",
")",
"array",
"=",
"vips_lib",
".",
"vips_value_get_blob",
"(",
"self",
".",
"gvalue",
",",
"psize",
")",
"buf",
"=",
"ffi",
".",
"cast",
"(",
"'char*'",
",",
"array",
")",
"result",
"=",
"ffi",
".",
"unpack",
"(",
"buf",
",",
"psize",
"[",
"0",
"]",
")",
"else",
":",
"raise",
"Error",
"(",
"'unsupported gtype for get {0}'",
".",
"format",
"(",
"type_name",
"(",
"gtype",
")",
")",
")",
"return",
"result"
] |
Get the contents of a GValue.
The contents of the GValue are read out as a Python type.
|
[
"Get",
"the",
"contents",
"of",
"a",
"GValue",
"."
] |
f4d9334d2e3085b4b058129f14ac17a7872b109b
|
https://github.com/libvips/pyvips/blob/f4d9334d2e3085b4b058129f14ac17a7872b109b/pyvips/gvalue.py#L230-L314
|
10,737
|
libvips/pyvips
|
examples/cod.py
|
to_polar
|
def to_polar(image):
"""Transform image coordinates to polar.
The image is transformed so that it is wrapped around a point in the
centre. Vertical straight lines become circles or segments of circles,
horizontal straight lines become radial spokes.
"""
# 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.0 / scale
index = xy.polar()
# scale vertical axis to 360 degrees
index *= [1, image.height / 360.0]
return image.mapim(index)
|
python
|
def to_polar(image):
"""Transform image coordinates to polar.
The image is transformed so that it is wrapped around a point in the
centre. Vertical straight lines become circles or segments of circles,
horizontal straight lines become radial spokes.
"""
# 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.0 / scale
index = xy.polar()
# scale vertical axis to 360 degrees
index *= [1, image.height / 360.0]
return image.mapim(index)
|
[
"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.0",
"/",
"scale",
"index",
"=",
"xy",
".",
"polar",
"(",
")",
"# scale vertical axis to 360 degrees",
"index",
"*=",
"[",
"1",
",",
"image",
".",
"height",
"/",
"360.0",
"]",
"return",
"image",
".",
"mapim",
"(",
"index",
")"
] |
Transform image coordinates to polar.
The image is transformed so that it is wrapped around a point in the
centre. Vertical straight lines become circles or segments of circles,
horizontal straight lines become radial spokes.
|
[
"Transform",
"image",
"coordinates",
"to",
"polar",
"."
] |
f4d9334d2e3085b4b058129f14ac17a7872b109b
|
https://github.com/libvips/pyvips/blob/f4d9334d2e3085b4b058129f14ac17a7872b109b/examples/cod.py#L12-L30
|
10,738
|
libvips/pyvips
|
examples/cod.py
|
to_rectangular
|
def to_rectangular(image):
"""Transform image coordinates to rectangular.
The image is transformed so that it is unwrapped from a point in the
centre. Circles or segments of circles become vertical straight lines,
radial lines become horizontal lines.
"""
# 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.width)
index *= scale / 2.0
index += [image.width / 2.0, image.height / 2.0]
return image.mapim(index)
|
python
|
def to_rectangular(image):
"""Transform image coordinates to rectangular.
The image is transformed so that it is unwrapped from a point in the
centre. Circles or segments of circles become vertical straight lines,
radial lines become horizontal lines.
"""
# 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.width)
index *= scale / 2.0
index += [image.width / 2.0, image.height / 2.0]
return image.mapim(index)
|
[
"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",
".",
"width",
")",
"index",
"*=",
"scale",
"/",
"2.0",
"index",
"+=",
"[",
"image",
".",
"width",
"/",
"2.0",
",",
"image",
".",
"height",
"/",
"2.0",
"]",
"return",
"image",
".",
"mapim",
"(",
"index",
")"
] |
Transform image coordinates to rectangular.
The image is transformed so that it is unwrapped from a point in the
centre. Circles or segments of circles become vertical straight lines,
radial lines become horizontal lines.
|
[
"Transform",
"image",
"coordinates",
"to",
"rectangular",
"."
] |
f4d9334d2e3085b4b058129f14ac17a7872b109b
|
https://github.com/libvips/pyvips/blob/f4d9334d2e3085b4b058129f14ac17a7872b109b/examples/cod.py#L33-L51
|
10,739
|
libvips/pyvips
|
pyvips/error.py
|
_to_string
|
def _to_string(x):
"""Convert to a unicode string.
If x is a byte string, assume it is utf-8 and decode to a Python unicode
string. You must call this on text strings you get back from libvips.
"""
if x == ffi.NULL:
x = 'NULL'
else:
x = ffi.string(x)
if isinstance(x, byte_type):
x = x.decode('utf-8')
return x
|
python
|
def _to_string(x):
"""Convert to a unicode string.
If x is a byte string, assume it is utf-8 and decode to a Python unicode
string. You must call this on text strings you get back from libvips.
"""
if x == ffi.NULL:
x = 'NULL'
else:
x = ffi.string(x)
if isinstance(x, byte_type):
x = x.decode('utf-8')
return x
|
[
"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.
If x is a byte string, assume it is utf-8 and decode to a Python unicode
string. You must call this on text strings you get back from libvips.
|
[
"Convert",
"to",
"a",
"unicode",
"string",
"."
] |
f4d9334d2e3085b4b058129f14ac17a7872b109b
|
https://github.com/libvips/pyvips/blob/f4d9334d2e3085b4b058129f14ac17a7872b109b/pyvips/error.py#L33-L47
|
10,740
|
libvips/pyvips
|
pyvips/vinterpolate.py
|
Interpolate.new
|
def new(name):
"""Make a new interpolator by name.
Make a new interpolator from the libvips class nickname. For example::
inter = pyvips.Interpolator.new('bicubic')
You can get a list of all supported interpolators from the command-line
with::
$ vips -l interpolate
See for example :meth:`.affine`.
"""
# 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)
|
python
|
def new(name):
"""Make a new interpolator by name.
Make a new interpolator from the libvips class nickname. For example::
inter = pyvips.Interpolator.new('bicubic')
You can get a list of all supported interpolators from the command-line
with::
$ vips -l interpolate
See for example :meth:`.affine`.
"""
# 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)
|
[
"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.
Make a new interpolator from the libvips class nickname. For example::
inter = pyvips.Interpolator.new('bicubic')
You can get a list of all supported interpolators from the command-line
with::
$ vips -l interpolate
See for example :meth:`.affine`.
|
[
"Make",
"a",
"new",
"interpolator",
"by",
"name",
"."
] |
f4d9334d2e3085b4b058129f14ac17a7872b109b
|
https://github.com/libvips/pyvips/blob/f4d9334d2e3085b4b058129f14ac17a7872b109b/pyvips/vinterpolate.py#L21-L44
|
10,741
|
libvips/pyvips
|
pyvips/vimage.py
|
_run_cmplx
|
def _run_cmplx(fn, image):
"""Run a complex function on a non-complex image.
The image needs to be complex, or have an even number of bands. The input
can be int, the output is always float or double.
"""
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 != 'double':
image = image.cast('float')
if image.format == 'double':
new_format = 'dpcomplex'
else:
new_format = 'complex'
image = image.copy(format=new_format, bands=image.bands / 2)
image = fn(image)
if original_format != 'complex' and original_format != 'dpcomplex':
if image.format == 'dpcomplex':
new_format = 'double'
else:
new_format = 'float'
image = image.copy(format=new_format, bands=image.bands * 2)
return image
|
python
|
def _run_cmplx(fn, image):
"""Run a complex function on a non-complex image.
The image needs to be complex, or have an even number of bands. The input
can be int, the output is always float or double.
"""
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 != 'double':
image = image.cast('float')
if image.format == 'double':
new_format = 'dpcomplex'
else:
new_format = 'complex'
image = image.copy(format=new_format, bands=image.bands / 2)
image = fn(image)
if original_format != 'complex' and original_format != 'dpcomplex':
if image.format == 'dpcomplex':
new_format = 'double'
else:
new_format = 'float'
image = image.copy(format=new_format, bands=image.bands * 2)
return image
|
[
"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",
"!=",
"'double'",
":",
"image",
"=",
"image",
".",
"cast",
"(",
"'float'",
")",
"if",
"image",
".",
"format",
"==",
"'double'",
":",
"new_format",
"=",
"'dpcomplex'",
"else",
":",
"new_format",
"=",
"'complex'",
"image",
"=",
"image",
".",
"copy",
"(",
"format",
"=",
"new_format",
",",
"bands",
"=",
"image",
".",
"bands",
"/",
"2",
")",
"image",
"=",
"fn",
"(",
"image",
")",
"if",
"original_format",
"!=",
"'complex'",
"and",
"original_format",
"!=",
"'dpcomplex'",
":",
"if",
"image",
".",
"format",
"==",
"'dpcomplex'",
":",
"new_format",
"=",
"'double'",
"else",
":",
"new_format",
"=",
"'float'",
"image",
"=",
"image",
".",
"copy",
"(",
"format",
"=",
"new_format",
",",
"bands",
"=",
"image",
".",
"bands",
"*",
"2",
")",
"return",
"image"
] |
Run a complex function on a non-complex image.
The image needs to be complex, or have an even number of bands. The input
can be int, the output is always float or double.
|
[
"Run",
"a",
"complex",
"function",
"on",
"a",
"non",
"-",
"complex",
"image",
"."
] |
f4d9334d2e3085b4b058129f14ac17a7872b109b
|
https://github.com/libvips/pyvips/blob/f4d9334d2e3085b4b058129f14ac17a7872b109b/pyvips/vimage.py#L50-L82
|
10,742
|
libvips/pyvips
|
pyvips/base.py
|
get_suffixes
|
def get_suffixes():
"""Get a list of all the filename suffixes supported by libvips.
Returns:
[string]
"""
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.append(name)
glib_lib.g_free(array[i])
i += 1
glib_lib.g_free(array)
return names
|
python
|
def get_suffixes():
"""Get a list of all the filename suffixes supported by libvips.
Returns:
[string]
"""
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.append(name)
glib_lib.g_free(array[i])
i += 1
glib_lib.g_free(array)
return names
|
[
"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",
".",
"append",
"(",
"name",
")",
"glib_lib",
".",
"g_free",
"(",
"array",
"[",
"i",
"]",
")",
"i",
"+=",
"1",
"glib_lib",
".",
"g_free",
"(",
"array",
")",
"return",
"names"
] |
Get a list of all the filename suffixes supported by libvips.
Returns:
[string]
|
[
"Get",
"a",
"list",
"of",
"all",
"the",
"filename",
"suffixes",
"supported",
"by",
"libvips",
"."
] |
f4d9334d2e3085b4b058129f14ac17a7872b109b
|
https://github.com/libvips/pyvips/blob/f4d9334d2e3085b4b058129f14ac17a7872b109b/pyvips/base.py#L39-L60
|
10,743
|
libvips/pyvips
|
pyvips/base.py
|
at_least_libvips
|
def at_least_libvips(x, y):
"""Is this at least libvips x.y?"""
major = version(0)
minor = version(1)
return major > x or (major == x and minor >= y)
|
python
|
def at_least_libvips(x, y):
"""Is this at least libvips x.y?"""
major = version(0)
minor = version(1)
return major > x or (major == x and minor >= y)
|
[
"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?
|
[
"Is",
"this",
"at",
"least",
"libvips",
"x",
".",
"y?"
] |
f4d9334d2e3085b4b058129f14ac17a7872b109b
|
https://github.com/libvips/pyvips/blob/f4d9334d2e3085b4b058129f14ac17a7872b109b/pyvips/base.py#L65-L71
|
10,744
|
libvips/pyvips
|
pyvips/base.py
|
type_map
|
def type_map(gtype, fn):
"""Map fn over all child types of gtype."""
cb = ffi.callback('VipsTypeMap2Fn', fn)
return vips_lib.vips_type_map(gtype, cb, ffi.NULL, ffi.NULL)
|
python
|
def type_map(gtype, fn):
"""Map fn over all child types of gtype."""
cb = ffi.callback('VipsTypeMap2Fn', fn)
return vips_lib.vips_type_map(gtype, cb, ffi.NULL, ffi.NULL)
|
[
"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.
|
[
"Map",
"fn",
"over",
"all",
"child",
"types",
"of",
"gtype",
"."
] |
f4d9334d2e3085b4b058129f14ac17a7872b109b
|
https://github.com/libvips/pyvips/blob/f4d9334d2e3085b4b058129f14ac17a7872b109b/pyvips/base.py#L110-L114
|
10,745
|
borntyping/python-colorlog
|
colorlog/logging.py
|
basicConfig
|
def basicConfig(**kwargs):
"""Call ``logging.basicConfig`` and override the formatter it creates."""
logging.basicConfig(**kwargs)
logging._acquireLock()
try:
stream = logging.root.handlers[0]
stream.setFormatter(
ColoredFormatter(
fmt=kwargs.get('format', BASIC_FORMAT),
datefmt=kwargs.get('datefmt', None)))
finally:
logging._releaseLock()
|
python
|
def basicConfig(**kwargs):
"""Call ``logging.basicConfig`` and override the formatter it creates."""
logging.basicConfig(**kwargs)
logging._acquireLock()
try:
stream = logging.root.handlers[0]
stream.setFormatter(
ColoredFormatter(
fmt=kwargs.get('format', BASIC_FORMAT),
datefmt=kwargs.get('datefmt', None)))
finally:
logging._releaseLock()
|
[
"def",
"basicConfig",
"(",
"*",
"*",
"kwargs",
")",
":",
"logging",
".",
"basicConfig",
"(",
"*",
"*",
"kwargs",
")",
"logging",
".",
"_acquireLock",
"(",
")",
"try",
":",
"stream",
"=",
"logging",
".",
"root",
".",
"handlers",
"[",
"0",
"]",
"stream",
".",
"setFormatter",
"(",
"ColoredFormatter",
"(",
"fmt",
"=",
"kwargs",
".",
"get",
"(",
"'format'",
",",
"BASIC_FORMAT",
")",
",",
"datefmt",
"=",
"kwargs",
".",
"get",
"(",
"'datefmt'",
",",
"None",
")",
")",
")",
"finally",
":",
"logging",
".",
"_releaseLock",
"(",
")"
] |
Call ``logging.basicConfig`` and override the formatter it creates.
|
[
"Call",
"logging",
".",
"basicConfig",
"and",
"override",
"the",
"formatter",
"it",
"creates",
"."
] |
d2be1e0e9bff0ceb288c6a6381a6d12cf550e1e7
|
https://github.com/borntyping/python-colorlog/blob/d2be1e0e9bff0ceb288c6a6381a6d12cf550e1e7/colorlog/logging.py#L13-L24
|
10,746
|
borntyping/python-colorlog
|
colorlog/logging.py
|
ensure_configured
|
def ensure_configured(func):
"""Modify a function to call ``basicConfig`` first if no handlers exist."""
@functools.wraps(func)
def wrapper(*args, **kwargs):
if len(logging.root.handlers) == 0:
basicConfig()
return func(*args, **kwargs)
return wrapper
|
python
|
def ensure_configured(func):
"""Modify a function to call ``basicConfig`` first if no handlers exist."""
@functools.wraps(func)
def wrapper(*args, **kwargs):
if len(logging.root.handlers) == 0:
basicConfig()
return func(*args, **kwargs)
return wrapper
|
[
"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.
|
[
"Modify",
"a",
"function",
"to",
"call",
"basicConfig",
"first",
"if",
"no",
"handlers",
"exist",
"."
] |
d2be1e0e9bff0ceb288c6a6381a6d12cf550e1e7
|
https://github.com/borntyping/python-colorlog/blob/d2be1e0e9bff0ceb288c6a6381a6d12cf550e1e7/colorlog/logging.py#L27-L34
|
10,747
|
borntyping/python-colorlog
|
colorlog/colorlog.py
|
TTYColoredFormatter.color
|
def color(self, log_colors, level_name):
"""Only returns colors if STDOUT is a TTY."""
if not self.stream.isatty():
log_colors = {}
return ColoredFormatter.color(self, log_colors, level_name)
|
python
|
def color(self, log_colors, level_name):
"""Only returns colors if STDOUT is a TTY."""
if not self.stream.isatty():
log_colors = {}
return ColoredFormatter.color(self, log_colors, level_name)
|
[
"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.
|
[
"Only",
"returns",
"colors",
"if",
"STDOUT",
"is",
"a",
"TTY",
"."
] |
d2be1e0e9bff0ceb288c6a6381a6d12cf550e1e7
|
https://github.com/borntyping/python-colorlog/blob/d2be1e0e9bff0ceb288c6a6381a6d12cf550e1e7/colorlog/colorlog.py#L207-L211
|
10,748
|
borntyping/python-colorlog
|
doc/example.py
|
setup_logger
|
def setup_logger():
"""Return a logger with a default ColoredFormatter."""
formatter = ColoredFormatter(
"%(log_color)s%(levelname)-8s%(reset)s %(blue)s%(message)s",
datefmt=None,
reset=True,
log_colors={
'DEBUG': 'cyan',
'INFO': 'green',
'WARNING': 'yellow',
'ERROR': 'red',
'CRITICAL': 'red',
}
)
logger = logging.getLogger('example')
handler = logging.StreamHandler()
handler.setFormatter(formatter)
logger.addHandler(handler)
logger.setLevel(logging.DEBUG)
return logger
|
python
|
def setup_logger():
"""Return a logger with a default ColoredFormatter."""
formatter = ColoredFormatter(
"%(log_color)s%(levelname)-8s%(reset)s %(blue)s%(message)s",
datefmt=None,
reset=True,
log_colors={
'DEBUG': 'cyan',
'INFO': 'green',
'WARNING': 'yellow',
'ERROR': 'red',
'CRITICAL': 'red',
}
)
logger = logging.getLogger('example')
handler = logging.StreamHandler()
handler.setFormatter(formatter)
logger.addHandler(handler)
logger.setLevel(logging.DEBUG)
return logger
|
[
"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'",
",",
"'WARNING'",
":",
"'yellow'",
",",
"'ERROR'",
":",
"'red'",
",",
"'CRITICAL'",
":",
"'red'",
",",
"}",
")",
"logger",
"=",
"logging",
".",
"getLogger",
"(",
"'example'",
")",
"handler",
"=",
"logging",
".",
"StreamHandler",
"(",
")",
"handler",
".",
"setFormatter",
"(",
"formatter",
")",
"logger",
".",
"addHandler",
"(",
"handler",
")",
"logger",
".",
"setLevel",
"(",
"logging",
".",
"DEBUG",
")",
"return",
"logger"
] |
Return a logger with a default ColoredFormatter.
|
[
"Return",
"a",
"logger",
"with",
"a",
"default",
"ColoredFormatter",
"."
] |
d2be1e0e9bff0ceb288c6a6381a6d12cf550e1e7
|
https://github.com/borntyping/python-colorlog/blob/d2be1e0e9bff0ceb288c6a6381a6d12cf550e1e7/doc/example.py#L8-L29
|
10,749
|
ralphbean/taskw
|
taskw/warrior.py
|
TaskWarriorBase._extract_annotations_from_task
|
def _extract_annotations_from_task(self, task):
""" Removes annotations from a task and returns a list of annotations
"""
annotations = list()
if 'annotations' in task:
existing_annotations = task.pop('annotations')
for v in existing_annotations:
if isinstance(v, dict):
annotations.append(v['description'])
else:
annotations.append(v)
for key in list(task.keys()):
if key.startswith('annotation_'):
annotations.append(task[key])
del(task[key])
return annotations
|
python
|
def _extract_annotations_from_task(self, task):
""" Removes annotations from a task and returns a list of annotations
"""
annotations = list()
if 'annotations' in task:
existing_annotations = task.pop('annotations')
for v in existing_annotations:
if isinstance(v, dict):
annotations.append(v['description'])
else:
annotations.append(v)
for key in list(task.keys()):
if key.startswith('annotation_'):
annotations.append(task[key])
del(task[key])
return annotations
|
[
"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",
")",
":",
"annotations",
".",
"append",
"(",
"v",
"[",
"'description'",
"]",
")",
"else",
":",
"annotations",
".",
"append",
"(",
"v",
")",
"for",
"key",
"in",
"list",
"(",
"task",
".",
"keys",
"(",
")",
")",
":",
"if",
"key",
".",
"startswith",
"(",
"'annotation_'",
")",
":",
"annotations",
".",
"append",
"(",
"task",
"[",
"key",
"]",
")",
"del",
"(",
"task",
"[",
"key",
"]",
")",
"return",
"annotations"
] |
Removes annotations from a task and returns a list of annotations
|
[
"Removes",
"annotations",
"from",
"a",
"task",
"and",
"returns",
"a",
"list",
"of",
"annotations"
] |
11e2f9132eaedd157f514538de9b5f3b69c30a52
|
https://github.com/ralphbean/taskw/blob/11e2f9132eaedd157f514538de9b5f3b69c30a52/taskw/warrior.py#L94-L111
|
10,750
|
ralphbean/taskw
|
taskw/warrior.py
|
TaskWarriorDirect.task_done
|
def task_done(self, **kw):
"""
Marks a pending task as done, optionally specifying a completion
date with the 'end' argument.
"""
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)
|
python
|
def task_done(self, **kw):
"""
Marks a pending task as done, optionally specifying a completion
date with the 'end' argument.
"""
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)
|
[
"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",
")"
] |
Marks a pending task as done, optionally specifying a completion
date with the 'end' argument.
|
[
"Marks",
"a",
"pending",
"task",
"as",
"done",
"optionally",
"specifying",
"a",
"completion",
"date",
"with",
"the",
"end",
"argument",
"."
] |
11e2f9132eaedd157f514538de9b5f3b69c30a52
|
https://github.com/ralphbean/taskw/blob/11e2f9132eaedd157f514538de9b5f3b69c30a52/taskw/warrior.py#L289-L298
|
10,751
|
ralphbean/taskw
|
taskw/warrior.py
|
TaskWarriorDirect.task_delete
|
def task_delete(self, **kw):
"""
Marks a task as deleted, optionally specifying a completion
date with the 'end' argument.
"""
def validate(task):
if task['status'] == Status.DELETED:
raise ValueError("Task is already deleted.")
return self._task_change_status(Status.DELETED, validate, **kw)
|
python
|
def task_delete(self, **kw):
"""
Marks a task as deleted, optionally specifying a completion
date with the 'end' argument.
"""
def validate(task):
if task['status'] == Status.DELETED:
raise ValueError("Task is already deleted.")
return self._task_change_status(Status.DELETED, validate, **kw)
|
[
"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",
")"
] |
Marks a task as deleted, optionally specifying a completion
date with the 'end' argument.
|
[
"Marks",
"a",
"task",
"as",
"deleted",
"optionally",
"specifying",
"a",
"completion",
"date",
"with",
"the",
"end",
"argument",
"."
] |
11e2f9132eaedd157f514538de9b5f3b69c30a52
|
https://github.com/ralphbean/taskw/blob/11e2f9132eaedd157f514538de9b5f3b69c30a52/taskw/warrior.py#L319-L328
|
10,752
|
ralphbean/taskw
|
taskw/warrior.py
|
TaskWarriorShellout._execute
|
def _execute(self, *args):
""" Execute a given taskwarrior command with arguments
Returns a 2-tuple of stdout and stderr (respectively).
"""
command = (
[
'task',
'rc:%s' % self.config_filename,
]
+ self.get_configuration_override_args()
+ [six.text_type(arg) for arg in args]
)
# subprocess is expecting bytestrings only, so nuke unicode if present
# and remove control characters
for i in range(len(command)):
if isinstance(command[i], six.text_type):
command[i] = (
taskw.utils.clean_ctrl_chars(command[i].encode('utf-8')))
try:
proc = subprocess.Popen(
command,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
)
stdout, stderr = proc.communicate()
except OSError as e:
if e.errno == errno.ENOENT:
raise OSError("Unable to find the 'task' command-line tool.")
raise
if proc.returncode != 0:
raise TaskwarriorError(command, stderr, stdout, proc.returncode)
# We should get bytes from the outside world. Turn those into unicode
# as soon as we can.
# Everything going into and coming out of taskwarrior *should* be
# utf-8, but there are weird edge cases where something totally unusual
# made it in.. so we need to be able to handle (or at least try to
# handle) whatever. Kitchen tries its best.
try:
stdout = stdout.decode(self.config.get('encoding', 'utf-8'))
except UnicodeDecodeError as e:
stdout = kitchen.text.converters.to_unicode(stdout)
try:
stderr = stderr.decode(self.config.get('encoding', 'utf-8'))
except UnicodeDecodeError as e:
stderr = kitchen.text.converters.to_unicode(stderr)
# strip any crazy terminal escape characters like bells, backspaces,
# and form feeds
for c in ('\a', '\b', '\f', ''):
stdout = stdout.replace(c, '?')
stderr = stderr.replace(c, '?')
return stdout, stderr
|
python
|
def _execute(self, *args):
""" Execute a given taskwarrior command with arguments
Returns a 2-tuple of stdout and stderr (respectively).
"""
command = (
[
'task',
'rc:%s' % self.config_filename,
]
+ self.get_configuration_override_args()
+ [six.text_type(arg) for arg in args]
)
# subprocess is expecting bytestrings only, so nuke unicode if present
# and remove control characters
for i in range(len(command)):
if isinstance(command[i], six.text_type):
command[i] = (
taskw.utils.clean_ctrl_chars(command[i].encode('utf-8')))
try:
proc = subprocess.Popen(
command,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
)
stdout, stderr = proc.communicate()
except OSError as e:
if e.errno == errno.ENOENT:
raise OSError("Unable to find the 'task' command-line tool.")
raise
if proc.returncode != 0:
raise TaskwarriorError(command, stderr, stdout, proc.returncode)
# We should get bytes from the outside world. Turn those into unicode
# as soon as we can.
# Everything going into and coming out of taskwarrior *should* be
# utf-8, but there are weird edge cases where something totally unusual
# made it in.. so we need to be able to handle (or at least try to
# handle) whatever. Kitchen tries its best.
try:
stdout = stdout.decode(self.config.get('encoding', 'utf-8'))
except UnicodeDecodeError as e:
stdout = kitchen.text.converters.to_unicode(stdout)
try:
stderr = stderr.decode(self.config.get('encoding', 'utf-8'))
except UnicodeDecodeError as e:
stderr = kitchen.text.converters.to_unicode(stderr)
# strip any crazy terminal escape characters like bells, backspaces,
# and form feeds
for c in ('\a', '\b', '\f', ''):
stdout = stdout.replace(c, '?')
stderr = stderr.replace(c, '?')
return stdout, stderr
|
[
"def",
"_execute",
"(",
"self",
",",
"*",
"args",
")",
":",
"command",
"=",
"(",
"[",
"'task'",
",",
"'rc:%s'",
"%",
"self",
".",
"config_filename",
",",
"]",
"+",
"self",
".",
"get_configuration_override_args",
"(",
")",
"+",
"[",
"six",
".",
"text_type",
"(",
"arg",
")",
"for",
"arg",
"in",
"args",
"]",
")",
"# subprocess is expecting bytestrings only, so nuke unicode if present",
"# and remove control characters",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"command",
")",
")",
":",
"if",
"isinstance",
"(",
"command",
"[",
"i",
"]",
",",
"six",
".",
"text_type",
")",
":",
"command",
"[",
"i",
"]",
"=",
"(",
"taskw",
".",
"utils",
".",
"clean_ctrl_chars",
"(",
"command",
"[",
"i",
"]",
".",
"encode",
"(",
"'utf-8'",
")",
")",
")",
"try",
":",
"proc",
"=",
"subprocess",
".",
"Popen",
"(",
"command",
",",
"stdout",
"=",
"subprocess",
".",
"PIPE",
",",
"stderr",
"=",
"subprocess",
".",
"PIPE",
",",
")",
"stdout",
",",
"stderr",
"=",
"proc",
".",
"communicate",
"(",
")",
"except",
"OSError",
"as",
"e",
":",
"if",
"e",
".",
"errno",
"==",
"errno",
".",
"ENOENT",
":",
"raise",
"OSError",
"(",
"\"Unable to find the 'task' command-line tool.\"",
")",
"raise",
"if",
"proc",
".",
"returncode",
"!=",
"0",
":",
"raise",
"TaskwarriorError",
"(",
"command",
",",
"stderr",
",",
"stdout",
",",
"proc",
".",
"returncode",
")",
"# We should get bytes from the outside world. Turn those into unicode",
"# as soon as we can.",
"# Everything going into and coming out of taskwarrior *should* be",
"# utf-8, but there are weird edge cases where something totally unusual",
"# made it in.. so we need to be able to handle (or at least try to",
"# handle) whatever. Kitchen tries its best.",
"try",
":",
"stdout",
"=",
"stdout",
".",
"decode",
"(",
"self",
".",
"config",
".",
"get",
"(",
"'encoding'",
",",
"'utf-8'",
")",
")",
"except",
"UnicodeDecodeError",
"as",
"e",
":",
"stdout",
"=",
"kitchen",
".",
"text",
".",
"converters",
".",
"to_unicode",
"(",
"stdout",
")",
"try",
":",
"stderr",
"=",
"stderr",
".",
"decode",
"(",
"self",
".",
"config",
".",
"get",
"(",
"'encoding'",
",",
"'utf-8'",
")",
")",
"except",
"UnicodeDecodeError",
"as",
"e",
":",
"stderr",
"=",
"kitchen",
".",
"text",
".",
"converters",
".",
"to_unicode",
"(",
"stderr",
")",
"# strip any crazy terminal escape characters like bells, backspaces,",
"# and form feeds",
"for",
"c",
"in",
"(",
"'\\a'",
",",
"'\\b'",
",",
"'\\f'",
",",
"'\u001b'",
")",
":",
"stdout",
"=",
"stdout",
".",
"replace",
"(",
"c",
",",
"'?'",
")",
"stderr",
"=",
"stderr",
".",
"replace",
"(",
"c",
",",
"'?'",
")",
"return",
"stdout",
",",
"stderr"
] |
Execute a given taskwarrior command with arguments
Returns a 2-tuple of stdout and stderr (respectively).
|
[
"Execute",
"a",
"given",
"taskwarrior",
"command",
"with",
"arguments"
] |
11e2f9132eaedd157f514538de9b5f3b69c30a52
|
https://github.com/ralphbean/taskw/blob/11e2f9132eaedd157f514538de9b5f3b69c30a52/taskw/warrior.py#L441-L499
|
10,753
|
ralphbean/taskw
|
taskw/warrior.py
|
TaskWarriorShellout.load_tasks
|
def load_tasks(self, command='all'):
""" Returns a dictionary of tasks for a list of command."""
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
# Here we merge the waiting list back into the pending list.
if 'pending' in results:
results['pending'].extend(
self._get_task_objects('status:waiting', 'export'))
return results
|
python
|
def load_tasks(self, command='all'):
""" Returns a dictionary of tasks for a list of command."""
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
# Here we merge the waiting list back into the pending list.
if 'pending' in results:
results['pending'].extend(
self._get_task_objects('status:waiting', 'export'))
return results
|
[
"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",
"# Here we merge the waiting list back into the pending list.",
"if",
"'pending'",
"in",
"results",
":",
"results",
"[",
"'pending'",
"]",
".",
"extend",
"(",
"self",
".",
"_get_task_objects",
"(",
"'status:waiting'",
",",
"'export'",
")",
")",
"return",
"results"
] |
Returns a dictionary of tasks for a list of command.
|
[
"Returns",
"a",
"dictionary",
"of",
"tasks",
"for",
"a",
"list",
"of",
"command",
"."
] |
11e2f9132eaedd157f514538de9b5f3b69c30a52
|
https://github.com/ralphbean/taskw/blob/11e2f9132eaedd157f514538de9b5f3b69c30a52/taskw/warrior.py#L572-L586
|
10,754
|
ralphbean/taskw
|
taskw/warrior.py
|
TaskWarriorShellout.filter_tasks
|
def filter_tasks(self, filter_dict):
""" Return a filtered list of tasks from taskwarrior.
Filter dict should be a dictionary mapping filter constraints
with their values. For example, to return only pending tasks,
you could use::
{'status': 'pending'}
Or, to return tasks that have the word "Abjad" in their description
that are also pending::
{
'status': 'pending',
'description.contains': 'Abjad',
}
Filters can be quite complex, and are documented on Taskwarrior's
website.
"""
query_args = taskw.utils.encode_query(filter_dict, self.get_version())
return self._get_task_objects(
'export',
*query_args
)
|
python
|
def filter_tasks(self, filter_dict):
""" Return a filtered list of tasks from taskwarrior.
Filter dict should be a dictionary mapping filter constraints
with their values. For example, to return only pending tasks,
you could use::
{'status': 'pending'}
Or, to return tasks that have the word "Abjad" in their description
that are also pending::
{
'status': 'pending',
'description.contains': 'Abjad',
}
Filters can be quite complex, and are documented on Taskwarrior's
website.
"""
query_args = taskw.utils.encode_query(filter_dict, self.get_version())
return self._get_task_objects(
'export',
*query_args
)
|
[
"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.
Filter dict should be a dictionary mapping filter constraints
with their values. For example, to return only pending tasks,
you could use::
{'status': 'pending'}
Or, to return tasks that have the word "Abjad" in their description
that are also pending::
{
'status': 'pending',
'description.contains': 'Abjad',
}
Filters can be quite complex, and are documented on Taskwarrior's
website.
|
[
"Return",
"a",
"filtered",
"list",
"of",
"tasks",
"from",
"taskwarrior",
"."
] |
11e2f9132eaedd157f514538de9b5f3b69c30a52
|
https://github.com/ralphbean/taskw/blob/11e2f9132eaedd157f514538de9b5f3b69c30a52/taskw/warrior.py#L588-L613
|
10,755
|
ralphbean/taskw
|
taskw/warrior.py
|
TaskWarriorShellout.task_annotate
|
def task_annotate(self, task, annotation):
""" Annotates a task. """
self._execute(
task['uuid'],
'annotate',
'--',
annotation
)
id, annotated_task = self.get_task(uuid=task[six.u('uuid')])
return annotated_task
|
python
|
def task_annotate(self, task, annotation):
""" Annotates a task. """
self._execute(
task['uuid'],
'annotate',
'--',
annotation
)
id, annotated_task = self.get_task(uuid=task[six.u('uuid')])
return annotated_task
|
[
"def",
"task_annotate",
"(",
"self",
",",
"task",
",",
"annotation",
")",
":",
"self",
".",
"_execute",
"(",
"task",
"[",
"'uuid'",
"]",
",",
"'annotate'",
",",
"'--'",
",",
"annotation",
")",
"id",
",",
"annotated_task",
"=",
"self",
".",
"get_task",
"(",
"uuid",
"=",
"task",
"[",
"six",
".",
"u",
"(",
"'uuid'",
")",
"]",
")",
"return",
"annotated_task"
] |
Annotates a task.
|
[
"Annotates",
"a",
"task",
"."
] |
11e2f9132eaedd157f514538de9b5f3b69c30a52
|
https://github.com/ralphbean/taskw/blob/11e2f9132eaedd157f514538de9b5f3b69c30a52/taskw/warrior.py#L710-L719
|
10,756
|
ralphbean/taskw
|
taskw/warrior.py
|
TaskWarriorShellout.task_denotate
|
def task_denotate(self, task, annotation):
""" Removes an annotation from a task. """
self._execute(
task['uuid'],
'denotate',
'--',
annotation
)
id, denotated_task = self.get_task(uuid=task[six.u('uuid')])
return denotated_task
|
python
|
def task_denotate(self, task, annotation):
""" Removes an annotation from a task. """
self._execute(
task['uuid'],
'denotate',
'--',
annotation
)
id, denotated_task = self.get_task(uuid=task[six.u('uuid')])
return denotated_task
|
[
"def",
"task_denotate",
"(",
"self",
",",
"task",
",",
"annotation",
")",
":",
"self",
".",
"_execute",
"(",
"task",
"[",
"'uuid'",
"]",
",",
"'denotate'",
",",
"'--'",
",",
"annotation",
")",
"id",
",",
"denotated_task",
"=",
"self",
".",
"get_task",
"(",
"uuid",
"=",
"task",
"[",
"six",
".",
"u",
"(",
"'uuid'",
")",
"]",
")",
"return",
"denotated_task"
] |
Removes an annotation from a task.
|
[
"Removes",
"an",
"annotation",
"from",
"a",
"task",
"."
] |
11e2f9132eaedd157f514538de9b5f3b69c30a52
|
https://github.com/ralphbean/taskw/blob/11e2f9132eaedd157f514538de9b5f3b69c30a52/taskw/warrior.py#L721-L730
|
10,757
|
ralphbean/taskw
|
taskw/warrior.py
|
TaskWarriorShellout.task_delete
|
def task_delete(self, **kw):
""" Marks a task as deleted. """
id, task = self.get_task(**kw)
if task['status'] == Status.DELETED:
raise ValueError("Task is already deleted.")
self._execute(id, 'delete')
return self.get_task(uuid=task['uuid'])[1]
|
python
|
def task_delete(self, **kw):
""" Marks a task as deleted. """
id, task = self.get_task(**kw)
if task['status'] == Status.DELETED:
raise ValueError("Task is already deleted.")
self._execute(id, 'delete')
return self.get_task(uuid=task['uuid'])[1]
|
[
"def",
"task_delete",
"(",
"self",
",",
"*",
"*",
"kw",
")",
":",
"id",
",",
"task",
"=",
"self",
".",
"get_task",
"(",
"*",
"*",
"kw",
")",
"if",
"task",
"[",
"'status'",
"]",
"==",
"Status",
".",
"DELETED",
":",
"raise",
"ValueError",
"(",
"\"Task is already deleted.\"",
")",
"self",
".",
"_execute",
"(",
"id",
",",
"'delete'",
")",
"return",
"self",
".",
"get_task",
"(",
"uuid",
"=",
"task",
"[",
"'uuid'",
"]",
")",
"[",
"1",
"]"
] |
Marks a task as deleted.
|
[
"Marks",
"a",
"task",
"as",
"deleted",
"."
] |
11e2f9132eaedd157f514538de9b5f3b69c30a52
|
https://github.com/ralphbean/taskw/blob/11e2f9132eaedd157f514538de9b5f3b69c30a52/taskw/warrior.py#L816-L825
|
10,758
|
ralphbean/taskw
|
taskw/warrior.py
|
TaskWarriorShellout.task_start
|
def task_start(self, **kw):
""" Marks a task as started. """
id, task = self.get_task(**kw)
self._execute(id, 'start')
return self.get_task(uuid=task['uuid'])[1]
|
python
|
def task_start(self, **kw):
""" Marks a task as started. """
id, task = self.get_task(**kw)
self._execute(id, 'start')
return self.get_task(uuid=task['uuid'])[1]
|
[
"def",
"task_start",
"(",
"self",
",",
"*",
"*",
"kw",
")",
":",
"id",
",",
"task",
"=",
"self",
".",
"get_task",
"(",
"*",
"*",
"kw",
")",
"self",
".",
"_execute",
"(",
"id",
",",
"'start'",
")",
"return",
"self",
".",
"get_task",
"(",
"uuid",
"=",
"task",
"[",
"'uuid'",
"]",
")",
"[",
"1",
"]"
] |
Marks a task as started.
|
[
"Marks",
"a",
"task",
"as",
"started",
"."
] |
11e2f9132eaedd157f514538de9b5f3b69c30a52
|
https://github.com/ralphbean/taskw/blob/11e2f9132eaedd157f514538de9b5f3b69c30a52/taskw/warrior.py#L827-L833
|
10,759
|
ralphbean/taskw
|
taskw/warrior.py
|
TaskWarriorShellout.task_stop
|
def task_stop(self, **kw):
""" Marks a task as stopped. """
id, task = self.get_task(**kw)
self._execute(id, 'stop')
return self.get_task(uuid=task['uuid'])[1]
|
python
|
def task_stop(self, **kw):
""" Marks a task as stopped. """
id, task = self.get_task(**kw)
self._execute(id, 'stop')
return self.get_task(uuid=task['uuid'])[1]
|
[
"def",
"task_stop",
"(",
"self",
",",
"*",
"*",
"kw",
")",
":",
"id",
",",
"task",
"=",
"self",
".",
"get_task",
"(",
"*",
"*",
"kw",
")",
"self",
".",
"_execute",
"(",
"id",
",",
"'stop'",
")",
"return",
"self",
".",
"get_task",
"(",
"uuid",
"=",
"task",
"[",
"'uuid'",
"]",
")",
"[",
"1",
"]"
] |
Marks a task as stopped.
|
[
"Marks",
"a",
"task",
"as",
"stopped",
"."
] |
11e2f9132eaedd157f514538de9b5f3b69c30a52
|
https://github.com/ralphbean/taskw/blob/11e2f9132eaedd157f514538de9b5f3b69c30a52/taskw/warrior.py#L835-L841
|
10,760
|
ralphbean/taskw
|
taskw/warrior.py
|
Status.to_file
|
def to_file(cls, status):
""" Returns the file in which this task is stored. """
return {
Status.PENDING: DataFile.PENDING,
Status.WAITING: DataFile.PENDING,
Status.COMPLETED: DataFile.COMPLETED,
Status.DELETED: DataFile.COMPLETED
}[status]
|
python
|
def to_file(cls, status):
""" Returns the file in which this task is stored. """
return {
Status.PENDING: DataFile.PENDING,
Status.WAITING: DataFile.PENDING,
Status.COMPLETED: DataFile.COMPLETED,
Status.DELETED: DataFile.COMPLETED
}[status]
|
[
"def",
"to_file",
"(",
"cls",
",",
"status",
")",
":",
"return",
"{",
"Status",
".",
"PENDING",
":",
"DataFile",
".",
"PENDING",
",",
"Status",
".",
"WAITING",
":",
"DataFile",
".",
"PENDING",
",",
"Status",
".",
"COMPLETED",
":",
"DataFile",
".",
"COMPLETED",
",",
"Status",
".",
"DELETED",
":",
"DataFile",
".",
"COMPLETED",
"}",
"[",
"status",
"]"
] |
Returns the file in which this task is stored.
|
[
"Returns",
"the",
"file",
"in",
"which",
"this",
"task",
"is",
"stored",
"."
] |
11e2f9132eaedd157f514538de9b5f3b69c30a52
|
https://github.com/ralphbean/taskw/blob/11e2f9132eaedd157f514538de9b5f3b69c30a52/taskw/warrior.py#L896-L903
|
10,761
|
ralphbean/taskw
|
taskw/task.py
|
Task.from_stub
|
def from_stub(cls, data, udas=None):
""" Create a Task from an already deserialized dict. """
udas = udas or {}
fields = cls.FIELDS.copy()
fields.update(udas)
processed = {}
for k, v in six.iteritems(data):
processed[k] = cls._serialize(k, v, fields)
return cls(processed, udas)
|
python
|
def from_stub(cls, data, udas=None):
""" Create a Task from an already deserialized dict. """
udas = udas or {}
fields = cls.FIELDS.copy()
fields.update(udas)
processed = {}
for k, v in six.iteritems(data):
processed[k] = cls._serialize(k, v, fields)
return cls(processed, udas)
|
[
"def",
"from_stub",
"(",
"cls",
",",
"data",
",",
"udas",
"=",
"None",
")",
":",
"udas",
"=",
"udas",
"or",
"{",
"}",
"fields",
"=",
"cls",
".",
"FIELDS",
".",
"copy",
"(",
")",
"fields",
".",
"update",
"(",
"udas",
")",
"processed",
"=",
"{",
"}",
"for",
"k",
",",
"v",
"in",
"six",
".",
"iteritems",
"(",
"data",
")",
":",
"processed",
"[",
"k",
"]",
"=",
"cls",
".",
"_serialize",
"(",
"k",
",",
"v",
",",
"fields",
")",
"return",
"cls",
"(",
"processed",
",",
"udas",
")"
] |
Create a Task from an already deserialized dict.
|
[
"Create",
"a",
"Task",
"from",
"an",
"already",
"deserialized",
"dict",
"."
] |
11e2f9132eaedd157f514538de9b5f3b69c30a52
|
https://github.com/ralphbean/taskw/blob/11e2f9132eaedd157f514538de9b5f3b69c30a52/taskw/task.py#L82-L93
|
10,762
|
ralphbean/taskw
|
taskw/task.py
|
Task.from_input
|
def from_input(cls, input_file=sys.stdin, modify=False, udas=None):
"""
Create a Task directly from stdin by reading one line. If modify=True,
two lines are expected, which is consistent with the Taskwarrior hook
system. The first line is interpreted as the original state of the Task,
and the second one as the new, modified state.
:param input_file: Input file. Defaults to sys.stdin.
:param modify: Flag for on-modify hook event. Defaults to False.
:param udas: Taskrc udas. Defaults to None.
:return Task
"""
original_task = input_file.readline().strip()
if modify:
modified_task = input_file.readline().strip()
return cls(json.loads(modified_task), udas=udas)
return cls(json.loads(original_task), udas=udas)
|
python
|
def from_input(cls, input_file=sys.stdin, modify=False, udas=None):
"""
Create a Task directly from stdin by reading one line. If modify=True,
two lines are expected, which is consistent with the Taskwarrior hook
system. The first line is interpreted as the original state of the Task,
and the second one as the new, modified state.
:param input_file: Input file. Defaults to sys.stdin.
:param modify: Flag for on-modify hook event. Defaults to False.
:param udas: Taskrc udas. Defaults to None.
:return Task
"""
original_task = input_file.readline().strip()
if modify:
modified_task = input_file.readline().strip()
return cls(json.loads(modified_task), udas=udas)
return cls(json.loads(original_task), udas=udas)
|
[
"def",
"from_input",
"(",
"cls",
",",
"input_file",
"=",
"sys",
".",
"stdin",
",",
"modify",
"=",
"False",
",",
"udas",
"=",
"None",
")",
":",
"original_task",
"=",
"input_file",
".",
"readline",
"(",
")",
".",
"strip",
"(",
")",
"if",
"modify",
":",
"modified_task",
"=",
"input_file",
".",
"readline",
"(",
")",
".",
"strip",
"(",
")",
"return",
"cls",
"(",
"json",
".",
"loads",
"(",
"modified_task",
")",
",",
"udas",
"=",
"udas",
")",
"return",
"cls",
"(",
"json",
".",
"loads",
"(",
"original_task",
")",
",",
"udas",
"=",
"udas",
")"
] |
Create a Task directly from stdin by reading one line. If modify=True,
two lines are expected, which is consistent with the Taskwarrior hook
system. The first line is interpreted as the original state of the Task,
and the second one as the new, modified state.
:param input_file: Input file. Defaults to sys.stdin.
:param modify: Flag for on-modify hook event. Defaults to False.
:param udas: Taskrc udas. Defaults to None.
:return Task
|
[
"Create",
"a",
"Task",
"directly",
"from",
"stdin",
"by",
"reading",
"one",
"line",
".",
"If",
"modify",
"=",
"True",
"two",
"lines",
"are",
"expected",
"which",
"is",
"consistent",
"with",
"the",
"Taskwarrior",
"hook",
"system",
".",
"The",
"first",
"line",
"is",
"interpreted",
"as",
"the",
"original",
"state",
"of",
"the",
"Task",
"and",
"the",
"second",
"one",
"as",
"the",
"new",
"modified",
"state",
"."
] |
11e2f9132eaedd157f514538de9b5f3b69c30a52
|
https://github.com/ralphbean/taskw/blob/11e2f9132eaedd157f514538de9b5f3b69c30a52/taskw/task.py#L96-L112
|
10,763
|
ralphbean/taskw
|
taskw/task.py
|
Task._deserialize
|
def _deserialize(cls, key, value, fields):
""" Marshal incoming data into Python objects."""
converter = cls._get_converter_for_field(key, None, fields)
return converter.deserialize(value)
|
python
|
def _deserialize(cls, key, value, fields):
""" Marshal incoming data into Python objects."""
converter = cls._get_converter_for_field(key, None, fields)
return converter.deserialize(value)
|
[
"def",
"_deserialize",
"(",
"cls",
",",
"key",
",",
"value",
",",
"fields",
")",
":",
"converter",
"=",
"cls",
".",
"_get_converter_for_field",
"(",
"key",
",",
"None",
",",
"fields",
")",
"return",
"converter",
".",
"deserialize",
"(",
"value",
")"
] |
Marshal incoming data into Python objects.
|
[
"Marshal",
"incoming",
"data",
"into",
"Python",
"objects",
"."
] |
11e2f9132eaedd157f514538de9b5f3b69c30a52
|
https://github.com/ralphbean/taskw/blob/11e2f9132eaedd157f514538de9b5f3b69c30a52/taskw/task.py#L123-L126
|
10,764
|
ralphbean/taskw
|
taskw/task.py
|
Task._serialize
|
def _serialize(cls, key, value, fields):
""" Marshal outgoing data into Taskwarrior's JSON format."""
converter = cls._get_converter_for_field(key, None, fields)
return converter.serialize(value)
|
python
|
def _serialize(cls, key, value, fields):
""" Marshal outgoing data into Taskwarrior's JSON format."""
converter = cls._get_converter_for_field(key, None, fields)
return converter.serialize(value)
|
[
"def",
"_serialize",
"(",
"cls",
",",
"key",
",",
"value",
",",
"fields",
")",
":",
"converter",
"=",
"cls",
".",
"_get_converter_for_field",
"(",
"key",
",",
"None",
",",
"fields",
")",
"return",
"converter",
".",
"serialize",
"(",
"value",
")"
] |
Marshal outgoing data into Taskwarrior's JSON format.
|
[
"Marshal",
"outgoing",
"data",
"into",
"Taskwarrior",
"s",
"JSON",
"format",
"."
] |
11e2f9132eaedd157f514538de9b5f3b69c30a52
|
https://github.com/ralphbean/taskw/blob/11e2f9132eaedd157f514538de9b5f3b69c30a52/taskw/task.py#L129-L132
|
10,765
|
ralphbean/taskw
|
taskw/task.py
|
Task.get_changes
|
def get_changes(self, serialized=False, keep=False):
""" Get a journal of changes that have occurred
:param `serialized`:
Return changes in the serialized format used by TaskWarrior.
:param `keep_changes`:
By default, the list of changes is reset after running
``.get_changes``; set this to `True` if you would like to
keep the changes recorded following running this command.
:returns: A dictionary of 2-tuples of changes, where the key is the
name of the field that has changed, and the value is a 2-tuple
containing the original value and the final value respectively.
"""
results = {}
# Check for explicitly-registered changes
for k, f, t in self._changes:
if k not in results:
results[k] = [f, None]
results[k][1] = (
self._serialize(k, t, self._fields)
if serialized else t
)
# Check for changes on subordinate items
for k, v in six.iteritems(self):
if isinstance(v, Dirtyable):
result = v.get_changes(keep=keep)
if result:
if not k in results:
results[k] = [result[0], None]
results[k][1] = (
self._serialize(k, result[1], self._fields)
if serialized else result[1]
)
# Clear out recorded changes
if not keep:
self._changes = []
return results
|
python
|
def get_changes(self, serialized=False, keep=False):
""" Get a journal of changes that have occurred
:param `serialized`:
Return changes in the serialized format used by TaskWarrior.
:param `keep_changes`:
By default, the list of changes is reset after running
``.get_changes``; set this to `True` if you would like to
keep the changes recorded following running this command.
:returns: A dictionary of 2-tuples of changes, where the key is the
name of the field that has changed, and the value is a 2-tuple
containing the original value and the final value respectively.
"""
results = {}
# Check for explicitly-registered changes
for k, f, t in self._changes:
if k not in results:
results[k] = [f, None]
results[k][1] = (
self._serialize(k, t, self._fields)
if serialized else t
)
# Check for changes on subordinate items
for k, v in six.iteritems(self):
if isinstance(v, Dirtyable):
result = v.get_changes(keep=keep)
if result:
if not k in results:
results[k] = [result[0], None]
results[k][1] = (
self._serialize(k, result[1], self._fields)
if serialized else result[1]
)
# Clear out recorded changes
if not keep:
self._changes = []
return results
|
[
"def",
"get_changes",
"(",
"self",
",",
"serialized",
"=",
"False",
",",
"keep",
"=",
"False",
")",
":",
"results",
"=",
"{",
"}",
"# Check for explicitly-registered changes",
"for",
"k",
",",
"f",
",",
"t",
"in",
"self",
".",
"_changes",
":",
"if",
"k",
"not",
"in",
"results",
":",
"results",
"[",
"k",
"]",
"=",
"[",
"f",
",",
"None",
"]",
"results",
"[",
"k",
"]",
"[",
"1",
"]",
"=",
"(",
"self",
".",
"_serialize",
"(",
"k",
",",
"t",
",",
"self",
".",
"_fields",
")",
"if",
"serialized",
"else",
"t",
")",
"# Check for changes on subordinate items",
"for",
"k",
",",
"v",
"in",
"six",
".",
"iteritems",
"(",
"self",
")",
":",
"if",
"isinstance",
"(",
"v",
",",
"Dirtyable",
")",
":",
"result",
"=",
"v",
".",
"get_changes",
"(",
"keep",
"=",
"keep",
")",
"if",
"result",
":",
"if",
"not",
"k",
"in",
"results",
":",
"results",
"[",
"k",
"]",
"=",
"[",
"result",
"[",
"0",
"]",
",",
"None",
"]",
"results",
"[",
"k",
"]",
"[",
"1",
"]",
"=",
"(",
"self",
".",
"_serialize",
"(",
"k",
",",
"result",
"[",
"1",
"]",
",",
"self",
".",
"_fields",
")",
"if",
"serialized",
"else",
"result",
"[",
"1",
"]",
")",
"# Clear out recorded changes",
"if",
"not",
"keep",
":",
"self",
".",
"_changes",
"=",
"[",
"]",
"return",
"results"
] |
Get a journal of changes that have occurred
:param `serialized`:
Return changes in the serialized format used by TaskWarrior.
:param `keep_changes`:
By default, the list of changes is reset after running
``.get_changes``; set this to `True` if you would like to
keep the changes recorded following running this command.
:returns: A dictionary of 2-tuples of changes, where the key is the
name of the field that has changed, and the value is a 2-tuple
containing the original value and the final value respectively.
|
[
"Get",
"a",
"journal",
"of",
"changes",
"that",
"have",
"occurred"
] |
11e2f9132eaedd157f514538de9b5f3b69c30a52
|
https://github.com/ralphbean/taskw/blob/11e2f9132eaedd157f514538de9b5f3b69c30a52/taskw/task.py#L149-L191
|
10,766
|
ralphbean/taskw
|
taskw/task.py
|
Task.update
|
def update(self, values, force=False):
""" Update this task dictionary
:returns: A dictionary mapping field names specified to be updated
and a boolean value indicating whether the field was changed.
"""
results = {}
for k, v in six.iteritems(values):
results[k] = self.__setitem__(k, v, force=force)
return results
|
python
|
def update(self, values, force=False):
""" Update this task dictionary
:returns: A dictionary mapping field names specified to be updated
and a boolean value indicating whether the field was changed.
"""
results = {}
for k, v in six.iteritems(values):
results[k] = self.__setitem__(k, v, force=force)
return results
|
[
"def",
"update",
"(",
"self",
",",
"values",
",",
"force",
"=",
"False",
")",
":",
"results",
"=",
"{",
"}",
"for",
"k",
",",
"v",
"in",
"six",
".",
"iteritems",
"(",
"values",
")",
":",
"results",
"[",
"k",
"]",
"=",
"self",
".",
"__setitem__",
"(",
"k",
",",
"v",
",",
"force",
"=",
"force",
")",
"return",
"results"
] |
Update this task dictionary
:returns: A dictionary mapping field names specified to be updated
and a boolean value indicating whether the field was changed.
|
[
"Update",
"this",
"task",
"dictionary"
] |
11e2f9132eaedd157f514538de9b5f3b69c30a52
|
https://github.com/ralphbean/taskw/blob/11e2f9132eaedd157f514538de9b5f3b69c30a52/taskw/task.py#L193-L203
|
10,767
|
ralphbean/taskw
|
taskw/task.py
|
Task.set
|
def set(self, key, value):
""" Set a key's value regardless of whether a change is seen."""
return self.__setitem__(key, value, force=True)
|
python
|
def set(self, key, value):
""" Set a key's value regardless of whether a change is seen."""
return self.__setitem__(key, value, force=True)
|
[
"def",
"set",
"(",
"self",
",",
"key",
",",
"value",
")",
":",
"return",
"self",
".",
"__setitem__",
"(",
"key",
",",
"value",
",",
"force",
"=",
"True",
")"
] |
Set a key's value regardless of whether a change is seen.
|
[
"Set",
"a",
"key",
"s",
"value",
"regardless",
"of",
"whether",
"a",
"change",
"is",
"seen",
"."
] |
11e2f9132eaedd157f514538de9b5f3b69c30a52
|
https://github.com/ralphbean/taskw/blob/11e2f9132eaedd157f514538de9b5f3b69c30a52/taskw/task.py#L205-L207
|
10,768
|
ralphbean/taskw
|
taskw/task.py
|
Task.serialized
|
def serialized(self):
""" Returns a serialized representation of this task."""
serialized = {}
for k, v in six.iteritems(self):
serialized[k] = self._serialize(k, v, self._fields)
return serialized
|
python
|
def serialized(self):
""" Returns a serialized representation of this task."""
serialized = {}
for k, v in six.iteritems(self):
serialized[k] = self._serialize(k, v, self._fields)
return serialized
|
[
"def",
"serialized",
"(",
"self",
")",
":",
"serialized",
"=",
"{",
"}",
"for",
"k",
",",
"v",
"in",
"six",
".",
"iteritems",
"(",
"self",
")",
":",
"serialized",
"[",
"k",
"]",
"=",
"self",
".",
"_serialize",
"(",
"k",
",",
"v",
",",
"self",
".",
"_fields",
")",
"return",
"serialized"
] |
Returns a serialized representation of this task.
|
[
"Returns",
"a",
"serialized",
"representation",
"of",
"this",
"task",
"."
] |
11e2f9132eaedd157f514538de9b5f3b69c30a52
|
https://github.com/ralphbean/taskw/blob/11e2f9132eaedd157f514538de9b5f3b69c30a52/taskw/task.py#L209-L214
|
10,769
|
ralphbean/taskw
|
taskw/utils.py
|
encode_task_experimental
|
def encode_task_experimental(task):
""" Convert a dict-like task to its string representation
Used for adding a task via `task add`
"""
# First, clean the task:
task = task.copy()
if 'tags' in task:
task['tags'] = ','.join(task['tags'])
for k in task:
task[k] = encode_task_value(k, task[k])
# Then, format it as a string
return [
"%s:\"%s\"" % (k, v) if v else "%s:" % (k, )
for k, v in sorted(task.items(), key=itemgetter(0))
]
|
python
|
def encode_task_experimental(task):
""" Convert a dict-like task to its string representation
Used for adding a task via `task add`
"""
# First, clean the task:
task = task.copy()
if 'tags' in task:
task['tags'] = ','.join(task['tags'])
for k in task:
task[k] = encode_task_value(k, task[k])
# Then, format it as a string
return [
"%s:\"%s\"" % (k, v) if v else "%s:" % (k, )
for k, v in sorted(task.items(), key=itemgetter(0))
]
|
[
"def",
"encode_task_experimental",
"(",
"task",
")",
":",
"# First, clean the task:",
"task",
"=",
"task",
".",
"copy",
"(",
")",
"if",
"'tags'",
"in",
"task",
":",
"task",
"[",
"'tags'",
"]",
"=",
"','",
".",
"join",
"(",
"task",
"[",
"'tags'",
"]",
")",
"for",
"k",
"in",
"task",
":",
"task",
"[",
"k",
"]",
"=",
"encode_task_value",
"(",
"k",
",",
"task",
"[",
"k",
"]",
")",
"# Then, format it as a string",
"return",
"[",
"\"%s:\\\"%s\\\"\"",
"%",
"(",
"k",
",",
"v",
")",
"if",
"v",
"else",
"\"%s:\"",
"%",
"(",
"k",
",",
")",
"for",
"k",
",",
"v",
"in",
"sorted",
"(",
"task",
".",
"items",
"(",
")",
",",
"key",
"=",
"itemgetter",
"(",
"0",
")",
")",
"]"
] |
Convert a dict-like task to its string representation
Used for adding a task via `task add`
|
[
"Convert",
"a",
"dict",
"-",
"like",
"task",
"to",
"its",
"string",
"representation",
"Used",
"for",
"adding",
"a",
"task",
"via",
"task",
"add"
] |
11e2f9132eaedd157f514538de9b5f3b69c30a52
|
https://github.com/ralphbean/taskw/blob/11e2f9132eaedd157f514538de9b5f3b69c30a52/taskw/utils.py#L125-L140
|
10,770
|
ralphbean/taskw
|
taskw/utils.py
|
encode_task
|
def encode_task(task):
""" Convert a dict-like task to its string representation """
# First, clean the task:
task = task.copy()
if 'tags' in task:
task['tags'] = ','.join(task['tags'])
for k in task:
for unsafe, safe in six.iteritems(encode_replacements):
if isinstance(task[k], six.string_types):
task[k] = task[k].replace(unsafe, safe)
if isinstance(task[k], datetime.datetime):
task[k] = task[k].strftime("%Y%m%dT%M%H%SZ")
# Then, format it as a string
return "[%s]\n" % " ".join([
"%s:\"%s\"" % (k, v)
for k, v in sorted(task.items(), key=itemgetter(0))
])
|
python
|
def encode_task(task):
""" Convert a dict-like task to its string representation """
# First, clean the task:
task = task.copy()
if 'tags' in task:
task['tags'] = ','.join(task['tags'])
for k in task:
for unsafe, safe in six.iteritems(encode_replacements):
if isinstance(task[k], six.string_types):
task[k] = task[k].replace(unsafe, safe)
if isinstance(task[k], datetime.datetime):
task[k] = task[k].strftime("%Y%m%dT%M%H%SZ")
# Then, format it as a string
return "[%s]\n" % " ".join([
"%s:\"%s\"" % (k, v)
for k, v in sorted(task.items(), key=itemgetter(0))
])
|
[
"def",
"encode_task",
"(",
"task",
")",
":",
"# First, clean the task:",
"task",
"=",
"task",
".",
"copy",
"(",
")",
"if",
"'tags'",
"in",
"task",
":",
"task",
"[",
"'tags'",
"]",
"=",
"','",
".",
"join",
"(",
"task",
"[",
"'tags'",
"]",
")",
"for",
"k",
"in",
"task",
":",
"for",
"unsafe",
",",
"safe",
"in",
"six",
".",
"iteritems",
"(",
"encode_replacements",
")",
":",
"if",
"isinstance",
"(",
"task",
"[",
"k",
"]",
",",
"six",
".",
"string_types",
")",
":",
"task",
"[",
"k",
"]",
"=",
"task",
"[",
"k",
"]",
".",
"replace",
"(",
"unsafe",
",",
"safe",
")",
"if",
"isinstance",
"(",
"task",
"[",
"k",
"]",
",",
"datetime",
".",
"datetime",
")",
":",
"task",
"[",
"k",
"]",
"=",
"task",
"[",
"k",
"]",
".",
"strftime",
"(",
"\"%Y%m%dT%M%H%SZ\"",
")",
"# Then, format it as a string",
"return",
"\"[%s]\\n\"",
"%",
"\" \"",
".",
"join",
"(",
"[",
"\"%s:\\\"%s\\\"\"",
"%",
"(",
"k",
",",
"v",
")",
"for",
"k",
",",
"v",
"in",
"sorted",
"(",
"task",
".",
"items",
"(",
")",
",",
"key",
"=",
"itemgetter",
"(",
"0",
")",
")",
"]",
")"
] |
Convert a dict-like task to its string representation
|
[
"Convert",
"a",
"dict",
"-",
"like",
"task",
"to",
"its",
"string",
"representation"
] |
11e2f9132eaedd157f514538de9b5f3b69c30a52
|
https://github.com/ralphbean/taskw/blob/11e2f9132eaedd157f514538de9b5f3b69c30a52/taskw/utils.py#L143-L161
|
10,771
|
ralphbean/taskw
|
taskw/utils.py
|
convert_dict_to_override_args
|
def convert_dict_to_override_args(config, prefix=''):
""" Converts a dictionary of override arguments into CLI arguments.
* Converts leaf nodes into dot paths of key names leading to the leaf
node.
* Does not include paths to leaf nodes not being non-dictionary type.
See `taskw.test.test_utils.TestUtils.test_convert_dict_to_override_args`
for details.
"""
args = []
for k, v in six.iteritems(config):
if isinstance(v, dict):
args.extend(
convert_dict_to_override_args(
v,
prefix='.'.join([
prefix,
k,
]) if prefix else k
)
)
else:
v = six.text_type(v)
left = 'rc' + (('.' + prefix) if prefix else '') + '.' + k
right = v if ' ' not in v else '"%s"' % v
args.append('='.join([left, right]))
return args
|
python
|
def convert_dict_to_override_args(config, prefix=''):
""" Converts a dictionary of override arguments into CLI arguments.
* Converts leaf nodes into dot paths of key names leading to the leaf
node.
* Does not include paths to leaf nodes not being non-dictionary type.
See `taskw.test.test_utils.TestUtils.test_convert_dict_to_override_args`
for details.
"""
args = []
for k, v in six.iteritems(config):
if isinstance(v, dict):
args.extend(
convert_dict_to_override_args(
v,
prefix='.'.join([
prefix,
k,
]) if prefix else k
)
)
else:
v = six.text_type(v)
left = 'rc' + (('.' + prefix) if prefix else '') + '.' + k
right = v if ' ' not in v else '"%s"' % v
args.append('='.join([left, right]))
return args
|
[
"def",
"convert_dict_to_override_args",
"(",
"config",
",",
"prefix",
"=",
"''",
")",
":",
"args",
"=",
"[",
"]",
"for",
"k",
",",
"v",
"in",
"six",
".",
"iteritems",
"(",
"config",
")",
":",
"if",
"isinstance",
"(",
"v",
",",
"dict",
")",
":",
"args",
".",
"extend",
"(",
"convert_dict_to_override_args",
"(",
"v",
",",
"prefix",
"=",
"'.'",
".",
"join",
"(",
"[",
"prefix",
",",
"k",
",",
"]",
")",
"if",
"prefix",
"else",
"k",
")",
")",
"else",
":",
"v",
"=",
"six",
".",
"text_type",
"(",
"v",
")",
"left",
"=",
"'rc'",
"+",
"(",
"(",
"'.'",
"+",
"prefix",
")",
"if",
"prefix",
"else",
"''",
")",
"+",
"'.'",
"+",
"k",
"right",
"=",
"v",
"if",
"' '",
"not",
"in",
"v",
"else",
"'\"%s\"'",
"%",
"v",
"args",
".",
"append",
"(",
"'='",
".",
"join",
"(",
"[",
"left",
",",
"right",
"]",
")",
")",
"return",
"args"
] |
Converts a dictionary of override arguments into CLI arguments.
* Converts leaf nodes into dot paths of key names leading to the leaf
node.
* Does not include paths to leaf nodes not being non-dictionary type.
See `taskw.test.test_utils.TestUtils.test_convert_dict_to_override_args`
for details.
|
[
"Converts",
"a",
"dictionary",
"of",
"override",
"arguments",
"into",
"CLI",
"arguments",
"."
] |
11e2f9132eaedd157f514538de9b5f3b69c30a52
|
https://github.com/ralphbean/taskw/blob/11e2f9132eaedd157f514538de9b5f3b69c30a52/taskw/utils.py#L235-L263
|
10,772
|
twoolie/NBT
|
examples/block_analysis.py
|
stats_per_chunk
|
def stats_per_chunk(chunk):
"""Given a chunk, increment the block types with the number of blocks found"""
for block_id in chunk.iter_block():
try:
block_counts[block_id] += 1
except KeyError:
block_counts[block_id] = 1
|
python
|
def stats_per_chunk(chunk):
"""Given a chunk, increment the block types with the number of blocks found"""
for block_id in chunk.iter_block():
try:
block_counts[block_id] += 1
except KeyError:
block_counts[block_id] = 1
|
[
"def",
"stats_per_chunk",
"(",
"chunk",
")",
":",
"for",
"block_id",
"in",
"chunk",
".",
"iter_block",
"(",
")",
":",
"try",
":",
"block_counts",
"[",
"block_id",
"]",
"+=",
"1",
"except",
"KeyError",
":",
"block_counts",
"[",
"block_id",
"]",
"=",
"1"
] |
Given a chunk, increment the block types with the number of blocks found
|
[
"Given",
"a",
"chunk",
"increment",
"the",
"block",
"types",
"with",
"the",
"number",
"of",
"blocks",
"found"
] |
b06dd6cc8117d2788da1d8416e642d58bad45762
|
https://github.com/twoolie/NBT/blob/b06dd6cc8117d2788da1d8416e642d58bad45762/examples/block_analysis.py#L23-L30
|
10,773
|
twoolie/NBT
|
examples/block_analysis.py
|
bounded_stats_per_chunk
|
def bounded_stats_per_chunk(chunk, block_counts, start, stop):
"""Given a chunk, return the number of blocks types within the specified selection"""
chunk_z, chunk_x = chunk.get_coords()
for z in range(16):
world_z = z + chunk_z*16
if ( (start != None and world_z < int(start[2])) or (stop != None and world_z > int(stop[2])) ):
# Outside the bounding box; skip to next iteration
#print("Z break: %d,%d,%d" % (world_z,start[2],stop[2]))
break
for x in range(16):
world_x = x + chunk_x*16
if ( (start != None and world_x < int(start[0])) or (stop != None and world_x > int(stop[0])) ):
# Outside the bounding box; skip to next iteration
#print("X break: %d,%d,%d" % (world_x,start[0],stop[0]))
break
for y in range(chunk.get_max_height() + 1):
if ( (start != None and y < int(start[1])) or (stop != None and y > int(stop[1])) ):
# Outside the bounding box; skip to next iteration
#print("Y break: %d,%d,%d" % (y,start[1],stop[1]))
break
#print("Chunk: %d,%d Coord: %d,%d,%d" % (c['x'], c['z'],x,y,z))
block_id = chunk.get_block(x,y,z)
if block_id != None:
try:
block_counts[block_id] += 1
except KeyError:
block_counts[block_id] = 1
|
python
|
def bounded_stats_per_chunk(chunk, block_counts, start, stop):
"""Given a chunk, return the number of blocks types within the specified selection"""
chunk_z, chunk_x = chunk.get_coords()
for z in range(16):
world_z = z + chunk_z*16
if ( (start != None and world_z < int(start[2])) or (stop != None and world_z > int(stop[2])) ):
# Outside the bounding box; skip to next iteration
#print("Z break: %d,%d,%d" % (world_z,start[2],stop[2]))
break
for x in range(16):
world_x = x + chunk_x*16
if ( (start != None and world_x < int(start[0])) or (stop != None and world_x > int(stop[0])) ):
# Outside the bounding box; skip to next iteration
#print("X break: %d,%d,%d" % (world_x,start[0],stop[0]))
break
for y in range(chunk.get_max_height() + 1):
if ( (start != None and y < int(start[1])) or (stop != None and y > int(stop[1])) ):
# Outside the bounding box; skip to next iteration
#print("Y break: %d,%d,%d" % (y,start[1],stop[1]))
break
#print("Chunk: %d,%d Coord: %d,%d,%d" % (c['x'], c['z'],x,y,z))
block_id = chunk.get_block(x,y,z)
if block_id != None:
try:
block_counts[block_id] += 1
except KeyError:
block_counts[block_id] = 1
|
[
"def",
"bounded_stats_per_chunk",
"(",
"chunk",
",",
"block_counts",
",",
"start",
",",
"stop",
")",
":",
"chunk_z",
",",
"chunk_x",
"=",
"chunk",
".",
"get_coords",
"(",
")",
"for",
"z",
"in",
"range",
"(",
"16",
")",
":",
"world_z",
"=",
"z",
"+",
"chunk_z",
"*",
"16",
"if",
"(",
"(",
"start",
"!=",
"None",
"and",
"world_z",
"<",
"int",
"(",
"start",
"[",
"2",
"]",
")",
")",
"or",
"(",
"stop",
"!=",
"None",
"and",
"world_z",
">",
"int",
"(",
"stop",
"[",
"2",
"]",
")",
")",
")",
":",
"# Outside the bounding box; skip to next iteration",
"#print(\"Z break: %d,%d,%d\" % (world_z,start[2],stop[2]))",
"break",
"for",
"x",
"in",
"range",
"(",
"16",
")",
":",
"world_x",
"=",
"x",
"+",
"chunk_x",
"*",
"16",
"if",
"(",
"(",
"start",
"!=",
"None",
"and",
"world_x",
"<",
"int",
"(",
"start",
"[",
"0",
"]",
")",
")",
"or",
"(",
"stop",
"!=",
"None",
"and",
"world_x",
">",
"int",
"(",
"stop",
"[",
"0",
"]",
")",
")",
")",
":",
"# Outside the bounding box; skip to next iteration",
"#print(\"X break: %d,%d,%d\" % (world_x,start[0],stop[0]))",
"break",
"for",
"y",
"in",
"range",
"(",
"chunk",
".",
"get_max_height",
"(",
")",
"+",
"1",
")",
":",
"if",
"(",
"(",
"start",
"!=",
"None",
"and",
"y",
"<",
"int",
"(",
"start",
"[",
"1",
"]",
")",
")",
"or",
"(",
"stop",
"!=",
"None",
"and",
"y",
">",
"int",
"(",
"stop",
"[",
"1",
"]",
")",
")",
")",
":",
"# Outside the bounding box; skip to next iteration",
"#print(\"Y break: %d,%d,%d\" % (y,start[1],stop[1]))",
"break",
"#print(\"Chunk: %d,%d Coord: %d,%d,%d\" % (c['x'], c['z'],x,y,z))",
"block_id",
"=",
"chunk",
".",
"get_block",
"(",
"x",
",",
"y",
",",
"z",
")",
"if",
"block_id",
"!=",
"None",
":",
"try",
":",
"block_counts",
"[",
"block_id",
"]",
"+=",
"1",
"except",
"KeyError",
":",
"block_counts",
"[",
"block_id",
"]",
"=",
"1"
] |
Given a chunk, return the number of blocks types within the specified selection
|
[
"Given",
"a",
"chunk",
"return",
"the",
"number",
"of",
"blocks",
"types",
"within",
"the",
"specified",
"selection"
] |
b06dd6cc8117d2788da1d8416e642d58bad45762
|
https://github.com/twoolie/NBT/blob/b06dd6cc8117d2788da1d8416e642d58bad45762/examples/block_analysis.py#L33-L60
|
10,774
|
twoolie/NBT
|
examples/block_analysis.py
|
process_region_file
|
def process_region_file(region, start, stop):
"""Given a region, return the number of blocks of each ID in that region"""
rx = region.loc.x
rz = region.loc.z
# Does the region overlap the bounding box at all?
if (start != None):
if ( (rx+1)*512-1 < int(start[0]) or (rz+1)*512-1 < int(start[2]) ):
return
elif (stop != None):
if ( rx*512-1 > int(stop[0]) or rz*512-1 > int(stop[2]) ):
return
# Get all chunks
print("Parsing region %s..." % os.path.basename(region.filename))
for c in region.iter_chunks_class():
cx, cz = c.get_coords();
# Does the chunk overlap the bounding box at all?
if (start != None):
if ( (cx+1)*16 + rx*512 - 1 < int(start[0]) or (cz+1)*16 + rz*512 - 1 < int(start[2]) ):
continue
elif (stop != None):
if ( cx*16 + rx*512 - 1 > int(stop[0]) or cz*16 + rz*512 - 1 > int(stop[2]) ):
continue
#print("Parsing chunk (" + str(cx) + ", " + str(cz) + ")...")
# Fast code if no start or stop coordinates are specified
# TODO: also use this code if start/stop is specified, but the complete chunk is included
if (start == None and stop == None):
stats_per_chunk(c)
else:
# Slow code that iterates through each coordinate
bounded_stats_per_chunk(c, start, stop)
|
python
|
def process_region_file(region, start, stop):
"""Given a region, return the number of blocks of each ID in that region"""
rx = region.loc.x
rz = region.loc.z
# Does the region overlap the bounding box at all?
if (start != None):
if ( (rx+1)*512-1 < int(start[0]) or (rz+1)*512-1 < int(start[2]) ):
return
elif (stop != None):
if ( rx*512-1 > int(stop[0]) or rz*512-1 > int(stop[2]) ):
return
# Get all chunks
print("Parsing region %s..." % os.path.basename(region.filename))
for c in region.iter_chunks_class():
cx, cz = c.get_coords();
# Does the chunk overlap the bounding box at all?
if (start != None):
if ( (cx+1)*16 + rx*512 - 1 < int(start[0]) or (cz+1)*16 + rz*512 - 1 < int(start[2]) ):
continue
elif (stop != None):
if ( cx*16 + rx*512 - 1 > int(stop[0]) or cz*16 + rz*512 - 1 > int(stop[2]) ):
continue
#print("Parsing chunk (" + str(cx) + ", " + str(cz) + ")...")
# Fast code if no start or stop coordinates are specified
# TODO: also use this code if start/stop is specified, but the complete chunk is included
if (start == None and stop == None):
stats_per_chunk(c)
else:
# Slow code that iterates through each coordinate
bounded_stats_per_chunk(c, start, stop)
|
[
"def",
"process_region_file",
"(",
"region",
",",
"start",
",",
"stop",
")",
":",
"rx",
"=",
"region",
".",
"loc",
".",
"x",
"rz",
"=",
"region",
".",
"loc",
".",
"z",
"# Does the region overlap the bounding box at all?",
"if",
"(",
"start",
"!=",
"None",
")",
":",
"if",
"(",
"(",
"rx",
"+",
"1",
")",
"*",
"512",
"-",
"1",
"<",
"int",
"(",
"start",
"[",
"0",
"]",
")",
"or",
"(",
"rz",
"+",
"1",
")",
"*",
"512",
"-",
"1",
"<",
"int",
"(",
"start",
"[",
"2",
"]",
")",
")",
":",
"return",
"elif",
"(",
"stop",
"!=",
"None",
")",
":",
"if",
"(",
"rx",
"*",
"512",
"-",
"1",
">",
"int",
"(",
"stop",
"[",
"0",
"]",
")",
"or",
"rz",
"*",
"512",
"-",
"1",
">",
"int",
"(",
"stop",
"[",
"2",
"]",
")",
")",
":",
"return",
"# Get all chunks",
"print",
"(",
"\"Parsing region %s...\"",
"%",
"os",
".",
"path",
".",
"basename",
"(",
"region",
".",
"filename",
")",
")",
"for",
"c",
"in",
"region",
".",
"iter_chunks_class",
"(",
")",
":",
"cx",
",",
"cz",
"=",
"c",
".",
"get_coords",
"(",
")",
"# Does the chunk overlap the bounding box at all?",
"if",
"(",
"start",
"!=",
"None",
")",
":",
"if",
"(",
"(",
"cx",
"+",
"1",
")",
"*",
"16",
"+",
"rx",
"*",
"512",
"-",
"1",
"<",
"int",
"(",
"start",
"[",
"0",
"]",
")",
"or",
"(",
"cz",
"+",
"1",
")",
"*",
"16",
"+",
"rz",
"*",
"512",
"-",
"1",
"<",
"int",
"(",
"start",
"[",
"2",
"]",
")",
")",
":",
"continue",
"elif",
"(",
"stop",
"!=",
"None",
")",
":",
"if",
"(",
"cx",
"*",
"16",
"+",
"rx",
"*",
"512",
"-",
"1",
">",
"int",
"(",
"stop",
"[",
"0",
"]",
")",
"or",
"cz",
"*",
"16",
"+",
"rz",
"*",
"512",
"-",
"1",
">",
"int",
"(",
"stop",
"[",
"2",
"]",
")",
")",
":",
"continue",
"#print(\"Parsing chunk (\" + str(cx) + \", \" + str(cz) + \")...\")",
"# Fast code if no start or stop coordinates are specified",
"# TODO: also use this code if start/stop is specified, but the complete chunk is included",
"if",
"(",
"start",
"==",
"None",
"and",
"stop",
"==",
"None",
")",
":",
"stats_per_chunk",
"(",
"c",
")",
"else",
":",
"# Slow code that iterates through each coordinate",
"bounded_stats_per_chunk",
"(",
"c",
",",
"start",
",",
"stop",
")"
] |
Given a region, return the number of blocks of each ID in that region
|
[
"Given",
"a",
"region",
"return",
"the",
"number",
"of",
"blocks",
"of",
"each",
"ID",
"in",
"that",
"region"
] |
b06dd6cc8117d2788da1d8416e642d58bad45762
|
https://github.com/twoolie/NBT/blob/b06dd6cc8117d2788da1d8416e642d58bad45762/examples/block_analysis.py#L63-L96
|
10,775
|
twoolie/NBT
|
nbt/world.py
|
_BaseWorldFolder.get_region
|
def get_region(self, x,z):
"""Get a region using x,z coordinates of a region. Cache results."""
if (x,z) not in self.regions:
if (x,z) in self.regionfiles:
self.regions[(x,z)] = region.RegionFile(self.regionfiles[(x,z)])
else:
# Return an empty RegionFile object
# TODO: this does not yet allow for saving of the region file
# TODO: this currently fails with a ValueError!
# TODO: generate the correct name, and create the file
# and add the fie to self.regionfiles
self.regions[(x,z)] = region.RegionFile()
self.regions[(x,z)].loc = Location(x=x,z=z)
return self.regions[(x,z)]
|
python
|
def get_region(self, x,z):
"""Get a region using x,z coordinates of a region. Cache results."""
if (x,z) not in self.regions:
if (x,z) in self.regionfiles:
self.regions[(x,z)] = region.RegionFile(self.regionfiles[(x,z)])
else:
# Return an empty RegionFile object
# TODO: this does not yet allow for saving of the region file
# TODO: this currently fails with a ValueError!
# TODO: generate the correct name, and create the file
# and add the fie to self.regionfiles
self.regions[(x,z)] = region.RegionFile()
self.regions[(x,z)].loc = Location(x=x,z=z)
return self.regions[(x,z)]
|
[
"def",
"get_region",
"(",
"self",
",",
"x",
",",
"z",
")",
":",
"if",
"(",
"x",
",",
"z",
")",
"not",
"in",
"self",
".",
"regions",
":",
"if",
"(",
"x",
",",
"z",
")",
"in",
"self",
".",
"regionfiles",
":",
"self",
".",
"regions",
"[",
"(",
"x",
",",
"z",
")",
"]",
"=",
"region",
".",
"RegionFile",
"(",
"self",
".",
"regionfiles",
"[",
"(",
"x",
",",
"z",
")",
"]",
")",
"else",
":",
"# Return an empty RegionFile object",
"# TODO: this does not yet allow for saving of the region file",
"# TODO: this currently fails with a ValueError!",
"# TODO: generate the correct name, and create the file",
"# and add the fie to self.regionfiles",
"self",
".",
"regions",
"[",
"(",
"x",
",",
"z",
")",
"]",
"=",
"region",
".",
"RegionFile",
"(",
")",
"self",
".",
"regions",
"[",
"(",
"x",
",",
"z",
")",
"]",
".",
"loc",
"=",
"Location",
"(",
"x",
"=",
"x",
",",
"z",
"=",
"z",
")",
"return",
"self",
".",
"regions",
"[",
"(",
"x",
",",
"z",
")",
"]"
] |
Get a region using x,z coordinates of a region. Cache results.
|
[
"Get",
"a",
"region",
"using",
"x",
"z",
"coordinates",
"of",
"a",
"region",
".",
"Cache",
"results",
"."
] |
b06dd6cc8117d2788da1d8416e642d58bad45762
|
https://github.com/twoolie/NBT/blob/b06dd6cc8117d2788da1d8416e642d58bad45762/nbt/world.py#L77-L90
|
10,776
|
twoolie/NBT
|
nbt/world.py
|
_BaseWorldFolder.iter_regions
|
def iter_regions(self):
"""
Return an iterable list of all region files. Use this function if you only
want to loop through each region files once, and do not want to cache the results.
"""
# TODO: Implement BoundingBox
# TODO: Implement sort order
for x,z in self.regionfiles.keys():
close_after_use = False
if (x,z) in self.regions:
regionfile = self.regions[(x,z)]
else:
# It is not yet cached.
# Get file, but do not cache later.
regionfile = region.RegionFile(self.regionfiles[(x,z)], chunkclass = self.chunkclass)
regionfile.loc = Location(x=x,z=z)
close_after_use = True
try:
yield regionfile
finally:
if close_after_use:
regionfile.close()
|
python
|
def iter_regions(self):
"""
Return an iterable list of all region files. Use this function if you only
want to loop through each region files once, and do not want to cache the results.
"""
# TODO: Implement BoundingBox
# TODO: Implement sort order
for x,z in self.regionfiles.keys():
close_after_use = False
if (x,z) in self.regions:
regionfile = self.regions[(x,z)]
else:
# It is not yet cached.
# Get file, but do not cache later.
regionfile = region.RegionFile(self.regionfiles[(x,z)], chunkclass = self.chunkclass)
regionfile.loc = Location(x=x,z=z)
close_after_use = True
try:
yield regionfile
finally:
if close_after_use:
regionfile.close()
|
[
"def",
"iter_regions",
"(",
"self",
")",
":",
"# TODO: Implement BoundingBox",
"# TODO: Implement sort order",
"for",
"x",
",",
"z",
"in",
"self",
".",
"regionfiles",
".",
"keys",
"(",
")",
":",
"close_after_use",
"=",
"False",
"if",
"(",
"x",
",",
"z",
")",
"in",
"self",
".",
"regions",
":",
"regionfile",
"=",
"self",
".",
"regions",
"[",
"(",
"x",
",",
"z",
")",
"]",
"else",
":",
"# It is not yet cached.",
"# Get file, but do not cache later.",
"regionfile",
"=",
"region",
".",
"RegionFile",
"(",
"self",
".",
"regionfiles",
"[",
"(",
"x",
",",
"z",
")",
"]",
",",
"chunkclass",
"=",
"self",
".",
"chunkclass",
")",
"regionfile",
".",
"loc",
"=",
"Location",
"(",
"x",
"=",
"x",
",",
"z",
"=",
"z",
")",
"close_after_use",
"=",
"True",
"try",
":",
"yield",
"regionfile",
"finally",
":",
"if",
"close_after_use",
":",
"regionfile",
".",
"close",
"(",
")"
] |
Return an iterable list of all region files. Use this function if you only
want to loop through each region files once, and do not want to cache the results.
|
[
"Return",
"an",
"iterable",
"list",
"of",
"all",
"region",
"files",
".",
"Use",
"this",
"function",
"if",
"you",
"only",
"want",
"to",
"loop",
"through",
"each",
"region",
"files",
"once",
"and",
"do",
"not",
"want",
"to",
"cache",
"the",
"results",
"."
] |
b06dd6cc8117d2788da1d8416e642d58bad45762
|
https://github.com/twoolie/NBT/blob/b06dd6cc8117d2788da1d8416e642d58bad45762/nbt/world.py#L92-L113
|
10,777
|
twoolie/NBT
|
nbt/world.py
|
_BaseWorldFolder.get_nbt
|
def get_nbt(self,x,z):
"""
Return a NBT specified by the chunk coordinates x,z. Raise InconceivedChunk
if the NBT file is not yet generated. To get a Chunk object, use get_chunk.
"""
rx,cx = divmod(x,32)
rz,cz = divmod(z,32)
if (rx,rz) not in self.regions and (rx,rz) not in self.regionfiles:
raise InconceivedChunk("Chunk %s,%s is not present in world" % (x,z))
nbt = self.get_region(rx,rz).get_nbt(cx,cz)
assert nbt != None
return nbt
|
python
|
def get_nbt(self,x,z):
"""
Return a NBT specified by the chunk coordinates x,z. Raise InconceivedChunk
if the NBT file is not yet generated. To get a Chunk object, use get_chunk.
"""
rx,cx = divmod(x,32)
rz,cz = divmod(z,32)
if (rx,rz) not in self.regions and (rx,rz) not in self.regionfiles:
raise InconceivedChunk("Chunk %s,%s is not present in world" % (x,z))
nbt = self.get_region(rx,rz).get_nbt(cx,cz)
assert nbt != None
return nbt
|
[
"def",
"get_nbt",
"(",
"self",
",",
"x",
",",
"z",
")",
":",
"rx",
",",
"cx",
"=",
"divmod",
"(",
"x",
",",
"32",
")",
"rz",
",",
"cz",
"=",
"divmod",
"(",
"z",
",",
"32",
")",
"if",
"(",
"rx",
",",
"rz",
")",
"not",
"in",
"self",
".",
"regions",
"and",
"(",
"rx",
",",
"rz",
")",
"not",
"in",
"self",
".",
"regionfiles",
":",
"raise",
"InconceivedChunk",
"(",
"\"Chunk %s,%s is not present in world\"",
"%",
"(",
"x",
",",
"z",
")",
")",
"nbt",
"=",
"self",
".",
"get_region",
"(",
"rx",
",",
"rz",
")",
".",
"get_nbt",
"(",
"cx",
",",
"cz",
")",
"assert",
"nbt",
"!=",
"None",
"return",
"nbt"
] |
Return a NBT specified by the chunk coordinates x,z. Raise InconceivedChunk
if the NBT file is not yet generated. To get a Chunk object, use get_chunk.
|
[
"Return",
"a",
"NBT",
"specified",
"by",
"the",
"chunk",
"coordinates",
"x",
"z",
".",
"Raise",
"InconceivedChunk",
"if",
"the",
"NBT",
"file",
"is",
"not",
"yet",
"generated",
".",
"To",
"get",
"a",
"Chunk",
"object",
"use",
"get_chunk",
"."
] |
b06dd6cc8117d2788da1d8416e642d58bad45762
|
https://github.com/twoolie/NBT/blob/b06dd6cc8117d2788da1d8416e642d58bad45762/nbt/world.py#L130-L141
|
10,778
|
twoolie/NBT
|
nbt/world.py
|
_BaseWorldFolder.get_chunk
|
def get_chunk(self,x,z):
"""
Return a chunk specified by the chunk coordinates x,z. Raise InconceivedChunk
if the chunk is not yet generated. To get the raw NBT data, use get_nbt.
"""
return self.chunkclass(self.get_nbt(x, z))
|
python
|
def get_chunk(self,x,z):
"""
Return a chunk specified by the chunk coordinates x,z. Raise InconceivedChunk
if the chunk is not yet generated. To get the raw NBT data, use get_nbt.
"""
return self.chunkclass(self.get_nbt(x, z))
|
[
"def",
"get_chunk",
"(",
"self",
",",
"x",
",",
"z",
")",
":",
"return",
"self",
".",
"chunkclass",
"(",
"self",
".",
"get_nbt",
"(",
"x",
",",
"z",
")",
")"
] |
Return a chunk specified by the chunk coordinates x,z. Raise InconceivedChunk
if the chunk is not yet generated. To get the raw NBT data, use get_nbt.
|
[
"Return",
"a",
"chunk",
"specified",
"by",
"the",
"chunk",
"coordinates",
"x",
"z",
".",
"Raise",
"InconceivedChunk",
"if",
"the",
"chunk",
"is",
"not",
"yet",
"generated",
".",
"To",
"get",
"the",
"raw",
"NBT",
"data",
"use",
"get_nbt",
"."
] |
b06dd6cc8117d2788da1d8416e642d58bad45762
|
https://github.com/twoolie/NBT/blob/b06dd6cc8117d2788da1d8416e642d58bad45762/nbt/world.py#L178-L183
|
10,779
|
twoolie/NBT
|
nbt/world.py
|
_BaseWorldFolder.chunk_count
|
def chunk_count(self):
"""Return a count of the chunks in this world folder."""
c = 0
for r in self.iter_regions():
c += r.chunk_count()
return c
|
python
|
def chunk_count(self):
"""Return a count of the chunks in this world folder."""
c = 0
for r in self.iter_regions():
c += r.chunk_count()
return c
|
[
"def",
"chunk_count",
"(",
"self",
")",
":",
"c",
"=",
"0",
"for",
"r",
"in",
"self",
".",
"iter_regions",
"(",
")",
":",
"c",
"+=",
"r",
".",
"chunk_count",
"(",
")",
"return",
"c"
] |
Return a count of the chunks in this world folder.
|
[
"Return",
"a",
"count",
"of",
"the",
"chunks",
"in",
"this",
"world",
"folder",
"."
] |
b06dd6cc8117d2788da1d8416e642d58bad45762
|
https://github.com/twoolie/NBT/blob/b06dd6cc8117d2788da1d8416e642d58bad45762/nbt/world.py#L209-L214
|
10,780
|
twoolie/NBT
|
nbt/world.py
|
_BaseWorldFolder.get_boundingbox
|
def get_boundingbox(self):
"""
Return minimum and maximum x and z coordinates of the chunks that
make up this world save
"""
b = BoundingBox()
for rx,rz in self.regionfiles.keys():
region = self.get_region(rx,rz)
rx,rz = 32*rx,32*rz
for cc in region.get_chunk_coords():
x,z = (rx+cc['x'],rz+cc['z'])
b.expand(x,None,z)
return b
|
python
|
def get_boundingbox(self):
"""
Return minimum and maximum x and z coordinates of the chunks that
make up this world save
"""
b = BoundingBox()
for rx,rz in self.regionfiles.keys():
region = self.get_region(rx,rz)
rx,rz = 32*rx,32*rz
for cc in region.get_chunk_coords():
x,z = (rx+cc['x'],rz+cc['z'])
b.expand(x,None,z)
return b
|
[
"def",
"get_boundingbox",
"(",
"self",
")",
":",
"b",
"=",
"BoundingBox",
"(",
")",
"for",
"rx",
",",
"rz",
"in",
"self",
".",
"regionfiles",
".",
"keys",
"(",
")",
":",
"region",
"=",
"self",
".",
"get_region",
"(",
"rx",
",",
"rz",
")",
"rx",
",",
"rz",
"=",
"32",
"*",
"rx",
",",
"32",
"*",
"rz",
"for",
"cc",
"in",
"region",
".",
"get_chunk_coords",
"(",
")",
":",
"x",
",",
"z",
"=",
"(",
"rx",
"+",
"cc",
"[",
"'x'",
"]",
",",
"rz",
"+",
"cc",
"[",
"'z'",
"]",
")",
"b",
".",
"expand",
"(",
"x",
",",
"None",
",",
"z",
")",
"return",
"b"
] |
Return minimum and maximum x and z coordinates of the chunks that
make up this world save
|
[
"Return",
"minimum",
"and",
"maximum",
"x",
"and",
"z",
"coordinates",
"of",
"the",
"chunks",
"that",
"make",
"up",
"this",
"world",
"save"
] |
b06dd6cc8117d2788da1d8416e642d58bad45762
|
https://github.com/twoolie/NBT/blob/b06dd6cc8117d2788da1d8416e642d58bad45762/nbt/world.py#L216-L228
|
10,781
|
twoolie/NBT
|
nbt/world.py
|
BoundingBox.expand
|
def expand(self,x,y,z):
"""
Expands the bounding
"""
if x != None:
if self.minx is None or x < self.minx:
self.minx = x
if self.maxx is None or x > self.maxx:
self.maxx = x
if y != None:
if self.miny is None or y < self.miny:
self.miny = y
if self.maxy is None or y > self.maxy:
self.maxy = y
if z != None:
if self.minz is None or z < self.minz:
self.minz = z
if self.maxz is None or z > self.maxz:
self.maxz = z
|
python
|
def expand(self,x,y,z):
"""
Expands the bounding
"""
if x != None:
if self.minx is None or x < self.minx:
self.minx = x
if self.maxx is None or x > self.maxx:
self.maxx = x
if y != None:
if self.miny is None or y < self.miny:
self.miny = y
if self.maxy is None or y > self.maxy:
self.maxy = y
if z != None:
if self.minz is None or z < self.minz:
self.minz = z
if self.maxz is None or z > self.maxz:
self.maxz = z
|
[
"def",
"expand",
"(",
"self",
",",
"x",
",",
"y",
",",
"z",
")",
":",
"if",
"x",
"!=",
"None",
":",
"if",
"self",
".",
"minx",
"is",
"None",
"or",
"x",
"<",
"self",
".",
"minx",
":",
"self",
".",
"minx",
"=",
"x",
"if",
"self",
".",
"maxx",
"is",
"None",
"or",
"x",
">",
"self",
".",
"maxx",
":",
"self",
".",
"maxx",
"=",
"x",
"if",
"y",
"!=",
"None",
":",
"if",
"self",
".",
"miny",
"is",
"None",
"or",
"y",
"<",
"self",
".",
"miny",
":",
"self",
".",
"miny",
"=",
"y",
"if",
"self",
".",
"maxy",
"is",
"None",
"or",
"y",
">",
"self",
".",
"maxy",
":",
"self",
".",
"maxy",
"=",
"y",
"if",
"z",
"!=",
"None",
":",
"if",
"self",
".",
"minz",
"is",
"None",
"or",
"z",
"<",
"self",
".",
"minz",
":",
"self",
".",
"minz",
"=",
"z",
"if",
"self",
".",
"maxz",
"is",
"None",
"or",
"z",
">",
"self",
".",
"maxz",
":",
"self",
".",
"maxz",
"=",
"z"
] |
Expands the bounding
|
[
"Expands",
"the",
"bounding"
] |
b06dd6cc8117d2788da1d8416e642d58bad45762
|
https://github.com/twoolie/NBT/blob/b06dd6cc8117d2788da1d8416e642d58bad45762/nbt/world.py#L275-L293
|
10,782
|
twoolie/NBT
|
examples/utilities.py
|
unpack_nbt
|
def unpack_nbt(tag):
"""
Unpack an NBT tag into a native Python data structure.
"""
if isinstance(tag, TAG_List):
return [unpack_nbt(i) for i in tag.tags]
elif isinstance(tag, TAG_Compound):
return dict((i.name, unpack_nbt(i)) for i in tag.tags)
else:
return tag.value
|
python
|
def unpack_nbt(tag):
"""
Unpack an NBT tag into a native Python data structure.
"""
if isinstance(tag, TAG_List):
return [unpack_nbt(i) for i in tag.tags]
elif isinstance(tag, TAG_Compound):
return dict((i.name, unpack_nbt(i)) for i in tag.tags)
else:
return tag.value
|
[
"def",
"unpack_nbt",
"(",
"tag",
")",
":",
"if",
"isinstance",
"(",
"tag",
",",
"TAG_List",
")",
":",
"return",
"[",
"unpack_nbt",
"(",
"i",
")",
"for",
"i",
"in",
"tag",
".",
"tags",
"]",
"elif",
"isinstance",
"(",
"tag",
",",
"TAG_Compound",
")",
":",
"return",
"dict",
"(",
"(",
"i",
".",
"name",
",",
"unpack_nbt",
"(",
"i",
")",
")",
"for",
"i",
"in",
"tag",
".",
"tags",
")",
"else",
":",
"return",
"tag",
".",
"value"
] |
Unpack an NBT tag into a native Python data structure.
|
[
"Unpack",
"an",
"NBT",
"tag",
"into",
"a",
"native",
"Python",
"data",
"structure",
"."
] |
b06dd6cc8117d2788da1d8416e642d58bad45762
|
https://github.com/twoolie/NBT/blob/b06dd6cc8117d2788da1d8416e642d58bad45762/examples/utilities.py#L21-L31
|
10,783
|
twoolie/NBT
|
nbt/region.py
|
RegionFile._init_file
|
def _init_file(self):
"""Initialise the file header. This will erase any data previously in the file."""
header_length = 2*SECTOR_LENGTH
if self.size > header_length:
self.file.truncate(header_length)
self.file.seek(0)
self.file.write(header_length*b'\x00')
self.size = header_length
|
python
|
def _init_file(self):
"""Initialise the file header. This will erase any data previously in the file."""
header_length = 2*SECTOR_LENGTH
if self.size > header_length:
self.file.truncate(header_length)
self.file.seek(0)
self.file.write(header_length*b'\x00')
self.size = header_length
|
[
"def",
"_init_file",
"(",
"self",
")",
":",
"header_length",
"=",
"2",
"*",
"SECTOR_LENGTH",
"if",
"self",
".",
"size",
">",
"header_length",
":",
"self",
".",
"file",
".",
"truncate",
"(",
"header_length",
")",
"self",
".",
"file",
".",
"seek",
"(",
"0",
")",
"self",
".",
"file",
".",
"write",
"(",
"header_length",
"*",
"b'\\x00'",
")",
"self",
".",
"size",
"=",
"header_length"
] |
Initialise the file header. This will erase any data previously in the file.
|
[
"Initialise",
"the",
"file",
"header",
".",
"This",
"will",
"erase",
"any",
"data",
"previously",
"in",
"the",
"file",
"."
] |
b06dd6cc8117d2788da1d8416e642d58bad45762
|
https://github.com/twoolie/NBT/blob/b06dd6cc8117d2788da1d8416e642d58bad45762/nbt/region.py#L297-L304
|
10,784
|
twoolie/NBT
|
nbt/region.py
|
RegionFile._sectors
|
def _sectors(self, ignore_chunk=None):
"""
Return a list of all sectors, each sector is a list of chunks occupying the block.
"""
sectorsize = self._bytes_to_sector(self.size)
sectors = [[] for s in range(sectorsize)]
sectors[0] = True # locations
sectors[1] = True # timestamps
for m in self.metadata.values():
if not m.is_created():
continue
if ignore_chunk == m:
continue
if m.blocklength and m.blockstart:
blockend = m.blockstart + max(m.blocklength, m.requiredblocks())
# Ensure 2 <= b < sectorsize, as well as m.blockstart <= b < blockend
for b in range(max(m.blockstart, 2), min(blockend, sectorsize)):
sectors[b].append(m)
return sectors
|
python
|
def _sectors(self, ignore_chunk=None):
"""
Return a list of all sectors, each sector is a list of chunks occupying the block.
"""
sectorsize = self._bytes_to_sector(self.size)
sectors = [[] for s in range(sectorsize)]
sectors[0] = True # locations
sectors[1] = True # timestamps
for m in self.metadata.values():
if not m.is_created():
continue
if ignore_chunk == m:
continue
if m.blocklength and m.blockstart:
blockend = m.blockstart + max(m.blocklength, m.requiredblocks())
# Ensure 2 <= b < sectorsize, as well as m.blockstart <= b < blockend
for b in range(max(m.blockstart, 2), min(blockend, sectorsize)):
sectors[b].append(m)
return sectors
|
[
"def",
"_sectors",
"(",
"self",
",",
"ignore_chunk",
"=",
"None",
")",
":",
"sectorsize",
"=",
"self",
".",
"_bytes_to_sector",
"(",
"self",
".",
"size",
")",
"sectors",
"=",
"[",
"[",
"]",
"for",
"s",
"in",
"range",
"(",
"sectorsize",
")",
"]",
"sectors",
"[",
"0",
"]",
"=",
"True",
"# locations",
"sectors",
"[",
"1",
"]",
"=",
"True",
"# timestamps",
"for",
"m",
"in",
"self",
".",
"metadata",
".",
"values",
"(",
")",
":",
"if",
"not",
"m",
".",
"is_created",
"(",
")",
":",
"continue",
"if",
"ignore_chunk",
"==",
"m",
":",
"continue",
"if",
"m",
".",
"blocklength",
"and",
"m",
".",
"blockstart",
":",
"blockend",
"=",
"m",
".",
"blockstart",
"+",
"max",
"(",
"m",
".",
"blocklength",
",",
"m",
".",
"requiredblocks",
"(",
")",
")",
"# Ensure 2 <= b < sectorsize, as well as m.blockstart <= b < blockend",
"for",
"b",
"in",
"range",
"(",
"max",
"(",
"m",
".",
"blockstart",
",",
"2",
")",
",",
"min",
"(",
"blockend",
",",
"sectorsize",
")",
")",
":",
"sectors",
"[",
"b",
"]",
".",
"append",
"(",
"m",
")",
"return",
"sectors"
] |
Return a list of all sectors, each sector is a list of chunks occupying the block.
|
[
"Return",
"a",
"list",
"of",
"all",
"sectors",
"each",
"sector",
"is",
"a",
"list",
"of",
"chunks",
"occupying",
"the",
"block",
"."
] |
b06dd6cc8117d2788da1d8416e642d58bad45762
|
https://github.com/twoolie/NBT/blob/b06dd6cc8117d2788da1d8416e642d58bad45762/nbt/region.py#L384-L402
|
10,785
|
twoolie/NBT
|
nbt/region.py
|
RegionFile._locate_free_sectors
|
def _locate_free_sectors(self, ignore_chunk=None):
"""Return a list of booleans, indicating the free sectors."""
sectors = self._sectors(ignore_chunk=ignore_chunk)
# Sectors are considered free, if the value is an empty list.
return [not i for i in sectors]
|
python
|
def _locate_free_sectors(self, ignore_chunk=None):
"""Return a list of booleans, indicating the free sectors."""
sectors = self._sectors(ignore_chunk=ignore_chunk)
# Sectors are considered free, if the value is an empty list.
return [not i for i in sectors]
|
[
"def",
"_locate_free_sectors",
"(",
"self",
",",
"ignore_chunk",
"=",
"None",
")",
":",
"sectors",
"=",
"self",
".",
"_sectors",
"(",
"ignore_chunk",
"=",
"ignore_chunk",
")",
"# Sectors are considered free, if the value is an empty list.",
"return",
"[",
"not",
"i",
"for",
"i",
"in",
"sectors",
"]"
] |
Return a list of booleans, indicating the free sectors.
|
[
"Return",
"a",
"list",
"of",
"booleans",
"indicating",
"the",
"free",
"sectors",
"."
] |
b06dd6cc8117d2788da1d8416e642d58bad45762
|
https://github.com/twoolie/NBT/blob/b06dd6cc8117d2788da1d8416e642d58bad45762/nbt/region.py#L404-L408
|
10,786
|
twoolie/NBT
|
nbt/region.py
|
RegionFile.get_nbt
|
def get_nbt(self, x, z):
"""
Return a NBTFile of the specified chunk.
Raise InconceivedChunk if the chunk is not included in the file.
"""
# TODO: cache results?
data = self.get_blockdata(x, z) # This may raise a RegionFileFormatError.
data = BytesIO(data)
err = None
try:
nbt = NBTFile(buffer=data)
if self.loc.x != None:
x += self.loc.x*32
if self.loc.z != None:
z += self.loc.z*32
nbt.loc = Location(x=x, z=z)
return nbt
# this may raise a MalformedFileError. Convert to ChunkDataError.
except MalformedFileError as e:
err = '%s' % e # avoid str(e) due to Unicode issues in Python 2.
if err:
raise ChunkDataError(err)
|
python
|
def get_nbt(self, x, z):
"""
Return a NBTFile of the specified chunk.
Raise InconceivedChunk if the chunk is not included in the file.
"""
# TODO: cache results?
data = self.get_blockdata(x, z) # This may raise a RegionFileFormatError.
data = BytesIO(data)
err = None
try:
nbt = NBTFile(buffer=data)
if self.loc.x != None:
x += self.loc.x*32
if self.loc.z != None:
z += self.loc.z*32
nbt.loc = Location(x=x, z=z)
return nbt
# this may raise a MalformedFileError. Convert to ChunkDataError.
except MalformedFileError as e:
err = '%s' % e # avoid str(e) due to Unicode issues in Python 2.
if err:
raise ChunkDataError(err)
|
[
"def",
"get_nbt",
"(",
"self",
",",
"x",
",",
"z",
")",
":",
"# TODO: cache results?",
"data",
"=",
"self",
".",
"get_blockdata",
"(",
"x",
",",
"z",
")",
"# This may raise a RegionFileFormatError.",
"data",
"=",
"BytesIO",
"(",
"data",
")",
"err",
"=",
"None",
"try",
":",
"nbt",
"=",
"NBTFile",
"(",
"buffer",
"=",
"data",
")",
"if",
"self",
".",
"loc",
".",
"x",
"!=",
"None",
":",
"x",
"+=",
"self",
".",
"loc",
".",
"x",
"*",
"32",
"if",
"self",
".",
"loc",
".",
"z",
"!=",
"None",
":",
"z",
"+=",
"self",
".",
"loc",
".",
"z",
"*",
"32",
"nbt",
".",
"loc",
"=",
"Location",
"(",
"x",
"=",
"x",
",",
"z",
"=",
"z",
")",
"return",
"nbt",
"# this may raise a MalformedFileError. Convert to ChunkDataError.",
"except",
"MalformedFileError",
"as",
"e",
":",
"err",
"=",
"'%s'",
"%",
"e",
"# avoid str(e) due to Unicode issues in Python 2.",
"if",
"err",
":",
"raise",
"ChunkDataError",
"(",
"err",
")"
] |
Return a NBTFile of the specified chunk.
Raise InconceivedChunk if the chunk is not included in the file.
|
[
"Return",
"a",
"NBTFile",
"of",
"the",
"specified",
"chunk",
".",
"Raise",
"InconceivedChunk",
"if",
"the",
"chunk",
"is",
"not",
"included",
"in",
"the",
"file",
"."
] |
b06dd6cc8117d2788da1d8416e642d58bad45762
|
https://github.com/twoolie/NBT/blob/b06dd6cc8117d2788da1d8416e642d58bad45762/nbt/region.py#L585-L606
|
10,787
|
twoolie/NBT
|
nbt/region.py
|
RegionFile.write_chunk
|
def write_chunk(self, x, z, nbt_file):
"""
Pack the NBT file as binary data, and write to file in a compressed format.
"""
data = BytesIO()
nbt_file.write_file(buffer=data) # render to buffer; uncompressed
self.write_blockdata(x, z, data.getvalue())
|
python
|
def write_chunk(self, x, z, nbt_file):
"""
Pack the NBT file as binary data, and write to file in a compressed format.
"""
data = BytesIO()
nbt_file.write_file(buffer=data) # render to buffer; uncompressed
self.write_blockdata(x, z, data.getvalue())
|
[
"def",
"write_chunk",
"(",
"self",
",",
"x",
",",
"z",
",",
"nbt_file",
")",
":",
"data",
"=",
"BytesIO",
"(",
")",
"nbt_file",
".",
"write_file",
"(",
"buffer",
"=",
"data",
")",
"# render to buffer; uncompressed",
"self",
".",
"write_blockdata",
"(",
"x",
",",
"z",
",",
"data",
".",
"getvalue",
"(",
")",
")"
] |
Pack the NBT file as binary data, and write to file in a compressed format.
|
[
"Pack",
"the",
"NBT",
"file",
"as",
"binary",
"data",
"and",
"write",
"to",
"file",
"in",
"a",
"compressed",
"format",
"."
] |
b06dd6cc8117d2788da1d8416e642d58bad45762
|
https://github.com/twoolie/NBT/blob/b06dd6cc8117d2788da1d8416e642d58bad45762/nbt/region.py#L712-L718
|
10,788
|
twoolie/NBT
|
nbt/region.py
|
RegionFile.unlink_chunk
|
def unlink_chunk(self, x, z):
"""
Remove a chunk from the header of the region file.
Fragmentation is not a problem, chunks are written to free sectors when possible.
"""
# This function fails for an empty file. If that is the case, just return.
if self.size < 2*SECTOR_LENGTH:
return
# zero the region header for the chunk (offset length and time)
self.file.seek(4 * (x + 32*z))
self.file.write(pack(">IB", 0, 0)[1:])
self.file.seek(SECTOR_LENGTH + 4 * (x + 32*z))
self.file.write(pack(">I", 0))
# Check if file should be truncated:
current = self.metadata[x, z]
free_sectors = self._locate_free_sectors(ignore_chunk=current)
truncate_count = list(reversed(free_sectors)).index(False)
if truncate_count > 0:
self.size = SECTOR_LENGTH * (len(free_sectors) - truncate_count)
self.file.truncate(self.size)
free_sectors = free_sectors[:-truncate_count]
# Calculate freed sectors
for s in range(current.blockstart, min(current.blockstart + current.blocklength, len(free_sectors))):
if free_sectors[s]:
# zero sector s
self.file.seek(SECTOR_LENGTH*s)
self.file.write(SECTOR_LENGTH*b'\x00')
# update the header
self.metadata[x, z] = ChunkMetadata(x, z)
|
python
|
def unlink_chunk(self, x, z):
"""
Remove a chunk from the header of the region file.
Fragmentation is not a problem, chunks are written to free sectors when possible.
"""
# This function fails for an empty file. If that is the case, just return.
if self.size < 2*SECTOR_LENGTH:
return
# zero the region header for the chunk (offset length and time)
self.file.seek(4 * (x + 32*z))
self.file.write(pack(">IB", 0, 0)[1:])
self.file.seek(SECTOR_LENGTH + 4 * (x + 32*z))
self.file.write(pack(">I", 0))
# Check if file should be truncated:
current = self.metadata[x, z]
free_sectors = self._locate_free_sectors(ignore_chunk=current)
truncate_count = list(reversed(free_sectors)).index(False)
if truncate_count > 0:
self.size = SECTOR_LENGTH * (len(free_sectors) - truncate_count)
self.file.truncate(self.size)
free_sectors = free_sectors[:-truncate_count]
# Calculate freed sectors
for s in range(current.blockstart, min(current.blockstart + current.blocklength, len(free_sectors))):
if free_sectors[s]:
# zero sector s
self.file.seek(SECTOR_LENGTH*s)
self.file.write(SECTOR_LENGTH*b'\x00')
# update the header
self.metadata[x, z] = ChunkMetadata(x, z)
|
[
"def",
"unlink_chunk",
"(",
"self",
",",
"x",
",",
"z",
")",
":",
"# This function fails for an empty file. If that is the case, just return.",
"if",
"self",
".",
"size",
"<",
"2",
"*",
"SECTOR_LENGTH",
":",
"return",
"# zero the region header for the chunk (offset length and time)",
"self",
".",
"file",
".",
"seek",
"(",
"4",
"*",
"(",
"x",
"+",
"32",
"*",
"z",
")",
")",
"self",
".",
"file",
".",
"write",
"(",
"pack",
"(",
"\">IB\"",
",",
"0",
",",
"0",
")",
"[",
"1",
":",
"]",
")",
"self",
".",
"file",
".",
"seek",
"(",
"SECTOR_LENGTH",
"+",
"4",
"*",
"(",
"x",
"+",
"32",
"*",
"z",
")",
")",
"self",
".",
"file",
".",
"write",
"(",
"pack",
"(",
"\">I\"",
",",
"0",
")",
")",
"# Check if file should be truncated:",
"current",
"=",
"self",
".",
"metadata",
"[",
"x",
",",
"z",
"]",
"free_sectors",
"=",
"self",
".",
"_locate_free_sectors",
"(",
"ignore_chunk",
"=",
"current",
")",
"truncate_count",
"=",
"list",
"(",
"reversed",
"(",
"free_sectors",
")",
")",
".",
"index",
"(",
"False",
")",
"if",
"truncate_count",
">",
"0",
":",
"self",
".",
"size",
"=",
"SECTOR_LENGTH",
"*",
"(",
"len",
"(",
"free_sectors",
")",
"-",
"truncate_count",
")",
"self",
".",
"file",
".",
"truncate",
"(",
"self",
".",
"size",
")",
"free_sectors",
"=",
"free_sectors",
"[",
":",
"-",
"truncate_count",
"]",
"# Calculate freed sectors",
"for",
"s",
"in",
"range",
"(",
"current",
".",
"blockstart",
",",
"min",
"(",
"current",
".",
"blockstart",
"+",
"current",
".",
"blocklength",
",",
"len",
"(",
"free_sectors",
")",
")",
")",
":",
"if",
"free_sectors",
"[",
"s",
"]",
":",
"# zero sector s",
"self",
".",
"file",
".",
"seek",
"(",
"SECTOR_LENGTH",
"*",
"s",
")",
"self",
".",
"file",
".",
"write",
"(",
"SECTOR_LENGTH",
"*",
"b'\\x00'",
")",
"# update the header",
"self",
".",
"metadata",
"[",
"x",
",",
"z",
"]",
"=",
"ChunkMetadata",
"(",
"x",
",",
"z",
")"
] |
Remove a chunk from the header of the region file.
Fragmentation is not a problem, chunks are written to free sectors when possible.
|
[
"Remove",
"a",
"chunk",
"from",
"the",
"header",
"of",
"the",
"region",
"file",
".",
"Fragmentation",
"is",
"not",
"a",
"problem",
"chunks",
"are",
"written",
"to",
"free",
"sectors",
"when",
"possible",
"."
] |
b06dd6cc8117d2788da1d8416e642d58bad45762
|
https://github.com/twoolie/NBT/blob/b06dd6cc8117d2788da1d8416e642d58bad45762/nbt/region.py#L720-L752
|
10,789
|
twoolie/NBT
|
nbt/region.py
|
RegionFile._classname
|
def _classname(self):
"""Return the fully qualified class name."""
if self.__class__.__module__ in (None,):
return self.__class__.__name__
else:
return "%s.%s" % (self.__class__.__module__, self.__class__.__name__)
|
python
|
def _classname(self):
"""Return the fully qualified class name."""
if self.__class__.__module__ in (None,):
return self.__class__.__name__
else:
return "%s.%s" % (self.__class__.__module__, self.__class__.__name__)
|
[
"def",
"_classname",
"(",
"self",
")",
":",
"if",
"self",
".",
"__class__",
".",
"__module__",
"in",
"(",
"None",
",",
")",
":",
"return",
"self",
".",
"__class__",
".",
"__name__",
"else",
":",
"return",
"\"%s.%s\"",
"%",
"(",
"self",
".",
"__class__",
".",
"__module__",
",",
"self",
".",
"__class__",
".",
"__name__",
")"
] |
Return the fully qualified class name.
|
[
"Return",
"the",
"fully",
"qualified",
"class",
"name",
"."
] |
b06dd6cc8117d2788da1d8416e642d58bad45762
|
https://github.com/twoolie/NBT/blob/b06dd6cc8117d2788da1d8416e642d58bad45762/nbt/region.py#L754-L759
|
10,790
|
twoolie/NBT
|
examples/chest_analysis.py
|
chests_per_chunk
|
def chests_per_chunk(chunk):
"""Find chests and get contents in a given chunk."""
chests = []
for entity in chunk['Entities']:
eid = entity["id"].value
if eid == "Minecart" and entity["type"].value == 1 or eid == "minecraft:chest_minecart":
x,y,z = entity["Pos"]
x,y,z = x.value,y.value,z.value
# Treasures are empty upon first opening
try:
items = items_from_nbt(entity["Items"])
except KeyError:
items = {}
chests.append(Chest("Minecart with chest",(x,y,z),items))
for entity in chunk['TileEntities']:
eid = entity["id"].value
if eid == "Chest" or eid == "minecraft:chest":
x,y,z = entity["x"].value,entity["y"].value,entity["z"].value
# Treasures are empty upon first opening
try:
items = items_from_nbt(entity["Items"])
except KeyError:
items = {}
chests.append(Chest("Chest",(x,y,z),items))
return chests
|
python
|
def chests_per_chunk(chunk):
"""Find chests and get contents in a given chunk."""
chests = []
for entity in chunk['Entities']:
eid = entity["id"].value
if eid == "Minecart" and entity["type"].value == 1 or eid == "minecraft:chest_minecart":
x,y,z = entity["Pos"]
x,y,z = x.value,y.value,z.value
# Treasures are empty upon first opening
try:
items = items_from_nbt(entity["Items"])
except KeyError:
items = {}
chests.append(Chest("Minecart with chest",(x,y,z),items))
for entity in chunk['TileEntities']:
eid = entity["id"].value
if eid == "Chest" or eid == "minecraft:chest":
x,y,z = entity["x"].value,entity["y"].value,entity["z"].value
# Treasures are empty upon first opening
try:
items = items_from_nbt(entity["Items"])
except KeyError:
items = {}
chests.append(Chest("Chest",(x,y,z),items))
return chests
|
[
"def",
"chests_per_chunk",
"(",
"chunk",
")",
":",
"chests",
"=",
"[",
"]",
"for",
"entity",
"in",
"chunk",
"[",
"'Entities'",
"]",
":",
"eid",
"=",
"entity",
"[",
"\"id\"",
"]",
".",
"value",
"if",
"eid",
"==",
"\"Minecart\"",
"and",
"entity",
"[",
"\"type\"",
"]",
".",
"value",
"==",
"1",
"or",
"eid",
"==",
"\"minecraft:chest_minecart\"",
":",
"x",
",",
"y",
",",
"z",
"=",
"entity",
"[",
"\"Pos\"",
"]",
"x",
",",
"y",
",",
"z",
"=",
"x",
".",
"value",
",",
"y",
".",
"value",
",",
"z",
".",
"value",
"# Treasures are empty upon first opening",
"try",
":",
"items",
"=",
"items_from_nbt",
"(",
"entity",
"[",
"\"Items\"",
"]",
")",
"except",
"KeyError",
":",
"items",
"=",
"{",
"}",
"chests",
".",
"append",
"(",
"Chest",
"(",
"\"Minecart with chest\"",
",",
"(",
"x",
",",
"y",
",",
"z",
")",
",",
"items",
")",
")",
"for",
"entity",
"in",
"chunk",
"[",
"'TileEntities'",
"]",
":",
"eid",
"=",
"entity",
"[",
"\"id\"",
"]",
".",
"value",
"if",
"eid",
"==",
"\"Chest\"",
"or",
"eid",
"==",
"\"minecraft:chest\"",
":",
"x",
",",
"y",
",",
"z",
"=",
"entity",
"[",
"\"x\"",
"]",
".",
"value",
",",
"entity",
"[",
"\"y\"",
"]",
".",
"value",
",",
"entity",
"[",
"\"z\"",
"]",
".",
"value",
"# Treasures are empty upon first opening",
"try",
":",
"items",
"=",
"items_from_nbt",
"(",
"entity",
"[",
"\"Items\"",
"]",
")",
"except",
"KeyError",
":",
"items",
"=",
"{",
"}",
"chests",
".",
"append",
"(",
"Chest",
"(",
"\"Chest\"",
",",
"(",
"x",
",",
"y",
",",
"z",
")",
",",
"items",
")",
")",
"return",
"chests"
] |
Find chests and get contents in a given chunk.
|
[
"Find",
"chests",
"and",
"get",
"contents",
"in",
"a",
"given",
"chunk",
"."
] |
b06dd6cc8117d2788da1d8416e642d58bad45762
|
https://github.com/twoolie/NBT/blob/b06dd6cc8117d2788da1d8416e642d58bad45762/examples/chest_analysis.py#L49-L81
|
10,791
|
twoolie/NBT
|
nbt/chunk.py
|
AnvilChunk.get_block
|
def get_block(self, x, y, z):
"""Get a block from relative x,y,z."""
sy,by = divmod(y, 16)
section = self.get_section(sy)
if section == None:
return None
return section.get_block(x, by, z)
|
python
|
def get_block(self, x, y, z):
"""Get a block from relative x,y,z."""
sy,by = divmod(y, 16)
section = self.get_section(sy)
if section == None:
return None
return section.get_block(x, by, z)
|
[
"def",
"get_block",
"(",
"self",
",",
"x",
",",
"y",
",",
"z",
")",
":",
"sy",
",",
"by",
"=",
"divmod",
"(",
"y",
",",
"16",
")",
"section",
"=",
"self",
".",
"get_section",
"(",
"sy",
")",
"if",
"section",
"==",
"None",
":",
"return",
"None",
"return",
"section",
".",
"get_block",
"(",
"x",
",",
"by",
",",
"z",
")"
] |
Get a block from relative x,y,z.
|
[
"Get",
"a",
"block",
"from",
"relative",
"x",
"y",
"z",
"."
] |
b06dd6cc8117d2788da1d8416e642d58bad45762
|
https://github.com/twoolie/NBT/blob/b06dd6cc8117d2788da1d8416e642d58bad45762/nbt/chunk.py#L281-L288
|
10,792
|
twoolie/NBT
|
nbt/chunk.py
|
BlockArray.get_blocks_byte_array
|
def get_blocks_byte_array(self, buffer=False):
"""Return a list of all blocks in this chunk."""
if buffer:
length = len(self.blocksList)
return BytesIO(pack(">i", length)+self.get_blocks_byte_array())
else:
return array.array('B', self.blocksList).tostring()
|
python
|
def get_blocks_byte_array(self, buffer=False):
"""Return a list of all blocks in this chunk."""
if buffer:
length = len(self.blocksList)
return BytesIO(pack(">i", length)+self.get_blocks_byte_array())
else:
return array.array('B', self.blocksList).tostring()
|
[
"def",
"get_blocks_byte_array",
"(",
"self",
",",
"buffer",
"=",
"False",
")",
":",
"if",
"buffer",
":",
"length",
"=",
"len",
"(",
"self",
".",
"blocksList",
")",
"return",
"BytesIO",
"(",
"pack",
"(",
"\">i\"",
",",
"length",
")",
"+",
"self",
".",
"get_blocks_byte_array",
"(",
")",
")",
"else",
":",
"return",
"array",
".",
"array",
"(",
"'B'",
",",
"self",
".",
"blocksList",
")",
".",
"tostring",
"(",
")"
] |
Return a list of all blocks in this chunk.
|
[
"Return",
"a",
"list",
"of",
"all",
"blocks",
"in",
"this",
"chunk",
"."
] |
b06dd6cc8117d2788da1d8416e642d58bad45762
|
https://github.com/twoolie/NBT/blob/b06dd6cc8117d2788da1d8416e642d58bad45762/nbt/chunk.py#L329-L335
|
10,793
|
twoolie/NBT
|
nbt/chunk.py
|
BlockArray.get_data_byte_array
|
def get_data_byte_array(self, buffer=False):
"""Return a list of data for all blocks in this chunk."""
if buffer:
length = len(self.dataList)
return BytesIO(pack(">i", length)+self.get_data_byte_array())
else:
return array.array('B', self.dataList).tostring()
|
python
|
def get_data_byte_array(self, buffer=False):
"""Return a list of data for all blocks in this chunk."""
if buffer:
length = len(self.dataList)
return BytesIO(pack(">i", length)+self.get_data_byte_array())
else:
return array.array('B', self.dataList).tostring()
|
[
"def",
"get_data_byte_array",
"(",
"self",
",",
"buffer",
"=",
"False",
")",
":",
"if",
"buffer",
":",
"length",
"=",
"len",
"(",
"self",
".",
"dataList",
")",
"return",
"BytesIO",
"(",
"pack",
"(",
"\">i\"",
",",
"length",
")",
"+",
"self",
".",
"get_data_byte_array",
"(",
")",
")",
"else",
":",
"return",
"array",
".",
"array",
"(",
"'B'",
",",
"self",
".",
"dataList",
")",
".",
"tostring",
"(",
")"
] |
Return a list of data for all blocks in this chunk.
|
[
"Return",
"a",
"list",
"of",
"data",
"for",
"all",
"blocks",
"in",
"this",
"chunk",
"."
] |
b06dd6cc8117d2788da1d8416e642d58bad45762
|
https://github.com/twoolie/NBT/blob/b06dd6cc8117d2788da1d8416e642d58bad45762/nbt/chunk.py#L337-L343
|
10,794
|
twoolie/NBT
|
nbt/chunk.py
|
BlockArray.generate_heightmap
|
def generate_heightmap(self, buffer=False, as_array=False):
"""Return a heightmap, representing the highest solid blocks in this chunk."""
non_solids = [0, 8, 9, 10, 11, 38, 37, 32, 31]
if buffer:
return BytesIO(pack(">i", 256)+self.generate_heightmap()) # Length + Heightmap, ready for insertion into Chunk NBT
else:
bytes = []
for z in range(16):
for x in range(16):
for y in range(127, -1, -1):
offset = y + z*128 + x*128*16
if (self.blocksList[offset] not in non_solids or y == 0):
bytes.append(y+1)
break
if (as_array):
return bytes
else:
return array.array('B', bytes).tostring()
|
python
|
def generate_heightmap(self, buffer=False, as_array=False):
"""Return a heightmap, representing the highest solid blocks in this chunk."""
non_solids = [0, 8, 9, 10, 11, 38, 37, 32, 31]
if buffer:
return BytesIO(pack(">i", 256)+self.generate_heightmap()) # Length + Heightmap, ready for insertion into Chunk NBT
else:
bytes = []
for z in range(16):
for x in range(16):
for y in range(127, -1, -1):
offset = y + z*128 + x*128*16
if (self.blocksList[offset] not in non_solids or y == 0):
bytes.append(y+1)
break
if (as_array):
return bytes
else:
return array.array('B', bytes).tostring()
|
[
"def",
"generate_heightmap",
"(",
"self",
",",
"buffer",
"=",
"False",
",",
"as_array",
"=",
"False",
")",
":",
"non_solids",
"=",
"[",
"0",
",",
"8",
",",
"9",
",",
"10",
",",
"11",
",",
"38",
",",
"37",
",",
"32",
",",
"31",
"]",
"if",
"buffer",
":",
"return",
"BytesIO",
"(",
"pack",
"(",
"\">i\"",
",",
"256",
")",
"+",
"self",
".",
"generate_heightmap",
"(",
")",
")",
"# Length + Heightmap, ready for insertion into Chunk NBT",
"else",
":",
"bytes",
"=",
"[",
"]",
"for",
"z",
"in",
"range",
"(",
"16",
")",
":",
"for",
"x",
"in",
"range",
"(",
"16",
")",
":",
"for",
"y",
"in",
"range",
"(",
"127",
",",
"-",
"1",
",",
"-",
"1",
")",
":",
"offset",
"=",
"y",
"+",
"z",
"*",
"128",
"+",
"x",
"*",
"128",
"*",
"16",
"if",
"(",
"self",
".",
"blocksList",
"[",
"offset",
"]",
"not",
"in",
"non_solids",
"or",
"y",
"==",
"0",
")",
":",
"bytes",
".",
"append",
"(",
"y",
"+",
"1",
")",
"break",
"if",
"(",
"as_array",
")",
":",
"return",
"bytes",
"else",
":",
"return",
"array",
".",
"array",
"(",
"'B'",
",",
"bytes",
")",
".",
"tostring",
"(",
")"
] |
Return a heightmap, representing the highest solid blocks in this chunk.
|
[
"Return",
"a",
"heightmap",
"representing",
"the",
"highest",
"solid",
"blocks",
"in",
"this",
"chunk",
"."
] |
b06dd6cc8117d2788da1d8416e642d58bad45762
|
https://github.com/twoolie/NBT/blob/b06dd6cc8117d2788da1d8416e642d58bad45762/nbt/chunk.py#L345-L362
|
10,795
|
twoolie/NBT
|
nbt/chunk.py
|
BlockArray.set_blocks
|
def set_blocks(self, list=None, dict=None, fill_air=False):
"""
Sets all blocks in this chunk, using either a list or dictionary.
Blocks not explicitly set can be filled to air by setting fill_air to True.
"""
if list:
# Inputting a list like self.blocksList
self.blocksList = list
elif dict:
# Inputting a dictionary like result of self.get_blocks_struct()
list = []
for x in range(16):
for z in range(16):
for y in range(128):
coord = x,y,z
offset = y + z*128 + x*128*16
if (coord in dict):
list.append(dict[coord])
else:
if (self.blocksList[offset] and not fill_air):
list.append(self.blocksList[offset])
else:
list.append(0) # Air
self.blocksList = list
else:
# None of the above...
return False
return True
|
python
|
def set_blocks(self, list=None, dict=None, fill_air=False):
"""
Sets all blocks in this chunk, using either a list or dictionary.
Blocks not explicitly set can be filled to air by setting fill_air to True.
"""
if list:
# Inputting a list like self.blocksList
self.blocksList = list
elif dict:
# Inputting a dictionary like result of self.get_blocks_struct()
list = []
for x in range(16):
for z in range(16):
for y in range(128):
coord = x,y,z
offset = y + z*128 + x*128*16
if (coord in dict):
list.append(dict[coord])
else:
if (self.blocksList[offset] and not fill_air):
list.append(self.blocksList[offset])
else:
list.append(0) # Air
self.blocksList = list
else:
# None of the above...
return False
return True
|
[
"def",
"set_blocks",
"(",
"self",
",",
"list",
"=",
"None",
",",
"dict",
"=",
"None",
",",
"fill_air",
"=",
"False",
")",
":",
"if",
"list",
":",
"# Inputting a list like self.blocksList",
"self",
".",
"blocksList",
"=",
"list",
"elif",
"dict",
":",
"# Inputting a dictionary like result of self.get_blocks_struct()",
"list",
"=",
"[",
"]",
"for",
"x",
"in",
"range",
"(",
"16",
")",
":",
"for",
"z",
"in",
"range",
"(",
"16",
")",
":",
"for",
"y",
"in",
"range",
"(",
"128",
")",
":",
"coord",
"=",
"x",
",",
"y",
",",
"z",
"offset",
"=",
"y",
"+",
"z",
"*",
"128",
"+",
"x",
"*",
"128",
"*",
"16",
"if",
"(",
"coord",
"in",
"dict",
")",
":",
"list",
".",
"append",
"(",
"dict",
"[",
"coord",
"]",
")",
"else",
":",
"if",
"(",
"self",
".",
"blocksList",
"[",
"offset",
"]",
"and",
"not",
"fill_air",
")",
":",
"list",
".",
"append",
"(",
"self",
".",
"blocksList",
"[",
"offset",
"]",
")",
"else",
":",
"list",
".",
"append",
"(",
"0",
")",
"# Air",
"self",
".",
"blocksList",
"=",
"list",
"else",
":",
"# None of the above...",
"return",
"False",
"return",
"True"
] |
Sets all blocks in this chunk, using either a list or dictionary.
Blocks not explicitly set can be filled to air by setting fill_air to True.
|
[
"Sets",
"all",
"blocks",
"in",
"this",
"chunk",
"using",
"either",
"a",
"list",
"or",
"dictionary",
".",
"Blocks",
"not",
"explicitly",
"set",
"can",
"be",
"filled",
"to",
"air",
"by",
"setting",
"fill_air",
"to",
"True",
"."
] |
b06dd6cc8117d2788da1d8416e642d58bad45762
|
https://github.com/twoolie/NBT/blob/b06dd6cc8117d2788da1d8416e642d58bad45762/nbt/chunk.py#L364-L391
|
10,796
|
twoolie/NBT
|
nbt/chunk.py
|
BlockArray.set_block
|
def set_block(self, x,y,z, id, data=0):
"""Sets the block a x, y, z to the specified id, and optionally data."""
offset = y + z*128 + x*128*16
self.blocksList[offset] = id
if (offset % 2 == 1):
# offset is odd
index = (offset-1)//2
b = self.dataList[index]
self.dataList[index] = (b & 240) + (data & 15) # modify lower bits, leaving higher bits in place
else:
# offset is even
index = offset//2
b = self.dataList[index]
self.dataList[index] = (b & 15) + (data << 4 & 240)
|
python
|
def set_block(self, x,y,z, id, data=0):
"""Sets the block a x, y, z to the specified id, and optionally data."""
offset = y + z*128 + x*128*16
self.blocksList[offset] = id
if (offset % 2 == 1):
# offset is odd
index = (offset-1)//2
b = self.dataList[index]
self.dataList[index] = (b & 240) + (data & 15) # modify lower bits, leaving higher bits in place
else:
# offset is even
index = offset//2
b = self.dataList[index]
self.dataList[index] = (b & 15) + (data << 4 & 240)
|
[
"def",
"set_block",
"(",
"self",
",",
"x",
",",
"y",
",",
"z",
",",
"id",
",",
"data",
"=",
"0",
")",
":",
"offset",
"=",
"y",
"+",
"z",
"*",
"128",
"+",
"x",
"*",
"128",
"*",
"16",
"self",
".",
"blocksList",
"[",
"offset",
"]",
"=",
"id",
"if",
"(",
"offset",
"%",
"2",
"==",
"1",
")",
":",
"# offset is odd",
"index",
"=",
"(",
"offset",
"-",
"1",
")",
"//",
"2",
"b",
"=",
"self",
".",
"dataList",
"[",
"index",
"]",
"self",
".",
"dataList",
"[",
"index",
"]",
"=",
"(",
"b",
"&",
"240",
")",
"+",
"(",
"data",
"&",
"15",
")",
"# modify lower bits, leaving higher bits in place",
"else",
":",
"# offset is even",
"index",
"=",
"offset",
"//",
"2",
"b",
"=",
"self",
".",
"dataList",
"[",
"index",
"]",
"self",
".",
"dataList",
"[",
"index",
"]",
"=",
"(",
"b",
"&",
"15",
")",
"+",
"(",
"data",
"<<",
"4",
"&",
"240",
")"
] |
Sets the block a x, y, z to the specified id, and optionally data.
|
[
"Sets",
"the",
"block",
"a",
"x",
"y",
"z",
"to",
"the",
"specified",
"id",
"and",
"optionally",
"data",
"."
] |
b06dd6cc8117d2788da1d8416e642d58bad45762
|
https://github.com/twoolie/NBT/blob/b06dd6cc8117d2788da1d8416e642d58bad45762/nbt/chunk.py#L393-L406
|
10,797
|
twoolie/NBT
|
nbt/chunk.py
|
BlockArray.get_block
|
def get_block(self, x,y,z, coord=False):
"""Return the id of the block at x, y, z."""
"""
Laid out like:
(0,0,0), (0,1,0), (0,2,0) ... (0,127,0), (0,0,1), (0,1,1), (0,2,1) ... (0,127,1), (0,0,2) ... (0,127,15), (1,0,0), (1,1,0) ... (15,127,15)
::
blocks = []
for x in range(15):
for z in range(15):
for y in range(127):
blocks.append(Block(x,y,z))
"""
offset = y + z*128 + x*128*16 if (coord == False) else coord[1] + coord[2]*128 + coord[0]*128*16
return self.blocksList[offset]
|
python
|
def get_block(self, x,y,z, coord=False):
"""Return the id of the block at x, y, z."""
"""
Laid out like:
(0,0,0), (0,1,0), (0,2,0) ... (0,127,0), (0,0,1), (0,1,1), (0,2,1) ... (0,127,1), (0,0,2) ... (0,127,15), (1,0,0), (1,1,0) ... (15,127,15)
::
blocks = []
for x in range(15):
for z in range(15):
for y in range(127):
blocks.append(Block(x,y,z))
"""
offset = y + z*128 + x*128*16 if (coord == False) else coord[1] + coord[2]*128 + coord[0]*128*16
return self.blocksList[offset]
|
[
"def",
"get_block",
"(",
"self",
",",
"x",
",",
"y",
",",
"z",
",",
"coord",
"=",
"False",
")",
":",
"\"\"\"\n Laid out like:\n (0,0,0), (0,1,0), (0,2,0) ... (0,127,0), (0,0,1), (0,1,1), (0,2,1) ... (0,127,1), (0,0,2) ... (0,127,15), (1,0,0), (1,1,0) ... (15,127,15)\n \n ::\n \n blocks = []\n for x in range(15):\n for z in range(15):\n for y in range(127):\n blocks.append(Block(x,y,z))\n \"\"\"",
"offset",
"=",
"y",
"+",
"z",
"*",
"128",
"+",
"x",
"*",
"128",
"*",
"16",
"if",
"(",
"coord",
"==",
"False",
")",
"else",
"coord",
"[",
"1",
"]",
"+",
"coord",
"[",
"2",
"]",
"*",
"128",
"+",
"coord",
"[",
"0",
"]",
"*",
"128",
"*",
"16",
"return",
"self",
".",
"blocksList",
"[",
"offset",
"]"
] |
Return the id of the block at x, y, z.
|
[
"Return",
"the",
"id",
"of",
"the",
"block",
"at",
"x",
"y",
"z",
"."
] |
b06dd6cc8117d2788da1d8416e642d58bad45762
|
https://github.com/twoolie/NBT/blob/b06dd6cc8117d2788da1d8416e642d58bad45762/nbt/chunk.py#L409-L425
|
10,798
|
twoolie/NBT
|
nbt/nbt.py
|
TAG.tag_info
|
def tag_info(self):
"""Return Unicode string with class, name and unnested value."""
return self.__class__.__name__ + (
'(%r)' % self.name if self.name
else "") + ": " + self.valuestr()
|
python
|
def tag_info(self):
"""Return Unicode string with class, name and unnested value."""
return self.__class__.__name__ + (
'(%r)' % self.name if self.name
else "") + ": " + self.valuestr()
|
[
"def",
"tag_info",
"(",
"self",
")",
":",
"return",
"self",
".",
"__class__",
".",
"__name__",
"+",
"(",
"'(%r)'",
"%",
"self",
".",
"name",
"if",
"self",
".",
"name",
"else",
"\"\"",
")",
"+",
"\": \"",
"+",
"self",
".",
"valuestr",
"(",
")"
] |
Return Unicode string with class, name and unnested value.
|
[
"Return",
"Unicode",
"string",
"with",
"class",
"name",
"and",
"unnested",
"value",
"."
] |
b06dd6cc8117d2788da1d8416e642d58bad45762
|
https://github.com/twoolie/NBT/blob/b06dd6cc8117d2788da1d8416e642d58bad45762/nbt/nbt.py#L56-L60
|
10,799
|
twoolie/NBT
|
nbt/nbt.py
|
NBTFile.parse_file
|
def parse_file(self, filename=None, buffer=None, fileobj=None):
"""Completely parse a file, extracting all tags."""
if filename:
self.file = GzipFile(filename, 'rb')
elif buffer:
if hasattr(buffer, 'name'):
self.filename = buffer.name
self.file = buffer
elif fileobj:
if hasattr(fileobj, 'name'):
self.filename = fileobj.name
self.file = GzipFile(fileobj=fileobj)
if self.file:
try:
type = TAG_Byte(buffer=self.file)
if type.value == self.id:
name = TAG_String(buffer=self.file).value
self._parse_buffer(self.file)
self.name = name
self.file.close()
else:
raise MalformedFileError(
"First record is not a Compound Tag")
except StructError as e:
raise MalformedFileError(
"Partial File Parse: file possibly truncated.")
else:
raise ValueError(
"NBTFile.parse_file(): Need to specify either a "
"filename or a file object"
)
|
python
|
def parse_file(self, filename=None, buffer=None, fileobj=None):
"""Completely parse a file, extracting all tags."""
if filename:
self.file = GzipFile(filename, 'rb')
elif buffer:
if hasattr(buffer, 'name'):
self.filename = buffer.name
self.file = buffer
elif fileobj:
if hasattr(fileobj, 'name'):
self.filename = fileobj.name
self.file = GzipFile(fileobj=fileobj)
if self.file:
try:
type = TAG_Byte(buffer=self.file)
if type.value == self.id:
name = TAG_String(buffer=self.file).value
self._parse_buffer(self.file)
self.name = name
self.file.close()
else:
raise MalformedFileError(
"First record is not a Compound Tag")
except StructError as e:
raise MalformedFileError(
"Partial File Parse: file possibly truncated.")
else:
raise ValueError(
"NBTFile.parse_file(): Need to specify either a "
"filename or a file object"
)
|
[
"def",
"parse_file",
"(",
"self",
",",
"filename",
"=",
"None",
",",
"buffer",
"=",
"None",
",",
"fileobj",
"=",
"None",
")",
":",
"if",
"filename",
":",
"self",
".",
"file",
"=",
"GzipFile",
"(",
"filename",
",",
"'rb'",
")",
"elif",
"buffer",
":",
"if",
"hasattr",
"(",
"buffer",
",",
"'name'",
")",
":",
"self",
".",
"filename",
"=",
"buffer",
".",
"name",
"self",
".",
"file",
"=",
"buffer",
"elif",
"fileobj",
":",
"if",
"hasattr",
"(",
"fileobj",
",",
"'name'",
")",
":",
"self",
".",
"filename",
"=",
"fileobj",
".",
"name",
"self",
".",
"file",
"=",
"GzipFile",
"(",
"fileobj",
"=",
"fileobj",
")",
"if",
"self",
".",
"file",
":",
"try",
":",
"type",
"=",
"TAG_Byte",
"(",
"buffer",
"=",
"self",
".",
"file",
")",
"if",
"type",
".",
"value",
"==",
"self",
".",
"id",
":",
"name",
"=",
"TAG_String",
"(",
"buffer",
"=",
"self",
".",
"file",
")",
".",
"value",
"self",
".",
"_parse_buffer",
"(",
"self",
".",
"file",
")",
"self",
".",
"name",
"=",
"name",
"self",
".",
"file",
".",
"close",
"(",
")",
"else",
":",
"raise",
"MalformedFileError",
"(",
"\"First record is not a Compound Tag\"",
")",
"except",
"StructError",
"as",
"e",
":",
"raise",
"MalformedFileError",
"(",
"\"Partial File Parse: file possibly truncated.\"",
")",
"else",
":",
"raise",
"ValueError",
"(",
"\"NBTFile.parse_file(): Need to specify either a \"",
"\"filename or a file object\"",
")"
] |
Completely parse a file, extracting all tags.
|
[
"Completely",
"parse",
"a",
"file",
"extracting",
"all",
"tags",
"."
] |
b06dd6cc8117d2788da1d8416e642d58bad45762
|
https://github.com/twoolie/NBT/blob/b06dd6cc8117d2788da1d8416e642d58bad45762/nbt/nbt.py#L641-L671
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.