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
gccxml/pygccxml
pygccxml/declarations/container_traits.py
container_traits_impl_t.key_type
def key_type(self, type_): """returns reference to the class key type declaration""" if not self.is_mapping(type_): raise TypeError( 'Type "%s" is not "mapping" container' % str(type_)) return self.__find_xxx_type( type_, self.key_type_index, self.key_type_typedef, 'container_key_type')
python
def key_type(self, type_): """returns reference to the class key type declaration""" if not self.is_mapping(type_): raise TypeError( 'Type "%s" is not "mapping" container' % str(type_)) return self.__find_xxx_type( type_, self.key_type_index, self.key_type_typedef, 'container_key_type')
[ "def", "key_type", "(", "self", ",", "type_", ")", ":", "if", "not", "self", ".", "is_mapping", "(", "type_", ")", ":", "raise", "TypeError", "(", "'Type \"%s\" is not \"mapping\" container'", "%", "str", "(", "type_", ")", ")", "return", "self", ".", "__find_xxx_type", "(", "type_", ",", "self", ".", "key_type_index", ",", "self", ".", "key_type_typedef", ",", "'container_key_type'", ")" ]
returns reference to the class key type declaration
[ "returns", "reference", "to", "the", "class", "key", "type", "declaration" ]
2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e
https://github.com/gccxml/pygccxml/blob/2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e/pygccxml/declarations/container_traits.py#L496-L506
train
236,100
gccxml/pygccxml
pygccxml/declarations/container_traits.py
container_traits_impl_t.remove_defaults
def remove_defaults(self, type_or_string): """ Removes template defaults from a templated class instantiation. For example: .. code-block:: c++ std::vector< int, std::allocator< int > > will become: .. code-block:: c++ std::vector< int > """ name = type_or_string if not utils.is_str(type_or_string): name = self.class_declaration(type_or_string).name if not self.remove_defaults_impl: return name no_defaults = self.remove_defaults_impl(name) if not no_defaults: return name return no_defaults
python
def remove_defaults(self, type_or_string): """ Removes template defaults from a templated class instantiation. For example: .. code-block:: c++ std::vector< int, std::allocator< int > > will become: .. code-block:: c++ std::vector< int > """ name = type_or_string if not utils.is_str(type_or_string): name = self.class_declaration(type_or_string).name if not self.remove_defaults_impl: return name no_defaults = self.remove_defaults_impl(name) if not no_defaults: return name return no_defaults
[ "def", "remove_defaults", "(", "self", ",", "type_or_string", ")", ":", "name", "=", "type_or_string", "if", "not", "utils", ".", "is_str", "(", "type_or_string", ")", ":", "name", "=", "self", ".", "class_declaration", "(", "type_or_string", ")", ".", "name", "if", "not", "self", ".", "remove_defaults_impl", ":", "return", "name", "no_defaults", "=", "self", ".", "remove_defaults_impl", "(", "name", ")", "if", "not", "no_defaults", ":", "return", "name", "return", "no_defaults" ]
Removes template defaults from a templated class instantiation. For example: .. code-block:: c++ std::vector< int, std::allocator< int > > will become: .. code-block:: c++ std::vector< int >
[ "Removes", "template", "defaults", "from", "a", "templated", "class", "instantiation", "." ]
2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e
https://github.com/gccxml/pygccxml/blob/2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e/pygccxml/declarations/container_traits.py#L508-L532
train
236,101
gccxml/pygccxml
pygccxml/declarations/namespace.py
namespace_t.take_parenting
def take_parenting(self, inst): """ Takes parenting from inst and transfers it to self. Args: inst (namespace_t): a namespace declaration """ if self is inst: return for decl in inst.declarations: decl.parent = self self.declarations.append(decl) inst.declarations = []
python
def take_parenting(self, inst): """ Takes parenting from inst and transfers it to self. Args: inst (namespace_t): a namespace declaration """ if self is inst: return for decl in inst.declarations: decl.parent = self self.declarations.append(decl) inst.declarations = []
[ "def", "take_parenting", "(", "self", ",", "inst", ")", ":", "if", "self", "is", "inst", ":", "return", "for", "decl", "in", "inst", ".", "declarations", ":", "decl", ".", "parent", "=", "self", "self", ".", "declarations", ".", "append", "(", "decl", ")", "inst", ".", "declarations", "=", "[", "]" ]
Takes parenting from inst and transfers it to self. Args: inst (namespace_t): a namespace declaration
[ "Takes", "parenting", "from", "inst", "and", "transfers", "it", "to", "self", "." ]
2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e
https://github.com/gccxml/pygccxml/blob/2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e/pygccxml/declarations/namespace.py#L73-L87
train
236,102
gccxml/pygccxml
pygccxml/declarations/namespace.py
namespace_t.remove_declaration
def remove_declaration(self, decl): """ Removes declaration from members list. :param decl: declaration to be removed :type decl: :class:`declaration_t` """ del self.declarations[self.declarations.index(decl)] decl.cache.reset()
python
def remove_declaration(self, decl): """ Removes declaration from members list. :param decl: declaration to be removed :type decl: :class:`declaration_t` """ del self.declarations[self.declarations.index(decl)] decl.cache.reset()
[ "def", "remove_declaration", "(", "self", ",", "decl", ")", ":", "del", "self", ".", "declarations", "[", "self", ".", "declarations", ".", "index", "(", "decl", ")", "]", "decl", ".", "cache", ".", "reset", "(", ")" ]
Removes declaration from members list. :param decl: declaration to be removed :type decl: :class:`declaration_t`
[ "Removes", "declaration", "from", "members", "list", "." ]
2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e
https://github.com/gccxml/pygccxml/blob/2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e/pygccxml/declarations/namespace.py#L94-L104
train
236,103
gccxml/pygccxml
pygccxml/declarations/namespace.py
namespace_t.namespace
def namespace(self, name=None, function=None, recursive=None): """ Returns reference to namespace declaration that matches a defined criteria. """ return ( self._find_single( scopedef.scopedef_t._impl_matchers[namespace_t.namespace], name=name, function=function, recursive=recursive) )
python
def namespace(self, name=None, function=None, recursive=None): """ Returns reference to namespace declaration that matches a defined criteria. """ return ( self._find_single( scopedef.scopedef_t._impl_matchers[namespace_t.namespace], name=name, function=function, recursive=recursive) )
[ "def", "namespace", "(", "self", ",", "name", "=", "None", ",", "function", "=", "None", ",", "recursive", "=", "None", ")", ":", "return", "(", "self", ".", "_find_single", "(", "scopedef", ".", "scopedef_t", ".", "_impl_matchers", "[", "namespace_t", ".", "namespace", "]", ",", "name", "=", "name", ",", "function", "=", "function", ",", "recursive", "=", "recursive", ")", ")" ]
Returns reference to namespace declaration that matches a defined criteria.
[ "Returns", "reference", "to", "namespace", "declaration", "that", "matches", "a", "defined", "criteria", "." ]
2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e
https://github.com/gccxml/pygccxml/blob/2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e/pygccxml/declarations/namespace.py#L109-L122
train
236,104
gccxml/pygccxml
pygccxml/declarations/namespace.py
namespace_t.namespaces
def namespaces( self, name=None, function=None, recursive=None, allow_empty=None): """ Returns a set of namespace declarations that match a defined criteria. """ return ( self._find_multiple( scopedef.scopedef_t._impl_matchers[namespace_t.namespace], name=name, function=function, recursive=recursive, allow_empty=allow_empty) )
python
def namespaces( self, name=None, function=None, recursive=None, allow_empty=None): """ Returns a set of namespace declarations that match a defined criteria. """ return ( self._find_multiple( scopedef.scopedef_t._impl_matchers[namespace_t.namespace], name=name, function=function, recursive=recursive, allow_empty=allow_empty) )
[ "def", "namespaces", "(", "self", ",", "name", "=", "None", ",", "function", "=", "None", ",", "recursive", "=", "None", ",", "allow_empty", "=", "None", ")", ":", "return", "(", "self", ".", "_find_multiple", "(", "scopedef", ".", "scopedef_t", ".", "_impl_matchers", "[", "namespace_t", ".", "namespace", "]", ",", "name", "=", "name", ",", "function", "=", "function", ",", "recursive", "=", "recursive", ",", "allow_empty", "=", "allow_empty", ")", ")" ]
Returns a set of namespace declarations that match a defined criteria.
[ "Returns", "a", "set", "of", "namespace", "declarations", "that", "match", "a", "defined", "criteria", "." ]
2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e
https://github.com/gccxml/pygccxml/blob/2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e/pygccxml/declarations/namespace.py#L124-L143
train
236,105
gccxml/pygccxml
pygccxml/declarations/namespace.py
namespace_t.free_function
def free_function( self, name=None, function=None, return_type=None, arg_types=None, header_dir=None, header_file=None, recursive=None): """ Returns reference to free function declaration that matches a defined criteria. """ return ( self._find_single( scopedef.scopedef_t._impl_matchers[namespace_t.free_function], name=name, function=function, decl_type=self._impl_decl_types[namespace_t.free_function], return_type=return_type, arg_types=arg_types, header_dir=header_dir, header_file=header_file, recursive=recursive) )
python
def free_function( self, name=None, function=None, return_type=None, arg_types=None, header_dir=None, header_file=None, recursive=None): """ Returns reference to free function declaration that matches a defined criteria. """ return ( self._find_single( scopedef.scopedef_t._impl_matchers[namespace_t.free_function], name=name, function=function, decl_type=self._impl_decl_types[namespace_t.free_function], return_type=return_type, arg_types=arg_types, header_dir=header_dir, header_file=header_file, recursive=recursive) )
[ "def", "free_function", "(", "self", ",", "name", "=", "None", ",", "function", "=", "None", ",", "return_type", "=", "None", ",", "arg_types", "=", "None", ",", "header_dir", "=", "None", ",", "header_file", "=", "None", ",", "recursive", "=", "None", ")", ":", "return", "(", "self", ".", "_find_single", "(", "scopedef", ".", "scopedef_t", ".", "_impl_matchers", "[", "namespace_t", ".", "free_function", "]", ",", "name", "=", "name", ",", "function", "=", "function", ",", "decl_type", "=", "self", ".", "_impl_decl_types", "[", "namespace_t", ".", "free_function", "]", ",", "return_type", "=", "return_type", ",", "arg_types", "=", "arg_types", ",", "header_dir", "=", "header_dir", ",", "header_file", "=", "header_file", ",", "recursive", "=", "recursive", ")", ")" ]
Returns reference to free function declaration that matches a defined criteria.
[ "Returns", "reference", "to", "free", "function", "declaration", "that", "matches", "a", "defined", "criteria", "." ]
2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e
https://github.com/gccxml/pygccxml/blob/2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e/pygccxml/declarations/namespace.py#L145-L171
train
236,106
gccxml/pygccxml
pygccxml/declarations/namespace.py
namespace_t.free_functions
def free_functions( self, name=None, function=None, return_type=None, arg_types=None, header_dir=None, header_file=None, recursive=None, allow_empty=None): """ Returns a set of free function declarations that match a defined criteria. """ return ( self._find_multiple( scopedef.scopedef_t._impl_matchers[namespace_t.free_function], name=name, function=function, decl_type=self._impl_decl_types[namespace_t.free_function], return_type=return_type, arg_types=arg_types, header_dir=header_dir, header_file=header_file, recursive=recursive, allow_empty=allow_empty) )
python
def free_functions( self, name=None, function=None, return_type=None, arg_types=None, header_dir=None, header_file=None, recursive=None, allow_empty=None): """ Returns a set of free function declarations that match a defined criteria. """ return ( self._find_multiple( scopedef.scopedef_t._impl_matchers[namespace_t.free_function], name=name, function=function, decl_type=self._impl_decl_types[namespace_t.free_function], return_type=return_type, arg_types=arg_types, header_dir=header_dir, header_file=header_file, recursive=recursive, allow_empty=allow_empty) )
[ "def", "free_functions", "(", "self", ",", "name", "=", "None", ",", "function", "=", "None", ",", "return_type", "=", "None", ",", "arg_types", "=", "None", ",", "header_dir", "=", "None", ",", "header_file", "=", "None", ",", "recursive", "=", "None", ",", "allow_empty", "=", "None", ")", ":", "return", "(", "self", ".", "_find_multiple", "(", "scopedef", ".", "scopedef_t", ".", "_impl_matchers", "[", "namespace_t", ".", "free_function", "]", ",", "name", "=", "name", ",", "function", "=", "function", ",", "decl_type", "=", "self", ".", "_impl_decl_types", "[", "namespace_t", ".", "free_function", "]", ",", "return_type", "=", "return_type", ",", "arg_types", "=", "arg_types", ",", "header_dir", "=", "header_dir", ",", "header_file", "=", "header_file", ",", "recursive", "=", "recursive", ",", "allow_empty", "=", "allow_empty", ")", ")" ]
Returns a set of free function declarations that match a defined criteria.
[ "Returns", "a", "set", "of", "free", "function", "declarations", "that", "match", "a", "defined", "criteria", "." ]
2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e
https://github.com/gccxml/pygccxml/blob/2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e/pygccxml/declarations/namespace.py#L173-L201
train
236,107
gccxml/pygccxml
pygccxml/declarations/namespace.py
namespace_t.free_operator
def free_operator( self, name=None, function=None, symbol=None, return_type=None, arg_types=None, header_dir=None, header_file=None, recursive=None): """ Returns reference to free operator declaration that matches a defined criteria. """ return ( self._find_single( scopedef.scopedef_t._impl_matchers[namespace_t.free_operator], name=self._build_operator_name(name, function, symbol), symbol=symbol, function=self._build_operator_function(name, function), decl_type=self._impl_decl_types[namespace_t.free_operator], return_type=return_type, arg_types=arg_types, header_dir=header_dir, header_file=header_file, recursive=recursive) )
python
def free_operator( self, name=None, function=None, symbol=None, return_type=None, arg_types=None, header_dir=None, header_file=None, recursive=None): """ Returns reference to free operator declaration that matches a defined criteria. """ return ( self._find_single( scopedef.scopedef_t._impl_matchers[namespace_t.free_operator], name=self._build_operator_name(name, function, symbol), symbol=symbol, function=self._build_operator_function(name, function), decl_type=self._impl_decl_types[namespace_t.free_operator], return_type=return_type, arg_types=arg_types, header_dir=header_dir, header_file=header_file, recursive=recursive) )
[ "def", "free_operator", "(", "self", ",", "name", "=", "None", ",", "function", "=", "None", ",", "symbol", "=", "None", ",", "return_type", "=", "None", ",", "arg_types", "=", "None", ",", "header_dir", "=", "None", ",", "header_file", "=", "None", ",", "recursive", "=", "None", ")", ":", "return", "(", "self", ".", "_find_single", "(", "scopedef", ".", "scopedef_t", ".", "_impl_matchers", "[", "namespace_t", ".", "free_operator", "]", ",", "name", "=", "self", ".", "_build_operator_name", "(", "name", ",", "function", ",", "symbol", ")", ",", "symbol", "=", "symbol", ",", "function", "=", "self", ".", "_build_operator_function", "(", "name", ",", "function", ")", ",", "decl_type", "=", "self", ".", "_impl_decl_types", "[", "namespace_t", ".", "free_operator", "]", ",", "return_type", "=", "return_type", ",", "arg_types", "=", "arg_types", ",", "header_dir", "=", "header_dir", ",", "header_file", "=", "header_file", ",", "recursive", "=", "recursive", ")", ")" ]
Returns reference to free operator declaration that matches a defined criteria.
[ "Returns", "reference", "to", "free", "operator", "declaration", "that", "matches", "a", "defined", "criteria", "." ]
2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e
https://github.com/gccxml/pygccxml/blob/2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e/pygccxml/declarations/namespace.py#L203-L230
train
236,108
gccxml/pygccxml
pygccxml/declarations/calldef_types.py
CALLING_CONVENTION_TYPES.extract
def extract(text, default=UNKNOWN): """extracts calling convention from the text. If the calling convention could not be found, the "default"is used""" if not text: return default found = CALLING_CONVENTION_TYPES.pattern.match(text) if found: return found.group('cc') return default
python
def extract(text, default=UNKNOWN): """extracts calling convention from the text. If the calling convention could not be found, the "default"is used""" if not text: return default found = CALLING_CONVENTION_TYPES.pattern.match(text) if found: return found.group('cc') return default
[ "def", "extract", "(", "text", ",", "default", "=", "UNKNOWN", ")", ":", "if", "not", "text", ":", "return", "default", "found", "=", "CALLING_CONVENTION_TYPES", ".", "pattern", ".", "match", "(", "text", ")", "if", "found", ":", "return", "found", ".", "group", "(", "'cc'", ")", "return", "default" ]
extracts calling convention from the text. If the calling convention could not be found, the "default"is used
[ "extracts", "calling", "convention", "from", "the", "text", ".", "If", "the", "calling", "convention", "could", "not", "be", "found", "the", "default", "is", "used" ]
2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e
https://github.com/gccxml/pygccxml/blob/2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e/pygccxml/declarations/calldef_types.py#L38-L47
train
236,109
gccxml/pygccxml
pygccxml/declarations/function_traits.py
is_same_function
def is_same_function(f1, f2): """returns true if f1 and f2 is same function Use case: sometimes when user defines some virtual function in base class, it overrides it in a derived one. Sometimes we need to know whether two member functions is actually same function. """ if f1 is f2: return True if f1.__class__ is not f2.__class__: return False if isinstance(f1, calldef_members.member_calldef_t) and \ f1.has_const != f2.has_const: return False if f1.name != f2.name: return False if not is_same_return_type(f1, f2): return False if len(f1.arguments) != len(f2.arguments): return False for f1_arg, f2_arg in zip(f1.arguments, f2.arguments): if not type_traits.is_same(f1_arg.decl_type, f2_arg.decl_type): return False return True
python
def is_same_function(f1, f2): """returns true if f1 and f2 is same function Use case: sometimes when user defines some virtual function in base class, it overrides it in a derived one. Sometimes we need to know whether two member functions is actually same function. """ if f1 is f2: return True if f1.__class__ is not f2.__class__: return False if isinstance(f1, calldef_members.member_calldef_t) and \ f1.has_const != f2.has_const: return False if f1.name != f2.name: return False if not is_same_return_type(f1, f2): return False if len(f1.arguments) != len(f2.arguments): return False for f1_arg, f2_arg in zip(f1.arguments, f2.arguments): if not type_traits.is_same(f1_arg.decl_type, f2_arg.decl_type): return False return True
[ "def", "is_same_function", "(", "f1", ",", "f2", ")", ":", "if", "f1", "is", "f2", ":", "return", "True", "if", "f1", ".", "__class__", "is", "not", "f2", ".", "__class__", ":", "return", "False", "if", "isinstance", "(", "f1", ",", "calldef_members", ".", "member_calldef_t", ")", "and", "f1", ".", "has_const", "!=", "f2", ".", "has_const", ":", "return", "False", "if", "f1", ".", "name", "!=", "f2", ".", "name", ":", "return", "False", "if", "not", "is_same_return_type", "(", "f1", ",", "f2", ")", ":", "return", "False", "if", "len", "(", "f1", ".", "arguments", ")", "!=", "len", "(", "f2", ".", "arguments", ")", ":", "return", "False", "for", "f1_arg", ",", "f2_arg", "in", "zip", "(", "f1", ".", "arguments", ",", "f2", ".", "arguments", ")", ":", "if", "not", "type_traits", ".", "is_same", "(", "f1_arg", ".", "decl_type", ",", "f2_arg", ".", "decl_type", ")", ":", "return", "False", "return", "True" ]
returns true if f1 and f2 is same function Use case: sometimes when user defines some virtual function in base class, it overrides it in a derived one. Sometimes we need to know whether two member functions is actually same function.
[ "returns", "true", "if", "f1", "and", "f2", "is", "same", "function" ]
2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e
https://github.com/gccxml/pygccxml/blob/2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e/pygccxml/declarations/function_traits.py#L73-L96
train
236,110
gccxml/pygccxml
pygccxml/declarations/scopedef.py
make_flatten
def make_flatten(decl_or_decls): """ Converts tree representation of declarations to flatten one. :param decl_or_decls: reference to list of declaration's or single declaration :type decl_or_decls: :class:`declaration_t` or [ :class:`declaration_t` ] :rtype: [ all internal declarations ] """ def proceed_single(decl): answer = [decl] if not isinstance(decl, scopedef_t): return answer for elem in decl.declarations: if isinstance(elem, scopedef_t): answer.extend(proceed_single(elem)) else: answer.append(elem) return answer decls = [] if isinstance(decl_or_decls, list): decls.extend(decl_or_decls) else: decls.append(decl_or_decls) answer = [] for decl in decls: answer.extend(proceed_single(decl)) return answer
python
def make_flatten(decl_or_decls): """ Converts tree representation of declarations to flatten one. :param decl_or_decls: reference to list of declaration's or single declaration :type decl_or_decls: :class:`declaration_t` or [ :class:`declaration_t` ] :rtype: [ all internal declarations ] """ def proceed_single(decl): answer = [decl] if not isinstance(decl, scopedef_t): return answer for elem in decl.declarations: if isinstance(elem, scopedef_t): answer.extend(proceed_single(elem)) else: answer.append(elem) return answer decls = [] if isinstance(decl_or_decls, list): decls.extend(decl_or_decls) else: decls.append(decl_or_decls) answer = [] for decl in decls: answer.extend(proceed_single(decl)) return answer
[ "def", "make_flatten", "(", "decl_or_decls", ")", ":", "def", "proceed_single", "(", "decl", ")", ":", "answer", "=", "[", "decl", "]", "if", "not", "isinstance", "(", "decl", ",", "scopedef_t", ")", ":", "return", "answer", "for", "elem", "in", "decl", ".", "declarations", ":", "if", "isinstance", "(", "elem", ",", "scopedef_t", ")", ":", "answer", ".", "extend", "(", "proceed_single", "(", "elem", ")", ")", "else", ":", "answer", ".", "append", "(", "elem", ")", "return", "answer", "decls", "=", "[", "]", "if", "isinstance", "(", "decl_or_decls", ",", "list", ")", ":", "decls", ".", "extend", "(", "decl_or_decls", ")", "else", ":", "decls", ".", "append", "(", "decl_or_decls", ")", "answer", "=", "[", "]", "for", "decl", "in", "decls", ":", "answer", ".", "extend", "(", "proceed_single", "(", "decl", ")", ")", "return", "answer" ]
Converts tree representation of declarations to flatten one. :param decl_or_decls: reference to list of declaration's or single declaration :type decl_or_decls: :class:`declaration_t` or [ :class:`declaration_t` ] :rtype: [ all internal declarations ]
[ "Converts", "tree", "representation", "of", "declarations", "to", "flatten", "one", "." ]
2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e
https://github.com/gccxml/pygccxml/blob/2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e/pygccxml/declarations/scopedef.py#L1058-L1088
train
236,111
gccxml/pygccxml
pygccxml/declarations/scopedef.py
find_all_declarations
def find_all_declarations( declarations, decl_type=None, name=None, parent=None, recursive=True, fullname=None): """ Returns a list of all declarations that match criteria, defined by developer. For more information about arguments see :class:`match_declaration_t` class. :rtype: [ matched declarations ] """ if recursive: decls = make_flatten(declarations) else: decls = declarations return list( filter( algorithm.match_declaration_t( decl_type=decl_type, name=name, fullname=fullname, parent=parent), decls))
python
def find_all_declarations( declarations, decl_type=None, name=None, parent=None, recursive=True, fullname=None): """ Returns a list of all declarations that match criteria, defined by developer. For more information about arguments see :class:`match_declaration_t` class. :rtype: [ matched declarations ] """ if recursive: decls = make_flatten(declarations) else: decls = declarations return list( filter( algorithm.match_declaration_t( decl_type=decl_type, name=name, fullname=fullname, parent=parent), decls))
[ "def", "find_all_declarations", "(", "declarations", ",", "decl_type", "=", "None", ",", "name", "=", "None", ",", "parent", "=", "None", ",", "recursive", "=", "True", ",", "fullname", "=", "None", ")", ":", "if", "recursive", ":", "decls", "=", "make_flatten", "(", "declarations", ")", "else", ":", "decls", "=", "declarations", "return", "list", "(", "filter", "(", "algorithm", ".", "match_declaration_t", "(", "decl_type", "=", "decl_type", ",", "name", "=", "name", ",", "fullname", "=", "fullname", ",", "parent", "=", "parent", ")", ",", "decls", ")", ")" ]
Returns a list of all declarations that match criteria, defined by developer. For more information about arguments see :class:`match_declaration_t` class. :rtype: [ matched declarations ]
[ "Returns", "a", "list", "of", "all", "declarations", "that", "match", "criteria", "defined", "by", "developer", "." ]
2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e
https://github.com/gccxml/pygccxml/blob/2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e/pygccxml/declarations/scopedef.py#L1091-L1121
train
236,112
gccxml/pygccxml
pygccxml/declarations/scopedef.py
find_declaration
def find_declaration( declarations, decl_type=None, name=None, parent=None, recursive=True, fullname=None): """ Returns single declaration that match criteria, defined by developer. If more the one declaration was found None will be returned. For more information about arguments see :class:`match_declaration_t` class. :rtype: matched declaration :class:`declaration_t` or None """ decl = find_all_declarations( declarations, decl_type=decl_type, name=name, parent=parent, recursive=recursive, fullname=fullname) if len(decl) == 1: return decl[0]
python
def find_declaration( declarations, decl_type=None, name=None, parent=None, recursive=True, fullname=None): """ Returns single declaration that match criteria, defined by developer. If more the one declaration was found None will be returned. For more information about arguments see :class:`match_declaration_t` class. :rtype: matched declaration :class:`declaration_t` or None """ decl = find_all_declarations( declarations, decl_type=decl_type, name=name, parent=parent, recursive=recursive, fullname=fullname) if len(decl) == 1: return decl[0]
[ "def", "find_declaration", "(", "declarations", ",", "decl_type", "=", "None", ",", "name", "=", "None", ",", "parent", "=", "None", ",", "recursive", "=", "True", ",", "fullname", "=", "None", ")", ":", "decl", "=", "find_all_declarations", "(", "declarations", ",", "decl_type", "=", "decl_type", ",", "name", "=", "name", ",", "parent", "=", "parent", ",", "recursive", "=", "recursive", ",", "fullname", "=", "fullname", ")", "if", "len", "(", "decl", ")", "==", "1", ":", "return", "decl", "[", "0", "]" ]
Returns single declaration that match criteria, defined by developer. If more the one declaration was found None will be returned. For more information about arguments see :class:`match_declaration_t` class. :rtype: matched declaration :class:`declaration_t` or None
[ "Returns", "single", "declaration", "that", "match", "criteria", "defined", "by", "developer", ".", "If", "more", "the", "one", "declaration", "was", "found", "None", "will", "be", "returned", "." ]
2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e
https://github.com/gccxml/pygccxml/blob/2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e/pygccxml/declarations/scopedef.py#L1124-L1150
train
236,113
gccxml/pygccxml
pygccxml/declarations/scopedef.py
find_first_declaration
def find_first_declaration( declarations, decl_type=None, name=None, parent=None, recursive=True, fullname=None): """ Returns first declaration that match criteria, defined by developer. For more information about arguments see :class:`match_declaration_t` class. :rtype: matched declaration :class:`declaration_t` or None """ decl_matcher = algorithm.match_declaration_t( decl_type=decl_type, name=name, fullname=fullname, parent=parent) if recursive: decls = make_flatten(declarations) else: decls = declarations for decl in decls: if decl_matcher(decl): return decl return None
python
def find_first_declaration( declarations, decl_type=None, name=None, parent=None, recursive=True, fullname=None): """ Returns first declaration that match criteria, defined by developer. For more information about arguments see :class:`match_declaration_t` class. :rtype: matched declaration :class:`declaration_t` or None """ decl_matcher = algorithm.match_declaration_t( decl_type=decl_type, name=name, fullname=fullname, parent=parent) if recursive: decls = make_flatten(declarations) else: decls = declarations for decl in decls: if decl_matcher(decl): return decl return None
[ "def", "find_first_declaration", "(", "declarations", ",", "decl_type", "=", "None", ",", "name", "=", "None", ",", "parent", "=", "None", ",", "recursive", "=", "True", ",", "fullname", "=", "None", ")", ":", "decl_matcher", "=", "algorithm", ".", "match_declaration_t", "(", "decl_type", "=", "decl_type", ",", "name", "=", "name", ",", "fullname", "=", "fullname", ",", "parent", "=", "parent", ")", "if", "recursive", ":", "decls", "=", "make_flatten", "(", "declarations", ")", "else", ":", "decls", "=", "declarations", "for", "decl", "in", "decls", ":", "if", "decl_matcher", "(", "decl", ")", ":", "return", "decl", "return", "None" ]
Returns first declaration that match criteria, defined by developer. For more information about arguments see :class:`match_declaration_t` class. :rtype: matched declaration :class:`declaration_t` or None
[ "Returns", "first", "declaration", "that", "match", "criteria", "defined", "by", "developer", "." ]
2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e
https://github.com/gccxml/pygccxml/blob/2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e/pygccxml/declarations/scopedef.py#L1153-L1182
train
236,114
gccxml/pygccxml
pygccxml/declarations/scopedef.py
declaration_files
def declaration_files(decl_or_decls): """ Returns set of files Every declaration is declared in some file. This function returns set, that contains all file names of declarations. :param decl_or_decls: reference to list of declaration's or single declaration :type decl_or_decls: :class:`declaration_t` or [:class:`declaration_t`] :rtype: set(declaration file names) """ files = set() decls = make_flatten(decl_or_decls) for decl in decls: if decl.location: files.add(decl.location.file_name) return files
python
def declaration_files(decl_or_decls): """ Returns set of files Every declaration is declared in some file. This function returns set, that contains all file names of declarations. :param decl_or_decls: reference to list of declaration's or single declaration :type decl_or_decls: :class:`declaration_t` or [:class:`declaration_t`] :rtype: set(declaration file names) """ files = set() decls = make_flatten(decl_or_decls) for decl in decls: if decl.location: files.add(decl.location.file_name) return files
[ "def", "declaration_files", "(", "decl_or_decls", ")", ":", "files", "=", "set", "(", ")", "decls", "=", "make_flatten", "(", "decl_or_decls", ")", "for", "decl", "in", "decls", ":", "if", "decl", ".", "location", ":", "files", ".", "add", "(", "decl", ".", "location", ".", "file_name", ")", "return", "files" ]
Returns set of files Every declaration is declared in some file. This function returns set, that contains all file names of declarations. :param decl_or_decls: reference to list of declaration's or single declaration :type decl_or_decls: :class:`declaration_t` or [:class:`declaration_t`] :rtype: set(declaration file names)
[ "Returns", "set", "of", "files" ]
2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e
https://github.com/gccxml/pygccxml/blob/2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e/pygccxml/declarations/scopedef.py#L1185-L1204
train
236,115
gccxml/pygccxml
pygccxml/declarations/scopedef.py
matcher.find
def find(decl_matcher, decls, recursive=True): """ Returns a list of declarations that match `decl_matcher` defined criteria or None :param decl_matcher: Python callable object, that takes one argument - reference to a declaration :param decls: the search scope, :class:declaration_t object or :class:declaration_t objects list t :param recursive: boolean, if True, the method will run `decl_matcher` on the internal declarations too """ where = [] if isinstance(decls, list): where.extend(decls) else: where.append(decls) if recursive: where = make_flatten(where) return list(filter(decl_matcher, where))
python
def find(decl_matcher, decls, recursive=True): """ Returns a list of declarations that match `decl_matcher` defined criteria or None :param decl_matcher: Python callable object, that takes one argument - reference to a declaration :param decls: the search scope, :class:declaration_t object or :class:declaration_t objects list t :param recursive: boolean, if True, the method will run `decl_matcher` on the internal declarations too """ where = [] if isinstance(decls, list): where.extend(decls) else: where.append(decls) if recursive: where = make_flatten(where) return list(filter(decl_matcher, where))
[ "def", "find", "(", "decl_matcher", ",", "decls", ",", "recursive", "=", "True", ")", ":", "where", "=", "[", "]", "if", "isinstance", "(", "decls", ",", "list", ")", ":", "where", ".", "extend", "(", "decls", ")", "else", ":", "where", ".", "append", "(", "decls", ")", "if", "recursive", ":", "where", "=", "make_flatten", "(", "where", ")", "return", "list", "(", "filter", "(", "decl_matcher", ",", "where", ")", ")" ]
Returns a list of declarations that match `decl_matcher` defined criteria or None :param decl_matcher: Python callable object, that takes one argument - reference to a declaration :param decls: the search scope, :class:declaration_t object or :class:declaration_t objects list t :param recursive: boolean, if True, the method will run `decl_matcher` on the internal declarations too
[ "Returns", "a", "list", "of", "declarations", "that", "match", "decl_matcher", "defined", "criteria", "or", "None" ]
2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e
https://github.com/gccxml/pygccxml/blob/2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e/pygccxml/declarations/scopedef.py#L29-L49
train
236,116
gccxml/pygccxml
pygccxml/declarations/scopedef.py
matcher.find_single
def find_single(decl_matcher, decls, recursive=True): """ Returns a reference to the declaration, that match `decl_matcher` defined criteria. if a unique declaration could not be found the method will return None. :param decl_matcher: Python callable object, that takes one argument - reference to a declaration :param decls: the search scope, :class:declaration_t object or :class:declaration_t objects list t :param recursive: boolean, if True, the method will run `decl_matcher` on the internal declarations too """ answer = matcher.find(decl_matcher, decls, recursive) if len(answer) == 1: return answer[0]
python
def find_single(decl_matcher, decls, recursive=True): """ Returns a reference to the declaration, that match `decl_matcher` defined criteria. if a unique declaration could not be found the method will return None. :param decl_matcher: Python callable object, that takes one argument - reference to a declaration :param decls: the search scope, :class:declaration_t object or :class:declaration_t objects list t :param recursive: boolean, if True, the method will run `decl_matcher` on the internal declarations too """ answer = matcher.find(decl_matcher, decls, recursive) if len(answer) == 1: return answer[0]
[ "def", "find_single", "(", "decl_matcher", ",", "decls", ",", "recursive", "=", "True", ")", ":", "answer", "=", "matcher", ".", "find", "(", "decl_matcher", ",", "decls", ",", "recursive", ")", "if", "len", "(", "answer", ")", "==", "1", ":", "return", "answer", "[", "0", "]" ]
Returns a reference to the declaration, that match `decl_matcher` defined criteria. if a unique declaration could not be found the method will return None. :param decl_matcher: Python callable object, that takes one argument - reference to a declaration :param decls: the search scope, :class:declaration_t object or :class:declaration_t objects list t :param recursive: boolean, if True, the method will run `decl_matcher` on the internal declarations too
[ "Returns", "a", "reference", "to", "the", "declaration", "that", "match", "decl_matcher", "defined", "criteria", "." ]
2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e
https://github.com/gccxml/pygccxml/blob/2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e/pygccxml/declarations/scopedef.py#L52-L68
train
236,117
gccxml/pygccxml
pygccxml/declarations/scopedef.py
matcher.get_single
def get_single(decl_matcher, decls, recursive=True): """ Returns a reference to declaration, that match `decl_matcher` defined criteria. If a unique declaration could not be found, an appropriate exception will be raised. :param decl_matcher: Python callable object, that takes one argument - reference to a declaration :param decls: the search scope, :class:declaration_t object or :class:declaration_t objects list t :param recursive: boolean, if True, the method will run `decl_matcher` on the internal declarations too """ answer = matcher.find(decl_matcher, decls, recursive) if len(answer) == 1: return answer[0] elif not answer: raise runtime_errors.declaration_not_found_t(decl_matcher) else: raise runtime_errors.multiple_declarations_found_t(decl_matcher)
python
def get_single(decl_matcher, decls, recursive=True): """ Returns a reference to declaration, that match `decl_matcher` defined criteria. If a unique declaration could not be found, an appropriate exception will be raised. :param decl_matcher: Python callable object, that takes one argument - reference to a declaration :param decls: the search scope, :class:declaration_t object or :class:declaration_t objects list t :param recursive: boolean, if True, the method will run `decl_matcher` on the internal declarations too """ answer = matcher.find(decl_matcher, decls, recursive) if len(answer) == 1: return answer[0] elif not answer: raise runtime_errors.declaration_not_found_t(decl_matcher) else: raise runtime_errors.multiple_declarations_found_t(decl_matcher)
[ "def", "get_single", "(", "decl_matcher", ",", "decls", ",", "recursive", "=", "True", ")", ":", "answer", "=", "matcher", ".", "find", "(", "decl_matcher", ",", "decls", ",", "recursive", ")", "if", "len", "(", "answer", ")", "==", "1", ":", "return", "answer", "[", "0", "]", "elif", "not", "answer", ":", "raise", "runtime_errors", ".", "declaration_not_found_t", "(", "decl_matcher", ")", "else", ":", "raise", "runtime_errors", ".", "multiple_declarations_found_t", "(", "decl_matcher", ")" ]
Returns a reference to declaration, that match `decl_matcher` defined criteria. If a unique declaration could not be found, an appropriate exception will be raised. :param decl_matcher: Python callable object, that takes one argument - reference to a declaration :param decls: the search scope, :class:declaration_t object or :class:declaration_t objects list t :param recursive: boolean, if True, the method will run `decl_matcher` on the internal declarations too
[ "Returns", "a", "reference", "to", "declaration", "that", "match", "decl_matcher", "defined", "criteria", "." ]
2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e
https://github.com/gccxml/pygccxml/blob/2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e/pygccxml/declarations/scopedef.py#L71-L92
train
236,118
gccxml/pygccxml
pygccxml/declarations/scopedef.py
scopedef_t.clear_optimizer
def clear_optimizer(self): """Cleans query optimizer state""" self._optimized = False self._type2decls = {} self._type2name2decls = {} self._type2decls_nr = {} self._type2name2decls_nr = {} self._all_decls = None self._all_decls_not_recursive = None for decl in self.declarations: if isinstance(decl, scopedef_t): decl.clear_optimizer()
python
def clear_optimizer(self): """Cleans query optimizer state""" self._optimized = False self._type2decls = {} self._type2name2decls = {} self._type2decls_nr = {} self._type2name2decls_nr = {} self._all_decls = None self._all_decls_not_recursive = None for decl in self.declarations: if isinstance(decl, scopedef_t): decl.clear_optimizer()
[ "def", "clear_optimizer", "(", "self", ")", ":", "self", ".", "_optimized", "=", "False", "self", ".", "_type2decls", "=", "{", "}", "self", ".", "_type2name2decls", "=", "{", "}", "self", ".", "_type2decls_nr", "=", "{", "}", "self", ".", "_type2name2decls_nr", "=", "{", "}", "self", ".", "_all_decls", "=", "None", "self", ".", "_all_decls_not_recursive", "=", "None", "for", "decl", "in", "self", ".", "declarations", ":", "if", "isinstance", "(", "decl", ",", "scopedef_t", ")", ":", "decl", ".", "clear_optimizer", "(", ")" ]
Cleans query optimizer state
[ "Cleans", "query", "optimizer", "state" ]
2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e
https://github.com/gccxml/pygccxml/blob/2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e/pygccxml/declarations/scopedef.py#L248-L260
train
236,119
gccxml/pygccxml
pygccxml/declarations/scopedef.py
scopedef_t.init_optimizer
def init_optimizer(self): """ Initializes query optimizer state. There are 4 internals hash tables: 1. from type to declarations 2. from type to declarations for non-recursive queries 3. from type to name to declarations 4. from type to name to declarations for non-recursive queries Almost every query includes declaration type information. Also very common query is to search some declaration(s) by name or full name. Those hash tables allows to search declaration very quick. """ if self.name == '::': self._logger.debug( "preparing data structures for query optimizer - started") start_time = timeit.default_timer() self.clear_optimizer() for dtype in scopedef_t._impl_all_decl_types: self._type2decls[dtype] = [] self._type2decls_nr[dtype] = [] self._type2name2decls[dtype] = {} self._type2name2decls_nr[dtype] = {} self._all_decls_not_recursive = self.declarations self._all_decls = make_flatten( self._all_decls_not_recursive) for decl in self._all_decls: types = self.__decl_types(decl) for type_ in types: self._type2decls[type_].append(decl) name2decls = self._type2name2decls[type_] if decl.name not in name2decls: name2decls[decl.name] = [] name2decls[decl.name].append(decl) if self is decl.parent: self._type2decls_nr[type_].append(decl) name2decls_nr = self._type2name2decls_nr[type_] if decl.name not in name2decls_nr: name2decls_nr[decl.name] = [] name2decls_nr[decl.name].append(decl) for decl in self._all_decls_not_recursive: if isinstance(decl, scopedef_t): decl.init_optimizer() if self.name == '::': self._logger.debug(( "preparing data structures for query optimizer - " + "done( %f seconds ). "), (timeit.default_timer() - start_time)) self._optimized = True
python
def init_optimizer(self): """ Initializes query optimizer state. There are 4 internals hash tables: 1. from type to declarations 2. from type to declarations for non-recursive queries 3. from type to name to declarations 4. from type to name to declarations for non-recursive queries Almost every query includes declaration type information. Also very common query is to search some declaration(s) by name or full name. Those hash tables allows to search declaration very quick. """ if self.name == '::': self._logger.debug( "preparing data structures for query optimizer - started") start_time = timeit.default_timer() self.clear_optimizer() for dtype in scopedef_t._impl_all_decl_types: self._type2decls[dtype] = [] self._type2decls_nr[dtype] = [] self._type2name2decls[dtype] = {} self._type2name2decls_nr[dtype] = {} self._all_decls_not_recursive = self.declarations self._all_decls = make_flatten( self._all_decls_not_recursive) for decl in self._all_decls: types = self.__decl_types(decl) for type_ in types: self._type2decls[type_].append(decl) name2decls = self._type2name2decls[type_] if decl.name not in name2decls: name2decls[decl.name] = [] name2decls[decl.name].append(decl) if self is decl.parent: self._type2decls_nr[type_].append(decl) name2decls_nr = self._type2name2decls_nr[type_] if decl.name not in name2decls_nr: name2decls_nr[decl.name] = [] name2decls_nr[decl.name].append(decl) for decl in self._all_decls_not_recursive: if isinstance(decl, scopedef_t): decl.init_optimizer() if self.name == '::': self._logger.debug(( "preparing data structures for query optimizer - " + "done( %f seconds ). "), (timeit.default_timer() - start_time)) self._optimized = True
[ "def", "init_optimizer", "(", "self", ")", ":", "if", "self", ".", "name", "==", "'::'", ":", "self", ".", "_logger", ".", "debug", "(", "\"preparing data structures for query optimizer - started\"", ")", "start_time", "=", "timeit", ".", "default_timer", "(", ")", "self", ".", "clear_optimizer", "(", ")", "for", "dtype", "in", "scopedef_t", ".", "_impl_all_decl_types", ":", "self", ".", "_type2decls", "[", "dtype", "]", "=", "[", "]", "self", ".", "_type2decls_nr", "[", "dtype", "]", "=", "[", "]", "self", ".", "_type2name2decls", "[", "dtype", "]", "=", "{", "}", "self", ".", "_type2name2decls_nr", "[", "dtype", "]", "=", "{", "}", "self", ".", "_all_decls_not_recursive", "=", "self", ".", "declarations", "self", ".", "_all_decls", "=", "make_flatten", "(", "self", ".", "_all_decls_not_recursive", ")", "for", "decl", "in", "self", ".", "_all_decls", ":", "types", "=", "self", ".", "__decl_types", "(", "decl", ")", "for", "type_", "in", "types", ":", "self", ".", "_type2decls", "[", "type_", "]", ".", "append", "(", "decl", ")", "name2decls", "=", "self", ".", "_type2name2decls", "[", "type_", "]", "if", "decl", ".", "name", "not", "in", "name2decls", ":", "name2decls", "[", "decl", ".", "name", "]", "=", "[", "]", "name2decls", "[", "decl", ".", "name", "]", ".", "append", "(", "decl", ")", "if", "self", "is", "decl", ".", "parent", ":", "self", ".", "_type2decls_nr", "[", "type_", "]", ".", "append", "(", "decl", ")", "name2decls_nr", "=", "self", ".", "_type2name2decls_nr", "[", "type_", "]", "if", "decl", ".", "name", "not", "in", "name2decls_nr", ":", "name2decls_nr", "[", "decl", ".", "name", "]", "=", "[", "]", "name2decls_nr", "[", "decl", ".", "name", "]", ".", "append", "(", "decl", ")", "for", "decl", "in", "self", ".", "_all_decls_not_recursive", ":", "if", "isinstance", "(", "decl", ",", "scopedef_t", ")", ":", "decl", ".", "init_optimizer", "(", ")", "if", "self", ".", "name", "==", "'::'", ":", "self", ".", "_logger", ".", "debug", "(", "(", "\"preparing data structures for query optimizer - \"", "+", "\"done( %f seconds ). \"", ")", ",", "(", "timeit", ".", "default_timer", "(", ")", "-", "start_time", ")", ")", "self", ".", "_optimized", "=", "True" ]
Initializes query optimizer state. There are 4 internals hash tables: 1. from type to declarations 2. from type to declarations for non-recursive queries 3. from type to name to declarations 4. from type to name to declarations for non-recursive queries Almost every query includes declaration type information. Also very common query is to search some declaration(s) by name or full name. Those hash tables allows to search declaration very quick.
[ "Initializes", "query", "optimizer", "state", "." ]
2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e
https://github.com/gccxml/pygccxml/blob/2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e/pygccxml/declarations/scopedef.py#L262-L314
train
236,120
gccxml/pygccxml
pygccxml/declarations/scopedef.py
scopedef_t.decls
def decls( self, name=None, function=None, decl_type=None, header_dir=None, header_file=None, recursive=None, allow_empty=None): """returns a set of declarations, that are matched defined criteria""" return ( self._find_multiple( self._impl_matchers[ scopedef_t.decl], name=name, function=function, decl_type=decl_type, header_dir=header_dir, header_file=header_file, recursive=recursive, allow_empty=allow_empty) )
python
def decls( self, name=None, function=None, decl_type=None, header_dir=None, header_file=None, recursive=None, allow_empty=None): """returns a set of declarations, that are matched defined criteria""" return ( self._find_multiple( self._impl_matchers[ scopedef_t.decl], name=name, function=function, decl_type=decl_type, header_dir=header_dir, header_file=header_file, recursive=recursive, allow_empty=allow_empty) )
[ "def", "decls", "(", "self", ",", "name", "=", "None", ",", "function", "=", "None", ",", "decl_type", "=", "None", ",", "header_dir", "=", "None", ",", "header_file", "=", "None", ",", "recursive", "=", "None", ",", "allow_empty", "=", "None", ")", ":", "return", "(", "self", ".", "_find_multiple", "(", "self", ".", "_impl_matchers", "[", "scopedef_t", ".", "decl", "]", ",", "name", "=", "name", ",", "function", "=", "function", ",", "decl_type", "=", "decl_type", ",", "header_dir", "=", "header_dir", ",", "header_file", "=", "header_file", ",", "recursive", "=", "recursive", ",", "allow_empty", "=", "allow_empty", ")", ")" ]
returns a set of declarations, that are matched defined criteria
[ "returns", "a", "set", "of", "declarations", "that", "are", "matched", "defined", "criteria" ]
2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e
https://github.com/gccxml/pygccxml/blob/2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e/pygccxml/declarations/scopedef.py#L515-L536
train
236,121
gccxml/pygccxml
pygccxml/declarations/scopedef.py
scopedef_t.classes
def classes( self, name=None, function=None, header_dir=None, header_file=None, recursive=None, allow_empty=None): """returns a set of class declarations, that are matched defined criteria""" return ( self._find_multiple( self._impl_matchers[scopedef_t.class_], name=name, function=function, decl_type=self._impl_decl_types[ scopedef_t.class_], header_dir=header_dir, header_file=header_file, recursive=recursive, allow_empty=allow_empty) )
python
def classes( self, name=None, function=None, header_dir=None, header_file=None, recursive=None, allow_empty=None): """returns a set of class declarations, that are matched defined criteria""" return ( self._find_multiple( self._impl_matchers[scopedef_t.class_], name=name, function=function, decl_type=self._impl_decl_types[ scopedef_t.class_], header_dir=header_dir, header_file=header_file, recursive=recursive, allow_empty=allow_empty) )
[ "def", "classes", "(", "self", ",", "name", "=", "None", ",", "function", "=", "None", ",", "header_dir", "=", "None", ",", "header_file", "=", "None", ",", "recursive", "=", "None", ",", "allow_empty", "=", "None", ")", ":", "return", "(", "self", ".", "_find_multiple", "(", "self", ".", "_impl_matchers", "[", "scopedef_t", ".", "class_", "]", ",", "name", "=", "name", ",", "function", "=", "function", ",", "decl_type", "=", "self", ".", "_impl_decl_types", "[", "scopedef_t", ".", "class_", "]", ",", "header_dir", "=", "header_dir", ",", "header_file", "=", "header_file", ",", "recursive", "=", "recursive", ",", "allow_empty", "=", "allow_empty", ")", ")" ]
returns a set of class declarations, that are matched defined criteria
[ "returns", "a", "set", "of", "class", "declarations", "that", "are", "matched", "defined", "criteria" ]
2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e
https://github.com/gccxml/pygccxml/blob/2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e/pygccxml/declarations/scopedef.py#L559-L580
train
236,122
gccxml/pygccxml
pygccxml/declarations/scopedef.py
scopedef_t.variable
def variable( self, name=None, function=None, decl_type=None, header_dir=None, header_file=None, recursive=None): """returns reference to variable declaration, that is matched defined criteria""" return ( self._find_single( self._impl_matchers[ scopedef_t.variable], name=name, function=function, decl_type=decl_type, header_dir=header_dir, header_file=header_file, recursive=recursive) )
python
def variable( self, name=None, function=None, decl_type=None, header_dir=None, header_file=None, recursive=None): """returns reference to variable declaration, that is matched defined criteria""" return ( self._find_single( self._impl_matchers[ scopedef_t.variable], name=name, function=function, decl_type=decl_type, header_dir=header_dir, header_file=header_file, recursive=recursive) )
[ "def", "variable", "(", "self", ",", "name", "=", "None", ",", "function", "=", "None", ",", "decl_type", "=", "None", ",", "header_dir", "=", "None", ",", "header_file", "=", "None", ",", "recursive", "=", "None", ")", ":", "return", "(", "self", ".", "_find_single", "(", "self", ".", "_impl_matchers", "[", "scopedef_t", ".", "variable", "]", ",", "name", "=", "name", ",", "function", "=", "function", ",", "decl_type", "=", "decl_type", ",", "header_dir", "=", "header_dir", ",", "header_file", "=", "header_file", ",", "recursive", "=", "recursive", ")", ")" ]
returns reference to variable declaration, that is matched defined criteria
[ "returns", "reference", "to", "variable", "declaration", "that", "is", "matched", "defined", "criteria" ]
2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e
https://github.com/gccxml/pygccxml/blob/2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e/pygccxml/declarations/scopedef.py#L582-L603
train
236,123
gccxml/pygccxml
pygccxml/declarations/scopedef.py
scopedef_t.variables
def variables( self, name=None, function=None, decl_type=None, header_dir=None, header_file=None, recursive=None, allow_empty=None): """returns a set of variable declarations, that are matched defined criteria""" return ( self._find_multiple( self._impl_matchers[ scopedef_t.variable], name=name, function=function, decl_type=decl_type, header_dir=header_dir, header_file=header_file, recursive=recursive, allow_empty=allow_empty) )
python
def variables( self, name=None, function=None, decl_type=None, header_dir=None, header_file=None, recursive=None, allow_empty=None): """returns a set of variable declarations, that are matched defined criteria""" return ( self._find_multiple( self._impl_matchers[ scopedef_t.variable], name=name, function=function, decl_type=decl_type, header_dir=header_dir, header_file=header_file, recursive=recursive, allow_empty=allow_empty) )
[ "def", "variables", "(", "self", ",", "name", "=", "None", ",", "function", "=", "None", ",", "decl_type", "=", "None", ",", "header_dir", "=", "None", ",", "header_file", "=", "None", ",", "recursive", "=", "None", ",", "allow_empty", "=", "None", ")", ":", "return", "(", "self", ".", "_find_multiple", "(", "self", ".", "_impl_matchers", "[", "scopedef_t", ".", "variable", "]", ",", "name", "=", "name", ",", "function", "=", "function", ",", "decl_type", "=", "decl_type", ",", "header_dir", "=", "header_dir", ",", "header_file", "=", "header_file", ",", "recursive", "=", "recursive", ",", "allow_empty", "=", "allow_empty", ")", ")" ]
returns a set of variable declarations, that are matched defined criteria
[ "returns", "a", "set", "of", "variable", "declarations", "that", "are", "matched", "defined", "criteria" ]
2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e
https://github.com/gccxml/pygccxml/blob/2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e/pygccxml/declarations/scopedef.py#L605-L628
train
236,124
gccxml/pygccxml
pygccxml/declarations/scopedef.py
scopedef_t.member_functions
def member_functions( self, name=None, function=None, return_type=None, arg_types=None, header_dir=None, header_file=None, recursive=None, allow_empty=None): """returns a set of member function declarations, that are matched defined criteria""" return ( self._find_multiple( self._impl_matchers[scopedef_t.member_function], name=name, function=function, decl_type=self._impl_decl_types[ scopedef_t.member_function], return_type=return_type, arg_types=arg_types, header_dir=header_dir, header_file=header_file, recursive=recursive, allow_empty=allow_empty) )
python
def member_functions( self, name=None, function=None, return_type=None, arg_types=None, header_dir=None, header_file=None, recursive=None, allow_empty=None): """returns a set of member function declarations, that are matched defined criteria""" return ( self._find_multiple( self._impl_matchers[scopedef_t.member_function], name=name, function=function, decl_type=self._impl_decl_types[ scopedef_t.member_function], return_type=return_type, arg_types=arg_types, header_dir=header_dir, header_file=header_file, recursive=recursive, allow_empty=allow_empty) )
[ "def", "member_functions", "(", "self", ",", "name", "=", "None", ",", "function", "=", "None", ",", "return_type", "=", "None", ",", "arg_types", "=", "None", ",", "header_dir", "=", "None", ",", "header_file", "=", "None", ",", "recursive", "=", "None", ",", "allow_empty", "=", "None", ")", ":", "return", "(", "self", ".", "_find_multiple", "(", "self", ".", "_impl_matchers", "[", "scopedef_t", ".", "member_function", "]", ",", "name", "=", "name", ",", "function", "=", "function", ",", "decl_type", "=", "self", ".", "_impl_decl_types", "[", "scopedef_t", ".", "member_function", "]", ",", "return_type", "=", "return_type", ",", "arg_types", "=", "arg_types", ",", "header_dir", "=", "header_dir", ",", "header_file", "=", "header_file", ",", "recursive", "=", "recursive", ",", "allow_empty", "=", "allow_empty", ")", ")" ]
returns a set of member function declarations, that are matched defined criteria
[ "returns", "a", "set", "of", "member", "function", "declarations", "that", "are", "matched", "defined", "criteria" ]
2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e
https://github.com/gccxml/pygccxml/blob/2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e/pygccxml/declarations/scopedef.py#L767-L792
train
236,125
gccxml/pygccxml
pygccxml/declarations/scopedef.py
scopedef_t.constructor
def constructor( self, name=None, function=None, return_type=None, arg_types=None, header_dir=None, header_file=None, recursive=None): """returns reference to constructor declaration, that is matched defined criteria""" return ( self._find_single( self._impl_matchers[scopedef_t.constructor], name=name, function=function, decl_type=self._impl_decl_types[ scopedef_t.constructor], return_type=return_type, arg_types=arg_types, header_dir=header_dir, header_file=header_file, recursive=recursive) )
python
def constructor( self, name=None, function=None, return_type=None, arg_types=None, header_dir=None, header_file=None, recursive=None): """returns reference to constructor declaration, that is matched defined criteria""" return ( self._find_single( self._impl_matchers[scopedef_t.constructor], name=name, function=function, decl_type=self._impl_decl_types[ scopedef_t.constructor], return_type=return_type, arg_types=arg_types, header_dir=header_dir, header_file=header_file, recursive=recursive) )
[ "def", "constructor", "(", "self", ",", "name", "=", "None", ",", "function", "=", "None", ",", "return_type", "=", "None", ",", "arg_types", "=", "None", ",", "header_dir", "=", "None", ",", "header_file", "=", "None", ",", "recursive", "=", "None", ")", ":", "return", "(", "self", ".", "_find_single", "(", "self", ".", "_impl_matchers", "[", "scopedef_t", ".", "constructor", "]", ",", "name", "=", "name", ",", "function", "=", "function", ",", "decl_type", "=", "self", ".", "_impl_decl_types", "[", "scopedef_t", ".", "constructor", "]", ",", "return_type", "=", "return_type", ",", "arg_types", "=", "arg_types", ",", "header_dir", "=", "header_dir", ",", "header_file", "=", "header_file", ",", "recursive", "=", "recursive", ")", ")" ]
returns reference to constructor declaration, that is matched defined criteria
[ "returns", "reference", "to", "constructor", "declaration", "that", "is", "matched", "defined", "criteria" ]
2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e
https://github.com/gccxml/pygccxml/blob/2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e/pygccxml/declarations/scopedef.py#L794-L817
train
236,126
gccxml/pygccxml
pygccxml/declarations/scopedef.py
scopedef_t.constructors
def constructors( self, name=None, function=None, return_type=None, arg_types=None, header_dir=None, header_file=None, recursive=None, allow_empty=None): """returns a set of constructor declarations, that are matched defined criteria""" return ( self._find_multiple( self._impl_matchers[scopedef_t.constructor], name=name, function=function, decl_type=self._impl_decl_types[ scopedef_t.constructor], return_type=return_type, arg_types=arg_types, header_dir=header_dir, header_file=header_file, recursive=recursive, allow_empty=allow_empty) )
python
def constructors( self, name=None, function=None, return_type=None, arg_types=None, header_dir=None, header_file=None, recursive=None, allow_empty=None): """returns a set of constructor declarations, that are matched defined criteria""" return ( self._find_multiple( self._impl_matchers[scopedef_t.constructor], name=name, function=function, decl_type=self._impl_decl_types[ scopedef_t.constructor], return_type=return_type, arg_types=arg_types, header_dir=header_dir, header_file=header_file, recursive=recursive, allow_empty=allow_empty) )
[ "def", "constructors", "(", "self", ",", "name", "=", "None", ",", "function", "=", "None", ",", "return_type", "=", "None", ",", "arg_types", "=", "None", ",", "header_dir", "=", "None", ",", "header_file", "=", "None", ",", "recursive", "=", "None", ",", "allow_empty", "=", "None", ")", ":", "return", "(", "self", ".", "_find_multiple", "(", "self", ".", "_impl_matchers", "[", "scopedef_t", ".", "constructor", "]", ",", "name", "=", "name", ",", "function", "=", "function", ",", "decl_type", "=", "self", ".", "_impl_decl_types", "[", "scopedef_t", ".", "constructor", "]", ",", "return_type", "=", "return_type", ",", "arg_types", "=", "arg_types", ",", "header_dir", "=", "header_dir", ",", "header_file", "=", "header_file", ",", "recursive", "=", "recursive", ",", "allow_empty", "=", "allow_empty", ")", ")" ]
returns a set of constructor declarations, that are matched defined criteria
[ "returns", "a", "set", "of", "constructor", "declarations", "that", "are", "matched", "defined", "criteria" ]
2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e
https://github.com/gccxml/pygccxml/blob/2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e/pygccxml/declarations/scopedef.py#L819-L844
train
236,127
gccxml/pygccxml
pygccxml/declarations/scopedef.py
scopedef_t.casting_operators
def casting_operators( self, name=None, function=None, return_type=None, arg_types=None, header_dir=None, header_file=None, recursive=None, allow_empty=None): """returns a set of casting operator declarations, that are matched defined criteria""" return ( self._find_multiple( self._impl_matchers[scopedef_t.casting_operator], name=name, function=function, decl_type=self._impl_decl_types[ scopedef_t.casting_operator], return_type=return_type, arg_types=arg_types, header_dir=header_dir, header_file=header_file, recursive=recursive, allow_empty=allow_empty) )
python
def casting_operators( self, name=None, function=None, return_type=None, arg_types=None, header_dir=None, header_file=None, recursive=None, allow_empty=None): """returns a set of casting operator declarations, that are matched defined criteria""" return ( self._find_multiple( self._impl_matchers[scopedef_t.casting_operator], name=name, function=function, decl_type=self._impl_decl_types[ scopedef_t.casting_operator], return_type=return_type, arg_types=arg_types, header_dir=header_dir, header_file=header_file, recursive=recursive, allow_empty=allow_empty) )
[ "def", "casting_operators", "(", "self", ",", "name", "=", "None", ",", "function", "=", "None", ",", "return_type", "=", "None", ",", "arg_types", "=", "None", ",", "header_dir", "=", "None", ",", "header_file", "=", "None", ",", "recursive", "=", "None", ",", "allow_empty", "=", "None", ")", ":", "return", "(", "self", ".", "_find_multiple", "(", "self", ".", "_impl_matchers", "[", "scopedef_t", ".", "casting_operator", "]", ",", "name", "=", "name", ",", "function", "=", "function", ",", "decl_type", "=", "self", ".", "_impl_decl_types", "[", "scopedef_t", ".", "casting_operator", "]", ",", "return_type", "=", "return_type", ",", "arg_types", "=", "arg_types", ",", "header_dir", "=", "header_dir", ",", "header_file", "=", "header_file", ",", "recursive", "=", "recursive", ",", "allow_empty", "=", "allow_empty", ")", ")" ]
returns a set of casting operator declarations, that are matched defined criteria
[ "returns", "a", "set", "of", "casting", "operator", "declarations", "that", "are", "matched", "defined", "criteria" ]
2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e
https://github.com/gccxml/pygccxml/blob/2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e/pygccxml/declarations/scopedef.py#L931-L956
train
236,128
gccxml/pygccxml
pygccxml/declarations/scopedef.py
scopedef_t.enumerations
def enumerations( self, name=None, function=None, header_dir=None, header_file=None, recursive=None, allow_empty=None): """returns a set of enumeration declarations, that are matched defined criteria""" return ( self._find_multiple( self._impl_matchers[scopedef_t.enumeration], name=name, function=function, decl_type=self._impl_decl_types[ scopedef_t.enumeration], header_dir=header_dir, header_file=header_file, recursive=recursive, allow_empty=allow_empty) )
python
def enumerations( self, name=None, function=None, header_dir=None, header_file=None, recursive=None, allow_empty=None): """returns a set of enumeration declarations, that are matched defined criteria""" return ( self._find_multiple( self._impl_matchers[scopedef_t.enumeration], name=name, function=function, decl_type=self._impl_decl_types[ scopedef_t.enumeration], header_dir=header_dir, header_file=header_file, recursive=recursive, allow_empty=allow_empty) )
[ "def", "enumerations", "(", "self", ",", "name", "=", "None", ",", "function", "=", "None", ",", "header_dir", "=", "None", ",", "header_file", "=", "None", ",", "recursive", "=", "None", ",", "allow_empty", "=", "None", ")", ":", "return", "(", "self", ".", "_find_multiple", "(", "self", ".", "_impl_matchers", "[", "scopedef_t", ".", "enumeration", "]", ",", "name", "=", "name", ",", "function", "=", "function", ",", "decl_type", "=", "self", ".", "_impl_decl_types", "[", "scopedef_t", ".", "enumeration", "]", ",", "header_dir", "=", "header_dir", ",", "header_file", "=", "header_file", ",", "recursive", "=", "recursive", ",", "allow_empty", "=", "allow_empty", ")", ")" ]
returns a set of enumeration declarations, that are matched defined criteria
[ "returns", "a", "set", "of", "enumeration", "declarations", "that", "are", "matched", "defined", "criteria" ]
2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e
https://github.com/gccxml/pygccxml/blob/2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e/pygccxml/declarations/scopedef.py#L979-L1000
train
236,129
gccxml/pygccxml
pygccxml/declarations/scopedef.py
scopedef_t.typedef
def typedef( self, name=None, function=None, header_dir=None, header_file=None, recursive=None): """returns reference to typedef declaration, that is matched defined criteria""" return ( self._find_single( self._impl_matchers[scopedef_t.typedef], name=name, function=function, decl_type=self._impl_decl_types[ scopedef_t.typedef], header_dir=header_dir, header_file=header_file, recursive=recursive) )
python
def typedef( self, name=None, function=None, header_dir=None, header_file=None, recursive=None): """returns reference to typedef declaration, that is matched defined criteria""" return ( self._find_single( self._impl_matchers[scopedef_t.typedef], name=name, function=function, decl_type=self._impl_decl_types[ scopedef_t.typedef], header_dir=header_dir, header_file=header_file, recursive=recursive) )
[ "def", "typedef", "(", "self", ",", "name", "=", "None", ",", "function", "=", "None", ",", "header_dir", "=", "None", ",", "header_file", "=", "None", ",", "recursive", "=", "None", ")", ":", "return", "(", "self", ".", "_find_single", "(", "self", ".", "_impl_matchers", "[", "scopedef_t", ".", "typedef", "]", ",", "name", "=", "name", ",", "function", "=", "function", ",", "decl_type", "=", "self", ".", "_impl_decl_types", "[", "scopedef_t", ".", "typedef", "]", ",", "header_dir", "=", "header_dir", ",", "header_file", "=", "header_file", ",", "recursive", "=", "recursive", ")", ")" ]
returns reference to typedef declaration, that is matched defined criteria
[ "returns", "reference", "to", "typedef", "declaration", "that", "is", "matched", "defined", "criteria" ]
2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e
https://github.com/gccxml/pygccxml/blob/2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e/pygccxml/declarations/scopedef.py#L1002-L1021
train
236,130
gccxml/pygccxml
pygccxml/declarations/scopedef.py
scopedef_t.typedefs
def typedefs( self, name=None, function=None, header_dir=None, header_file=None, recursive=None, allow_empty=None): """returns a set of typedef declarations, that are matched defined criteria""" return ( self._find_multiple( self._impl_matchers[scopedef_t.typedef], name=name, function=function, decl_type=self._impl_decl_types[ scopedef_t.typedef], header_dir=header_dir, header_file=header_file, recursive=recursive, allow_empty=allow_empty) )
python
def typedefs( self, name=None, function=None, header_dir=None, header_file=None, recursive=None, allow_empty=None): """returns a set of typedef declarations, that are matched defined criteria""" return ( self._find_multiple( self._impl_matchers[scopedef_t.typedef], name=name, function=function, decl_type=self._impl_decl_types[ scopedef_t.typedef], header_dir=header_dir, header_file=header_file, recursive=recursive, allow_empty=allow_empty) )
[ "def", "typedefs", "(", "self", ",", "name", "=", "None", ",", "function", "=", "None", ",", "header_dir", "=", "None", ",", "header_file", "=", "None", ",", "recursive", "=", "None", ",", "allow_empty", "=", "None", ")", ":", "return", "(", "self", ".", "_find_multiple", "(", "self", ".", "_impl_matchers", "[", "scopedef_t", ".", "typedef", "]", ",", "name", "=", "name", ",", "function", "=", "function", ",", "decl_type", "=", "self", ".", "_impl_decl_types", "[", "scopedef_t", ".", "typedef", "]", ",", "header_dir", "=", "header_dir", ",", "header_file", "=", "header_file", ",", "recursive", "=", "recursive", ",", "allow_empty", "=", "allow_empty", ")", ")" ]
returns a set of typedef declarations, that are matched defined criteria
[ "returns", "a", "set", "of", "typedef", "declarations", "that", "are", "matched", "defined", "criteria" ]
2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e
https://github.com/gccxml/pygccxml/blob/2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e/pygccxml/declarations/scopedef.py#L1023-L1044
train
236,131
gccxml/pygccxml
pygccxml/parser/config.py
load_xml_generator_configuration
def load_xml_generator_configuration(configuration, **defaults): """ Loads CastXML or GCC-XML configuration. Args: configuration (string|configparser.ConfigParser): can be a string (file path to a configuration file) or instance of :class:`configparser.ConfigParser`. defaults: can be used to override single configuration values. Returns: :class:`.xml_generator_configuration_t`: a configuration object The file passed needs to be in a format that can be parsed by :class:`configparser.ConfigParser`. An example configuration file skeleton can be found `here <https://github.com/gccxml/pygccxml/blob/develop/ unittests/xml_generator.cfg>`_. """ parser = configuration if utils.is_str(configuration): parser = ConfigParser() parser.read(configuration) # Create a new empty configuration cfg = xml_generator_configuration_t() values = defaults if not values: values = {} if parser.has_section('xml_generator'): for name, value in parser.items('xml_generator'): if value.strip(): values[name] = value for name, value in values.items(): if isinstance(value, str): value = value.strip() if name == 'gccxml_path': cfg.gccxml_path = value if name == 'xml_generator_path': cfg.xml_generator_path = value elif name == 'working_directory': cfg.working_directory = value elif name == 'include_paths': for p in value.split(';'): p = p.strip() if p: cfg.include_paths.append(os.path.normpath(p)) elif name == 'compiler': cfg.compiler = value elif name == 'xml_generator': cfg.xml_generator = value elif name == 'castxml_epic_version': cfg.castxml_epic_version = int(value) elif name == 'keep_xml': cfg.keep_xml = value elif name == 'cflags': cfg.cflags = value elif name == 'flags': cfg.flags = value elif name == 'compiler_path': cfg.compiler_path = value else: print('\n%s entry was ignored' % name) # If no compiler path was set and we are using castxml, set the path # Here we overwrite the default configuration done in the cfg because # the xml_generator was set through the setter after the creation of a new # emppty configuration object. cfg.compiler_path = create_compiler_path( cfg.xml_generator, cfg.compiler_path) return cfg
python
def load_xml_generator_configuration(configuration, **defaults): """ Loads CastXML or GCC-XML configuration. Args: configuration (string|configparser.ConfigParser): can be a string (file path to a configuration file) or instance of :class:`configparser.ConfigParser`. defaults: can be used to override single configuration values. Returns: :class:`.xml_generator_configuration_t`: a configuration object The file passed needs to be in a format that can be parsed by :class:`configparser.ConfigParser`. An example configuration file skeleton can be found `here <https://github.com/gccxml/pygccxml/blob/develop/ unittests/xml_generator.cfg>`_. """ parser = configuration if utils.is_str(configuration): parser = ConfigParser() parser.read(configuration) # Create a new empty configuration cfg = xml_generator_configuration_t() values = defaults if not values: values = {} if parser.has_section('xml_generator'): for name, value in parser.items('xml_generator'): if value.strip(): values[name] = value for name, value in values.items(): if isinstance(value, str): value = value.strip() if name == 'gccxml_path': cfg.gccxml_path = value if name == 'xml_generator_path': cfg.xml_generator_path = value elif name == 'working_directory': cfg.working_directory = value elif name == 'include_paths': for p in value.split(';'): p = p.strip() if p: cfg.include_paths.append(os.path.normpath(p)) elif name == 'compiler': cfg.compiler = value elif name == 'xml_generator': cfg.xml_generator = value elif name == 'castxml_epic_version': cfg.castxml_epic_version = int(value) elif name == 'keep_xml': cfg.keep_xml = value elif name == 'cflags': cfg.cflags = value elif name == 'flags': cfg.flags = value elif name == 'compiler_path': cfg.compiler_path = value else: print('\n%s entry was ignored' % name) # If no compiler path was set and we are using castxml, set the path # Here we overwrite the default configuration done in the cfg because # the xml_generator was set through the setter after the creation of a new # emppty configuration object. cfg.compiler_path = create_compiler_path( cfg.xml_generator, cfg.compiler_path) return cfg
[ "def", "load_xml_generator_configuration", "(", "configuration", ",", "*", "*", "defaults", ")", ":", "parser", "=", "configuration", "if", "utils", ".", "is_str", "(", "configuration", ")", ":", "parser", "=", "ConfigParser", "(", ")", "parser", ".", "read", "(", "configuration", ")", "# Create a new empty configuration", "cfg", "=", "xml_generator_configuration_t", "(", ")", "values", "=", "defaults", "if", "not", "values", ":", "values", "=", "{", "}", "if", "parser", ".", "has_section", "(", "'xml_generator'", ")", ":", "for", "name", ",", "value", "in", "parser", ".", "items", "(", "'xml_generator'", ")", ":", "if", "value", ".", "strip", "(", ")", ":", "values", "[", "name", "]", "=", "value", "for", "name", ",", "value", "in", "values", ".", "items", "(", ")", ":", "if", "isinstance", "(", "value", ",", "str", ")", ":", "value", "=", "value", ".", "strip", "(", ")", "if", "name", "==", "'gccxml_path'", ":", "cfg", ".", "gccxml_path", "=", "value", "if", "name", "==", "'xml_generator_path'", ":", "cfg", ".", "xml_generator_path", "=", "value", "elif", "name", "==", "'working_directory'", ":", "cfg", ".", "working_directory", "=", "value", "elif", "name", "==", "'include_paths'", ":", "for", "p", "in", "value", ".", "split", "(", "';'", ")", ":", "p", "=", "p", ".", "strip", "(", ")", "if", "p", ":", "cfg", ".", "include_paths", ".", "append", "(", "os", ".", "path", ".", "normpath", "(", "p", ")", ")", "elif", "name", "==", "'compiler'", ":", "cfg", ".", "compiler", "=", "value", "elif", "name", "==", "'xml_generator'", ":", "cfg", ".", "xml_generator", "=", "value", "elif", "name", "==", "'castxml_epic_version'", ":", "cfg", ".", "castxml_epic_version", "=", "int", "(", "value", ")", "elif", "name", "==", "'keep_xml'", ":", "cfg", ".", "keep_xml", "=", "value", "elif", "name", "==", "'cflags'", ":", "cfg", ".", "cflags", "=", "value", "elif", "name", "==", "'flags'", ":", "cfg", ".", "flags", "=", "value", "elif", "name", "==", "'compiler_path'", ":", "cfg", ".", "compiler_path", "=", "value", "else", ":", "print", "(", "'\\n%s entry was ignored'", "%", "name", ")", "# If no compiler path was set and we are using castxml, set the path", "# Here we overwrite the default configuration done in the cfg because", "# the xml_generator was set through the setter after the creation of a new", "# emppty configuration object.", "cfg", ".", "compiler_path", "=", "create_compiler_path", "(", "cfg", ".", "xml_generator", ",", "cfg", ".", "compiler_path", ")", "return", "cfg" ]
Loads CastXML or GCC-XML configuration. Args: configuration (string|configparser.ConfigParser): can be a string (file path to a configuration file) or instance of :class:`configparser.ConfigParser`. defaults: can be used to override single configuration values. Returns: :class:`.xml_generator_configuration_t`: a configuration object The file passed needs to be in a format that can be parsed by :class:`configparser.ConfigParser`. An example configuration file skeleton can be found `here <https://github.com/gccxml/pygccxml/blob/develop/ unittests/xml_generator.cfg>`_.
[ "Loads", "CastXML", "or", "GCC", "-", "XML", "configuration", "." ]
2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e
https://github.com/gccxml/pygccxml/blob/2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e/pygccxml/parser/config.py#L333-L410
train
236,132
gccxml/pygccxml
pygccxml/parser/config.py
create_compiler_path
def create_compiler_path(xml_generator, compiler_path): """ Try to guess a path for the compiler. If you want ot use a specific compiler, please provide the compiler path manually, as the guess may not be what you are expecting. Providing the path can be done by passing it as an argument (compiler_path) to the xml_generator_configuration_t() or by defining it in your pygccxml configuration file. """ if xml_generator == 'castxml' and compiler_path is None: if platform.system() == 'Windows': # Look for msvc p = subprocess.Popen( ['where', 'cl'], stdout=subprocess.PIPE, stderr=subprocess.PIPE) compiler_path = p.stdout.read().decode("utf-8").rstrip() p.wait() p.stdout.close() p.stderr.close() # No msvc found; look for mingw if compiler_path == '': p = subprocess.Popen( ['where', 'mingw'], stdout=subprocess.PIPE, stderr=subprocess.PIPE) compiler_path = p.stdout.read().decode("utf-8").rstrip() p.wait() p.stdout.close() p.stderr.close() else: # OS X or Linux # Look for clang first, then gcc p = subprocess.Popen( ['which', 'clang++'], stdout=subprocess.PIPE, stderr=subprocess.PIPE) compiler_path = p.stdout.read().decode("utf-8").rstrip() p.wait() p.stdout.close() p.stderr.close() # No clang found; use gcc if compiler_path == '': p = subprocess.Popen( ['which', 'c++'], stdout=subprocess.PIPE, stderr=subprocess.PIPE) compiler_path = p.stdout.read().decode("utf-8").rstrip() p.wait() p.stdout.close() p.stderr.close() if compiler_path == "": compiler_path = None return compiler_path
python
def create_compiler_path(xml_generator, compiler_path): """ Try to guess a path for the compiler. If you want ot use a specific compiler, please provide the compiler path manually, as the guess may not be what you are expecting. Providing the path can be done by passing it as an argument (compiler_path) to the xml_generator_configuration_t() or by defining it in your pygccxml configuration file. """ if xml_generator == 'castxml' and compiler_path is None: if platform.system() == 'Windows': # Look for msvc p = subprocess.Popen( ['where', 'cl'], stdout=subprocess.PIPE, stderr=subprocess.PIPE) compiler_path = p.stdout.read().decode("utf-8").rstrip() p.wait() p.stdout.close() p.stderr.close() # No msvc found; look for mingw if compiler_path == '': p = subprocess.Popen( ['where', 'mingw'], stdout=subprocess.PIPE, stderr=subprocess.PIPE) compiler_path = p.stdout.read().decode("utf-8").rstrip() p.wait() p.stdout.close() p.stderr.close() else: # OS X or Linux # Look for clang first, then gcc p = subprocess.Popen( ['which', 'clang++'], stdout=subprocess.PIPE, stderr=subprocess.PIPE) compiler_path = p.stdout.read().decode("utf-8").rstrip() p.wait() p.stdout.close() p.stderr.close() # No clang found; use gcc if compiler_path == '': p = subprocess.Popen( ['which', 'c++'], stdout=subprocess.PIPE, stderr=subprocess.PIPE) compiler_path = p.stdout.read().decode("utf-8").rstrip() p.wait() p.stdout.close() p.stderr.close() if compiler_path == "": compiler_path = None return compiler_path
[ "def", "create_compiler_path", "(", "xml_generator", ",", "compiler_path", ")", ":", "if", "xml_generator", "==", "'castxml'", "and", "compiler_path", "is", "None", ":", "if", "platform", ".", "system", "(", ")", "==", "'Windows'", ":", "# Look for msvc", "p", "=", "subprocess", ".", "Popen", "(", "[", "'where'", ",", "'cl'", "]", ",", "stdout", "=", "subprocess", ".", "PIPE", ",", "stderr", "=", "subprocess", ".", "PIPE", ")", "compiler_path", "=", "p", ".", "stdout", ".", "read", "(", ")", ".", "decode", "(", "\"utf-8\"", ")", ".", "rstrip", "(", ")", "p", ".", "wait", "(", ")", "p", ".", "stdout", ".", "close", "(", ")", "p", ".", "stderr", ".", "close", "(", ")", "# No msvc found; look for mingw", "if", "compiler_path", "==", "''", ":", "p", "=", "subprocess", ".", "Popen", "(", "[", "'where'", ",", "'mingw'", "]", ",", "stdout", "=", "subprocess", ".", "PIPE", ",", "stderr", "=", "subprocess", ".", "PIPE", ")", "compiler_path", "=", "p", ".", "stdout", ".", "read", "(", ")", ".", "decode", "(", "\"utf-8\"", ")", ".", "rstrip", "(", ")", "p", ".", "wait", "(", ")", "p", ".", "stdout", ".", "close", "(", ")", "p", ".", "stderr", ".", "close", "(", ")", "else", ":", "# OS X or Linux", "# Look for clang first, then gcc", "p", "=", "subprocess", ".", "Popen", "(", "[", "'which'", ",", "'clang++'", "]", ",", "stdout", "=", "subprocess", ".", "PIPE", ",", "stderr", "=", "subprocess", ".", "PIPE", ")", "compiler_path", "=", "p", ".", "stdout", ".", "read", "(", ")", ".", "decode", "(", "\"utf-8\"", ")", ".", "rstrip", "(", ")", "p", ".", "wait", "(", ")", "p", ".", "stdout", ".", "close", "(", ")", "p", ".", "stderr", ".", "close", "(", ")", "# No clang found; use gcc", "if", "compiler_path", "==", "''", ":", "p", "=", "subprocess", ".", "Popen", "(", "[", "'which'", ",", "'c++'", "]", ",", "stdout", "=", "subprocess", ".", "PIPE", ",", "stderr", "=", "subprocess", ".", "PIPE", ")", "compiler_path", "=", "p", ".", "stdout", ".", "read", "(", ")", ".", "decode", "(", "\"utf-8\"", ")", ".", "rstrip", "(", ")", "p", ".", "wait", "(", ")", "p", ".", "stdout", ".", "close", "(", ")", "p", ".", "stderr", ".", "close", "(", ")", "if", "compiler_path", "==", "\"\"", ":", "compiler_path", "=", "None", "return", "compiler_path" ]
Try to guess a path for the compiler. If you want ot use a specific compiler, please provide the compiler path manually, as the guess may not be what you are expecting. Providing the path can be done by passing it as an argument (compiler_path) to the xml_generator_configuration_t() or by defining it in your pygccxml configuration file.
[ "Try", "to", "guess", "a", "path", "for", "the", "compiler", "." ]
2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e
https://github.com/gccxml/pygccxml/blob/2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e/pygccxml/parser/config.py#L413-L471
train
236,133
gccxml/pygccxml
pygccxml/parser/config.py
parser_configuration_t.raise_on_wrong_settings
def raise_on_wrong_settings(self): """ Validates the configuration settings and raises RuntimeError on error """ self.__ensure_dir_exists(self.working_directory, 'working directory') for idir in self.include_paths: self.__ensure_dir_exists(idir, 'include directory') if self.__xml_generator not in ["castxml", "gccxml"]: msg = ('xml_generator("%s") should either be ' + '"castxml" or "gccxml".') % self.xml_generator raise RuntimeError(msg)
python
def raise_on_wrong_settings(self): """ Validates the configuration settings and raises RuntimeError on error """ self.__ensure_dir_exists(self.working_directory, 'working directory') for idir in self.include_paths: self.__ensure_dir_exists(idir, 'include directory') if self.__xml_generator not in ["castxml", "gccxml"]: msg = ('xml_generator("%s") should either be ' + '"castxml" or "gccxml".') % self.xml_generator raise RuntimeError(msg)
[ "def", "raise_on_wrong_settings", "(", "self", ")", ":", "self", ".", "__ensure_dir_exists", "(", "self", ".", "working_directory", ",", "'working directory'", ")", "for", "idir", "in", "self", ".", "include_paths", ":", "self", ".", "__ensure_dir_exists", "(", "idir", ",", "'include directory'", ")", "if", "self", ".", "__xml_generator", "not", "in", "[", "\"castxml\"", ",", "\"gccxml\"", "]", ":", "msg", "=", "(", "'xml_generator(\"%s\") should either be '", "+", "'\"castxml\" or \"gccxml\".'", ")", "%", "self", ".", "xml_generator", "raise", "RuntimeError", "(", "msg", ")" ]
Validates the configuration settings and raises RuntimeError on error
[ "Validates", "the", "configuration", "settings", "and", "raises", "RuntimeError", "on", "error" ]
2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e
https://github.com/gccxml/pygccxml/blob/2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e/pygccxml/parser/config.py#L210-L220
train
236,134
gccxml/pygccxml
pygccxml/declarations/declaration_utils.py
declaration_path
def declaration_path(decl): """ Returns a list of parent declarations names. Args: decl (declaration_t): declaration for which declaration path should be calculated. Returns: list[(str | basestring)]: list of names, where first item is the top parent name and last item the inputted declaration name. """ if not decl: return [] if not decl.cache.declaration_path: result = [decl.name] parent = decl.parent while parent: if parent.cache.declaration_path: result.reverse() decl.cache.declaration_path = parent.cache.declaration_path + \ result return decl.cache.declaration_path else: result.append(parent.name) parent = parent.parent result.reverse() decl.cache.declaration_path = result return result return decl.cache.declaration_path
python
def declaration_path(decl): """ Returns a list of parent declarations names. Args: decl (declaration_t): declaration for which declaration path should be calculated. Returns: list[(str | basestring)]: list of names, where first item is the top parent name and last item the inputted declaration name. """ if not decl: return [] if not decl.cache.declaration_path: result = [decl.name] parent = decl.parent while parent: if parent.cache.declaration_path: result.reverse() decl.cache.declaration_path = parent.cache.declaration_path + \ result return decl.cache.declaration_path else: result.append(parent.name) parent = parent.parent result.reverse() decl.cache.declaration_path = result return result return decl.cache.declaration_path
[ "def", "declaration_path", "(", "decl", ")", ":", "if", "not", "decl", ":", "return", "[", "]", "if", "not", "decl", ".", "cache", ".", "declaration_path", ":", "result", "=", "[", "decl", ".", "name", "]", "parent", "=", "decl", ".", "parent", "while", "parent", ":", "if", "parent", ".", "cache", ".", "declaration_path", ":", "result", ".", "reverse", "(", ")", "decl", ".", "cache", ".", "declaration_path", "=", "parent", ".", "cache", ".", "declaration_path", "+", "result", "return", "decl", ".", "cache", ".", "declaration_path", "else", ":", "result", ".", "append", "(", "parent", ".", "name", ")", "parent", "=", "parent", ".", "parent", "result", ".", "reverse", "(", ")", "decl", ".", "cache", ".", "declaration_path", "=", "result", "return", "result", "return", "decl", ".", "cache", ".", "declaration_path" ]
Returns a list of parent declarations names. Args: decl (declaration_t): declaration for which declaration path should be calculated. Returns: list[(str | basestring)]: list of names, where first item is the top parent name and last item the inputted declaration name.
[ "Returns", "a", "list", "of", "parent", "declarations", "names", "." ]
2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e
https://github.com/gccxml/pygccxml/blob/2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e/pygccxml/declarations/declaration_utils.py#L7-L39
train
236,135
gccxml/pygccxml
pygccxml/declarations/declaration_utils.py
partial_declaration_path
def partial_declaration_path(decl): """ Returns a list of parent declarations names without template arguments that have default value. Args: decl (declaration_t): declaration for which the partial declaration path should be calculated. Returns: list[(str | basestring)]: list of names, where first item is the top parent name and last item the inputted declaration name. """ # TODO: # If parent declaration cache already has declaration_path, reuse it for # calculation. if not decl: return [] if not decl.cache.partial_declaration_path: result = [decl.partial_name] parent = decl.parent while parent: if parent.cache.partial_declaration_path: result.reverse() decl.cache.partial_declaration_path \ = parent.cache.partial_declaration_path + result return decl.cache.partial_declaration_path else: result.append(parent.partial_name) parent = parent.parent result.reverse() decl.cache.partial_declaration_path = result return result return decl.cache.partial_declaration_path
python
def partial_declaration_path(decl): """ Returns a list of parent declarations names without template arguments that have default value. Args: decl (declaration_t): declaration for which the partial declaration path should be calculated. Returns: list[(str | basestring)]: list of names, where first item is the top parent name and last item the inputted declaration name. """ # TODO: # If parent declaration cache already has declaration_path, reuse it for # calculation. if not decl: return [] if not decl.cache.partial_declaration_path: result = [decl.partial_name] parent = decl.parent while parent: if parent.cache.partial_declaration_path: result.reverse() decl.cache.partial_declaration_path \ = parent.cache.partial_declaration_path + result return decl.cache.partial_declaration_path else: result.append(parent.partial_name) parent = parent.parent result.reverse() decl.cache.partial_declaration_path = result return result return decl.cache.partial_declaration_path
[ "def", "partial_declaration_path", "(", "decl", ")", ":", "# TODO:", "# If parent declaration cache already has declaration_path, reuse it for", "# calculation.", "if", "not", "decl", ":", "return", "[", "]", "if", "not", "decl", ".", "cache", ".", "partial_declaration_path", ":", "result", "=", "[", "decl", ".", "partial_name", "]", "parent", "=", "decl", ".", "parent", "while", "parent", ":", "if", "parent", ".", "cache", ".", "partial_declaration_path", ":", "result", ".", "reverse", "(", ")", "decl", ".", "cache", ".", "partial_declaration_path", "=", "parent", ".", "cache", ".", "partial_declaration_path", "+", "result", "return", "decl", ".", "cache", ".", "partial_declaration_path", "else", ":", "result", ".", "append", "(", "parent", ".", "partial_name", ")", "parent", "=", "parent", ".", "parent", "result", ".", "reverse", "(", ")", "decl", ".", "cache", ".", "partial_declaration_path", "=", "result", "return", "result", "return", "decl", ".", "cache", ".", "partial_declaration_path" ]
Returns a list of parent declarations names without template arguments that have default value. Args: decl (declaration_t): declaration for which the partial declaration path should be calculated. Returns: list[(str | basestring)]: list of names, where first item is the top parent name and last item the inputted declaration name.
[ "Returns", "a", "list", "of", "parent", "declarations", "names", "without", "template", "arguments", "that", "have", "default", "value", "." ]
2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e
https://github.com/gccxml/pygccxml/blob/2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e/pygccxml/declarations/declaration_utils.py#L42-L78
train
236,136
gccxml/pygccxml
pygccxml/declarations/declaration_utils.py
full_name
def full_name(decl, with_defaults=True): """ Returns declaration full qualified name. If `decl` belongs to anonymous namespace or class, the function will return C++ illegal qualified name. Args: decl (declaration_t): declaration for which the full qualified name should be calculated. Returns: list[(str | basestring)]: full name of the declaration. """ if None is decl: raise RuntimeError("Unable to generate full name for None object!") if with_defaults: if not decl.cache.full_name: path = declaration_path(decl) if path == [""]: # Declarations without names are allowed (for examples class # or struct instances). In this case set an empty name.. decl.cache.full_name = "" else: decl.cache.full_name = full_name_from_declaration_path(path) return decl.cache.full_name else: if not decl.cache.full_partial_name: path = partial_declaration_path(decl) if path == [""]: # Declarations without names are allowed (for examples class # or struct instances). In this case set an empty name. decl.cache.full_partial_name = "" else: decl.cache.full_partial_name = \ full_name_from_declaration_path(path) return decl.cache.full_partial_name
python
def full_name(decl, with_defaults=True): """ Returns declaration full qualified name. If `decl` belongs to anonymous namespace or class, the function will return C++ illegal qualified name. Args: decl (declaration_t): declaration for which the full qualified name should be calculated. Returns: list[(str | basestring)]: full name of the declaration. """ if None is decl: raise RuntimeError("Unable to generate full name for None object!") if with_defaults: if not decl.cache.full_name: path = declaration_path(decl) if path == [""]: # Declarations without names are allowed (for examples class # or struct instances). In this case set an empty name.. decl.cache.full_name = "" else: decl.cache.full_name = full_name_from_declaration_path(path) return decl.cache.full_name else: if not decl.cache.full_partial_name: path = partial_declaration_path(decl) if path == [""]: # Declarations without names are allowed (for examples class # or struct instances). In this case set an empty name. decl.cache.full_partial_name = "" else: decl.cache.full_partial_name = \ full_name_from_declaration_path(path) return decl.cache.full_partial_name
[ "def", "full_name", "(", "decl", ",", "with_defaults", "=", "True", ")", ":", "if", "None", "is", "decl", ":", "raise", "RuntimeError", "(", "\"Unable to generate full name for None object!\"", ")", "if", "with_defaults", ":", "if", "not", "decl", ".", "cache", ".", "full_name", ":", "path", "=", "declaration_path", "(", "decl", ")", "if", "path", "==", "[", "\"\"", "]", ":", "# Declarations without names are allowed (for examples class", "# or struct instances). In this case set an empty name..", "decl", ".", "cache", ".", "full_name", "=", "\"\"", "else", ":", "decl", ".", "cache", ".", "full_name", "=", "full_name_from_declaration_path", "(", "path", ")", "return", "decl", ".", "cache", ".", "full_name", "else", ":", "if", "not", "decl", ".", "cache", ".", "full_partial_name", ":", "path", "=", "partial_declaration_path", "(", "decl", ")", "if", "path", "==", "[", "\"\"", "]", ":", "# Declarations without names are allowed (for examples class", "# or struct instances). In this case set an empty name.", "decl", ".", "cache", ".", "full_partial_name", "=", "\"\"", "else", ":", "decl", ".", "cache", ".", "full_partial_name", "=", "full_name_from_declaration_path", "(", "path", ")", "return", "decl", ".", "cache", ".", "full_partial_name" ]
Returns declaration full qualified name. If `decl` belongs to anonymous namespace or class, the function will return C++ illegal qualified name. Args: decl (declaration_t): declaration for which the full qualified name should be calculated. Returns: list[(str | basestring)]: full name of the declaration.
[ "Returns", "declaration", "full", "qualified", "name", "." ]
2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e
https://github.com/gccxml/pygccxml/blob/2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e/pygccxml/declarations/declaration_utils.py#L90-L128
train
236,137
gccxml/pygccxml
pygccxml/declarations/declaration_utils.py
get_named_parent
def get_named_parent(decl): """ Returns a reference to a named parent declaration. Args: decl (declaration_t): the child declaration Returns: declaration_t: the declaration or None if not found. """ if not decl: return None parent = decl.parent while parent and (not parent.name or parent.name == '::'): parent = parent.parent return parent
python
def get_named_parent(decl): """ Returns a reference to a named parent declaration. Args: decl (declaration_t): the child declaration Returns: declaration_t: the declaration or None if not found. """ if not decl: return None parent = decl.parent while parent and (not parent.name or parent.name == '::'): parent = parent.parent return parent
[ "def", "get_named_parent", "(", "decl", ")", ":", "if", "not", "decl", ":", "return", "None", "parent", "=", "decl", ".", "parent", "while", "parent", "and", "(", "not", "parent", ".", "name", "or", "parent", ".", "name", "==", "'::'", ")", ":", "parent", "=", "parent", ".", "parent", "return", "parent" ]
Returns a reference to a named parent declaration. Args: decl (declaration_t): the child declaration Returns: declaration_t: the declaration or None if not found.
[ "Returns", "a", "reference", "to", "a", "named", "parent", "declaration", "." ]
2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e
https://github.com/gccxml/pygccxml/blob/2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e/pygccxml/declarations/declaration_utils.py#L131-L149
train
236,138
gccxml/pygccxml
pygccxml/declarations/decl_printer.py
print_declarations
def print_declarations( decls, detailed=True, recursive=True, writer=lambda x: sys.stdout.write(x + os.linesep), verbose=True): """ print declarations tree rooted at each of the included nodes. :param decls: either a single :class:declaration_t object or list of :class:declaration_t objects """ prn = decl_printer_t(0, detailed, recursive, writer, verbose=verbose) if not isinstance(decls, list): decls = [decls] for d in decls: prn.level = 0 prn.instance = d algorithm.apply_visitor(prn, d)
python
def print_declarations( decls, detailed=True, recursive=True, writer=lambda x: sys.stdout.write(x + os.linesep), verbose=True): """ print declarations tree rooted at each of the included nodes. :param decls: either a single :class:declaration_t object or list of :class:declaration_t objects """ prn = decl_printer_t(0, detailed, recursive, writer, verbose=verbose) if not isinstance(decls, list): decls = [decls] for d in decls: prn.level = 0 prn.instance = d algorithm.apply_visitor(prn, d)
[ "def", "print_declarations", "(", "decls", ",", "detailed", "=", "True", ",", "recursive", "=", "True", ",", "writer", "=", "lambda", "x", ":", "sys", ".", "stdout", ".", "write", "(", "x", "+", "os", ".", "linesep", ")", ",", "verbose", "=", "True", ")", ":", "prn", "=", "decl_printer_t", "(", "0", ",", "detailed", ",", "recursive", ",", "writer", ",", "verbose", "=", "verbose", ")", "if", "not", "isinstance", "(", "decls", ",", "list", ")", ":", "decls", "=", "[", "decls", "]", "for", "d", "in", "decls", ":", "prn", ".", "level", "=", "0", "prn", ".", "instance", "=", "d", "algorithm", ".", "apply_visitor", "(", "prn", ",", "d", ")" ]
print declarations tree rooted at each of the included nodes. :param decls: either a single :class:declaration_t object or list of :class:declaration_t objects
[ "print", "declarations", "tree", "rooted", "at", "each", "of", "the", "included", "nodes", "." ]
2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e
https://github.com/gccxml/pygccxml/blob/2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e/pygccxml/declarations/decl_printer.py#L434-L452
train
236,139
gccxml/pygccxml
pygccxml/declarations/decl_printer.py
dump_declarations
def dump_declarations(declarations, file_path): """ Dump declarations tree rooted at each of the included nodes to the file :param declarations: either a single :class:declaration_t object or a list of :class:declaration_t objects :param file_path: path to a file """ with open(file_path, "w+") as f: print_declarations(declarations, writer=f.write)
python
def dump_declarations(declarations, file_path): """ Dump declarations tree rooted at each of the included nodes to the file :param declarations: either a single :class:declaration_t object or a list of :class:declaration_t objects :param file_path: path to a file """ with open(file_path, "w+") as f: print_declarations(declarations, writer=f.write)
[ "def", "dump_declarations", "(", "declarations", ",", "file_path", ")", ":", "with", "open", "(", "file_path", ",", "\"w+\"", ")", "as", "f", ":", "print_declarations", "(", "declarations", ",", "writer", "=", "f", ".", "write", ")" ]
Dump declarations tree rooted at each of the included nodes to the file :param declarations: either a single :class:declaration_t object or a list of :class:declaration_t objects :param file_path: path to a file
[ "Dump", "declarations", "tree", "rooted", "at", "each", "of", "the", "included", "nodes", "to", "the", "file" ]
2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e
https://github.com/gccxml/pygccxml/blob/2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e/pygccxml/declarations/decl_printer.py#L455-L466
train
236,140
gccxml/pygccxml
pygccxml/parser/source_reader.py
source_reader_t.__add_symbols
def __add_symbols(self, cmd): """ Add all additional defined and undefined symbols. """ if self.__config.define_symbols: symbols = self.__config.define_symbols cmd.append(''.join( [' -D"%s"' % def_symbol for def_symbol in symbols])) if self.__config.undefine_symbols: un_symbols = self.__config.undefine_symbols cmd.append(''.join( [' -U"%s"' % undef_symbol for undef_symbol in un_symbols])) return cmd
python
def __add_symbols(self, cmd): """ Add all additional defined and undefined symbols. """ if self.__config.define_symbols: symbols = self.__config.define_symbols cmd.append(''.join( [' -D"%s"' % def_symbol for def_symbol in symbols])) if self.__config.undefine_symbols: un_symbols = self.__config.undefine_symbols cmd.append(''.join( [' -U"%s"' % undef_symbol for undef_symbol in un_symbols])) return cmd
[ "def", "__add_symbols", "(", "self", ",", "cmd", ")", ":", "if", "self", ".", "__config", ".", "define_symbols", ":", "symbols", "=", "self", ".", "__config", ".", "define_symbols", "cmd", ".", "append", "(", "''", ".", "join", "(", "[", "' -D\"%s\"'", "%", "def_symbol", "for", "def_symbol", "in", "symbols", "]", ")", ")", "if", "self", ".", "__config", ".", "undefine_symbols", ":", "un_symbols", "=", "self", ".", "__config", ".", "undefine_symbols", "cmd", ".", "append", "(", "''", ".", "join", "(", "[", "' -U\"%s\"'", "%", "undef_symbol", "for", "undef_symbol", "in", "un_symbols", "]", ")", ")", "return", "cmd" ]
Add all additional defined and undefined symbols.
[ "Add", "all", "additional", "defined", "and", "undefined", "symbols", "." ]
2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e
https://github.com/gccxml/pygccxml/blob/2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e/pygccxml/parser/source_reader.py#L183-L199
train
236,141
gccxml/pygccxml
pygccxml/parser/source_reader.py
source_reader_t.create_xml_file
def create_xml_file(self, source_file, destination=None): """ This method will generate a xml file using an external tool. The method will return the file path of the generated xml file. :param source_file: path to the source file that should be parsed. :type source_file: str :param destination: if given, will be used as target file path for the xml generator. :type destination: str :rtype: path to xml file. """ xml_file = destination # If file specified, remove it to start else create new file name if xml_file: utils.remove_file_no_raise(xml_file, self.__config) else: xml_file = utils.create_temp_file_name(suffix='.xml') ffname = source_file if not os.path.isabs(ffname): ffname = self.__file_full_name(source_file) command_line = self.__create_command_line(ffname, xml_file) process = subprocess.Popen( args=command_line, shell=True, stdout=subprocess.PIPE) try: results = [] while process.poll() is None: line = process.stdout.readline() if line.strip(): results.append(line.rstrip()) for line in process.stdout.readlines(): if line.strip(): results.append(line.rstrip()) exit_status = process.returncode msg = os.linesep.join([str(s) for s in results]) if self.__config.ignore_gccxml_output: if not os.path.isfile(xml_file): raise RuntimeError( "Error occurred while running " + self.__config.xml_generator.upper() + ": %s status:%s" % (msg, exit_status)) else: if msg or exit_status or not \ os.path.isfile(xml_file): if not os.path.isfile(xml_file): raise RuntimeError( "Error occurred while running " + self.__config.xml_generator.upper() + " xml file does not exist") else: raise RuntimeError( "Error occurred while running " + self.__config.xml_generator.upper() + ": %s status:%s" % (msg, exit_status)) except Exception: utils.remove_file_no_raise(xml_file, self.__config) raise finally: process.wait() process.stdout.close() return xml_file
python
def create_xml_file(self, source_file, destination=None): """ This method will generate a xml file using an external tool. The method will return the file path of the generated xml file. :param source_file: path to the source file that should be parsed. :type source_file: str :param destination: if given, will be used as target file path for the xml generator. :type destination: str :rtype: path to xml file. """ xml_file = destination # If file specified, remove it to start else create new file name if xml_file: utils.remove_file_no_raise(xml_file, self.__config) else: xml_file = utils.create_temp_file_name(suffix='.xml') ffname = source_file if not os.path.isabs(ffname): ffname = self.__file_full_name(source_file) command_line = self.__create_command_line(ffname, xml_file) process = subprocess.Popen( args=command_line, shell=True, stdout=subprocess.PIPE) try: results = [] while process.poll() is None: line = process.stdout.readline() if line.strip(): results.append(line.rstrip()) for line in process.stdout.readlines(): if line.strip(): results.append(line.rstrip()) exit_status = process.returncode msg = os.linesep.join([str(s) for s in results]) if self.__config.ignore_gccxml_output: if not os.path.isfile(xml_file): raise RuntimeError( "Error occurred while running " + self.__config.xml_generator.upper() + ": %s status:%s" % (msg, exit_status)) else: if msg or exit_status or not \ os.path.isfile(xml_file): if not os.path.isfile(xml_file): raise RuntimeError( "Error occurred while running " + self.__config.xml_generator.upper() + " xml file does not exist") else: raise RuntimeError( "Error occurred while running " + self.__config.xml_generator.upper() + ": %s status:%s" % (msg, exit_status)) except Exception: utils.remove_file_no_raise(xml_file, self.__config) raise finally: process.wait() process.stdout.close() return xml_file
[ "def", "create_xml_file", "(", "self", ",", "source_file", ",", "destination", "=", "None", ")", ":", "xml_file", "=", "destination", "# If file specified, remove it to start else create new file name", "if", "xml_file", ":", "utils", ".", "remove_file_no_raise", "(", "xml_file", ",", "self", ".", "__config", ")", "else", ":", "xml_file", "=", "utils", ".", "create_temp_file_name", "(", "suffix", "=", "'.xml'", ")", "ffname", "=", "source_file", "if", "not", "os", ".", "path", ".", "isabs", "(", "ffname", ")", ":", "ffname", "=", "self", ".", "__file_full_name", "(", "source_file", ")", "command_line", "=", "self", ".", "__create_command_line", "(", "ffname", ",", "xml_file", ")", "process", "=", "subprocess", ".", "Popen", "(", "args", "=", "command_line", ",", "shell", "=", "True", ",", "stdout", "=", "subprocess", ".", "PIPE", ")", "try", ":", "results", "=", "[", "]", "while", "process", ".", "poll", "(", ")", "is", "None", ":", "line", "=", "process", ".", "stdout", ".", "readline", "(", ")", "if", "line", ".", "strip", "(", ")", ":", "results", ".", "append", "(", "line", ".", "rstrip", "(", ")", ")", "for", "line", "in", "process", ".", "stdout", ".", "readlines", "(", ")", ":", "if", "line", ".", "strip", "(", ")", ":", "results", ".", "append", "(", "line", ".", "rstrip", "(", ")", ")", "exit_status", "=", "process", ".", "returncode", "msg", "=", "os", ".", "linesep", ".", "join", "(", "[", "str", "(", "s", ")", "for", "s", "in", "results", "]", ")", "if", "self", ".", "__config", ".", "ignore_gccxml_output", ":", "if", "not", "os", ".", "path", ".", "isfile", "(", "xml_file", ")", ":", "raise", "RuntimeError", "(", "\"Error occurred while running \"", "+", "self", ".", "__config", ".", "xml_generator", ".", "upper", "(", ")", "+", "\": %s status:%s\"", "%", "(", "msg", ",", "exit_status", ")", ")", "else", ":", "if", "msg", "or", "exit_status", "or", "not", "os", ".", "path", ".", "isfile", "(", "xml_file", ")", ":", "if", "not", "os", ".", "path", ".", "isfile", "(", "xml_file", ")", ":", "raise", "RuntimeError", "(", "\"Error occurred while running \"", "+", "self", ".", "__config", ".", "xml_generator", ".", "upper", "(", ")", "+", "\" xml file does not exist\"", ")", "else", ":", "raise", "RuntimeError", "(", "\"Error occurred while running \"", "+", "self", ".", "__config", ".", "xml_generator", ".", "upper", "(", ")", "+", "\": %s status:%s\"", "%", "(", "msg", ",", "exit_status", ")", ")", "except", "Exception", ":", "utils", ".", "remove_file_no_raise", "(", "xml_file", ",", "self", ".", "__config", ")", "raise", "finally", ":", "process", ".", "wait", "(", ")", "process", ".", "stdout", ".", "close", "(", ")", "return", "xml_file" ]
This method will generate a xml file using an external tool. The method will return the file path of the generated xml file. :param source_file: path to the source file that should be parsed. :type source_file: str :param destination: if given, will be used as target file path for the xml generator. :type destination: str :rtype: path to xml file.
[ "This", "method", "will", "generate", "a", "xml", "file", "using", "an", "external", "tool", "." ]
2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e
https://github.com/gccxml/pygccxml/blob/2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e/pygccxml/parser/source_reader.py#L201-L273
train
236,142
gccxml/pygccxml
pygccxml/parser/source_reader.py
source_reader_t.create_xml_file_from_string
def create_xml_file_from_string(self, content, destination=None): """ Creates XML file from text. :param content: C++ source code :type content: str :param destination: file name for xml file :type destination: str :rtype: returns file name of xml file """ header_file = utils.create_temp_file_name(suffix='.h') try: with open(header_file, "w+") as header: header.write(content) xml_file = self.create_xml_file(header_file, destination) finally: utils.remove_file_no_raise(header_file, self.__config) return xml_file
python
def create_xml_file_from_string(self, content, destination=None): """ Creates XML file from text. :param content: C++ source code :type content: str :param destination: file name for xml file :type destination: str :rtype: returns file name of xml file """ header_file = utils.create_temp_file_name(suffix='.h') try: with open(header_file, "w+") as header: header.write(content) xml_file = self.create_xml_file(header_file, destination) finally: utils.remove_file_no_raise(header_file, self.__config) return xml_file
[ "def", "create_xml_file_from_string", "(", "self", ",", "content", ",", "destination", "=", "None", ")", ":", "header_file", "=", "utils", ".", "create_temp_file_name", "(", "suffix", "=", "'.h'", ")", "try", ":", "with", "open", "(", "header_file", ",", "\"w+\"", ")", "as", "header", ":", "header", ".", "write", "(", "content", ")", "xml_file", "=", "self", ".", "create_xml_file", "(", "header_file", ",", "destination", ")", "finally", ":", "utils", ".", "remove_file_no_raise", "(", "header_file", ",", "self", ".", "__config", ")", "return", "xml_file" ]
Creates XML file from text. :param content: C++ source code :type content: str :param destination: file name for xml file :type destination: str :rtype: returns file name of xml file
[ "Creates", "XML", "file", "from", "text", "." ]
2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e
https://github.com/gccxml/pygccxml/blob/2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e/pygccxml/parser/source_reader.py#L275-L295
train
236,143
gccxml/pygccxml
pygccxml/parser/source_reader.py
source_reader_t.read_cpp_source_file
def read_cpp_source_file(self, source_file): """ Reads C++ source file and returns declarations tree :param source_file: path to C++ source file :type source_file: str """ xml_file = '' try: ffname = self.__file_full_name(source_file) self.logger.debug("Reading source file: [%s].", ffname) decls = self.__dcache.cached_value(ffname, self.__config) if not decls: self.logger.debug( "File has not been found in cache, parsing...") xml_file = self.create_xml_file(ffname) decls, files = self.__parse_xml_file(xml_file) self.__dcache.update( ffname, self.__config, decls, files) else: self.logger.debug(( "File has not been changed, reading declarations " + "from cache.")) except Exception: if xml_file: utils.remove_file_no_raise(xml_file, self.__config) raise if xml_file: utils.remove_file_no_raise(xml_file, self.__config) return decls
python
def read_cpp_source_file(self, source_file): """ Reads C++ source file and returns declarations tree :param source_file: path to C++ source file :type source_file: str """ xml_file = '' try: ffname = self.__file_full_name(source_file) self.logger.debug("Reading source file: [%s].", ffname) decls = self.__dcache.cached_value(ffname, self.__config) if not decls: self.logger.debug( "File has not been found in cache, parsing...") xml_file = self.create_xml_file(ffname) decls, files = self.__parse_xml_file(xml_file) self.__dcache.update( ffname, self.__config, decls, files) else: self.logger.debug(( "File has not been changed, reading declarations " + "from cache.")) except Exception: if xml_file: utils.remove_file_no_raise(xml_file, self.__config) raise if xml_file: utils.remove_file_no_raise(xml_file, self.__config) return decls
[ "def", "read_cpp_source_file", "(", "self", ",", "source_file", ")", ":", "xml_file", "=", "''", "try", ":", "ffname", "=", "self", ".", "__file_full_name", "(", "source_file", ")", "self", ".", "logger", ".", "debug", "(", "\"Reading source file: [%s].\"", ",", "ffname", ")", "decls", "=", "self", ".", "__dcache", ".", "cached_value", "(", "ffname", ",", "self", ".", "__config", ")", "if", "not", "decls", ":", "self", ".", "logger", ".", "debug", "(", "\"File has not been found in cache, parsing...\"", ")", "xml_file", "=", "self", ".", "create_xml_file", "(", "ffname", ")", "decls", ",", "files", "=", "self", ".", "__parse_xml_file", "(", "xml_file", ")", "self", ".", "__dcache", ".", "update", "(", "ffname", ",", "self", ".", "__config", ",", "decls", ",", "files", ")", "else", ":", "self", ".", "logger", ".", "debug", "(", "(", "\"File has not been changed, reading declarations \"", "+", "\"from cache.\"", ")", ")", "except", "Exception", ":", "if", "xml_file", ":", "utils", ".", "remove_file_no_raise", "(", "xml_file", ",", "self", ".", "__config", ")", "raise", "if", "xml_file", ":", "utils", ".", "remove_file_no_raise", "(", "xml_file", ",", "self", ".", "__config", ")", "return", "decls" ]
Reads C++ source file and returns declarations tree :param source_file: path to C++ source file :type source_file: str
[ "Reads", "C", "++", "source", "file", "and", "returns", "declarations", "tree" ]
2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e
https://github.com/gccxml/pygccxml/blob/2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e/pygccxml/parser/source_reader.py#L300-L332
train
236,144
gccxml/pygccxml
pygccxml/parser/source_reader.py
source_reader_t.read_xml_file
def read_xml_file(self, xml_file): """ Read generated XML file. :param xml_file: path to xml file :type xml_file: str :rtype: declarations tree """ assert self.__config is not None ffname = self.__file_full_name(xml_file) self.logger.debug("Reading xml file: [%s]", xml_file) decls = self.__dcache.cached_value(ffname, self.__config) if not decls: self.logger.debug("File has not been found in cache, parsing...") decls, _ = self.__parse_xml_file(ffname) self.__dcache.update(ffname, self.__config, decls, []) else: self.logger.debug( "File has not been changed, reading declarations from cache.") return decls
python
def read_xml_file(self, xml_file): """ Read generated XML file. :param xml_file: path to xml file :type xml_file: str :rtype: declarations tree """ assert self.__config is not None ffname = self.__file_full_name(xml_file) self.logger.debug("Reading xml file: [%s]", xml_file) decls = self.__dcache.cached_value(ffname, self.__config) if not decls: self.logger.debug("File has not been found in cache, parsing...") decls, _ = self.__parse_xml_file(ffname) self.__dcache.update(ffname, self.__config, decls, []) else: self.logger.debug( "File has not been changed, reading declarations from cache.") return decls
[ "def", "read_xml_file", "(", "self", ",", "xml_file", ")", ":", "assert", "self", ".", "__config", "is", "not", "None", "ffname", "=", "self", ".", "__file_full_name", "(", "xml_file", ")", "self", ".", "logger", ".", "debug", "(", "\"Reading xml file: [%s]\"", ",", "xml_file", ")", "decls", "=", "self", ".", "__dcache", ".", "cached_value", "(", "ffname", ",", "self", ".", "__config", ")", "if", "not", "decls", ":", "self", ".", "logger", ".", "debug", "(", "\"File has not been found in cache, parsing...\"", ")", "decls", ",", "_", "=", "self", ".", "__parse_xml_file", "(", "ffname", ")", "self", ".", "__dcache", ".", "update", "(", "ffname", ",", "self", ".", "__config", ",", "decls", ",", "[", "]", ")", "else", ":", "self", ".", "logger", ".", "debug", "(", "\"File has not been changed, reading declarations from cache.\"", ")", "return", "decls" ]
Read generated XML file. :param xml_file: path to xml file :type xml_file: str :rtype: declarations tree
[ "Read", "generated", "XML", "file", "." ]
2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e
https://github.com/gccxml/pygccxml/blob/2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e/pygccxml/parser/source_reader.py#L334-L358
train
236,145
gccxml/pygccxml
pygccxml/parser/source_reader.py
source_reader_t.read_string
def read_string(self, content): """ Reads a Python string that contains C++ code, and return the declarations tree. """ header_file = utils.create_temp_file_name(suffix='.h') with open(header_file, "w+") as f: f.write(content) try: decls = self.read_file(header_file) except Exception: utils.remove_file_no_raise(header_file, self.__config) raise utils.remove_file_no_raise(header_file, self.__config) return decls
python
def read_string(self, content): """ Reads a Python string that contains C++ code, and return the declarations tree. """ header_file = utils.create_temp_file_name(suffix='.h') with open(header_file, "w+") as f: f.write(content) try: decls = self.read_file(header_file) except Exception: utils.remove_file_no_raise(header_file, self.__config) raise utils.remove_file_no_raise(header_file, self.__config) return decls
[ "def", "read_string", "(", "self", ",", "content", ")", ":", "header_file", "=", "utils", ".", "create_temp_file_name", "(", "suffix", "=", "'.h'", ")", "with", "open", "(", "header_file", ",", "\"w+\"", ")", "as", "f", ":", "f", ".", "write", "(", "content", ")", "try", ":", "decls", "=", "self", ".", "read_file", "(", "header_file", ")", "except", "Exception", ":", "utils", ".", "remove_file_no_raise", "(", "header_file", ",", "self", ".", "__config", ")", "raise", "utils", ".", "remove_file_no_raise", "(", "header_file", ",", "self", ".", "__config", ")", "return", "decls" ]
Reads a Python string that contains C++ code, and return the declarations tree.
[ "Reads", "a", "Python", "string", "that", "contains", "C", "++", "code", "and", "return", "the", "declarations", "tree", "." ]
2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e
https://github.com/gccxml/pygccxml/blob/2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e/pygccxml/parser/source_reader.py#L360-L378
train
236,146
gccxml/pygccxml
pygccxml/declarations/algorithm.py
apply_visitor
def apply_visitor(visitor, decl_inst): """ Applies a visitor on declaration instance. :param visitor: instance :type visitor: :class:`type_visitor_t` or :class:`decl_visitor_t` """ fname = 'visit_' + \ decl_inst.__class__.__name__[:-2] # removing '_t' from class name if not hasattr(visitor, fname): raise runtime_errors.visit_function_has_not_been_found_t( visitor, decl_inst) return getattr(visitor, fname)()
python
def apply_visitor(visitor, decl_inst): """ Applies a visitor on declaration instance. :param visitor: instance :type visitor: :class:`type_visitor_t` or :class:`decl_visitor_t` """ fname = 'visit_' + \ decl_inst.__class__.__name__[:-2] # removing '_t' from class name if not hasattr(visitor, fname): raise runtime_errors.visit_function_has_not_been_found_t( visitor, decl_inst) return getattr(visitor, fname)()
[ "def", "apply_visitor", "(", "visitor", ",", "decl_inst", ")", ":", "fname", "=", "'visit_'", "+", "decl_inst", ".", "__class__", ".", "__name__", "[", ":", "-", "2", "]", "# removing '_t' from class name", "if", "not", "hasattr", "(", "visitor", ",", "fname", ")", ":", "raise", "runtime_errors", ".", "visit_function_has_not_been_found_t", "(", "visitor", ",", "decl_inst", ")", "return", "getattr", "(", "visitor", ",", "fname", ")", "(", ")" ]
Applies a visitor on declaration instance. :param visitor: instance :type visitor: :class:`type_visitor_t` or :class:`decl_visitor_t`
[ "Applies", "a", "visitor", "on", "declaration", "instance", "." ]
2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e
https://github.com/gccxml/pygccxml/blob/2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e/pygccxml/declarations/algorithm.py#L73-L87
train
236,147
gccxml/pygccxml
pygccxml/declarations/algorithm.py
match_declaration_t.does_match_exist
def does_match_exist(self, inst): """ Returns True if inst does match one of specified criteria. :param inst: declaration instance :type inst: :class:`declaration_t` :rtype: bool """ answer = True if self._decl_type is not None: answer &= isinstance(inst, self._decl_type) if self.name is not None: answer &= inst.name == self.name if self.parent is not None: answer &= self.parent is inst.parent if self.fullname is not None: if inst.name: answer &= self.fullname == declaration_utils.full_name(inst) else: answer = False return answer
python
def does_match_exist(self, inst): """ Returns True if inst does match one of specified criteria. :param inst: declaration instance :type inst: :class:`declaration_t` :rtype: bool """ answer = True if self._decl_type is not None: answer &= isinstance(inst, self._decl_type) if self.name is not None: answer &= inst.name == self.name if self.parent is not None: answer &= self.parent is inst.parent if self.fullname is not None: if inst.name: answer &= self.fullname == declaration_utils.full_name(inst) else: answer = False return answer
[ "def", "does_match_exist", "(", "self", ",", "inst", ")", ":", "answer", "=", "True", "if", "self", ".", "_decl_type", "is", "not", "None", ":", "answer", "&=", "isinstance", "(", "inst", ",", "self", ".", "_decl_type", ")", "if", "self", ".", "name", "is", "not", "None", ":", "answer", "&=", "inst", ".", "name", "==", "self", ".", "name", "if", "self", ".", "parent", "is", "not", "None", ":", "answer", "&=", "self", ".", "parent", "is", "inst", ".", "parent", "if", "self", ".", "fullname", "is", "not", "None", ":", "if", "inst", ".", "name", ":", "answer", "&=", "self", ".", "fullname", "==", "declaration_utils", ".", "full_name", "(", "inst", ")", "else", ":", "answer", "=", "False", "return", "answer" ]
Returns True if inst does match one of specified criteria. :param inst: declaration instance :type inst: :class:`declaration_t` :rtype: bool
[ "Returns", "True", "if", "inst", "does", "match", "one", "of", "specified", "criteria", "." ]
2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e
https://github.com/gccxml/pygccxml/blob/2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e/pygccxml/declarations/algorithm.py#L37-L60
train
236,148
gccxml/pygccxml
pygccxml/declarations/declaration.py
declaration_t.partial_name
def partial_name(self): """ Declaration name, without template default arguments. Right now std containers is the only classes that support this functionality. """ if None is self._partial_name: self._partial_name = self._get_partial_name_impl() return self._partial_name
python
def partial_name(self): """ Declaration name, without template default arguments. Right now std containers is the only classes that support this functionality. """ if None is self._partial_name: self._partial_name = self._get_partial_name_impl() return self._partial_name
[ "def", "partial_name", "(", "self", ")", ":", "if", "None", "is", "self", ".", "_partial_name", ":", "self", ".", "_partial_name", "=", "self", ".", "_get_partial_name_impl", "(", ")", "return", "self", ".", "_partial_name" ]
Declaration name, without template default arguments. Right now std containers is the only classes that support this functionality.
[ "Declaration", "name", "without", "template", "default", "arguments", "." ]
2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e
https://github.com/gccxml/pygccxml/blob/2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e/pygccxml/declarations/declaration.py#L175-L187
train
236,149
gccxml/pygccxml
pygccxml/declarations/declaration.py
declaration_t.top_parent
def top_parent(self): """ Reference to top parent declaration. @type: declaration_t """ parent = self.parent while parent is not None: if parent.parent is None: return parent else: parent = parent.parent return self
python
def top_parent(self): """ Reference to top parent declaration. @type: declaration_t """ parent = self.parent while parent is not None: if parent.parent is None: return parent else: parent = parent.parent return self
[ "def", "top_parent", "(", "self", ")", ":", "parent", "=", "self", ".", "parent", "while", "parent", "is", "not", "None", ":", "if", "parent", ".", "parent", "is", "None", ":", "return", "parent", "else", ":", "parent", "=", "parent", ".", "parent", "return", "self" ]
Reference to top parent declaration. @type: declaration_t
[ "Reference", "to", "top", "parent", "declaration", "." ]
2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e
https://github.com/gccxml/pygccxml/blob/2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e/pygccxml/declarations/declaration.py#L208-L221
train
236,150
gccxml/pygccxml
pygccxml/declarations/calldef.py
argument_t.clone
def clone(self, **keywd): """constructs new argument_t instance return argument_t( name=keywd.get('name', self.name), decl_type=keywd.get('decl_type', self.decl_type), default_value=keywd.get('default_value', self.default_value), attributes=keywd.get('attributes', self.attributes )) """ return argument_t( name=keywd.get('name', self.name), decl_type=keywd.get('decl_type', self.decl_type), default_value=keywd.get('default_value', self.default_value), attributes=keywd.get('attributes', self.attributes))
python
def clone(self, **keywd): """constructs new argument_t instance return argument_t( name=keywd.get('name', self.name), decl_type=keywd.get('decl_type', self.decl_type), default_value=keywd.get('default_value', self.default_value), attributes=keywd.get('attributes', self.attributes )) """ return argument_t( name=keywd.get('name', self.name), decl_type=keywd.get('decl_type', self.decl_type), default_value=keywd.get('default_value', self.default_value), attributes=keywd.get('attributes', self.attributes))
[ "def", "clone", "(", "self", ",", "*", "*", "keywd", ")", ":", "return", "argument_t", "(", "name", "=", "keywd", ".", "get", "(", "'name'", ",", "self", ".", "name", ")", ",", "decl_type", "=", "keywd", ".", "get", "(", "'decl_type'", ",", "self", ".", "decl_type", ")", ",", "default_value", "=", "keywd", ".", "get", "(", "'default_value'", ",", "self", ".", "default_value", ")", ",", "attributes", "=", "keywd", ".", "get", "(", "'attributes'", ",", "self", ".", "attributes", ")", ")" ]
constructs new argument_t instance return argument_t( name=keywd.get('name', self.name), decl_type=keywd.get('decl_type', self.decl_type), default_value=keywd.get('default_value', self.default_value), attributes=keywd.get('attributes', self.attributes ))
[ "constructs", "new", "argument_t", "instance" ]
2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e
https://github.com/gccxml/pygccxml/blob/2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e/pygccxml/declarations/calldef.py#L44-L58
train
236,151
gccxml/pygccxml
pygccxml/declarations/calldef.py
calldef_t.required_args
def required_args(self): """list of all required arguments""" r_args = [] for arg in self.arguments: if not arg.default_value: r_args.append(arg) else: break return r_args
python
def required_args(self): """list of all required arguments""" r_args = [] for arg in self.arguments: if not arg.default_value: r_args.append(arg) else: break return r_args
[ "def", "required_args", "(", "self", ")", ":", "r_args", "=", "[", "]", "for", "arg", "in", "self", ".", "arguments", ":", "if", "not", "arg", ".", "default_value", ":", "r_args", ".", "append", "(", "arg", ")", "else", ":", "break", "return", "r_args" ]
list of all required arguments
[ "list", "of", "all", "required", "arguments" ]
2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e
https://github.com/gccxml/pygccxml/blob/2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e/pygccxml/declarations/calldef.py#L224-L232
train
236,152
gccxml/pygccxml
pygccxml/declarations/calldef.py
calldef_t.overloads
def overloads(self): """A list of overloaded "callables" (i.e. other callables with the same name within the same scope. @type: list of :class:`calldef_t` """ if not self.parent: return [] # finding all functions with the same name return self.parent.calldefs( name=self.name, function=lambda decl: decl is not self, allow_empty=True, recursive=False)
python
def overloads(self): """A list of overloaded "callables" (i.e. other callables with the same name within the same scope. @type: list of :class:`calldef_t` """ if not self.parent: return [] # finding all functions with the same name return self.parent.calldefs( name=self.name, function=lambda decl: decl is not self, allow_empty=True, recursive=False)
[ "def", "overloads", "(", "self", ")", ":", "if", "not", "self", ".", "parent", ":", "return", "[", "]", "# finding all functions with the same name", "return", "self", ".", "parent", ".", "calldefs", "(", "name", "=", "self", ".", "name", ",", "function", "=", "lambda", "decl", ":", "decl", "is", "not", "self", ",", "allow_empty", "=", "True", ",", "recursive", "=", "False", ")" ]
A list of overloaded "callables" (i.e. other callables with the same name within the same scope. @type: list of :class:`calldef_t`
[ "A", "list", "of", "overloaded", "callables", "(", "i", ".", "e", ".", "other", "callables", "with", "the", "same", "name", "within", "the", "same", "scope", "." ]
2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e
https://github.com/gccxml/pygccxml/blob/2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e/pygccxml/declarations/calldef.py#L273-L286
train
236,153
gccxml/pygccxml
pygccxml/parser/declarations_cache.py
file_signature
def file_signature(filename): """ Return a signature for a file. """ if not os.path.isfile(filename): return None if not os.path.exists(filename): return None # Duplicate auto-generated files can be recognized with the sha1 hash. sig = hashlib.sha1() with open(filename, "rb") as f: buf = f.read() sig.update(buf) return sig.hexdigest()
python
def file_signature(filename): """ Return a signature for a file. """ if not os.path.isfile(filename): return None if not os.path.exists(filename): return None # Duplicate auto-generated files can be recognized with the sha1 hash. sig = hashlib.sha1() with open(filename, "rb") as f: buf = f.read() sig.update(buf) return sig.hexdigest()
[ "def", "file_signature", "(", "filename", ")", ":", "if", "not", "os", ".", "path", ".", "isfile", "(", "filename", ")", ":", "return", "None", "if", "not", "os", ".", "path", ".", "exists", "(", "filename", ")", ":", "return", "None", "# Duplicate auto-generated files can be recognized with the sha1 hash.", "sig", "=", "hashlib", ".", "sha1", "(", ")", "with", "open", "(", "filename", ",", "\"rb\"", ")", "as", "f", ":", "buf", "=", "f", ".", "read", "(", ")", "sig", ".", "update", "(", "buf", ")", "return", "sig", ".", "hexdigest", "(", ")" ]
Return a signature for a file.
[ "Return", "a", "signature", "for", "a", "file", "." ]
2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e
https://github.com/gccxml/pygccxml/blob/2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e/pygccxml/parser/declarations_cache.py#L17-L34
train
236,154
gccxml/pygccxml
pygccxml/parser/declarations_cache.py
file_cache_t.__load
def __load(file_name): """ Load pickled cache from file and return the object. """ if os.path.exists(file_name) and not os.path.isfile(file_name): raise RuntimeError( 'Cache should be initialized with valid full file name') if not os.path.exists(file_name): open(file_name, 'w+b').close() return {} cache_file_obj = open(file_name, 'rb') try: file_cache_t.logger.info('Loading cache file "%s".', file_name) start_time = timeit.default_timer() cache = pickle.load(cache_file_obj) file_cache_t.logger.debug( "Cache file has been loaded in %.1f secs", (timeit.default_timer() - start_time)) file_cache_t.logger.debug( "Found cache in file: [%s] entries: %s", file_name, len(list(cache.keys()))) except (pickle.UnpicklingError, AttributeError, EOFError, ImportError, IndexError) as error: file_cache_t.logger.exception( "Error occurred while reading cache file: %s", error) cache_file_obj.close() file_cache_t.logger.info( "Invalid cache file: [%s] Regenerating.", file_name) open(file_name, 'w+b').close() # Create empty file cache = {} # Empty cache finally: cache_file_obj.close() return cache
python
def __load(file_name): """ Load pickled cache from file and return the object. """ if os.path.exists(file_name) and not os.path.isfile(file_name): raise RuntimeError( 'Cache should be initialized with valid full file name') if not os.path.exists(file_name): open(file_name, 'w+b').close() return {} cache_file_obj = open(file_name, 'rb') try: file_cache_t.logger.info('Loading cache file "%s".', file_name) start_time = timeit.default_timer() cache = pickle.load(cache_file_obj) file_cache_t.logger.debug( "Cache file has been loaded in %.1f secs", (timeit.default_timer() - start_time)) file_cache_t.logger.debug( "Found cache in file: [%s] entries: %s", file_name, len(list(cache.keys()))) except (pickle.UnpicklingError, AttributeError, EOFError, ImportError, IndexError) as error: file_cache_t.logger.exception( "Error occurred while reading cache file: %s", error) cache_file_obj.close() file_cache_t.logger.info( "Invalid cache file: [%s] Regenerating.", file_name) open(file_name, 'w+b').close() # Create empty file cache = {} # Empty cache finally: cache_file_obj.close() return cache
[ "def", "__load", "(", "file_name", ")", ":", "if", "os", ".", "path", ".", "exists", "(", "file_name", ")", "and", "not", "os", ".", "path", ".", "isfile", "(", "file_name", ")", ":", "raise", "RuntimeError", "(", "'Cache should be initialized with valid full file name'", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "file_name", ")", ":", "open", "(", "file_name", ",", "'w+b'", ")", ".", "close", "(", ")", "return", "{", "}", "cache_file_obj", "=", "open", "(", "file_name", ",", "'rb'", ")", "try", ":", "file_cache_t", ".", "logger", ".", "info", "(", "'Loading cache file \"%s\".'", ",", "file_name", ")", "start_time", "=", "timeit", ".", "default_timer", "(", ")", "cache", "=", "pickle", ".", "load", "(", "cache_file_obj", ")", "file_cache_t", ".", "logger", ".", "debug", "(", "\"Cache file has been loaded in %.1f secs\"", ",", "(", "timeit", ".", "default_timer", "(", ")", "-", "start_time", ")", ")", "file_cache_t", ".", "logger", ".", "debug", "(", "\"Found cache in file: [%s] entries: %s\"", ",", "file_name", ",", "len", "(", "list", "(", "cache", ".", "keys", "(", ")", ")", ")", ")", "except", "(", "pickle", ".", "UnpicklingError", ",", "AttributeError", ",", "EOFError", ",", "ImportError", ",", "IndexError", ")", "as", "error", ":", "file_cache_t", ".", "logger", ".", "exception", "(", "\"Error occurred while reading cache file: %s\"", ",", "error", ")", "cache_file_obj", ".", "close", "(", ")", "file_cache_t", ".", "logger", ".", "info", "(", "\"Invalid cache file: [%s] Regenerating.\"", ",", "file_name", ")", "open", "(", "file_name", ",", "'w+b'", ")", ".", "close", "(", ")", "# Create empty file", "cache", "=", "{", "}", "# Empty cache", "finally", ":", "cache_file_obj", ".", "close", "(", ")", "return", "cache" ]
Load pickled cache from file and return the object.
[ "Load", "pickled", "cache", "from", "file", "and", "return", "the", "object", "." ]
2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e
https://github.com/gccxml/pygccxml/blob/2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e/pygccxml/parser/declarations_cache.py#L179-L212
train
236,155
gccxml/pygccxml
pygccxml/parser/declarations_cache.py
file_cache_t.update
def update(self, source_file, configuration, declarations, included_files): """ Update a cached record with the current key and value contents. """ record = record_t( source_signature=file_signature(source_file), config_signature=configuration_signature(configuration), included_files=included_files, included_files_signature=list( map( file_signature, included_files)), declarations=declarations) # Switched over to holding full record in cache so we don't have # to keep creating records in the next method. self.__cache[record.key()] = record self.__cache[record.key()].was_hit = True self.__needs_flushed = True
python
def update(self, source_file, configuration, declarations, included_files): """ Update a cached record with the current key and value contents. """ record = record_t( source_signature=file_signature(source_file), config_signature=configuration_signature(configuration), included_files=included_files, included_files_signature=list( map( file_signature, included_files)), declarations=declarations) # Switched over to holding full record in cache so we don't have # to keep creating records in the next method. self.__cache[record.key()] = record self.__cache[record.key()].was_hit = True self.__needs_flushed = True
[ "def", "update", "(", "self", ",", "source_file", ",", "configuration", ",", "declarations", ",", "included_files", ")", ":", "record", "=", "record_t", "(", "source_signature", "=", "file_signature", "(", "source_file", ")", ",", "config_signature", "=", "configuration_signature", "(", "configuration", ")", ",", "included_files", "=", "included_files", ",", "included_files_signature", "=", "list", "(", "map", "(", "file_signature", ",", "included_files", ")", ")", ",", "declarations", "=", "declarations", ")", "# Switched over to holding full record in cache so we don't have", "# to keep creating records in the next method.", "self", ".", "__cache", "[", "record", ".", "key", "(", ")", "]", "=", "record", "self", ".", "__cache", "[", "record", ".", "key", "(", ")", "]", ".", "was_hit", "=", "True", "self", ".", "__needs_flushed", "=", "True" ]
Update a cached record with the current key and value contents.
[ "Update", "a", "cached", "record", "with", "the", "current", "key", "and", "value", "contents", "." ]
2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e
https://github.com/gccxml/pygccxml/blob/2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e/pygccxml/parser/declarations_cache.py#L234-L250
train
236,156
gccxml/pygccxml
pygccxml/parser/declarations_cache.py
file_cache_t.cached_value
def cached_value(self, source_file, configuration): """ Attempt to lookup the cached declarations for the given file and configuration. Returns None if declaration not found or signature check fails. """ key = record_t.create_key(source_file, configuration) if key not in self.__cache: return None record = self.__cache[key] if self.__is_valid_signature(record): record.was_hit = True # Record cache hit return record.declarations # some file has been changed del self.__cache[key] return None
python
def cached_value(self, source_file, configuration): """ Attempt to lookup the cached declarations for the given file and configuration. Returns None if declaration not found or signature check fails. """ key = record_t.create_key(source_file, configuration) if key not in self.__cache: return None record = self.__cache[key] if self.__is_valid_signature(record): record.was_hit = True # Record cache hit return record.declarations # some file has been changed del self.__cache[key] return None
[ "def", "cached_value", "(", "self", ",", "source_file", ",", "configuration", ")", ":", "key", "=", "record_t", ".", "create_key", "(", "source_file", ",", "configuration", ")", "if", "key", "not", "in", "self", ".", "__cache", ":", "return", "None", "record", "=", "self", ".", "__cache", "[", "key", "]", "if", "self", ".", "__is_valid_signature", "(", "record", ")", ":", "record", ".", "was_hit", "=", "True", "# Record cache hit", "return", "record", ".", "declarations", "# some file has been changed", "del", "self", ".", "__cache", "[", "key", "]", "return", "None" ]
Attempt to lookup the cached declarations for the given file and configuration. Returns None if declaration not found or signature check fails.
[ "Attempt", "to", "lookup", "the", "cached", "declarations", "for", "the", "given", "file", "and", "configuration", "." ]
2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e
https://github.com/gccxml/pygccxml/blob/2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e/pygccxml/parser/declarations_cache.py#L252-L271
train
236,157
gccxml/pygccxml
release_utils/utils.py
find_version
def find_version(file_path): """ Find the version of pygccxml. Used by setup.py and the sphinx's conf.py. Inspired by https://packaging.python.org/single_source_version/ Args: file_path (str): path to the file containing the version. """ with io.open( os.path.join( os.path.dirname(__file__), os.path.normpath(file_path)), encoding="utf8") as fp: content = fp.read() version_match = re.search(r"^__version__ = ['\"]([^'\"]*)['\"]", content, re.M) if version_match: return version_match.group(1) raise RuntimeError("Unable to find version string.")
python
def find_version(file_path): """ Find the version of pygccxml. Used by setup.py and the sphinx's conf.py. Inspired by https://packaging.python.org/single_source_version/ Args: file_path (str): path to the file containing the version. """ with io.open( os.path.join( os.path.dirname(__file__), os.path.normpath(file_path)), encoding="utf8") as fp: content = fp.read() version_match = re.search(r"^__version__ = ['\"]([^'\"]*)['\"]", content, re.M) if version_match: return version_match.group(1) raise RuntimeError("Unable to find version string.")
[ "def", "find_version", "(", "file_path", ")", ":", "with", "io", ".", "open", "(", "os", ".", "path", ".", "join", "(", "os", ".", "path", ".", "dirname", "(", "__file__", ")", ",", "os", ".", "path", ".", "normpath", "(", "file_path", ")", ")", ",", "encoding", "=", "\"utf8\"", ")", "as", "fp", ":", "content", "=", "fp", ".", "read", "(", ")", "version_match", "=", "re", ".", "search", "(", "r\"^__version__ = ['\\\"]([^'\\\"]*)['\\\"]\"", ",", "content", ",", "re", ".", "M", ")", "if", "version_match", ":", "return", "version_match", ".", "group", "(", "1", ")", "raise", "RuntimeError", "(", "\"Unable to find version string.\"", ")" ]
Find the version of pygccxml. Used by setup.py and the sphinx's conf.py. Inspired by https://packaging.python.org/single_source_version/ Args: file_path (str): path to the file containing the version.
[ "Find", "the", "version", "of", "pygccxml", "." ]
2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e
https://github.com/gccxml/pygccxml/blob/2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e/release_utils/utils.py#L12-L34
train
236,158
gccxml/pygccxml
pygccxml/parser/scanner.py
scanner_t.__read_byte_size
def __read_byte_size(decl, attrs): """Using duck typing to set the size instead of in constructor""" size = attrs.get(XML_AN_SIZE, 0) # Make sure the size is in bytes instead of bits decl.byte_size = int(size) / 8
python
def __read_byte_size(decl, attrs): """Using duck typing to set the size instead of in constructor""" size = attrs.get(XML_AN_SIZE, 0) # Make sure the size is in bytes instead of bits decl.byte_size = int(size) / 8
[ "def", "__read_byte_size", "(", "decl", ",", "attrs", ")", ":", "size", "=", "attrs", ".", "get", "(", "XML_AN_SIZE", ",", "0", ")", "# Make sure the size is in bytes instead of bits", "decl", ".", "byte_size", "=", "int", "(", "size", ")", "/", "8" ]
Using duck typing to set the size instead of in constructor
[ "Using", "duck", "typing", "to", "set", "the", "size", "instead", "of", "in", "constructor" ]
2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e
https://github.com/gccxml/pygccxml/blob/2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e/pygccxml/parser/scanner.py#L338-L342
train
236,159
gccxml/pygccxml
pygccxml/parser/scanner.py
scanner_t.__read_byte_offset
def __read_byte_offset(decl, attrs): """Using duck typing to set the offset instead of in constructor""" offset = attrs.get(XML_AN_OFFSET, 0) # Make sure the size is in bytes instead of bits decl.byte_offset = int(offset) / 8
python
def __read_byte_offset(decl, attrs): """Using duck typing to set the offset instead of in constructor""" offset = attrs.get(XML_AN_OFFSET, 0) # Make sure the size is in bytes instead of bits decl.byte_offset = int(offset) / 8
[ "def", "__read_byte_offset", "(", "decl", ",", "attrs", ")", ":", "offset", "=", "attrs", ".", "get", "(", "XML_AN_OFFSET", ",", "0", ")", "# Make sure the size is in bytes instead of bits", "decl", ".", "byte_offset", "=", "int", "(", "offset", ")", "/", "8" ]
Using duck typing to set the offset instead of in constructor
[ "Using", "duck", "typing", "to", "set", "the", "offset", "instead", "of", "in", "constructor" ]
2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e
https://github.com/gccxml/pygccxml/blob/2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e/pygccxml/parser/scanner.py#L345-L349
train
236,160
gccxml/pygccxml
pygccxml/parser/scanner.py
scanner_t.__read_byte_align
def __read_byte_align(decl, attrs): """Using duck typing to set the alignment""" align = attrs.get(XML_AN_ALIGN, 0) # Make sure the size is in bytes instead of bits decl.byte_align = int(align) / 8
python
def __read_byte_align(decl, attrs): """Using duck typing to set the alignment""" align = attrs.get(XML_AN_ALIGN, 0) # Make sure the size is in bytes instead of bits decl.byte_align = int(align) / 8
[ "def", "__read_byte_align", "(", "decl", ",", "attrs", ")", ":", "align", "=", "attrs", ".", "get", "(", "XML_AN_ALIGN", ",", "0", ")", "# Make sure the size is in bytes instead of bits", "decl", ".", "byte_align", "=", "int", "(", "align", ")", "/", "8" ]
Using duck typing to set the alignment
[ "Using", "duck", "typing", "to", "set", "the", "alignment" ]
2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e
https://github.com/gccxml/pygccxml/blob/2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e/pygccxml/parser/scanner.py#L352-L356
train
236,161
gccxml/pygccxml
pygccxml/parser/declarations_joiner.py
bind_aliases
def bind_aliases(decls): """ This function binds between class and it's typedefs. :param decls: list of all declarations :rtype: None """ visited = set() typedefs = [ decl for decl in decls if isinstance(decl, declarations.typedef_t)] for decl in typedefs: type_ = declarations.remove_alias(decl.decl_type) if not isinstance(type_, declarations.declarated_t): continue cls_inst = type_.declaration if not isinstance(cls_inst, declarations.class_types): continue if id(cls_inst) not in visited: visited.add(id(cls_inst)) del cls_inst.aliases[:] cls_inst.aliases.append(decl)
python
def bind_aliases(decls): """ This function binds between class and it's typedefs. :param decls: list of all declarations :rtype: None """ visited = set() typedefs = [ decl for decl in decls if isinstance(decl, declarations.typedef_t)] for decl in typedefs: type_ = declarations.remove_alias(decl.decl_type) if not isinstance(type_, declarations.declarated_t): continue cls_inst = type_.declaration if not isinstance(cls_inst, declarations.class_types): continue if id(cls_inst) not in visited: visited.add(id(cls_inst)) del cls_inst.aliases[:] cls_inst.aliases.append(decl)
[ "def", "bind_aliases", "(", "decls", ")", ":", "visited", "=", "set", "(", ")", "typedefs", "=", "[", "decl", "for", "decl", "in", "decls", "if", "isinstance", "(", "decl", ",", "declarations", ".", "typedef_t", ")", "]", "for", "decl", "in", "typedefs", ":", "type_", "=", "declarations", ".", "remove_alias", "(", "decl", ".", "decl_type", ")", "if", "not", "isinstance", "(", "type_", ",", "declarations", ".", "declarated_t", ")", ":", "continue", "cls_inst", "=", "type_", ".", "declaration", "if", "not", "isinstance", "(", "cls_inst", ",", "declarations", ".", "class_types", ")", ":", "continue", "if", "id", "(", "cls_inst", ")", "not", "in", "visited", ":", "visited", ".", "add", "(", "id", "(", "cls_inst", ")", ")", "del", "cls_inst", ".", "aliases", "[", ":", "]", "cls_inst", ".", "aliases", ".", "append", "(", "decl", ")" ]
This function binds between class and it's typedefs. :param decls: list of all declarations :rtype: None
[ "This", "function", "binds", "between", "class", "and", "it", "s", "typedefs", "." ]
2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e
https://github.com/gccxml/pygccxml/blob/2b1efbb9e37ceb2ae925c7f3ce1570f476db9e1e/pygccxml/parser/declarations_joiner.py#L9-L32
train
236,162
d11wtq/dockerpty
features/environment.py
after_scenario
def after_scenario(ctx, scenario): """ Cleans up docker containers used as test fixtures after test completes. """ if hasattr(ctx, 'container') and hasattr(ctx, 'client'): try: ctx.client.remove_container(ctx.container, force=True) except: pass
python
def after_scenario(ctx, scenario): """ Cleans up docker containers used as test fixtures after test completes. """ if hasattr(ctx, 'container') and hasattr(ctx, 'client'): try: ctx.client.remove_container(ctx.container, force=True) except: pass
[ "def", "after_scenario", "(", "ctx", ",", "scenario", ")", ":", "if", "hasattr", "(", "ctx", ",", "'container'", ")", "and", "hasattr", "(", "ctx", ",", "'client'", ")", ":", "try", ":", "ctx", ".", "client", ".", "remove_container", "(", "ctx", ".", "container", ",", "force", "=", "True", ")", "except", ":", "pass" ]
Cleans up docker containers used as test fixtures after test completes.
[ "Cleans", "up", "docker", "containers", "used", "as", "test", "fixtures", "after", "test", "completes", "." ]
f8d17d893c6758b7cc25825e99f6b02202632a97
https://github.com/d11wtq/dockerpty/blob/f8d17d893c6758b7cc25825e99f6b02202632a97/features/environment.py#L37-L46
train
236,163
d11wtq/dockerpty
dockerpty/io.py
set_blocking
def set_blocking(fd, blocking=True): """ Set the given file-descriptor blocking or non-blocking. Returns the original blocking status. """ old_flag = fcntl.fcntl(fd, fcntl.F_GETFL) if blocking: new_flag = old_flag & ~ os.O_NONBLOCK else: new_flag = old_flag | os.O_NONBLOCK fcntl.fcntl(fd, fcntl.F_SETFL, new_flag) return not bool(old_flag & os.O_NONBLOCK)
python
def set_blocking(fd, blocking=True): """ Set the given file-descriptor blocking or non-blocking. Returns the original blocking status. """ old_flag = fcntl.fcntl(fd, fcntl.F_GETFL) if blocking: new_flag = old_flag & ~ os.O_NONBLOCK else: new_flag = old_flag | os.O_NONBLOCK fcntl.fcntl(fd, fcntl.F_SETFL, new_flag) return not bool(old_flag & os.O_NONBLOCK)
[ "def", "set_blocking", "(", "fd", ",", "blocking", "=", "True", ")", ":", "old_flag", "=", "fcntl", ".", "fcntl", "(", "fd", ",", "fcntl", ".", "F_GETFL", ")", "if", "blocking", ":", "new_flag", "=", "old_flag", "&", "~", "os", ".", "O_NONBLOCK", "else", ":", "new_flag", "=", "old_flag", "|", "os", ".", "O_NONBLOCK", "fcntl", ".", "fcntl", "(", "fd", ",", "fcntl", ".", "F_SETFL", ",", "new_flag", ")", "return", "not", "bool", "(", "old_flag", "&", "os", ".", "O_NONBLOCK", ")" ]
Set the given file-descriptor blocking or non-blocking. Returns the original blocking status.
[ "Set", "the", "given", "file", "-", "descriptor", "blocking", "or", "non", "-", "blocking", "." ]
f8d17d893c6758b7cc25825e99f6b02202632a97
https://github.com/d11wtq/dockerpty/blob/f8d17d893c6758b7cc25825e99f6b02202632a97/dockerpty/io.py#L25-L41
train
236,164
d11wtq/dockerpty
dockerpty/io.py
select
def select(read_streams, write_streams, timeout=0): """ Select the streams from `read_streams` that are ready for reading, and streams from `write_streams` ready for writing. Uses `select.select()` internally but only returns two lists of ready streams. """ exception_streams = [] try: return builtin_select.select( read_streams, write_streams, exception_streams, timeout, )[0:2] except builtin_select.error as e: # POSIX signals interrupt select() no = e.errno if six.PY3 else e[0] if no == errno.EINTR: return ([], []) else: raise e
python
def select(read_streams, write_streams, timeout=0): """ Select the streams from `read_streams` that are ready for reading, and streams from `write_streams` ready for writing. Uses `select.select()` internally but only returns two lists of ready streams. """ exception_streams = [] try: return builtin_select.select( read_streams, write_streams, exception_streams, timeout, )[0:2] except builtin_select.error as e: # POSIX signals interrupt select() no = e.errno if six.PY3 else e[0] if no == errno.EINTR: return ([], []) else: raise e
[ "def", "select", "(", "read_streams", ",", "write_streams", ",", "timeout", "=", "0", ")", ":", "exception_streams", "=", "[", "]", "try", ":", "return", "builtin_select", ".", "select", "(", "read_streams", ",", "write_streams", ",", "exception_streams", ",", "timeout", ",", ")", "[", "0", ":", "2", "]", "except", "builtin_select", ".", "error", "as", "e", ":", "# POSIX signals interrupt select()", "no", "=", "e", ".", "errno", "if", "six", ".", "PY3", "else", "e", "[", "0", "]", "if", "no", "==", "errno", ".", "EINTR", ":", "return", "(", "[", "]", ",", "[", "]", ")", "else", ":", "raise", "e" ]
Select the streams from `read_streams` that are ready for reading, and streams from `write_streams` ready for writing. Uses `select.select()` internally but only returns two lists of ready streams.
[ "Select", "the", "streams", "from", "read_streams", "that", "are", "ready", "for", "reading", "and", "streams", "from", "write_streams", "ready", "for", "writing", "." ]
f8d17d893c6758b7cc25825e99f6b02202632a97
https://github.com/d11wtq/dockerpty/blob/f8d17d893c6758b7cc25825e99f6b02202632a97/dockerpty/io.py#L44-L67
train
236,165
d11wtq/dockerpty
dockerpty/io.py
Stream.read
def read(self, n=4096): """ Return `n` bytes of data from the Stream, or None at end of stream. """ while True: try: if hasattr(self.fd, 'recv'): return self.fd.recv(n) return os.read(self.fd.fileno(), n) except EnvironmentError as e: if e.errno not in Stream.ERRNO_RECOVERABLE: raise e
python
def read(self, n=4096): """ Return `n` bytes of data from the Stream, or None at end of stream. """ while True: try: if hasattr(self.fd, 'recv'): return self.fd.recv(n) return os.read(self.fd.fileno(), n) except EnvironmentError as e: if e.errno not in Stream.ERRNO_RECOVERABLE: raise e
[ "def", "read", "(", "self", ",", "n", "=", "4096", ")", ":", "while", "True", ":", "try", ":", "if", "hasattr", "(", "self", ".", "fd", ",", "'recv'", ")", ":", "return", "self", ".", "fd", ".", "recv", "(", "n", ")", "return", "os", ".", "read", "(", "self", ".", "fd", ".", "fileno", "(", ")", ",", "n", ")", "except", "EnvironmentError", "as", "e", ":", "if", "e", ".", "errno", "not", "in", "Stream", ".", "ERRNO_RECOVERABLE", ":", "raise", "e" ]
Return `n` bytes of data from the Stream, or None at end of stream.
[ "Return", "n", "bytes", "of", "data", "from", "the", "Stream", "or", "None", "at", "end", "of", "stream", "." ]
f8d17d893c6758b7cc25825e99f6b02202632a97
https://github.com/d11wtq/dockerpty/blob/f8d17d893c6758b7cc25825e99f6b02202632a97/dockerpty/io.py#L112-L124
train
236,166
d11wtq/dockerpty
dockerpty/io.py
Stream.do_write
def do_write(self): """ Flushes as much pending data from the internal write buffer as possible. """ while True: try: written = 0 if hasattr(self.fd, 'send'): written = self.fd.send(self.buffer) else: written = os.write(self.fd.fileno(), self.buffer) self.buffer = self.buffer[written:] # try to close after writes if a close was requested if self.close_requested and len(self.buffer) == 0: self.close() return written except EnvironmentError as e: if e.errno not in Stream.ERRNO_RECOVERABLE: raise e
python
def do_write(self): """ Flushes as much pending data from the internal write buffer as possible. """ while True: try: written = 0 if hasattr(self.fd, 'send'): written = self.fd.send(self.buffer) else: written = os.write(self.fd.fileno(), self.buffer) self.buffer = self.buffer[written:] # try to close after writes if a close was requested if self.close_requested and len(self.buffer) == 0: self.close() return written except EnvironmentError as e: if e.errno not in Stream.ERRNO_RECOVERABLE: raise e
[ "def", "do_write", "(", "self", ")", ":", "while", "True", ":", "try", ":", "written", "=", "0", "if", "hasattr", "(", "self", ".", "fd", ",", "'send'", ")", ":", "written", "=", "self", ".", "fd", ".", "send", "(", "self", ".", "buffer", ")", "else", ":", "written", "=", "os", ".", "write", "(", "self", ".", "fd", ".", "fileno", "(", ")", ",", "self", ".", "buffer", ")", "self", ".", "buffer", "=", "self", ".", "buffer", "[", "written", ":", "]", "# try to close after writes if a close was requested", "if", "self", ".", "close_requested", "and", "len", "(", "self", ".", "buffer", ")", "==", "0", ":", "self", ".", "close", "(", ")", "return", "written", "except", "EnvironmentError", "as", "e", ":", "if", "e", ".", "errno", "not", "in", "Stream", ".", "ERRNO_RECOVERABLE", ":", "raise", "e" ]
Flushes as much pending data from the internal write buffer as possible.
[ "Flushes", "as", "much", "pending", "data", "from", "the", "internal", "write", "buffer", "as", "possible", "." ]
f8d17d893c6758b7cc25825e99f6b02202632a97
https://github.com/d11wtq/dockerpty/blob/f8d17d893c6758b7cc25825e99f6b02202632a97/dockerpty/io.py#L142-L164
train
236,167
d11wtq/dockerpty
dockerpty/io.py
Demuxer.read
def read(self, n=4096): """ Read up to `n` bytes of data from the Stream, after demuxing. Less than `n` bytes of data may be returned depending on the available payload, but the number of bytes returned will never exceed `n`. Because demuxing involves scanning 8-byte headers, the actual amount of data read from the underlying stream may be greater than `n`. """ size = self._next_packet_size(n) if size <= 0: return else: data = six.binary_type() while len(data) < size: nxt = self.stream.read(size - len(data)) if not nxt: # the stream has closed, return what data we got return data data = data + nxt return data
python
def read(self, n=4096): """ Read up to `n` bytes of data from the Stream, after demuxing. Less than `n` bytes of data may be returned depending on the available payload, but the number of bytes returned will never exceed `n`. Because demuxing involves scanning 8-byte headers, the actual amount of data read from the underlying stream may be greater than `n`. """ size = self._next_packet_size(n) if size <= 0: return else: data = six.binary_type() while len(data) < size: nxt = self.stream.read(size - len(data)) if not nxt: # the stream has closed, return what data we got return data data = data + nxt return data
[ "def", "read", "(", "self", ",", "n", "=", "4096", ")", ":", "size", "=", "self", ".", "_next_packet_size", "(", "n", ")", "if", "size", "<=", "0", ":", "return", "else", ":", "data", "=", "six", ".", "binary_type", "(", ")", "while", "len", "(", "data", ")", "<", "size", ":", "nxt", "=", "self", ".", "stream", ".", "read", "(", "size", "-", "len", "(", "data", ")", ")", "if", "not", "nxt", ":", "# the stream has closed, return what data we got", "return", "data", "data", "=", "data", "+", "nxt", "return", "data" ]
Read up to `n` bytes of data from the Stream, after demuxing. Less than `n` bytes of data may be returned depending on the available payload, but the number of bytes returned will never exceed `n`. Because demuxing involves scanning 8-byte headers, the actual amount of data read from the underlying stream may be greater than `n`.
[ "Read", "up", "to", "n", "bytes", "of", "data", "from", "the", "Stream", "after", "demuxing", "." ]
f8d17d893c6758b7cc25825e99f6b02202632a97
https://github.com/d11wtq/dockerpty/blob/f8d17d893c6758b7cc25825e99f6b02202632a97/dockerpty/io.py#L224-L247
train
236,168
d11wtq/dockerpty
dockerpty/io.py
Pump.flush
def flush(self, n=4096): """ Flush `n` bytes of data from the reader Stream to the writer Stream. Returns the number of bytes that were actually flushed. A return value of zero is not an error. If EOF has been reached, `None` is returned. """ try: read = self.from_stream.read(n) if read is None or len(read) == 0: self.eof = True if self.propagate_close: self.to_stream.close() return None return self.to_stream.write(read) except OSError as e: if e.errno != errno.EPIPE: raise e
python
def flush(self, n=4096): """ Flush `n` bytes of data from the reader Stream to the writer Stream. Returns the number of bytes that were actually flushed. A return value of zero is not an error. If EOF has been reached, `None` is returned. """ try: read = self.from_stream.read(n) if read is None or len(read) == 0: self.eof = True if self.propagate_close: self.to_stream.close() return None return self.to_stream.write(read) except OSError as e: if e.errno != errno.EPIPE: raise e
[ "def", "flush", "(", "self", ",", "n", "=", "4096", ")", ":", "try", ":", "read", "=", "self", ".", "from_stream", ".", "read", "(", "n", ")", "if", "read", "is", "None", "or", "len", "(", "read", ")", "==", "0", ":", "self", ".", "eof", "=", "True", "if", "self", ".", "propagate_close", ":", "self", ".", "to_stream", ".", "close", "(", ")", "return", "None", "return", "self", ".", "to_stream", ".", "write", "(", "read", ")", "except", "OSError", "as", "e", ":", "if", "e", ".", "errno", "!=", "errno", ".", "EPIPE", ":", "raise", "e" ]
Flush `n` bytes of data from the reader Stream to the writer Stream. Returns the number of bytes that were actually flushed. A return value of zero is not an error. If EOF has been reached, `None` is returned.
[ "Flush", "n", "bytes", "of", "data", "from", "the", "reader", "Stream", "to", "the", "writer", "Stream", "." ]
f8d17d893c6758b7cc25825e99f6b02202632a97
https://github.com/d11wtq/dockerpty/blob/f8d17d893c6758b7cc25825e99f6b02202632a97/dockerpty/io.py#L356-L378
train
236,169
d11wtq/dockerpty
dockerpty/__init__.py
exec_command
def exec_command( client, container, command, interactive=True, stdout=None, stderr=None, stdin=None): """ Run provided command via exec API in provided container. This is just a wrapper for PseudoTerminal(client, container).exec_command() """ exec_id = exec_create(client, container, command, interactive=interactive) operation = ExecOperation(client, exec_id, interactive=interactive, stdout=stdout, stderr=stderr, stdin=stdin) PseudoTerminal(client, operation).start()
python
def exec_command( client, container, command, interactive=True, stdout=None, stderr=None, stdin=None): """ Run provided command via exec API in provided container. This is just a wrapper for PseudoTerminal(client, container).exec_command() """ exec_id = exec_create(client, container, command, interactive=interactive) operation = ExecOperation(client, exec_id, interactive=interactive, stdout=stdout, stderr=stderr, stdin=stdin) PseudoTerminal(client, operation).start()
[ "def", "exec_command", "(", "client", ",", "container", ",", "command", ",", "interactive", "=", "True", ",", "stdout", "=", "None", ",", "stderr", "=", "None", ",", "stdin", "=", "None", ")", ":", "exec_id", "=", "exec_create", "(", "client", ",", "container", ",", "command", ",", "interactive", "=", "interactive", ")", "operation", "=", "ExecOperation", "(", "client", ",", "exec_id", ",", "interactive", "=", "interactive", ",", "stdout", "=", "stdout", ",", "stderr", "=", "stderr", ",", "stdin", "=", "stdin", ")", "PseudoTerminal", "(", "client", ",", "operation", ")", ".", "start", "(", ")" ]
Run provided command via exec API in provided container. This is just a wrapper for PseudoTerminal(client, container).exec_command()
[ "Run", "provided", "command", "via", "exec", "API", "in", "provided", "container", "." ]
f8d17d893c6758b7cc25825e99f6b02202632a97
https://github.com/d11wtq/dockerpty/blob/f8d17d893c6758b7cc25825e99f6b02202632a97/dockerpty/__init__.py#L33-L44
train
236,170
d11wtq/dockerpty
dockerpty/tty.py
Terminal.start
def start(self): """ Saves the current terminal attributes and makes the tty raw. This method returns None immediately. """ if os.isatty(self.fd.fileno()) and self.israw(): self.original_attributes = termios.tcgetattr(self.fd) tty.setraw(self.fd)
python
def start(self): """ Saves the current terminal attributes and makes the tty raw. This method returns None immediately. """ if os.isatty(self.fd.fileno()) and self.israw(): self.original_attributes = termios.tcgetattr(self.fd) tty.setraw(self.fd)
[ "def", "start", "(", "self", ")", ":", "if", "os", ".", "isatty", "(", "self", ".", "fd", ".", "fileno", "(", ")", ")", "and", "self", ".", "israw", "(", ")", ":", "self", ".", "original_attributes", "=", "termios", ".", "tcgetattr", "(", "self", ".", "fd", ")", "tty", ".", "setraw", "(", "self", ".", "fd", ")" ]
Saves the current terminal attributes and makes the tty raw. This method returns None immediately.
[ "Saves", "the", "current", "terminal", "attributes", "and", "makes", "the", "tty", "raw", "." ]
f8d17d893c6758b7cc25825e99f6b02202632a97
https://github.com/d11wtq/dockerpty/blob/f8d17d893c6758b7cc25825e99f6b02202632a97/dockerpty/tty.py#L100-L109
train
236,171
d11wtq/dockerpty
dockerpty/tty.py
Terminal.stop
def stop(self): """ Restores the terminal attributes back to before setting raw mode. If the raw terminal was not started, does nothing. """ if self.original_attributes is not None: termios.tcsetattr( self.fd, termios.TCSADRAIN, self.original_attributes, )
python
def stop(self): """ Restores the terminal attributes back to before setting raw mode. If the raw terminal was not started, does nothing. """ if self.original_attributes is not None: termios.tcsetattr( self.fd, termios.TCSADRAIN, self.original_attributes, )
[ "def", "stop", "(", "self", ")", ":", "if", "self", ".", "original_attributes", "is", "not", "None", ":", "termios", ".", "tcsetattr", "(", "self", ".", "fd", ",", "termios", ".", "TCSADRAIN", ",", "self", ".", "original_attributes", ",", ")" ]
Restores the terminal attributes back to before setting raw mode. If the raw terminal was not started, does nothing.
[ "Restores", "the", "terminal", "attributes", "back", "to", "before", "setting", "raw", "mode", "." ]
f8d17d893c6758b7cc25825e99f6b02202632a97
https://github.com/d11wtq/dockerpty/blob/f8d17d893c6758b7cc25825e99f6b02202632a97/dockerpty/tty.py#L112-L124
train
236,172
d11wtq/dockerpty
dockerpty/pty.py
WINCHHandler.start
def start(self): """ Start trapping WINCH signals and resizing the PTY. This method saves the previous WINCH handler so it can be restored on `stop()`. """ def handle(signum, frame): if signum == signal.SIGWINCH: self.pty.resize() self.original_handler = signal.signal(signal.SIGWINCH, handle)
python
def start(self): """ Start trapping WINCH signals and resizing the PTY. This method saves the previous WINCH handler so it can be restored on `stop()`. """ def handle(signum, frame): if signum == signal.SIGWINCH: self.pty.resize() self.original_handler = signal.signal(signal.SIGWINCH, handle)
[ "def", "start", "(", "self", ")", ":", "def", "handle", "(", "signum", ",", "frame", ")", ":", "if", "signum", "==", "signal", ".", "SIGWINCH", ":", "self", ".", "pty", ".", "resize", "(", ")", "self", ".", "original_handler", "=", "signal", ".", "signal", "(", "signal", ".", "SIGWINCH", ",", "handle", ")" ]
Start trapping WINCH signals and resizing the PTY. This method saves the previous WINCH handler so it can be restored on `stop()`.
[ "Start", "trapping", "WINCH", "signals", "and", "resizing", "the", "PTY", "." ]
f8d17d893c6758b7cc25825e99f6b02202632a97
https://github.com/d11wtq/dockerpty/blob/f8d17d893c6758b7cc25825e99f6b02202632a97/dockerpty/pty.py#L57-L69
train
236,173
d11wtq/dockerpty
dockerpty/pty.py
WINCHHandler.stop
def stop(self): """ Stop trapping WINCH signals and restore the previous WINCH handler. """ if self.original_handler is not None: signal.signal(signal.SIGWINCH, self.original_handler)
python
def stop(self): """ Stop trapping WINCH signals and restore the previous WINCH handler. """ if self.original_handler is not None: signal.signal(signal.SIGWINCH, self.original_handler)
[ "def", "stop", "(", "self", ")", ":", "if", "self", ".", "original_handler", "is", "not", "None", ":", "signal", ".", "signal", "(", "signal", ".", "SIGWINCH", ",", "self", ".", "original_handler", ")" ]
Stop trapping WINCH signals and restore the previous WINCH handler.
[ "Stop", "trapping", "WINCH", "signals", "and", "restore", "the", "previous", "WINCH", "handler", "." ]
f8d17d893c6758b7cc25825e99f6b02202632a97
https://github.com/d11wtq/dockerpty/blob/f8d17d893c6758b7cc25825e99f6b02202632a97/dockerpty/pty.py#L71-L77
train
236,174
d11wtq/dockerpty
dockerpty/pty.py
RunOperation.resize
def resize(self, height, width, **kwargs): """ resize pty within container """ self.client.resize(self.container, height=height, width=width)
python
def resize(self, height, width, **kwargs): """ resize pty within container """ self.client.resize(self.container, height=height, width=width)
[ "def", "resize", "(", "self", ",", "height", ",", "width", ",", "*", "*", "kwargs", ")", ":", "self", ".", "client", ".", "resize", "(", "self", ".", "container", ",", "height", "=", "height", ",", "width", "=", "width", ")" ]
resize pty within container
[ "resize", "pty", "within", "container" ]
f8d17d893c6758b7cc25825e99f6b02202632a97
https://github.com/d11wtq/dockerpty/blob/f8d17d893c6758b7cc25825e99f6b02202632a97/dockerpty/pty.py#L193-L197
train
236,175
d11wtq/dockerpty
dockerpty/pty.py
ExecOperation.resize
def resize(self, height, width, **kwargs): """ resize pty of an execed process """ self.client.exec_resize(self.exec_id, height=height, width=width)
python
def resize(self, height, width, **kwargs): """ resize pty of an execed process """ self.client.exec_resize(self.exec_id, height=height, width=width)
[ "def", "resize", "(", "self", ",", "height", ",", "width", ",", "*", "*", "kwargs", ")", ":", "self", ".", "client", ".", "exec_resize", "(", "self", ".", "exec_id", ",", "height", "=", "height", ",", "width", "=", "width", ")" ]
resize pty of an execed process
[ "resize", "pty", "of", "an", "execed", "process" ]
f8d17d893c6758b7cc25825e99f6b02202632a97
https://github.com/d11wtq/dockerpty/blob/f8d17d893c6758b7cc25825e99f6b02202632a97/dockerpty/pty.py#L267-L271
train
236,176
d11wtq/dockerpty
dockerpty/pty.py
ExecOperation._exec_info
def _exec_info(self): """ Caching wrapper around client.exec_inspect """ if self._info is None: self._info = self.client.exec_inspect(self.exec_id) return self._info
python
def _exec_info(self): """ Caching wrapper around client.exec_inspect """ if self._info is None: self._info = self.client.exec_inspect(self.exec_id) return self._info
[ "def", "_exec_info", "(", "self", ")", ":", "if", "self", ".", "_info", "is", "None", ":", "self", ".", "_info", "=", "self", ".", "client", ".", "exec_inspect", "(", "self", ".", "exec_id", ")", "return", "self", ".", "_info" ]
Caching wrapper around client.exec_inspect
[ "Caching", "wrapper", "around", "client", ".", "exec_inspect" ]
f8d17d893c6758b7cc25825e99f6b02202632a97
https://github.com/d11wtq/dockerpty/blob/f8d17d893c6758b7cc25825e99f6b02202632a97/dockerpty/pty.py#L279-L285
train
236,177
mhe/pynrrd
nrrd/formatters.py
format_number
def format_number(x): """Format number to string Function converts a number to string. For numbers of class :class:`float`, up to 17 digits will be used to print the entire floating point number. Any padding zeros will be removed at the end of the number. See :ref:`user-guide:int` and :ref:`user-guide:double` for more information on the format. .. note:: IEEE754-1985 standard says that 17 significant decimal digits are required to adequately represent a 64-bit floating point number. Not all fractional numbers can be exactly represented in floating point. An example is 0.1 which will be approximated as 0.10000000000000001. Parameters ---------- x : :class:`int` or :class:`float` Number to convert to string Returns ------- vector : :class:`str` String of number :obj:`x` """ if isinstance(x, float): # Helps prevent loss of precision as using str() in Python 2 only prints 12 digits of precision. # However, IEEE754-1985 standard says that 17 significant decimal digits is required to adequately represent a # floating point number. # The g option is used rather than f because g precision uses significant digits while f is just the number of # digits after the decimal. (NRRD C implementation uses g). value = '{:.17g}'.format(x) else: value = str(x) return value
python
def format_number(x): """Format number to string Function converts a number to string. For numbers of class :class:`float`, up to 17 digits will be used to print the entire floating point number. Any padding zeros will be removed at the end of the number. See :ref:`user-guide:int` and :ref:`user-guide:double` for more information on the format. .. note:: IEEE754-1985 standard says that 17 significant decimal digits are required to adequately represent a 64-bit floating point number. Not all fractional numbers can be exactly represented in floating point. An example is 0.1 which will be approximated as 0.10000000000000001. Parameters ---------- x : :class:`int` or :class:`float` Number to convert to string Returns ------- vector : :class:`str` String of number :obj:`x` """ if isinstance(x, float): # Helps prevent loss of precision as using str() in Python 2 only prints 12 digits of precision. # However, IEEE754-1985 standard says that 17 significant decimal digits is required to adequately represent a # floating point number. # The g option is used rather than f because g precision uses significant digits while f is just the number of # digits after the decimal. (NRRD C implementation uses g). value = '{:.17g}'.format(x) else: value = str(x) return value
[ "def", "format_number", "(", "x", ")", ":", "if", "isinstance", "(", "x", ",", "float", ")", ":", "# Helps prevent loss of precision as using str() in Python 2 only prints 12 digits of precision.", "# However, IEEE754-1985 standard says that 17 significant decimal digits is required to adequately represent a", "# floating point number.", "# The g option is used rather than f because g precision uses significant digits while f is just the number of", "# digits after the decimal. (NRRD C implementation uses g).", "value", "=", "'{:.17g}'", ".", "format", "(", "x", ")", "else", ":", "value", "=", "str", "(", "x", ")", "return", "value" ]
Format number to string Function converts a number to string. For numbers of class :class:`float`, up to 17 digits will be used to print the entire floating point number. Any padding zeros will be removed at the end of the number. See :ref:`user-guide:int` and :ref:`user-guide:double` for more information on the format. .. note:: IEEE754-1985 standard says that 17 significant decimal digits are required to adequately represent a 64-bit floating point number. Not all fractional numbers can be exactly represented in floating point. An example is 0.1 which will be approximated as 0.10000000000000001. Parameters ---------- x : :class:`int` or :class:`float` Number to convert to string Returns ------- vector : :class:`str` String of number :obj:`x`
[ "Format", "number", "to", "string" ]
96dd875b302031ea27e2d3aaa611dc6f2dfc7979
https://github.com/mhe/pynrrd/blob/96dd875b302031ea27e2d3aaa611dc6f2dfc7979/nrrd/formatters.py#L4-L38
train
236,178
mhe/pynrrd
nrrd/parsers.py
parse_number_auto_dtype
def parse_number_auto_dtype(x): """Parse number from string with automatic type detection. Parses input string and converts to a number using automatic type detection. If the number contains any fractional parts, then the number will be converted to float, otherwise the number will be converted to an int. See :ref:`user-guide:int` and :ref:`user-guide:double` for more information on the format. Parameters ---------- x : :class:`str` String representation of number Returns ------- result : :class:`int` or :class:`float` Number parsed from :obj:`x` string """ value = float(x) if value.is_integer(): value = int(value) return value
python
def parse_number_auto_dtype(x): """Parse number from string with automatic type detection. Parses input string and converts to a number using automatic type detection. If the number contains any fractional parts, then the number will be converted to float, otherwise the number will be converted to an int. See :ref:`user-guide:int` and :ref:`user-guide:double` for more information on the format. Parameters ---------- x : :class:`str` String representation of number Returns ------- result : :class:`int` or :class:`float` Number parsed from :obj:`x` string """ value = float(x) if value.is_integer(): value = int(value) return value
[ "def", "parse_number_auto_dtype", "(", "x", ")", ":", "value", "=", "float", "(", "x", ")", "if", "value", ".", "is_integer", "(", ")", ":", "value", "=", "int", "(", "value", ")", "return", "value" ]
Parse number from string with automatic type detection. Parses input string and converts to a number using automatic type detection. If the number contains any fractional parts, then the number will be converted to float, otherwise the number will be converted to an int. See :ref:`user-guide:int` and :ref:`user-guide:double` for more information on the format. Parameters ---------- x : :class:`str` String representation of number Returns ------- result : :class:`int` or :class:`float` Number parsed from :obj:`x` string
[ "Parse", "number", "from", "string", "with", "automatic", "type", "detection", "." ]
96dd875b302031ea27e2d3aaa611dc6f2dfc7979
https://github.com/mhe/pynrrd/blob/96dd875b302031ea27e2d3aaa611dc6f2dfc7979/nrrd/parsers.py#L207-L231
train
236,179
mhe/pynrrd
nrrd/reader.py
_determine_datatype
def _determine_datatype(fields): """Determine the numpy dtype of the data.""" # Convert the NRRD type string identifier into a NumPy string identifier using a map np_typestring = _TYPEMAP_NRRD2NUMPY[fields['type']] # This is only added if the datatype has more than one byte and is not using ASCII encoding # Note: Endian is not required for ASCII encoding if np.dtype(np_typestring).itemsize > 1 and fields['encoding'] not in ['ASCII', 'ascii', 'text', 'txt']: if 'endian' not in fields: raise NRRDError('Header is missing required field: "endian".') elif fields['endian'] == 'big': np_typestring = '>' + np_typestring elif fields['endian'] == 'little': np_typestring = '<' + np_typestring else: raise NRRDError('Invalid endian value in header: "%s"' % fields['endian']) return np.dtype(np_typestring)
python
def _determine_datatype(fields): """Determine the numpy dtype of the data.""" # Convert the NRRD type string identifier into a NumPy string identifier using a map np_typestring = _TYPEMAP_NRRD2NUMPY[fields['type']] # This is only added if the datatype has more than one byte and is not using ASCII encoding # Note: Endian is not required for ASCII encoding if np.dtype(np_typestring).itemsize > 1 and fields['encoding'] not in ['ASCII', 'ascii', 'text', 'txt']: if 'endian' not in fields: raise NRRDError('Header is missing required field: "endian".') elif fields['endian'] == 'big': np_typestring = '>' + np_typestring elif fields['endian'] == 'little': np_typestring = '<' + np_typestring else: raise NRRDError('Invalid endian value in header: "%s"' % fields['endian']) return np.dtype(np_typestring)
[ "def", "_determine_datatype", "(", "fields", ")", ":", "# Convert the NRRD type string identifier into a NumPy string identifier using a map", "np_typestring", "=", "_TYPEMAP_NRRD2NUMPY", "[", "fields", "[", "'type'", "]", "]", "# This is only added if the datatype has more than one byte and is not using ASCII encoding", "# Note: Endian is not required for ASCII encoding", "if", "np", ".", "dtype", "(", "np_typestring", ")", ".", "itemsize", ">", "1", "and", "fields", "[", "'encoding'", "]", "not", "in", "[", "'ASCII'", ",", "'ascii'", ",", "'text'", ",", "'txt'", "]", ":", "if", "'endian'", "not", "in", "fields", ":", "raise", "NRRDError", "(", "'Header is missing required field: \"endian\".'", ")", "elif", "fields", "[", "'endian'", "]", "==", "'big'", ":", "np_typestring", "=", "'>'", "+", "np_typestring", "elif", "fields", "[", "'endian'", "]", "==", "'little'", ":", "np_typestring", "=", "'<'", "+", "np_typestring", "else", ":", "raise", "NRRDError", "(", "'Invalid endian value in header: \"%s\"'", "%", "fields", "[", "'endian'", "]", ")", "return", "np", ".", "dtype", "(", "np_typestring", ")" ]
Determine the numpy dtype of the data.
[ "Determine", "the", "numpy", "dtype", "of", "the", "data", "." ]
96dd875b302031ea27e2d3aaa611dc6f2dfc7979
https://github.com/mhe/pynrrd/blob/96dd875b302031ea27e2d3aaa611dc6f2dfc7979/nrrd/reader.py#L145-L163
train
236,180
mhe/pynrrd
nrrd/reader.py
_validate_magic_line
def _validate_magic_line(line): """For NRRD files, the first four characters are always "NRRD", and remaining characters give information about the file format version >>> _validate_magic_line('NRRD0005') 8 >>> _validate_magic_line('NRRD0006') Traceback (most recent call last): ... NrrdError: NRRD file version too new for this library. >>> _validate_magic_line('NRRD') Traceback (most recent call last): ... NrrdError: Invalid NRRD magic line: NRRD """ if not line.startswith('NRRD'): raise NRRDError('Invalid NRRD magic line. Is this an NRRD file?') try: version = int(line[4:]) if version > 5: raise NRRDError('Unsupported NRRD file version (version: %i). This library only supports v%i and below.' % (version, 5)) except ValueError: raise NRRDError('Invalid NRRD magic line: %s' % line) return len(line)
python
def _validate_magic_line(line): """For NRRD files, the first four characters are always "NRRD", and remaining characters give information about the file format version >>> _validate_magic_line('NRRD0005') 8 >>> _validate_magic_line('NRRD0006') Traceback (most recent call last): ... NrrdError: NRRD file version too new for this library. >>> _validate_magic_line('NRRD') Traceback (most recent call last): ... NrrdError: Invalid NRRD magic line: NRRD """ if not line.startswith('NRRD'): raise NRRDError('Invalid NRRD magic line. Is this an NRRD file?') try: version = int(line[4:]) if version > 5: raise NRRDError('Unsupported NRRD file version (version: %i). This library only supports v%i and below.' % (version, 5)) except ValueError: raise NRRDError('Invalid NRRD magic line: %s' % line) return len(line)
[ "def", "_validate_magic_line", "(", "line", ")", ":", "if", "not", "line", ".", "startswith", "(", "'NRRD'", ")", ":", "raise", "NRRDError", "(", "'Invalid NRRD magic line. Is this an NRRD file?'", ")", "try", ":", "version", "=", "int", "(", "line", "[", "4", ":", "]", ")", "if", "version", ">", "5", ":", "raise", "NRRDError", "(", "'Unsupported NRRD file version (version: %i). This library only supports v%i and below.'", "%", "(", "version", ",", "5", ")", ")", "except", "ValueError", ":", "raise", "NRRDError", "(", "'Invalid NRRD magic line: %s'", "%", "line", ")", "return", "len", "(", "line", ")" ]
For NRRD files, the first four characters are always "NRRD", and remaining characters give information about the file format version >>> _validate_magic_line('NRRD0005') 8 >>> _validate_magic_line('NRRD0006') Traceback (most recent call last): ... NrrdError: NRRD file version too new for this library. >>> _validate_magic_line('NRRD') Traceback (most recent call last): ... NrrdError: Invalid NRRD magic line: NRRD
[ "For", "NRRD", "files", "the", "first", "four", "characters", "are", "always", "NRRD", "and", "remaining", "characters", "give", "information", "about", "the", "file", "format", "version" ]
96dd875b302031ea27e2d3aaa611dc6f2dfc7979
https://github.com/mhe/pynrrd/blob/96dd875b302031ea27e2d3aaa611dc6f2dfc7979/nrrd/reader.py#L166-L193
train
236,181
mhe/pynrrd
nrrd/reader.py
read
def read(filename, custom_field_map=None, index_order='F'): """Read a NRRD file and return the header and data See :ref:`user-guide:Reading NRRD files` for more information on reading NRRD files. .. note:: Users should be aware that the `index_order` argument needs to be consistent between `nrrd.read` and `nrrd.write`. I.e., reading an array with `index_order='F'` will result in a transposed version of the original data and hence the writer needs to be aware of this. Parameters ---------- filename : :class:`str` Filename of the NRRD file custom_field_map : :class:`dict` (:class:`str`, :class:`str`), optional Dictionary used for parsing custom field types where the key is the custom field name and the value is a string identifying datatype for the custom field. index_order : {'C', 'F'}, optional Specifies the index order of the resulting data array. Either 'C' (C-order) where the dimensions are ordered from slowest-varying to fastest-varying (e.g. (z, y, x)), or 'F' (Fortran-order) where the dimensions are ordered from fastest-varying to slowest-varying (e.g. (x, y, z)). Returns ------- data : :class:`numpy.ndarray` Data read from NRRD file header : :class:`dict` (:class:`str`, :obj:`Object`) Dictionary containing the header fields and their corresponding parsed value See Also -------- :meth:`write`, :meth:`read_header`, :meth:`read_data` """ """Read a NRRD file and return a tuple (data, header).""" with open(filename, 'rb') as fh: header = read_header(fh, custom_field_map) data = read_data(header, fh, filename, index_order) return data, header
python
def read(filename, custom_field_map=None, index_order='F'): """Read a NRRD file and return the header and data See :ref:`user-guide:Reading NRRD files` for more information on reading NRRD files. .. note:: Users should be aware that the `index_order` argument needs to be consistent between `nrrd.read` and `nrrd.write`. I.e., reading an array with `index_order='F'` will result in a transposed version of the original data and hence the writer needs to be aware of this. Parameters ---------- filename : :class:`str` Filename of the NRRD file custom_field_map : :class:`dict` (:class:`str`, :class:`str`), optional Dictionary used for parsing custom field types where the key is the custom field name and the value is a string identifying datatype for the custom field. index_order : {'C', 'F'}, optional Specifies the index order of the resulting data array. Either 'C' (C-order) where the dimensions are ordered from slowest-varying to fastest-varying (e.g. (z, y, x)), or 'F' (Fortran-order) where the dimensions are ordered from fastest-varying to slowest-varying (e.g. (x, y, z)). Returns ------- data : :class:`numpy.ndarray` Data read from NRRD file header : :class:`dict` (:class:`str`, :obj:`Object`) Dictionary containing the header fields and their corresponding parsed value See Also -------- :meth:`write`, :meth:`read_header`, :meth:`read_data` """ """Read a NRRD file and return a tuple (data, header).""" with open(filename, 'rb') as fh: header = read_header(fh, custom_field_map) data = read_data(header, fh, filename, index_order) return data, header
[ "def", "read", "(", "filename", ",", "custom_field_map", "=", "None", ",", "index_order", "=", "'F'", ")", ":", "\"\"\"Read a NRRD file and return a tuple (data, header).\"\"\"", "with", "open", "(", "filename", ",", "'rb'", ")", "as", "fh", ":", "header", "=", "read_header", "(", "fh", ",", "custom_field_map", ")", "data", "=", "read_data", "(", "header", ",", "fh", ",", "filename", ",", "index_order", ")", "return", "data", ",", "header" ]
Read a NRRD file and return the header and data See :ref:`user-guide:Reading NRRD files` for more information on reading NRRD files. .. note:: Users should be aware that the `index_order` argument needs to be consistent between `nrrd.read` and `nrrd.write`. I.e., reading an array with `index_order='F'` will result in a transposed version of the original data and hence the writer needs to be aware of this. Parameters ---------- filename : :class:`str` Filename of the NRRD file custom_field_map : :class:`dict` (:class:`str`, :class:`str`), optional Dictionary used for parsing custom field types where the key is the custom field name and the value is a string identifying datatype for the custom field. index_order : {'C', 'F'}, optional Specifies the index order of the resulting data array. Either 'C' (C-order) where the dimensions are ordered from slowest-varying to fastest-varying (e.g. (z, y, x)), or 'F' (Fortran-order) where the dimensions are ordered from fastest-varying to slowest-varying (e.g. (x, y, z)). Returns ------- data : :class:`numpy.ndarray` Data read from NRRD file header : :class:`dict` (:class:`str`, :obj:`Object`) Dictionary containing the header fields and their corresponding parsed value See Also -------- :meth:`write`, :meth:`read_header`, :meth:`read_data`
[ "Read", "a", "NRRD", "file", "and", "return", "the", "header", "and", "data" ]
96dd875b302031ea27e2d3aaa611dc6f2dfc7979
https://github.com/mhe/pynrrd/blob/96dd875b302031ea27e2d3aaa611dc6f2dfc7979/nrrd/reader.py#L469-L506
train
236,182
bspaans/python-mingus
mingus/containers/track.py
Track.add_notes
def add_notes(self, note, duration=None): """Add a Note, note as string or NoteContainer to the last Bar. If the Bar is full, a new one will automatically be created. If the Bar is not full but the note can't fit in, this method will return False. True otherwise. An InstrumentRangeError exception will be raised if an Instrument is attached to the Track, but the note turns out not to be within the range of the Instrument. """ if self.instrument != None: if not self.instrument.can_play_notes(note): raise InstrumentRangeError, \ "Note '%s' is not in range of the instrument (%s)" % (note, self.instrument) if duration == None: duration = 4 # Check whether the last bar is full, if so create a new bar and add the # note there if len(self.bars) == 0: self.bars.append(Bar()) last_bar = self.bars[-1] if last_bar.is_full(): self.bars.append(Bar(last_bar.key, last_bar.meter)) # warning should hold note if it doesn't fit return self.bars[-1].place_notes(note, duration)
python
def add_notes(self, note, duration=None): """Add a Note, note as string or NoteContainer to the last Bar. If the Bar is full, a new one will automatically be created. If the Bar is not full but the note can't fit in, this method will return False. True otherwise. An InstrumentRangeError exception will be raised if an Instrument is attached to the Track, but the note turns out not to be within the range of the Instrument. """ if self.instrument != None: if not self.instrument.can_play_notes(note): raise InstrumentRangeError, \ "Note '%s' is not in range of the instrument (%s)" % (note, self.instrument) if duration == None: duration = 4 # Check whether the last bar is full, if so create a new bar and add the # note there if len(self.bars) == 0: self.bars.append(Bar()) last_bar = self.bars[-1] if last_bar.is_full(): self.bars.append(Bar(last_bar.key, last_bar.meter)) # warning should hold note if it doesn't fit return self.bars[-1].place_notes(note, duration)
[ "def", "add_notes", "(", "self", ",", "note", ",", "duration", "=", "None", ")", ":", "if", "self", ".", "instrument", "!=", "None", ":", "if", "not", "self", ".", "instrument", ".", "can_play_notes", "(", "note", ")", ":", "raise", "InstrumentRangeError", ",", "\"Note '%s' is not in range of the instrument (%s)\"", "%", "(", "note", ",", "self", ".", "instrument", ")", "if", "duration", "==", "None", ":", "duration", "=", "4", "# Check whether the last bar is full, if so create a new bar and add the", "# note there", "if", "len", "(", "self", ".", "bars", ")", "==", "0", ":", "self", ".", "bars", ".", "append", "(", "Bar", "(", ")", ")", "last_bar", "=", "self", ".", "bars", "[", "-", "1", "]", "if", "last_bar", ".", "is_full", "(", ")", ":", "self", ".", "bars", ".", "append", "(", "Bar", "(", "last_bar", ".", "key", ",", "last_bar", ".", "meter", ")", ")", "# warning should hold note if it doesn't fit", "return", "self", ".", "bars", "[", "-", "1", "]", ".", "place_notes", "(", "note", ",", "duration", ")" ]
Add a Note, note as string or NoteContainer to the last Bar. If the Bar is full, a new one will automatically be created. If the Bar is not full but the note can't fit in, this method will return False. True otherwise. An InstrumentRangeError exception will be raised if an Instrument is attached to the Track, but the note turns out not to be within the range of the Instrument.
[ "Add", "a", "Note", "note", "as", "string", "or", "NoteContainer", "to", "the", "last", "Bar", "." ]
aa5a5d992d45ada61be0f9f86261380731bd7749
https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/containers/track.py#L51-L80
train
236,183
bspaans/python-mingus
mingus/containers/track.py
Track.get_notes
def get_notes(self): """Return an iterator that iterates through every bar in the this track.""" for bar in self.bars: for beat, duration, notes in bar: yield beat, duration, notes
python
def get_notes(self): """Return an iterator that iterates through every bar in the this track.""" for bar in self.bars: for beat, duration, notes in bar: yield beat, duration, notes
[ "def", "get_notes", "(", "self", ")", ":", "for", "bar", "in", "self", ".", "bars", ":", "for", "beat", ",", "duration", ",", "notes", "in", "bar", ":", "yield", "beat", ",", "duration", ",", "notes" ]
Return an iterator that iterates through every bar in the this track.
[ "Return", "an", "iterator", "that", "iterates", "through", "every", "bar", "in", "the", "this", "track", "." ]
aa5a5d992d45ada61be0f9f86261380731bd7749
https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/containers/track.py#L82-L87
train
236,184
bspaans/python-mingus
mingus/containers/track.py
Track.from_chords
def from_chords(self, chords, duration=1): """Add chords to the Track. The given chords should be a list of shorthand strings or list of list of shorthand strings, etc. Each sublist divides the value by 2. If a tuning is set, chords will be expanded so they have a proper fingering. Example: >>> t = Track().from_chords(['C', ['Am', 'Dm'], 'G7', 'C#'], 1) """ tun = self.get_tuning() def add_chord(chord, duration): if type(chord) == list: for c in chord: add_chord(c, duration * 2) else: chord = NoteContainer().from_chord(chord) if tun: chord = tun.find_chord_fingering(chord, return_best_as_NoteContainer=True) if not self.add_notes(chord, duration): # This should be the standard behaviour of add_notes dur = self.bars[-1].value_left() self.add_notes(chord, dur) # warning should hold note self.add_notes(chord, value.subtract(duration, dur)) for c in chords: if c is not None: add_chord(c, duration) else: self.add_notes(None, duration) return self
python
def from_chords(self, chords, duration=1): """Add chords to the Track. The given chords should be a list of shorthand strings or list of list of shorthand strings, etc. Each sublist divides the value by 2. If a tuning is set, chords will be expanded so they have a proper fingering. Example: >>> t = Track().from_chords(['C', ['Am', 'Dm'], 'G7', 'C#'], 1) """ tun = self.get_tuning() def add_chord(chord, duration): if type(chord) == list: for c in chord: add_chord(c, duration * 2) else: chord = NoteContainer().from_chord(chord) if tun: chord = tun.find_chord_fingering(chord, return_best_as_NoteContainer=True) if not self.add_notes(chord, duration): # This should be the standard behaviour of add_notes dur = self.bars[-1].value_left() self.add_notes(chord, dur) # warning should hold note self.add_notes(chord, value.subtract(duration, dur)) for c in chords: if c is not None: add_chord(c, duration) else: self.add_notes(None, duration) return self
[ "def", "from_chords", "(", "self", ",", "chords", ",", "duration", "=", "1", ")", ":", "tun", "=", "self", ".", "get_tuning", "(", ")", "def", "add_chord", "(", "chord", ",", "duration", ")", ":", "if", "type", "(", "chord", ")", "==", "list", ":", "for", "c", "in", "chord", ":", "add_chord", "(", "c", ",", "duration", "*", "2", ")", "else", ":", "chord", "=", "NoteContainer", "(", ")", ".", "from_chord", "(", "chord", ")", "if", "tun", ":", "chord", "=", "tun", ".", "find_chord_fingering", "(", "chord", ",", "return_best_as_NoteContainer", "=", "True", ")", "if", "not", "self", ".", "add_notes", "(", "chord", ",", "duration", ")", ":", "# This should be the standard behaviour of add_notes", "dur", "=", "self", ".", "bars", "[", "-", "1", "]", ".", "value_left", "(", ")", "self", ".", "add_notes", "(", "chord", ",", "dur", ")", "# warning should hold note", "self", ".", "add_notes", "(", "chord", ",", "value", ".", "subtract", "(", "duration", ",", "dur", ")", ")", "for", "c", "in", "chords", ":", "if", "c", "is", "not", "None", ":", "add_chord", "(", "c", ",", "duration", ")", "else", ":", "self", ".", "add_notes", "(", "None", ",", "duration", ")", "return", "self" ]
Add chords to the Track. The given chords should be a list of shorthand strings or list of list of shorthand strings, etc. Each sublist divides the value by 2. If a tuning is set, chords will be expanded so they have a proper fingering. Example: >>> t = Track().from_chords(['C', ['Am', 'Dm'], 'G7', 'C#'], 1)
[ "Add", "chords", "to", "the", "Track", "." ]
aa5a5d992d45ada61be0f9f86261380731bd7749
https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/containers/track.py#L89-L127
train
236,185
bspaans/python-mingus
mingus/containers/track.py
Track.get_tuning
def get_tuning(self): """Return a StringTuning object. If an instrument is set and has a tuning it will be returned. Otherwise the track's one will be used. """ if self.instrument and self.instrument.tuning: return self.instrument.tuning return self.tuning
python
def get_tuning(self): """Return a StringTuning object. If an instrument is set and has a tuning it will be returned. Otherwise the track's one will be used. """ if self.instrument and self.instrument.tuning: return self.instrument.tuning return self.tuning
[ "def", "get_tuning", "(", "self", ")", ":", "if", "self", ".", "instrument", "and", "self", ".", "instrument", ".", "tuning", ":", "return", "self", ".", "instrument", ".", "tuning", "return", "self", ".", "tuning" ]
Return a StringTuning object. If an instrument is set and has a tuning it will be returned. Otherwise the track's one will be used.
[ "Return", "a", "StringTuning", "object", "." ]
aa5a5d992d45ada61be0f9f86261380731bd7749
https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/containers/track.py#L129-L137
train
236,186
bspaans/python-mingus
mingus/containers/track.py
Track.transpose
def transpose(self, interval, up=True): """Transpose all the notes in the track up or down the interval. Call transpose() on every Bar. """ for bar in self.bars: bar.transpose(interval, up) return self
python
def transpose(self, interval, up=True): """Transpose all the notes in the track up or down the interval. Call transpose() on every Bar. """ for bar in self.bars: bar.transpose(interval, up) return self
[ "def", "transpose", "(", "self", ",", "interval", ",", "up", "=", "True", ")", ":", "for", "bar", "in", "self", ".", "bars", ":", "bar", ".", "transpose", "(", "interval", ",", "up", ")", "return", "self" ]
Transpose all the notes in the track up or down the interval. Call transpose() on every Bar.
[ "Transpose", "all", "the", "notes", "in", "the", "track", "up", "or", "down", "the", "interval", "." ]
aa5a5d992d45ada61be0f9f86261380731bd7749
https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/containers/track.py#L150-L157
train
236,187
bspaans/python-mingus
mingus/containers/bar.py
Bar.set_meter
def set_meter(self, meter): """Set the meter of this bar. Meters in mingus are represented by a single tuple. If the format of the meter is not recognised, a MeterFormatError will be raised. """ # warning should raise exception if _meter.valid_beat_duration(meter[1]): self.meter = (meter[0], meter[1]) self.length = meter[0] * (1.0 / meter[1]) elif meter == (0, 0): self.meter = (0, 0) self.length = 0.0 else: raise MeterFormatError("The meter argument '%s' is not an " "understood representation of a meter. " "Expecting a tuple." % meter)
python
def set_meter(self, meter): """Set the meter of this bar. Meters in mingus are represented by a single tuple. If the format of the meter is not recognised, a MeterFormatError will be raised. """ # warning should raise exception if _meter.valid_beat_duration(meter[1]): self.meter = (meter[0], meter[1]) self.length = meter[0] * (1.0 / meter[1]) elif meter == (0, 0): self.meter = (0, 0) self.length = 0.0 else: raise MeterFormatError("The meter argument '%s' is not an " "understood representation of a meter. " "Expecting a tuple." % meter)
[ "def", "set_meter", "(", "self", ",", "meter", ")", ":", "# warning should raise exception", "if", "_meter", ".", "valid_beat_duration", "(", "meter", "[", "1", "]", ")", ":", "self", ".", "meter", "=", "(", "meter", "[", "0", "]", ",", "meter", "[", "1", "]", ")", "self", ".", "length", "=", "meter", "[", "0", "]", "*", "(", "1.0", "/", "meter", "[", "1", "]", ")", "elif", "meter", "==", "(", "0", ",", "0", ")", ":", "self", ".", "meter", "=", "(", "0", ",", "0", ")", "self", ".", "length", "=", "0.0", "else", ":", "raise", "MeterFormatError", "(", "\"The meter argument '%s' is not an \"", "\"understood representation of a meter. \"", "\"Expecting a tuple.\"", "%", "meter", ")" ]
Set the meter of this bar. Meters in mingus are represented by a single tuple. If the format of the meter is not recognised, a MeterFormatError will be raised.
[ "Set", "the", "meter", "of", "this", "bar", "." ]
aa5a5d992d45ada61be0f9f86261380731bd7749
https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/containers/bar.py#L54-L72
train
236,188
bspaans/python-mingus
mingus/containers/bar.py
Bar.place_notes
def place_notes(self, notes, duration): """Place the notes on the current_beat. Notes can be strings, Notes, list of strings, list of Notes or a NoteContainer. Raise a MeterFormatError if the duration is not valid. Return True if succesful, False otherwise (ie. the Bar hasn't got enough room for a note of that duration). """ # note should be able to be one of strings, lists, Notes or # NoteContainers if hasattr(notes, 'notes'): pass elif hasattr(notes, 'name'): notes = NoteContainer(notes) elif type(notes) == str: notes = NoteContainer(notes) elif type(notes) == list: notes = NoteContainer(notes) if self.current_beat + 1.0 / duration <= self.length or self.length\ == 0.0: self.bar.append([self.current_beat, duration, notes]) self.current_beat += 1.0 / duration return True else: return False
python
def place_notes(self, notes, duration): """Place the notes on the current_beat. Notes can be strings, Notes, list of strings, list of Notes or a NoteContainer. Raise a MeterFormatError if the duration is not valid. Return True if succesful, False otherwise (ie. the Bar hasn't got enough room for a note of that duration). """ # note should be able to be one of strings, lists, Notes or # NoteContainers if hasattr(notes, 'notes'): pass elif hasattr(notes, 'name'): notes = NoteContainer(notes) elif type(notes) == str: notes = NoteContainer(notes) elif type(notes) == list: notes = NoteContainer(notes) if self.current_beat + 1.0 / duration <= self.length or self.length\ == 0.0: self.bar.append([self.current_beat, duration, notes]) self.current_beat += 1.0 / duration return True else: return False
[ "def", "place_notes", "(", "self", ",", "notes", ",", "duration", ")", ":", "# note should be able to be one of strings, lists, Notes or", "# NoteContainers", "if", "hasattr", "(", "notes", ",", "'notes'", ")", ":", "pass", "elif", "hasattr", "(", "notes", ",", "'name'", ")", ":", "notes", "=", "NoteContainer", "(", "notes", ")", "elif", "type", "(", "notes", ")", "==", "str", ":", "notes", "=", "NoteContainer", "(", "notes", ")", "elif", "type", "(", "notes", ")", "==", "list", ":", "notes", "=", "NoteContainer", "(", "notes", ")", "if", "self", ".", "current_beat", "+", "1.0", "/", "duration", "<=", "self", ".", "length", "or", "self", ".", "length", "==", "0.0", ":", "self", ".", "bar", ".", "append", "(", "[", "self", ".", "current_beat", ",", "duration", ",", "notes", "]", ")", "self", ".", "current_beat", "+=", "1.0", "/", "duration", "return", "True", "else", ":", "return", "False" ]
Place the notes on the current_beat. Notes can be strings, Notes, list of strings, list of Notes or a NoteContainer. Raise a MeterFormatError if the duration is not valid. Return True if succesful, False otherwise (ie. the Bar hasn't got enough room for a note of that duration).
[ "Place", "the", "notes", "on", "the", "current_beat", "." ]
aa5a5d992d45ada61be0f9f86261380731bd7749
https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/containers/bar.py#L74-L101
train
236,189
bspaans/python-mingus
mingus/containers/bar.py
Bar.place_notes_at
def place_notes_at(self, notes, at): """Place notes at the given index.""" for x in self.bar: if x[0] == at: x[0][2] += notes
python
def place_notes_at(self, notes, at): """Place notes at the given index.""" for x in self.bar: if x[0] == at: x[0][2] += notes
[ "def", "place_notes_at", "(", "self", ",", "notes", ",", "at", ")", ":", "for", "x", "in", "self", ".", "bar", ":", "if", "x", "[", "0", "]", "==", "at", ":", "x", "[", "0", "]", "[", "2", "]", "+=", "notes" ]
Place notes at the given index.
[ "Place", "notes", "at", "the", "given", "index", "." ]
aa5a5d992d45ada61be0f9f86261380731bd7749
https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/containers/bar.py#L103-L107
train
236,190
bspaans/python-mingus
mingus/containers/bar.py
Bar.remove_last_entry
def remove_last_entry(self): """Remove the last NoteContainer in the Bar.""" self.current_beat -= 1.0 / self.bar[-1][1] self.bar = self.bar[:-1] return self.current_beat
python
def remove_last_entry(self): """Remove the last NoteContainer in the Bar.""" self.current_beat -= 1.0 / self.bar[-1][1] self.bar = self.bar[:-1] return self.current_beat
[ "def", "remove_last_entry", "(", "self", ")", ":", "self", ".", "current_beat", "-=", "1.0", "/", "self", ".", "bar", "[", "-", "1", "]", "[", "1", "]", "self", ".", "bar", "=", "self", ".", "bar", "[", ":", "-", "1", "]", "return", "self", ".", "current_beat" ]
Remove the last NoteContainer in the Bar.
[ "Remove", "the", "last", "NoteContainer", "in", "the", "Bar", "." ]
aa5a5d992d45ada61be0f9f86261380731bd7749
https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/containers/bar.py#L116-L120
train
236,191
bspaans/python-mingus
mingus/containers/bar.py
Bar.is_full
def is_full(self): """Return False if there is room in this Bar for another NoteContainer, True otherwise.""" if self.length == 0.0: return False if len(self.bar) == 0: return False if self.current_beat >= self.length - 0.001: return True return False
python
def is_full(self): """Return False if there is room in this Bar for another NoteContainer, True otherwise.""" if self.length == 0.0: return False if len(self.bar) == 0: return False if self.current_beat >= self.length - 0.001: return True return False
[ "def", "is_full", "(", "self", ")", ":", "if", "self", ".", "length", "==", "0.0", ":", "return", "False", "if", "len", "(", "self", ".", "bar", ")", "==", "0", ":", "return", "False", "if", "self", ".", "current_beat", ">=", "self", ".", "length", "-", "0.001", ":", "return", "True", "return", "False" ]
Return False if there is room in this Bar for another NoteContainer, True otherwise.
[ "Return", "False", "if", "there", "is", "room", "in", "this", "Bar", "for", "another", "NoteContainer", "True", "otherwise", "." ]
aa5a5d992d45ada61be0f9f86261380731bd7749
https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/containers/bar.py#L122-L131
train
236,192
bspaans/python-mingus
mingus/containers/bar.py
Bar.change_note_duration
def change_note_duration(self, at, to): """Change the note duration at the given index to the given duration.""" if valid_beat_duration(to): diff = 0 for x in self.bar: if diff != 0: x[0][0] -= diff if x[0] == at: cur = x[0][1] x[0][1] = to diff = 1 / cur - 1 / to
python
def change_note_duration(self, at, to): """Change the note duration at the given index to the given duration.""" if valid_beat_duration(to): diff = 0 for x in self.bar: if diff != 0: x[0][0] -= diff if x[0] == at: cur = x[0][1] x[0][1] = to diff = 1 / cur - 1 / to
[ "def", "change_note_duration", "(", "self", ",", "at", ",", "to", ")", ":", "if", "valid_beat_duration", "(", "to", ")", ":", "diff", "=", "0", "for", "x", "in", "self", ".", "bar", ":", "if", "diff", "!=", "0", ":", "x", "[", "0", "]", "[", "0", "]", "-=", "diff", "if", "x", "[", "0", "]", "==", "at", ":", "cur", "=", "x", "[", "0", "]", "[", "1", "]", "x", "[", "0", "]", "[", "1", "]", "=", "to", "diff", "=", "1", "/", "cur", "-", "1", "/", "to" ]
Change the note duration at the given index to the given duration.
[ "Change", "the", "note", "duration", "at", "the", "given", "index", "to", "the", "given", "duration", "." ]
aa5a5d992d45ada61be0f9f86261380731bd7749
https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/containers/bar.py#L133-L144
train
236,193
bspaans/python-mingus
mingus/containers/bar.py
Bar.get_range
def get_range(self): """Return the highest and the lowest note in a tuple.""" (min, max) = (100000, -1) for cont in self.bar: for note in cont[2]: if int(note) < int(min): min = note elif int(note) > int(max): max = note return (min, max)
python
def get_range(self): """Return the highest and the lowest note in a tuple.""" (min, max) = (100000, -1) for cont in self.bar: for note in cont[2]: if int(note) < int(min): min = note elif int(note) > int(max): max = note return (min, max)
[ "def", "get_range", "(", "self", ")", ":", "(", "min", ",", "max", ")", "=", "(", "100000", ",", "-", "1", ")", "for", "cont", "in", "self", ".", "bar", ":", "for", "note", "in", "cont", "[", "2", "]", ":", "if", "int", "(", "note", ")", "<", "int", "(", "min", ")", ":", "min", "=", "note", "elif", "int", "(", "note", ")", ">", "int", "(", "max", ")", ":", "max", "=", "note", "return", "(", "min", ",", "max", ")" ]
Return the highest and the lowest note in a tuple.
[ "Return", "the", "highest", "and", "the", "lowest", "note", "in", "a", "tuple", "." ]
aa5a5d992d45ada61be0f9f86261380731bd7749
https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/containers/bar.py#L146-L155
train
236,194
bspaans/python-mingus
mingus/containers/bar.py
Bar.transpose
def transpose(self, interval, up=True): """Transpose the notes in the bar up or down the interval. Call transpose() on all NoteContainers in the bar. """ for cont in self.bar: cont[2].transpose(interval, up)
python
def transpose(self, interval, up=True): """Transpose the notes in the bar up or down the interval. Call transpose() on all NoteContainers in the bar. """ for cont in self.bar: cont[2].transpose(interval, up)
[ "def", "transpose", "(", "self", ",", "interval", ",", "up", "=", "True", ")", ":", "for", "cont", "in", "self", ".", "bar", ":", "cont", "[", "2", "]", ".", "transpose", "(", "interval", ",", "up", ")" ]
Transpose the notes in the bar up or down the interval. Call transpose() on all NoteContainers in the bar.
[ "Transpose", "the", "notes", "in", "the", "bar", "up", "or", "down", "the", "interval", "." ]
aa5a5d992d45ada61be0f9f86261380731bd7749
https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/containers/bar.py#L175-L181
train
236,195
bspaans/python-mingus
mingus/containers/bar.py
Bar.get_note_names
def get_note_names(self): """Return a list of unique note names in the Bar.""" res = [] for cont in self.bar: for x in cont[2].get_note_names(): if x not in res: res.append(x) return res
python
def get_note_names(self): """Return a list of unique note names in the Bar.""" res = [] for cont in self.bar: for x in cont[2].get_note_names(): if x not in res: res.append(x) return res
[ "def", "get_note_names", "(", "self", ")", ":", "res", "=", "[", "]", "for", "cont", "in", "self", ".", "bar", ":", "for", "x", "in", "cont", "[", "2", "]", ".", "get_note_names", "(", ")", ":", "if", "x", "not", "in", "res", ":", "res", ".", "append", "(", "x", ")", "return", "res" ]
Return a list of unique note names in the Bar.
[ "Return", "a", "list", "of", "unique", "note", "names", "in", "the", "Bar", "." ]
aa5a5d992d45ada61be0f9f86261380731bd7749
https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/containers/bar.py#L198-L205
train
236,196
bspaans/python-mingus
mingus/midi/midi_file_in.py
MidiFile.parse_midi_file_header
def parse_midi_file_header(self, fp): """Read the header of a MIDI file and return a tuple containing the format type, number of tracks and parsed time division information.""" # Check header try: if fp.read(4) != 'MThd': raise HeaderError('Not a valid MIDI file header. Byte %d.' % self.bytes_read) self.bytes_read += 4 except: raise IOError("Couldn't read from file.") # Parse chunk size try: chunk_size = self.bytes_to_int(fp.read(4)) self.bytes_read += 4 except: raise IOError("Couldn't read chunk size from file. Byte %d." % self.bytes_read) # Expect chunk size to be at least 6 if chunk_size < 6: return False try: format_type = self.bytes_to_int(fp.read(2)) self.bytes_read += 2 if format_type not in [0, 1, 2]: raise FormatError('%d is not a valid MIDI format.' % format_type) except: raise IOError("Couldn't read format type from file.") try: number_of_tracks = self.bytes_to_int(fp.read(2)) time_division = self.parse_time_division(fp.read(2)) self.bytes_read += 4 except: raise IOError("Couldn't read number of tracks " "and/or time division from tracks.") chunk_size -= 6 if chunk_size % 2 == 1: raise FormatError("Won't parse this.") fp.read(chunk_size / 2) self.bytes_read += chunk_size / 2 return (format_type, number_of_tracks, time_division)
python
def parse_midi_file_header(self, fp): """Read the header of a MIDI file and return a tuple containing the format type, number of tracks and parsed time division information.""" # Check header try: if fp.read(4) != 'MThd': raise HeaderError('Not a valid MIDI file header. Byte %d.' % self.bytes_read) self.bytes_read += 4 except: raise IOError("Couldn't read from file.") # Parse chunk size try: chunk_size = self.bytes_to_int(fp.read(4)) self.bytes_read += 4 except: raise IOError("Couldn't read chunk size from file. Byte %d." % self.bytes_read) # Expect chunk size to be at least 6 if chunk_size < 6: return False try: format_type = self.bytes_to_int(fp.read(2)) self.bytes_read += 2 if format_type not in [0, 1, 2]: raise FormatError('%d is not a valid MIDI format.' % format_type) except: raise IOError("Couldn't read format type from file.") try: number_of_tracks = self.bytes_to_int(fp.read(2)) time_division = self.parse_time_division(fp.read(2)) self.bytes_read += 4 except: raise IOError("Couldn't read number of tracks " "and/or time division from tracks.") chunk_size -= 6 if chunk_size % 2 == 1: raise FormatError("Won't parse this.") fp.read(chunk_size / 2) self.bytes_read += chunk_size / 2 return (format_type, number_of_tracks, time_division)
[ "def", "parse_midi_file_header", "(", "self", ",", "fp", ")", ":", "# Check header", "try", ":", "if", "fp", ".", "read", "(", "4", ")", "!=", "'MThd'", ":", "raise", "HeaderError", "(", "'Not a valid MIDI file header. Byte %d.'", "%", "self", ".", "bytes_read", ")", "self", ".", "bytes_read", "+=", "4", "except", ":", "raise", "IOError", "(", "\"Couldn't read from file.\"", ")", "# Parse chunk size", "try", ":", "chunk_size", "=", "self", ".", "bytes_to_int", "(", "fp", ".", "read", "(", "4", ")", ")", "self", ".", "bytes_read", "+=", "4", "except", ":", "raise", "IOError", "(", "\"Couldn't read chunk size from file. Byte %d.\"", "%", "self", ".", "bytes_read", ")", "# Expect chunk size to be at least 6", "if", "chunk_size", "<", "6", ":", "return", "False", "try", ":", "format_type", "=", "self", ".", "bytes_to_int", "(", "fp", ".", "read", "(", "2", ")", ")", "self", ".", "bytes_read", "+=", "2", "if", "format_type", "not", "in", "[", "0", ",", "1", ",", "2", "]", ":", "raise", "FormatError", "(", "'%d is not a valid MIDI format.'", "%", "format_type", ")", "except", ":", "raise", "IOError", "(", "\"Couldn't read format type from file.\"", ")", "try", ":", "number_of_tracks", "=", "self", ".", "bytes_to_int", "(", "fp", ".", "read", "(", "2", ")", ")", "time_division", "=", "self", ".", "parse_time_division", "(", "fp", ".", "read", "(", "2", ")", ")", "self", ".", "bytes_read", "+=", "4", "except", ":", "raise", "IOError", "(", "\"Couldn't read number of tracks \"", "\"and/or time division from tracks.\"", ")", "chunk_size", "-=", "6", "if", "chunk_size", "%", "2", "==", "1", ":", "raise", "FormatError", "(", "\"Won't parse this.\"", ")", "fp", ".", "read", "(", "chunk_size", "/", "2", ")", "self", ".", "bytes_read", "+=", "chunk_size", "/", "2", "return", "(", "format_type", ",", "number_of_tracks", ",", "time_division", ")" ]
Read the header of a MIDI file and return a tuple containing the format type, number of tracks and parsed time division information.
[ "Read", "the", "header", "of", "a", "MIDI", "file", "and", "return", "a", "tuple", "containing", "the", "format", "type", "number", "of", "tracks", "and", "parsed", "time", "division", "information", "." ]
aa5a5d992d45ada61be0f9f86261380731bd7749
https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/midi/midi_file_in.py#L171-L215
train
236,197
bspaans/python-mingus
mingus/midi/midi_file_in.py
MidiFile.parse_time_division
def parse_time_division(self, bytes): """Parse the time division found in the header of a MIDI file and return a dictionary with the boolean fps set to indicate whether to use frames per second or ticks per beat. If fps is True, the values SMPTE_frames and clock_ticks will also be set. If fps is False, ticks_per_beat will hold the value. """ # If highest bit is set, time division is set in frames per second # otherwise in ticks_per_beat value = self.bytes_to_int(bytes) if not value & 0x8000: return {'fps': False, 'ticks_per_beat': value & 0x7FFF} else: SMPTE_frames = (value & 0x7F00) >> 2 if SMPTE_frames not in [24, 25, 29, 30]: raise TimeDivisionError, \ "'%d' is not a valid value for the number of SMPTE frames"\ % SMPTE_frames clock_ticks = (value & 0x00FF) >> 2 return {'fps': True, 'SMPTE_frames': SMPTE_frames, 'clock_ticks': clock_ticks}
python
def parse_time_division(self, bytes): """Parse the time division found in the header of a MIDI file and return a dictionary with the boolean fps set to indicate whether to use frames per second or ticks per beat. If fps is True, the values SMPTE_frames and clock_ticks will also be set. If fps is False, ticks_per_beat will hold the value. """ # If highest bit is set, time division is set in frames per second # otherwise in ticks_per_beat value = self.bytes_to_int(bytes) if not value & 0x8000: return {'fps': False, 'ticks_per_beat': value & 0x7FFF} else: SMPTE_frames = (value & 0x7F00) >> 2 if SMPTE_frames not in [24, 25, 29, 30]: raise TimeDivisionError, \ "'%d' is not a valid value for the number of SMPTE frames"\ % SMPTE_frames clock_ticks = (value & 0x00FF) >> 2 return {'fps': True, 'SMPTE_frames': SMPTE_frames, 'clock_ticks': clock_ticks}
[ "def", "parse_time_division", "(", "self", ",", "bytes", ")", ":", "# If highest bit is set, time division is set in frames per second", "# otherwise in ticks_per_beat", "value", "=", "self", ".", "bytes_to_int", "(", "bytes", ")", "if", "not", "value", "&", "0x8000", ":", "return", "{", "'fps'", ":", "False", ",", "'ticks_per_beat'", ":", "value", "&", "0x7FFF", "}", "else", ":", "SMPTE_frames", "=", "(", "value", "&", "0x7F00", ")", ">>", "2", "if", "SMPTE_frames", "not", "in", "[", "24", ",", "25", ",", "29", ",", "30", "]", ":", "raise", "TimeDivisionError", ",", "\"'%d' is not a valid value for the number of SMPTE frames\"", "%", "SMPTE_frames", "clock_ticks", "=", "(", "value", "&", "0x00FF", ")", ">>", "2", "return", "{", "'fps'", ":", "True", ",", "'SMPTE_frames'", ":", "SMPTE_frames", ",", "'clock_ticks'", ":", "clock_ticks", "}" ]
Parse the time division found in the header of a MIDI file and return a dictionary with the boolean fps set to indicate whether to use frames per second or ticks per beat. If fps is True, the values SMPTE_frames and clock_ticks will also be set. If fps is False, ticks_per_beat will hold the value.
[ "Parse", "the", "time", "division", "found", "in", "the", "header", "of", "a", "MIDI", "file", "and", "return", "a", "dictionary", "with", "the", "boolean", "fps", "set", "to", "indicate", "whether", "to", "use", "frames", "per", "second", "or", "ticks", "per", "beat", "." ]
aa5a5d992d45ada61be0f9f86261380731bd7749
https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/midi/midi_file_in.py#L220-L241
train
236,198
bspaans/python-mingus
mingus/midi/midi_file_in.py
MidiFile.parse_track
def parse_track(self, fp): """Parse a MIDI track from its header to its events. Return a list of events and the number of bytes that were read. """ events = [] chunk_size = self.parse_track_header(fp) bytes = chunk_size while chunk_size > 0: (delta_time, chunk_delta) = self.parse_varbyte_as_int(fp) chunk_size -= chunk_delta (event, chunk_delta) = self.parse_midi_event(fp) chunk_size -= chunk_delta events.append([delta_time, event]) if chunk_size < 0: print 'yikes.', self.bytes_read, chunk_size return events
python
def parse_track(self, fp): """Parse a MIDI track from its header to its events. Return a list of events and the number of bytes that were read. """ events = [] chunk_size = self.parse_track_header(fp) bytes = chunk_size while chunk_size > 0: (delta_time, chunk_delta) = self.parse_varbyte_as_int(fp) chunk_size -= chunk_delta (event, chunk_delta) = self.parse_midi_event(fp) chunk_size -= chunk_delta events.append([delta_time, event]) if chunk_size < 0: print 'yikes.', self.bytes_read, chunk_size return events
[ "def", "parse_track", "(", "self", ",", "fp", ")", ":", "events", "=", "[", "]", "chunk_size", "=", "self", ".", "parse_track_header", "(", "fp", ")", "bytes", "=", "chunk_size", "while", "chunk_size", ">", "0", ":", "(", "delta_time", ",", "chunk_delta", ")", "=", "self", ".", "parse_varbyte_as_int", "(", "fp", ")", "chunk_size", "-=", "chunk_delta", "(", "event", ",", "chunk_delta", ")", "=", "self", ".", "parse_midi_event", "(", "fp", ")", "chunk_size", "-=", "chunk_delta", "events", ".", "append", "(", "[", "delta_time", ",", "event", "]", ")", "if", "chunk_size", "<", "0", ":", "print", "'yikes.'", ",", "self", ".", "bytes_read", ",", "chunk_size", "return", "events" ]
Parse a MIDI track from its header to its events. Return a list of events and the number of bytes that were read.
[ "Parse", "a", "MIDI", "track", "from", "its", "header", "to", "its", "events", "." ]
aa5a5d992d45ada61be0f9f86261380731bd7749
https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/midi/midi_file_in.py#L243-L259
train
236,199