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
listlengths
20
707
docstring
stringlengths
3
17.3k
docstring_tokens
listlengths
3
222
sha
stringlengths
40
40
url
stringlengths
87
242
partition
stringclasses
1 value
idx
int64
0
252k
obriencj/python-javatools
javatools/cheetah/__init__.py
xml_entity_escape
def xml_entity_escape(data): """ replace special characters with their XML entity versions """ data = data.replace("&", "&amp;") data = data.replace(">", "&gt;") data = data.replace("<", "&lt;") return data
python
def xml_entity_escape(data): """ replace special characters with their XML entity versions """ data = data.replace("&", "&amp;") data = data.replace(">", "&gt;") data = data.replace("<", "&lt;") return data
[ "def", "xml_entity_escape", "(", "data", ")", ":", "data", "=", "data", ".", "replace", "(", "\"&\"", ",", "\"&amp;\"", ")", "data", "=", "data", ".", "replace", "(", "\">\"", ",", "\"&gt;\"", ")", "data", "=", "data", ".", "replace", "(", "\"<\"", "...
replace special characters with their XML entity versions
[ "replace", "special", "characters", "with", "their", "XML", "entity", "versions" ]
9e2332b452ddc508bed0615937dddcb2cf051557
https://github.com/obriencj/python-javatools/blob/9e2332b452ddc508bed0615937dddcb2cf051557/javatools/cheetah/__init__.py#L53-L61
train
30,300
obriencj/python-javatools
javatools/classinfo.py
should_show
def should_show(options, member): """ whether to show a member by its access flags and the show option. There's probably a faster and smarter way to do this, but eh. """ show = options.show if show == SHOW_PUBLIC: return member.is_public() elif show == SHOW_PACKAGE: return member.is_public() or member.is_protected() elif show == SHOW_PRIVATE: return True
python
def should_show(options, member): """ whether to show a member by its access flags and the show option. There's probably a faster and smarter way to do this, but eh. """ show = options.show if show == SHOW_PUBLIC: return member.is_public() elif show == SHOW_PACKAGE: return member.is_public() or member.is_protected() elif show == SHOW_PRIVATE: return True
[ "def", "should_show", "(", "options", ",", "member", ")", ":", "show", "=", "options", ".", "show", "if", "show", "==", "SHOW_PUBLIC", ":", "return", "member", ".", "is_public", "(", ")", "elif", "show", "==", "SHOW_PACKAGE", ":", "return", "member", "."...
whether to show a member by its access flags and the show option. There's probably a faster and smarter way to do this, but eh.
[ "whether", "to", "show", "a", "member", "by", "its", "access", "flags", "and", "the", "show", "option", ".", "There", "s", "probably", "a", "faster", "and", "smarter", "way", "to", "do", "this", "but", "eh", "." ]
9e2332b452ddc508bed0615937dddcb2cf051557
https://github.com/obriencj/python-javatools/blob/9e2332b452ddc508bed0615937dddcb2cf051557/javatools/classinfo.py#L57-L70
train
30,301
obriencj/python-javatools
javatools/__init__.py
_unpack_annotation_val
def _unpack_annotation_val(unpacker, cpool): """ tag, data tuple of an annotation """ tag, = unpacker.unpack_struct(_B) tag = chr(tag) if tag in 'BCDFIJSZs': data, = unpacker.unpack_struct(_H) elif tag == 'e': data = unpacker.unpack_struct(_HH) elif tag == 'c': data, = unpacker.unpack_struct(_H) elif tag == '@': data = JavaAnnotation(cpool) data.unpack(unpacker) elif tag == '[': data = list() count, = unpacker.unpack_struct(_H) for _i in range(0, count): data.append(_unpack_annotation_val(unpacker, cpool)) else: raise Unimplemented("Unknown tag {}".format(tag)) return tag, data
python
def _unpack_annotation_val(unpacker, cpool): """ tag, data tuple of an annotation """ tag, = unpacker.unpack_struct(_B) tag = chr(tag) if tag in 'BCDFIJSZs': data, = unpacker.unpack_struct(_H) elif tag == 'e': data = unpacker.unpack_struct(_HH) elif tag == 'c': data, = unpacker.unpack_struct(_H) elif tag == '@': data = JavaAnnotation(cpool) data.unpack(unpacker) elif tag == '[': data = list() count, = unpacker.unpack_struct(_H) for _i in range(0, count): data.append(_unpack_annotation_val(unpacker, cpool)) else: raise Unimplemented("Unknown tag {}".format(tag)) return tag, data
[ "def", "_unpack_annotation_val", "(", "unpacker", ",", "cpool", ")", ":", "tag", ",", "=", "unpacker", ".", "unpack_struct", "(", "_B", ")", "tag", "=", "chr", "(", "tag", ")", "if", "tag", "in", "'BCDFIJSZs'", ":", "data", ",", "=", "unpacker", ".", ...
tag, data tuple of an annotation
[ "tag", "data", "tuple", "of", "an", "annotation" ]
9e2332b452ddc508bed0615937dddcb2cf051557
https://github.com/obriencj/python-javatools/blob/9e2332b452ddc508bed0615937dddcb2cf051557/javatools/__init__.py#L1945-L1975
train
30,302
obriencj/python-javatools
javatools/__init__.py
_pretty_annotation_val
def _pretty_annotation_val(val, cpool): """ a pretty display of a tag and data pair annotation value """ tag, data = val if tag in 'BCDFIJSZs': data = "%s#%i" % (tag, data) elif tag == 'e': data = "e#%i.#%i" % data elif tag == 'c': data = "c#%i" % data elif tag == '@': data = "@" + data.pretty_annotation() elif tag == '[': combine = list() for val in data: combine.append(_pretty_annotation_val(val, cpool)) data = "[%s]" % ", ".join(combine) return data
python
def _pretty_annotation_val(val, cpool): """ a pretty display of a tag and data pair annotation value """ tag, data = val if tag in 'BCDFIJSZs': data = "%s#%i" % (tag, data) elif tag == 'e': data = "e#%i.#%i" % data elif tag == 'c': data = "c#%i" % data elif tag == '@': data = "@" + data.pretty_annotation() elif tag == '[': combine = list() for val in data: combine.append(_pretty_annotation_val(val, cpool)) data = "[%s]" % ", ".join(combine) return data
[ "def", "_pretty_annotation_val", "(", "val", ",", "cpool", ")", ":", "tag", ",", "data", "=", "val", "if", "tag", "in", "'BCDFIJSZs'", ":", "data", "=", "\"%s#%i\"", "%", "(", "tag", ",", "data", ")", "elif", "tag", "==", "'e'", ":", "data", "=", "...
a pretty display of a tag and data pair annotation value
[ "a", "pretty", "display", "of", "a", "tag", "and", "data", "pair", "annotation", "value" ]
9e2332b452ddc508bed0615937dddcb2cf051557
https://github.com/obriencj/python-javatools/blob/9e2332b452ddc508bed0615937dddcb2cf051557/javatools/__init__.py#L1978-L2003
train
30,303
obriencj/python-javatools
javatools/__init__.py
platform_from_version
def platform_from_version(major, minor): """ returns the minimum platform version that can load the given class version indicated by major.minor or None if no known platforms match the given version """ v = (major, minor) for low, high, name in _platforms: if low <= v <= high: return name return None
python
def platform_from_version(major, minor): """ returns the minimum platform version that can load the given class version indicated by major.minor or None if no known platforms match the given version """ v = (major, minor) for low, high, name in _platforms: if low <= v <= high: return name return None
[ "def", "platform_from_version", "(", "major", ",", "minor", ")", ":", "v", "=", "(", "major", ",", "minor", ")", "for", "low", ",", "high", ",", "name", "in", "_platforms", ":", "if", "low", "<=", "v", "<=", "high", ":", "return", "name", "return", ...
returns the minimum platform version that can load the given class version indicated by major.minor or None if no known platforms match the given version
[ "returns", "the", "minimum", "platform", "version", "that", "can", "load", "the", "given", "class", "version", "indicated", "by", "major", ".", "minor", "or", "None", "if", "no", "known", "platforms", "match", "the", "given", "version" ]
9e2332b452ddc508bed0615937dddcb2cf051557
https://github.com/obriencj/python-javatools/blob/9e2332b452ddc508bed0615937dddcb2cf051557/javatools/__init__.py#L2024-L2035
train
30,304
obriencj/python-javatools
javatools/__init__.py
_next_argsig
def _next_argsig(s): """ given a string, find the next complete argument signature and return it and a new string advanced past that point """ c = s[0] if c in "BCDFIJSVZ": result = (c, s[1:]) elif c == "[": d, s = _next_argsig(s[1:]) result = (c + d, s[len(d) + 1:]) elif c == "L": i = s.find(';') + 1 result = (s[:i], s[i + 1:]) elif c == "(": i = s.find(')') + 1 result = (s[:i], s[i:]) else: raise Unimplemented("_next_argsig is %r in %r" % (c, s)) return result
python
def _next_argsig(s): """ given a string, find the next complete argument signature and return it and a new string advanced past that point """ c = s[0] if c in "BCDFIJSVZ": result = (c, s[1:]) elif c == "[": d, s = _next_argsig(s[1:]) result = (c + d, s[len(d) + 1:]) elif c == "L": i = s.find(';') + 1 result = (s[:i], s[i + 1:]) elif c == "(": i = s.find(')') + 1 result = (s[:i], s[i:]) else: raise Unimplemented("_next_argsig is %r in %r" % (c, s)) return result
[ "def", "_next_argsig", "(", "s", ")", ":", "c", "=", "s", "[", "0", "]", "if", "c", "in", "\"BCDFIJSVZ\"", ":", "result", "=", "(", "c", ",", "s", "[", "1", ":", "]", ")", "elif", "c", "==", "\"[\"", ":", "d", ",", "s", "=", "_next_argsig", ...
given a string, find the next complete argument signature and return it and a new string advanced past that point
[ "given", "a", "string", "find", "the", "next", "complete", "argument", "signature", "and", "return", "it", "and", "a", "new", "string", "advanced", "past", "that", "point" ]
9e2332b452ddc508bed0615937dddcb2cf051557
https://github.com/obriencj/python-javatools/blob/9e2332b452ddc508bed0615937dddcb2cf051557/javatools/__init__.py#L2170-L2196
train
30,305
obriencj/python-javatools
javatools/__init__.py
_typeseq_iter
def _typeseq_iter(s): """ iterate through all of the type signatures in a sequence """ s = str(s) while s: t, s = _next_argsig(s) yield t
python
def _typeseq_iter(s): """ iterate through all of the type signatures in a sequence """ s = str(s) while s: t, s = _next_argsig(s) yield t
[ "def", "_typeseq_iter", "(", "s", ")", ":", "s", "=", "str", "(", "s", ")", "while", "s", ":", "t", ",", "s", "=", "_next_argsig", "(", "s", ")", "yield", "t" ]
iterate through all of the type signatures in a sequence
[ "iterate", "through", "all", "of", "the", "type", "signatures", "in", "a", "sequence" ]
9e2332b452ddc508bed0615937dddcb2cf051557
https://github.com/obriencj/python-javatools/blob/9e2332b452ddc508bed0615937dddcb2cf051557/javatools/__init__.py#L2199-L2207
train
30,306
obriencj/python-javatools
javatools/__init__.py
_pretty_type
def _pretty_type(s, offset=0): # pylint: disable=R0911, R0912 # too many returns, too many branches. Not converting this to a # dict lookup. Waiving instead. """ returns the pretty version of a type code """ tc = s[offset] if tc == "V": return "void" elif tc == "Z": return "boolean" elif tc == "C": return "char" elif tc == "B": return "byte" elif tc == "S": return "short" elif tc == "I": return "int" elif tc == "J": return "long" elif tc == "D": return "double" elif tc == "F": return "float" elif tc == "L": return _pretty_class(s[offset + 1:-1]) elif tc == "[": return "%s[]" % _pretty_type(s, offset + 1) elif tc == "(": return "(%s)" % ",".join(_pretty_typeseq(s[offset + 1:-1])) elif tc == "T": return "generic " + s[offset + 1:] else: raise Unimplemented("unknown type, %r" % tc)
python
def _pretty_type(s, offset=0): # pylint: disable=R0911, R0912 # too many returns, too many branches. Not converting this to a # dict lookup. Waiving instead. """ returns the pretty version of a type code """ tc = s[offset] if tc == "V": return "void" elif tc == "Z": return "boolean" elif tc == "C": return "char" elif tc == "B": return "byte" elif tc == "S": return "short" elif tc == "I": return "int" elif tc == "J": return "long" elif tc == "D": return "double" elif tc == "F": return "float" elif tc == "L": return _pretty_class(s[offset + 1:-1]) elif tc == "[": return "%s[]" % _pretty_type(s, offset + 1) elif tc == "(": return "(%s)" % ",".join(_pretty_typeseq(s[offset + 1:-1])) elif tc == "T": return "generic " + s[offset + 1:] else: raise Unimplemented("unknown type, %r" % tc)
[ "def", "_pretty_type", "(", "s", ",", "offset", "=", "0", ")", ":", "# pylint: disable=R0911, R0912", "# too many returns, too many branches. Not converting this to a", "# dict lookup. Waiving instead.", "tc", "=", "s", "[", "offset", "]", "if", "tc", "==", "\"V\"", ":"...
returns the pretty version of a type code
[ "returns", "the", "pretty", "version", "of", "a", "type", "code" ]
9e2332b452ddc508bed0615937dddcb2cf051557
https://github.com/obriencj/python-javatools/blob/9e2332b452ddc508bed0615937dddcb2cf051557/javatools/__init__.py#L2226-L2277
train
30,307
obriencj/python-javatools
javatools/__init__.py
is_class_file
def is_class_file(filename): """ checks whether the given file is a Java class file, by opening it and checking for the magic header """ with open(filename, "rb") as fd: c = fd.read(len(JAVA_CLASS_MAGIC)) if isinstance(c, str): # Python 2 c = map(ord, c) return tuple(c) == JAVA_CLASS_MAGIC
python
def is_class_file(filename): """ checks whether the given file is a Java class file, by opening it and checking for the magic header """ with open(filename, "rb") as fd: c = fd.read(len(JAVA_CLASS_MAGIC)) if isinstance(c, str): # Python 2 c = map(ord, c) return tuple(c) == JAVA_CLASS_MAGIC
[ "def", "is_class_file", "(", "filename", ")", ":", "with", "open", "(", "filename", ",", "\"rb\"", ")", "as", "fd", ":", "c", "=", "fd", ".", "read", "(", "len", "(", "JAVA_CLASS_MAGIC", ")", ")", "if", "isinstance", "(", "c", ",", "str", ")", ":",...
checks whether the given file is a Java class file, by opening it and checking for the magic header
[ "checks", "whether", "the", "given", "file", "is", "a", "Java", "class", "file", "by", "opening", "it", "and", "checking", "for", "the", "magic", "header" ]
9e2332b452ddc508bed0615937dddcb2cf051557
https://github.com/obriencj/python-javatools/blob/9e2332b452ddc508bed0615937dddcb2cf051557/javatools/__init__.py#L2312-L2322
train
30,308
obriencj/python-javatools
javatools/__init__.py
unpack_class
def unpack_class(data, magic=None): """ unpacks a Java class from data, which can be a string, a buffer, or a stream supporting the read method. Returns a populated JavaClassInfo instance. If data is a stream which has already been confirmed to be a java class, it may have had the first four bytes read from it already. In this case, pass those magic bytes as a str or tuple and the unpacker will not attempt to read them again. Raises a ClassUnpackException or an UnpackException if the class data is malformed. Raises Unimplemented if a feature is discovered which isn't understood by javatools yet. """ with unpack(data) as up: magic = magic or up.unpack_struct(_BBBB) if magic != JAVA_CLASS_MAGIC: raise ClassUnpackException("Not a Java class file") o = JavaClassInfo() o.unpack(up, magic=magic) return o
python
def unpack_class(data, magic=None): """ unpacks a Java class from data, which can be a string, a buffer, or a stream supporting the read method. Returns a populated JavaClassInfo instance. If data is a stream which has already been confirmed to be a java class, it may have had the first four bytes read from it already. In this case, pass those magic bytes as a str or tuple and the unpacker will not attempt to read them again. Raises a ClassUnpackException or an UnpackException if the class data is malformed. Raises Unimplemented if a feature is discovered which isn't understood by javatools yet. """ with unpack(data) as up: magic = magic or up.unpack_struct(_BBBB) if magic != JAVA_CLASS_MAGIC: raise ClassUnpackException("Not a Java class file") o = JavaClassInfo() o.unpack(up, magic=magic) return o
[ "def", "unpack_class", "(", "data", ",", "magic", "=", "None", ")", ":", "with", "unpack", "(", "data", ")", "as", "up", ":", "magic", "=", "magic", "or", "up", ".", "unpack_struct", "(", "_BBBB", ")", "if", "magic", "!=", "JAVA_CLASS_MAGIC", ":", "r...
unpacks a Java class from data, which can be a string, a buffer, or a stream supporting the read method. Returns a populated JavaClassInfo instance. If data is a stream which has already been confirmed to be a java class, it may have had the first four bytes read from it already. In this case, pass those magic bytes as a str or tuple and the unpacker will not attempt to read them again. Raises a ClassUnpackException or an UnpackException if the class data is malformed. Raises Unimplemented if a feature is discovered which isn't understood by javatools yet.
[ "unpacks", "a", "Java", "class", "from", "data", "which", "can", "be", "a", "string", "a", "buffer", "or", "a", "stream", "supporting", "the", "read", "method", ".", "Returns", "a", "populated", "JavaClassInfo", "instance", "." ]
9e2332b452ddc508bed0615937dddcb2cf051557
https://github.com/obriencj/python-javatools/blob/9e2332b452ddc508bed0615937dddcb2cf051557/javatools/__init__.py#L2325-L2349
train
30,309
obriencj/python-javatools
javatools/__init__.py
JavaConstantPool.unpack
def unpack(self, unpacker): """ Unpacks the constant pool from an unpacker stream """ (count, ) = unpacker.unpack_struct(_H) # first item is never present in the actual data buffer, but # the count number acts like it would be. items = [(None, None), ] count -= 1 # Long and Double const types will "consume" an item count, # but not data hackpass = False for _i in range(0, count): if hackpass: # previous item was a long or double hackpass = False items.append((None, None)) else: item = _unpack_const_item(unpacker) items.append(item) # if this item was a long or double, skip the next # counter. if item[0] in (CONST_Long, CONST_Double): hackpass = True self.consts = items
python
def unpack(self, unpacker): """ Unpacks the constant pool from an unpacker stream """ (count, ) = unpacker.unpack_struct(_H) # first item is never present in the actual data buffer, but # the count number acts like it would be. items = [(None, None), ] count -= 1 # Long and Double const types will "consume" an item count, # but not data hackpass = False for _i in range(0, count): if hackpass: # previous item was a long or double hackpass = False items.append((None, None)) else: item = _unpack_const_item(unpacker) items.append(item) # if this item was a long or double, skip the next # counter. if item[0] in (CONST_Long, CONST_Double): hackpass = True self.consts = items
[ "def", "unpack", "(", "self", ",", "unpacker", ")", ":", "(", "count", ",", ")", "=", "unpacker", ".", "unpack_struct", "(", "_H", ")", "# first item is never present in the actual data buffer, but", "# the count number acts like it would be.", "items", "=", "[", "(",...
Unpacks the constant pool from an unpacker stream
[ "Unpacks", "the", "constant", "pool", "from", "an", "unpacker", "stream" ]
9e2332b452ddc508bed0615937dddcb2cf051557
https://github.com/obriencj/python-javatools/blob/9e2332b452ddc508bed0615937dddcb2cf051557/javatools/__init__.py#L179-L211
train
30,310
obriencj/python-javatools
javatools/__init__.py
JavaConstantPool.deref_const
def deref_const(self, index): """ returns the dereferenced value from the const pool. For simple types, this will be a single value indicating the constant. For more complex types, such as fieldref, methodref, etc, this will return a tuple. """ if not index: raise IndexError("Requested const 0") t, v = self.consts[index] if t in (CONST_Utf8, CONST_Integer, CONST_Float, CONST_Long, CONST_Double): return v elif t in (CONST_Class, CONST_String, CONST_MethodType): return self.deref_const(v) elif t in (CONST_Fieldref, CONST_Methodref, CONST_InterfaceMethodref, CONST_NameAndType, CONST_ModuleId): return tuple(self.deref_const(i) for i in v) else: raise Unimplemented("Unknown constant pool type %r" % t)
python
def deref_const(self, index): """ returns the dereferenced value from the const pool. For simple types, this will be a single value indicating the constant. For more complex types, such as fieldref, methodref, etc, this will return a tuple. """ if not index: raise IndexError("Requested const 0") t, v = self.consts[index] if t in (CONST_Utf8, CONST_Integer, CONST_Float, CONST_Long, CONST_Double): return v elif t in (CONST_Class, CONST_String, CONST_MethodType): return self.deref_const(v) elif t in (CONST_Fieldref, CONST_Methodref, CONST_InterfaceMethodref, CONST_NameAndType, CONST_ModuleId): return tuple(self.deref_const(i) for i in v) else: raise Unimplemented("Unknown constant pool type %r" % t)
[ "def", "deref_const", "(", "self", ",", "index", ")", ":", "if", "not", "index", ":", "raise", "IndexError", "(", "\"Requested const 0\"", ")", "t", ",", "v", "=", "self", ".", "consts", "[", "index", "]", "if", "t", "in", "(", "CONST_Utf8", ",", "CO...
returns the dereferenced value from the const pool. For simple types, this will be a single value indicating the constant. For more complex types, such as fieldref, methodref, etc, this will return a tuple.
[ "returns", "the", "dereferenced", "value", "from", "the", "const", "pool", ".", "For", "simple", "types", "this", "will", "be", "a", "single", "value", "indicating", "the", "constant", ".", "For", "more", "complex", "types", "such", "as", "fieldref", "method...
9e2332b452ddc508bed0615937dddcb2cf051557
https://github.com/obriencj/python-javatools/blob/9e2332b452ddc508bed0615937dddcb2cf051557/javatools/__init__.py#L222-L248
train
30,311
obriencj/python-javatools
javatools/__init__.py
JavaAttributes.unpack
def unpack(self, unpacker): """ Unpack an attributes table from an unpacker stream. Modifies the structure of this instance. """ # bound method for dereferencing constants cval = self.cpool.deref_const (count,) = unpacker.unpack_struct(_H) for _i in range(0, count): (name, size) = unpacker.unpack_struct(_HI) self[cval(name)] = unpacker.read(size)
python
def unpack(self, unpacker): """ Unpack an attributes table from an unpacker stream. Modifies the structure of this instance. """ # bound method for dereferencing constants cval = self.cpool.deref_const (count,) = unpacker.unpack_struct(_H) for _i in range(0, count): (name, size) = unpacker.unpack_struct(_HI) self[cval(name)] = unpacker.read(size)
[ "def", "unpack", "(", "self", ",", "unpacker", ")", ":", "# bound method for dereferencing constants", "cval", "=", "self", ".", "cpool", ".", "deref_const", "(", "count", ",", ")", "=", "unpacker", ".", "unpack_struct", "(", "_H", ")", "for", "_i", "in", ...
Unpack an attributes table from an unpacker stream. Modifies the structure of this instance.
[ "Unpack", "an", "attributes", "table", "from", "an", "unpacker", "stream", ".", "Modifies", "the", "structure", "of", "this", "instance", "." ]
9e2332b452ddc508bed0615937dddcb2cf051557
https://github.com/obriencj/python-javatools/blob/9e2332b452ddc508bed0615937dddcb2cf051557/javatools/__init__.py#L362-L374
train
30,312
obriencj/python-javatools
javatools/__init__.py
JavaClassInfo.unpack
def unpack(self, unpacker, magic=None): """ Unpacks a Java class from an unpacker stream. Updates the structure of this instance. If the unpacker has already had the magic header read off of it, the read value may be passed via the optional magic parameter and it will not attempt to read the value again. """ # only unpack the magic bytes if it wasn't specified magic = magic or unpacker.unpack_struct(_BBBB) if isinstance(magic, (str, buffer)): magic = tuple(ord(m) for m in magic) else: magic = tuple(magic) if magic != JAVA_CLASS_MAGIC: raise ClassUnpackException("Not a Java class file") self.magic = magic # unpack (minor, major), store as (major, minor) self.version = unpacker.unpack_struct(_HH)[::-1] # unpack constant pool self.cpool.unpack(unpacker) (a, b, c) = unpacker.unpack_struct(_HHH) self.access_flags = a self.this_ref = b self.super_ref = c # unpack interfaces (count,) = unpacker.unpack_struct(_H) self.interfaces = unpacker.unpack(">%iH" % count) uobjs = unpacker.unpack_objects # unpack fields self.fields = tuple(uobjs(JavaMemberInfo, self.cpool, is_method=False)) # unpack methods self.methods = tuple(uobjs(JavaMemberInfo, self.cpool, is_method=True)) # unpack attributes self.attribs.unpack(unpacker)
python
def unpack(self, unpacker, magic=None): """ Unpacks a Java class from an unpacker stream. Updates the structure of this instance. If the unpacker has already had the magic header read off of it, the read value may be passed via the optional magic parameter and it will not attempt to read the value again. """ # only unpack the magic bytes if it wasn't specified magic = magic or unpacker.unpack_struct(_BBBB) if isinstance(magic, (str, buffer)): magic = tuple(ord(m) for m in magic) else: magic = tuple(magic) if magic != JAVA_CLASS_MAGIC: raise ClassUnpackException("Not a Java class file") self.magic = magic # unpack (minor, major), store as (major, minor) self.version = unpacker.unpack_struct(_HH)[::-1] # unpack constant pool self.cpool.unpack(unpacker) (a, b, c) = unpacker.unpack_struct(_HHH) self.access_flags = a self.this_ref = b self.super_ref = c # unpack interfaces (count,) = unpacker.unpack_struct(_H) self.interfaces = unpacker.unpack(">%iH" % count) uobjs = unpacker.unpack_objects # unpack fields self.fields = tuple(uobjs(JavaMemberInfo, self.cpool, is_method=False)) # unpack methods self.methods = tuple(uobjs(JavaMemberInfo, self.cpool, is_method=True)) # unpack attributes self.attribs.unpack(unpacker)
[ "def", "unpack", "(", "self", ",", "unpacker", ",", "magic", "=", "None", ")", ":", "# only unpack the magic bytes if it wasn't specified", "magic", "=", "magic", "or", "unpacker", ".", "unpack_struct", "(", "_BBBB", ")", "if", "isinstance", "(", "magic", ",", ...
Unpacks a Java class from an unpacker stream. Updates the structure of this instance. If the unpacker has already had the magic header read off of it, the read value may be passed via the optional magic parameter and it will not attempt to read the value again.
[ "Unpacks", "a", "Java", "class", "from", "an", "unpacker", "stream", ".", "Updates", "the", "structure", "of", "this", "instance", "." ]
9e2332b452ddc508bed0615937dddcb2cf051557
https://github.com/obriencj/python-javatools/blob/9e2332b452ddc508bed0615937dddcb2cf051557/javatools/__init__.py#L420-L469
train
30,313
obriencj/python-javatools
javatools/__init__.py
JavaClassInfo.get_field_by_name
def get_field_by_name(self, name): """ the field member matching name, or None if no such field is found """ for f in self.fields: if f.get_name() == name: return f return None
python
def get_field_by_name(self, name): """ the field member matching name, or None if no such field is found """ for f in self.fields: if f.get_name() == name: return f return None
[ "def", "get_field_by_name", "(", "self", ",", "name", ")", ":", "for", "f", "in", "self", ".", "fields", ":", "if", "f", ".", "get_name", "(", ")", "==", "name", ":", "return", "f", "return", "None" ]
the field member matching name, or None if no such field is found
[ "the", "field", "member", "matching", "name", "or", "None", "if", "no", "such", "field", "is", "found" ]
9e2332b452ddc508bed0615937dddcb2cf051557
https://github.com/obriencj/python-javatools/blob/9e2332b452ddc508bed0615937dddcb2cf051557/javatools/__init__.py#L472-L480
train
30,314
obriencj/python-javatools
javatools/__init__.py
JavaClassInfo.get_methods_by_name
def get_methods_by_name(self, name): """ generator of methods matching name. This will include any bridges present. """ return (m for m in self.methods if m.get_name() == name)
python
def get_methods_by_name(self, name): """ generator of methods matching name. This will include any bridges present. """ return (m for m in self.methods if m.get_name() == name)
[ "def", "get_methods_by_name", "(", "self", ",", "name", ")", ":", "return", "(", "m", "for", "m", "in", "self", ".", "methods", "if", "m", ".", "get_name", "(", ")", "==", "name", ")" ]
generator of methods matching name. This will include any bridges present.
[ "generator", "of", "methods", "matching", "name", ".", "This", "will", "include", "any", "bridges", "present", "." ]
9e2332b452ddc508bed0615937dddcb2cf051557
https://github.com/obriencj/python-javatools/blob/9e2332b452ddc508bed0615937dddcb2cf051557/javatools/__init__.py#L483-L489
train
30,315
obriencj/python-javatools
javatools/__init__.py
JavaClassInfo.get_method
def get_method(self, name, arg_types=()): """ searches for the method matching the name and having argument type descriptors matching those in arg_types. Parameters ========== arg_types : sequence of strings each string is a parameter type, in the non-pretty format. Returns ======= method : `JavaMemberInfo` or `None` the single matching, non-bridging method of matching name and parameter types. """ # ensure any lists or iterables are converted to tuple for # comparison against get_arg_type_descriptors() arg_types = tuple(arg_types) for m in self.get_methods_by_name(name): if (((not m.is_bridge()) and m.get_arg_type_descriptors() == arg_types)): return m return None
python
def get_method(self, name, arg_types=()): """ searches for the method matching the name and having argument type descriptors matching those in arg_types. Parameters ========== arg_types : sequence of strings each string is a parameter type, in the non-pretty format. Returns ======= method : `JavaMemberInfo` or `None` the single matching, non-bridging method of matching name and parameter types. """ # ensure any lists or iterables are converted to tuple for # comparison against get_arg_type_descriptors() arg_types = tuple(arg_types) for m in self.get_methods_by_name(name): if (((not m.is_bridge()) and m.get_arg_type_descriptors() == arg_types)): return m return None
[ "def", "get_method", "(", "self", ",", "name", ",", "arg_types", "=", "(", ")", ")", ":", "# ensure any lists or iterables are converted to tuple for", "# comparison against get_arg_type_descriptors()", "arg_types", "=", "tuple", "(", "arg_types", ")", "for", "m", "in",...
searches for the method matching the name and having argument type descriptors matching those in arg_types. Parameters ========== arg_types : sequence of strings each string is a parameter type, in the non-pretty format. Returns ======= method : `JavaMemberInfo` or `None` the single matching, non-bridging method of matching name and parameter types.
[ "searches", "for", "the", "method", "matching", "the", "name", "and", "having", "argument", "type", "descriptors", "matching", "those", "in", "arg_types", "." ]
9e2332b452ddc508bed0615937dddcb2cf051557
https://github.com/obriencj/python-javatools/blob/9e2332b452ddc508bed0615937dddcb2cf051557/javatools/__init__.py#L492-L517
train
30,316
obriencj/python-javatools
javatools/__init__.py
JavaClassInfo.get_method_bridges
def get_method_bridges(self, name, arg_types=()): """ generator of bridge methods found that adapt the return types of a named method and having argument type descriptors matching those in arg_types. """ for m in self.get_methods_by_name(name): if ((m.is_bridge() and m.get_arg_type_descriptors() == arg_types)): yield m
python
def get_method_bridges(self, name, arg_types=()): """ generator of bridge methods found that adapt the return types of a named method and having argument type descriptors matching those in arg_types. """ for m in self.get_methods_by_name(name): if ((m.is_bridge() and m.get_arg_type_descriptors() == arg_types)): yield m
[ "def", "get_method_bridges", "(", "self", ",", "name", ",", "arg_types", "=", "(", ")", ")", ":", "for", "m", "in", "self", ".", "get_methods_by_name", "(", "name", ")", ":", "if", "(", "(", "m", ".", "is_bridge", "(", ")", "and", "m", ".", "get_ar...
generator of bridge methods found that adapt the return types of a named method and having argument type descriptors matching those in arg_types.
[ "generator", "of", "bridge", "methods", "found", "that", "adapt", "the", "return", "types", "of", "a", "named", "method", "and", "having", "argument", "type", "descriptors", "matching", "those", "in", "arg_types", "." ]
9e2332b452ddc508bed0615937dddcb2cf051557
https://github.com/obriencj/python-javatools/blob/9e2332b452ddc508bed0615937dddcb2cf051557/javatools/__init__.py#L520-L530
train
30,317
obriencj/python-javatools
javatools/__init__.py
JavaClassInfo.get_sourcefile
def get_sourcefile(self): """ the name of thie file this class was compiled from, or None if not indicated reference: http://docs.oracle.com/javase/specs/jvms/se7/html/jvms-4.html#jvms-4.7.10 """ # noqa buff = self.get_attribute("SourceFile") if buff is None: return None with unpack(buff) as up: (ref,) = up.unpack_struct(_H) return self.deref_const(ref)
python
def get_sourcefile(self): """ the name of thie file this class was compiled from, or None if not indicated reference: http://docs.oracle.com/javase/specs/jvms/se7/html/jvms-4.html#jvms-4.7.10 """ # noqa buff = self.get_attribute("SourceFile") if buff is None: return None with unpack(buff) as up: (ref,) = up.unpack_struct(_H) return self.deref_const(ref)
[ "def", "get_sourcefile", "(", "self", ")", ":", "# noqa", "buff", "=", "self", ".", "get_attribute", "(", "\"SourceFile\"", ")", "if", "buff", "is", "None", ":", "return", "None", "with", "unpack", "(", "buff", ")", "as", "up", ":", "(", "ref", ",", ...
the name of thie file this class was compiled from, or None if not indicated reference: http://docs.oracle.com/javase/specs/jvms/se7/html/jvms-4.html#jvms-4.7.10
[ "the", "name", "of", "thie", "file", "this", "class", "was", "compiled", "from", "or", "None", "if", "not", "indicated" ]
9e2332b452ddc508bed0615937dddcb2cf051557
https://github.com/obriencj/python-javatools/blob/9e2332b452ddc508bed0615937dddcb2cf051557/javatools/__init__.py#L686-L701
train
30,318
obriencj/python-javatools
javatools/__init__.py
JavaClassInfo.get_innerclasses
def get_innerclasses(self): """ sequence of JavaInnerClassInfo instances describing the inner classes of this class definition reference: http://docs.oracle.com/javase/specs/jvms/se7/html/jvms-4.html#jvms-4.7.6 """ # noqa buff = self.get_attribute("InnerClasses") if buff is None: return tuple() with unpack(buff) as up: return tuple(up.unpack_objects(JavaInnerClassInfo, self.cpool))
python
def get_innerclasses(self): """ sequence of JavaInnerClassInfo instances describing the inner classes of this class definition reference: http://docs.oracle.com/javase/specs/jvms/se7/html/jvms-4.html#jvms-4.7.6 """ # noqa buff = self.get_attribute("InnerClasses") if buff is None: return tuple() with unpack(buff) as up: return tuple(up.unpack_objects(JavaInnerClassInfo, self.cpool))
[ "def", "get_innerclasses", "(", "self", ")", ":", "# noqa", "buff", "=", "self", ".", "get_attribute", "(", "\"InnerClasses\"", ")", "if", "buff", "is", "None", ":", "return", "tuple", "(", ")", "with", "unpack", "(", "buff", ")", "as", "up", ":", "ret...
sequence of JavaInnerClassInfo instances describing the inner classes of this class definition reference: http://docs.oracle.com/javase/specs/jvms/se7/html/jvms-4.html#jvms-4.7.6
[ "sequence", "of", "JavaInnerClassInfo", "instances", "describing", "the", "inner", "classes", "of", "this", "class", "definition" ]
9e2332b452ddc508bed0615937dddcb2cf051557
https://github.com/obriencj/python-javatools/blob/9e2332b452ddc508bed0615937dddcb2cf051557/javatools/__init__.py#L714-L727
train
30,319
obriencj/python-javatools
javatools/__init__.py
JavaClassInfo._pretty_access_flags_gen
def _pretty_access_flags_gen(self): """ generator of the pretty access flags """ if self.is_public(): yield "public" if self.is_final(): yield "final" if self.is_abstract(): yield "abstract" if self.is_interface(): if self.is_annotation(): yield "@interface" else: yield "interface" if self.is_enum(): yield "enum"
python
def _pretty_access_flags_gen(self): """ generator of the pretty access flags """ if self.is_public(): yield "public" if self.is_final(): yield "final" if self.is_abstract(): yield "abstract" if self.is_interface(): if self.is_annotation(): yield "@interface" else: yield "interface" if self.is_enum(): yield "enum"
[ "def", "_pretty_access_flags_gen", "(", "self", ")", ":", "if", "self", ".", "is_public", "(", ")", ":", "yield", "\"public\"", "if", "self", ".", "is_final", "(", ")", ":", "yield", "\"final\"", "if", "self", ".", "is_abstract", "(", ")", ":", "yield", ...
generator of the pretty access flags
[ "generator", "of", "the", "pretty", "access", "flags" ]
9e2332b452ddc508bed0615937dddcb2cf051557
https://github.com/obriencj/python-javatools/blob/9e2332b452ddc508bed0615937dddcb2cf051557/javatools/__init__.py#L793-L810
train
30,320
obriencj/python-javatools
javatools/__init__.py
JavaClassInfo.pretty_descriptor
def pretty_descriptor(self): """ get the class or interface name, its accessor flags, its parent class, and any interfaces it implements """ f = " ".join(self.pretty_access_flags()) if not self.is_interface(): f += " class" n = self.pretty_this() e = self.pretty_super() i = ",".join(self.pretty_interfaces()) if i: return "%s %s extends %s implements %s" % (f, n, e, i) else: return "%s %s extends %s" % (f, n, e)
python
def pretty_descriptor(self): """ get the class or interface name, its accessor flags, its parent class, and any interfaces it implements """ f = " ".join(self.pretty_access_flags()) if not self.is_interface(): f += " class" n = self.pretty_this() e = self.pretty_super() i = ",".join(self.pretty_interfaces()) if i: return "%s %s extends %s implements %s" % (f, n, e, i) else: return "%s %s extends %s" % (f, n, e)
[ "def", "pretty_descriptor", "(", "self", ")", ":", "f", "=", "\" \"", ".", "join", "(", "self", ".", "pretty_access_flags", "(", ")", ")", "if", "not", "self", ".", "is_interface", "(", ")", ":", "f", "+=", "\" class\"", "n", "=", "self", ".", "prett...
get the class or interface name, its accessor flags, its parent class, and any interfaces it implements
[ "get", "the", "class", "or", "interface", "name", "its", "accessor", "flags", "its", "parent", "class", "and", "any", "interfaces", "it", "implements" ]
9e2332b452ddc508bed0615937dddcb2cf051557
https://github.com/obriencj/python-javatools/blob/9e2332b452ddc508bed0615937dddcb2cf051557/javatools/__init__.py#L845-L862
train
30,321
obriencj/python-javatools
javatools/__init__.py
JavaClassInfo._get_provides
def _get_provides(self, private=False): """ iterator of provided classes, fields, methods """ # TODO I probably need to add inner classes here me = self.pretty_this() yield me for field in self.fields: if private or field.is_public(): yield "%s.%s" % (me, field.pretty_identifier()) for method in self.methods: if private or method.is_public(): yield "%s.%s" % (me, method.pretty_identifier())
python
def _get_provides(self, private=False): """ iterator of provided classes, fields, methods """ # TODO I probably need to add inner classes here me = self.pretty_this() yield me for field in self.fields: if private or field.is_public(): yield "%s.%s" % (me, field.pretty_identifier()) for method in self.methods: if private or method.is_public(): yield "%s.%s" % (me, method.pretty_identifier())
[ "def", "_get_provides", "(", "self", ",", "private", "=", "False", ")", ":", "# TODO I probably need to add inner classes here", "me", "=", "self", ".", "pretty_this", "(", ")", "yield", "me", "for", "field", "in", "self", ".", "fields", ":", "if", "private", ...
iterator of provided classes, fields, methods
[ "iterator", "of", "provided", "classes", "fields", "methods" ]
9e2332b452ddc508bed0615937dddcb2cf051557
https://github.com/obriencj/python-javatools/blob/9e2332b452ddc508bed0615937dddcb2cf051557/javatools/__init__.py#L865-L881
train
30,322
obriencj/python-javatools
javatools/__init__.py
JavaClassInfo._get_requires
def _get_requires(self): """ iterator of required classes, fields, methods, determined my mining the constant pool for such types """ provided = set(self.get_provides(private=True)) cpool = self.cpool # loop through the constant pool for API types for i, t, _v in cpool.constants(): if t in (CONST_Class, CONST_Fieldref, CONST_Methodref, CONST_InterfaceMethodref): # convert this away from unicode so we can pv = str(cpool.pretty_deref_const(i)) if pv[0] == "[": # sometimes when calling operations on an array # the type embeded in the cpool will be the array # type, not just the class type. Let's only gather # the types themselves and ignore the fact that # the class really wanted an array of them. In # the event that this was a method or field on the # array, we'll throw away that as well, and just # emit the type contained in the array. t = _typeseq(pv) if t[1] == "L": pv = _pretty_type(t[1:]) else: pv = None if pv and (pv not in provided): yield pv
python
def _get_requires(self): """ iterator of required classes, fields, methods, determined my mining the constant pool for such types """ provided = set(self.get_provides(private=True)) cpool = self.cpool # loop through the constant pool for API types for i, t, _v in cpool.constants(): if t in (CONST_Class, CONST_Fieldref, CONST_Methodref, CONST_InterfaceMethodref): # convert this away from unicode so we can pv = str(cpool.pretty_deref_const(i)) if pv[0] == "[": # sometimes when calling operations on an array # the type embeded in the cpool will be the array # type, not just the class type. Let's only gather # the types themselves and ignore the fact that # the class really wanted an array of them. In # the event that this was a method or field on the # array, we'll throw away that as well, and just # emit the type contained in the array. t = _typeseq(pv) if t[1] == "L": pv = _pretty_type(t[1:]) else: pv = None if pv and (pv not in provided): yield pv
[ "def", "_get_requires", "(", "self", ")", ":", "provided", "=", "set", "(", "self", ".", "get_provides", "(", "private", "=", "True", ")", ")", "cpool", "=", "self", ".", "cpool", "# loop through the constant pool for API types", "for", "i", ",", "t", ",", ...
iterator of required classes, fields, methods, determined my mining the constant pool for such types
[ "iterator", "of", "required", "classes", "fields", "methods", "determined", "my", "mining", "the", "constant", "pool", "for", "such", "types" ]
9e2332b452ddc508bed0615937dddcb2cf051557
https://github.com/obriencj/python-javatools/blob/9e2332b452ddc508bed0615937dddcb2cf051557/javatools/__init__.py#L884-L918
train
30,323
obriencj/python-javatools
javatools/__init__.py
JavaClassInfo.get_provides
def get_provides(self, ignored=tuple(), private=False): """ The provided API, including the class itself, its fields, and its methods. """ if private: if self._provides_private is None: self._provides_private = set(self._get_provides(True)) provides = self._provides_private else: if self._provides is None: self._provides = set(self._get_provides(False)) provides = self._provides return [prov for prov in provides if not fnmatches(prov, *ignored)]
python
def get_provides(self, ignored=tuple(), private=False): """ The provided API, including the class itself, its fields, and its methods. """ if private: if self._provides_private is None: self._provides_private = set(self._get_provides(True)) provides = self._provides_private else: if self._provides is None: self._provides = set(self._get_provides(False)) provides = self._provides return [prov for prov in provides if not fnmatches(prov, *ignored)]
[ "def", "get_provides", "(", "self", ",", "ignored", "=", "tuple", "(", ")", ",", "private", "=", "False", ")", ":", "if", "private", ":", "if", "self", ".", "_provides_private", "is", "None", ":", "self", ".", "_provides_private", "=", "set", "(", "sel...
The provided API, including the class itself, its fields, and its methods.
[ "The", "provided", "API", "including", "the", "class", "itself", "its", "fields", "and", "its", "methods", "." ]
9e2332b452ddc508bed0615937dddcb2cf051557
https://github.com/obriencj/python-javatools/blob/9e2332b452ddc508bed0615937dddcb2cf051557/javatools/__init__.py#L921-L936
train
30,324
obriencj/python-javatools
javatools/__init__.py
JavaClassInfo.get_requires
def get_requires(self, ignored=tuple()): """ The required API, including all external classes, fields, and methods that this class references """ if self._requires is None: self._requires = set(self._get_requires()) requires = self._requires return [req for req in requires if not fnmatches(req, *ignored)]
python
def get_requires(self, ignored=tuple()): """ The required API, including all external classes, fields, and methods that this class references """ if self._requires is None: self._requires = set(self._get_requires()) requires = self._requires return [req for req in requires if not fnmatches(req, *ignored)]
[ "def", "get_requires", "(", "self", ",", "ignored", "=", "tuple", "(", ")", ")", ":", "if", "self", ".", "_requires", "is", "None", ":", "self", ".", "_requires", "=", "set", "(", "self", ".", "_get_requires", "(", ")", ")", "requires", "=", "self", ...
The required API, including all external classes, fields, and methods that this class references
[ "The", "required", "API", "including", "all", "external", "classes", "fields", "and", "methods", "that", "this", "class", "references" ]
9e2332b452ddc508bed0615937dddcb2cf051557
https://github.com/obriencj/python-javatools/blob/9e2332b452ddc508bed0615937dddcb2cf051557/javatools/__init__.py#L939-L949
train
30,325
obriencj/python-javatools
javatools/__init__.py
JavaMemberInfo.unpack
def unpack(self, unpacker): """ unpack the contents of this instance from the values in unpacker """ (a, b, c) = unpacker.unpack_struct(_HHH) self.access_flags = a self.name_ref = b self.descriptor_ref = c self.attribs.unpack(unpacker)
python
def unpack(self, unpacker): """ unpack the contents of this instance from the values in unpacker """ (a, b, c) = unpacker.unpack_struct(_HHH) self.access_flags = a self.name_ref = b self.descriptor_ref = c self.attribs.unpack(unpacker)
[ "def", "unpack", "(", "self", ",", "unpacker", ")", ":", "(", "a", ",", "b", ",", "c", ")", "=", "unpacker", ".", "unpack_struct", "(", "_HHH", ")", "self", ".", "access_flags", "=", "a", "self", ".", "name_ref", "=", "b", "self", ".", "descriptor_...
unpack the contents of this instance from the values in unpacker
[ "unpack", "the", "contents", "of", "this", "instance", "from", "the", "values", "in", "unpacker" ]
9e2332b452ddc508bed0615937dddcb2cf051557
https://github.com/obriencj/python-javatools/blob/9e2332b452ddc508bed0615937dddcb2cf051557/javatools/__init__.py#L1025-L1035
train
30,326
obriencj/python-javatools
javatools/__init__.py
JavaMemberInfo.get_annotationdefault
def get_annotationdefault(self): """ The AnnotationDefault attribute, only present upon fields in an annotaion. reference: http://docs.oracle.com/javase/specs/jvms/se7/html/jvms-4.html#jvms-4.7.20 """ # noqa buff = self.get_attribute("AnnotationDefault") if buff is None: return None with unpack(buff) as up: (ti, ) = up.unpack_struct(_H) return ti
python
def get_annotationdefault(self): """ The AnnotationDefault attribute, only present upon fields in an annotaion. reference: http://docs.oracle.com/javase/specs/jvms/se7/html/jvms-4.html#jvms-4.7.20 """ # noqa buff = self.get_attribute("AnnotationDefault") if buff is None: return None with unpack(buff) as up: (ti, ) = up.unpack_struct(_H) return ti
[ "def", "get_annotationdefault", "(", "self", ")", ":", "# noqa", "buff", "=", "self", ".", "get_attribute", "(", "\"AnnotationDefault\"", ")", "if", "buff", "is", "None", ":", "return", "None", "with", "unpack", "(", "buff", ")", "as", "up", ":", "(", "t...
The AnnotationDefault attribute, only present upon fields in an annotaion. reference: http://docs.oracle.com/javase/specs/jvms/se7/html/jvms-4.html#jvms-4.7.20
[ "The", "AnnotationDefault", "attribute", "only", "present", "upon", "fields", "in", "an", "annotaion", "." ]
9e2332b452ddc508bed0615937dddcb2cf051557
https://github.com/obriencj/python-javatools/blob/9e2332b452ddc508bed0615937dddcb2cf051557/javatools/__init__.py#L1270-L1285
train
30,327
obriencj/python-javatools
javatools/__init__.py
JavaMemberInfo.get_code
def get_code(self): """ the JavaCodeInfo of this member if it is a non-abstract method, None otherwise reference: http://docs.oracle.com/javase/specs/jvms/se7/html/jvms-4.html#jvms-4.7.3 """ # noqa buff = self.get_attribute("Code") if buff is None: return None with unpack(buff) as up: code = JavaCodeInfo(self.cpool) code.unpack(up) return code
python
def get_code(self): """ the JavaCodeInfo of this member if it is a non-abstract method, None otherwise reference: http://docs.oracle.com/javase/specs/jvms/se7/html/jvms-4.html#jvms-4.7.3 """ # noqa buff = self.get_attribute("Code") if buff is None: return None with unpack(buff) as up: code = JavaCodeInfo(self.cpool) code.unpack(up) return code
[ "def", "get_code", "(", "self", ")", ":", "# noqa", "buff", "=", "self", ".", "get_attribute", "(", "\"Code\"", ")", "if", "buff", "is", "None", ":", "return", "None", "with", "unpack", "(", "buff", ")", "as", "up", ":", "code", "=", "JavaCodeInfo", ...
the JavaCodeInfo of this member if it is a non-abstract method, None otherwise reference: http://docs.oracle.com/javase/specs/jvms/se7/html/jvms-4.html#jvms-4.7.3
[ "the", "JavaCodeInfo", "of", "this", "member", "if", "it", "is", "a", "non", "-", "abstract", "method", "None", "otherwise" ]
9e2332b452ddc508bed0615937dddcb2cf051557
https://github.com/obriencj/python-javatools/blob/9e2332b452ddc508bed0615937dddcb2cf051557/javatools/__init__.py#L1300-L1316
train
30,328
obriencj/python-javatools
javatools/__init__.py
JavaMemberInfo.get_exceptions
def get_exceptions(self): """ a tuple of class names for the exception types this method may raise, or None if this is not a method reference: http://docs.oracle.com/javase/specs/jvms/se7/html/jvms-4.html#jvms-4.7.5 """ # noqa buff = self.get_attribute("Exceptions") if buff is None: return () with unpack(buff) as up: return tuple(self.deref_const(e[0]) for e in up.unpack_struct_array(_H))
python
def get_exceptions(self): """ a tuple of class names for the exception types this method may raise, or None if this is not a method reference: http://docs.oracle.com/javase/specs/jvms/se7/html/jvms-4.html#jvms-4.7.5 """ # noqa buff = self.get_attribute("Exceptions") if buff is None: return () with unpack(buff) as up: return tuple(self.deref_const(e[0]) for e in up.unpack_struct_array(_H))
[ "def", "get_exceptions", "(", "self", ")", ":", "# noqa", "buff", "=", "self", ".", "get_attribute", "(", "\"Exceptions\"", ")", "if", "buff", "is", "None", ":", "return", "(", ")", "with", "unpack", "(", "buff", ")", "as", "up", ":", "return", "tuple"...
a tuple of class names for the exception types this method may raise, or None if this is not a method reference: http://docs.oracle.com/javase/specs/jvms/se7/html/jvms-4.html#jvms-4.7.5
[ "a", "tuple", "of", "class", "names", "for", "the", "exception", "types", "this", "method", "may", "raise", "or", "None", "if", "this", "is", "not", "a", "method" ]
9e2332b452ddc508bed0615937dddcb2cf051557
https://github.com/obriencj/python-javatools/blob/9e2332b452ddc508bed0615937dddcb2cf051557/javatools/__init__.py#L1319-L1333
train
30,329
obriencj/python-javatools
javatools/__init__.py
JavaMemberInfo.get_constantvalue
def get_constantvalue(self): """ the constant pool index for this field, or None if this is not a contant field reference: http://docs.oracle.com/javase/specs/jvms/se7/html/jvms-4.html#jvms-4.7.2 """ # noqa buff = self.get_attribute("ConstantValue") if buff is None: return None with unpack(buff) as up: (cval_ref, ) = up.unpack_struct(_H) return cval_ref
python
def get_constantvalue(self): """ the constant pool index for this field, or None if this is not a contant field reference: http://docs.oracle.com/javase/specs/jvms/se7/html/jvms-4.html#jvms-4.7.2 """ # noqa buff = self.get_attribute("ConstantValue") if buff is None: return None with unpack(buff) as up: (cval_ref, ) = up.unpack_struct(_H) return cval_ref
[ "def", "get_constantvalue", "(", "self", ")", ":", "# noqa", "buff", "=", "self", ".", "get_attribute", "(", "\"ConstantValue\"", ")", "if", "buff", "is", "None", ":", "return", "None", "with", "unpack", "(", "buff", ")", "as", "up", ":", "(", "cval_ref"...
the constant pool index for this field, or None if this is not a contant field reference: http://docs.oracle.com/javase/specs/jvms/se7/html/jvms-4.html#jvms-4.7.2
[ "the", "constant", "pool", "index", "for", "this", "field", "or", "None", "if", "this", "is", "not", "a", "contant", "field" ]
9e2332b452ddc508bed0615937dddcb2cf051557
https://github.com/obriencj/python-javatools/blob/9e2332b452ddc508bed0615937dddcb2cf051557/javatools/__init__.py#L1336-L1351
train
30,330
obriencj/python-javatools
javatools/__init__.py
JavaMemberInfo.get_arg_type_descriptors
def get_arg_type_descriptors(self): """ The parameter type descriptor list for a method, or None for a field. Type descriptors are shorthand identifiers for the builtin java types. """ if not self.is_method: return tuple() tp = _typeseq(self.get_descriptor()) tp = _typeseq(tp[0][1:-1]) return tp
python
def get_arg_type_descriptors(self): """ The parameter type descriptor list for a method, or None for a field. Type descriptors are shorthand identifiers for the builtin java types. """ if not self.is_method: return tuple() tp = _typeseq(self.get_descriptor()) tp = _typeseq(tp[0][1:-1]) return tp
[ "def", "get_arg_type_descriptors", "(", "self", ")", ":", "if", "not", "self", ".", "is_method", ":", "return", "tuple", "(", ")", "tp", "=", "_typeseq", "(", "self", ".", "get_descriptor", "(", ")", ")", "tp", "=", "_typeseq", "(", "tp", "[", "0", "...
The parameter type descriptor list for a method, or None for a field. Type descriptors are shorthand identifiers for the builtin java types.
[ "The", "parameter", "type", "descriptor", "list", "for", "a", "method", "or", "None", "for", "a", "field", ".", "Type", "descriptors", "are", "shorthand", "identifiers", "for", "the", "builtin", "java", "types", "." ]
9e2332b452ddc508bed0615937dddcb2cf051557
https://github.com/obriencj/python-javatools/blob/9e2332b452ddc508bed0615937dddcb2cf051557/javatools/__init__.py#L1376-L1389
train
30,331
obriencj/python-javatools
javatools/__init__.py
JavaMemberInfo.pretty_arg_types
def pretty_arg_types(self): """ Sequence of pretty argument types. """ if self.is_method: types = self.get_arg_type_descriptors() return (_pretty_type(t) for t in types) else: return tuple()
python
def pretty_arg_types(self): """ Sequence of pretty argument types. """ if self.is_method: types = self.get_arg_type_descriptors() return (_pretty_type(t) for t in types) else: return tuple()
[ "def", "pretty_arg_types", "(", "self", ")", ":", "if", "self", ".", "is_method", ":", "types", "=", "self", ".", "get_arg_type_descriptors", "(", ")", "return", "(", "_pretty_type", "(", "t", ")", "for", "t", "in", "types", ")", "else", ":", "return", ...
Sequence of pretty argument types.
[ "Sequence", "of", "pretty", "argument", "types", "." ]
9e2332b452ddc508bed0615937dddcb2cf051557
https://github.com/obriencj/python-javatools/blob/9e2332b452ddc508bed0615937dddcb2cf051557/javatools/__init__.py#L1400-L1409
train
30,332
obriencj/python-javatools
javatools/__init__.py
JavaMemberInfo.pretty_descriptor
def pretty_descriptor(self): """ assemble a long member name from access flags, type, argument types, exceptions as applicable """ f = " ".join(self.pretty_access_flags()) p = self.pretty_type() n = self.get_name() t = ",".join(self.pretty_exceptions()) if n == "<init>": # we pretend that there's no return type, even though it's # V for constructors p = None if self.is_method: # stick the name and args together so there's no space n = "%s(%s)" % (n, ",".join(self.pretty_arg_types())) if t: # assemble any throws as necessary t = "throws " + t return " ".join(z for z in (f, p, n, t) if z)
python
def pretty_descriptor(self): """ assemble a long member name from access flags, type, argument types, exceptions as applicable """ f = " ".join(self.pretty_access_flags()) p = self.pretty_type() n = self.get_name() t = ",".join(self.pretty_exceptions()) if n == "<init>": # we pretend that there's no return type, even though it's # V for constructors p = None if self.is_method: # stick the name and args together so there's no space n = "%s(%s)" % (n, ",".join(self.pretty_arg_types())) if t: # assemble any throws as necessary t = "throws " + t return " ".join(z for z in (f, p, n, t) if z)
[ "def", "pretty_descriptor", "(", "self", ")", ":", "f", "=", "\" \"", ".", "join", "(", "self", ".", "pretty_access_flags", "(", ")", ")", "p", "=", "self", ".", "pretty_type", "(", ")", "n", "=", "self", ".", "get_name", "(", ")", "t", "=", "\",\"...
assemble a long member name from access flags, type, argument types, exceptions as applicable
[ "assemble", "a", "long", "member", "name", "from", "access", "flags", "type", "argument", "types", "exceptions", "as", "applicable" ]
9e2332b452ddc508bed0615937dddcb2cf051557
https://github.com/obriencj/python-javatools/blob/9e2332b452ddc508bed0615937dddcb2cf051557/javatools/__init__.py#L1412-L1436
train
30,333
obriencj/python-javatools
javatools/__init__.py
JavaMemberInfo.pretty_identifier
def pretty_identifier(self): """ The pretty version of get_identifier """ ident = self.get_name() if self.is_method: args = ",".join(self.pretty_arg_types()) ident = "%s(%s)" % (ident, args) return "%s:%s" % (ident, self.pretty_type())
python
def pretty_identifier(self): """ The pretty version of get_identifier """ ident = self.get_name() if self.is_method: args = ",".join(self.pretty_arg_types()) ident = "%s(%s)" % (ident, args) return "%s:%s" % (ident, self.pretty_type())
[ "def", "pretty_identifier", "(", "self", ")", ":", "ident", "=", "self", ".", "get_name", "(", ")", "if", "self", ".", "is_method", ":", "args", "=", "\",\"", ".", "join", "(", "self", ".", "pretty_arg_types", "(", ")", ")", "ident", "=", "\"%s(%s)\"",...
The pretty version of get_identifier
[ "The", "pretty", "version", "of", "get_identifier" ]
9e2332b452ddc508bed0615937dddcb2cf051557
https://github.com/obriencj/python-javatools/blob/9e2332b452ddc508bed0615937dddcb2cf051557/javatools/__init__.py#L1520-L1530
train
30,334
obriencj/python-javatools
javatools/__init__.py
JavaCodeInfo.unpack
def unpack(self, unpacker): """ unpacks a code block from a buffer. Updates the internal structure of this instance """ (a, b, c) = unpacker.unpack_struct(_HHI) self.max_stack = a self.max_locals = b self.code = unpacker.read(c) uobjs = unpacker.unpack_objects self.exceptions = tuple(uobjs(JavaExceptionInfo, self)) self.attribs.unpack(unpacker)
python
def unpack(self, unpacker): """ unpacks a code block from a buffer. Updates the internal structure of this instance """ (a, b, c) = unpacker.unpack_struct(_HHI) self.max_stack = a self.max_locals = b self.code = unpacker.read(c) uobjs = unpacker.unpack_objects self.exceptions = tuple(uobjs(JavaExceptionInfo, self)) self.attribs.unpack(unpacker)
[ "def", "unpack", "(", "self", ",", "unpacker", ")", ":", "(", "a", ",", "b", ",", "c", ")", "=", "unpacker", ".", "unpack_struct", "(", "_HHI", ")", "self", ".", "max_stack", "=", "a", "self", ".", "max_locals", "=", "b", "self", ".", "code", "="...
unpacks a code block from a buffer. Updates the internal structure of this instance
[ "unpacks", "a", "code", "block", "from", "a", "buffer", ".", "Updates", "the", "internal", "structure", "of", "this", "instance" ]
9e2332b452ddc508bed0615937dddcb2cf051557
https://github.com/obriencj/python-javatools/blob/9e2332b452ddc508bed0615937dddcb2cf051557/javatools/__init__.py#L1571-L1586
train
30,335
obriencj/python-javatools
javatools/__init__.py
JavaCodeInfo.get_line_for_offset
def get_line_for_offset(self, code_offset): """ returns the line number given a code offset """ prev_line = 0 for (offset, line) in self.get_linenumbertable(): if offset < code_offset: prev_line = line elif offset == code_offset: return line else: return prev_line return prev_line
python
def get_line_for_offset(self, code_offset): """ returns the line number given a code offset """ prev_line = 0 for (offset, line) in self.get_linenumbertable(): if offset < code_offset: prev_line = line elif offset == code_offset: return line else: return prev_line return prev_line
[ "def", "get_line_for_offset", "(", "self", ",", "code_offset", ")", ":", "prev_line", "=", "0", "for", "(", "offset", ",", "line", ")", "in", "self", ".", "get_linenumbertable", "(", ")", ":", "if", "offset", "<", "code_offset", ":", "prev_line", "=", "l...
returns the line number given a code offset
[ "returns", "the", "line", "number", "given", "a", "code", "offset" ]
9e2332b452ddc508bed0615937dddcb2cf051557
https://github.com/obriencj/python-javatools/blob/9e2332b452ddc508bed0615937dddcb2cf051557/javatools/__init__.py#L1655-L1670
train
30,336
obriencj/python-javatools
javatools/__init__.py
JavaExceptionInfo.unpack
def unpack(self, unpacker): """ unpacks an exception handler entry in an exception table. Updates the internal structure of this instance """ (a, b, c, d) = unpacker.unpack_struct(_HHHH) self.start_pc = a self.end_pc = b self.handler_pc = c self.catch_type_ref = d
python
def unpack(self, unpacker): """ unpacks an exception handler entry in an exception table. Updates the internal structure of this instance """ (a, b, c, d) = unpacker.unpack_struct(_HHHH) self.start_pc = a self.end_pc = b self.handler_pc = c self.catch_type_ref = d
[ "def", "unpack", "(", "self", ",", "unpacker", ")", ":", "(", "a", ",", "b", ",", "c", ",", "d", ")", "=", "unpacker", ".", "unpack_struct", "(", "_HHHH", ")", "self", ".", "start_pc", "=", "a", "self", ".", "end_pc", "=", "b", "self", ".", "ha...
unpacks an exception handler entry in an exception table. Updates the internal structure of this instance
[ "unpacks", "an", "exception", "handler", "entry", "in", "an", "exception", "table", ".", "Updates", "the", "internal", "structure", "of", "this", "instance" ]
9e2332b452ddc508bed0615937dddcb2cf051557
https://github.com/obriencj/python-javatools/blob/9e2332b452ddc508bed0615937dddcb2cf051557/javatools/__init__.py#L1734-L1745
train
30,337
obriencj/python-javatools
javatools/__init__.py
JavaExceptionInfo.info
def info(self): """ tuple of the start_pc, end_pc, handler_pc and catch_type_ref """ return (self.start_pc, self.end_pc, self.handler_pc, self.get_catch_type())
python
def info(self): """ tuple of the start_pc, end_pc, handler_pc and catch_type_ref """ return (self.start_pc, self.end_pc, self.handler_pc, self.get_catch_type())
[ "def", "info", "(", "self", ")", ":", "return", "(", "self", ".", "start_pc", ",", "self", ".", "end_pc", ",", "self", ".", "handler_pc", ",", "self", ".", "get_catch_type", "(", ")", ")" ]
tuple of the start_pc, end_pc, handler_pc and catch_type_ref
[ "tuple", "of", "the", "start_pc", "end_pc", "handler_pc", "and", "catch_type_ref" ]
9e2332b452ddc508bed0615937dddcb2cf051557
https://github.com/obriencj/python-javatools/blob/9e2332b452ddc508bed0615937dddcb2cf051557/javatools/__init__.py#L1777-L1783
train
30,338
obriencj/python-javatools
javatools/__init__.py
JavaInnerClassInfo.unpack
def unpack(self, unpacker): """ unpack this instance with data from unpacker """ (a, b, c, d) = unpacker.unpack_struct(_HHHH) self.inner_info_ref = a self.outer_info_ref = b self.name_ref = c self.access_flags = d
python
def unpack(self, unpacker): """ unpack this instance with data from unpacker """ (a, b, c, d) = unpacker.unpack_struct(_HHHH) self.inner_info_ref = a self.outer_info_ref = b self.name_ref = c self.access_flags = d
[ "def", "unpack", "(", "self", ",", "unpacker", ")", ":", "(", "a", ",", "b", ",", "c", ",", "d", ")", "=", "unpacker", ".", "unpack_struct", "(", "_HHHH", ")", "self", ".", "inner_info_ref", "=", "a", "self", ".", "outer_info_ref", "=", "b", "self"...
unpack this instance with data from unpacker
[ "unpack", "this", "instance", "with", "data", "from", "unpacker" ]
9e2332b452ddc508bed0615937dddcb2cf051557
https://github.com/obriencj/python-javatools/blob/9e2332b452ddc508bed0615937dddcb2cf051557/javatools/__init__.py#L1815-L1825
train
30,339
obriencj/python-javatools
javatools/manifest.py
parse_sections
def parse_sections(data): """ yields one section at a time in the form [ (key, [val, ...]), ... ] where key is a string and val is a string representing a single line of any value associated with the key. Multiple vals may be present if the value is long enough to require line continuations in which case simply concatenate the vals together to get the full value. :type data: unicode in Py2, str in Py3 """ if not data: return # our current section curr = None for lineno, line in enumerate(data.splitlines()): # Clean up the line cleanline = line.replace('\x00', '') if not cleanline: # blank line means end of current section (if any) if curr: yield curr curr = None elif cleanline[0] == ' ': # line beginning with a space means a continuation if curr is None: raise MalformedManifest("bad line continuation, " " line: %i" % lineno) else: # pylint: disable=unsubscriptable-object curr[-1][1].append(cleanline[1:]) else: # otherwise the beginning of a new k:v pair if curr is None: curr = list() try: key, val = cleanline.split(':', 1) curr.append((key, [val[1:]])) except ValueError: raise MalformedManifest( "Invalid manifest line: %i; line contents: %s" % (lineno, cleanline)) # yield and leftovers if curr: yield curr
python
def parse_sections(data): """ yields one section at a time in the form [ (key, [val, ...]), ... ] where key is a string and val is a string representing a single line of any value associated with the key. Multiple vals may be present if the value is long enough to require line continuations in which case simply concatenate the vals together to get the full value. :type data: unicode in Py2, str in Py3 """ if not data: return # our current section curr = None for lineno, line in enumerate(data.splitlines()): # Clean up the line cleanline = line.replace('\x00', '') if not cleanline: # blank line means end of current section (if any) if curr: yield curr curr = None elif cleanline[0] == ' ': # line beginning with a space means a continuation if curr is None: raise MalformedManifest("bad line continuation, " " line: %i" % lineno) else: # pylint: disable=unsubscriptable-object curr[-1][1].append(cleanline[1:]) else: # otherwise the beginning of a new k:v pair if curr is None: curr = list() try: key, val = cleanline.split(':', 1) curr.append((key, [val[1:]])) except ValueError: raise MalformedManifest( "Invalid manifest line: %i; line contents: %s" % (lineno, cleanline)) # yield and leftovers if curr: yield curr
[ "def", "parse_sections", "(", "data", ")", ":", "if", "not", "data", ":", "return", "# our current section", "curr", "=", "None", "for", "lineno", ",", "line", "in", "enumerate", "(", "data", ".", "splitlines", "(", ")", ")", ":", "# Clean up the line", "c...
yields one section at a time in the form [ (key, [val, ...]), ... ] where key is a string and val is a string representing a single line of any value associated with the key. Multiple vals may be present if the value is long enough to require line continuations in which case simply concatenate the vals together to get the full value. :type data: unicode in Py2, str in Py3
[ "yields", "one", "section", "at", "a", "time", "in", "the", "form" ]
9e2332b452ddc508bed0615937dddcb2cf051557
https://github.com/obriencj/python-javatools/blob/9e2332b452ddc508bed0615937dddcb2cf051557/javatools/manifest.py#L698-L753
train
30,340
obriencj/python-javatools
javatools/manifest.py
digest_chunks
def digest_chunks(chunks, algorithms=(hashlib.md5, hashlib.sha1)): """ returns a base64 rep of the given digest algorithms from the chunks of data """ hashes = [algorithm() for algorithm in algorithms] for chunk in chunks: for h in hashes: h.update(chunk) return [_b64encode_to_str(h.digest()) for h in hashes]
python
def digest_chunks(chunks, algorithms=(hashlib.md5, hashlib.sha1)): """ returns a base64 rep of the given digest algorithms from the chunks of data """ hashes = [algorithm() for algorithm in algorithms] for chunk in chunks: for h in hashes: h.update(chunk) return [_b64encode_to_str(h.digest()) for h in hashes]
[ "def", "digest_chunks", "(", "chunks", ",", "algorithms", "=", "(", "hashlib", ".", "md5", ",", "hashlib", ".", "sha1", ")", ")", ":", "hashes", "=", "[", "algorithm", "(", ")", "for", "algorithm", "in", "algorithms", "]", "for", "chunk", "in", "chunks...
returns a base64 rep of the given digest algorithms from the chunks of data
[ "returns", "a", "base64", "rep", "of", "the", "given", "digest", "algorithms", "from", "the", "chunks", "of", "data" ]
9e2332b452ddc508bed0615937dddcb2cf051557
https://github.com/obriencj/python-javatools/blob/9e2332b452ddc508bed0615937dddcb2cf051557/javatools/manifest.py#L796-L808
train
30,341
obriencj/python-javatools
javatools/manifest.py
file_chunk
def file_chunk(filename, size=_BUFFERING): """ returns a generator function which when called will emit x-sized chunks of filename's contents """ def chunks(): with open(filename, "rb", _BUFFERING) as fd: buf = fd.read(size) while buf: yield buf buf = fd.read(size) return chunks
python
def file_chunk(filename, size=_BUFFERING): """ returns a generator function which when called will emit x-sized chunks of filename's contents """ def chunks(): with open(filename, "rb", _BUFFERING) as fd: buf = fd.read(size) while buf: yield buf buf = fd.read(size) return chunks
[ "def", "file_chunk", "(", "filename", ",", "size", "=", "_BUFFERING", ")", ":", "def", "chunks", "(", ")", ":", "with", "open", "(", "filename", ",", "\"rb\"", ",", "_BUFFERING", ")", "as", "fd", ":", "buf", "=", "fd", ".", "read", "(", "size", ")"...
returns a generator function which when called will emit x-sized chunks of filename's contents
[ "returns", "a", "generator", "function", "which", "when", "called", "will", "emit", "x", "-", "sized", "chunks", "of", "filename", "s", "contents" ]
9e2332b452ddc508bed0615937dddcb2cf051557
https://github.com/obriencj/python-javatools/blob/9e2332b452ddc508bed0615937dddcb2cf051557/javatools/manifest.py#L811-L823
train
30,342
obriencj/python-javatools
javatools/manifest.py
zipentry_chunk
def zipentry_chunk(zipfile, name, size=_BUFFERING): """ returns a generator function which when called will emit x-sized chunks of the named entry in the zipfile object """ def chunks(): with zipfile.open(name) as fd: buf = fd.read(size) while buf: yield buf buf = fd.read(size) return chunks
python
def zipentry_chunk(zipfile, name, size=_BUFFERING): """ returns a generator function which when called will emit x-sized chunks of the named entry in the zipfile object """ def chunks(): with zipfile.open(name) as fd: buf = fd.read(size) while buf: yield buf buf = fd.read(size) return chunks
[ "def", "zipentry_chunk", "(", "zipfile", ",", "name", ",", "size", "=", "_BUFFERING", ")", ":", "def", "chunks", "(", ")", ":", "with", "zipfile", ".", "open", "(", "name", ")", "as", "fd", ":", "buf", "=", "fd", ".", "read", "(", "size", ")", "w...
returns a generator function which when called will emit x-sized chunks of the named entry in the zipfile object
[ "returns", "a", "generator", "function", "which", "when", "called", "will", "emit", "x", "-", "sized", "chunks", "of", "the", "named", "entry", "in", "the", "zipfile", "object" ]
9e2332b452ddc508bed0615937dddcb2cf051557
https://github.com/obriencj/python-javatools/blob/9e2332b452ddc508bed0615937dddcb2cf051557/javatools/manifest.py#L826-L838
train
30,343
obriencj/python-javatools
javatools/manifest.py
single_path_generator
def single_path_generator(pathname): """ emits name,chunkgen pairs for the given file at pathname. If pathname is a directory, will act recursively and will emit for each file in the directory tree chunkgen is a generator that can be iterated over to obtain the contents of the file in multiple parts """ if isdir(pathname): trim = len(pathname) if pathname[-1] != sep: trim += 1 for entry in directory_generator(pathname, trim): yield entry else: zf = ZipFile(pathname) for f in zf.namelist(): if f[-1] != '/': yield f, zipentry_chunk(zf, f) zf.close()
python
def single_path_generator(pathname): """ emits name,chunkgen pairs for the given file at pathname. If pathname is a directory, will act recursively and will emit for each file in the directory tree chunkgen is a generator that can be iterated over to obtain the contents of the file in multiple parts """ if isdir(pathname): trim = len(pathname) if pathname[-1] != sep: trim += 1 for entry in directory_generator(pathname, trim): yield entry else: zf = ZipFile(pathname) for f in zf.namelist(): if f[-1] != '/': yield f, zipentry_chunk(zf, f) zf.close()
[ "def", "single_path_generator", "(", "pathname", ")", ":", "if", "isdir", "(", "pathname", ")", ":", "trim", "=", "len", "(", "pathname", ")", "if", "pathname", "[", "-", "1", "]", "!=", "sep", ":", "trim", "+=", "1", "for", "entry", "in", "directory...
emits name,chunkgen pairs for the given file at pathname. If pathname is a directory, will act recursively and will emit for each file in the directory tree chunkgen is a generator that can be iterated over to obtain the contents of the file in multiple parts
[ "emits", "name", "chunkgen", "pairs", "for", "the", "given", "file", "at", "pathname", ".", "If", "pathname", "is", "a", "directory", "will", "act", "recursively", "and", "will", "emit", "for", "each", "file", "in", "the", "directory", "tree", "chunkgen", ...
9e2332b452ddc508bed0615937dddcb2cf051557
https://github.com/obriencj/python-javatools/blob/9e2332b452ddc508bed0615937dddcb2cf051557/javatools/manifest.py#L902-L923
train
30,344
obriencj/python-javatools
javatools/manifest.py
cli_create
def cli_create(argument_list): """ command-line call to create a manifest from a JAR file or a directory """ parser = argparse.ArgumentParser() parser.add_argument("content", help="file or directory") # TODO: shouldn't we always process directories recursively? parser.add_argument("-r", "--recursive", help="process directories recursively") parser.add_argument("-i", "--ignore", nargs="+", action="append", help="patterns to ignore " "(can be given more than once)") parser.add_argument("-m", "--manifest", default=None, help="output file (default is stdout)") parser.add_argument("-d", "--digest", help="digest(s) to use, comma-separated") args = parser.parse_args(argument_list) # TODO: remove digest from here, they are created when signing! if args.digest is None: args.digest = "MD5,SHA1" requested_digests = args.digest.split(",") use_digests = [_get_digest(digest) for digest in requested_digests] if args.recursive: entries = multi_path_generator(args.content) else: entries = single_path_generator(args.content) mf = Manifest() ignores = ["META-INF/*"] if args.ignore: ignores.extend(*args.ignore) for name, chunks in entries: # skip the stuff that we were told to ignore if ignores and fnmatches(name, *ignores): continue sec = mf.create_section(name) digests = zip(requested_digests, digest_chunks(chunks(), use_digests)) for digest_name, digest_value in digests: sec[digest_name + "-Digest"] = digest_value if args.manifest: # we'll output to the manifest file if specified, and we'll # even create parent directories for it, if necessary makedirsp(split(args.manifest)[0]) output = open(args.manifest, "wb") else: output = sys.stdout mf.store(output) if args.manifest: output.close()
python
def cli_create(argument_list): """ command-line call to create a manifest from a JAR file or a directory """ parser = argparse.ArgumentParser() parser.add_argument("content", help="file or directory") # TODO: shouldn't we always process directories recursively? parser.add_argument("-r", "--recursive", help="process directories recursively") parser.add_argument("-i", "--ignore", nargs="+", action="append", help="patterns to ignore " "(can be given more than once)") parser.add_argument("-m", "--manifest", default=None, help="output file (default is stdout)") parser.add_argument("-d", "--digest", help="digest(s) to use, comma-separated") args = parser.parse_args(argument_list) # TODO: remove digest from here, they are created when signing! if args.digest is None: args.digest = "MD5,SHA1" requested_digests = args.digest.split(",") use_digests = [_get_digest(digest) for digest in requested_digests] if args.recursive: entries = multi_path_generator(args.content) else: entries = single_path_generator(args.content) mf = Manifest() ignores = ["META-INF/*"] if args.ignore: ignores.extend(*args.ignore) for name, chunks in entries: # skip the stuff that we were told to ignore if ignores and fnmatches(name, *ignores): continue sec = mf.create_section(name) digests = zip(requested_digests, digest_chunks(chunks(), use_digests)) for digest_name, digest_value in digests: sec[digest_name + "-Digest"] = digest_value if args.manifest: # we'll output to the manifest file if specified, and we'll # even create parent directories for it, if necessary makedirsp(split(args.manifest)[0]) output = open(args.manifest, "wb") else: output = sys.stdout mf.store(output) if args.manifest: output.close()
[ "def", "cli_create", "(", "argument_list", ")", ":", "parser", "=", "argparse", ".", "ArgumentParser", "(", ")", "parser", ".", "add_argument", "(", "\"content\"", ",", "help", "=", "\"file or directory\"", ")", "# TODO: shouldn't we always process directories recursive...
command-line call to create a manifest from a JAR file or a directory
[ "command", "-", "line", "call", "to", "create", "a", "manifest", "from", "a", "JAR", "file", "or", "a", "directory" ]
9e2332b452ddc508bed0615937dddcb2cf051557
https://github.com/obriencj/python-javatools/blob/9e2332b452ddc508bed0615937dddcb2cf051557/javatools/manifest.py#L926-L986
train
30,345
obriencj/python-javatools
javatools/manifest.py
main
def main(args=sys.argv): """ main entry point for the manifest CLI """ if len(args) < 2: return usage("Command expected") command = args[1] rest = args[2:] if "create".startswith(command): return cli_create(rest) elif "query".startswith(command): return cli_query(rest) elif "verify".startswith(command): return cli_verify(rest) else: return usage("Unknown command: %s" % command)
python
def main(args=sys.argv): """ main entry point for the manifest CLI """ if len(args) < 2: return usage("Command expected") command = args[1] rest = args[2:] if "create".startswith(command): return cli_create(rest) elif "query".startswith(command): return cli_query(rest) elif "verify".startswith(command): return cli_verify(rest) else: return usage("Unknown command: %s" % command)
[ "def", "main", "(", "args", "=", "sys", ".", "argv", ")", ":", "if", "len", "(", "args", ")", "<", "2", ":", "return", "usage", "(", "\"Command expected\"", ")", "command", "=", "args", "[", "1", "]", "rest", "=", "args", "[", "2", ":", "]", "i...
main entry point for the manifest CLI
[ "main", "entry", "point", "for", "the", "manifest", "CLI" ]
9e2332b452ddc508bed0615937dddcb2cf051557
https://github.com/obriencj/python-javatools/blob/9e2332b452ddc508bed0615937dddcb2cf051557/javatools/manifest.py#L1041-L1059
train
30,346
obriencj/python-javatools
javatools/manifest.py
ManifestSection.load
def load(self, items): """ Populate this section from an iteration of the parse_items call """ for k, vals in items: self[k] = "".join(vals)
python
def load(self, items): """ Populate this section from an iteration of the parse_items call """ for k, vals in items: self[k] = "".join(vals)
[ "def", "load", "(", "self", ",", "items", ")", ":", "for", "k", ",", "vals", "in", "items", ":", "self", "[", "k", "]", "=", "\"\"", ".", "join", "(", "vals", ")" ]
Populate this section from an iteration of the parse_items call
[ "Populate", "this", "section", "from", "an", "iteration", "of", "the", "parse_items", "call" ]
9e2332b452ddc508bed0615937dddcb2cf051557
https://github.com/obriencj/python-javatools/blob/9e2332b452ddc508bed0615937dddcb2cf051557/javatools/manifest.py#L267-L273
train
30,347
obriencj/python-javatools
javatools/manifest.py
ManifestSection.store
def store(self, stream, linesep=os.linesep): """ Serialize this section and write it to a binary stream """ for k, v in self.items(): write_key_val(stream, k, v, linesep) stream.write(linesep.encode('utf-8'))
python
def store(self, stream, linesep=os.linesep): """ Serialize this section and write it to a binary stream """ for k, v in self.items(): write_key_val(stream, k, v, linesep) stream.write(linesep.encode('utf-8'))
[ "def", "store", "(", "self", ",", "stream", ",", "linesep", "=", "os", ".", "linesep", ")", ":", "for", "k", ",", "v", "in", "self", ".", "items", "(", ")", ":", "write_key_val", "(", "stream", ",", "k", ",", "v", ",", "linesep", ")", "stream", ...
Serialize this section and write it to a binary stream
[ "Serialize", "this", "section", "and", "write", "it", "to", "a", "binary", "stream" ]
9e2332b452ddc508bed0615937dddcb2cf051557
https://github.com/obriencj/python-javatools/blob/9e2332b452ddc508bed0615937dddcb2cf051557/javatools/manifest.py#L276-L284
train
30,348
obriencj/python-javatools
javatools/manifest.py
Manifest.create_section
def create_section(self, name, overwrite=True): """ create and return a new sub-section of this manifest, with the given Name attribute. If a sub-section already exists with that name, it will be lost unless overwrite is False in which case the existing sub-section will be returned. """ if overwrite: sect = ManifestSection(name) self.sub_sections[name] = sect else: sect = self.sub_sections.get(name, None) if sect is None: sect = ManifestSection(name) self.sub_sections[name] = sect return sect
python
def create_section(self, name, overwrite=True): """ create and return a new sub-section of this manifest, with the given Name attribute. If a sub-section already exists with that name, it will be lost unless overwrite is False in which case the existing sub-section will be returned. """ if overwrite: sect = ManifestSection(name) self.sub_sections[name] = sect else: sect = self.sub_sections.get(name, None) if sect is None: sect = ManifestSection(name) self.sub_sections[name] = sect return sect
[ "def", "create_section", "(", "self", ",", "name", ",", "overwrite", "=", "True", ")", ":", "if", "overwrite", ":", "sect", "=", "ManifestSection", "(", "name", ")", "self", ".", "sub_sections", "[", "name", "]", "=", "sect", "else", ":", "sect", "=", ...
create and return a new sub-section of this manifest, with the given Name attribute. If a sub-section already exists with that name, it will be lost unless overwrite is False in which case the existing sub-section will be returned.
[ "create", "and", "return", "a", "new", "sub", "-", "section", "of", "this", "manifest", "with", "the", "given", "Name", "attribute", ".", "If", "a", "sub", "-", "section", "already", "exists", "with", "that", "name", "it", "will", "be", "lost", "unless",...
9e2332b452ddc508bed0615937dddcb2cf051557
https://github.com/obriencj/python-javatools/blob/9e2332b452ddc508bed0615937dddcb2cf051557/javatools/manifest.py#L325-L343
train
30,349
obriencj/python-javatools
javatools/manifest.py
Manifest.store
def store(self, stream, linesep=None): """ Serialize the Manifest to a binary stream """ # either specified here, specified on the instance, or the OS # default linesep = linesep or self.linesep or os.linesep ManifestSection.store(self, stream, linesep) for sect in sorted(self.sub_sections.values()): sect.store(stream, linesep)
python
def store(self, stream, linesep=None): """ Serialize the Manifest to a binary stream """ # either specified here, specified on the instance, or the OS # default linesep = linesep or self.linesep or os.linesep ManifestSection.store(self, stream, linesep) for sect in sorted(self.sub_sections.values()): sect.store(stream, linesep)
[ "def", "store", "(", "self", ",", "stream", ",", "linesep", "=", "None", ")", ":", "# either specified here, specified on the instance, or the OS", "# default", "linesep", "=", "linesep", "or", "self", ".", "linesep", "or", "os", ".", "linesep", "ManifestSection", ...
Serialize the Manifest to a binary stream
[ "Serialize", "the", "Manifest", "to", "a", "binary", "stream" ]
9e2332b452ddc508bed0615937dddcb2cf051557
https://github.com/obriencj/python-javatools/blob/9e2332b452ddc508bed0615937dddcb2cf051557/javatools/manifest.py#L389-L400
train
30,350
obriencj/python-javatools
javatools/manifest.py
Manifest.clear
def clear(self): """ removes all items from this manifest, and clears and removes all sub-sections """ for sub in self.sub_sections.values(): sub.clear() self.sub_sections.clear() ManifestSection.clear(self)
python
def clear(self): """ removes all items from this manifest, and clears and removes all sub-sections """ for sub in self.sub_sections.values(): sub.clear() self.sub_sections.clear() ManifestSection.clear(self)
[ "def", "clear", "(", "self", ")", ":", "for", "sub", "in", "self", ".", "sub_sections", ".", "values", "(", ")", ":", "sub", ".", "clear", "(", ")", "self", ".", "sub_sections", ".", "clear", "(", ")", "ManifestSection", ".", "clear", "(", "self", ...
removes all items from this manifest, and clears and removes all sub-sections
[ "removes", "all", "items", "from", "this", "manifest", "and", "clears", "and", "removes", "all", "sub", "-", "sections" ]
9e2332b452ddc508bed0615937dddcb2cf051557
https://github.com/obriencj/python-javatools/blob/9e2332b452ddc508bed0615937dddcb2cf051557/javatools/manifest.py#L487-L497
train
30,351
obriencj/python-javatools
javatools/manifest.py
SignatureManifest.digest_manifest
def digest_manifest(self, manifest, java_algorithm="SHA-256"): """ Create a main section checksum and sub-section checksums based off of the data from an existing manifest using an algorithm given by Java-style name. """ # pick a line separator for creating checksums of the manifest # contents. We want to use either the one from the given # manifest, or the OS default if it hasn't specified one. linesep = manifest.linesep or os.linesep all_key = java_algorithm + "-Digest-Manifest" main_key = java_algorithm + "-Digest-Manifest-Main-Attributes" sect_key = java_algorithm + "-Digest" digest = _get_digest(java_algorithm) accum = manifest.get_main_section() self[main_key] = b64_encoded_digest(accum, digest) for sub_section in manifest.sub_sections.values(): sub_data = sub_section.get_data(linesep) sf_sect = self.create_section(sub_section.primary()) sf_sect[sect_key] = b64_encoded_digest(sub_data, digest) accum += sub_data self[all_key] = b64_encoded_digest(accum, digest)
python
def digest_manifest(self, manifest, java_algorithm="SHA-256"): """ Create a main section checksum and sub-section checksums based off of the data from an existing manifest using an algorithm given by Java-style name. """ # pick a line separator for creating checksums of the manifest # contents. We want to use either the one from the given # manifest, or the OS default if it hasn't specified one. linesep = manifest.linesep or os.linesep all_key = java_algorithm + "-Digest-Manifest" main_key = java_algorithm + "-Digest-Manifest-Main-Attributes" sect_key = java_algorithm + "-Digest" digest = _get_digest(java_algorithm) accum = manifest.get_main_section() self[main_key] = b64_encoded_digest(accum, digest) for sub_section in manifest.sub_sections.values(): sub_data = sub_section.get_data(linesep) sf_sect = self.create_section(sub_section.primary()) sf_sect[sect_key] = b64_encoded_digest(sub_data, digest) accum += sub_data self[all_key] = b64_encoded_digest(accum, digest)
[ "def", "digest_manifest", "(", "self", ",", "manifest", ",", "java_algorithm", "=", "\"SHA-256\"", ")", ":", "# pick a line separator for creating checksums of the manifest", "# contents. We want to use either the one from the given", "# manifest, or the OS default if it hasn't specified...
Create a main section checksum and sub-section checksums based off of the data from an existing manifest using an algorithm given by Java-style name.
[ "Create", "a", "main", "section", "checksum", "and", "sub", "-", "section", "checksums", "based", "off", "of", "the", "data", "from", "an", "existing", "manifest", "using", "an", "algorithm", "given", "by", "Java", "-", "style", "name", "." ]
9e2332b452ddc508bed0615937dddcb2cf051557
https://github.com/obriencj/python-javatools/blob/9e2332b452ddc508bed0615937dddcb2cf051557/javatools/manifest.py#L514-L540
train
30,352
obriencj/python-javatools
javatools/manifest.py
SignatureManifest.verify_manifest_main_checksum
def verify_manifest_main_checksum(self, manifest): """ Verify the checksum over the manifest main section. :return: True if the signature over main section verifies """ # NOTE: JAR spec does not state whether there can be >1 digest used, # and should the validator require any or all digests to match. # We allow mismatching digests and require just one to be correct. # We see no security risk: it is the signer of the .SF file # who shall check, what is being signed. for java_digest in self.keys_with_suffix("-Digest-Manifest"): whole_mf_digest = b64_encoded_digest( manifest.get_data(), _get_digest(java_digest)) # It is enough for at least one digest to be correct if whole_mf_digest == self.get(java_digest + "-Digest-Manifest"): return True return False
python
def verify_manifest_main_checksum(self, manifest): """ Verify the checksum over the manifest main section. :return: True if the signature over main section verifies """ # NOTE: JAR spec does not state whether there can be >1 digest used, # and should the validator require any or all digests to match. # We allow mismatching digests and require just one to be correct. # We see no security risk: it is the signer of the .SF file # who shall check, what is being signed. for java_digest in self.keys_with_suffix("-Digest-Manifest"): whole_mf_digest = b64_encoded_digest( manifest.get_data(), _get_digest(java_digest)) # It is enough for at least one digest to be correct if whole_mf_digest == self.get(java_digest + "-Digest-Manifest"): return True return False
[ "def", "verify_manifest_main_checksum", "(", "self", ",", "manifest", ")", ":", "# NOTE: JAR spec does not state whether there can be >1 digest used,", "# and should the validator require any or all digests to match.", "# We allow mismatching digests and require just one to be correct.", "# We...
Verify the checksum over the manifest main section. :return: True if the signature over main section verifies
[ "Verify", "the", "checksum", "over", "the", "manifest", "main", "section", "." ]
9e2332b452ddc508bed0615937dddcb2cf051557
https://github.com/obriencj/python-javatools/blob/9e2332b452ddc508bed0615937dddcb2cf051557/javatools/manifest.py#L542-L563
train
30,353
obriencj/python-javatools
javatools/manifest.py
SignatureManifest.verify_manifest_entry_checksums
def verify_manifest_entry_checksums(self, manifest, strict=True): """ Verifies the checksums over the given manifest. If strict is True then entries which had no digests will fail verification. If strict is False then entries with no digests will not be considered failing. :return: List of entries which failed to verify. Reference: http://docs.oracle.com/javase/7/docs/technotes/guides/jar/jar.html#Signature_Validation """ # TODO: this behavior is probably wrong -- surely if there are # multiple digests, they should ALL match, or verification would # fail? failures = [] for s in manifest.sub_sections.values(): sf_section = self.create_section(s.primary(), overwrite=False) digests = s.keys_with_suffix("-Digest") if not digests and strict: failures.append(s.primary()) continue for java_digest in digests: section_digest = b64_encoded_digest( s.get_data(manifest.linesep), _get_digest(java_digest)) if section_digest == sf_section.get(java_digest + "-Digest"): # found a match, verified break else: # no matches found for the digests present failures.append(s.primary()) return failures
python
def verify_manifest_entry_checksums(self, manifest, strict=True): """ Verifies the checksums over the given manifest. If strict is True then entries which had no digests will fail verification. If strict is False then entries with no digests will not be considered failing. :return: List of entries which failed to verify. Reference: http://docs.oracle.com/javase/7/docs/technotes/guides/jar/jar.html#Signature_Validation """ # TODO: this behavior is probably wrong -- surely if there are # multiple digests, they should ALL match, or verification would # fail? failures = [] for s in manifest.sub_sections.values(): sf_section = self.create_section(s.primary(), overwrite=False) digests = s.keys_with_suffix("-Digest") if not digests and strict: failures.append(s.primary()) continue for java_digest in digests: section_digest = b64_encoded_digest( s.get_data(manifest.linesep), _get_digest(java_digest)) if section_digest == sf_section.get(java_digest + "-Digest"): # found a match, verified break else: # no matches found for the digests present failures.append(s.primary()) return failures
[ "def", "verify_manifest_entry_checksums", "(", "self", ",", "manifest", ",", "strict", "=", "True", ")", ":", "# TODO: this behavior is probably wrong -- surely if there are", "# multiple digests, they should ALL match, or verification would", "# fail?", "failures", "=", "[", "]"...
Verifies the checksums over the given manifest. If strict is True then entries which had no digests will fail verification. If strict is False then entries with no digests will not be considered failing. :return: List of entries which failed to verify. Reference: http://docs.oracle.com/javase/7/docs/technotes/guides/jar/jar.html#Signature_Validation
[ "Verifies", "the", "checksums", "over", "the", "given", "manifest", ".", "If", "strict", "is", "True", "then", "entries", "which", "had", "no", "digests", "will", "fail", "verification", ".", "If", "strict", "is", "False", "then", "entries", "with", "no", ...
9e2332b452ddc508bed0615937dddcb2cf051557
https://github.com/obriencj/python-javatools/blob/9e2332b452ddc508bed0615937dddcb2cf051557/javatools/manifest.py#L585-L624
train
30,354
obriencj/python-javatools
javatools/dirutils.py
fnmatches
def fnmatches(entry, *pattern_list): """ returns true if entry matches any of the glob patterns, false otherwise """ for pattern in pattern_list: if pattern and fnmatch(entry, pattern): return True return False
python
def fnmatches(entry, *pattern_list): """ returns true if entry matches any of the glob patterns, false otherwise """ for pattern in pattern_list: if pattern and fnmatch(entry, pattern): return True return False
[ "def", "fnmatches", "(", "entry", ",", "*", "pattern_list", ")", ":", "for", "pattern", "in", "pattern_list", ":", "if", "pattern", "and", "fnmatch", "(", "entry", ",", "pattern", ")", ":", "return", "True", "return", "False" ]
returns true if entry matches any of the glob patterns, false otherwise
[ "returns", "true", "if", "entry", "matches", "any", "of", "the", "glob", "patterns", "false", "otherwise" ]
9e2332b452ddc508bed0615937dddcb2cf051557
https://github.com/obriencj/python-javatools/blob/9e2332b452ddc508bed0615937dddcb2cf051557/javatools/dirutils.py#L39-L48
train
30,355
obriencj/python-javatools
javatools/dirutils.py
copydir
def copydir(orig, dest): """ copies directory orig to dest. Returns a list of tuples of relative filenames which were copied from orig to dest """ copied = list() makedirsp(dest) for root, dirs, files in walk(orig): for d in dirs: # ensure directories exist makedirsp(join(dest, d)) for f in files: root_f = join(root, f) dest_f = join(dest, relpath(root_f, orig)) copy(root_f, dest_f) copied.append((root_f, dest_f)) return copied
python
def copydir(orig, dest): """ copies directory orig to dest. Returns a list of tuples of relative filenames which were copied from orig to dest """ copied = list() makedirsp(dest) for root, dirs, files in walk(orig): for d in dirs: # ensure directories exist makedirsp(join(dest, d)) for f in files: root_f = join(root, f) dest_f = join(dest, relpath(root_f, orig)) copy(root_f, dest_f) copied.append((root_f, dest_f)) return copied
[ "def", "copydir", "(", "orig", ",", "dest", ")", ":", "copied", "=", "list", "(", ")", "makedirsp", "(", "dest", ")", "for", "root", ",", "dirs", ",", "files", "in", "walk", "(", "orig", ")", ":", "for", "d", "in", "dirs", ":", "# ensure directorie...
copies directory orig to dest. Returns a list of tuples of relative filenames which were copied from orig to dest
[ "copies", "directory", "orig", "to", "dest", ".", "Returns", "a", "list", "of", "tuples", "of", "relative", "filenames", "which", "were", "copied", "from", "orig", "to", "dest" ]
9e2332b452ddc508bed0615937dddcb2cf051557
https://github.com/obriencj/python-javatools/blob/9e2332b452ddc508bed0615937dddcb2cf051557/javatools/dirutils.py#L60-L81
train
30,356
obriencj/python-javatools
javatools/dirutils.py
_gen_from_dircmp
def _gen_from_dircmp(dc, lpath, rpath): """ do the work of comparing the dircmp """ left_only = dc.left_only left_only.sort() for f in left_only: fp = join(dc.left, f) if isdir(fp): for r, _ds, fs in walk(fp): r = relpath(r, lpath) for f in fs: yield(LEFT, join(r, f)) else: yield (LEFT, relpath(fp, lpath)) right_only = dc.right_only right_only.sort() for f in right_only: fp = join(dc.right, f) if isdir(fp): for r, _ds, fs in walk(fp): r = relpath(r, rpath) for f in fs: yield(RIGHT, join(r, f)) else: yield (RIGHT, relpath(fp, rpath)) diff_files = dc.diff_files diff_files.sort() for f in diff_files: yield (DIFF, join(relpath(dc.right, rpath), f)) same_files = dc.same_files same_files.sort() for f in same_files: yield (BOTH, join(relpath(dc.left, lpath), f)) subdirs = dc.subdirs.values() subdirs = sorted(subdirs) for sub in subdirs: for event in _gen_from_dircmp(sub, lpath, rpath): yield event
python
def _gen_from_dircmp(dc, lpath, rpath): """ do the work of comparing the dircmp """ left_only = dc.left_only left_only.sort() for f in left_only: fp = join(dc.left, f) if isdir(fp): for r, _ds, fs in walk(fp): r = relpath(r, lpath) for f in fs: yield(LEFT, join(r, f)) else: yield (LEFT, relpath(fp, lpath)) right_only = dc.right_only right_only.sort() for f in right_only: fp = join(dc.right, f) if isdir(fp): for r, _ds, fs in walk(fp): r = relpath(r, rpath) for f in fs: yield(RIGHT, join(r, f)) else: yield (RIGHT, relpath(fp, rpath)) diff_files = dc.diff_files diff_files.sort() for f in diff_files: yield (DIFF, join(relpath(dc.right, rpath), f)) same_files = dc.same_files same_files.sort() for f in same_files: yield (BOTH, join(relpath(dc.left, lpath), f)) subdirs = dc.subdirs.values() subdirs = sorted(subdirs) for sub in subdirs: for event in _gen_from_dircmp(sub, lpath, rpath): yield event
[ "def", "_gen_from_dircmp", "(", "dc", ",", "lpath", ",", "rpath", ")", ":", "left_only", "=", "dc", ".", "left_only", "left_only", ".", "sort", "(", ")", "for", "f", "in", "left_only", ":", "fp", "=", "join", "(", "dc", ".", "left", ",", "f", ")", ...
do the work of comparing the dircmp
[ "do", "the", "work", "of", "comparing", "the", "dircmp" ]
9e2332b452ddc508bed0615937dddcb2cf051557
https://github.com/obriencj/python-javatools/blob/9e2332b452ddc508bed0615937dddcb2cf051557/javatools/dirutils.py#L96-L143
train
30,357
obriencj/python-javatools
javatools/jarutil.py
verify
def verify(certificate, jar_file, sf_name=None): """ Verifies signature of a JAR file. Limitations: - diagnostic is less verbose than of jarsigner :return None if verification succeeds. :exception SignatureBlockFileVerificationError, ManifestChecksumError, JarChecksumError, JarSignatureMissingError Reference: http://docs.oracle.com/javase/7/docs/technotes/guides/jar/jar.html#Signature_Validation Note that the validation is done in three steps. Failure at any step is a failure of the whole validation. """ # noqua # Step 0: get the "key alias", used also for naming of sig-related files. zip_file = ZipFile(jar_file) sf_files = [f for f in zip_file.namelist() if file_matches_sigfile(f)] if len(sf_files) == 0: raise JarSignatureMissingError("No .SF file in %s" % jar_file) elif len(sf_files) > 1: if sf_name is None: msg = "Multiple .SF files in %s, but SF_NAME.SF not specified" \ % jar_file raise VerificationError(msg) elif ('META-INF/' + sf_name) in sf_files: sf_filename = 'META-INF/' + sf_name else: msg = "No .SF file in %s named META-INF/%s (found %d .SF files)" \ % (jar_file, sf_name, len(sf_files)) raise VerificationError(msg) elif len(sf_files) == 1: if sf_name is None: sf_filename = sf_files[0] elif sf_files[0] == 'META-INF/' + sf_name: sf_filename = sf_files[0] else: msg = "No .SF file in %s named META-INF/%s" % (jar_file, sf_name) raise VerificationError(msg) key_alias = sf_filename[9:-3] # "META-INF/%s.SF" sf_data = zip_file.read(sf_filename) # Step 1: check the crypto part. file_list = zip_file.namelist() sig_block_filename = None # JAR specification mentions only RSA and DSA; jarsigner also has EC # TODO: what about "SIG-*"? signature_extensions = ("RSA", "DSA", "EC") for extension in signature_extensions: candidate_filename = "META-INF/%s.%s" % (key_alias, extension) if candidate_filename in file_list: sig_block_filename = candidate_filename break if sig_block_filename is None: msg = "None of %s found in JAR" % \ ", ".join(key_alias + "." + x for x in signature_extensions) raise JarSignatureMissingError(msg) sig_block_data = zip_file.read(sig_block_filename) try: verify_signature_block(certificate, sf_data, sig_block_data) except SignatureBlockVerificationError as message: message = "Signature block verification failed: %s" % message raise SignatureBlockFileVerificationError(message) # KEYALIAS.SF is correctly signed. # Step 2: Check that it contains correct checksum of the manifest. signature_manifest = SignatureManifest() signature_manifest.parse(sf_data) jar_manifest = Manifest() jar_manifest.load_from_jar(jar_file) errors = signature_manifest.verify_manifest(jar_manifest) if len(errors) > 0: msg = "%s: in .SF file, section checksum(s) failed for: %s" \ % (jar_file, ",".join(errors)) raise ManifestChecksumError(msg) # Checksums of MANIFEST.MF itself are correct. # Step 3: Check that it contains valid checksums for each file # from the JAR. NOTE: the check is done for JAR entries. If some # JAR entries are deleted after signing, the verification still # succeeds. This seems to not follow the reference specification, # but that's what jarsigner does. errors = jar_manifest.verify_jar_checksums(jar_file) if len(errors) > 0: msg = "Checksum(s) for jar entries of jar file %s failed for: %s" \ % (jar_file, ",".join(errors)) raise JarChecksumError(msg) return None
python
def verify(certificate, jar_file, sf_name=None): """ Verifies signature of a JAR file. Limitations: - diagnostic is less verbose than of jarsigner :return None if verification succeeds. :exception SignatureBlockFileVerificationError, ManifestChecksumError, JarChecksumError, JarSignatureMissingError Reference: http://docs.oracle.com/javase/7/docs/technotes/guides/jar/jar.html#Signature_Validation Note that the validation is done in three steps. Failure at any step is a failure of the whole validation. """ # noqua # Step 0: get the "key alias", used also for naming of sig-related files. zip_file = ZipFile(jar_file) sf_files = [f for f in zip_file.namelist() if file_matches_sigfile(f)] if len(sf_files) == 0: raise JarSignatureMissingError("No .SF file in %s" % jar_file) elif len(sf_files) > 1: if sf_name is None: msg = "Multiple .SF files in %s, but SF_NAME.SF not specified" \ % jar_file raise VerificationError(msg) elif ('META-INF/' + sf_name) in sf_files: sf_filename = 'META-INF/' + sf_name else: msg = "No .SF file in %s named META-INF/%s (found %d .SF files)" \ % (jar_file, sf_name, len(sf_files)) raise VerificationError(msg) elif len(sf_files) == 1: if sf_name is None: sf_filename = sf_files[0] elif sf_files[0] == 'META-INF/' + sf_name: sf_filename = sf_files[0] else: msg = "No .SF file in %s named META-INF/%s" % (jar_file, sf_name) raise VerificationError(msg) key_alias = sf_filename[9:-3] # "META-INF/%s.SF" sf_data = zip_file.read(sf_filename) # Step 1: check the crypto part. file_list = zip_file.namelist() sig_block_filename = None # JAR specification mentions only RSA and DSA; jarsigner also has EC # TODO: what about "SIG-*"? signature_extensions = ("RSA", "DSA", "EC") for extension in signature_extensions: candidate_filename = "META-INF/%s.%s" % (key_alias, extension) if candidate_filename in file_list: sig_block_filename = candidate_filename break if sig_block_filename is None: msg = "None of %s found in JAR" % \ ", ".join(key_alias + "." + x for x in signature_extensions) raise JarSignatureMissingError(msg) sig_block_data = zip_file.read(sig_block_filename) try: verify_signature_block(certificate, sf_data, sig_block_data) except SignatureBlockVerificationError as message: message = "Signature block verification failed: %s" % message raise SignatureBlockFileVerificationError(message) # KEYALIAS.SF is correctly signed. # Step 2: Check that it contains correct checksum of the manifest. signature_manifest = SignatureManifest() signature_manifest.parse(sf_data) jar_manifest = Manifest() jar_manifest.load_from_jar(jar_file) errors = signature_manifest.verify_manifest(jar_manifest) if len(errors) > 0: msg = "%s: in .SF file, section checksum(s) failed for: %s" \ % (jar_file, ",".join(errors)) raise ManifestChecksumError(msg) # Checksums of MANIFEST.MF itself are correct. # Step 3: Check that it contains valid checksums for each file # from the JAR. NOTE: the check is done for JAR entries. If some # JAR entries are deleted after signing, the verification still # succeeds. This seems to not follow the reference specification, # but that's what jarsigner does. errors = jar_manifest.verify_jar_checksums(jar_file) if len(errors) > 0: msg = "Checksum(s) for jar entries of jar file %s failed for: %s" \ % (jar_file, ",".join(errors)) raise JarChecksumError(msg) return None
[ "def", "verify", "(", "certificate", ",", "jar_file", ",", "sf_name", "=", "None", ")", ":", "# noqua", "# Step 0: get the \"key alias\", used also for naming of sig-related files.", "zip_file", "=", "ZipFile", "(", "jar_file", ")", "sf_files", "=", "[", "f", "for", ...
Verifies signature of a JAR file. Limitations: - diagnostic is less verbose than of jarsigner :return None if verification succeeds. :exception SignatureBlockFileVerificationError, ManifestChecksumError, JarChecksumError, JarSignatureMissingError Reference: http://docs.oracle.com/javase/7/docs/technotes/guides/jar/jar.html#Signature_Validation Note that the validation is done in three steps. Failure at any step is a failure of the whole validation.
[ "Verifies", "signature", "of", "a", "JAR", "file", "." ]
9e2332b452ddc508bed0615937dddcb2cf051557
https://github.com/obriencj/python-javatools/blob/9e2332b452ddc508bed0615937dddcb2cf051557/javatools/jarutil.py#L70-L174
train
30,358
obriencj/python-javatools
javatools/jarutil.py
cli_create_jar
def cli_create_jar(argument_list): """ A subset of "jar" command. Creating new JARs only. """ usage_message = "usage: jarutil c [OPTIONS] file.jar files..." parser = argparse.ArgumentParser(usage=usage_message) parser.add_argument("jar_file", type=str, help="The file to create") parser.add_argument("-m", "--main-class", type=str, help="Specify application entry point") args, entries = parser.parse_known_args(argument_list) create_jar(args.jar_file, entries) return 0
python
def cli_create_jar(argument_list): """ A subset of "jar" command. Creating new JARs only. """ usage_message = "usage: jarutil c [OPTIONS] file.jar files..." parser = argparse.ArgumentParser(usage=usage_message) parser.add_argument("jar_file", type=str, help="The file to create") parser.add_argument("-m", "--main-class", type=str, help="Specify application entry point") args, entries = parser.parse_known_args(argument_list) create_jar(args.jar_file, entries) return 0
[ "def", "cli_create_jar", "(", "argument_list", ")", ":", "usage_message", "=", "\"usage: jarutil c [OPTIONS] file.jar files...\"", "parser", "=", "argparse", ".", "ArgumentParser", "(", "usage", "=", "usage_message", ")", "parser", ".", "add_argument", "(", "\"jar_file\...
A subset of "jar" command. Creating new JARs only.
[ "A", "subset", "of", "jar", "command", ".", "Creating", "new", "JARs", "only", "." ]
9e2332b452ddc508bed0615937dddcb2cf051557
https://github.com/obriencj/python-javatools/blob/9e2332b452ddc508bed0615937dddcb2cf051557/javatools/jarutil.py#L243-L258
train
30,359
obriencj/python-javatools
javatools/crypto.py
create_signature_block
def create_signature_block(openssl_digest, certificate, private_key, extra_certs, data): """ Produces a signature block for the data. Reference --------- http://docs.oracle.com/javase/7/docs/technotes/guides/jar/jar.html#Digital_Signatures Note: Oracle does not specify the content of the "signature file block", friendly saying that "These are binary files not intended to be interpreted by humans". :param openssl_digest: alrogithm known to OpenSSL used to digest the data :type openssl_digest: str :param certificate: filename of the certificate file (PEM format) :type certificate: str :param private_key:filename of private key used to sign (PEM format) :type private_key: str :param extra_certs: additional certificates to embed into the signature (PEM format) :type extra_certs: array of filenames :param data: the content to be signed :type data: bytes :returns: content of the signature block file as produced by jarsigner :rtype: bytes """ # noqa smime = SMIME.SMIME() with BIO.openfile(private_key) as k, BIO.openfile(certificate) as c: smime.load_key_bio(k, c) if extra_certs is not None: # Could we use just X509.new_stack_from_der() instead? stack = X509.X509_Stack() for cert in extra_certs: stack.push(X509.load_cert(cert)) smime.set_x509_stack(stack) pkcs7 = smime.sign(BIO.MemoryBuffer(data), algo=openssl_digest, flags=(SMIME.PKCS7_BINARY | SMIME.PKCS7_DETACHED | SMIME.PKCS7_NOATTR)) tmp = BIO.MemoryBuffer() pkcs7.write_der(tmp) return tmp.read()
python
def create_signature_block(openssl_digest, certificate, private_key, extra_certs, data): """ Produces a signature block for the data. Reference --------- http://docs.oracle.com/javase/7/docs/technotes/guides/jar/jar.html#Digital_Signatures Note: Oracle does not specify the content of the "signature file block", friendly saying that "These are binary files not intended to be interpreted by humans". :param openssl_digest: alrogithm known to OpenSSL used to digest the data :type openssl_digest: str :param certificate: filename of the certificate file (PEM format) :type certificate: str :param private_key:filename of private key used to sign (PEM format) :type private_key: str :param extra_certs: additional certificates to embed into the signature (PEM format) :type extra_certs: array of filenames :param data: the content to be signed :type data: bytes :returns: content of the signature block file as produced by jarsigner :rtype: bytes """ # noqa smime = SMIME.SMIME() with BIO.openfile(private_key) as k, BIO.openfile(certificate) as c: smime.load_key_bio(k, c) if extra_certs is not None: # Could we use just X509.new_stack_from_der() instead? stack = X509.X509_Stack() for cert in extra_certs: stack.push(X509.load_cert(cert)) smime.set_x509_stack(stack) pkcs7 = smime.sign(BIO.MemoryBuffer(data), algo=openssl_digest, flags=(SMIME.PKCS7_BINARY | SMIME.PKCS7_DETACHED | SMIME.PKCS7_NOATTR)) tmp = BIO.MemoryBuffer() pkcs7.write_der(tmp) return tmp.read()
[ "def", "create_signature_block", "(", "openssl_digest", ",", "certificate", ",", "private_key", ",", "extra_certs", ",", "data", ")", ":", "# noqa", "smime", "=", "SMIME", ".", "SMIME", "(", ")", "with", "BIO", ".", "openfile", "(", "private_key", ")", "as",...
Produces a signature block for the data. Reference --------- http://docs.oracle.com/javase/7/docs/technotes/guides/jar/jar.html#Digital_Signatures Note: Oracle does not specify the content of the "signature file block", friendly saying that "These are binary files not intended to be interpreted by humans". :param openssl_digest: alrogithm known to OpenSSL used to digest the data :type openssl_digest: str :param certificate: filename of the certificate file (PEM format) :type certificate: str :param private_key:filename of private key used to sign (PEM format) :type private_key: str :param extra_certs: additional certificates to embed into the signature (PEM format) :type extra_certs: array of filenames :param data: the content to be signed :type data: bytes :returns: content of the signature block file as produced by jarsigner :rtype: bytes
[ "Produces", "a", "signature", "block", "for", "the", "data", "." ]
9e2332b452ddc508bed0615937dddcb2cf051557
https://github.com/obriencj/python-javatools/blob/9e2332b452ddc508bed0615937dddcb2cf051557/javatools/crypto.py#L66-L112
train
30,360
obriencj/python-javatools
javatools/crypto.py
verify_signature_block
def verify_signature_block(certificate_file, content, signature): """ Verifies the 'signature' over the 'content', trusting the 'certificate'. :param certificate_file: the trusted certificate (PEM format) :type certificate_file: str :param content: The signature should match this content :type content: str :param signature: data (DER format) subject to check :type signature: str :return None if the signature validates. :exception SignatureBlockVerificationError """ sig_bio = BIO.MemoryBuffer(signature) pkcs7 = SMIME.PKCS7(m2.pkcs7_read_bio_der(sig_bio._ptr()), 1) signers_cert_stack = pkcs7.get0_signers(X509.X509_Stack()) trusted_cert_store = X509.X509_Store() trusted_cert_store.set_verify_cb(ignore_missing_email_protection_eku_cb) trusted_cert_store.load_info(certificate_file) smime = SMIME.SMIME() smime.set_x509_stack(signers_cert_stack) smime.set_x509_store(trusted_cert_store) data_bio = BIO.MemoryBuffer(content) try: smime.verify(pkcs7, data_bio) except SMIME.PKCS7_Error as message: raise SignatureBlockVerificationError(message) else: return None
python
def verify_signature_block(certificate_file, content, signature): """ Verifies the 'signature' over the 'content', trusting the 'certificate'. :param certificate_file: the trusted certificate (PEM format) :type certificate_file: str :param content: The signature should match this content :type content: str :param signature: data (DER format) subject to check :type signature: str :return None if the signature validates. :exception SignatureBlockVerificationError """ sig_bio = BIO.MemoryBuffer(signature) pkcs7 = SMIME.PKCS7(m2.pkcs7_read_bio_der(sig_bio._ptr()), 1) signers_cert_stack = pkcs7.get0_signers(X509.X509_Stack()) trusted_cert_store = X509.X509_Store() trusted_cert_store.set_verify_cb(ignore_missing_email_protection_eku_cb) trusted_cert_store.load_info(certificate_file) smime = SMIME.SMIME() smime.set_x509_stack(signers_cert_stack) smime.set_x509_store(trusted_cert_store) data_bio = BIO.MemoryBuffer(content) try: smime.verify(pkcs7, data_bio) except SMIME.PKCS7_Error as message: raise SignatureBlockVerificationError(message) else: return None
[ "def", "verify_signature_block", "(", "certificate_file", ",", "content", ",", "signature", ")", ":", "sig_bio", "=", "BIO", ".", "MemoryBuffer", "(", "signature", ")", "pkcs7", "=", "SMIME", ".", "PKCS7", "(", "m2", ".", "pkcs7_read_bio_der", "(", "sig_bio", ...
Verifies the 'signature' over the 'content', trusting the 'certificate'. :param certificate_file: the trusted certificate (PEM format) :type certificate_file: str :param content: The signature should match this content :type content: str :param signature: data (DER format) subject to check :type signature: str :return None if the signature validates. :exception SignatureBlockVerificationError
[ "Verifies", "the", "signature", "over", "the", "content", "trusting", "the", "certificate", "." ]
9e2332b452ddc508bed0615937dddcb2cf051557
https://github.com/obriencj/python-javatools/blob/9e2332b452ddc508bed0615937dddcb2cf051557/javatools/crypto.py#L152-L183
train
30,361
divio/python-mautic
mautic/emails.py
Emails.send
def send(self, obj_id): """ Send email to the assigned lists :param obj_id: int :return: dict|str """ response = self._client.session.post( '{url}/{id}/send'.format( url=self.endpoint_url, id=obj_id ) ) return self.process_response(response)
python
def send(self, obj_id): """ Send email to the assigned lists :param obj_id: int :return: dict|str """ response = self._client.session.post( '{url}/{id}/send'.format( url=self.endpoint_url, id=obj_id ) ) return self.process_response(response)
[ "def", "send", "(", "self", ",", "obj_id", ")", ":", "response", "=", "self", ".", "_client", ".", "session", ".", "post", "(", "'{url}/{id}/send'", ".", "format", "(", "url", "=", "self", ".", "endpoint_url", ",", "id", "=", "obj_id", ")", ")", "ret...
Send email to the assigned lists :param obj_id: int :return: dict|str
[ "Send", "email", "to", "the", "assigned", "lists" ]
1fbff629070200002373c5e94c75e01561df418a
https://github.com/divio/python-mautic/blob/1fbff629070200002373c5e94c75e01561df418a/mautic/emails.py#L10-L22
train
30,362
divio/python-mautic
mautic/emails.py
Emails.send_to_contact
def send_to_contact(self, obj_id, contact_id): """ Send email to a specific contact :param obj_id: int :param contact_id: int :return: dict|str """ response = self._client.session.post( '{url}/{id}/send/contact/{contact_id}'.format( url=self.endpoint_url, id=obj_id, contact_id=contact_id ) ) return self.process_response(response)
python
def send_to_contact(self, obj_id, contact_id): """ Send email to a specific contact :param obj_id: int :param contact_id: int :return: dict|str """ response = self._client.session.post( '{url}/{id}/send/contact/{contact_id}'.format( url=self.endpoint_url, id=obj_id, contact_id=contact_id ) ) return self.process_response(response)
[ "def", "send_to_contact", "(", "self", ",", "obj_id", ",", "contact_id", ")", ":", "response", "=", "self", ".", "_client", ".", "session", ".", "post", "(", "'{url}/{id}/send/contact/{contact_id}'", ".", "format", "(", "url", "=", "self", ".", "endpoint_url",...
Send email to a specific contact :param obj_id: int :param contact_id: int :return: dict|str
[ "Send", "email", "to", "a", "specific", "contact" ]
1fbff629070200002373c5e94c75e01561df418a
https://github.com/divio/python-mautic/blob/1fbff629070200002373c5e94c75e01561df418a/mautic/emails.py#L24-L37
train
30,363
divio/python-mautic
mautic/contacts.py
Contacts.get_owners
def get_owners(self): """ Get a list of users available as contact owners :return: dict|str """ response = self._client.session.get( '{url}/list/owners'.format(url=self.endpoint_url) ) return self.process_response(response)
python
def get_owners(self): """ Get a list of users available as contact owners :return: dict|str """ response = self._client.session.get( '{url}/list/owners'.format(url=self.endpoint_url) ) return self.process_response(response)
[ "def", "get_owners", "(", "self", ")", ":", "response", "=", "self", ".", "_client", ".", "session", ".", "get", "(", "'{url}/list/owners'", ".", "format", "(", "url", "=", "self", ".", "endpoint_url", ")", ")", "return", "self", ".", "process_response", ...
Get a list of users available as contact owners :return: dict|str
[ "Get", "a", "list", "of", "users", "available", "as", "contact", "owners" ]
1fbff629070200002373c5e94c75e01561df418a
https://github.com/divio/python-mautic/blob/1fbff629070200002373c5e94c75e01561df418a/mautic/contacts.py#L17-L26
train
30,364
divio/python-mautic
mautic/contacts.py
Contacts.get_events
def get_events( self, obj_id, search='', include_events=None, exclude_events=None, order_by='', order_by_dir='ASC', page=1 ): """ Get a list of a contact's engagement events :param obj_id: int Contact ID :param search: str :param include_events: list|tuple :param exclude_events: list|tuple :param order_by: str :param order_by_dir: str :param page: int :return: dict|str """ if include_events is None: include_events = [] if exclude_events is None: exclude_events = [] parameters = { 'search': search, 'includeEvents': include_events, 'excludeEvents': exclude_events, 'orderBy': order_by, 'orderByDir': order_by_dir, 'page': page } response = self._client.session.get( '{url}/{id}/events'.format( url=self.endpoint_url, id=obj_id ), params=parameters ) return self.process_response(response)
python
def get_events( self, obj_id, search='', include_events=None, exclude_events=None, order_by='', order_by_dir='ASC', page=1 ): """ Get a list of a contact's engagement events :param obj_id: int Contact ID :param search: str :param include_events: list|tuple :param exclude_events: list|tuple :param order_by: str :param order_by_dir: str :param page: int :return: dict|str """ if include_events is None: include_events = [] if exclude_events is None: exclude_events = [] parameters = { 'search': search, 'includeEvents': include_events, 'excludeEvents': exclude_events, 'orderBy': order_by, 'orderByDir': order_by_dir, 'page': page } response = self._client.session.get( '{url}/{id}/events'.format( url=self.endpoint_url, id=obj_id ), params=parameters ) return self.process_response(response)
[ "def", "get_events", "(", "self", ",", "obj_id", ",", "search", "=", "''", ",", "include_events", "=", "None", ",", "exclude_events", "=", "None", ",", "order_by", "=", "''", ",", "order_by_dir", "=", "'ASC'", ",", "page", "=", "1", ")", ":", "if", "...
Get a list of a contact's engagement events :param obj_id: int Contact ID :param search: str :param include_events: list|tuple :param exclude_events: list|tuple :param order_by: str :param order_by_dir: str :param page: int :return: dict|str
[ "Get", "a", "list", "of", "a", "contact", "s", "engagement", "events" ]
1fbff629070200002373c5e94c75e01561df418a
https://github.com/divio/python-mautic/blob/1fbff629070200002373c5e94c75e01561df418a/mautic/contacts.py#L50-L91
train
30,365
divio/python-mautic
mautic/contacts.py
Contacts.get_contact_notes
def get_contact_notes( self, obj_id, search='', start=0, limit=0, order_by='', order_by_dir='ASC' ): """ Get a list of a contact's notes :param obj_id: int Contact ID :param search: str :param start: int :param limit: int :param order_by: str :param order_by_dir: str :return: dict|str """ parameters = { 'search': search, 'start': start, 'limit': limit, 'orderBy': order_by, 'orderByDir': order_by_dir, } response = self._client.session.get( '{url}/{id}/notes'.format( url=self.endpoint_url, id=obj_id ), params=parameters ) return self.process_response(response)
python
def get_contact_notes( self, obj_id, search='', start=0, limit=0, order_by='', order_by_dir='ASC' ): """ Get a list of a contact's notes :param obj_id: int Contact ID :param search: str :param start: int :param limit: int :param order_by: str :param order_by_dir: str :return: dict|str """ parameters = { 'search': search, 'start': start, 'limit': limit, 'orderBy': order_by, 'orderByDir': order_by_dir, } response = self._client.session.get( '{url}/{id}/notes'.format( url=self.endpoint_url, id=obj_id ), params=parameters ) return self.process_response(response)
[ "def", "get_contact_notes", "(", "self", ",", "obj_id", ",", "search", "=", "''", ",", "start", "=", "0", ",", "limit", "=", "0", ",", "order_by", "=", "''", ",", "order_by_dir", "=", "'ASC'", ")", ":", "parameters", "=", "{", "'search'", ":", "searc...
Get a list of a contact's notes :param obj_id: int Contact ID :param search: str :param start: int :param limit: int :param order_by: str :param order_by_dir: str :return: dict|str
[ "Get", "a", "list", "of", "a", "contact", "s", "notes" ]
1fbff629070200002373c5e94c75e01561df418a
https://github.com/divio/python-mautic/blob/1fbff629070200002373c5e94c75e01561df418a/mautic/contacts.py#L93-L127
train
30,366
divio/python-mautic
mautic/contacts.py
Contacts.add_points
def add_points(self, obj_id, points, **kwargs): """ Add the points to a contact :param obj_id: int :param points: int :param kwargs: dict 'eventname' and 'actionname' :return: dict|str """ response = self._client.session.post( '{url}/{id}/points/plus/{points}'.format( url=self.endpoint_url, id=obj_id, points=points ), data=kwargs ) return self.process_response(response)
python
def add_points(self, obj_id, points, **kwargs): """ Add the points to a contact :param obj_id: int :param points: int :param kwargs: dict 'eventname' and 'actionname' :return: dict|str """ response = self._client.session.post( '{url}/{id}/points/plus/{points}'.format( url=self.endpoint_url, id=obj_id, points=points ), data=kwargs ) return self.process_response(response)
[ "def", "add_points", "(", "self", ",", "obj_id", ",", "points", ",", "*", "*", "kwargs", ")", ":", "response", "=", "self", ".", "_client", ".", "session", ".", "post", "(", "'{url}/{id}/points/plus/{points}'", ".", "format", "(", "url", "=", "self", "."...
Add the points to a contact :param obj_id: int :param points: int :param kwargs: dict 'eventname' and 'actionname' :return: dict|str
[ "Add", "the", "points", "to", "a", "contact" ]
1fbff629070200002373c5e94c75e01561df418a
https://github.com/divio/python-mautic/blob/1fbff629070200002373c5e94c75e01561df418a/mautic/contacts.py#L159-L175
train
30,367
divio/python-mautic
mautic/contacts.py
Contacts.add_dnc
def add_dnc( self, obj_id, channel='email', reason=MANUAL, channel_id=None, comments='via API' ): """ Adds Do Not Contact :param obj_id: int :param channel: str :param reason: str :param channel_id: int :param comments: str :return: dict|str """ data = { 'reason': reason, 'channelId': channel_id, 'comments': comments } response = self._client.session.post( '{url}/{id}/dnc/add/{channel}'.format( url=self.endpoint_url, id=obj_id, channel=channel ), data=data ) return self.process_response(response)
python
def add_dnc( self, obj_id, channel='email', reason=MANUAL, channel_id=None, comments='via API' ): """ Adds Do Not Contact :param obj_id: int :param channel: str :param reason: str :param channel_id: int :param comments: str :return: dict|str """ data = { 'reason': reason, 'channelId': channel_id, 'comments': comments } response = self._client.session.post( '{url}/{id}/dnc/add/{channel}'.format( url=self.endpoint_url, id=obj_id, channel=channel ), data=data ) return self.process_response(response)
[ "def", "add_dnc", "(", "self", ",", "obj_id", ",", "channel", "=", "'email'", ",", "reason", "=", "MANUAL", ",", "channel_id", "=", "None", ",", "comments", "=", "'via API'", ")", ":", "data", "=", "{", "'reason'", ":", "reason", ",", "'channelId'", ":...
Adds Do Not Contact :param obj_id: int :param channel: str :param reason: str :param channel_id: int :param comments: str :return: dict|str
[ "Adds", "Do", "Not", "Contact" ]
1fbff629070200002373c5e94c75e01561df418a
https://github.com/divio/python-mautic/blob/1fbff629070200002373c5e94c75e01561df418a/mautic/contacts.py#L195-L224
train
30,368
divio/python-mautic
mautic/contacts.py
Contacts.remove_dnc
def remove_dnc(self, obj_id, channel): """ Removes Do Not Contact :param obj_id: int :param channel: str :return: dict|str """ response = self._client.session.post( '{url}/{id}/dnc/remove/{channel}'.format( url=self.endpoint_url, id=obj_id, channel=channel ) ) return self.process_response(response)
python
def remove_dnc(self, obj_id, channel): """ Removes Do Not Contact :param obj_id: int :param channel: str :return: dict|str """ response = self._client.session.post( '{url}/{id}/dnc/remove/{channel}'.format( url=self.endpoint_url, id=obj_id, channel=channel ) ) return self.process_response(response)
[ "def", "remove_dnc", "(", "self", ",", "obj_id", ",", "channel", ")", ":", "response", "=", "self", ".", "_client", ".", "session", ".", "post", "(", "'{url}/{id}/dnc/remove/{channel}'", ".", "format", "(", "url", "=", "self", ".", "endpoint_url", ",", "id...
Removes Do Not Contact :param obj_id: int :param channel: str :return: dict|str
[ "Removes", "Do", "Not", "Contact" ]
1fbff629070200002373c5e94c75e01561df418a
https://github.com/divio/python-mautic/blob/1fbff629070200002373c5e94c75e01561df418a/mautic/contacts.py#L226-L239
train
30,369
divio/python-mautic
mautic/api.py
API.get
def get(self, obj_id): """ Get a single item :param obj_id: int :return: dict|str """ response = self._client.session.get( '{url}/{id}'.format( url=self.endpoint_url, id=obj_id ) ) return self.process_response(response)
python
def get(self, obj_id): """ Get a single item :param obj_id: int :return: dict|str """ response = self._client.session.get( '{url}/{id}'.format( url=self.endpoint_url, id=obj_id ) ) return self.process_response(response)
[ "def", "get", "(", "self", ",", "obj_id", ")", ":", "response", "=", "self", ".", "_client", ".", "session", ".", "get", "(", "'{url}/{id}'", ".", "format", "(", "url", "=", "self", ".", "endpoint_url", ",", "id", "=", "obj_id", ")", ")", "return", ...
Get a single item :param obj_id: int :return: dict|str
[ "Get", "a", "single", "item" ]
1fbff629070200002373c5e94c75e01561df418a
https://github.com/divio/python-mautic/blob/1fbff629070200002373c5e94c75e01561df418a/mautic/api.py#L104-L116
train
30,370
divio/python-mautic
mautic/api.py
API.get_list
def get_list( self, search='', start=0, limit=0, order_by='', order_by_dir='ASC', published_only=False, minimal=False ): """ Get a list of items :param search: str :param start: int :param limit: int :param order_by: str :param order_by_dir: str :param published_only: bool :param minimal: bool :return: dict|str """ parameters = {} args = ['search', 'start', 'limit', 'minimal'] for arg in args: if arg in locals() and locals()[arg]: parameters[arg] = locals()[arg] if order_by: parameters['orderBy'] = order_by if order_by_dir: parameters['orderByDir'] = order_by_dir if published_only: parameters['publishedOnly'] = 'true' response = self._client.session.get( self.endpoint_url, params=parameters ) return self.process_response(response)
python
def get_list( self, search='', start=0, limit=0, order_by='', order_by_dir='ASC', published_only=False, minimal=False ): """ Get a list of items :param search: str :param start: int :param limit: int :param order_by: str :param order_by_dir: str :param published_only: bool :param minimal: bool :return: dict|str """ parameters = {} args = ['search', 'start', 'limit', 'minimal'] for arg in args: if arg in locals() and locals()[arg]: parameters[arg] = locals()[arg] if order_by: parameters['orderBy'] = order_by if order_by_dir: parameters['orderByDir'] = order_by_dir if published_only: parameters['publishedOnly'] = 'true' response = self._client.session.get( self.endpoint_url, params=parameters ) return self.process_response(response)
[ "def", "get_list", "(", "self", ",", "search", "=", "''", ",", "start", "=", "0", ",", "limit", "=", "0", ",", "order_by", "=", "''", ",", "order_by_dir", "=", "'ASC'", ",", "published_only", "=", "False", ",", "minimal", "=", "False", ")", ":", "p...
Get a list of items :param search: str :param start: int :param limit: int :param order_by: str :param order_by_dir: str :param published_only: bool :param minimal: bool :return: dict|str
[ "Get", "a", "list", "of", "items" ]
1fbff629070200002373c5e94c75e01561df418a
https://github.com/divio/python-mautic/blob/1fbff629070200002373c5e94c75e01561df418a/mautic/api.py#L118-L155
train
30,371
divio/python-mautic
mautic/api.py
API.edit
def edit(self, obj_id, parameters, create_if_not_exists=False): """ Edit an item with option to create if it doesn't exist :param obj_id: int :param create_if_not_exists: bool :param parameters: dict :return: dict|str """ if create_if_not_exists: response = self._client.session.put( '{url}/{id}/edit'.format( url=self.endpoint_url, id=obj_id ), data=parameters ) else: response = self._client.session.patch( '{url}/{id}/edit'.format( url=self.endpoint_url, id=obj_id ), data=parameters ) return self.process_response(response)
python
def edit(self, obj_id, parameters, create_if_not_exists=False): """ Edit an item with option to create if it doesn't exist :param obj_id: int :param create_if_not_exists: bool :param parameters: dict :return: dict|str """ if create_if_not_exists: response = self._client.session.put( '{url}/{id}/edit'.format( url=self.endpoint_url, id=obj_id ), data=parameters ) else: response = self._client.session.patch( '{url}/{id}/edit'.format( url=self.endpoint_url, id=obj_id ), data=parameters ) return self.process_response(response)
[ "def", "edit", "(", "self", ",", "obj_id", ",", "parameters", ",", "create_if_not_exists", "=", "False", ")", ":", "if", "create_if_not_exists", ":", "response", "=", "self", ".", "_client", ".", "session", ".", "put", "(", "'{url}/{id}/edit'", ".", "format"...
Edit an item with option to create if it doesn't exist :param obj_id: int :param create_if_not_exists: bool :param parameters: dict :return: dict|str
[ "Edit", "an", "item", "with", "option", "to", "create", "if", "it", "doesn", "t", "exist" ]
1fbff629070200002373c5e94c75e01561df418a
https://github.com/divio/python-mautic/blob/1fbff629070200002373c5e94c75e01561df418a/mautic/api.py#L190-L213
train
30,372
divio/python-mautic
mautic/stats.py
Stats.get
def get(self, table='', start=0, limit=0, order=None, where=None): """ Get a list of stat items :param table: str database table name :param start: int :param limit: int :param order: list|tuple :param where: list|tuple :return: """ parameters = {} args = ['start', 'limit', 'order', 'where'] for arg in args: if arg in locals() and locals()[arg]: parameters[arg] = locals()[arg] response = self._client.session.get( '{url}/{table}'.format( url=self.endpoint_url, table=table ), params=parameters ) return self.process_response(response)
python
def get(self, table='', start=0, limit=0, order=None, where=None): """ Get a list of stat items :param table: str database table name :param start: int :param limit: int :param order: list|tuple :param where: list|tuple :return: """ parameters = {} args = ['start', 'limit', 'order', 'where'] for arg in args: if arg in locals() and locals()[arg]: parameters[arg] = locals()[arg] response = self._client.session.get( '{url}/{table}'.format( url=self.endpoint_url, table=table ), params=parameters ) return self.process_response(response)
[ "def", "get", "(", "self", ",", "table", "=", "''", ",", "start", "=", "0", ",", "limit", "=", "0", ",", "order", "=", "None", ",", "where", "=", "None", ")", ":", "parameters", "=", "{", "}", "args", "=", "[", "'start'", ",", "'limit'", ",", ...
Get a list of stat items :param table: str database table name :param start: int :param limit: int :param order: list|tuple :param where: list|tuple :return:
[ "Get", "a", "list", "of", "stat", "items" ]
1fbff629070200002373c5e94c75e01561df418a
https://github.com/divio/python-mautic/blob/1fbff629070200002373c5e94c75e01561df418a/mautic/stats.py#L10-L34
train
30,373
divio/python-mautic
mautic/segments.py
Segments.add_contact
def add_contact(self, segment_id, contact_id): """ Add a contact to the segment :param segment_id: int Segment ID :param contact_id: int Contact ID :return: dict|str """ response = self._client.session.post( '{url}/{segment_id}/contact/add/{contact_id}'.format( url=self.endpoint_url, segment_id=segment_id, contact_id=contact_id ) ) return self.process_response(response)
python
def add_contact(self, segment_id, contact_id): """ Add a contact to the segment :param segment_id: int Segment ID :param contact_id: int Contact ID :return: dict|str """ response = self._client.session.post( '{url}/{segment_id}/contact/add/{contact_id}'.format( url=self.endpoint_url, segment_id=segment_id, contact_id=contact_id ) ) return self.process_response(response)
[ "def", "add_contact", "(", "self", ",", "segment_id", ",", "contact_id", ")", ":", "response", "=", "self", ".", "_client", ".", "session", ".", "post", "(", "'{url}/{segment_id}/contact/add/{contact_id}'", ".", "format", "(", "url", "=", "self", ".", "endpoin...
Add a contact to the segment :param segment_id: int Segment ID :param contact_id: int Contact ID :return: dict|str
[ "Add", "a", "contact", "to", "the", "segment" ]
1fbff629070200002373c5e94c75e01561df418a
https://github.com/divio/python-mautic/blob/1fbff629070200002373c5e94c75e01561df418a/mautic/segments.py#L10-L26
train
30,374
divio/python-mautic
mautic/users.py
Users.check_permission
def check_permission(self, obj_id, permissions): """ Get list of permissions for a user :param obj_id: int :param permissions: str|list|tuple :return: dict|str """ response = self._client.session.post( '{url}/{id}/permissioncheck'.format( url=self.endpoint_url, id=obj_id ), data={'permissions': permissions} ) return self.process_response(response)
python
def check_permission(self, obj_id, permissions): """ Get list of permissions for a user :param obj_id: int :param permissions: str|list|tuple :return: dict|str """ response = self._client.session.post( '{url}/{id}/permissioncheck'.format( url=self.endpoint_url, id=obj_id ), data={'permissions': permissions} ) return self.process_response(response)
[ "def", "check_permission", "(", "self", ",", "obj_id", ",", "permissions", ")", ":", "response", "=", "self", ".", "_client", ".", "session", ".", "post", "(", "'{url}/{id}/permissioncheck'", ".", "format", "(", "url", "=", "self", ".", "endpoint_url", ",", ...
Get list of permissions for a user :param obj_id: int :param permissions: str|list|tuple :return: dict|str
[ "Get", "list", "of", "permissions", "for", "a", "user" ]
1fbff629070200002373c5e94c75e01561df418a
https://github.com/divio/python-mautic/blob/1fbff629070200002373c5e94c75e01561df418a/mautic/users.py#L21-L35
train
30,375
divio/python-mautic
mautic/point_triggers.py
PointTriggers.delete_trigger_events
def delete_trigger_events(self, trigger_id, event_ids): """ Remove events from a point trigger :param trigger_id: int :param event_ids: list|tuple :return: dict|str """ response = self._client.session.delete( '{url}/{trigger_id}/events/delete'.format( url=self.endpoint_url, trigger_id=trigger_id ), params={'events': event_ids} ) return self.process_response(response)
python
def delete_trigger_events(self, trigger_id, event_ids): """ Remove events from a point trigger :param trigger_id: int :param event_ids: list|tuple :return: dict|str """ response = self._client.session.delete( '{url}/{trigger_id}/events/delete'.format( url=self.endpoint_url, trigger_id=trigger_id ), params={'events': event_ids} ) return self.process_response(response)
[ "def", "delete_trigger_events", "(", "self", ",", "trigger_id", ",", "event_ids", ")", ":", "response", "=", "self", ".", "_client", ".", "session", ".", "delete", "(", "'{url}/{trigger_id}/events/delete'", ".", "format", "(", "url", "=", "self", ".", "endpoin...
Remove events from a point trigger :param trigger_id: int :param event_ids: list|tuple :return: dict|str
[ "Remove", "events", "from", "a", "point", "trigger" ]
1fbff629070200002373c5e94c75e01561df418a
https://github.com/divio/python-mautic/blob/1fbff629070200002373c5e94c75e01561df418a/mautic/point_triggers.py#L10-L25
train
30,376
divio/python-mautic
mautic/forms.py
Forms.delete_fields
def delete_fields(self, form_id, field_ids): """ Remove fields from a form :param form_id: int :param field_ids: list|tuple :return: dict|str """ response = self._client.session.delete( '{url}/{form_id}/fields/delete'.format( url=self.endpoint_url, form_id=form_id ), params={'fields': field_ids} ) return self.process_response(response)
python
def delete_fields(self, form_id, field_ids): """ Remove fields from a form :param form_id: int :param field_ids: list|tuple :return: dict|str """ response = self._client.session.delete( '{url}/{form_id}/fields/delete'.format( url=self.endpoint_url, form_id=form_id ), params={'fields': field_ids} ) return self.process_response(response)
[ "def", "delete_fields", "(", "self", ",", "form_id", ",", "field_ids", ")", ":", "response", "=", "self", ".", "_client", ".", "session", ".", "delete", "(", "'{url}/{form_id}/fields/delete'", ".", "format", "(", "url", "=", "self", ".", "endpoint_url", ",",...
Remove fields from a form :param form_id: int :param field_ids: list|tuple :return: dict|str
[ "Remove", "fields", "from", "a", "form" ]
1fbff629070200002373c5e94c75e01561df418a
https://github.com/divio/python-mautic/blob/1fbff629070200002373c5e94c75e01561df418a/mautic/forms.py#L10-L25
train
30,377
divio/python-mautic
mautic/forms.py
Forms.delete_actions
def delete_actions(self, form_id, action_ids): """ Remove actions from a form :param form_id: int :param action_ids: list|tuple :return: dict|str """ response = self._client.session.delete( '{url}/{form_id}/actions/delete'.format( url=self.endpoint_url, form_id=form_id ), params={'actions': action_ids} ) return self.process_response(response)
python
def delete_actions(self, form_id, action_ids): """ Remove actions from a form :param form_id: int :param action_ids: list|tuple :return: dict|str """ response = self._client.session.delete( '{url}/{form_id}/actions/delete'.format( url=self.endpoint_url, form_id=form_id ), params={'actions': action_ids} ) return self.process_response(response)
[ "def", "delete_actions", "(", "self", ",", "form_id", ",", "action_ids", ")", ":", "response", "=", "self", ".", "_client", ".", "session", ".", "delete", "(", "'{url}/{form_id}/actions/delete'", ".", "format", "(", "url", "=", "self", ".", "endpoint_url", "...
Remove actions from a form :param form_id: int :param action_ids: list|tuple :return: dict|str
[ "Remove", "actions", "from", "a", "form" ]
1fbff629070200002373c5e94c75e01561df418a
https://github.com/divio/python-mautic/blob/1fbff629070200002373c5e94c75e01561df418a/mautic/forms.py#L27-L42
train
30,378
divio/python-mautic
mautic/utils.py
update_token_tempfile
def update_token_tempfile(token): """ Example of function for token update """ with open(tmp, 'w') as f: f.write(json.dumps(token, indent=4))
python
def update_token_tempfile(token): """ Example of function for token update """ with open(tmp, 'w') as f: f.write(json.dumps(token, indent=4))
[ "def", "update_token_tempfile", "(", "token", ")", ":", "with", "open", "(", "tmp", ",", "'w'", ")", "as", "f", ":", "f", ".", "write", "(", "json", ".", "dumps", "(", "token", ",", "indent", "=", "4", ")", ")" ]
Example of function for token update
[ "Example", "of", "function", "for", "token", "update" ]
1fbff629070200002373c5e94c75e01561df418a
https://github.com/divio/python-mautic/blob/1fbff629070200002373c5e94c75e01561df418a/mautic/utils.py#L20-L25
train
30,379
divio/python-mautic
mautic/files.py
Files.set_folder
def set_folder(self, folder='assets'): """ Changes the file folder to look at :param folder: str [images, assets] :return: None """ folder = folder.replace('/', '.') self._endpoint = 'files/{folder}'.format(folder=folder)
python
def set_folder(self, folder='assets'): """ Changes the file folder to look at :param folder: str [images, assets] :return: None """ folder = folder.replace('/', '.') self._endpoint = 'files/{folder}'.format(folder=folder)
[ "def", "set_folder", "(", "self", ",", "folder", "=", "'assets'", ")", ":", "folder", "=", "folder", ".", "replace", "(", "'/'", ",", "'.'", ")", "self", ".", "_endpoint", "=", "'files/{folder}'", ".", "format", "(", "folder", "=", "folder", ")" ]
Changes the file folder to look at :param folder: str [images, assets] :return: None
[ "Changes", "the", "file", "folder", "to", "look", "at" ]
1fbff629070200002373c5e94c75e01561df418a
https://github.com/divio/python-mautic/blob/1fbff629070200002373c5e94c75e01561df418a/mautic/files.py#L10-L18
train
30,380
peterwittek/somoclu
src/Python/somoclu/train.py
_check_cooling_parameters
def _check_cooling_parameters(radiuscooling, scalecooling): """Helper function to verify the cooling parameters of the training. """ if radiuscooling != "linear" and radiuscooling != "exponential": raise Exception("Invalid parameter for radiuscooling: " + radiuscooling) if scalecooling != "linear" and scalecooling != "exponential": raise Exception("Invalid parameter for scalecooling: " + scalecooling)
python
def _check_cooling_parameters(radiuscooling, scalecooling): """Helper function to verify the cooling parameters of the training. """ if radiuscooling != "linear" and radiuscooling != "exponential": raise Exception("Invalid parameter for radiuscooling: " + radiuscooling) if scalecooling != "linear" and scalecooling != "exponential": raise Exception("Invalid parameter for scalecooling: " + scalecooling)
[ "def", "_check_cooling_parameters", "(", "radiuscooling", ",", "scalecooling", ")", ":", "if", "radiuscooling", "!=", "\"linear\"", "and", "radiuscooling", "!=", "\"exponential\"", ":", "raise", "Exception", "(", "\"Invalid parameter for radiuscooling: \"", "+", "radiusco...
Helper function to verify the cooling parameters of the training.
[ "Helper", "function", "to", "verify", "the", "cooling", "parameters", "of", "the", "training", "." ]
b31dfbeba6765e64aedddcf8259626d6684f5349
https://github.com/peterwittek/somoclu/blob/b31dfbeba6765e64aedddcf8259626d6684f5349/src/Python/somoclu/train.py#L663-L671
train
30,381
peterwittek/somoclu
src/Python/somoclu/train.py
_hexplot
def _hexplot(matrix, fig, colormap): """Internal function to plot a hexagonal map. """ umatrix_min = matrix.min() umatrix_max = matrix.max() n_rows, n_columns = matrix.shape cmap = plt.get_cmap(colormap) offsets = np.zeros((n_columns * n_rows, 2)) facecolors = [] for row in range(n_rows): for col in range(n_columns): if row % 2 == 0: offsets[row * n_columns + col] = [col + 0.5, 2 * n_rows - 2 * row] facecolors.append(cmap((matrix[row, col] - umatrix_min) / (umatrix_max) * 255)) else: offsets[row * n_columns + col] = [col, 2 * n_rows - 2 * row] facecolors.append(cmap((matrix[row, col] - umatrix_min) / (umatrix_max) * 255)) polygon = np.zeros((6, 2), float) polygon[:, 0] = 1.1 * np.array([0.5, 0.5, 0.0, -0.5, -0.5, 0.0]) polygon[:, 1] = 1.1 * np.array([-np.sqrt(3) / 6, np.sqrt(3) / 6, np.sqrt(3) / 2 + np.sqrt(3) / 6, np.sqrt(3) / 6, -np.sqrt(3) / 6, -np.sqrt(3) / 2 - np.sqrt(3) / 6]) polygons = np.expand_dims(polygon, 0) + np.expand_dims(offsets, 1) ax = fig.gca() collection = mcoll.PolyCollection( polygons, offsets=offsets, facecolors=facecolors, edgecolors=facecolors, linewidths=1.0, offset_position="data") ax.add_collection(collection, autolim=False) corners = ((-0.5, -0.5), (n_columns + 0.5, 2 * n_rows + 0.5)) ax.update_datalim(corners) ax.autoscale_view(tight=True) return offsets
python
def _hexplot(matrix, fig, colormap): """Internal function to plot a hexagonal map. """ umatrix_min = matrix.min() umatrix_max = matrix.max() n_rows, n_columns = matrix.shape cmap = plt.get_cmap(colormap) offsets = np.zeros((n_columns * n_rows, 2)) facecolors = [] for row in range(n_rows): for col in range(n_columns): if row % 2 == 0: offsets[row * n_columns + col] = [col + 0.5, 2 * n_rows - 2 * row] facecolors.append(cmap((matrix[row, col] - umatrix_min) / (umatrix_max) * 255)) else: offsets[row * n_columns + col] = [col, 2 * n_rows - 2 * row] facecolors.append(cmap((matrix[row, col] - umatrix_min) / (umatrix_max) * 255)) polygon = np.zeros((6, 2), float) polygon[:, 0] = 1.1 * np.array([0.5, 0.5, 0.0, -0.5, -0.5, 0.0]) polygon[:, 1] = 1.1 * np.array([-np.sqrt(3) / 6, np.sqrt(3) / 6, np.sqrt(3) / 2 + np.sqrt(3) / 6, np.sqrt(3) / 6, -np.sqrt(3) / 6, -np.sqrt(3) / 2 - np.sqrt(3) / 6]) polygons = np.expand_dims(polygon, 0) + np.expand_dims(offsets, 1) ax = fig.gca() collection = mcoll.PolyCollection( polygons, offsets=offsets, facecolors=facecolors, edgecolors=facecolors, linewidths=1.0, offset_position="data") ax.add_collection(collection, autolim=False) corners = ((-0.5, -0.5), (n_columns + 0.5, 2 * n_rows + 0.5)) ax.update_datalim(corners) ax.autoscale_view(tight=True) return offsets
[ "def", "_hexplot", "(", "matrix", ",", "fig", ",", "colormap", ")", ":", "umatrix_min", "=", "matrix", ".", "min", "(", ")", "umatrix_max", "=", "matrix", ".", "max", "(", ")", "n_rows", ",", "n_columns", "=", "matrix", ".", "shape", "cmap", "=", "pl...
Internal function to plot a hexagonal map.
[ "Internal", "function", "to", "plot", "a", "hexagonal", "map", "." ]
b31dfbeba6765e64aedddcf8259626d6684f5349
https://github.com/peterwittek/somoclu/blob/b31dfbeba6765e64aedddcf8259626d6684f5349/src/Python/somoclu/train.py#L674-L713
train
30,382
peterwittek/somoclu
src/Python/somoclu/train.py
Somoclu.load_bmus
def load_bmus(self, filename): """Load the best matching units from a file to the Somoclu object. :param filename: The name of the file. :type filename: str. """ self.bmus = np.loadtxt(filename, comments='%', usecols=(1, 2)) if self.n_vectors != 0 and len(self.bmus) != self.n_vectors: raise Exception("The number of best matching units does not match " "the number of data instances") else: self.n_vectors = len(self.bmus) tmp = self.bmus[:, 0].copy() self.bmus[:, 0] = self.bmus[:, 1].copy() self.bmus[:, 1] = tmp if max(self.bmus[:, 0]) > self._n_columns - 1 or \ max(self.bmus[:, 1]) > self._n_rows - 1: raise Exception("The dimensions of the best matching units do not " "match that of the map")
python
def load_bmus(self, filename): """Load the best matching units from a file to the Somoclu object. :param filename: The name of the file. :type filename: str. """ self.bmus = np.loadtxt(filename, comments='%', usecols=(1, 2)) if self.n_vectors != 0 and len(self.bmus) != self.n_vectors: raise Exception("The number of best matching units does not match " "the number of data instances") else: self.n_vectors = len(self.bmus) tmp = self.bmus[:, 0].copy() self.bmus[:, 0] = self.bmus[:, 1].copy() self.bmus[:, 1] = tmp if max(self.bmus[:, 0]) > self._n_columns - 1 or \ max(self.bmus[:, 1]) > self._n_rows - 1: raise Exception("The dimensions of the best matching units do not " "match that of the map")
[ "def", "load_bmus", "(", "self", ",", "filename", ")", ":", "self", ".", "bmus", "=", "np", ".", "loadtxt", "(", "filename", ",", "comments", "=", "'%'", ",", "usecols", "=", "(", "1", ",", "2", ")", ")", "if", "self", ".", "n_vectors", "!=", "0"...
Load the best matching units from a file to the Somoclu object. :param filename: The name of the file. :type filename: str.
[ "Load", "the", "best", "matching", "units", "from", "a", "file", "to", "the", "Somoclu", "object", "." ]
b31dfbeba6765e64aedddcf8259626d6684f5349
https://github.com/peterwittek/somoclu/blob/b31dfbeba6765e64aedddcf8259626d6684f5349/src/Python/somoclu/train.py#L136-L154
train
30,383
peterwittek/somoclu
src/Python/somoclu/train.py
Somoclu.load_umatrix
def load_umatrix(self, filename): """Load the umatrix from a file to the Somoclu object. :param filename: The name of the file. :type filename: str. """ self.umatrix = np.loadtxt(filename, comments='%') if self.umatrix.shape != (self._n_rows, self._n_columns): raise Exception("The dimensions of the U-matrix do not " "match that of the map")
python
def load_umatrix(self, filename): """Load the umatrix from a file to the Somoclu object. :param filename: The name of the file. :type filename: str. """ self.umatrix = np.loadtxt(filename, comments='%') if self.umatrix.shape != (self._n_rows, self._n_columns): raise Exception("The dimensions of the U-matrix do not " "match that of the map")
[ "def", "load_umatrix", "(", "self", ",", "filename", ")", ":", "self", ".", "umatrix", "=", "np", ".", "loadtxt", "(", "filename", ",", "comments", "=", "'%'", ")", "if", "self", ".", "umatrix", ".", "shape", "!=", "(", "self", ".", "_n_rows", ",", ...
Load the umatrix from a file to the Somoclu object. :param filename: The name of the file. :type filename: str.
[ "Load", "the", "umatrix", "from", "a", "file", "to", "the", "Somoclu", "object", "." ]
b31dfbeba6765e64aedddcf8259626d6684f5349
https://github.com/peterwittek/somoclu/blob/b31dfbeba6765e64aedddcf8259626d6684f5349/src/Python/somoclu/train.py#L156-L166
train
30,384
peterwittek/somoclu
src/Python/somoclu/train.py
Somoclu.load_codebook
def load_codebook(self, filename): """Load the codebook from a file to the Somoclu object. :param filename: The name of the file. :type filename: str. """ self.codebook = np.loadtxt(filename, comments='%') if self.n_dim == 0: self.n_dim = self.codebook.shape[1] if self.codebook.shape != (self._n_rows * self._n_columns, self.n_dim): raise Exception("The dimensions of the codebook do not " "match that of the map") self.codebook.shape = (self._n_rows, self._n_columns, self.n_dim)
python
def load_codebook(self, filename): """Load the codebook from a file to the Somoclu object. :param filename: The name of the file. :type filename: str. """ self.codebook = np.loadtxt(filename, comments='%') if self.n_dim == 0: self.n_dim = self.codebook.shape[1] if self.codebook.shape != (self._n_rows * self._n_columns, self.n_dim): raise Exception("The dimensions of the codebook do not " "match that of the map") self.codebook.shape = (self._n_rows, self._n_columns, self.n_dim)
[ "def", "load_codebook", "(", "self", ",", "filename", ")", ":", "self", ".", "codebook", "=", "np", ".", "loadtxt", "(", "filename", ",", "comments", "=", "'%'", ")", "if", "self", ".", "n_dim", "==", "0", ":", "self", ".", "n_dim", "=", "self", "....
Load the codebook from a file to the Somoclu object. :param filename: The name of the file. :type filename: str.
[ "Load", "the", "codebook", "from", "a", "file", "to", "the", "Somoclu", "object", "." ]
b31dfbeba6765e64aedddcf8259626d6684f5349
https://github.com/peterwittek/somoclu/blob/b31dfbeba6765e64aedddcf8259626d6684f5349/src/Python/somoclu/train.py#L168-L181
train
30,385
peterwittek/somoclu
src/Python/somoclu/train.py
Somoclu.update_data
def update_data(self, data): """Change the data set in the Somoclu object. It is useful when the data is updated and the training should continue on the new data. :param data: The training data. :type data: 2D numpy.array of float32. """ oldn_dim = self.n_dim if data.dtype != np.float32: print("Warning: data was not float32. A 32-bit copy was made") self._data = np.float32(data) else: self._data = data self.n_vectors, self.n_dim = data.shape if self.n_dim != oldn_dim and oldn_dim != 0: raise Exception("The dimension of the new data does not match!") self.bmus = np.zeros(self.n_vectors * 2, dtype=np.intc)
python
def update_data(self, data): """Change the data set in the Somoclu object. It is useful when the data is updated and the training should continue on the new data. :param data: The training data. :type data: 2D numpy.array of float32. """ oldn_dim = self.n_dim if data.dtype != np.float32: print("Warning: data was not float32. A 32-bit copy was made") self._data = np.float32(data) else: self._data = data self.n_vectors, self.n_dim = data.shape if self.n_dim != oldn_dim and oldn_dim != 0: raise Exception("The dimension of the new data does not match!") self.bmus = np.zeros(self.n_vectors * 2, dtype=np.intc)
[ "def", "update_data", "(", "self", ",", "data", ")", ":", "oldn_dim", "=", "self", ".", "n_dim", "if", "data", ".", "dtype", "!=", "np", ".", "float32", ":", "print", "(", "\"Warning: data was not float32. A 32-bit copy was made\"", ")", "self", ".", "_data", ...
Change the data set in the Somoclu object. It is useful when the data is updated and the training should continue on the new data. :param data: The training data. :type data: 2D numpy.array of float32.
[ "Change", "the", "data", "set", "in", "the", "Somoclu", "object", ".", "It", "is", "useful", "when", "the", "data", "is", "updated", "and", "the", "training", "should", "continue", "on", "the", "new", "data", "." ]
b31dfbeba6765e64aedddcf8259626d6684f5349
https://github.com/peterwittek/somoclu/blob/b31dfbeba6765e64aedddcf8259626d6684f5349/src/Python/somoclu/train.py#L233-L249
train
30,386
peterwittek/somoclu
src/Python/somoclu/train.py
Somoclu.view_component_planes
def view_component_planes(self, dimensions=None, figsize=None, colormap=cm.Spectral_r, colorbar=False, bestmatches=False, bestmatchcolors=None, labels=None, zoom=None, filename=None): """Observe the component planes in the codebook of the SOM. :param dimensions: Optional parameter to specify along which dimension or dimensions should the plotting happen. By default, each dimension is plotted in a sequence of plots. :type dimension: int or list of int. :param figsize: Optional parameter to specify the size of the figure. :type figsize: (int, int) :param colormap: Optional parameter to specify the color map to be used. :type colormap: matplotlib.colors.Colormap :param colorbar: Optional parameter to include a colormap as legend. :type colorbar: bool. :param bestmatches: Optional parameter to plot best matching units. :type bestmatches: bool. :param bestmatchcolors: Optional parameter to specify the color of each best matching unit. :type bestmatchcolors: list of int. :param labels: Optional parameter to specify the label of each point. :type labels: list of str. :param zoom: Optional parameter to zoom into a region on the map. The first two coordinates of the tuple are the row limits, the second tuple contains the column limits. :type zoom: ((int, int), (int, int)) :param filename: If specified, the plot will not be shown but saved to this file. :type filename: str. """ if self.codebook is None: raise Exception("The codebook is not available. Either train a map" " or load a codebook from a file") if dimensions is None: dimensions = range(self.n_dim) for i in dimensions: plt = self._view_matrix(self.codebook[:, :, i], figsize, colormap, colorbar, bestmatches, bestmatchcolors, labels, zoom, filename) return plt
python
def view_component_planes(self, dimensions=None, figsize=None, colormap=cm.Spectral_r, colorbar=False, bestmatches=False, bestmatchcolors=None, labels=None, zoom=None, filename=None): """Observe the component planes in the codebook of the SOM. :param dimensions: Optional parameter to specify along which dimension or dimensions should the plotting happen. By default, each dimension is plotted in a sequence of plots. :type dimension: int or list of int. :param figsize: Optional parameter to specify the size of the figure. :type figsize: (int, int) :param colormap: Optional parameter to specify the color map to be used. :type colormap: matplotlib.colors.Colormap :param colorbar: Optional parameter to include a colormap as legend. :type colorbar: bool. :param bestmatches: Optional parameter to plot best matching units. :type bestmatches: bool. :param bestmatchcolors: Optional parameter to specify the color of each best matching unit. :type bestmatchcolors: list of int. :param labels: Optional parameter to specify the label of each point. :type labels: list of str. :param zoom: Optional parameter to zoom into a region on the map. The first two coordinates of the tuple are the row limits, the second tuple contains the column limits. :type zoom: ((int, int), (int, int)) :param filename: If specified, the plot will not be shown but saved to this file. :type filename: str. """ if self.codebook is None: raise Exception("The codebook is not available. Either train a map" " or load a codebook from a file") if dimensions is None: dimensions = range(self.n_dim) for i in dimensions: plt = self._view_matrix(self.codebook[:, :, i], figsize, colormap, colorbar, bestmatches, bestmatchcolors, labels, zoom, filename) return plt
[ "def", "view_component_planes", "(", "self", ",", "dimensions", "=", "None", ",", "figsize", "=", "None", ",", "colormap", "=", "cm", ".", "Spectral_r", ",", "colorbar", "=", "False", ",", "bestmatches", "=", "False", ",", "bestmatchcolors", "=", "None", "...
Observe the component planes in the codebook of the SOM. :param dimensions: Optional parameter to specify along which dimension or dimensions should the plotting happen. By default, each dimension is plotted in a sequence of plots. :type dimension: int or list of int. :param figsize: Optional parameter to specify the size of the figure. :type figsize: (int, int) :param colormap: Optional parameter to specify the color map to be used. :type colormap: matplotlib.colors.Colormap :param colorbar: Optional parameter to include a colormap as legend. :type colorbar: bool. :param bestmatches: Optional parameter to plot best matching units. :type bestmatches: bool. :param bestmatchcolors: Optional parameter to specify the color of each best matching unit. :type bestmatchcolors: list of int. :param labels: Optional parameter to specify the label of each point. :type labels: list of str. :param zoom: Optional parameter to zoom into a region on the map. The first two coordinates of the tuple are the row limits, the second tuple contains the column limits. :type zoom: ((int, int), (int, int)) :param filename: If specified, the plot will not be shown but saved to this file. :type filename: str.
[ "Observe", "the", "component", "planes", "in", "the", "codebook", "of", "the", "SOM", "." ]
b31dfbeba6765e64aedddcf8259626d6684f5349
https://github.com/peterwittek/somoclu/blob/b31dfbeba6765e64aedddcf8259626d6684f5349/src/Python/somoclu/train.py#L251-L293
train
30,387
peterwittek/somoclu
src/Python/somoclu/train.py
Somoclu.view_umatrix
def view_umatrix(self, figsize=None, colormap=cm.Spectral_r, colorbar=False, bestmatches=False, bestmatchcolors=None, labels=None, zoom=None, filename=None): """Plot the U-matrix of the trained map. :param figsize: Optional parameter to specify the size of the figure. :type figsize: (int, int) :param colormap: Optional parameter to specify the color map to be used. :type colormap: matplotlib.colors.Colormap :param colorbar: Optional parameter to include a colormap as legend. :type colorbar: bool. :param bestmatches: Optional parameter to plot best matching units. :type bestmatches: bool. :param bestmatchcolors: Optional parameter to specify the color of each best matching unit. :type bestmatchcolors: list of int. :param labels: Optional parameter to specify the label of each point. :type labels: list of str. :param zoom: Optional parameter to zoom into a region on the map. The first two coordinates of the tuple are the row limits, the second tuple contains the column limits. :type zoom: ((int, int), (int, int)) :param filename: If specified, the plot will not be shown but saved to this file. :type filename: str. """ if self.umatrix is None: raise Exception("The U-matrix is not available. Either train a map" " or load a U-matrix from a file") return self._view_matrix(self.umatrix, figsize, colormap, colorbar, bestmatches, bestmatchcolors, labels, zoom, filename)
python
def view_umatrix(self, figsize=None, colormap=cm.Spectral_r, colorbar=False, bestmatches=False, bestmatchcolors=None, labels=None, zoom=None, filename=None): """Plot the U-matrix of the trained map. :param figsize: Optional parameter to specify the size of the figure. :type figsize: (int, int) :param colormap: Optional parameter to specify the color map to be used. :type colormap: matplotlib.colors.Colormap :param colorbar: Optional parameter to include a colormap as legend. :type colorbar: bool. :param bestmatches: Optional parameter to plot best matching units. :type bestmatches: bool. :param bestmatchcolors: Optional parameter to specify the color of each best matching unit. :type bestmatchcolors: list of int. :param labels: Optional parameter to specify the label of each point. :type labels: list of str. :param zoom: Optional parameter to zoom into a region on the map. The first two coordinates of the tuple are the row limits, the second tuple contains the column limits. :type zoom: ((int, int), (int, int)) :param filename: If specified, the plot will not be shown but saved to this file. :type filename: str. """ if self.umatrix is None: raise Exception("The U-matrix is not available. Either train a map" " or load a U-matrix from a file") return self._view_matrix(self.umatrix, figsize, colormap, colorbar, bestmatches, bestmatchcolors, labels, zoom, filename)
[ "def", "view_umatrix", "(", "self", ",", "figsize", "=", "None", ",", "colormap", "=", "cm", ".", "Spectral_r", ",", "colorbar", "=", "False", ",", "bestmatches", "=", "False", ",", "bestmatchcolors", "=", "None", ",", "labels", "=", "None", ",", "zoom",...
Plot the U-matrix of the trained map. :param figsize: Optional parameter to specify the size of the figure. :type figsize: (int, int) :param colormap: Optional parameter to specify the color map to be used. :type colormap: matplotlib.colors.Colormap :param colorbar: Optional parameter to include a colormap as legend. :type colorbar: bool. :param bestmatches: Optional parameter to plot best matching units. :type bestmatches: bool. :param bestmatchcolors: Optional parameter to specify the color of each best matching unit. :type bestmatchcolors: list of int. :param labels: Optional parameter to specify the label of each point. :type labels: list of str. :param zoom: Optional parameter to zoom into a region on the map. The first two coordinates of the tuple are the row limits, the second tuple contains the column limits. :type zoom: ((int, int), (int, int)) :param filename: If specified, the plot will not be shown but saved to this file. :type filename: str.
[ "Plot", "the", "U", "-", "matrix", "of", "the", "trained", "map", "." ]
b31dfbeba6765e64aedddcf8259626d6684f5349
https://github.com/peterwittek/somoclu/blob/b31dfbeba6765e64aedddcf8259626d6684f5349/src/Python/somoclu/train.py#L295-L327
train
30,388
peterwittek/somoclu
src/Python/somoclu/train.py
Somoclu.view_activation_map
def view_activation_map(self, data_vector=None, data_index=None, activation_map=None, figsize=None, colormap=cm.Spectral_r, colorbar=False, bestmatches=False, bestmatchcolors=None, labels=None, zoom=None, filename=None): """Plot the activation map of a given data instance or a new data vector :param data_vector: Optional parameter for a new vector :type data_vector: numpy.array :param data_index: Optional parameter for the index of the data instance :type data_index: int. :param activation_map: Optional parameter to pass the an activation map :type activation_map: numpy.array :param figsize: Optional parameter to specify the size of the figure. :type figsize: (int, int) :param colormap: Optional parameter to specify the color map to be used. :type colormap: matplotlib.colors.Colormap :param colorbar: Optional parameter to include a colormap as legend. :type colorbar: bool. :param bestmatches: Optional parameter to plot best matching units. :type bestmatches: bool. :param bestmatchcolors: Optional parameter to specify the color of each best matching unit. :type bestmatchcolors: list of int. :param labels: Optional parameter to specify the label of each point. :type labels: list of str. :param zoom: Optional parameter to zoom into a region on the map. The first two coordinates of the tuple are the row limits, the second tuple contains the column limits. :type zoom: ((int, int), (int, int)) :param filename: If specified, the plot will not be shown but saved to this file. :type filename: str. """ if data_vector is None and data_index is None: raise Exception("Either specify a vector to see its activation " "or give an index of the training data instances") if data_vector is not None and data_index is not None: raise Exception("You cannot specify both a data vector and the " "index of a training data instance") if data_vector is not None and activation_map is not None: raise Exception("You cannot pass a previously computated" "activation map with a data vector") if data_vector is not None: try: d1, _ = data_vector.shape w = data_vector.copy() except ValueError: d1, _ = data_vector.shape w = data_vector.reshape(1, d1) if w.shape[1] == 1: w = w.T matrix = cdist(self.codebook.reshape((self.codebook.shape[0] * self.codebook.shape[1], self.codebook.shape[2])), w, 'euclidean').T matrix.shape = (self.codebook.shape[0], self.codebook.shape[1]) else: if activation_map is None and self.activation_map is None: self.get_surface_state() if activation_map is None: activation_map = self.activation_map matrix = activation_map[data_index].reshape((self.codebook.shape[0], self.codebook.shape[1])) return self._view_matrix(matrix, figsize, colormap, colorbar, bestmatches, bestmatchcolors, labels, zoom, filename)
python
def view_activation_map(self, data_vector=None, data_index=None, activation_map=None, figsize=None, colormap=cm.Spectral_r, colorbar=False, bestmatches=False, bestmatchcolors=None, labels=None, zoom=None, filename=None): """Plot the activation map of a given data instance or a new data vector :param data_vector: Optional parameter for a new vector :type data_vector: numpy.array :param data_index: Optional parameter for the index of the data instance :type data_index: int. :param activation_map: Optional parameter to pass the an activation map :type activation_map: numpy.array :param figsize: Optional parameter to specify the size of the figure. :type figsize: (int, int) :param colormap: Optional parameter to specify the color map to be used. :type colormap: matplotlib.colors.Colormap :param colorbar: Optional parameter to include a colormap as legend. :type colorbar: bool. :param bestmatches: Optional parameter to plot best matching units. :type bestmatches: bool. :param bestmatchcolors: Optional parameter to specify the color of each best matching unit. :type bestmatchcolors: list of int. :param labels: Optional parameter to specify the label of each point. :type labels: list of str. :param zoom: Optional parameter to zoom into a region on the map. The first two coordinates of the tuple are the row limits, the second tuple contains the column limits. :type zoom: ((int, int), (int, int)) :param filename: If specified, the plot will not be shown but saved to this file. :type filename: str. """ if data_vector is None and data_index is None: raise Exception("Either specify a vector to see its activation " "or give an index of the training data instances") if data_vector is not None and data_index is not None: raise Exception("You cannot specify both a data vector and the " "index of a training data instance") if data_vector is not None and activation_map is not None: raise Exception("You cannot pass a previously computated" "activation map with a data vector") if data_vector is not None: try: d1, _ = data_vector.shape w = data_vector.copy() except ValueError: d1, _ = data_vector.shape w = data_vector.reshape(1, d1) if w.shape[1] == 1: w = w.T matrix = cdist(self.codebook.reshape((self.codebook.shape[0] * self.codebook.shape[1], self.codebook.shape[2])), w, 'euclidean').T matrix.shape = (self.codebook.shape[0], self.codebook.shape[1]) else: if activation_map is None and self.activation_map is None: self.get_surface_state() if activation_map is None: activation_map = self.activation_map matrix = activation_map[data_index].reshape((self.codebook.shape[0], self.codebook.shape[1])) return self._view_matrix(matrix, figsize, colormap, colorbar, bestmatches, bestmatchcolors, labels, zoom, filename)
[ "def", "view_activation_map", "(", "self", ",", "data_vector", "=", "None", ",", "data_index", "=", "None", ",", "activation_map", "=", "None", ",", "figsize", "=", "None", ",", "colormap", "=", "cm", ".", "Spectral_r", ",", "colorbar", "=", "False", ",", ...
Plot the activation map of a given data instance or a new data vector :param data_vector: Optional parameter for a new vector :type data_vector: numpy.array :param data_index: Optional parameter for the index of the data instance :type data_index: int. :param activation_map: Optional parameter to pass the an activation map :type activation_map: numpy.array :param figsize: Optional parameter to specify the size of the figure. :type figsize: (int, int) :param colormap: Optional parameter to specify the color map to be used. :type colormap: matplotlib.colors.Colormap :param colorbar: Optional parameter to include a colormap as legend. :type colorbar: bool. :param bestmatches: Optional parameter to plot best matching units. :type bestmatches: bool. :param bestmatchcolors: Optional parameter to specify the color of each best matching unit. :type bestmatchcolors: list of int. :param labels: Optional parameter to specify the label of each point. :type labels: list of str. :param zoom: Optional parameter to zoom into a region on the map. The first two coordinates of the tuple are the row limits, the second tuple contains the column limits. :type zoom: ((int, int), (int, int)) :param filename: If specified, the plot will not be shown but saved to this file. :type filename: str.
[ "Plot", "the", "activation", "map", "of", "a", "given", "data", "instance", "or", "a", "new", "data", "vector" ]
b31dfbeba6765e64aedddcf8259626d6684f5349
https://github.com/peterwittek/somoclu/blob/b31dfbeba6765e64aedddcf8259626d6684f5349/src/Python/somoclu/train.py#L329-L397
train
30,389
peterwittek/somoclu
src/Python/somoclu/train.py
Somoclu._check_parameters
def _check_parameters(self): """Internal function to verify the basic parameters of the SOM. """ if self._map_type != "planar" and self._map_type != "toroid": raise Exception("Invalid parameter for _map_type: " + self._map_type) if self._grid_type != "rectangular" and self._grid_type != "hexagonal": raise Exception("Invalid parameter for _grid_type: " + self._grid_type) if self._neighborhood != "gaussian" and self._neighborhood != "bubble": raise Exception("Invalid parameter for neighborhood: " + self._neighborhood) if self._kernel_type != 0 and self._kernel_type != 1: raise Exception("Invalid parameter for kernelTye: " + self._kernel_type) if self._verbose < 0 and self._verbose > 2: raise Exception("Invalid parameter for verbose: " + self._kernel_type)
python
def _check_parameters(self): """Internal function to verify the basic parameters of the SOM. """ if self._map_type != "planar" and self._map_type != "toroid": raise Exception("Invalid parameter for _map_type: " + self._map_type) if self._grid_type != "rectangular" and self._grid_type != "hexagonal": raise Exception("Invalid parameter for _grid_type: " + self._grid_type) if self._neighborhood != "gaussian" and self._neighborhood != "bubble": raise Exception("Invalid parameter for neighborhood: " + self._neighborhood) if self._kernel_type != 0 and self._kernel_type != 1: raise Exception("Invalid parameter for kernelTye: " + self._kernel_type) if self._verbose < 0 and self._verbose > 2: raise Exception("Invalid parameter for verbose: " + self._kernel_type)
[ "def", "_check_parameters", "(", "self", ")", ":", "if", "self", ".", "_map_type", "!=", "\"planar\"", "and", "self", ".", "_map_type", "!=", "\"toroid\"", ":", "raise", "Exception", "(", "\"Invalid parameter for _map_type: \"", "+", "self", ".", "_map_type", ")...
Internal function to verify the basic parameters of the SOM.
[ "Internal", "function", "to", "verify", "the", "basic", "parameters", "of", "the", "SOM", "." ]
b31dfbeba6765e64aedddcf8259626d6684f5349
https://github.com/peterwittek/somoclu/blob/b31dfbeba6765e64aedddcf8259626d6684f5349/src/Python/somoclu/train.py#L466-L483
train
30,390
peterwittek/somoclu
src/Python/somoclu/train.py
Somoclu._init_codebook
def _init_codebook(self): """Internal function to set the codebook or to indicate it to the C++ code that it should be randomly initialized. """ codebook_size = self._n_columns * self._n_rows * self.n_dim if self.codebook is None: if self._initialization == "random": self.codebook = np.zeros(codebook_size, dtype=np.float32) self.codebook[0:2] = [1000, 2000] else: self._pca_init() elif self.codebook.size != codebook_size: raise Exception("Invalid size for initial codebook") else: if self.codebook.dtype != np.float32: print("Warning: initialcodebook was not float32. A 32-bit " "copy was made") self.codebook = np.float32(self.codebook) self.codebook.shape = (codebook_size, )
python
def _init_codebook(self): """Internal function to set the codebook or to indicate it to the C++ code that it should be randomly initialized. """ codebook_size = self._n_columns * self._n_rows * self.n_dim if self.codebook is None: if self._initialization == "random": self.codebook = np.zeros(codebook_size, dtype=np.float32) self.codebook[0:2] = [1000, 2000] else: self._pca_init() elif self.codebook.size != codebook_size: raise Exception("Invalid size for initial codebook") else: if self.codebook.dtype != np.float32: print("Warning: initialcodebook was not float32. A 32-bit " "copy was made") self.codebook = np.float32(self.codebook) self.codebook.shape = (codebook_size, )
[ "def", "_init_codebook", "(", "self", ")", ":", "codebook_size", "=", "self", ".", "_n_columns", "*", "self", ".", "_n_rows", "*", "self", ".", "n_dim", "if", "self", ".", "codebook", "is", "None", ":", "if", "self", ".", "_initialization", "==", "\"rand...
Internal function to set the codebook or to indicate it to the C++ code that it should be randomly initialized.
[ "Internal", "function", "to", "set", "the", "codebook", "or", "to", "indicate", "it", "to", "the", "C", "++", "code", "that", "it", "should", "be", "randomly", "initialized", "." ]
b31dfbeba6765e64aedddcf8259626d6684f5349
https://github.com/peterwittek/somoclu/blob/b31dfbeba6765e64aedddcf8259626d6684f5349/src/Python/somoclu/train.py#L511-L529
train
30,391
peterwittek/somoclu
src/Python/somoclu/train.py
Somoclu.cluster
def cluster(self, algorithm=None): """Cluster the codebook. The clusters of the data instances can be assigned based on the BMUs. The method populates the class variable Somoclu.clusters. If viewing methods are called after clustering, but without colors for best matching units, colors will be automatically assigned based on cluster membership. :param algorithm: Optional parameter to specify a scikit-learn clustering algorithm. The default is K-means with eight clusters. :type filename: sklearn.base.ClusterMixin. """ import sklearn.base if algorithm is None: import sklearn.cluster algorithm = sklearn.cluster.KMeans() elif not isinstance(algorithm, sklearn.base.ClusterMixin): raise Exception("Cannot use algorithm of type " + type(algorithm)) original_shape = self.codebook.shape self.codebook.shape = (self._n_columns * self._n_rows, self.n_dim) linear_clusters = algorithm.fit_predict(self.codebook) self.codebook.shape = original_shape self.clusters = np.zeros((self._n_rows, self._n_columns), dtype=int) for i, c in enumerate(linear_clusters): self.clusters[i // self._n_columns, i % self._n_columns] = c
python
def cluster(self, algorithm=None): """Cluster the codebook. The clusters of the data instances can be assigned based on the BMUs. The method populates the class variable Somoclu.clusters. If viewing methods are called after clustering, but without colors for best matching units, colors will be automatically assigned based on cluster membership. :param algorithm: Optional parameter to specify a scikit-learn clustering algorithm. The default is K-means with eight clusters. :type filename: sklearn.base.ClusterMixin. """ import sklearn.base if algorithm is None: import sklearn.cluster algorithm = sklearn.cluster.KMeans() elif not isinstance(algorithm, sklearn.base.ClusterMixin): raise Exception("Cannot use algorithm of type " + type(algorithm)) original_shape = self.codebook.shape self.codebook.shape = (self._n_columns * self._n_rows, self.n_dim) linear_clusters = algorithm.fit_predict(self.codebook) self.codebook.shape = original_shape self.clusters = np.zeros((self._n_rows, self._n_columns), dtype=int) for i, c in enumerate(linear_clusters): self.clusters[i // self._n_columns, i % self._n_columns] = c
[ "def", "cluster", "(", "self", ",", "algorithm", "=", "None", ")", ":", "import", "sklearn", ".", "base", "if", "algorithm", "is", "None", ":", "import", "sklearn", ".", "cluster", "algorithm", "=", "sklearn", ".", "cluster", ".", "KMeans", "(", ")", "...
Cluster the codebook. The clusters of the data instances can be assigned based on the BMUs. The method populates the class variable Somoclu.clusters. If viewing methods are called after clustering, but without colors for best matching units, colors will be automatically assigned based on cluster membership. :param algorithm: Optional parameter to specify a scikit-learn clustering algorithm. The default is K-means with eight clusters. :type filename: sklearn.base.ClusterMixin.
[ "Cluster", "the", "codebook", ".", "The", "clusters", "of", "the", "data", "instances", "can", "be", "assigned", "based", "on", "the", "BMUs", ".", "The", "method", "populates", "the", "class", "variable", "Somoclu", ".", "clusters", ".", "If", "viewing", ...
b31dfbeba6765e64aedddcf8259626d6684f5349
https://github.com/peterwittek/somoclu/blob/b31dfbeba6765e64aedddcf8259626d6684f5349/src/Python/somoclu/train.py#L531-L556
train
30,392
peterwittek/somoclu
src/Python/somoclu/train.py
Somoclu.get_surface_state
def get_surface_state(self, data=None): """Return the Euclidean distance between codebook and data. :param data: Optional parameter to specify data, otherwise the data used previously to train the SOM is used. :type data: 2D numpy.array of float32. :returns: The the dot product of the codebook and the data. :rtype: 2D numpy.array """ if data is None: d = self._data else: d = data codebookReshaped = self.codebook.reshape(self.codebook.shape[0] * self.codebook.shape[1], self.codebook.shape[2]) parts = np.array_split(d, 200, axis=0) am = np.empty((0, (self._n_columns * self._n_rows)), dtype="float64") for part in parts: am = np.concatenate((am, (cdist((part), codebookReshaped, 'euclidean'))), axis=0) if data is None: self.activation_map = am return am
python
def get_surface_state(self, data=None): """Return the Euclidean distance between codebook and data. :param data: Optional parameter to specify data, otherwise the data used previously to train the SOM is used. :type data: 2D numpy.array of float32. :returns: The the dot product of the codebook and the data. :rtype: 2D numpy.array """ if data is None: d = self._data else: d = data codebookReshaped = self.codebook.reshape(self.codebook.shape[0] * self.codebook.shape[1], self.codebook.shape[2]) parts = np.array_split(d, 200, axis=0) am = np.empty((0, (self._n_columns * self._n_rows)), dtype="float64") for part in parts: am = np.concatenate((am, (cdist((part), codebookReshaped, 'euclidean'))), axis=0) if data is None: self.activation_map = am return am
[ "def", "get_surface_state", "(", "self", ",", "data", "=", "None", ")", ":", "if", "data", "is", "None", ":", "d", "=", "self", ".", "_data", "else", ":", "d", "=", "data", "codebookReshaped", "=", "self", ".", "codebook", ".", "reshape", "(", "self"...
Return the Euclidean distance between codebook and data. :param data: Optional parameter to specify data, otherwise the data used previously to train the SOM is used. :type data: 2D numpy.array of float32. :returns: The the dot product of the codebook and the data. :rtype: 2D numpy.array
[ "Return", "the", "Euclidean", "distance", "between", "codebook", "and", "data", "." ]
b31dfbeba6765e64aedddcf8259626d6684f5349
https://github.com/peterwittek/somoclu/blob/b31dfbeba6765e64aedddcf8259626d6684f5349/src/Python/somoclu/train.py#L558-L582
train
30,393
peterwittek/somoclu
src/Python/somoclu/train.py
Somoclu.get_bmus
def get_bmus(self, activation_map): """Returns Best Matching Units indexes of the activation map. :param activation_map: Activation map computed with self.get_surface_state() :type activation_map: 2D numpy.array :returns: The bmus indexes corresponding to this activation map (same as self.bmus for the training samples). :rtype: 2D numpy.array """ Y, X = np.unravel_index(activation_map.argmin(axis=1), (self._n_rows, self._n_columns)) return np.vstack((X, Y)).T
python
def get_bmus(self, activation_map): """Returns Best Matching Units indexes of the activation map. :param activation_map: Activation map computed with self.get_surface_state() :type activation_map: 2D numpy.array :returns: The bmus indexes corresponding to this activation map (same as self.bmus for the training samples). :rtype: 2D numpy.array """ Y, X = np.unravel_index(activation_map.argmin(axis=1), (self._n_rows, self._n_columns)) return np.vstack((X, Y)).T
[ "def", "get_bmus", "(", "self", ",", "activation_map", ")", ":", "Y", ",", "X", "=", "np", ".", "unravel_index", "(", "activation_map", ".", "argmin", "(", "axis", "=", "1", ")", ",", "(", "self", ".", "_n_rows", ",", "self", ".", "_n_columns", ")", ...
Returns Best Matching Units indexes of the activation map. :param activation_map: Activation map computed with self.get_surface_state() :type activation_map: 2D numpy.array :returns: The bmus indexes corresponding to this activation map (same as self.bmus for the training samples). :rtype: 2D numpy.array
[ "Returns", "Best", "Matching", "Units", "indexes", "of", "the", "activation", "map", "." ]
b31dfbeba6765e64aedddcf8259626d6684f5349
https://github.com/peterwittek/somoclu/blob/b31dfbeba6765e64aedddcf8259626d6684f5349/src/Python/somoclu/train.py#L584-L597
train
30,394
peterwittek/somoclu
src/Python/somoclu/train.py
Somoclu.view_similarity_matrix
def view_similarity_matrix(self, data=None, labels=None, figsize=None, filename=None): """Plot the similarity map according to the activation map :param data: Optional parameter for data points to calculate the similarity with :type data: numpy.array :param figsize: Optional parameter to specify the size of the figure. :type figsize: (int, int) :param labels: Optional parameter to specify the label of each point. :type labels: list of str. :param filename: If specified, the plot will not be shown but saved to this file. :type filename: str. """ if not have_heatmap: raise Exception("Import dependencies missing for viewing " "similarity matrix. You must have seaborn and " "scikit-learn") if data is None and self.activation_map is None: self.get_surface_state() if data is None: X = self.activation_map else: X = data # Calculate the pairwise correlations as a metric for similarity corrmat = 1 - pairwise_distances(X, metric="correlation") # Set up the matplotlib figure if figsize is None: figsize = (12, 9) f, ax = plt.subplots(figsize=figsize) # Y axis has inverted labels (seaborn default, no idea why) if labels is None: xticklabels = [] yticklabels = [] else: xticklabels = labels yticklabels = labels # Draw the heatmap using seaborn sns.heatmap(corrmat, vmax=1, vmin=-1, square=True, xticklabels=xticklabels, yticklabels=yticklabels, cmap="RdBu_r", center=0) f.tight_layout() # This sets the ticks to a readable angle plt.yticks(rotation=0) plt.xticks(rotation=90) # This sets the labels for the two axes ax.set_yticklabels(yticklabels, ha='right', va='center', size=8) ax.set_xticklabels(xticklabels, ha='center', va='top', size=8) # Save and close the figure if filename is not None: plt.savefig(filename, bbox_inches='tight') else: plt.show() return plt
python
def view_similarity_matrix(self, data=None, labels=None, figsize=None, filename=None): """Plot the similarity map according to the activation map :param data: Optional parameter for data points to calculate the similarity with :type data: numpy.array :param figsize: Optional parameter to specify the size of the figure. :type figsize: (int, int) :param labels: Optional parameter to specify the label of each point. :type labels: list of str. :param filename: If specified, the plot will not be shown but saved to this file. :type filename: str. """ if not have_heatmap: raise Exception("Import dependencies missing for viewing " "similarity matrix. You must have seaborn and " "scikit-learn") if data is None and self.activation_map is None: self.get_surface_state() if data is None: X = self.activation_map else: X = data # Calculate the pairwise correlations as a metric for similarity corrmat = 1 - pairwise_distances(X, metric="correlation") # Set up the matplotlib figure if figsize is None: figsize = (12, 9) f, ax = plt.subplots(figsize=figsize) # Y axis has inverted labels (seaborn default, no idea why) if labels is None: xticklabels = [] yticklabels = [] else: xticklabels = labels yticklabels = labels # Draw the heatmap using seaborn sns.heatmap(corrmat, vmax=1, vmin=-1, square=True, xticklabels=xticklabels, yticklabels=yticklabels, cmap="RdBu_r", center=0) f.tight_layout() # This sets the ticks to a readable angle plt.yticks(rotation=0) plt.xticks(rotation=90) # This sets the labels for the two axes ax.set_yticklabels(yticklabels, ha='right', va='center', size=8) ax.set_xticklabels(xticklabels, ha='center', va='top', size=8) # Save and close the figure if filename is not None: plt.savefig(filename, bbox_inches='tight') else: plt.show() return plt
[ "def", "view_similarity_matrix", "(", "self", ",", "data", "=", "None", ",", "labels", "=", "None", ",", "figsize", "=", "None", ",", "filename", "=", "None", ")", ":", "if", "not", "have_heatmap", ":", "raise", "Exception", "(", "\"Import dependencies missi...
Plot the similarity map according to the activation map :param data: Optional parameter for data points to calculate the similarity with :type data: numpy.array :param figsize: Optional parameter to specify the size of the figure. :type figsize: (int, int) :param labels: Optional parameter to specify the label of each point. :type labels: list of str. :param filename: If specified, the plot will not be shown but saved to this file. :type filename: str.
[ "Plot", "the", "similarity", "map", "according", "to", "the", "activation", "map" ]
b31dfbeba6765e64aedddcf8259626d6684f5349
https://github.com/peterwittek/somoclu/blob/b31dfbeba6765e64aedddcf8259626d6684f5349/src/Python/somoclu/train.py#L599-L660
train
30,395
cwaldbieser/jhub_cas_authenticator
jhub_cas_authenticator/cas_auth.py
find_child_element
def find_child_element(elm, child_local_name): """ Find an XML child element by local tag name. """ for n in range(len(elm)): child_elm = elm[n] tag = etree.QName(child_elm) if tag.localname == child_local_name: return child_elm return None
python
def find_child_element(elm, child_local_name): """ Find an XML child element by local tag name. """ for n in range(len(elm)): child_elm = elm[n] tag = etree.QName(child_elm) if tag.localname == child_local_name: return child_elm return None
[ "def", "find_child_element", "(", "elm", ",", "child_local_name", ")", ":", "for", "n", "in", "range", "(", "len", "(", "elm", ")", ")", ":", "child_elm", "=", "elm", "[", "n", "]", "tag", "=", "etree", ".", "QName", "(", "child_elm", ")", "if", "t...
Find an XML child element by local tag name.
[ "Find", "an", "XML", "child", "element", "by", "local", "tag", "name", "." ]
b483ac85d16dad2532ef76846268c5660ddd5611
https://github.com/cwaldbieser/jhub_cas_authenticator/blob/b483ac85d16dad2532ef76846268c5660ddd5611/jhub_cas_authenticator/cas_auth.py#L239-L248
train
30,396
cwaldbieser/jhub_cas_authenticator
jhub_cas_authenticator/cas_auth.py
CASLoginHandler.make_service_url
def make_service_url(self): """ Make the service URL CAS will use to redirect the browser back to this service. """ cas_service_url = self.authenticator.cas_service_url if cas_service_url is None: cas_service_url = self.request.protocol + "://" + self.request.host + self.request.uri return cas_service_url
python
def make_service_url(self): """ Make the service URL CAS will use to redirect the browser back to this service. """ cas_service_url = self.authenticator.cas_service_url if cas_service_url is None: cas_service_url = self.request.protocol + "://" + self.request.host + self.request.uri return cas_service_url
[ "def", "make_service_url", "(", "self", ")", ":", "cas_service_url", "=", "self", ".", "authenticator", ".", "cas_service_url", "if", "cas_service_url", "is", "None", ":", "cas_service_url", "=", "self", ".", "request", ".", "protocol", "+", "\"://\"", "+", "s...
Make the service URL CAS will use to redirect the browser back to this service.
[ "Make", "the", "service", "URL", "CAS", "will", "use", "to", "redirect", "the", "browser", "back", "to", "this", "service", "." ]
b483ac85d16dad2532ef76846268c5660ddd5611
https://github.com/cwaldbieser/jhub_cas_authenticator/blob/b483ac85d16dad2532ef76846268c5660ddd5611/jhub_cas_authenticator/cas_auth.py#L97-L104
train
30,397
cwaldbieser/jhub_cas_authenticator
jhub_cas_authenticator/cas_auth.py
CASLoginHandler.validate_service_ticket
def validate_service_ticket(self, ticket): """ Validate a CAS service ticket. Returns (is_valid, user, attribs). `is_valid` - boolean `attribs` - set of attribute-value tuples. """ app_log = logging.getLogger("tornado.application") http_client = AsyncHTTPClient() service = self.make_service_url() qs_dict = dict(service=service, ticket=ticket) qs = urllib.parse.urlencode(qs_dict) cas_validate_url = self.authenticator.cas_service_validate_url + "?" + qs response = None app_log.debug("Validate URL: {0}".format(cas_validate_url)) try: response = yield http_client.fetch( cas_validate_url, method="GET", ca_certs=self.authenticator.cas_client_ca_certs) app_log.debug("Response was successful: {0}".format(response)) except HTTPError as ex: app_log.debug("Response was unsuccessful: {0}".format(response)) return (False, None, None) parser = etree.XMLParser() root = etree.fromstring(response.body, parser=parser) auth_result_elm = root[0] is_success = (etree.QName(auth_result_elm).localname == 'authenticationSuccess') if not is_success: return (False, None, None) user_elm = find_child_element(auth_result_elm, "user") user = user_elm.text.lower() attrib_results = set([]) attribs = find_child_element(auth_result_elm, "attributes") if attribs is None: attribs = [] for attrib in attribs: name = etree.QName(attrib).localname value = attrib.text attrib_results.add((name, value)) return (True, user, attrib_results)
python
def validate_service_ticket(self, ticket): """ Validate a CAS service ticket. Returns (is_valid, user, attribs). `is_valid` - boolean `attribs` - set of attribute-value tuples. """ app_log = logging.getLogger("tornado.application") http_client = AsyncHTTPClient() service = self.make_service_url() qs_dict = dict(service=service, ticket=ticket) qs = urllib.parse.urlencode(qs_dict) cas_validate_url = self.authenticator.cas_service_validate_url + "?" + qs response = None app_log.debug("Validate URL: {0}".format(cas_validate_url)) try: response = yield http_client.fetch( cas_validate_url, method="GET", ca_certs=self.authenticator.cas_client_ca_certs) app_log.debug("Response was successful: {0}".format(response)) except HTTPError as ex: app_log.debug("Response was unsuccessful: {0}".format(response)) return (False, None, None) parser = etree.XMLParser() root = etree.fromstring(response.body, parser=parser) auth_result_elm = root[0] is_success = (etree.QName(auth_result_elm).localname == 'authenticationSuccess') if not is_success: return (False, None, None) user_elm = find_child_element(auth_result_elm, "user") user = user_elm.text.lower() attrib_results = set([]) attribs = find_child_element(auth_result_elm, "attributes") if attribs is None: attribs = [] for attrib in attribs: name = etree.QName(attrib).localname value = attrib.text attrib_results.add((name, value)) return (True, user, attrib_results)
[ "def", "validate_service_ticket", "(", "self", ",", "ticket", ")", ":", "app_log", "=", "logging", ".", "getLogger", "(", "\"tornado.application\"", ")", "http_client", "=", "AsyncHTTPClient", "(", ")", "service", "=", "self", ".", "make_service_url", "(", ")", ...
Validate a CAS service ticket. Returns (is_valid, user, attribs). `is_valid` - boolean `attribs` - set of attribute-value tuples.
[ "Validate", "a", "CAS", "service", "ticket", "." ]
b483ac85d16dad2532ef76846268c5660ddd5611
https://github.com/cwaldbieser/jhub_cas_authenticator/blob/b483ac85d16dad2532ef76846268c5660ddd5611/jhub_cas_authenticator/cas_auth.py#L107-L148
train
30,398
openstack/monasca-persister
monasca_persister/persister.py
clean_exit
def clean_exit(signum, frame=None): """Exit all processes attempting to finish uncommitted active work before exit. Can be called on an os signal or no zookeeper losing connection. """ global exiting if exiting: # Since this is set up as a handler for SIGCHLD when this kills one # child it gets another signal, the global exiting avoids this running # multiple times. LOG.debug('Exit in progress clean_exit received additional signal %s' % signum) return LOG.info('Received signal %s, beginning graceful shutdown.' % signum) exiting = True wait_for_exit = False for process in processors: try: if process.is_alive(): # Sends sigterm which any processes after a notification is sent attempt to handle process.terminate() wait_for_exit = True except Exception: # nosec # There is really nothing to do if the kill fails, so just go on. # The # nosec keeps bandit from reporting this as a security issue pass # wait for a couple seconds to give the subprocesses a chance to shut down correctly. if wait_for_exit: time.sleep(2) # Kill everything, that didn't already die for child in multiprocessing.active_children(): LOG.debug('Killing pid %s' % child.pid) try: os.kill(child.pid, signal.SIGKILL) except Exception: # nosec # There is really nothing to do if the kill fails, so just go on. # The # nosec keeps bandit from reporting this as a security issue pass if signum == signal.SIGTERM: sys.exit(0) sys.exit(signum)
python
def clean_exit(signum, frame=None): """Exit all processes attempting to finish uncommitted active work before exit. Can be called on an os signal or no zookeeper losing connection. """ global exiting if exiting: # Since this is set up as a handler for SIGCHLD when this kills one # child it gets another signal, the global exiting avoids this running # multiple times. LOG.debug('Exit in progress clean_exit received additional signal %s' % signum) return LOG.info('Received signal %s, beginning graceful shutdown.' % signum) exiting = True wait_for_exit = False for process in processors: try: if process.is_alive(): # Sends sigterm which any processes after a notification is sent attempt to handle process.terminate() wait_for_exit = True except Exception: # nosec # There is really nothing to do if the kill fails, so just go on. # The # nosec keeps bandit from reporting this as a security issue pass # wait for a couple seconds to give the subprocesses a chance to shut down correctly. if wait_for_exit: time.sleep(2) # Kill everything, that didn't already die for child in multiprocessing.active_children(): LOG.debug('Killing pid %s' % child.pid) try: os.kill(child.pid, signal.SIGKILL) except Exception: # nosec # There is really nothing to do if the kill fails, so just go on. # The # nosec keeps bandit from reporting this as a security issue pass if signum == signal.SIGTERM: sys.exit(0) sys.exit(signum)
[ "def", "clean_exit", "(", "signum", ",", "frame", "=", "None", ")", ":", "global", "exiting", "if", "exiting", ":", "# Since this is set up as a handler for SIGCHLD when this kills one", "# child it gets another signal, the global exiting avoids this running", "# multiple times.", ...
Exit all processes attempting to finish uncommitted active work before exit. Can be called on an os signal or no zookeeper losing connection.
[ "Exit", "all", "processes", "attempting", "to", "finish", "uncommitted", "active", "work", "before", "exit", ".", "Can", "be", "called", "on", "an", "os", "signal", "or", "no", "zookeeper", "losing", "connection", "." ]
dcfdb5c7840cd1203dd98b95cdad32ec9569445e
https://github.com/openstack/monasca-persister/blob/dcfdb5c7840cd1203dd98b95cdad32ec9569445e/monasca_persister/persister.py#L45-L89
train
30,399