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
CLARIAH/grlc
src/swagger.py
get_repo_info
def get_repo_info(loader, sha, prov_g): """Generate swagger information from the repo being used.""" user_repo = loader.getFullName() repo_title = loader.getRepoTitle() contact_name = loader.getContactName() contact_url = loader.getContactUrl() commit_list = loader.getCommitList() licence_url = loader.getLicenceURL() # Add the API URI as a used entity by the activity if prov_g: prov_g.add_used_entity(loader.getRepoURI()) prev_commit = None next_commit = None version = sha if sha else commit_list[0] if commit_list.index(version) < len(commit_list) - 1: prev_commit = commit_list[commit_list.index(version) + 1] if commit_list.index(version) > 0: next_commit = commit_list[commit_list.index(version) - 1] info = { 'version': version, 'title': repo_title, 'contact': { 'name': contact_name, 'url': contact_url }, 'license': { 'name': 'License', 'url': licence_url } } basePath = '/api/' + user_repo + '/' basePath += ('commit/' + sha + '/') if sha else '' return prev_commit, next_commit, info, basePath
python
def get_repo_info(loader, sha, prov_g): """Generate swagger information from the repo being used.""" user_repo = loader.getFullName() repo_title = loader.getRepoTitle() contact_name = loader.getContactName() contact_url = loader.getContactUrl() commit_list = loader.getCommitList() licence_url = loader.getLicenceURL() # Add the API URI as a used entity by the activity if prov_g: prov_g.add_used_entity(loader.getRepoURI()) prev_commit = None next_commit = None version = sha if sha else commit_list[0] if commit_list.index(version) < len(commit_list) - 1: prev_commit = commit_list[commit_list.index(version) + 1] if commit_list.index(version) > 0: next_commit = commit_list[commit_list.index(version) - 1] info = { 'version': version, 'title': repo_title, 'contact': { 'name': contact_name, 'url': contact_url }, 'license': { 'name': 'License', 'url': licence_url } } basePath = '/api/' + user_repo + '/' basePath += ('commit/' + sha + '/') if sha else '' return prev_commit, next_commit, info, basePath
[ "def", "get_repo_info", "(", "loader", ",", "sha", ",", "prov_g", ")", ":", "user_repo", "=", "loader", ".", "getFullName", "(", ")", "repo_title", "=", "loader", ".", "getRepoTitle", "(", ")", "contact_name", "=", "loader", ".", "getContactName", "(", ")"...
Generate swagger information from the repo being used.
[ "Generate", "swagger", "information", "from", "the", "repo", "being", "used", "." ]
f5664e34f039010c00ef8ebb69917c05e8ce75d7
https://github.com/CLARIAH/grlc/blob/f5664e34f039010c00ef8ebb69917c05e8ce75d7/src/swagger.py#L24-L61
train
24,200
CLARIAH/grlc
src/pagination.py
buildPaginationHeader
def buildPaginationHeader(resultCount, resultsPerPage, pageArg, url): '''Build link header for result pagination''' lastPage = resultCount / resultsPerPage if pageArg: page = int(pageArg) next_url = re.sub("page=[0-9]+", "page={}".format(page + 1), url) prev_url = re.sub("page=[0-9]+", "page={}".format(page - 1), url) first_url = re.sub("page=[0-9]+", "page=1", url) last_url = re.sub("page=[0-9]+", "page={}".format(lastPage), url) else: page = 1 next_url = url + "?page=2" prev_url = "" first_url = url + "?page=1" last_url = url + "?page={}".format(lastPage) if page == 1: headerLink = "<{}>; rel=next, <{}>; rel=last".format(next_url, last_url) elif page == lastPage: headerLink = "<{}>; rel=prev, <{}>; rel=first".format(prev_url, first_url) else: headerLink = "<{}>; rel=next, <{}>; rel=prev, <{}>; rel=first, <{}>; rel=last".format(next_url, prev_url, first_url, last_url) return headerLink
python
def buildPaginationHeader(resultCount, resultsPerPage, pageArg, url): '''Build link header for result pagination''' lastPage = resultCount / resultsPerPage if pageArg: page = int(pageArg) next_url = re.sub("page=[0-9]+", "page={}".format(page + 1), url) prev_url = re.sub("page=[0-9]+", "page={}".format(page - 1), url) first_url = re.sub("page=[0-9]+", "page=1", url) last_url = re.sub("page=[0-9]+", "page={}".format(lastPage), url) else: page = 1 next_url = url + "?page=2" prev_url = "" first_url = url + "?page=1" last_url = url + "?page={}".format(lastPage) if page == 1: headerLink = "<{}>; rel=next, <{}>; rel=last".format(next_url, last_url) elif page == lastPage: headerLink = "<{}>; rel=prev, <{}>; rel=first".format(prev_url, first_url) else: headerLink = "<{}>; rel=next, <{}>; rel=prev, <{}>; rel=first, <{}>; rel=last".format(next_url, prev_url, first_url, last_url) return headerLink
[ "def", "buildPaginationHeader", "(", "resultCount", ",", "resultsPerPage", ",", "pageArg", ",", "url", ")", ":", "lastPage", "=", "resultCount", "/", "resultsPerPage", "if", "pageArg", ":", "page", "=", "int", "(", "pageArg", ")", "next_url", "=", "re", ".",...
Build link header for result pagination
[ "Build", "link", "header", "for", "result", "pagination" ]
f5664e34f039010c00ef8ebb69917c05e8ce75d7
https://github.com/CLARIAH/grlc/blob/f5664e34f039010c00ef8ebb69917c05e8ce75d7/src/pagination.py#L12-L35
train
24,201
goerz/better-apidoc
better_apidoc.py
format_directive
def format_directive(module, package=None): # type: (unicode, unicode) -> unicode """Create the automodule directive and add the options.""" directive = '.. automodule:: %s\n' % makename(package, module) for option in OPTIONS: directive += ' :%s:\n' % option return directive
python
def format_directive(module, package=None): # type: (unicode, unicode) -> unicode """Create the automodule directive and add the options.""" directive = '.. automodule:: %s\n' % makename(package, module) for option in OPTIONS: directive += ' :%s:\n' % option return directive
[ "def", "format_directive", "(", "module", ",", "package", "=", "None", ")", ":", "# type: (unicode, unicode) -> unicode", "directive", "=", "'.. automodule:: %s\\n'", "%", "makename", "(", "package", ",", "module", ")", "for", "option", "in", "OPTIONS", ":", "dire...
Create the automodule directive and add the options.
[ "Create", "the", "automodule", "directive", "and", "add", "the", "options", "." ]
bbf979e01d7eff1a597c2608ef2609d1e83e8001
https://github.com/goerz/better-apidoc/blob/bbf979e01d7eff1a597c2608ef2609d1e83e8001/better_apidoc.py#L116-L122
train
24,202
goerz/better-apidoc
better_apidoc.py
extract_summary
def extract_summary(obj): # type: (List[unicode], Any) -> unicode """Extract summary from docstring.""" try: doc = inspect.getdoc(obj).split("\n") except AttributeError: doc = '' # Skip a blank lines at the top while doc and not doc[0].strip(): doc.pop(0) # If there's a blank line, then we can assume the first sentence / # paragraph has ended, so anything after shouldn't be part of the # summary for i, piece in enumerate(doc): if not piece.strip(): doc = doc[:i] break # Try to find the "first sentence", which may span multiple lines sentences = periods_re.split(" ".join(doc)) # type: ignore if len(sentences) == 1: summary = sentences[0].strip() else: summary = '' state_machine = RSTStateMachine(state_classes, 'Body') while sentences: summary += sentences.pop(0) + '.' node = new_document('') node.reporter = NullReporter('', 999, 4) node.settings.pep_references = None node.settings.rfc_references = None state_machine.run([summary], node) if not node.traverse(nodes.system_message): # considered as that splitting by period does not break inline # markups break return summary
python
def extract_summary(obj): # type: (List[unicode], Any) -> unicode """Extract summary from docstring.""" try: doc = inspect.getdoc(obj).split("\n") except AttributeError: doc = '' # Skip a blank lines at the top while doc and not doc[0].strip(): doc.pop(0) # If there's a blank line, then we can assume the first sentence / # paragraph has ended, so anything after shouldn't be part of the # summary for i, piece in enumerate(doc): if not piece.strip(): doc = doc[:i] break # Try to find the "first sentence", which may span multiple lines sentences = periods_re.split(" ".join(doc)) # type: ignore if len(sentences) == 1: summary = sentences[0].strip() else: summary = '' state_machine = RSTStateMachine(state_classes, 'Body') while sentences: summary += sentences.pop(0) + '.' node = new_document('') node.reporter = NullReporter('', 999, 4) node.settings.pep_references = None node.settings.rfc_references = None state_machine.run([summary], node) if not node.traverse(nodes.system_message): # considered as that splitting by period does not break inline # markups break return summary
[ "def", "extract_summary", "(", "obj", ")", ":", "# type: (List[unicode], Any) -> unicode", "try", ":", "doc", "=", "inspect", ".", "getdoc", "(", "obj", ")", ".", "split", "(", "\"\\n\"", ")", "except", "AttributeError", ":", "doc", "=", "''", "# Skip a blank ...
Extract summary from docstring.
[ "Extract", "summary", "from", "docstring", "." ]
bbf979e01d7eff1a597c2608ef2609d1e83e8001
https://github.com/goerz/better-apidoc/blob/bbf979e01d7eff1a597c2608ef2609d1e83e8001/better_apidoc.py#L272-L312
train
24,203
goerz/better-apidoc
better_apidoc.py
_get_member_ref_str
def _get_member_ref_str(name, obj, role='obj', known_refs=None): """generate a ReST-formmated reference link to the given `obj` of type `role`, using `name` as the link text""" if known_refs is not None: if name in known_refs: return known_refs[name] ref = _get_fullname(name, obj) return ":%s:`%s <%s>`" % (role, name, ref)
python
def _get_member_ref_str(name, obj, role='obj', known_refs=None): """generate a ReST-formmated reference link to the given `obj` of type `role`, using `name` as the link text""" if known_refs is not None: if name in known_refs: return known_refs[name] ref = _get_fullname(name, obj) return ":%s:`%s <%s>`" % (role, name, ref)
[ "def", "_get_member_ref_str", "(", "name", ",", "obj", ",", "role", "=", "'obj'", ",", "known_refs", "=", "None", ")", ":", "if", "known_refs", "is", "not", "None", ":", "if", "name", "in", "known_refs", ":", "return", "known_refs", "[", "name", "]", "...
generate a ReST-formmated reference link to the given `obj` of type `role`, using `name` as the link text
[ "generate", "a", "ReST", "-", "formmated", "reference", "link", "to", "the", "given", "obj", "of", "type", "role", "using", "name", "as", "the", "link", "text" ]
bbf979e01d7eff1a597c2608ef2609d1e83e8001
https://github.com/goerz/better-apidoc/blob/bbf979e01d7eff1a597c2608ef2609d1e83e8001/better_apidoc.py#L315-L322
train
24,204
goerz/better-apidoc
better_apidoc.py
_get_mod_ns
def _get_mod_ns(name, fullname, includeprivate): """Return the template context of module identified by `fullname` as a dict""" ns = { # template variables 'name': name, 'fullname': fullname, 'members': [], 'functions': [], 'classes': [], 'exceptions': [], 'subpackages': [], 'submodules': [], 'doc': None} p = 0 if includeprivate: p = 1 mod = importlib.import_module(fullname) ns['members'] = _get_members(mod)[p] ns['functions'] = _get_members(mod, typ='function')[p] ns['classes'] = _get_members(mod, typ='class')[p] ns['exceptions'] = _get_members(mod, typ='exception')[p] ns['data'] = _get_members(mod, typ='data')[p] ns['doc'] = mod.__doc__ return ns
python
def _get_mod_ns(name, fullname, includeprivate): """Return the template context of module identified by `fullname` as a dict""" ns = { # template variables 'name': name, 'fullname': fullname, 'members': [], 'functions': [], 'classes': [], 'exceptions': [], 'subpackages': [], 'submodules': [], 'doc': None} p = 0 if includeprivate: p = 1 mod = importlib.import_module(fullname) ns['members'] = _get_members(mod)[p] ns['functions'] = _get_members(mod, typ='function')[p] ns['classes'] = _get_members(mod, typ='class')[p] ns['exceptions'] = _get_members(mod, typ='exception')[p] ns['data'] = _get_members(mod, typ='data')[p] ns['doc'] = mod.__doc__ return ns
[ "def", "_get_mod_ns", "(", "name", ",", "fullname", ",", "includeprivate", ")", ":", "ns", "=", "{", "# template variables", "'name'", ":", "name", ",", "'fullname'", ":", "fullname", ",", "'members'", ":", "[", "]", ",", "'functions'", ":", "[", "]", ",...
Return the template context of module identified by `fullname` as a dict
[ "Return", "the", "template", "context", "of", "module", "identified", "by", "fullname", "as", "a", "dict" ]
bbf979e01d7eff1a597c2608ef2609d1e83e8001
https://github.com/goerz/better-apidoc/blob/bbf979e01d7eff1a597c2608ef2609d1e83e8001/better_apidoc.py#L345-L362
train
24,205
ValvePython/vdf
vdf/vdict.py
VDFDict.get_all_for
def get_all_for(self, key): """ Returns all values of the given key """ if not isinstance(key, _string_type): raise TypeError("Key needs to be a string.") return [self[(idx, key)] for idx in _range(self.__kcount[key])]
python
def get_all_for(self, key): """ Returns all values of the given key """ if not isinstance(key, _string_type): raise TypeError("Key needs to be a string.") return [self[(idx, key)] for idx in _range(self.__kcount[key])]
[ "def", "get_all_for", "(", "self", ",", "key", ")", ":", "if", "not", "isinstance", "(", "key", ",", "_string_type", ")", ":", "raise", "TypeError", "(", "\"Key needs to be a string.\"", ")", "return", "[", "self", "[", "(", "idx", ",", "key", ")", "]", ...
Returns all values of the given key
[ "Returns", "all", "values", "of", "the", "given", "key" ]
4b168702736f51318baa3a12aa5a2827d360f94a
https://github.com/ValvePython/vdf/blob/4b168702736f51318baa3a12aa5a2827d360f94a/vdf/vdict.py#L186-L190
train
24,206
ValvePython/vdf
vdf/vdict.py
VDFDict.remove_all_for
def remove_all_for(self, key): """ Removes all items with the given key """ if not isinstance(key, _string_type): raise TypeError("Key need to be a string.") for idx in _range(self.__kcount[key]): super(VDFDict, self).__delitem__((idx, key)) self.__omap = list(filter(lambda x: x[1] != key, self.__omap)) del self.__kcount[key]
python
def remove_all_for(self, key): """ Removes all items with the given key """ if not isinstance(key, _string_type): raise TypeError("Key need to be a string.") for idx in _range(self.__kcount[key]): super(VDFDict, self).__delitem__((idx, key)) self.__omap = list(filter(lambda x: x[1] != key, self.__omap)) del self.__kcount[key]
[ "def", "remove_all_for", "(", "self", ",", "key", ")", ":", "if", "not", "isinstance", "(", "key", ",", "_string_type", ")", ":", "raise", "TypeError", "(", "\"Key need to be a string.\"", ")", "for", "idx", "in", "_range", "(", "self", ".", "__kcount", "[...
Removes all items with the given key
[ "Removes", "all", "items", "with", "the", "given", "key" ]
4b168702736f51318baa3a12aa5a2827d360f94a
https://github.com/ValvePython/vdf/blob/4b168702736f51318baa3a12aa5a2827d360f94a/vdf/vdict.py#L192-L202
train
24,207
ValvePython/vdf
vdf/vdict.py
VDFDict.has_duplicates
def has_duplicates(self): """ Returns ``True`` if the dict contains keys with duplicates. Recurses through any all keys with value that is ``VDFDict``. """ for n in getattr(self.__kcount, _iter_values)(): if n != 1: return True def dict_recurse(obj): for v in getattr(obj, _iter_values)(): if isinstance(v, VDFDict) and v.has_duplicates(): return True elif isinstance(v, dict): return dict_recurse(v) return False return dict_recurse(self)
python
def has_duplicates(self): """ Returns ``True`` if the dict contains keys with duplicates. Recurses through any all keys with value that is ``VDFDict``. """ for n in getattr(self.__kcount, _iter_values)(): if n != 1: return True def dict_recurse(obj): for v in getattr(obj, _iter_values)(): if isinstance(v, VDFDict) and v.has_duplicates(): return True elif isinstance(v, dict): return dict_recurse(v) return False return dict_recurse(self)
[ "def", "has_duplicates", "(", "self", ")", ":", "for", "n", "in", "getattr", "(", "self", ".", "__kcount", ",", "_iter_values", ")", "(", ")", ":", "if", "n", "!=", "1", ":", "return", "True", "def", "dict_recurse", "(", "obj", ")", ":", "for", "v"...
Returns ``True`` if the dict contains keys with duplicates. Recurses through any all keys with value that is ``VDFDict``.
[ "Returns", "True", "if", "the", "dict", "contains", "keys", "with", "duplicates", ".", "Recurses", "through", "any", "all", "keys", "with", "value", "that", "is", "VDFDict", "." ]
4b168702736f51318baa3a12aa5a2827d360f94a
https://github.com/ValvePython/vdf/blob/4b168702736f51318baa3a12aa5a2827d360f94a/vdf/vdict.py#L204-L221
train
24,208
ValvePython/vdf
vdf/__init__.py
dumps
def dumps(obj, pretty=False, escaped=True): """ Serialize ``obj`` to a VDF formatted ``str``. """ if not isinstance(obj, dict): raise TypeError("Expected data to be an instance of``dict``") if not isinstance(pretty, bool): raise TypeError("Expected pretty to be of type bool") if not isinstance(escaped, bool): raise TypeError("Expected escaped to be of type bool") return ''.join(_dump_gen(obj, pretty, escaped))
python
def dumps(obj, pretty=False, escaped=True): """ Serialize ``obj`` to a VDF formatted ``str``. """ if not isinstance(obj, dict): raise TypeError("Expected data to be an instance of``dict``") if not isinstance(pretty, bool): raise TypeError("Expected pretty to be of type bool") if not isinstance(escaped, bool): raise TypeError("Expected escaped to be of type bool") return ''.join(_dump_gen(obj, pretty, escaped))
[ "def", "dumps", "(", "obj", ",", "pretty", "=", "False", ",", "escaped", "=", "True", ")", ":", "if", "not", "isinstance", "(", "obj", ",", "dict", ")", ":", "raise", "TypeError", "(", "\"Expected data to be an instance of``dict``\"", ")", "if", "not", "is...
Serialize ``obj`` to a VDF formatted ``str``.
[ "Serialize", "obj", "to", "a", "VDF", "formatted", "str", "." ]
4b168702736f51318baa3a12aa5a2827d360f94a
https://github.com/ValvePython/vdf/blob/4b168702736f51318baa3a12aa5a2827d360f94a/vdf/__init__.py#L189-L200
train
24,209
ValvePython/vdf
vdf/__init__.py
binary_dumps
def binary_dumps(obj, alt_format=False): """ Serialize ``obj`` to a binary VDF formatted ``bytes``. """ return b''.join(_binary_dump_gen(obj, alt_format=alt_format))
python
def binary_dumps(obj, alt_format=False): """ Serialize ``obj`` to a binary VDF formatted ``bytes``. """ return b''.join(_binary_dump_gen(obj, alt_format=alt_format))
[ "def", "binary_dumps", "(", "obj", ",", "alt_format", "=", "False", ")", ":", "return", "b''", ".", "join", "(", "_binary_dump_gen", "(", "obj", ",", "alt_format", "=", "alt_format", ")", ")" ]
Serialize ``obj`` to a binary VDF formatted ``bytes``.
[ "Serialize", "obj", "to", "a", "binary", "VDF", "formatted", "bytes", "." ]
4b168702736f51318baa3a12aa5a2827d360f94a
https://github.com/ValvePython/vdf/blob/4b168702736f51318baa3a12aa5a2827d360f94a/vdf/__init__.py#L367-L371
train
24,210
ValvePython/vdf
vdf/__init__.py
vbkv_loads
def vbkv_loads(s, mapper=dict, merge_duplicate_keys=True): """ Deserialize ``s`` (``bytes`` containing a VBKV to a Python object. ``mapper`` specifies the Python object used after deserializetion. ``dict` is used by default. Alternatively, ``collections.OrderedDict`` can be used if you wish to preserve key order. Or any object that acts like a ``dict``. ``merge_duplicate_keys`` when ``True`` will merge multiple KeyValue lists with the same key into one instead of overwriting. You can se this to ``False`` if you are using ``VDFDict`` and need to preserve the duplicates. """ if s[:4] != b'VBKV': raise ValueError("Invalid header") checksum, = struct.unpack('<i', s[4:8]) if checksum != crc32(s[8:]): raise ValueError("Invalid checksum") return binary_loads(s[8:], mapper, merge_duplicate_keys, alt_format=True)
python
def vbkv_loads(s, mapper=dict, merge_duplicate_keys=True): """ Deserialize ``s`` (``bytes`` containing a VBKV to a Python object. ``mapper`` specifies the Python object used after deserializetion. ``dict` is used by default. Alternatively, ``collections.OrderedDict`` can be used if you wish to preserve key order. Or any object that acts like a ``dict``. ``merge_duplicate_keys`` when ``True`` will merge multiple KeyValue lists with the same key into one instead of overwriting. You can se this to ``False`` if you are using ``VDFDict`` and need to preserve the duplicates. """ if s[:4] != b'VBKV': raise ValueError("Invalid header") checksum, = struct.unpack('<i', s[4:8]) if checksum != crc32(s[8:]): raise ValueError("Invalid checksum") return binary_loads(s[8:], mapper, merge_duplicate_keys, alt_format=True)
[ "def", "vbkv_loads", "(", "s", ",", "mapper", "=", "dict", ",", "merge_duplicate_keys", "=", "True", ")", ":", "if", "s", "[", ":", "4", "]", "!=", "b'VBKV'", ":", "raise", "ValueError", "(", "\"Invalid header\"", ")", "checksum", ",", "=", "struct", "...
Deserialize ``s`` (``bytes`` containing a VBKV to a Python object. ``mapper`` specifies the Python object used after deserializetion. ``dict` is used by default. Alternatively, ``collections.OrderedDict`` can be used if you wish to preserve key order. Or any object that acts like a ``dict``. ``merge_duplicate_keys`` when ``True`` will merge multiple KeyValue lists with the same key into one instead of overwriting. You can se this to ``False`` if you are using ``VDFDict`` and need to preserve the duplicates.
[ "Deserialize", "s", "(", "bytes", "containing", "a", "VBKV", "to", "a", "Python", "object", "." ]
4b168702736f51318baa3a12aa5a2827d360f94a
https://github.com/ValvePython/vdf/blob/4b168702736f51318baa3a12aa5a2827d360f94a/vdf/__init__.py#L421-L441
train
24,211
ValvePython/vdf
vdf/__init__.py
vbkv_dumps
def vbkv_dumps(obj): """ Serialize ``obj`` to a VBKV formatted ``bytes``. """ data = b''.join(_binary_dump_gen(obj, alt_format=True)) checksum = crc32(data) return b'VBKV' + struct.pack('<i', checksum) + data
python
def vbkv_dumps(obj): """ Serialize ``obj`` to a VBKV formatted ``bytes``. """ data = b''.join(_binary_dump_gen(obj, alt_format=True)) checksum = crc32(data) return b'VBKV' + struct.pack('<i', checksum) + data
[ "def", "vbkv_dumps", "(", "obj", ")", ":", "data", "=", "b''", ".", "join", "(", "_binary_dump_gen", "(", "obj", ",", "alt_format", "=", "True", ")", ")", "checksum", "=", "crc32", "(", "data", ")", "return", "b'VBKV'", "+", "struct", ".", "pack", "(...
Serialize ``obj`` to a VBKV formatted ``bytes``.
[ "Serialize", "obj", "to", "a", "VBKV", "formatted", "bytes", "." ]
4b168702736f51318baa3a12aa5a2827d360f94a
https://github.com/ValvePython/vdf/blob/4b168702736f51318baa3a12aa5a2827d360f94a/vdf/__init__.py#L443-L450
train
24,212
ldo/dbussy
dbussy.py
signature_validate
def signature_validate(signature, error = None) : "is signature a valid sequence of zero or more complete types." error, my_error = _get_error(error) result = dbus.dbus_signature_validate(signature.encode(), error._dbobj) != 0 my_error.raise_if_set() return \ result
python
def signature_validate(signature, error = None) : "is signature a valid sequence of zero or more complete types." error, my_error = _get_error(error) result = dbus.dbus_signature_validate(signature.encode(), error._dbobj) != 0 my_error.raise_if_set() return \ result
[ "def", "signature_validate", "(", "signature", ",", "error", "=", "None", ")", ":", "error", ",", "my_error", "=", "_get_error", "(", "error", ")", "result", "=", "dbus", ".", "dbus_signature_validate", "(", "signature", ".", "encode", "(", ")", ",", "erro...
is signature a valid sequence of zero or more complete types.
[ "is", "signature", "a", "valid", "sequence", "of", "zero", "or", "more", "complete", "types", "." ]
59e4fbe8b8111ceead884e50d1973901a0a2d240
https://github.com/ldo/dbussy/blob/59e4fbe8b8111ceead884e50d1973901a0a2d240/dbussy.py#L5539-L5545
train
24,213
ldo/dbussy
dbussy.py
unparse_signature
def unparse_signature(signature) : "converts a signature from parsed form to string form." signature = parse_signature(signature) if not isinstance(signature, (tuple, list)) : signature = [signature] #end if return \ DBUS.Signature("".join(t.signature for t in signature))
python
def unparse_signature(signature) : "converts a signature from parsed form to string form." signature = parse_signature(signature) if not isinstance(signature, (tuple, list)) : signature = [signature] #end if return \ DBUS.Signature("".join(t.signature for t in signature))
[ "def", "unparse_signature", "(", "signature", ")", ":", "signature", "=", "parse_signature", "(", "signature", ")", "if", "not", "isinstance", "(", "signature", ",", "(", "tuple", ",", "list", ")", ")", ":", "signature", "=", "[", "signature", "]", "#end i...
converts a signature from parsed form to string form.
[ "converts", "a", "signature", "from", "parsed", "form", "to", "string", "form", "." ]
59e4fbe8b8111ceead884e50d1973901a0a2d240
https://github.com/ldo/dbussy/blob/59e4fbe8b8111ceead884e50d1973901a0a2d240/dbussy.py#L5616-L5623
train
24,214
ldo/dbussy
dbussy.py
signature_validate_single
def signature_validate_single(signature, error = None) : "is signature a single valid type." error, my_error = _get_error(error) result = dbus.dbus_signature_validate_single(signature.encode(), error._dbobj) != 0 my_error.raise_if_set() return \ result
python
def signature_validate_single(signature, error = None) : "is signature a single valid type." error, my_error = _get_error(error) result = dbus.dbus_signature_validate_single(signature.encode(), error._dbobj) != 0 my_error.raise_if_set() return \ result
[ "def", "signature_validate_single", "(", "signature", ",", "error", "=", "None", ")", ":", "error", ",", "my_error", "=", "_get_error", "(", "error", ")", "result", "=", "dbus", ".", "dbus_signature_validate_single", "(", "signature", ".", "encode", "(", ")", ...
is signature a single valid type.
[ "is", "signature", "a", "single", "valid", "type", "." ]
59e4fbe8b8111ceead884e50d1973901a0a2d240
https://github.com/ldo/dbussy/blob/59e4fbe8b8111ceead884e50d1973901a0a2d240/dbussy.py#L5626-L5632
train
24,215
ldo/dbussy
dbussy.py
split_path
def split_path(path) : "convenience routine for splitting a path into a list of components." if isinstance(path, (tuple, list)) : result = path # assume already split elif path == "/" : result = [] else : if not path.startswith("/") or path.endswith("/") : raise DBusError(DBUS.ERROR_INVALID_ARGS, "invalid path %s" % repr(path)) #end if result = path.split("/")[1:] #end if return \ result
python
def split_path(path) : "convenience routine for splitting a path into a list of components." if isinstance(path, (tuple, list)) : result = path # assume already split elif path == "/" : result = [] else : if not path.startswith("/") or path.endswith("/") : raise DBusError(DBUS.ERROR_INVALID_ARGS, "invalid path %s" % repr(path)) #end if result = path.split("/")[1:] #end if return \ result
[ "def", "split_path", "(", "path", ")", ":", "if", "isinstance", "(", "path", ",", "(", "tuple", ",", "list", ")", ")", ":", "result", "=", "path", "# assume already split", "elif", "path", "==", "\"/\"", ":", "result", "=", "[", "]", "else", ":", "if...
convenience routine for splitting a path into a list of components.
[ "convenience", "routine", "for", "splitting", "a", "path", "into", "a", "list", "of", "components", "." ]
59e4fbe8b8111ceead884e50d1973901a0a2d240
https://github.com/ldo/dbussy/blob/59e4fbe8b8111ceead884e50d1973901a0a2d240/dbussy.py#L5672-L5685
train
24,216
ldo/dbussy
dbussy.py
validate_utf8
def validate_utf8(alleged_utf8, error = None) : "alleged_utf8 must be null-terminated bytes." error, my_error = _get_error(error) result = dbus.dbus_validate_utf8(alleged_utf8, error._dbobj) != 0 my_error.raise_if_set() return \ result
python
def validate_utf8(alleged_utf8, error = None) : "alleged_utf8 must be null-terminated bytes." error, my_error = _get_error(error) result = dbus.dbus_validate_utf8(alleged_utf8, error._dbobj) != 0 my_error.raise_if_set() return \ result
[ "def", "validate_utf8", "(", "alleged_utf8", ",", "error", "=", "None", ")", ":", "error", ",", "my_error", "=", "_get_error", "(", "error", ")", "result", "=", "dbus", ".", "dbus_validate_utf8", "(", "alleged_utf8", ",", "error", ".", "_dbobj", ")", "!=",...
alleged_utf8 must be null-terminated bytes.
[ "alleged_utf8", "must", "be", "null", "-", "terminated", "bytes", "." ]
59e4fbe8b8111ceead884e50d1973901a0a2d240
https://github.com/ldo/dbussy/blob/59e4fbe8b8111ceead884e50d1973901a0a2d240/dbussy.py#L5759-L5765
train
24,217
ldo/dbussy
dbussy.py
DBUS.int_subtype
def int_subtype(i, bits, signed) : "returns integer i after checking that it fits in the given number of bits." if not isinstance(i, int) : raise TypeError("value is not int: %s" % repr(i)) #end if if signed : lo = - 1 << bits - 1 hi = (1 << bits - 1) - 1 else : lo = 0 hi = (1 << bits) - 1 #end if if i < lo or i > hi : raise ValueError \ ( "%d not in range of %s %d-bit value" % (i, ("unsigned", "signed")[signed], bits) ) #end if return \ i
python
def int_subtype(i, bits, signed) : "returns integer i after checking that it fits in the given number of bits." if not isinstance(i, int) : raise TypeError("value is not int: %s" % repr(i)) #end if if signed : lo = - 1 << bits - 1 hi = (1 << bits - 1) - 1 else : lo = 0 hi = (1 << bits) - 1 #end if if i < lo or i > hi : raise ValueError \ ( "%d not in range of %s %d-bit value" % (i, ("unsigned", "signed")[signed], bits) ) #end if return \ i
[ "def", "int_subtype", "(", "i", ",", "bits", ",", "signed", ")", ":", "if", "not", "isinstance", "(", "i", ",", "int", ")", ":", "raise", "TypeError", "(", "\"value is not int: %s\"", "%", "repr", "(", "i", ")", ")", "#end if", "if", "signed", ":", "...
returns integer i after checking that it fits in the given number of bits.
[ "returns", "integer", "i", "after", "checking", "that", "it", "fits", "in", "the", "given", "number", "of", "bits", "." ]
59e4fbe8b8111ceead884e50d1973901a0a2d240
https://github.com/ldo/dbussy/blob/59e4fbe8b8111ceead884e50d1973901a0a2d240/dbussy.py#L88-L107
train
24,218
ldo/dbussy
dbussy.py
Connection.server_id
def server_id(self) : "asks the server at the other end for its unique id." c_result = dbus.dbus_connection_get_server_id(self._dbobj) result = ct.cast(c_result, ct.c_char_p).value.decode() dbus.dbus_free(c_result) return \ result
python
def server_id(self) : "asks the server at the other end for its unique id." c_result = dbus.dbus_connection_get_server_id(self._dbobj) result = ct.cast(c_result, ct.c_char_p).value.decode() dbus.dbus_free(c_result) return \ result
[ "def", "server_id", "(", "self", ")", ":", "c_result", "=", "dbus", ".", "dbus_connection_get_server_id", "(", "self", ".", "_dbobj", ")", "result", "=", "ct", ".", "cast", "(", "c_result", ",", "ct", ".", "c_char_p", ")", ".", "value", ".", "decode", ...
asks the server at the other end for its unique id.
[ "asks", "the", "server", "at", "the", "other", "end", "for", "its", "unique", "id", "." ]
59e4fbe8b8111ceead884e50d1973901a0a2d240
https://github.com/ldo/dbussy/blob/59e4fbe8b8111ceead884e50d1973901a0a2d240/dbussy.py#L2146-L2152
train
24,219
ldo/dbussy
dbussy.py
Connection.send
def send(self, message) : "puts a message in the outgoing queue." if not isinstance(message, Message) : raise TypeError("message must be a Message") #end if serial = ct.c_uint() if not dbus.dbus_connection_send(self._dbobj, message._dbobj, ct.byref(serial)) : raise CallFailed("dbus_connection_send") #end if return \ serial.value
python
def send(self, message) : "puts a message in the outgoing queue." if not isinstance(message, Message) : raise TypeError("message must be a Message") #end if serial = ct.c_uint() if not dbus.dbus_connection_send(self._dbobj, message._dbobj, ct.byref(serial)) : raise CallFailed("dbus_connection_send") #end if return \ serial.value
[ "def", "send", "(", "self", ",", "message", ")", ":", "if", "not", "isinstance", "(", "message", ",", "Message", ")", ":", "raise", "TypeError", "(", "\"message must be a Message\"", ")", "#end if", "serial", "=", "ct", ".", "c_uint", "(", ")", "if", "no...
puts a message in the outgoing queue.
[ "puts", "a", "message", "in", "the", "outgoing", "queue", "." ]
59e4fbe8b8111ceead884e50d1973901a0a2d240
https://github.com/ldo/dbussy/blob/59e4fbe8b8111ceead884e50d1973901a0a2d240/dbussy.py#L2187-L2197
train
24,220
ldo/dbussy
dbussy.py
Connection.send_with_reply_and_block
def send_with_reply_and_block(self, message, timeout = DBUS.TIMEOUT_USE_DEFAULT, error = None) : "sends a message, blocks the thread until the reply is available, and returns it." if not isinstance(message, Message) : raise TypeError("message must be a Message") #end if error, my_error = _get_error(error) reply = dbus.dbus_connection_send_with_reply_and_block(self._dbobj, message._dbobj, _get_timeout(timeout), error._dbobj) my_error.raise_if_set() if reply != None : result = Message(reply) else : result = None #end if return \ result
python
def send_with_reply_and_block(self, message, timeout = DBUS.TIMEOUT_USE_DEFAULT, error = None) : "sends a message, blocks the thread until the reply is available, and returns it." if not isinstance(message, Message) : raise TypeError("message must be a Message") #end if error, my_error = _get_error(error) reply = dbus.dbus_connection_send_with_reply_and_block(self._dbobj, message._dbobj, _get_timeout(timeout), error._dbobj) my_error.raise_if_set() if reply != None : result = Message(reply) else : result = None #end if return \ result
[ "def", "send_with_reply_and_block", "(", "self", ",", "message", ",", "timeout", "=", "DBUS", ".", "TIMEOUT_USE_DEFAULT", ",", "error", "=", "None", ")", ":", "if", "not", "isinstance", "(", "message", ",", "Message", ")", ":", "raise", "TypeError", "(", "...
sends a message, blocks the thread until the reply is available, and returns it.
[ "sends", "a", "message", "blocks", "the", "thread", "until", "the", "reply", "is", "available", "and", "returns", "it", "." ]
59e4fbe8b8111ceead884e50d1973901a0a2d240
https://github.com/ldo/dbussy/blob/59e4fbe8b8111ceead884e50d1973901a0a2d240/dbussy.py#L2219-L2233
train
24,221
ldo/dbussy
dbussy.py
Connection.list_registered
def list_registered(self, parent_path) : "lists all the object paths for which you have ObjectPathVTable handlers registered." child_entries = ct.POINTER(ct.c_char_p)() if not dbus.dbus_connection_list_registered(self._dbobj, parent_path.encode(), ct.byref(child_entries)) : raise CallFailed("dbus_connection_list_registered") #end if result = [] i = 0 while True : entry = child_entries[i] if entry == None : break result.append(entry.decode()) i += 1 #end while dbus.dbus_free_string_array(child_entries) return \ result
python
def list_registered(self, parent_path) : "lists all the object paths for which you have ObjectPathVTable handlers registered." child_entries = ct.POINTER(ct.c_char_p)() if not dbus.dbus_connection_list_registered(self._dbobj, parent_path.encode(), ct.byref(child_entries)) : raise CallFailed("dbus_connection_list_registered") #end if result = [] i = 0 while True : entry = child_entries[i] if entry == None : break result.append(entry.decode()) i += 1 #end while dbus.dbus_free_string_array(child_entries) return \ result
[ "def", "list_registered", "(", "self", ",", "parent_path", ")", ":", "child_entries", "=", "ct", ".", "POINTER", "(", "ct", ".", "c_char_p", ")", "(", ")", "if", "not", "dbus", ".", "dbus_connection_list_registered", "(", "self", ".", "_dbobj", ",", "paren...
lists all the object paths for which you have ObjectPathVTable handlers registered.
[ "lists", "all", "the", "object", "paths", "for", "which", "you", "have", "ObjectPathVTable", "handlers", "registered", "." ]
59e4fbe8b8111ceead884e50d1973901a0a2d240
https://github.com/ldo/dbussy/blob/59e4fbe8b8111ceead884e50d1973901a0a2d240/dbussy.py#L2661-L2678
train
24,222
ldo/dbussy
dbussy.py
Connection.bus_get
def bus_get(celf, type, private, error = None) : "returns a Connection to one of the predefined D-Bus buses; type is a BUS_xxx value." error, my_error = _get_error(error) result = (dbus.dbus_bus_get, dbus.dbus_bus_get_private)[private](type, error._dbobj) my_error.raise_if_set() if result != None : result = celf(result) #end if return \ result
python
def bus_get(celf, type, private, error = None) : "returns a Connection to one of the predefined D-Bus buses; type is a BUS_xxx value." error, my_error = _get_error(error) result = (dbus.dbus_bus_get, dbus.dbus_bus_get_private)[private](type, error._dbobj) my_error.raise_if_set() if result != None : result = celf(result) #end if return \ result
[ "def", "bus_get", "(", "celf", ",", "type", ",", "private", ",", "error", "=", "None", ")", ":", "error", ",", "my_error", "=", "_get_error", "(", "error", ")", "result", "=", "(", "dbus", ".", "dbus_bus_get", ",", "dbus", ".", "dbus_bus_get_private", ...
returns a Connection to one of the predefined D-Bus buses; type is a BUS_xxx value.
[ "returns", "a", "Connection", "to", "one", "of", "the", "predefined", "D", "-", "Bus", "buses", ";", "type", "is", "a", "BUS_xxx", "value", "." ]
59e4fbe8b8111ceead884e50d1973901a0a2d240
https://github.com/ldo/dbussy/blob/59e4fbe8b8111ceead884e50d1973901a0a2d240/dbussy.py#L2924-L2933
train
24,223
ldo/dbussy
dbussy.py
Connection.become_monitor
def become_monitor(self, rules) : "turns the connection into one that can only receive monitoring messages." message = Message.new_method_call \ ( destination = DBUS.SERVICE_DBUS, path = DBUS.PATH_DBUS, iface = DBUS.INTERFACE_MONITORING, method = "BecomeMonitor" ) message.append_objects("asu", (list(format_rule(rule) for rule in rules)), 0) self.send(message)
python
def become_monitor(self, rules) : "turns the connection into one that can only receive monitoring messages." message = Message.new_method_call \ ( destination = DBUS.SERVICE_DBUS, path = DBUS.PATH_DBUS, iface = DBUS.INTERFACE_MONITORING, method = "BecomeMonitor" ) message.append_objects("asu", (list(format_rule(rule) for rule in rules)), 0) self.send(message)
[ "def", "become_monitor", "(", "self", ",", "rules", ")", ":", "message", "=", "Message", ".", "new_method_call", "(", "destination", "=", "DBUS", ".", "SERVICE_DBUS", ",", "path", "=", "DBUS", ".", "PATH_DBUS", ",", "iface", "=", "DBUS", ".", "INTERFACE_MO...
turns the connection into one that can only receive monitoring messages.
[ "turns", "the", "connection", "into", "one", "that", "can", "only", "receive", "monitoring", "messages", "." ]
59e4fbe8b8111ceead884e50d1973901a0a2d240
https://github.com/ldo/dbussy/blob/59e4fbe8b8111ceead884e50d1973901a0a2d240/dbussy.py#L3371-L3381
train
24,224
ldo/dbussy
dbussy.py
PreallocatedSend.send
def send(self, message) : "alternative to Connection.send_preallocated." if not isinstance(message, Message) : raise TypeError("message must be a Message") #end if assert not self._sent, "preallocated has already been sent" serial = ct.c_uint() dbus.dbus_connection_send_preallocated(self._parent._dbobj, self._dbobj, message._dbobj, ct.byref(serial)) self._sent = True return \ serial.value
python
def send(self, message) : "alternative to Connection.send_preallocated." if not isinstance(message, Message) : raise TypeError("message must be a Message") #end if assert not self._sent, "preallocated has already been sent" serial = ct.c_uint() dbus.dbus_connection_send_preallocated(self._parent._dbobj, self._dbobj, message._dbobj, ct.byref(serial)) self._sent = True return \ serial.value
[ "def", "send", "(", "self", ",", "message", ")", ":", "if", "not", "isinstance", "(", "message", ",", "Message", ")", ":", "raise", "TypeError", "(", "\"message must be a Message\"", ")", "#end if", "assert", "not", "self", ".", "_sent", ",", "\"preallocated...
alternative to Connection.send_preallocated.
[ "alternative", "to", "Connection", ".", "send_preallocated", "." ]
59e4fbe8b8111ceead884e50d1973901a0a2d240
https://github.com/ldo/dbussy/blob/59e4fbe8b8111ceead884e50d1973901a0a2d240/dbussy.py#L3869-L3879
train
24,225
ldo/dbussy
dbussy.py
Message.new_error
def new_error(self, name, message) : "creates a new DBUS.MESSAGE_TYPE_ERROR message that is a reply to this Message." result = dbus.dbus_message_new_error(self._dbobj, name.encode(), (lambda : None, lambda : message.encode())[message != None]()) if result == None : raise CallFailed("dbus_message_new_error") #end if return \ type(self)(result)
python
def new_error(self, name, message) : "creates a new DBUS.MESSAGE_TYPE_ERROR message that is a reply to this Message." result = dbus.dbus_message_new_error(self._dbobj, name.encode(), (lambda : None, lambda : message.encode())[message != None]()) if result == None : raise CallFailed("dbus_message_new_error") #end if return \ type(self)(result)
[ "def", "new_error", "(", "self", ",", "name", ",", "message", ")", ":", "result", "=", "dbus", ".", "dbus_message_new_error", "(", "self", ".", "_dbobj", ",", "name", ".", "encode", "(", ")", ",", "(", "lambda", ":", "None", ",", "lambda", ":", "mess...
creates a new DBUS.MESSAGE_TYPE_ERROR message that is a reply to this Message.
[ "creates", "a", "new", "DBUS", ".", "MESSAGE_TYPE_ERROR", "message", "that", "is", "a", "reply", "to", "this", "Message", "." ]
59e4fbe8b8111ceead884e50d1973901a0a2d240
https://github.com/ldo/dbussy/blob/59e4fbe8b8111ceead884e50d1973901a0a2d240/dbussy.py#L3930-L3937
train
24,226
ldo/dbussy
dbussy.py
Message.new_method_call
def new_method_call(celf, destination, path, iface, method) : "creates a new DBUS.MESSAGE_TYPE_METHOD_CALL message." result = dbus.dbus_message_new_method_call \ ( (lambda : None, lambda : destination.encode())[destination != None](), path.encode(), (lambda : None, lambda : iface.encode())[iface != None](), method.encode(), ) if result == None : raise CallFailed("dbus_message_new_method_call") #end if return \ celf(result)
python
def new_method_call(celf, destination, path, iface, method) : "creates a new DBUS.MESSAGE_TYPE_METHOD_CALL message." result = dbus.dbus_message_new_method_call \ ( (lambda : None, lambda : destination.encode())[destination != None](), path.encode(), (lambda : None, lambda : iface.encode())[iface != None](), method.encode(), ) if result == None : raise CallFailed("dbus_message_new_method_call") #end if return \ celf(result)
[ "def", "new_method_call", "(", "celf", ",", "destination", ",", "path", ",", "iface", ",", "method", ")", ":", "result", "=", "dbus", ".", "dbus_message_new_method_call", "(", "(", "lambda", ":", "None", ",", "lambda", ":", "destination", ".", "encode", "(...
creates a new DBUS.MESSAGE_TYPE_METHOD_CALL message.
[ "creates", "a", "new", "DBUS", ".", "MESSAGE_TYPE_METHOD_CALL", "message", "." ]
59e4fbe8b8111ceead884e50d1973901a0a2d240
https://github.com/ldo/dbussy/blob/59e4fbe8b8111ceead884e50d1973901a0a2d240/dbussy.py#L3943-L3956
train
24,227
ldo/dbussy
dbussy.py
Message.new_method_return
def new_method_return(self) : "creates a new DBUS.MESSAGE_TYPE_METHOD_RETURN that is a reply to this Message." result = dbus.dbus_message_new_method_return(self._dbobj) if result == None : raise CallFailed("dbus_message_new_method_return") #end if return \ type(self)(result)
python
def new_method_return(self) : "creates a new DBUS.MESSAGE_TYPE_METHOD_RETURN that is a reply to this Message." result = dbus.dbus_message_new_method_return(self._dbobj) if result == None : raise CallFailed("dbus_message_new_method_return") #end if return \ type(self)(result)
[ "def", "new_method_return", "(", "self", ")", ":", "result", "=", "dbus", ".", "dbus_message_new_method_return", "(", "self", ".", "_dbobj", ")", "if", "result", "==", "None", ":", "raise", "CallFailed", "(", "\"dbus_message_new_method_return\"", ")", "#end if", ...
creates a new DBUS.MESSAGE_TYPE_METHOD_RETURN that is a reply to this Message.
[ "creates", "a", "new", "DBUS", ".", "MESSAGE_TYPE_METHOD_RETURN", "that", "is", "a", "reply", "to", "this", "Message", "." ]
59e4fbe8b8111ceead884e50d1973901a0a2d240
https://github.com/ldo/dbussy/blob/59e4fbe8b8111ceead884e50d1973901a0a2d240/dbussy.py#L3959-L3966
train
24,228
ldo/dbussy
dbussy.py
Message.new_signal
def new_signal(celf, path, iface, name) : "creates a new DBUS.MESSAGE_TYPE_SIGNAL message." result = dbus.dbus_message_new_signal(path.encode(), iface.encode(), name.encode()) if result == None : raise CallFailed("dbus_message_new_signal") #end if return \ celf(result)
python
def new_signal(celf, path, iface, name) : "creates a new DBUS.MESSAGE_TYPE_SIGNAL message." result = dbus.dbus_message_new_signal(path.encode(), iface.encode(), name.encode()) if result == None : raise CallFailed("dbus_message_new_signal") #end if return \ celf(result)
[ "def", "new_signal", "(", "celf", ",", "path", ",", "iface", ",", "name", ")", ":", "result", "=", "dbus", ".", "dbus_message_new_signal", "(", "path", ".", "encode", "(", ")", ",", "iface", ".", "encode", "(", ")", ",", "name", ".", "encode", "(", ...
creates a new DBUS.MESSAGE_TYPE_SIGNAL message.
[ "creates", "a", "new", "DBUS", ".", "MESSAGE_TYPE_SIGNAL", "message", "." ]
59e4fbe8b8111ceead884e50d1973901a0a2d240
https://github.com/ldo/dbussy/blob/59e4fbe8b8111ceead884e50d1973901a0a2d240/dbussy.py#L3970-L3977
train
24,229
ldo/dbussy
dbussy.py
Message.copy
def copy(self) : "creates a copy of this Message." result = dbus.dbus_message_copy(self._dbobj) if result == None : raise CallFailed("dbus_message_copy") #end if return \ type(self)(result)
python
def copy(self) : "creates a copy of this Message." result = dbus.dbus_message_copy(self._dbobj) if result == None : raise CallFailed("dbus_message_copy") #end if return \ type(self)(result)
[ "def", "copy", "(", "self", ")", ":", "result", "=", "dbus", ".", "dbus_message_copy", "(", "self", ".", "_dbobj", ")", "if", "result", "==", "None", ":", "raise", "CallFailed", "(", "\"dbus_message_copy\"", ")", "#end if", "return", "type", "(", "self", ...
creates a copy of this Message.
[ "creates", "a", "copy", "of", "this", "Message", "." ]
59e4fbe8b8111ceead884e50d1973901a0a2d240
https://github.com/ldo/dbussy/blob/59e4fbe8b8111ceead884e50d1973901a0a2d240/dbussy.py#L3980-L3987
train
24,230
ldo/dbussy
dbussy.py
Message.iter_init
def iter_init(self) : "creates an iterator for extracting the arguments of the Message." iter = self.ExtractIter(None) if dbus.dbus_message_iter_init(self._dbobj, iter._dbobj) == 0 : iter._nulliter = True #end if return \ iter
python
def iter_init(self) : "creates an iterator for extracting the arguments of the Message." iter = self.ExtractIter(None) if dbus.dbus_message_iter_init(self._dbobj, iter._dbobj) == 0 : iter._nulliter = True #end if return \ iter
[ "def", "iter_init", "(", "self", ")", ":", "iter", "=", "self", ".", "ExtractIter", "(", "None", ")", "if", "dbus", ".", "dbus_message_iter_init", "(", "self", ".", "_dbobj", ",", "iter", ".", "_dbobj", ")", "==", "0", ":", "iter", ".", "_nulliter", ...
creates an iterator for extracting the arguments of the Message.
[ "creates", "an", "iterator", "for", "extracting", "the", "arguments", "of", "the", "Message", "." ]
59e4fbe8b8111ceead884e50d1973901a0a2d240
https://github.com/ldo/dbussy/blob/59e4fbe8b8111ceead884e50d1973901a0a2d240/dbussy.py#L4278-L4285
train
24,231
ldo/dbussy
dbussy.py
Message.iter_init_append
def iter_init_append(self) : "creates a Message.AppendIter for appending arguments to the Message." iter = self.AppendIter(None) dbus.dbus_message_iter_init_append(self._dbobj, iter._dbobj) return \ iter
python
def iter_init_append(self) : "creates a Message.AppendIter for appending arguments to the Message." iter = self.AppendIter(None) dbus.dbus_message_iter_init_append(self._dbobj, iter._dbobj) return \ iter
[ "def", "iter_init_append", "(", "self", ")", ":", "iter", "=", "self", ".", "AppendIter", "(", "None", ")", "dbus", ".", "dbus_message_iter_init_append", "(", "self", ".", "_dbobj", ",", "iter", ".", "_dbobj", ")", "return", "iter" ]
creates a Message.AppendIter for appending arguments to the Message.
[ "creates", "a", "Message", ".", "AppendIter", "for", "appending", "arguments", "to", "the", "Message", "." ]
59e4fbe8b8111ceead884e50d1973901a0a2d240
https://github.com/ldo/dbussy/blob/59e4fbe8b8111ceead884e50d1973901a0a2d240/dbussy.py#L4329-L4334
train
24,232
ldo/dbussy
dbussy.py
Message.error_name
def error_name(self) : "the error name for a DBUS.MESSAGE_TYPE_ERROR message." result = dbus.dbus_message_get_error_name(self._dbobj) if result != None : result = result.decode() #end if return \ result
python
def error_name(self) : "the error name for a DBUS.MESSAGE_TYPE_ERROR message." result = dbus.dbus_message_get_error_name(self._dbobj) if result != None : result = result.decode() #end if return \ result
[ "def", "error_name", "(", "self", ")", ":", "result", "=", "dbus", ".", "dbus_message_get_error_name", "(", "self", ".", "_dbobj", ")", "if", "result", "!=", "None", ":", "result", "=", "result", ".", "decode", "(", ")", "#end if", "return", "result" ]
the error name for a DBUS.MESSAGE_TYPE_ERROR message.
[ "the", "error", "name", "for", "a", "DBUS", ".", "MESSAGE_TYPE_ERROR", "message", "." ]
59e4fbe8b8111ceead884e50d1973901a0a2d240
https://github.com/ldo/dbussy/blob/59e4fbe8b8111ceead884e50d1973901a0a2d240/dbussy.py#L4519-L4526
train
24,233
ldo/dbussy
dbussy.py
Message.destination
def destination(self) : "the bus name that the message is to be sent to." result = dbus.dbus_message_get_destination(self._dbobj) if result != None : result = result.decode() #end if return \ result
python
def destination(self) : "the bus name that the message is to be sent to." result = dbus.dbus_message_get_destination(self._dbobj) if result != None : result = result.decode() #end if return \ result
[ "def", "destination", "(", "self", ")", ":", "result", "=", "dbus", ".", "dbus_message_get_destination", "(", "self", ".", "_dbobj", ")", "if", "result", "!=", "None", ":", "result", "=", "result", ".", "decode", "(", ")", "#end if", "return", "result" ]
the bus name that the message is to be sent to.
[ "the", "bus", "name", "that", "the", "message", "is", "to", "be", "sent", "to", "." ]
59e4fbe8b8111ceead884e50d1973901a0a2d240
https://github.com/ldo/dbussy/blob/59e4fbe8b8111ceead884e50d1973901a0a2d240/dbussy.py#L4537-L4544
train
24,234
ldo/dbussy
dbussy.py
Message.marshal
def marshal(self) : "serializes this Message into the wire protocol format and returns a bytes object." buf = ct.POINTER(ct.c_ubyte)() nr_bytes = ct.c_int() if not dbus.dbus_message_marshal(self._dbobj, ct.byref(buf), ct.byref(nr_bytes)) : raise CallFailed("dbus_message_marshal") #end if result = bytearray(nr_bytes.value) ct.memmove \ ( ct.addressof((ct.c_ubyte * nr_bytes.value).from_buffer(result)), buf, nr_bytes.value ) dbus.dbus_free(buf) return \ result
python
def marshal(self) : "serializes this Message into the wire protocol format and returns a bytes object." buf = ct.POINTER(ct.c_ubyte)() nr_bytes = ct.c_int() if not dbus.dbus_message_marshal(self._dbobj, ct.byref(buf), ct.byref(nr_bytes)) : raise CallFailed("dbus_message_marshal") #end if result = bytearray(nr_bytes.value) ct.memmove \ ( ct.addressof((ct.c_ubyte * nr_bytes.value).from_buffer(result)), buf, nr_bytes.value ) dbus.dbus_free(buf) return \ result
[ "def", "marshal", "(", "self", ")", ":", "buf", "=", "ct", ".", "POINTER", "(", "ct", ".", "c_ubyte", ")", "(", ")", "nr_bytes", "=", "ct", ".", "c_int", "(", ")", "if", "not", "dbus", ".", "dbus_message_marshal", "(", "self", ".", "_dbobj", ",", ...
serializes this Message into the wire protocol format and returns a bytes object.
[ "serializes", "this", "Message", "into", "the", "wire", "protocol", "format", "and", "returns", "a", "bytes", "object", "." ]
59e4fbe8b8111ceead884e50d1973901a0a2d240
https://github.com/ldo/dbussy/blob/59e4fbe8b8111ceead884e50d1973901a0a2d240/dbussy.py#L4690-L4706
train
24,235
ldo/dbussy
dbussy.py
PendingCall.cancel
def cancel(self) : "tells libdbus you no longer care about the pending incoming message." dbus.dbus_pending_call_cancel(self._dbobj) if self._awaiting != None : # This probably shouldn’t occur. Looking at the source of libdbus, # it doesn’t keep track of any “cancelled” state for the PendingCall, # it just detaches it from any notifications about an incoming reply. self._awaiting.cancel()
python
def cancel(self) : "tells libdbus you no longer care about the pending incoming message." dbus.dbus_pending_call_cancel(self._dbobj) if self._awaiting != None : # This probably shouldn’t occur. Looking at the source of libdbus, # it doesn’t keep track of any “cancelled” state for the PendingCall, # it just detaches it from any notifications about an incoming reply. self._awaiting.cancel()
[ "def", "cancel", "(", "self", ")", ":", "dbus", ".", "dbus_pending_call_cancel", "(", "self", ".", "_dbobj", ")", "if", "self", ".", "_awaiting", "!=", "None", ":", "# This probably shouldn’t occur. Looking at the source of libdbus,", "# it doesn’t keep track of any “canc...
tells libdbus you no longer care about the pending incoming message.
[ "tells", "libdbus", "you", "no", "longer", "care", "about", "the", "pending", "incoming", "message", "." ]
59e4fbe8b8111ceead884e50d1973901a0a2d240
https://github.com/ldo/dbussy/blob/59e4fbe8b8111ceead884e50d1973901a0a2d240/dbussy.py#L4834-L4841
train
24,236
ldo/dbussy
dbussy.py
Error.set
def set(self, name, msg) : "fills in the error name and message." dbus.dbus_set_error(self._dbobj, name.encode(), b"%s", msg.encode())
python
def set(self, name, msg) : "fills in the error name and message." dbus.dbus_set_error(self._dbobj, name.encode(), b"%s", msg.encode())
[ "def", "set", "(", "self", ",", "name", ",", "msg", ")", ":", "dbus", ".", "dbus_set_error", "(", "self", ".", "_dbobj", ",", "name", ".", "encode", "(", ")", ",", "b\"%s\"", ",", "msg", ".", "encode", "(", ")", ")" ]
fills in the error name and message.
[ "fills", "in", "the", "error", "name", "and", "message", "." ]
59e4fbe8b8111ceead884e50d1973901a0a2d240
https://github.com/ldo/dbussy/blob/59e4fbe8b8111ceead884e50d1973901a0a2d240/dbussy.py#L4927-L4929
train
24,237
ldo/dbussy
dbussy.py
Introspection.parse
def parse(celf, s) : "generates an Introspection tree from the given XML string description." def from_string_elts(celf, attrs, tree) : elts = dict((k, attrs[k]) for k in attrs) child_tags = dict \ ( (childclass.tag_name, childclass) for childclass in tuple(celf.tag_elts.values()) + (Introspection.Annotation,) ) children = [] for child in tree : if child.tag not in child_tags : raise KeyError("unrecognized tag %s" % child.tag) #end if childclass = child_tags[child.tag] childattrs = {} for attrname in childclass.tag_attrs : if hasattr(childclass, "tag_attrs_optional") and attrname in childclass.tag_attrs_optional : childattrs[attrname] = child.attrib.get(attrname, None) else : if attrname not in child.attrib : raise ValueError("missing %s attribute for %s tag" % (attrname, child.tag)) #end if childattrs[attrname] = child.attrib[attrname] #end if #end for if hasattr(childclass, "attr_convert") : for attr in childclass.attr_convert : if attr in childattrs : childattrs[attr] = childclass.attr_convert[attr](childattrs[attr]) #end if #end for #end if children.append(from_string_elts(childclass, childattrs, child)) #end for for child_tag, childclass in tuple(celf.tag_elts.items()) + ((), (("annotations", Introspection.Annotation),))[tree.tag != "annotation"] : for child in children : if isinstance(child, childclass) : if child_tag not in elts : elts[child_tag] = [] #end if elts[child_tag].append(child) #end if #end for #end for return \ celf(**elts) #end from_string_elts #begin parse tree = XMLElementTree.fromstring(s) assert tree.tag == "node", "root of introspection tree must be <node> tag" return \ from_string_elts(Introspection, {}, tree)
python
def parse(celf, s) : "generates an Introspection tree from the given XML string description." def from_string_elts(celf, attrs, tree) : elts = dict((k, attrs[k]) for k in attrs) child_tags = dict \ ( (childclass.tag_name, childclass) for childclass in tuple(celf.tag_elts.values()) + (Introspection.Annotation,) ) children = [] for child in tree : if child.tag not in child_tags : raise KeyError("unrecognized tag %s" % child.tag) #end if childclass = child_tags[child.tag] childattrs = {} for attrname in childclass.tag_attrs : if hasattr(childclass, "tag_attrs_optional") and attrname in childclass.tag_attrs_optional : childattrs[attrname] = child.attrib.get(attrname, None) else : if attrname not in child.attrib : raise ValueError("missing %s attribute for %s tag" % (attrname, child.tag)) #end if childattrs[attrname] = child.attrib[attrname] #end if #end for if hasattr(childclass, "attr_convert") : for attr in childclass.attr_convert : if attr in childattrs : childattrs[attr] = childclass.attr_convert[attr](childattrs[attr]) #end if #end for #end if children.append(from_string_elts(childclass, childattrs, child)) #end for for child_tag, childclass in tuple(celf.tag_elts.items()) + ((), (("annotations", Introspection.Annotation),))[tree.tag != "annotation"] : for child in children : if isinstance(child, childclass) : if child_tag not in elts : elts[child_tag] = [] #end if elts[child_tag].append(child) #end if #end for #end for return \ celf(**elts) #end from_string_elts #begin parse tree = XMLElementTree.fromstring(s) assert tree.tag == "node", "root of introspection tree must be <node> tag" return \ from_string_elts(Introspection, {}, tree)
[ "def", "parse", "(", "celf", ",", "s", ")", ":", "def", "from_string_elts", "(", "celf", ",", "attrs", ",", "tree", ")", ":", "elts", "=", "dict", "(", "(", "k", ",", "attrs", "[", "k", "]", ")", "for", "k", "in", "attrs", ")", "child_tags", "=...
generates an Introspection tree from the given XML string description.
[ "generates", "an", "Introspection", "tree", "from", "the", "given", "XML", "string", "description", "." ]
59e4fbe8b8111ceead884e50d1973901a0a2d240
https://github.com/ldo/dbussy/blob/59e4fbe8b8111ceead884e50d1973901a0a2d240/dbussy.py#L6141-L6195
train
24,238
ldo/dbussy
dbussy.py
Introspection.unparse
def unparse(self, indent_step = 4, max_linelen = 72) : "returns an XML string description of this Introspection tree." out = io.StringIO() def to_string(obj, indent) : tag_name = obj.tag_name attrs = [] for attrname in obj.tag_attrs : attr = getattr(obj, attrname) if attr != None : if isinstance(attr, enum.Enum) : attr = attr.value elif isinstance(attr, Type) : attr = unparse_signature(attr) elif not isinstance(attr, str) : raise TypeError("unexpected attribute type %s for %s" % (type(attr).__name__, repr(attr))) #end if attrs.append("%s=%s" % (attrname, quote_xml_attr(attr))) #end if #end for has_elts = \ ( sum ( len(getattr(obj, attrname)) for attrname in tuple(obj.tag_elts.keys()) + ((), ("annotations",)) [not isinstance(obj, Introspection.Annotation)] ) != 0 ) out.write(" " * indent + "<" + tag_name) if ( max_linelen != None and indent + len(tag_name) + sum((len(s) + 1) for s in attrs) + 2 + int(has_elts) > max_linelen ) : out.write("\n") for attr in attrs : out.write(" " * (indent + indent_step)) out.write(attr) out.write("\n") #end for out.write(" " * indent) else : for attr in attrs : out.write(" ") out.write(attr) #end for #end if if not has_elts : out.write("/") #end if out.write(">\n") if has_elts : for attrname in sorted(obj.tag_elts.keys()) + ["annotations"] : for elt in getattr(obj, attrname) : to_string(elt, indent + indent_step) #end for #end for out.write(" " * indent + "</" + tag_name + ">\n") #end if #end to_string #begin unparse out.write(DBUS.INTROSPECT_1_0_XML_DOCTYPE_DECL_NODE) out.write("<node") if self.name != None : out.write(" name=%s" % quote_xml_attr(self.name)) #end if out.write(">\n") for elt in self.interfaces : to_string(elt, indent_step) #end for for elt in self.nodes : to_string(elt, indent_step) #end for out.write("</node>\n") return \ out.getvalue()
python
def unparse(self, indent_step = 4, max_linelen = 72) : "returns an XML string description of this Introspection tree." out = io.StringIO() def to_string(obj, indent) : tag_name = obj.tag_name attrs = [] for attrname in obj.tag_attrs : attr = getattr(obj, attrname) if attr != None : if isinstance(attr, enum.Enum) : attr = attr.value elif isinstance(attr, Type) : attr = unparse_signature(attr) elif not isinstance(attr, str) : raise TypeError("unexpected attribute type %s for %s" % (type(attr).__name__, repr(attr))) #end if attrs.append("%s=%s" % (attrname, quote_xml_attr(attr))) #end if #end for has_elts = \ ( sum ( len(getattr(obj, attrname)) for attrname in tuple(obj.tag_elts.keys()) + ((), ("annotations",)) [not isinstance(obj, Introspection.Annotation)] ) != 0 ) out.write(" " * indent + "<" + tag_name) if ( max_linelen != None and indent + len(tag_name) + sum((len(s) + 1) for s in attrs) + 2 + int(has_elts) > max_linelen ) : out.write("\n") for attr in attrs : out.write(" " * (indent + indent_step)) out.write(attr) out.write("\n") #end for out.write(" " * indent) else : for attr in attrs : out.write(" ") out.write(attr) #end for #end if if not has_elts : out.write("/") #end if out.write(">\n") if has_elts : for attrname in sorted(obj.tag_elts.keys()) + ["annotations"] : for elt in getattr(obj, attrname) : to_string(elt, indent + indent_step) #end for #end for out.write(" " * indent + "</" + tag_name + ">\n") #end if #end to_string #begin unparse out.write(DBUS.INTROSPECT_1_0_XML_DOCTYPE_DECL_NODE) out.write("<node") if self.name != None : out.write(" name=%s" % quote_xml_attr(self.name)) #end if out.write(">\n") for elt in self.interfaces : to_string(elt, indent_step) #end for for elt in self.nodes : to_string(elt, indent_step) #end for out.write("</node>\n") return \ out.getvalue()
[ "def", "unparse", "(", "self", ",", "indent_step", "=", "4", ",", "max_linelen", "=", "72", ")", ":", "out", "=", "io", ".", "StringIO", "(", ")", "def", "to_string", "(", "obj", ",", "indent", ")", ":", "tag_name", "=", "obj", ".", "tag_name", "at...
returns an XML string description of this Introspection tree.
[ "returns", "an", "XML", "string", "description", "of", "this", "Introspection", "tree", "." ]
59e4fbe8b8111ceead884e50d1973901a0a2d240
https://github.com/ldo/dbussy/blob/59e4fbe8b8111ceead884e50d1973901a0a2d240/dbussy.py#L6198-L6291
train
24,239
ldo/dbussy
ravel.py
ErrorReturn.as_error
def as_error(self) : "fills in and returns an Error object that reports the specified error name and message." result = dbus.Error.init() result.set(self.args[0], self.args[1]) return \ result
python
def as_error(self) : "fills in and returns an Error object that reports the specified error name and message." result = dbus.Error.init() result.set(self.args[0], self.args[1]) return \ result
[ "def", "as_error", "(", "self", ")", ":", "result", "=", "dbus", ".", "Error", ".", "init", "(", ")", "result", ".", "set", "(", "self", ".", "args", "[", "0", "]", ",", "self", ".", "args", "[", "1", "]", ")", "return", "result" ]
fills in and returns an Error object that reports the specified error name and message.
[ "fills", "in", "and", "returns", "an", "Error", "object", "that", "reports", "the", "specified", "error", "name", "and", "message", "." ]
59e4fbe8b8111ceead884e50d1973901a0a2d240
https://github.com/ldo/dbussy/blob/59e4fbe8b8111ceead884e50d1973901a0a2d240/ravel.py#L37-L42
train
24,240
ldo/dbussy
ravel.py
Connection.release_name_async
async def release_name_async(self, bus_name, error = None, timeout = DBUS.TIMEOUT_USE_DEFAULT) : "releases a registered bus name." assert self.loop != None, "no event loop to attach coroutine to" return \ await self.connection.bus_release_name_async(bus_name, error = error, timeout = timeout)
python
async def release_name_async(self, bus_name, error = None, timeout = DBUS.TIMEOUT_USE_DEFAULT) : "releases a registered bus name." assert self.loop != None, "no event loop to attach coroutine to" return \ await self.connection.bus_release_name_async(bus_name, error = error, timeout = timeout)
[ "async", "def", "release_name_async", "(", "self", ",", "bus_name", ",", "error", "=", "None", ",", "timeout", "=", "DBUS", ".", "TIMEOUT_USE_DEFAULT", ")", ":", "assert", "self", ".", "loop", "!=", "None", ",", "\"no event loop to attach coroutine to\"", "retur...
releases a registered bus name.
[ "releases", "a", "registered", "bus", "name", "." ]
59e4fbe8b8111ceead884e50d1973901a0a2d240
https://github.com/ldo/dbussy/blob/59e4fbe8b8111ceead884e50d1973901a0a2d240/ravel.py#L382-L386
train
24,241
martinpitt/python-dbusmock
dbusmock/templates/bluez4.py
DefaultAdapter
def DefaultAdapter(self): '''Retrieve the default adapter ''' default_adapter = None for obj in mockobject.objects.keys(): if obj.startswith('/org/bluez/') and 'dev_' not in obj: default_adapter = obj if default_adapter: return dbus.ObjectPath(default_adapter, variant_level=1) else: raise dbus.exceptions.DBusException( 'No such adapter.', name='org.bluez.Error.NoSuchAdapter')
python
def DefaultAdapter(self): '''Retrieve the default adapter ''' default_adapter = None for obj in mockobject.objects.keys(): if obj.startswith('/org/bluez/') and 'dev_' not in obj: default_adapter = obj if default_adapter: return dbus.ObjectPath(default_adapter, variant_level=1) else: raise dbus.exceptions.DBusException( 'No such adapter.', name='org.bluez.Error.NoSuchAdapter')
[ "def", "DefaultAdapter", "(", "self", ")", ":", "default_adapter", "=", "None", "for", "obj", "in", "mockobject", ".", "objects", ".", "keys", "(", ")", ":", "if", "obj", ".", "startswith", "(", "'/org/bluez/'", ")", "and", "'dev_'", "not", "in", "obj", ...
Retrieve the default adapter
[ "Retrieve", "the", "default", "adapter" ]
26f65f78bc0ed347233f699a8d6ee0e6880e7eb0
https://github.com/martinpitt/python-dbusmock/blob/26f65f78bc0ed347233f699a8d6ee0e6880e7eb0/dbusmock/templates/bluez4.py#L155-L168
train
24,242
martinpitt/python-dbusmock
dbusmock/templates/bluez4.py
ListAdapters
def ListAdapters(self): '''List all known adapters ''' adapters = [] for obj in mockobject.objects.keys(): if obj.startswith('/org/bluez/') and 'dev_' not in obj: adapters.append(dbus.ObjectPath(obj, variant_level=1)) return dbus.Array(adapters, variant_level=1)
python
def ListAdapters(self): '''List all known adapters ''' adapters = [] for obj in mockobject.objects.keys(): if obj.startswith('/org/bluez/') and 'dev_' not in obj: adapters.append(dbus.ObjectPath(obj, variant_level=1)) return dbus.Array(adapters, variant_level=1)
[ "def", "ListAdapters", "(", "self", ")", ":", "adapters", "=", "[", "]", "for", "obj", "in", "mockobject", ".", "objects", ".", "keys", "(", ")", ":", "if", "obj", ".", "startswith", "(", "'/org/bluez/'", ")", "and", "'dev_'", "not", "in", "obj", ":"...
List all known adapters
[ "List", "all", "known", "adapters" ]
26f65f78bc0ed347233f699a8d6ee0e6880e7eb0
https://github.com/martinpitt/python-dbusmock/blob/26f65f78bc0ed347233f699a8d6ee0e6880e7eb0/dbusmock/templates/bluez4.py#L173-L182
train
24,243
martinpitt/python-dbusmock
dbusmock/templates/bluez4.py
CreateDevice
def CreateDevice(self, device_address): '''Create a new device ''' device_name = 'dev_' + device_address.replace(':', '_').upper() adapter_path = self.path path = adapter_path + '/' + device_name if path not in mockobject.objects: raise dbus.exceptions.DBusException( 'Could not create device for %s.' % device_address, name='org.bluez.Error.Failed') adapter = mockobject.objects[self.path] adapter.EmitSignal(ADAPTER_IFACE, 'DeviceCreated', 'o', [dbus.ObjectPath(path, variant_level=1)]) return dbus.ObjectPath(path, variant_level=1)
python
def CreateDevice(self, device_address): '''Create a new device ''' device_name = 'dev_' + device_address.replace(':', '_').upper() adapter_path = self.path path = adapter_path + '/' + device_name if path not in mockobject.objects: raise dbus.exceptions.DBusException( 'Could not create device for %s.' % device_address, name='org.bluez.Error.Failed') adapter = mockobject.objects[self.path] adapter.EmitSignal(ADAPTER_IFACE, 'DeviceCreated', 'o', [dbus.ObjectPath(path, variant_level=1)]) return dbus.ObjectPath(path, variant_level=1)
[ "def", "CreateDevice", "(", "self", ",", "device_address", ")", ":", "device_name", "=", "'dev_'", "+", "device_address", ".", "replace", "(", "':'", ",", "'_'", ")", ".", "upper", "(", ")", "adapter_path", "=", "self", ".", "path", "path", "=", "adapter...
Create a new device
[ "Create", "a", "new", "device" ]
26f65f78bc0ed347233f699a8d6ee0e6880e7eb0
https://github.com/martinpitt/python-dbusmock/blob/26f65f78bc0ed347233f699a8d6ee0e6880e7eb0/dbusmock/templates/bluez4.py#L187-L202
train
24,244
martinpitt/python-dbusmock
dbusmock/templates/bluez4.py
AddDevice
def AddDevice(self, adapter_device_name, device_address, alias): '''Convenience method to add a Bluetooth device You have to specify a device address which must be a valid Bluetooth address (e.g. 'AA:BB:CC:DD:EE:FF'). The alias is the human-readable name for the device (e.g. as set on the device itself), and the adapter device name is the device_name passed to AddAdapter. This will create a new, unpaired and unconnected device. Returns the new object path. ''' device_name = 'dev_' + device_address.replace(':', '_').upper() adapter_path = '/org/bluez/' + adapter_device_name path = adapter_path + '/' + device_name if adapter_path not in mockobject.objects: raise dbus.exceptions.DBusException( 'No such adapter.', name='org.bluez.Error.NoSuchAdapter') properties = { 'UUIDs': dbus.Array([], signature='s', variant_level=1), 'Blocked': dbus.Boolean(False, variant_level=1), 'Connected': dbus.Boolean(False, variant_level=1), 'LegacyPairing': dbus.Boolean(False, variant_level=1), 'Paired': dbus.Boolean(False, variant_level=1), 'Trusted': dbus.Boolean(False, variant_level=1), 'RSSI': dbus.Int16(-79, variant_level=1), # arbitrary 'Adapter': dbus.ObjectPath(adapter_path, variant_level=1), 'Address': dbus.String(device_address, variant_level=1), 'Alias': dbus.String(alias, variant_level=1), 'Name': dbus.String(alias, variant_level=1), 'Class': dbus.UInt32(0x240404, variant_level=1), # Audio, headset. 'Icon': dbus.String('audio-headset', variant_level=1), } self.AddObject(path, DEVICE_IFACE, # Properties properties, # Methods [ ('GetProperties', '', 'a{sv}', 'ret = self.GetAll("org.bluez.Device")'), ('SetProperty', 'sv', '', 'self.Set("org.bluez.Device", args[0], args[1]); ' 'self.EmitSignal("org.bluez.Device", "PropertyChanged",' ' "sv", [args[0], args[1]])'), ]) manager = mockobject.objects['/'] manager.EmitSignal(OBJECT_MANAGER_IFACE, 'InterfacesAdded', 'oa{sa{sv}}', [ dbus.ObjectPath(path, variant_level=1), {DEVICE_IFACE: properties}, ]) adapter = mockobject.objects[adapter_path] adapter.EmitSignal(ADAPTER_IFACE, 'DeviceFound', 'sa{sv}', [ properties['Address'], properties, ]) return path
python
def AddDevice(self, adapter_device_name, device_address, alias): '''Convenience method to add a Bluetooth device You have to specify a device address which must be a valid Bluetooth address (e.g. 'AA:BB:CC:DD:EE:FF'). The alias is the human-readable name for the device (e.g. as set on the device itself), and the adapter device name is the device_name passed to AddAdapter. This will create a new, unpaired and unconnected device. Returns the new object path. ''' device_name = 'dev_' + device_address.replace(':', '_').upper() adapter_path = '/org/bluez/' + adapter_device_name path = adapter_path + '/' + device_name if adapter_path not in mockobject.objects: raise dbus.exceptions.DBusException( 'No such adapter.', name='org.bluez.Error.NoSuchAdapter') properties = { 'UUIDs': dbus.Array([], signature='s', variant_level=1), 'Blocked': dbus.Boolean(False, variant_level=1), 'Connected': dbus.Boolean(False, variant_level=1), 'LegacyPairing': dbus.Boolean(False, variant_level=1), 'Paired': dbus.Boolean(False, variant_level=1), 'Trusted': dbus.Boolean(False, variant_level=1), 'RSSI': dbus.Int16(-79, variant_level=1), # arbitrary 'Adapter': dbus.ObjectPath(adapter_path, variant_level=1), 'Address': dbus.String(device_address, variant_level=1), 'Alias': dbus.String(alias, variant_level=1), 'Name': dbus.String(alias, variant_level=1), 'Class': dbus.UInt32(0x240404, variant_level=1), # Audio, headset. 'Icon': dbus.String('audio-headset', variant_level=1), } self.AddObject(path, DEVICE_IFACE, # Properties properties, # Methods [ ('GetProperties', '', 'a{sv}', 'ret = self.GetAll("org.bluez.Device")'), ('SetProperty', 'sv', '', 'self.Set("org.bluez.Device", args[0], args[1]); ' 'self.EmitSignal("org.bluez.Device", "PropertyChanged",' ' "sv", [args[0], args[1]])'), ]) manager = mockobject.objects['/'] manager.EmitSignal(OBJECT_MANAGER_IFACE, 'InterfacesAdded', 'oa{sa{sv}}', [ dbus.ObjectPath(path, variant_level=1), {DEVICE_IFACE: properties}, ]) adapter = mockobject.objects[adapter_path] adapter.EmitSignal(ADAPTER_IFACE, 'DeviceFound', 'sa{sv}', [ properties['Address'], properties, ]) return path
[ "def", "AddDevice", "(", "self", ",", "adapter_device_name", ",", "device_address", ",", "alias", ")", ":", "device_name", "=", "'dev_'", "+", "device_address", ".", "replace", "(", "':'", ",", "'_'", ")", ".", "upper", "(", ")", "adapter_path", "=", "'/or...
Convenience method to add a Bluetooth device You have to specify a device address which must be a valid Bluetooth address (e.g. 'AA:BB:CC:DD:EE:FF'). The alias is the human-readable name for the device (e.g. as set on the device itself), and the adapter device name is the device_name passed to AddAdapter. This will create a new, unpaired and unconnected device. Returns the new object path.
[ "Convenience", "method", "to", "add", "a", "Bluetooth", "device" ]
26f65f78bc0ed347233f699a8d6ee0e6880e7eb0
https://github.com/martinpitt/python-dbusmock/blob/26f65f78bc0ed347233f699a8d6ee0e6880e7eb0/dbusmock/templates/bluez4.py#L207-L269
train
24,245
martinpitt/python-dbusmock
dbusmock/templates/bluez4.py
ListDevices
def ListDevices(self): '''List all known devices ''' devices = [] for obj in mockobject.objects.keys(): if obj.startswith('/org/bluez/') and 'dev_' in obj: devices.append(dbus.ObjectPath(obj, variant_level=1)) return dbus.Array(devices, variant_level=1)
python
def ListDevices(self): '''List all known devices ''' devices = [] for obj in mockobject.objects.keys(): if obj.startswith('/org/bluez/') and 'dev_' in obj: devices.append(dbus.ObjectPath(obj, variant_level=1)) return dbus.Array(devices, variant_level=1)
[ "def", "ListDevices", "(", "self", ")", ":", "devices", "=", "[", "]", "for", "obj", "in", "mockobject", ".", "objects", ".", "keys", "(", ")", ":", "if", "obj", ".", "startswith", "(", "'/org/bluez/'", ")", "and", "'dev_'", "in", "obj", ":", "device...
List all known devices
[ "List", "all", "known", "devices" ]
26f65f78bc0ed347233f699a8d6ee0e6880e7eb0
https://github.com/martinpitt/python-dbusmock/blob/26f65f78bc0ed347233f699a8d6ee0e6880e7eb0/dbusmock/templates/bluez4.py#L274-L283
train
24,246
martinpitt/python-dbusmock
dbusmock/templates/bluez4.py
FindDevice
def FindDevice(self, address): '''Find a specific device by bluetooth address. ''' for obj in mockobject.objects.keys(): if obj.startswith('/org/bluez/') and 'dev_' in obj: o = mockobject.objects[obj] if o.props[DEVICE_IFACE]['Address'] \ == dbus.String(address, variant_level=1): return obj raise dbus.exceptions.DBusException('No such device.', name='org.bluez.Error.NoSuchDevice')
python
def FindDevice(self, address): '''Find a specific device by bluetooth address. ''' for obj in mockobject.objects.keys(): if obj.startswith('/org/bluez/') and 'dev_' in obj: o = mockobject.objects[obj] if o.props[DEVICE_IFACE]['Address'] \ == dbus.String(address, variant_level=1): return obj raise dbus.exceptions.DBusException('No such device.', name='org.bluez.Error.NoSuchDevice')
[ "def", "FindDevice", "(", "self", ",", "address", ")", ":", "for", "obj", "in", "mockobject", ".", "objects", ".", "keys", "(", ")", ":", "if", "obj", ".", "startswith", "(", "'/org/bluez/'", ")", "and", "'dev_'", "in", "obj", ":", "o", "=", "mockobj...
Find a specific device by bluetooth address.
[ "Find", "a", "specific", "device", "by", "bluetooth", "address", "." ]
26f65f78bc0ed347233f699a8d6ee0e6880e7eb0
https://github.com/martinpitt/python-dbusmock/blob/26f65f78bc0ed347233f699a8d6ee0e6880e7eb0/dbusmock/templates/bluez4.py#L288-L299
train
24,247
martinpitt/python-dbusmock
dbusmock/templates/bluez4.py
Connect
def Connect(self): '''Connect a device ''' device_path = self.path if device_path not in mockobject.objects: raise dbus.exceptions.DBusException('No such device.', name='org.bluez.Error.NoSuchDevice') device = mockobject.objects[device_path] device.props[AUDIO_IFACE]['State'] = dbus.String("connected", variant_level=1) device.EmitSignal(AUDIO_IFACE, 'PropertyChanged', 'sv', [ 'State', dbus.String("connected", variant_level=1), ]) device.props[DEVICE_IFACE]['Connected'] = dbus.Boolean(True, variant_level=1) device.EmitSignal(DEVICE_IFACE, 'PropertyChanged', 'sv', [ 'Connected', dbus.Boolean(True, variant_level=1), ])
python
def Connect(self): '''Connect a device ''' device_path = self.path if device_path not in mockobject.objects: raise dbus.exceptions.DBusException('No such device.', name='org.bluez.Error.NoSuchDevice') device = mockobject.objects[device_path] device.props[AUDIO_IFACE]['State'] = dbus.String("connected", variant_level=1) device.EmitSignal(AUDIO_IFACE, 'PropertyChanged', 'sv', [ 'State', dbus.String("connected", variant_level=1), ]) device.props[DEVICE_IFACE]['Connected'] = dbus.Boolean(True, variant_level=1) device.EmitSignal(DEVICE_IFACE, 'PropertyChanged', 'sv', [ 'Connected', dbus.Boolean(True, variant_level=1), ])
[ "def", "Connect", "(", "self", ")", ":", "device_path", "=", "self", ".", "path", "if", "device_path", "not", "in", "mockobject", ".", "objects", ":", "raise", "dbus", ".", "exceptions", ".", "DBusException", "(", "'No such device.'", ",", "name", "=", "'o...
Connect a device
[ "Connect", "a", "device" ]
26f65f78bc0ed347233f699a8d6ee0e6880e7eb0
https://github.com/martinpitt/python-dbusmock/blob/26f65f78bc0ed347233f699a8d6ee0e6880e7eb0/dbusmock/templates/bluez4.py#L376-L396
train
24,248
martinpitt/python-dbusmock
dbusmock/templates/bluez4.py
Disconnect
def Disconnect(self): '''Disconnect a device ''' device_path = self.path if device_path not in mockobject.objects: raise dbus.exceptions.DBusException('No such device.', name='org.bluez.Error.NoSuchDevice') device = mockobject.objects[device_path] try: device.props[AUDIO_IFACE]['State'] = dbus.String("disconnected", variant_level=1) device.EmitSignal(AUDIO_IFACE, 'PropertyChanged', 'sv', [ 'State', dbus.String("disconnected", variant_level=1), ]) except KeyError: pass device.props[DEVICE_IFACE]['Connected'] = dbus.Boolean(False, variant_level=1) device.EmitSignal(DEVICE_IFACE, 'PropertyChanged', 'sv', [ 'Connected', dbus.Boolean(False, variant_level=1), ])
python
def Disconnect(self): '''Disconnect a device ''' device_path = self.path if device_path not in mockobject.objects: raise dbus.exceptions.DBusException('No such device.', name='org.bluez.Error.NoSuchDevice') device = mockobject.objects[device_path] try: device.props[AUDIO_IFACE]['State'] = dbus.String("disconnected", variant_level=1) device.EmitSignal(AUDIO_IFACE, 'PropertyChanged', 'sv', [ 'State', dbus.String("disconnected", variant_level=1), ]) except KeyError: pass device.props[DEVICE_IFACE]['Connected'] = dbus.Boolean(False, variant_level=1) device.EmitSignal(DEVICE_IFACE, 'PropertyChanged', 'sv', [ 'Connected', dbus.Boolean(False, variant_level=1), ])
[ "def", "Disconnect", "(", "self", ")", ":", "device_path", "=", "self", ".", "path", "if", "device_path", "not", "in", "mockobject", ".", "objects", ":", "raise", "dbus", ".", "exceptions", ".", "DBusException", "(", "'No such device.'", ",", "name", "=", ...
Disconnect a device
[ "Disconnect", "a", "device" ]
26f65f78bc0ed347233f699a8d6ee0e6880e7eb0
https://github.com/martinpitt/python-dbusmock/blob/26f65f78bc0ed347233f699a8d6ee0e6880e7eb0/dbusmock/templates/bluez4.py#L401-L425
train
24,249
martinpitt/python-dbusmock
dbusmock/templates/networkmanager.py
AddEthernetDevice
def AddEthernetDevice(self, device_name, iface_name, state): '''Add an ethernet device. You have to specify device_name, device interface name (e. g. eth0), and state. You can use the predefined DeviceState values (e. g. DeviceState.ACTIVATED) or supply a numeric value. For valid state values please visit http://projects.gnome.org/NetworkManager/developers/api/09/spec.html#type-NM_DEVICE_STATE Please note that this does not set any global properties. Returns the new object path. ''' path = '/org/freedesktop/NetworkManager/Devices/' + device_name wired_props = {'Carrier': False, 'HwAddress': dbus.String('78:DD:08:D2:3D:43'), 'PermHwAddress': dbus.String('78:DD:08:D2:3D:43'), 'Speed': dbus.UInt32(0)} self.AddObject(path, 'org.freedesktop.NetworkManager.Device.Wired', wired_props, []) props = {'DeviceType': dbus.UInt32(1), 'State': dbus.UInt32(state), 'Interface': iface_name, 'ActiveConnection': dbus.ObjectPath('/'), 'AvailableConnections': dbus.Array([], signature='o'), 'AutoConnect': False, 'Managed': True, 'Driver': 'dbusmock', 'IpInterface': ''} obj = dbusmock.get_object(path) obj.AddProperties(DEVICE_IFACE, props) self.object_manager_emit_added(path) NM = dbusmock.get_object(MANAGER_OBJ) devices = NM.Get(MANAGER_IFACE, 'Devices') devices.append(path) NM.Set(MANAGER_IFACE, 'Devices', devices) NM.EmitSignal('org.freedesktop.NetworkManager', 'DeviceAdded', 'o', [path]) return path
python
def AddEthernetDevice(self, device_name, iface_name, state): '''Add an ethernet device. You have to specify device_name, device interface name (e. g. eth0), and state. You can use the predefined DeviceState values (e. g. DeviceState.ACTIVATED) or supply a numeric value. For valid state values please visit http://projects.gnome.org/NetworkManager/developers/api/09/spec.html#type-NM_DEVICE_STATE Please note that this does not set any global properties. Returns the new object path. ''' path = '/org/freedesktop/NetworkManager/Devices/' + device_name wired_props = {'Carrier': False, 'HwAddress': dbus.String('78:DD:08:D2:3D:43'), 'PermHwAddress': dbus.String('78:DD:08:D2:3D:43'), 'Speed': dbus.UInt32(0)} self.AddObject(path, 'org.freedesktop.NetworkManager.Device.Wired', wired_props, []) props = {'DeviceType': dbus.UInt32(1), 'State': dbus.UInt32(state), 'Interface': iface_name, 'ActiveConnection': dbus.ObjectPath('/'), 'AvailableConnections': dbus.Array([], signature='o'), 'AutoConnect': False, 'Managed': True, 'Driver': 'dbusmock', 'IpInterface': ''} obj = dbusmock.get_object(path) obj.AddProperties(DEVICE_IFACE, props) self.object_manager_emit_added(path) NM = dbusmock.get_object(MANAGER_OBJ) devices = NM.Get(MANAGER_IFACE, 'Devices') devices.append(path) NM.Set(MANAGER_IFACE, 'Devices', devices) NM.EmitSignal('org.freedesktop.NetworkManager', 'DeviceAdded', 'o', [path]) return path
[ "def", "AddEthernetDevice", "(", "self", ",", "device_name", ",", "iface_name", ",", "state", ")", ":", "path", "=", "'/org/freedesktop/NetworkManager/Devices/'", "+", "device_name", "wired_props", "=", "{", "'Carrier'", ":", "False", ",", "'HwAddress'", ":", "dbu...
Add an ethernet device. You have to specify device_name, device interface name (e. g. eth0), and state. You can use the predefined DeviceState values (e. g. DeviceState.ACTIVATED) or supply a numeric value. For valid state values please visit http://projects.gnome.org/NetworkManager/developers/api/09/spec.html#type-NM_DEVICE_STATE Please note that this does not set any global properties. Returns the new object path.
[ "Add", "an", "ethernet", "device", "." ]
26f65f78bc0ed347233f699a8d6ee0e6880e7eb0
https://github.com/martinpitt/python-dbusmock/blob/26f65f78bc0ed347233f699a8d6ee0e6880e7eb0/dbusmock/templates/networkmanager.py#L299-L343
train
24,250
martinpitt/python-dbusmock
dbusmock/templates/networkmanager.py
AddWiFiDevice
def AddWiFiDevice(self, device_name, iface_name, state): '''Add a WiFi Device. You have to specify device_name, device interface name (e. g. wlan0) and state. You can use the predefined DeviceState values (e. g. DeviceState.ACTIVATED) or supply a numeric value. For valid state values, please visit http://projects.gnome.org/NetworkManager/developers/api/09/spec.html#type-NM_DEVICE_STATE Please note that this does not set any global properties. Returns the new object path. ''' path = '/org/freedesktop/NetworkManager/Devices/' + device_name self.AddObject(path, WIRELESS_DEVICE_IFACE, { 'HwAddress': dbus.String('11:22:33:44:55:66'), 'PermHwAddress': dbus.String('11:22:33:44:55:66'), 'Bitrate': dbus.UInt32(5400), 'Mode': dbus.UInt32(2), 'WirelessCapabilities': dbus.UInt32(255), 'AccessPoints': dbus.Array([], signature='o'), }, [ ('GetAccessPoints', '', 'ao', 'ret = self.access_points'), ('GetAllAccessPoints', '', 'ao', 'ret = self.access_points'), ('RequestScan', 'a{sv}', '', ''), ]) dev_obj = dbusmock.get_object(path) dev_obj.access_points = [] dev_obj.AddProperties(DEVICE_IFACE, { 'ActiveConnection': dbus.ObjectPath('/'), 'AvailableConnections': dbus.Array([], signature='o'), 'AutoConnect': False, 'Managed': True, 'Driver': 'dbusmock', 'DeviceType': dbus.UInt32(2), 'State': dbus.UInt32(state), 'Interface': iface_name, 'IpInterface': iface_name, }) self.object_manager_emit_added(path) NM = dbusmock.get_object(MANAGER_OBJ) devices = NM.Get(MANAGER_IFACE, 'Devices') devices.append(path) NM.Set(MANAGER_IFACE, 'Devices', devices) NM.EmitSignal('org.freedesktop.NetworkManager', 'DeviceAdded', 'o', [path]) return path
python
def AddWiFiDevice(self, device_name, iface_name, state): '''Add a WiFi Device. You have to specify device_name, device interface name (e. g. wlan0) and state. You can use the predefined DeviceState values (e. g. DeviceState.ACTIVATED) or supply a numeric value. For valid state values, please visit http://projects.gnome.org/NetworkManager/developers/api/09/spec.html#type-NM_DEVICE_STATE Please note that this does not set any global properties. Returns the new object path. ''' path = '/org/freedesktop/NetworkManager/Devices/' + device_name self.AddObject(path, WIRELESS_DEVICE_IFACE, { 'HwAddress': dbus.String('11:22:33:44:55:66'), 'PermHwAddress': dbus.String('11:22:33:44:55:66'), 'Bitrate': dbus.UInt32(5400), 'Mode': dbus.UInt32(2), 'WirelessCapabilities': dbus.UInt32(255), 'AccessPoints': dbus.Array([], signature='o'), }, [ ('GetAccessPoints', '', 'ao', 'ret = self.access_points'), ('GetAllAccessPoints', '', 'ao', 'ret = self.access_points'), ('RequestScan', 'a{sv}', '', ''), ]) dev_obj = dbusmock.get_object(path) dev_obj.access_points = [] dev_obj.AddProperties(DEVICE_IFACE, { 'ActiveConnection': dbus.ObjectPath('/'), 'AvailableConnections': dbus.Array([], signature='o'), 'AutoConnect': False, 'Managed': True, 'Driver': 'dbusmock', 'DeviceType': dbus.UInt32(2), 'State': dbus.UInt32(state), 'Interface': iface_name, 'IpInterface': iface_name, }) self.object_manager_emit_added(path) NM = dbusmock.get_object(MANAGER_OBJ) devices = NM.Get(MANAGER_IFACE, 'Devices') devices.append(path) NM.Set(MANAGER_IFACE, 'Devices', devices) NM.EmitSignal('org.freedesktop.NetworkManager', 'DeviceAdded', 'o', [path]) return path
[ "def", "AddWiFiDevice", "(", "self", ",", "device_name", ",", "iface_name", ",", "state", ")", ":", "path", "=", "'/org/freedesktop/NetworkManager/Devices/'", "+", "device_name", "self", ".", "AddObject", "(", "path", ",", "WIRELESS_DEVICE_IFACE", ",", "{", "'HwAd...
Add a WiFi Device. You have to specify device_name, device interface name (e. g. wlan0) and state. You can use the predefined DeviceState values (e. g. DeviceState.ACTIVATED) or supply a numeric value. For valid state values, please visit http://projects.gnome.org/NetworkManager/developers/api/09/spec.html#type-NM_DEVICE_STATE Please note that this does not set any global properties. Returns the new object path.
[ "Add", "a", "WiFi", "Device", "." ]
26f65f78bc0ed347233f699a8d6ee0e6880e7eb0
https://github.com/martinpitt/python-dbusmock/blob/26f65f78bc0ed347233f699a8d6ee0e6880e7eb0/dbusmock/templates/networkmanager.py#L348-L404
train
24,251
martinpitt/python-dbusmock
dbusmock/templates/networkmanager.py
AddAccessPoint
def AddAccessPoint(self, dev_path, ap_name, ssid, hw_address, mode, frequency, rate, strength, security): '''Add an access point to an existing WiFi device. You have to specify WiFi Device path, Access Point object name, ssid, hw_address, mode, frequency, rate, strength and security. For valid access point property values, please visit http://projects.gnome.org/NetworkManager/developers/api/09/spec.html#org.freedesktop.NetworkManager.AccessPoint Please note that this does not set any global properties. Returns the new object path. ''' dev_obj = dbusmock.get_object(dev_path) ap_path = '/org/freedesktop/NetworkManager/AccessPoint/' + ap_name if ap_path in dev_obj.access_points: raise dbus.exceptions.DBusException( 'Access point %s on device %s already exists' % (ap_name, dev_path), name=MANAGER_IFACE + '.AlreadyExists') flags = NM80211ApFlags.NM_802_11_AP_FLAGS_PRIVACY if security == NM80211ApSecurityFlags.NM_802_11_AP_SEC_NONE: flags = NM80211ApFlags.NM_802_11_AP_FLAGS_NONE self.AddObject(ap_path, ACCESS_POINT_IFACE, {'Ssid': dbus.ByteArray(ssid.encode('UTF-8')), 'HwAddress': dbus.String(hw_address), 'Flags': dbus.UInt32(flags), 'LastSeen': dbus.Int32(1), 'Frequency': dbus.UInt32(frequency), 'MaxBitrate': dbus.UInt32(rate), 'Mode': dbus.UInt32(mode), 'RsnFlags': dbus.UInt32(security), 'WpaFlags': dbus.UInt32(security), 'Strength': dbus.Byte(strength)}, []) self.object_manager_emit_added(ap_path) dev_obj.access_points.append(ap_path) aps = dev_obj.Get(WIRELESS_DEVICE_IFACE, 'AccessPoints') aps.append(ap_path) dev_obj.Set(WIRELESS_DEVICE_IFACE, 'AccessPoints', aps) dev_obj.EmitSignal(WIRELESS_DEVICE_IFACE, 'AccessPointAdded', 'o', [ap_path]) return ap_path
python
def AddAccessPoint(self, dev_path, ap_name, ssid, hw_address, mode, frequency, rate, strength, security): '''Add an access point to an existing WiFi device. You have to specify WiFi Device path, Access Point object name, ssid, hw_address, mode, frequency, rate, strength and security. For valid access point property values, please visit http://projects.gnome.org/NetworkManager/developers/api/09/spec.html#org.freedesktop.NetworkManager.AccessPoint Please note that this does not set any global properties. Returns the new object path. ''' dev_obj = dbusmock.get_object(dev_path) ap_path = '/org/freedesktop/NetworkManager/AccessPoint/' + ap_name if ap_path in dev_obj.access_points: raise dbus.exceptions.DBusException( 'Access point %s on device %s already exists' % (ap_name, dev_path), name=MANAGER_IFACE + '.AlreadyExists') flags = NM80211ApFlags.NM_802_11_AP_FLAGS_PRIVACY if security == NM80211ApSecurityFlags.NM_802_11_AP_SEC_NONE: flags = NM80211ApFlags.NM_802_11_AP_FLAGS_NONE self.AddObject(ap_path, ACCESS_POINT_IFACE, {'Ssid': dbus.ByteArray(ssid.encode('UTF-8')), 'HwAddress': dbus.String(hw_address), 'Flags': dbus.UInt32(flags), 'LastSeen': dbus.Int32(1), 'Frequency': dbus.UInt32(frequency), 'MaxBitrate': dbus.UInt32(rate), 'Mode': dbus.UInt32(mode), 'RsnFlags': dbus.UInt32(security), 'WpaFlags': dbus.UInt32(security), 'Strength': dbus.Byte(strength)}, []) self.object_manager_emit_added(ap_path) dev_obj.access_points.append(ap_path) aps = dev_obj.Get(WIRELESS_DEVICE_IFACE, 'AccessPoints') aps.append(ap_path) dev_obj.Set(WIRELESS_DEVICE_IFACE, 'AccessPoints', aps) dev_obj.EmitSignal(WIRELESS_DEVICE_IFACE, 'AccessPointAdded', 'o', [ap_path]) return ap_path
[ "def", "AddAccessPoint", "(", "self", ",", "dev_path", ",", "ap_name", ",", "ssid", ",", "hw_address", ",", "mode", ",", "frequency", ",", "rate", ",", "strength", ",", "security", ")", ":", "dev_obj", "=", "dbusmock", ".", "get_object", "(", "dev_path", ...
Add an access point to an existing WiFi device. You have to specify WiFi Device path, Access Point object name, ssid, hw_address, mode, frequency, rate, strength and security. For valid access point property values, please visit http://projects.gnome.org/NetworkManager/developers/api/09/spec.html#org.freedesktop.NetworkManager.AccessPoint Please note that this does not set any global properties. Returns the new object path.
[ "Add", "an", "access", "point", "to", "an", "existing", "WiFi", "device", "." ]
26f65f78bc0ed347233f699a8d6ee0e6880e7eb0
https://github.com/martinpitt/python-dbusmock/blob/26f65f78bc0ed347233f699a8d6ee0e6880e7eb0/dbusmock/templates/networkmanager.py#L409-L456
train
24,252
martinpitt/python-dbusmock
dbusmock/templates/networkmanager.py
AddWiFiConnection
def AddWiFiConnection(self, dev_path, connection_name, ssid_name, key_mgmt): '''Add an available connection to an existing WiFi device and access point. You have to specify WiFi Device path, Connection object name, SSID and key management. The SSID must match one of the previously created access points. Please note that this does not set any global properties. Returns the new object path. ''' dev_obj = dbusmock.get_object(dev_path) connection_path = '/org/freedesktop/NetworkManager/Settings/' + connection_name connections = dev_obj.Get(DEVICE_IFACE, 'AvailableConnections') settings_obj = dbusmock.get_object(SETTINGS_OBJ) main_connections = settings_obj.ListConnections() ssid = ssid_name.encode('UTF-8') # Find the access point by ssid access_point = None access_points = dev_obj.access_points for ap_path in access_points: ap = dbusmock.get_object(ap_path) if ap.Get(ACCESS_POINT_IFACE, 'Ssid') == ssid: access_point = ap break if not access_point: raise dbus.exceptions.DBusException( 'Access point with SSID [%s] could not be found' % (ssid_name), name=MANAGER_IFACE + '.DoesNotExist') hw_address = access_point.Get(ACCESS_POINT_IFACE, 'HwAddress') mode = access_point.Get(ACCESS_POINT_IFACE, 'Mode') security = access_point.Get(ACCESS_POINT_IFACE, 'WpaFlags') if connection_path in connections or connection_path in main_connections: raise dbus.exceptions.DBusException( 'Connection %s on device %s already exists' % (connection_name, dev_path), name=MANAGER_IFACE + '.AlreadyExists') # Parse mac address string into byte array mac_bytes = binascii.unhexlify(hw_address.replace(':', '')) settings = { '802-11-wireless': { 'seen-bssids': [hw_address], 'ssid': dbus.ByteArray(ssid), 'mac-address': dbus.ByteArray(mac_bytes), 'mode': InfrastructureMode.NAME_MAP[mode] }, 'connection': { 'timestamp': dbus.UInt64(1374828522), 'type': '802-11-wireless', 'id': ssid_name, 'uuid': str(uuid.uuid4()) }, } if security != NM80211ApSecurityFlags.NM_802_11_AP_SEC_NONE: settings['802-11-wireless']['security'] = '802-11-wireless-security' settings['802-11-wireless-security'] = NM80211ApSecurityFlags.NAME_MAP[security] self.AddObject(connection_path, CSETTINGS_IFACE, { 'Unsaved': False }, [ ('Delete', '', '', 'self.ConnectionDelete(self)'), ('GetSettings', '', 'a{sa{sv}}', 'ret = self.ConnectionGetSettings(self)'), ('GetSecrets', 's', 'a{sa{sv}}', 'ret = self.ConnectionGetSecrets(self, args[0])'), ('Update', 'a{sa{sv}}', '', 'self.ConnectionUpdate(self, args[0])'), ]) self.object_manager_emit_added(connection_path) connection_obj = dbusmock.get_object(connection_path) connection_obj.settings = settings connection_obj.connection_path = connection_path connection_obj.ConnectionDelete = ConnectionDelete connection_obj.ConnectionGetSettings = ConnectionGetSettings connection_obj.ConnectionGetSecrets = ConnectionGetSecrets connection_obj.ConnectionUpdate = ConnectionUpdate connections.append(dbus.ObjectPath(connection_path)) dev_obj.Set(DEVICE_IFACE, 'AvailableConnections', connections) main_connections.append(connection_path) settings_obj.Set(SETTINGS_IFACE, 'Connections', main_connections) settings_obj.EmitSignal(SETTINGS_IFACE, 'NewConnection', 'o', [ap_path]) return connection_path
python
def AddWiFiConnection(self, dev_path, connection_name, ssid_name, key_mgmt): '''Add an available connection to an existing WiFi device and access point. You have to specify WiFi Device path, Connection object name, SSID and key management. The SSID must match one of the previously created access points. Please note that this does not set any global properties. Returns the new object path. ''' dev_obj = dbusmock.get_object(dev_path) connection_path = '/org/freedesktop/NetworkManager/Settings/' + connection_name connections = dev_obj.Get(DEVICE_IFACE, 'AvailableConnections') settings_obj = dbusmock.get_object(SETTINGS_OBJ) main_connections = settings_obj.ListConnections() ssid = ssid_name.encode('UTF-8') # Find the access point by ssid access_point = None access_points = dev_obj.access_points for ap_path in access_points: ap = dbusmock.get_object(ap_path) if ap.Get(ACCESS_POINT_IFACE, 'Ssid') == ssid: access_point = ap break if not access_point: raise dbus.exceptions.DBusException( 'Access point with SSID [%s] could not be found' % (ssid_name), name=MANAGER_IFACE + '.DoesNotExist') hw_address = access_point.Get(ACCESS_POINT_IFACE, 'HwAddress') mode = access_point.Get(ACCESS_POINT_IFACE, 'Mode') security = access_point.Get(ACCESS_POINT_IFACE, 'WpaFlags') if connection_path in connections or connection_path in main_connections: raise dbus.exceptions.DBusException( 'Connection %s on device %s already exists' % (connection_name, dev_path), name=MANAGER_IFACE + '.AlreadyExists') # Parse mac address string into byte array mac_bytes = binascii.unhexlify(hw_address.replace(':', '')) settings = { '802-11-wireless': { 'seen-bssids': [hw_address], 'ssid': dbus.ByteArray(ssid), 'mac-address': dbus.ByteArray(mac_bytes), 'mode': InfrastructureMode.NAME_MAP[mode] }, 'connection': { 'timestamp': dbus.UInt64(1374828522), 'type': '802-11-wireless', 'id': ssid_name, 'uuid': str(uuid.uuid4()) }, } if security != NM80211ApSecurityFlags.NM_802_11_AP_SEC_NONE: settings['802-11-wireless']['security'] = '802-11-wireless-security' settings['802-11-wireless-security'] = NM80211ApSecurityFlags.NAME_MAP[security] self.AddObject(connection_path, CSETTINGS_IFACE, { 'Unsaved': False }, [ ('Delete', '', '', 'self.ConnectionDelete(self)'), ('GetSettings', '', 'a{sa{sv}}', 'ret = self.ConnectionGetSettings(self)'), ('GetSecrets', 's', 'a{sa{sv}}', 'ret = self.ConnectionGetSecrets(self, args[0])'), ('Update', 'a{sa{sv}}', '', 'self.ConnectionUpdate(self, args[0])'), ]) self.object_manager_emit_added(connection_path) connection_obj = dbusmock.get_object(connection_path) connection_obj.settings = settings connection_obj.connection_path = connection_path connection_obj.ConnectionDelete = ConnectionDelete connection_obj.ConnectionGetSettings = ConnectionGetSettings connection_obj.ConnectionGetSecrets = ConnectionGetSecrets connection_obj.ConnectionUpdate = ConnectionUpdate connections.append(dbus.ObjectPath(connection_path)) dev_obj.Set(DEVICE_IFACE, 'AvailableConnections', connections) main_connections.append(connection_path) settings_obj.Set(SETTINGS_IFACE, 'Connections', main_connections) settings_obj.EmitSignal(SETTINGS_IFACE, 'NewConnection', 'o', [ap_path]) return connection_path
[ "def", "AddWiFiConnection", "(", "self", ",", "dev_path", ",", "connection_name", ",", "ssid_name", ",", "key_mgmt", ")", ":", "dev_obj", "=", "dbusmock", ".", "get_object", "(", "dev_path", ")", "connection_path", "=", "'/org/freedesktop/NetworkManager/Settings/'", ...
Add an available connection to an existing WiFi device and access point. You have to specify WiFi Device path, Connection object name, SSID and key management. The SSID must match one of the previously created access points. Please note that this does not set any global properties. Returns the new object path.
[ "Add", "an", "available", "connection", "to", "an", "existing", "WiFi", "device", "and", "access", "point", "." ]
26f65f78bc0ed347233f699a8d6ee0e6880e7eb0
https://github.com/martinpitt/python-dbusmock/blob/26f65f78bc0ed347233f699a8d6ee0e6880e7eb0/dbusmock/templates/networkmanager.py#L461-L557
train
24,253
martinpitt/python-dbusmock
dbusmock/templates/networkmanager.py
AddActiveConnection
def AddActiveConnection(self, devices, connection_device, specific_object, name, state): '''Add an active connection to an existing WiFi device. You have to a list of the involved WiFi devices, the connection path, the access point path, ActiveConnection object name and connection state. Please note that this does not set any global properties. Returns the new object path. ''' conn_obj = dbusmock.get_object(connection_device) settings = conn_obj.settings conn_uuid = settings['connection']['uuid'] conn_type = settings['connection']['type'] device_objects = [dbus.ObjectPath(dev) for dev in devices] active_connection_path = '/org/freedesktop/NetworkManager/ActiveConnection/' + name self.AddObject(active_connection_path, ACTIVE_CONNECTION_IFACE, { 'Devices': dbus.Array(device_objects, signature='o'), 'Default6': False, 'Default': True, 'Type': conn_type, 'Vpn': (conn_type == 'vpn'), 'Connection': dbus.ObjectPath(connection_device), 'Master': dbus.ObjectPath('/'), 'SpecificObject': dbus.ObjectPath(specific_object), 'Uuid': conn_uuid, 'State': dbus.UInt32(state), }, []) for dev_path in devices: self.SetDeviceActive(dev_path, active_connection_path) self.object_manager_emit_added(active_connection_path) NM = dbusmock.get_object(MANAGER_OBJ) active_connections = NM.Get(MANAGER_IFACE, 'ActiveConnections') active_connections.append(dbus.ObjectPath(active_connection_path)) NM.SetProperty(MANAGER_OBJ, MANAGER_IFACE, 'ActiveConnections', active_connections) return active_connection_path
python
def AddActiveConnection(self, devices, connection_device, specific_object, name, state): '''Add an active connection to an existing WiFi device. You have to a list of the involved WiFi devices, the connection path, the access point path, ActiveConnection object name and connection state. Please note that this does not set any global properties. Returns the new object path. ''' conn_obj = dbusmock.get_object(connection_device) settings = conn_obj.settings conn_uuid = settings['connection']['uuid'] conn_type = settings['connection']['type'] device_objects = [dbus.ObjectPath(dev) for dev in devices] active_connection_path = '/org/freedesktop/NetworkManager/ActiveConnection/' + name self.AddObject(active_connection_path, ACTIVE_CONNECTION_IFACE, { 'Devices': dbus.Array(device_objects, signature='o'), 'Default6': False, 'Default': True, 'Type': conn_type, 'Vpn': (conn_type == 'vpn'), 'Connection': dbus.ObjectPath(connection_device), 'Master': dbus.ObjectPath('/'), 'SpecificObject': dbus.ObjectPath(specific_object), 'Uuid': conn_uuid, 'State': dbus.UInt32(state), }, []) for dev_path in devices: self.SetDeviceActive(dev_path, active_connection_path) self.object_manager_emit_added(active_connection_path) NM = dbusmock.get_object(MANAGER_OBJ) active_connections = NM.Get(MANAGER_IFACE, 'ActiveConnections') active_connections.append(dbus.ObjectPath(active_connection_path)) NM.SetProperty(MANAGER_OBJ, MANAGER_IFACE, 'ActiveConnections', active_connections) return active_connection_path
[ "def", "AddActiveConnection", "(", "self", ",", "devices", ",", "connection_device", ",", "specific_object", ",", "name", ",", "state", ")", ":", "conn_obj", "=", "dbusmock", ".", "get_object", "(", "connection_device", ")", "settings", "=", "conn_obj", ".", "...
Add an active connection to an existing WiFi device. You have to a list of the involved WiFi devices, the connection path, the access point path, ActiveConnection object name and connection state. Please note that this does not set any global properties. Returns the new object path.
[ "Add", "an", "active", "connection", "to", "an", "existing", "WiFi", "device", "." ]
26f65f78bc0ed347233f699a8d6ee0e6880e7eb0
https://github.com/martinpitt/python-dbusmock/blob/26f65f78bc0ed347233f699a8d6ee0e6880e7eb0/dbusmock/templates/networkmanager.py#L562-L608
train
24,254
martinpitt/python-dbusmock
dbusmock/templates/networkmanager.py
RemoveAccessPoint
def RemoveAccessPoint(self, dev_path, ap_path): '''Remove the specified access point. You have to specify the device to remove the access point from, and the path of the access point. Please note that this does not set any global properties. ''' dev_obj = dbusmock.get_object(dev_path) aps = dev_obj.Get(WIRELESS_DEVICE_IFACE, 'AccessPoints') aps.remove(ap_path) dev_obj.Set(WIRELESS_DEVICE_IFACE, 'AccessPoints', aps) dev_obj.access_points.remove(ap_path) dev_obj.EmitSignal(WIRELESS_DEVICE_IFACE, 'AccessPointRemoved', 'o', [ap_path]) self.object_manager_emit_removed(ap_path) self.RemoveObject(ap_path)
python
def RemoveAccessPoint(self, dev_path, ap_path): '''Remove the specified access point. You have to specify the device to remove the access point from, and the path of the access point. Please note that this does not set any global properties. ''' dev_obj = dbusmock.get_object(dev_path) aps = dev_obj.Get(WIRELESS_DEVICE_IFACE, 'AccessPoints') aps.remove(ap_path) dev_obj.Set(WIRELESS_DEVICE_IFACE, 'AccessPoints', aps) dev_obj.access_points.remove(ap_path) dev_obj.EmitSignal(WIRELESS_DEVICE_IFACE, 'AccessPointRemoved', 'o', [ap_path]) self.object_manager_emit_removed(ap_path) self.RemoveObject(ap_path)
[ "def", "RemoveAccessPoint", "(", "self", ",", "dev_path", ",", "ap_path", ")", ":", "dev_obj", "=", "dbusmock", ".", "get_object", "(", "dev_path", ")", "aps", "=", "dev_obj", ".", "Get", "(", "WIRELESS_DEVICE_IFACE", ",", "'AccessPoints'", ")", "aps", ".", ...
Remove the specified access point. You have to specify the device to remove the access point from, and the path of the access point. Please note that this does not set any global properties.
[ "Remove", "the", "specified", "access", "point", "." ]
26f65f78bc0ed347233f699a8d6ee0e6880e7eb0
https://github.com/martinpitt/python-dbusmock/blob/26f65f78bc0ed347233f699a8d6ee0e6880e7eb0/dbusmock/templates/networkmanager.py#L613-L633
train
24,255
martinpitt/python-dbusmock
dbusmock/templates/networkmanager.py
RemoveWifiConnection
def RemoveWifiConnection(self, dev_path, connection_path): '''Remove the specified WiFi connection. You have to specify the device to remove the connection from, and the path of the Connection. Please note that this does not set any global properties. ''' dev_obj = dbusmock.get_object(dev_path) settings_obj = dbusmock.get_object(SETTINGS_OBJ) connections = dev_obj.Get(DEVICE_IFACE, 'AvailableConnections') main_connections = settings_obj.ListConnections() if connection_path not in connections and connection_path not in main_connections: return connections.remove(dbus.ObjectPath(connection_path)) dev_obj.Set(DEVICE_IFACE, 'AvailableConnections', connections) main_connections.remove(connection_path) settings_obj.Set(SETTINGS_IFACE, 'Connections', main_connections) settings_obj.EmitSignal(SETTINGS_IFACE, 'ConnectionRemoved', 'o', [connection_path]) connection_obj = dbusmock.get_object(connection_path) connection_obj.EmitSignal(CSETTINGS_IFACE, 'Removed', '', []) self.object_manager_emit_removed(connection_path) self.RemoveObject(connection_path)
python
def RemoveWifiConnection(self, dev_path, connection_path): '''Remove the specified WiFi connection. You have to specify the device to remove the connection from, and the path of the Connection. Please note that this does not set any global properties. ''' dev_obj = dbusmock.get_object(dev_path) settings_obj = dbusmock.get_object(SETTINGS_OBJ) connections = dev_obj.Get(DEVICE_IFACE, 'AvailableConnections') main_connections = settings_obj.ListConnections() if connection_path not in connections and connection_path not in main_connections: return connections.remove(dbus.ObjectPath(connection_path)) dev_obj.Set(DEVICE_IFACE, 'AvailableConnections', connections) main_connections.remove(connection_path) settings_obj.Set(SETTINGS_IFACE, 'Connections', main_connections) settings_obj.EmitSignal(SETTINGS_IFACE, 'ConnectionRemoved', 'o', [connection_path]) connection_obj = dbusmock.get_object(connection_path) connection_obj.EmitSignal(CSETTINGS_IFACE, 'Removed', '', []) self.object_manager_emit_removed(connection_path) self.RemoveObject(connection_path)
[ "def", "RemoveWifiConnection", "(", "self", ",", "dev_path", ",", "connection_path", ")", ":", "dev_obj", "=", "dbusmock", ".", "get_object", "(", "dev_path", ")", "settings_obj", "=", "dbusmock", ".", "get_object", "(", "SETTINGS_OBJ", ")", "connections", "=", ...
Remove the specified WiFi connection. You have to specify the device to remove the connection from, and the path of the Connection. Please note that this does not set any global properties.
[ "Remove", "the", "specified", "WiFi", "connection", "." ]
26f65f78bc0ed347233f699a8d6ee0e6880e7eb0
https://github.com/martinpitt/python-dbusmock/blob/26f65f78bc0ed347233f699a8d6ee0e6880e7eb0/dbusmock/templates/networkmanager.py#L638-L668
train
24,256
martinpitt/python-dbusmock
dbusmock/templates/networkmanager.py
RemoveActiveConnection
def RemoveActiveConnection(self, dev_path, active_connection_path): '''Remove the specified ActiveConnection. You have to specify the device to remove the connection from, and the path of the ActiveConnection. Please note that this does not set any global properties. ''' self.SetDeviceDisconnected(dev_path) NM = dbusmock.get_object(MANAGER_OBJ) active_connections = NM.Get(MANAGER_IFACE, 'ActiveConnections') if active_connection_path not in active_connections: return active_connections.remove(dbus.ObjectPath(active_connection_path)) NM.SetProperty(MANAGER_OBJ, MANAGER_IFACE, 'ActiveConnections', active_connections) self.object_manager_emit_removed(active_connection_path) self.RemoveObject(active_connection_path)
python
def RemoveActiveConnection(self, dev_path, active_connection_path): '''Remove the specified ActiveConnection. You have to specify the device to remove the connection from, and the path of the ActiveConnection. Please note that this does not set any global properties. ''' self.SetDeviceDisconnected(dev_path) NM = dbusmock.get_object(MANAGER_OBJ) active_connections = NM.Get(MANAGER_IFACE, 'ActiveConnections') if active_connection_path not in active_connections: return active_connections.remove(dbus.ObjectPath(active_connection_path)) NM.SetProperty(MANAGER_OBJ, MANAGER_IFACE, 'ActiveConnections', active_connections) self.object_manager_emit_removed(active_connection_path) self.RemoveObject(active_connection_path)
[ "def", "RemoveActiveConnection", "(", "self", ",", "dev_path", ",", "active_connection_path", ")", ":", "self", ".", "SetDeviceDisconnected", "(", "dev_path", ")", "NM", "=", "dbusmock", ".", "get_object", "(", "MANAGER_OBJ", ")", "active_connections", "=", "NM", ...
Remove the specified ActiveConnection. You have to specify the device to remove the connection from, and the path of the ActiveConnection. Please note that this does not set any global properties.
[ "Remove", "the", "specified", "ActiveConnection", "." ]
26f65f78bc0ed347233f699a8d6ee0e6880e7eb0
https://github.com/martinpitt/python-dbusmock/blob/26f65f78bc0ed347233f699a8d6ee0e6880e7eb0/dbusmock/templates/networkmanager.py#L673-L693
train
24,257
martinpitt/python-dbusmock
dbusmock/templates/networkmanager.py
SettingsAddConnection
def SettingsAddConnection(self, connection_settings): '''Add a connection. connection_settings is a String String Variant Map Map. See https://developer.gnome.org/NetworkManager/0.9/spec.html #type-String_String_Variant_Map_Map If you omit uuid, this method adds one for you. ''' if 'uuid' not in connection_settings['connection']: connection_settings['connection']['uuid'] = str(uuid.uuid4()) NM = dbusmock.get_object(MANAGER_OBJ) settings_obj = dbusmock.get_object(SETTINGS_OBJ) main_connections = settings_obj.ListConnections() # Mimic how NM names connections count = 0 while True: connection_obj_path = dbus.ObjectPath(SETTINGS_OBJ + '/' + str(count)) if connection_obj_path not in main_connections: break count += 1 connection_path = str(connection_obj_path) self.AddObject(connection_path, CSETTINGS_IFACE, { 'Unsaved': False }, [ ('Delete', '', '', 'self.ConnectionDelete(self)'), ('GetSettings', '', 'a{sa{sv}}', 'ret = self.ConnectionGetSettings(self)'), ('GetSecrets', 's', 'a{sa{sv}}', 'ret = self.ConnectionGetSecrets(self, args[0])'), ('Update', 'a{sa{sv}}', '', 'self.ConnectionUpdate(self, args[0])'), ]) self.object_manager_emit_added(connection_path) connection_obj = dbusmock.get_object(connection_path) connection_obj.settings = connection_settings connection_obj.connection_path = connection_path connection_obj.ConnectionDelete = ConnectionDelete connection_obj.ConnectionGetSettings = ConnectionGetSettings connection_obj.ConnectionGetSecrets = ConnectionGetSecrets connection_obj.ConnectionUpdate = ConnectionUpdate main_connections.append(connection_path) settings_obj.Set(SETTINGS_IFACE, 'Connections', main_connections) settings_obj.EmitSignal(SETTINGS_IFACE, 'NewConnection', 'o', [connection_path]) auto_connect = False if 'autoconnect' in connection_settings['connection']: auto_connect = connection_settings['connection']['autoconnect'] if auto_connect: dev = None devices = NM.GetDevices() # Grab the first device. if len(devices) > 0: dev = devices[0] if dev: activate_connection(NM, connection_path, dev, connection_path) return connection_path
python
def SettingsAddConnection(self, connection_settings): '''Add a connection. connection_settings is a String String Variant Map Map. See https://developer.gnome.org/NetworkManager/0.9/spec.html #type-String_String_Variant_Map_Map If you omit uuid, this method adds one for you. ''' if 'uuid' not in connection_settings['connection']: connection_settings['connection']['uuid'] = str(uuid.uuid4()) NM = dbusmock.get_object(MANAGER_OBJ) settings_obj = dbusmock.get_object(SETTINGS_OBJ) main_connections = settings_obj.ListConnections() # Mimic how NM names connections count = 0 while True: connection_obj_path = dbus.ObjectPath(SETTINGS_OBJ + '/' + str(count)) if connection_obj_path not in main_connections: break count += 1 connection_path = str(connection_obj_path) self.AddObject(connection_path, CSETTINGS_IFACE, { 'Unsaved': False }, [ ('Delete', '', '', 'self.ConnectionDelete(self)'), ('GetSettings', '', 'a{sa{sv}}', 'ret = self.ConnectionGetSettings(self)'), ('GetSecrets', 's', 'a{sa{sv}}', 'ret = self.ConnectionGetSecrets(self, args[0])'), ('Update', 'a{sa{sv}}', '', 'self.ConnectionUpdate(self, args[0])'), ]) self.object_manager_emit_added(connection_path) connection_obj = dbusmock.get_object(connection_path) connection_obj.settings = connection_settings connection_obj.connection_path = connection_path connection_obj.ConnectionDelete = ConnectionDelete connection_obj.ConnectionGetSettings = ConnectionGetSettings connection_obj.ConnectionGetSecrets = ConnectionGetSecrets connection_obj.ConnectionUpdate = ConnectionUpdate main_connections.append(connection_path) settings_obj.Set(SETTINGS_IFACE, 'Connections', main_connections) settings_obj.EmitSignal(SETTINGS_IFACE, 'NewConnection', 'o', [connection_path]) auto_connect = False if 'autoconnect' in connection_settings['connection']: auto_connect = connection_settings['connection']['autoconnect'] if auto_connect: dev = None devices = NM.GetDevices() # Grab the first device. if len(devices) > 0: dev = devices[0] if dev: activate_connection(NM, connection_path, dev, connection_path) return connection_path
[ "def", "SettingsAddConnection", "(", "self", ",", "connection_settings", ")", ":", "if", "'uuid'", "not", "in", "connection_settings", "[", "'connection'", "]", ":", "connection_settings", "[", "'connection'", "]", "[", "'uuid'", "]", "=", "str", "(", "uuid", ...
Add a connection. connection_settings is a String String Variant Map Map. See https://developer.gnome.org/NetworkManager/0.9/spec.html #type-String_String_Variant_Map_Map If you omit uuid, this method adds one for you.
[ "Add", "a", "connection", "." ]
26f65f78bc0ed347233f699a8d6ee0e6880e7eb0
https://github.com/martinpitt/python-dbusmock/blob/26f65f78bc0ed347233f699a8d6ee0e6880e7eb0/dbusmock/templates/networkmanager.py#L698-L765
train
24,258
martinpitt/python-dbusmock
dbusmock/templates/networkmanager.py
ConnectionUpdate
def ConnectionUpdate(self, settings): '''Update settings on a connection. settings is a String String Variant Map Map. See https://developer.gnome.org/NetworkManager/0.9/spec.html #type-String_String_Variant_Map_Map ''' connection_path = self.connection_path NM = dbusmock.get_object(MANAGER_OBJ) settings_obj = dbusmock.get_object(SETTINGS_OBJ) main_connections = settings_obj.ListConnections() if connection_path not in main_connections: raise dbus.exceptions.DBusException( 'Connection %s does not exist' % connection_path, name=MANAGER_IFACE + '.DoesNotExist',) # Take care not to overwrite the secrets for setting_name in settings: setting = settings[setting_name] for k in setting: if setting_name not in self.settings: self.settings[setting_name] = {} self.settings[setting_name][k] = setting[k] self.EmitSignal(CSETTINGS_IFACE, 'Updated', '', []) auto_connect = False if 'autoconnect' in settings['connection']: auto_connect = settings['connection']['autoconnect'] if auto_connect: dev = None devices = NM.GetDevices() # Grab the first device. if len(devices) > 0: dev = devices[0] if dev: activate_connection(NM, connection_path, dev, connection_path) return connection_path
python
def ConnectionUpdate(self, settings): '''Update settings on a connection. settings is a String String Variant Map Map. See https://developer.gnome.org/NetworkManager/0.9/spec.html #type-String_String_Variant_Map_Map ''' connection_path = self.connection_path NM = dbusmock.get_object(MANAGER_OBJ) settings_obj = dbusmock.get_object(SETTINGS_OBJ) main_connections = settings_obj.ListConnections() if connection_path not in main_connections: raise dbus.exceptions.DBusException( 'Connection %s does not exist' % connection_path, name=MANAGER_IFACE + '.DoesNotExist',) # Take care not to overwrite the secrets for setting_name in settings: setting = settings[setting_name] for k in setting: if setting_name not in self.settings: self.settings[setting_name] = {} self.settings[setting_name][k] = setting[k] self.EmitSignal(CSETTINGS_IFACE, 'Updated', '', []) auto_connect = False if 'autoconnect' in settings['connection']: auto_connect = settings['connection']['autoconnect'] if auto_connect: dev = None devices = NM.GetDevices() # Grab the first device. if len(devices) > 0: dev = devices[0] if dev: activate_connection(NM, connection_path, dev, connection_path) return connection_path
[ "def", "ConnectionUpdate", "(", "self", ",", "settings", ")", ":", "connection_path", "=", "self", ".", "connection_path", "NM", "=", "dbusmock", ".", "get_object", "(", "MANAGER_OBJ", ")", "settings_obj", "=", "dbusmock", ".", "get_object", "(", "SETTINGS_OBJ",...
Update settings on a connection. settings is a String String Variant Map Map. See https://developer.gnome.org/NetworkManager/0.9/spec.html #type-String_String_Variant_Map_Map
[ "Update", "settings", "on", "a", "connection", "." ]
26f65f78bc0ed347233f699a8d6ee0e6880e7eb0
https://github.com/martinpitt/python-dbusmock/blob/26f65f78bc0ed347233f699a8d6ee0e6880e7eb0/dbusmock/templates/networkmanager.py#L779-L823
train
24,259
martinpitt/python-dbusmock
dbusmock/templates/networkmanager.py
ConnectionDelete
def ConnectionDelete(self): '''Deletes a connection. This also * removes the deleted connection from any device, * removes any active connection(s) it might be associated with, * removes it from the Settings interface, * as well as deletes the object from the mock. Note: If this was the only active connection, we change the global connection state. ''' connection_path = self.connection_path NM = dbusmock.get_object(MANAGER_OBJ) settings_obj = dbusmock.get_object(SETTINGS_OBJ) # Find the associated active connection(s). active_connections = NM.Get(MANAGER_IFACE, 'ActiveConnections') associated_active_connections = [] for ac in active_connections: ac_obj = dbusmock.get_object(ac) ac_con = ac_obj.Get(ACTIVE_CONNECTION_IFACE, 'Connection') if ac_con == connection_path: associated_active_connections.append(ac) # We found that the connection we are deleting are associated to all # active connections and subsequently set the global state to # disconnected. if len(active_connections) == len(associated_active_connections): self.SetGlobalConnectionState(NMState.NM_STATE_DISCONNECTED) # Remove the connection from all associated devices. # We also remove all associated active connections. for dev_path in NM.GetDevices(): dev_obj = dbusmock.get_object(dev_path) connections = dev_obj.Get(DEVICE_IFACE, 'AvailableConnections') for ac in associated_active_connections: NM.RemoveActiveConnection(dev_path, ac) if connection_path not in connections: continue connections.remove(dbus.ObjectPath(connection_path)) dev_obj.Set(DEVICE_IFACE, 'AvailableConnections', connections) # Remove the connection from the settings interface main_connections = settings_obj.ListConnections() if connection_path not in main_connections: return main_connections.remove(connection_path) settings_obj.Set(SETTINGS_IFACE, 'Connections', main_connections) settings_obj.EmitSignal(SETTINGS_IFACE, 'ConnectionRemoved', 'o', [connection_path]) # Remove the connection from the mock connection_obj = dbusmock.get_object(connection_path) connection_obj.EmitSignal(CSETTINGS_IFACE, 'Removed', '', []) self.object_manager_emit_removed(connection_path) self.RemoveObject(connection_path)
python
def ConnectionDelete(self): '''Deletes a connection. This also * removes the deleted connection from any device, * removes any active connection(s) it might be associated with, * removes it from the Settings interface, * as well as deletes the object from the mock. Note: If this was the only active connection, we change the global connection state. ''' connection_path = self.connection_path NM = dbusmock.get_object(MANAGER_OBJ) settings_obj = dbusmock.get_object(SETTINGS_OBJ) # Find the associated active connection(s). active_connections = NM.Get(MANAGER_IFACE, 'ActiveConnections') associated_active_connections = [] for ac in active_connections: ac_obj = dbusmock.get_object(ac) ac_con = ac_obj.Get(ACTIVE_CONNECTION_IFACE, 'Connection') if ac_con == connection_path: associated_active_connections.append(ac) # We found that the connection we are deleting are associated to all # active connections and subsequently set the global state to # disconnected. if len(active_connections) == len(associated_active_connections): self.SetGlobalConnectionState(NMState.NM_STATE_DISCONNECTED) # Remove the connection from all associated devices. # We also remove all associated active connections. for dev_path in NM.GetDevices(): dev_obj = dbusmock.get_object(dev_path) connections = dev_obj.Get(DEVICE_IFACE, 'AvailableConnections') for ac in associated_active_connections: NM.RemoveActiveConnection(dev_path, ac) if connection_path not in connections: continue connections.remove(dbus.ObjectPath(connection_path)) dev_obj.Set(DEVICE_IFACE, 'AvailableConnections', connections) # Remove the connection from the settings interface main_connections = settings_obj.ListConnections() if connection_path not in main_connections: return main_connections.remove(connection_path) settings_obj.Set(SETTINGS_IFACE, 'Connections', main_connections) settings_obj.EmitSignal(SETTINGS_IFACE, 'ConnectionRemoved', 'o', [connection_path]) # Remove the connection from the mock connection_obj = dbusmock.get_object(connection_path) connection_obj.EmitSignal(CSETTINGS_IFACE, 'Removed', '', []) self.object_manager_emit_removed(connection_path) self.RemoveObject(connection_path)
[ "def", "ConnectionDelete", "(", "self", ")", ":", "connection_path", "=", "self", ".", "connection_path", "NM", "=", "dbusmock", ".", "get_object", "(", "MANAGER_OBJ", ")", "settings_obj", "=", "dbusmock", ".", "get_object", "(", "SETTINGS_OBJ", ")", "# Find the...
Deletes a connection. This also * removes the deleted connection from any device, * removes any active connection(s) it might be associated with, * removes it from the Settings interface, * as well as deletes the object from the mock. Note: If this was the only active connection, we change the global connection state.
[ "Deletes", "a", "connection", "." ]
26f65f78bc0ed347233f699a8d6ee0e6880e7eb0
https://github.com/martinpitt/python-dbusmock/blob/26f65f78bc0ed347233f699a8d6ee0e6880e7eb0/dbusmock/templates/networkmanager.py#L853-L913
train
24,260
martinpitt/python-dbusmock
dbusmock/templates/upower.py
AddAC
def AddAC(self, device_name, model_name): '''Convenience method to add an AC object You have to specify a device name which must be a valid part of an object path, e. g. "mock_ac", and an arbitrary model name. Please note that this does not set any global properties such as "on-battery". Returns the new object path. ''' path = '/org/freedesktop/UPower/devices/' + device_name self.AddObject(path, DEVICE_IFACE, { 'PowerSupply': dbus.Boolean(True, variant_level=1), 'Model': dbus.String(model_name, variant_level=1), 'Online': dbus.Boolean(True, variant_level=1), }, []) self.EmitSignal(MAIN_IFACE, 'DeviceAdded', self.device_sig_type, [path]) return path
python
def AddAC(self, device_name, model_name): '''Convenience method to add an AC object You have to specify a device name which must be a valid part of an object path, e. g. "mock_ac", and an arbitrary model name. Please note that this does not set any global properties such as "on-battery". Returns the new object path. ''' path = '/org/freedesktop/UPower/devices/' + device_name self.AddObject(path, DEVICE_IFACE, { 'PowerSupply': dbus.Boolean(True, variant_level=1), 'Model': dbus.String(model_name, variant_level=1), 'Online': dbus.Boolean(True, variant_level=1), }, []) self.EmitSignal(MAIN_IFACE, 'DeviceAdded', self.device_sig_type, [path]) return path
[ "def", "AddAC", "(", "self", ",", "device_name", ",", "model_name", ")", ":", "path", "=", "'/org/freedesktop/UPower/devices/'", "+", "device_name", "self", ".", "AddObject", "(", "path", ",", "DEVICE_IFACE", ",", "{", "'PowerSupply'", ":", "dbus", ".", "Boole...
Convenience method to add an AC object You have to specify a device name which must be a valid part of an object path, e. g. "mock_ac", and an arbitrary model name. Please note that this does not set any global properties such as "on-battery". Returns the new object path.
[ "Convenience", "method", "to", "add", "an", "AC", "object" ]
26f65f78bc0ed347233f699a8d6ee0e6880e7eb0
https://github.com/martinpitt/python-dbusmock/blob/26f65f78bc0ed347233f699a8d6ee0e6880e7eb0/dbusmock/templates/upower.py#L101-L122
train
24,261
martinpitt/python-dbusmock
dbusmock/templates/upower.py
AddDischargingBattery
def AddDischargingBattery(self, device_name, model_name, percentage, seconds_to_empty): '''Convenience method to add a discharging battery object You have to specify a device name which must be a valid part of an object path, e. g. "mock_ac", an arbitrary model name, the charge percentage, and the seconds until the battery is empty. Please note that this does not set any global properties such as "on-battery". Returns the new object path. ''' path = '/org/freedesktop/UPower/devices/' + device_name self.AddObject(path, DEVICE_IFACE, { 'PowerSupply': dbus.Boolean(True, variant_level=1), 'IsPresent': dbus.Boolean(True, variant_level=1), 'Model': dbus.String(model_name, variant_level=1), 'Percentage': dbus.Double(percentage, variant_level=1), 'TimeToEmpty': dbus.Int64(seconds_to_empty, variant_level=1), 'EnergyFull': dbus.Double(100.0, variant_level=1), 'Energy': dbus.Double(percentage, variant_level=1), # UP_DEVICE_STATE_DISCHARGING 'State': dbus.UInt32(2, variant_level=1), # UP_DEVICE_KIND_BATTERY 'Type': dbus.UInt32(2, variant_level=1), }, []) self.EmitSignal(MAIN_IFACE, 'DeviceAdded', self.device_sig_type, [path]) return path
python
def AddDischargingBattery(self, device_name, model_name, percentage, seconds_to_empty): '''Convenience method to add a discharging battery object You have to specify a device name which must be a valid part of an object path, e. g. "mock_ac", an arbitrary model name, the charge percentage, and the seconds until the battery is empty. Please note that this does not set any global properties such as "on-battery". Returns the new object path. ''' path = '/org/freedesktop/UPower/devices/' + device_name self.AddObject(path, DEVICE_IFACE, { 'PowerSupply': dbus.Boolean(True, variant_level=1), 'IsPresent': dbus.Boolean(True, variant_level=1), 'Model': dbus.String(model_name, variant_level=1), 'Percentage': dbus.Double(percentage, variant_level=1), 'TimeToEmpty': dbus.Int64(seconds_to_empty, variant_level=1), 'EnergyFull': dbus.Double(100.0, variant_level=1), 'Energy': dbus.Double(percentage, variant_level=1), # UP_DEVICE_STATE_DISCHARGING 'State': dbus.UInt32(2, variant_level=1), # UP_DEVICE_KIND_BATTERY 'Type': dbus.UInt32(2, variant_level=1), }, []) self.EmitSignal(MAIN_IFACE, 'DeviceAdded', self.device_sig_type, [path]) return path
[ "def", "AddDischargingBattery", "(", "self", ",", "device_name", ",", "model_name", ",", "percentage", ",", "seconds_to_empty", ")", ":", "path", "=", "'/org/freedesktop/UPower/devices/'", "+", "device_name", "self", ".", "AddObject", "(", "path", ",", "DEVICE_IFACE...
Convenience method to add a discharging battery object You have to specify a device name which must be a valid part of an object path, e. g. "mock_ac", an arbitrary model name, the charge percentage, and the seconds until the battery is empty. Please note that this does not set any global properties such as "on-battery". Returns the new object path.
[ "Convenience", "method", "to", "add", "a", "discharging", "battery", "object" ]
26f65f78bc0ed347233f699a8d6ee0e6880e7eb0
https://github.com/martinpitt/python-dbusmock/blob/26f65f78bc0ed347233f699a8d6ee0e6880e7eb0/dbusmock/templates/upower.py#L127-L157
train
24,262
martinpitt/python-dbusmock
dbusmock/templates/upower.py
SetupDisplayDevice
def SetupDisplayDevice(self, type, state, percentage, energy, energy_full, energy_rate, time_to_empty, time_to_full, is_present, icon_name, warning_level): '''Convenience method to configure DisplayDevice properties This calls Set() for all properties that the DisplayDevice is defined to have, and is shorter if you have to completely set it up instead of changing just one or two properties. This is only available when mocking the 1.0 API. ''' if not self.api1: raise dbus.exceptions.DBusException( 'SetupDisplayDevice() can only be used with the 1.0 API', name=MOCK_IFACE + '.APIVersion') display_props = mockobject.objects[self.p_display_dev] display_props.Set(DEVICE_IFACE, 'Type', dbus.UInt32(type)) display_props.Set(DEVICE_IFACE, 'State', dbus.UInt32(state)) display_props.Set(DEVICE_IFACE, 'Percentage', percentage) display_props.Set(DEVICE_IFACE, 'Energy', energy) display_props.Set(DEVICE_IFACE, 'EnergyFull', energy_full) display_props.Set(DEVICE_IFACE, 'EnergyRate', energy_rate) display_props.Set(DEVICE_IFACE, 'TimeToEmpty', dbus.Int64(time_to_empty)) display_props.Set(DEVICE_IFACE, 'TimeToFull', dbus.Int64(time_to_full)) display_props.Set(DEVICE_IFACE, 'IsPresent', is_present) display_props.Set(DEVICE_IFACE, 'IconName', icon_name) display_props.Set(DEVICE_IFACE, 'WarningLevel', dbus.UInt32(warning_level))
python
def SetupDisplayDevice(self, type, state, percentage, energy, energy_full, energy_rate, time_to_empty, time_to_full, is_present, icon_name, warning_level): '''Convenience method to configure DisplayDevice properties This calls Set() for all properties that the DisplayDevice is defined to have, and is shorter if you have to completely set it up instead of changing just one or two properties. This is only available when mocking the 1.0 API. ''' if not self.api1: raise dbus.exceptions.DBusException( 'SetupDisplayDevice() can only be used with the 1.0 API', name=MOCK_IFACE + '.APIVersion') display_props = mockobject.objects[self.p_display_dev] display_props.Set(DEVICE_IFACE, 'Type', dbus.UInt32(type)) display_props.Set(DEVICE_IFACE, 'State', dbus.UInt32(state)) display_props.Set(DEVICE_IFACE, 'Percentage', percentage) display_props.Set(DEVICE_IFACE, 'Energy', energy) display_props.Set(DEVICE_IFACE, 'EnergyFull', energy_full) display_props.Set(DEVICE_IFACE, 'EnergyRate', energy_rate) display_props.Set(DEVICE_IFACE, 'TimeToEmpty', dbus.Int64(time_to_empty)) display_props.Set(DEVICE_IFACE, 'TimeToFull', dbus.Int64(time_to_full)) display_props.Set(DEVICE_IFACE, 'IsPresent', is_present) display_props.Set(DEVICE_IFACE, 'IconName', icon_name) display_props.Set(DEVICE_IFACE, 'WarningLevel', dbus.UInt32(warning_level))
[ "def", "SetupDisplayDevice", "(", "self", ",", "type", ",", "state", ",", "percentage", ",", "energy", ",", "energy_full", ",", "energy_rate", ",", "time_to_empty", ",", "time_to_full", ",", "is_present", ",", "icon_name", ",", "warning_level", ")", ":", "if",...
Convenience method to configure DisplayDevice properties This calls Set() for all properties that the DisplayDevice is defined to have, and is shorter if you have to completely set it up instead of changing just one or two properties. This is only available when mocking the 1.0 API.
[ "Convenience", "method", "to", "configure", "DisplayDevice", "properties" ]
26f65f78bc0ed347233f699a8d6ee0e6880e7eb0
https://github.com/martinpitt/python-dbusmock/blob/26f65f78bc0ed347233f699a8d6ee0e6880e7eb0/dbusmock/templates/upower.py#L197-L234
train
24,263
martinpitt/python-dbusmock
dbusmock/templates/upower.py
SetDeviceProperties
def SetDeviceProperties(self, object_path, properties): '''Convenience method to Set a device's properties. object_path: the device to update properties: dictionary of keys to dbus variants. If the 1.0 API is being mocked, changing this property will trigger the device's PropertiesChanged signal; otherwise, the older org.freedesktop.UPower DeviceChanged signal will be emitted. ''' device = dbusmock.get_object(object_path) # set the properties for key, value in properties.items(): device.Set(DEVICE_IFACE, key, value) # notify the listeners if not self.api1: self.EmitSignal(MAIN_IFACE, 'DeviceChanged', 's', [object_path])
python
def SetDeviceProperties(self, object_path, properties): '''Convenience method to Set a device's properties. object_path: the device to update properties: dictionary of keys to dbus variants. If the 1.0 API is being mocked, changing this property will trigger the device's PropertiesChanged signal; otherwise, the older org.freedesktop.UPower DeviceChanged signal will be emitted. ''' device = dbusmock.get_object(object_path) # set the properties for key, value in properties.items(): device.Set(DEVICE_IFACE, key, value) # notify the listeners if not self.api1: self.EmitSignal(MAIN_IFACE, 'DeviceChanged', 's', [object_path])
[ "def", "SetDeviceProperties", "(", "self", ",", "object_path", ",", "properties", ")", ":", "device", "=", "dbusmock", ".", "get_object", "(", "object_path", ")", "# set the properties", "for", "key", ",", "value", "in", "properties", ".", "items", "(", ")", ...
Convenience method to Set a device's properties. object_path: the device to update properties: dictionary of keys to dbus variants. If the 1.0 API is being mocked, changing this property will trigger the device's PropertiesChanged signal; otherwise, the older org.freedesktop.UPower DeviceChanged signal will be emitted.
[ "Convenience", "method", "to", "Set", "a", "device", "s", "properties", "." ]
26f65f78bc0ed347233f699a8d6ee0e6880e7eb0
https://github.com/martinpitt/python-dbusmock/blob/26f65f78bc0ed347233f699a8d6ee0e6880e7eb0/dbusmock/templates/upower.py#L238-L256
train
24,264
martinpitt/python-dbusmock
dbusmock/templates/logind.py
AddSeat
def AddSeat(self, seat): '''Convenience method to add a seat. Return the object path of the new seat. ''' seat_path = '/org/freedesktop/login1/seat/' + seat if seat_path in mockobject.objects: raise dbus.exceptions.DBusException('Seat %s already exists' % seat, name=MOCK_IFACE + '.SeatExists') self.AddObject(seat_path, 'org.freedesktop.login1.Seat', { 'Sessions': dbus.Array([], signature='(so)'), 'CanGraphical': False, 'CanMultiSession': True, 'CanTTY': False, 'IdleHint': False, 'ActiveSession': ('', dbus.ObjectPath('/')), 'Id': seat, 'IdleSinceHint': dbus.UInt64(0), 'IdleSinceHintMonotonic': dbus.UInt64(0), }, [ ('ActivateSession', 's', '', ''), ('Terminate', '', '', '') ]) return seat_path
python
def AddSeat(self, seat): '''Convenience method to add a seat. Return the object path of the new seat. ''' seat_path = '/org/freedesktop/login1/seat/' + seat if seat_path in mockobject.objects: raise dbus.exceptions.DBusException('Seat %s already exists' % seat, name=MOCK_IFACE + '.SeatExists') self.AddObject(seat_path, 'org.freedesktop.login1.Seat', { 'Sessions': dbus.Array([], signature='(so)'), 'CanGraphical': False, 'CanMultiSession': True, 'CanTTY': False, 'IdleHint': False, 'ActiveSession': ('', dbus.ObjectPath('/')), 'Id': seat, 'IdleSinceHint': dbus.UInt64(0), 'IdleSinceHintMonotonic': dbus.UInt64(0), }, [ ('ActivateSession', 's', '', ''), ('Terminate', '', '', '') ]) return seat_path
[ "def", "AddSeat", "(", "self", ",", "seat", ")", ":", "seat_path", "=", "'/org/freedesktop/login1/seat/'", "+", "seat", "if", "seat_path", "in", "mockobject", ".", "objects", ":", "raise", "dbus", ".", "exceptions", ".", "DBusException", "(", "'Seat %s already e...
Convenience method to add a seat. Return the object path of the new seat.
[ "Convenience", "method", "to", "add", "a", "seat", "." ]
26f65f78bc0ed347233f699a8d6ee0e6880e7eb0
https://github.com/martinpitt/python-dbusmock/blob/26f65f78bc0ed347233f699a8d6ee0e6880e7eb0/dbusmock/templates/logind.py#L117-L145
train
24,265
martinpitt/python-dbusmock
dbusmock/templates/logind.py
AddUser
def AddUser(self, uid, username, active): '''Convenience method to add a user. Return the object path of the new user. ''' user_path = '/org/freedesktop/login1/user/%i' % uid if user_path in mockobject.objects: raise dbus.exceptions.DBusException('User %i already exists' % uid, name=MOCK_IFACE + '.UserExists') self.AddObject(user_path, 'org.freedesktop.login1.User', { 'Sessions': dbus.Array([], signature='(so)'), 'IdleHint': False, 'DefaultControlGroup': 'systemd:/user/' + username, 'Name': username, 'RuntimePath': '/run/user/%i' % uid, 'Service': '', 'State': (active and 'active' or 'online'), 'Display': ('', dbus.ObjectPath('/')), 'UID': dbus.UInt32(uid), 'GID': dbus.UInt32(uid), 'IdleSinceHint': dbus.UInt64(0), 'IdleSinceHintMonotonic': dbus.UInt64(0), 'Timestamp': dbus.UInt64(42), 'TimestampMonotonic': dbus.UInt64(42), }, [ ('Kill', 's', '', ''), ('Terminate', '', '', ''), ]) return user_path
python
def AddUser(self, uid, username, active): '''Convenience method to add a user. Return the object path of the new user. ''' user_path = '/org/freedesktop/login1/user/%i' % uid if user_path in mockobject.objects: raise dbus.exceptions.DBusException('User %i already exists' % uid, name=MOCK_IFACE + '.UserExists') self.AddObject(user_path, 'org.freedesktop.login1.User', { 'Sessions': dbus.Array([], signature='(so)'), 'IdleHint': False, 'DefaultControlGroup': 'systemd:/user/' + username, 'Name': username, 'RuntimePath': '/run/user/%i' % uid, 'Service': '', 'State': (active and 'active' or 'online'), 'Display': ('', dbus.ObjectPath('/')), 'UID': dbus.UInt32(uid), 'GID': dbus.UInt32(uid), 'IdleSinceHint': dbus.UInt64(0), 'IdleSinceHintMonotonic': dbus.UInt64(0), 'Timestamp': dbus.UInt64(42), 'TimestampMonotonic': dbus.UInt64(42), }, [ ('Kill', 's', '', ''), ('Terminate', '', '', ''), ]) return user_path
[ "def", "AddUser", "(", "self", ",", "uid", ",", "username", ",", "active", ")", ":", "user_path", "=", "'/org/freedesktop/login1/user/%i'", "%", "uid", "if", "user_path", "in", "mockobject", ".", "objects", ":", "raise", "dbus", ".", "exceptions", ".", "DBus...
Convenience method to add a user. Return the object path of the new user.
[ "Convenience", "method", "to", "add", "a", "user", "." ]
26f65f78bc0ed347233f699a8d6ee0e6880e7eb0
https://github.com/martinpitt/python-dbusmock/blob/26f65f78bc0ed347233f699a8d6ee0e6880e7eb0/dbusmock/templates/logind.py#L150-L183
train
24,266
martinpitt/python-dbusmock
dbusmock/templates/logind.py
AddSession
def AddSession(self, session_id, seat, uid, username, active): '''Convenience method to add a session. If the given seat and/or user do not exit, they will be created. Return the object path of the new session. ''' seat_path = dbus.ObjectPath('/org/freedesktop/login1/seat/' + seat) if seat_path not in mockobject.objects: self.AddSeat(seat) user_path = dbus.ObjectPath('/org/freedesktop/login1/user/%i' % uid) if user_path not in mockobject.objects: self.AddUser(uid, username, active) session_path = dbus.ObjectPath('/org/freedesktop/login1/session/' + session_id) if session_path in mockobject.objects: raise dbus.exceptions.DBusException('Session %s already exists' % session_id, name=MOCK_IFACE + '.SessionExists') self.AddObject(session_path, 'org.freedesktop.login1.Session', { 'Controllers': dbus.Array([], signature='s'), 'ResetControllers': dbus.Array([], signature='s'), 'Active': active, 'IdleHint': False, 'KillProcesses': False, 'Remote': False, 'Class': 'user', 'DefaultControlGroup': 'systemd:/user/%s/%s' % (username, session_id), 'Display': os.getenv('DISPLAY', ''), 'Id': session_id, 'Name': username, 'RemoteHost': '', 'RemoteUser': '', 'Service': 'dbusmock', 'State': (active and 'active' or 'online'), 'TTY': '', 'Type': 'test', 'Seat': (seat, seat_path), 'User': (dbus.UInt32(uid), user_path), 'Audit': dbus.UInt32(0), 'Leader': dbus.UInt32(1), 'VTNr': dbus.UInt32(1), 'IdleSinceHint': dbus.UInt64(0), 'IdleSinceHintMonotonic': dbus.UInt64(0), 'Timestamp': dbus.UInt64(42), 'TimestampMonotonic': dbus.UInt64(42), }, [ ('Activate', '', '', ''), ('Kill', 'ss', '', ''), ('Lock', '', '', ''), ('SetIdleHint', 'b', '', ''), ('Terminate', '', '', ''), ('Unlock', '', '', ''), ]) # add session to seat obj_seat = mockobject.objects[seat_path] cur_sessions = obj_seat.Get('org.freedesktop.login1.Seat', 'Sessions') cur_sessions.append((session_id, session_path)) obj_seat.Set('org.freedesktop.login1.Seat', 'Sessions', cur_sessions) obj_seat.Set('org.freedesktop.login1.Seat', 'ActiveSession', (session_id, session_path)) # add session to user obj_user = mockobject.objects[user_path] cur_sessions = obj_user.Get('org.freedesktop.login1.User', 'Sessions') cur_sessions.append((session_id, session_path)) obj_user.Set('org.freedesktop.login1.User', 'Sessions', cur_sessions) return session_path
python
def AddSession(self, session_id, seat, uid, username, active): '''Convenience method to add a session. If the given seat and/or user do not exit, they will be created. Return the object path of the new session. ''' seat_path = dbus.ObjectPath('/org/freedesktop/login1/seat/' + seat) if seat_path not in mockobject.objects: self.AddSeat(seat) user_path = dbus.ObjectPath('/org/freedesktop/login1/user/%i' % uid) if user_path not in mockobject.objects: self.AddUser(uid, username, active) session_path = dbus.ObjectPath('/org/freedesktop/login1/session/' + session_id) if session_path in mockobject.objects: raise dbus.exceptions.DBusException('Session %s already exists' % session_id, name=MOCK_IFACE + '.SessionExists') self.AddObject(session_path, 'org.freedesktop.login1.Session', { 'Controllers': dbus.Array([], signature='s'), 'ResetControllers': dbus.Array([], signature='s'), 'Active': active, 'IdleHint': False, 'KillProcesses': False, 'Remote': False, 'Class': 'user', 'DefaultControlGroup': 'systemd:/user/%s/%s' % (username, session_id), 'Display': os.getenv('DISPLAY', ''), 'Id': session_id, 'Name': username, 'RemoteHost': '', 'RemoteUser': '', 'Service': 'dbusmock', 'State': (active and 'active' or 'online'), 'TTY': '', 'Type': 'test', 'Seat': (seat, seat_path), 'User': (dbus.UInt32(uid), user_path), 'Audit': dbus.UInt32(0), 'Leader': dbus.UInt32(1), 'VTNr': dbus.UInt32(1), 'IdleSinceHint': dbus.UInt64(0), 'IdleSinceHintMonotonic': dbus.UInt64(0), 'Timestamp': dbus.UInt64(42), 'TimestampMonotonic': dbus.UInt64(42), }, [ ('Activate', '', '', ''), ('Kill', 'ss', '', ''), ('Lock', '', '', ''), ('SetIdleHint', 'b', '', ''), ('Terminate', '', '', ''), ('Unlock', '', '', ''), ]) # add session to seat obj_seat = mockobject.objects[seat_path] cur_sessions = obj_seat.Get('org.freedesktop.login1.Seat', 'Sessions') cur_sessions.append((session_id, session_path)) obj_seat.Set('org.freedesktop.login1.Seat', 'Sessions', cur_sessions) obj_seat.Set('org.freedesktop.login1.Seat', 'ActiveSession', (session_id, session_path)) # add session to user obj_user = mockobject.objects[user_path] cur_sessions = obj_user.Get('org.freedesktop.login1.User', 'Sessions') cur_sessions.append((session_id, session_path)) obj_user.Set('org.freedesktop.login1.User', 'Sessions', cur_sessions) return session_path
[ "def", "AddSession", "(", "self", ",", "session_id", ",", "seat", ",", "uid", ",", "username", ",", "active", ")", ":", "seat_path", "=", "dbus", ".", "ObjectPath", "(", "'/org/freedesktop/login1/seat/'", "+", "seat", ")", "if", "seat_path", "not", "in", "...
Convenience method to add a session. If the given seat and/or user do not exit, they will be created. Return the object path of the new session.
[ "Convenience", "method", "to", "add", "a", "session", "." ]
26f65f78bc0ed347233f699a8d6ee0e6880e7eb0
https://github.com/martinpitt/python-dbusmock/blob/26f65f78bc0ed347233f699a8d6ee0e6880e7eb0/dbusmock/templates/logind.py#L188-L260
train
24,267
martinpitt/python-dbusmock
dbusmock/mockobject.py
DBusMockObject._set_up_object_manager
def _set_up_object_manager(self): '''Set up this mock object as a D-Bus ObjectManager.''' if self.path == '/': cond = 'k != \'/\'' else: cond = 'k.startswith(\'%s/\')' % self.path self.AddMethod(OBJECT_MANAGER_IFACE, 'GetManagedObjects', '', 'a{oa{sa{sv}}}', 'ret = {dbus.ObjectPath(k): objects[k].props ' + ' for k in objects.keys() if ' + cond + '}') self.object_manager = self
python
def _set_up_object_manager(self): '''Set up this mock object as a D-Bus ObjectManager.''' if self.path == '/': cond = 'k != \'/\'' else: cond = 'k.startswith(\'%s/\')' % self.path self.AddMethod(OBJECT_MANAGER_IFACE, 'GetManagedObjects', '', 'a{oa{sa{sv}}}', 'ret = {dbus.ObjectPath(k): objects[k].props ' + ' for k in objects.keys() if ' + cond + '}') self.object_manager = self
[ "def", "_set_up_object_manager", "(", "self", ")", ":", "if", "self", ".", "path", "==", "'/'", ":", "cond", "=", "'k != \\'/\\''", "else", ":", "cond", "=", "'k.startswith(\\'%s/\\')'", "%", "self", ".", "path", "self", ".", "AddMethod", "(", "OBJECT_MANAGE...
Set up this mock object as a D-Bus ObjectManager.
[ "Set", "up", "this", "mock", "object", "as", "a", "D", "-", "Bus", "ObjectManager", "." ]
26f65f78bc0ed347233f699a8d6ee0e6880e7eb0
https://github.com/martinpitt/python-dbusmock/blob/26f65f78bc0ed347233f699a8d6ee0e6880e7eb0/dbusmock/mockobject.py#L108-L119
train
24,268
martinpitt/python-dbusmock
dbusmock/mockobject.py
DBusMockObject.Get
def Get(self, interface_name, property_name): '''Standard D-Bus API for getting a property value''' self.log('Get %s.%s' % (interface_name, property_name)) if not interface_name: interface_name = self.interface try: return self.GetAll(interface_name)[property_name] except KeyError: raise dbus.exceptions.DBusException( 'no such property ' + property_name, name=self.interface + '.UnknownProperty')
python
def Get(self, interface_name, property_name): '''Standard D-Bus API for getting a property value''' self.log('Get %s.%s' % (interface_name, property_name)) if not interface_name: interface_name = self.interface try: return self.GetAll(interface_name)[property_name] except KeyError: raise dbus.exceptions.DBusException( 'no such property ' + property_name, name=self.interface + '.UnknownProperty')
[ "def", "Get", "(", "self", ",", "interface_name", ",", "property_name", ")", ":", "self", ".", "log", "(", "'Get %s.%s'", "%", "(", "interface_name", ",", "property_name", ")", ")", "if", "not", "interface_name", ":", "interface_name", "=", "self", ".", "i...
Standard D-Bus API for getting a property value
[ "Standard", "D", "-", "Bus", "API", "for", "getting", "a", "property", "value" ]
26f65f78bc0ed347233f699a8d6ee0e6880e7eb0
https://github.com/martinpitt/python-dbusmock/blob/26f65f78bc0ed347233f699a8d6ee0e6880e7eb0/dbusmock/mockobject.py#L133-L145
train
24,269
martinpitt/python-dbusmock
dbusmock/mockobject.py
DBusMockObject.GetAll
def GetAll(self, interface_name, *args, **kwargs): '''Standard D-Bus API for getting all property values''' self.log('GetAll ' + interface_name) if not interface_name: interface_name = self.interface try: return self.props[interface_name] except KeyError: raise dbus.exceptions.DBusException( 'no such interface ' + interface_name, name=self.interface + '.UnknownInterface')
python
def GetAll(self, interface_name, *args, **kwargs): '''Standard D-Bus API for getting all property values''' self.log('GetAll ' + interface_name) if not interface_name: interface_name = self.interface try: return self.props[interface_name] except KeyError: raise dbus.exceptions.DBusException( 'no such interface ' + interface_name, name=self.interface + '.UnknownInterface')
[ "def", "GetAll", "(", "self", ",", "interface_name", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "self", ".", "log", "(", "'GetAll '", "+", "interface_name", ")", "if", "not", "interface_name", ":", "interface_name", "=", "self", ".", "interface...
Standard D-Bus API for getting all property values
[ "Standard", "D", "-", "Bus", "API", "for", "getting", "all", "property", "values" ]
26f65f78bc0ed347233f699a8d6ee0e6880e7eb0
https://github.com/martinpitt/python-dbusmock/blob/26f65f78bc0ed347233f699a8d6ee0e6880e7eb0/dbusmock/mockobject.py#L149-L161
train
24,270
martinpitt/python-dbusmock
dbusmock/mockobject.py
DBusMockObject.Set
def Set(self, interface_name, property_name, value, *args, **kwargs): '''Standard D-Bus API for setting a property value''' self.log('Set %s.%s%s' % (interface_name, property_name, self.format_args((value,)))) try: iface_props = self.props[interface_name] except KeyError: raise dbus.exceptions.DBusException( 'no such interface ' + interface_name, name=self.interface + '.UnknownInterface') if property_name not in iface_props: raise dbus.exceptions.DBusException( 'no such property ' + property_name, name=self.interface + '.UnknownProperty') iface_props[property_name] = value self.EmitSignal('org.freedesktop.DBus.Properties', 'PropertiesChanged', 'sa{sv}as', [interface_name, dbus.Dictionary({property_name: value}, signature='sv'), dbus.Array([], signature='s') ])
python
def Set(self, interface_name, property_name, value, *args, **kwargs): '''Standard D-Bus API for setting a property value''' self.log('Set %s.%s%s' % (interface_name, property_name, self.format_args((value,)))) try: iface_props = self.props[interface_name] except KeyError: raise dbus.exceptions.DBusException( 'no such interface ' + interface_name, name=self.interface + '.UnknownInterface') if property_name not in iface_props: raise dbus.exceptions.DBusException( 'no such property ' + property_name, name=self.interface + '.UnknownProperty') iface_props[property_name] = value self.EmitSignal('org.freedesktop.DBus.Properties', 'PropertiesChanged', 'sa{sv}as', [interface_name, dbus.Dictionary({property_name: value}, signature='sv'), dbus.Array([], signature='s') ])
[ "def", "Set", "(", "self", ",", "interface_name", ",", "property_name", ",", "value", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "self", ".", "log", "(", "'Set %s.%s%s'", "%", "(", "interface_name", ",", "property_name", ",", "self", ".", "fo...
Standard D-Bus API for setting a property value
[ "Standard", "D", "-", "Bus", "API", "for", "setting", "a", "property", "value" ]
26f65f78bc0ed347233f699a8d6ee0e6880e7eb0
https://github.com/martinpitt/python-dbusmock/blob/26f65f78bc0ed347233f699a8d6ee0e6880e7eb0/dbusmock/mockobject.py#L165-L192
train
24,271
martinpitt/python-dbusmock
dbusmock/mockobject.py
DBusMockObject.AddObject
def AddObject(self, path, interface, properties, methods): '''Add a new D-Bus object to the mock path: D-Bus object path interface: Primary D-Bus interface name of this object (where properties and methods will be put on) properties: A property_name (string) → value map with initial properties on "interface" methods: An array of 4-tuples (name, in_sig, out_sig, code) describing methods to add to "interface"; see AddMethod() for details of the tuple values If this is a D-Bus ObjectManager instance, the InterfacesAdded signal will *not* be emitted for the object automatically; it must be emitted manually if desired. This is because AddInterface may be called after AddObject, but before the InterfacesAdded signal should be emitted. Example: dbus_proxy.AddObject('/com/example/Foo/Manager', 'com.example.Foo.Control', { 'state': dbus.String('online', variant_level=1), }, [ ('Start', '', '', ''), ('EchoInt', 'i', 'i', 'ret = args[0]'), ('GetClients', '', 'ao', 'ret = ["/com/example/Foo/Client1"]'), ]) ''' if path in objects: raise dbus.exceptions.DBusException( 'object %s already exists' % path, name='org.freedesktop.DBus.Mock.NameError') obj = DBusMockObject(self.bus_name, path, interface, properties) # make sure created objects inherit the log file stream obj.logfile = self.logfile obj.object_manager = self.object_manager obj.is_logfile_owner = False obj.AddMethods(interface, methods) objects[path] = obj
python
def AddObject(self, path, interface, properties, methods): '''Add a new D-Bus object to the mock path: D-Bus object path interface: Primary D-Bus interface name of this object (where properties and methods will be put on) properties: A property_name (string) → value map with initial properties on "interface" methods: An array of 4-tuples (name, in_sig, out_sig, code) describing methods to add to "interface"; see AddMethod() for details of the tuple values If this is a D-Bus ObjectManager instance, the InterfacesAdded signal will *not* be emitted for the object automatically; it must be emitted manually if desired. This is because AddInterface may be called after AddObject, but before the InterfacesAdded signal should be emitted. Example: dbus_proxy.AddObject('/com/example/Foo/Manager', 'com.example.Foo.Control', { 'state': dbus.String('online', variant_level=1), }, [ ('Start', '', '', ''), ('EchoInt', 'i', 'i', 'ret = args[0]'), ('GetClients', '', 'ao', 'ret = ["/com/example/Foo/Client1"]'), ]) ''' if path in objects: raise dbus.exceptions.DBusException( 'object %s already exists' % path, name='org.freedesktop.DBus.Mock.NameError') obj = DBusMockObject(self.bus_name, path, interface, properties) # make sure created objects inherit the log file stream obj.logfile = self.logfile obj.object_manager = self.object_manager obj.is_logfile_owner = False obj.AddMethods(interface, methods) objects[path] = obj
[ "def", "AddObject", "(", "self", ",", "path", ",", "interface", ",", "properties", ",", "methods", ")", ":", "if", "path", "in", "objects", ":", "raise", "dbus", ".", "exceptions", ".", "DBusException", "(", "'object %s already exists'", "%", "path", ",", ...
Add a new D-Bus object to the mock path: D-Bus object path interface: Primary D-Bus interface name of this object (where properties and methods will be put on) properties: A property_name (string) → value map with initial properties on "interface" methods: An array of 4-tuples (name, in_sig, out_sig, code) describing methods to add to "interface"; see AddMethod() for details of the tuple values If this is a D-Bus ObjectManager instance, the InterfacesAdded signal will *not* be emitted for the object automatically; it must be emitted manually if desired. This is because AddInterface may be called after AddObject, but before the InterfacesAdded signal should be emitted. Example: dbus_proxy.AddObject('/com/example/Foo/Manager', 'com.example.Foo.Control', { 'state': dbus.String('online', variant_level=1), }, [ ('Start', '', '', ''), ('EchoInt', 'i', 'i', 'ret = args[0]'), ('GetClients', '', 'ao', 'ret = ["/com/example/Foo/Client1"]'), ])
[ "Add", "a", "new", "D", "-", "Bus", "object", "to", "the", "mock" ]
26f65f78bc0ed347233f699a8d6ee0e6880e7eb0
https://github.com/martinpitt/python-dbusmock/blob/26f65f78bc0ed347233f699a8d6ee0e6880e7eb0/dbusmock/mockobject.py#L197-L241
train
24,272
martinpitt/python-dbusmock
dbusmock/mockobject.py
DBusMockObject.RemoveObject
def RemoveObject(self, path): '''Remove a D-Bus object from the mock As with AddObject, this will *not* emit the InterfacesRemoved signal if it’s an ObjectManager instance. ''' try: objects[path].remove_from_connection() del objects[path] except KeyError: raise dbus.exceptions.DBusException( 'object %s does not exist' % path, name='org.freedesktop.DBus.Mock.NameError')
python
def RemoveObject(self, path): '''Remove a D-Bus object from the mock As with AddObject, this will *not* emit the InterfacesRemoved signal if it’s an ObjectManager instance. ''' try: objects[path].remove_from_connection() del objects[path] except KeyError: raise dbus.exceptions.DBusException( 'object %s does not exist' % path, name='org.freedesktop.DBus.Mock.NameError')
[ "def", "RemoveObject", "(", "self", ",", "path", ")", ":", "try", ":", "objects", "[", "path", "]", ".", "remove_from_connection", "(", ")", "del", "objects", "[", "path", "]", "except", "KeyError", ":", "raise", "dbus", ".", "exceptions", ".", "DBusExce...
Remove a D-Bus object from the mock As with AddObject, this will *not* emit the InterfacesRemoved signal if it’s an ObjectManager instance.
[ "Remove", "a", "D", "-", "Bus", "object", "from", "the", "mock" ]
26f65f78bc0ed347233f699a8d6ee0e6880e7eb0
https://github.com/martinpitt/python-dbusmock/blob/26f65f78bc0ed347233f699a8d6ee0e6880e7eb0/dbusmock/mockobject.py#L246-L258
train
24,273
martinpitt/python-dbusmock
dbusmock/mockobject.py
DBusMockObject.Reset
def Reset(self): '''Reset the mock object state. Remove all mock objects from the bus and tidy up so the state is as if python-dbusmock had just been restarted. If the mock object was originally created with a template (from the command line, the Python API or by calling AddTemplate over D-Bus), it will be re-instantiated with that template. ''' # Clear other existing objects. for obj_name, obj in objects.items(): if obj_name != self.path: obj.remove_from_connection() objects.clear() # Reinitialise our state. Carefully remove new methods from our dict; # they don't not actually exist if they are a statically defined # template function for method_name in self.methods[self.interface]: try: delattr(self.__class__, method_name) except AttributeError: pass self._reset({}) if self._template is not None: self.AddTemplate(self._template, self._template_parameters) objects[self.path] = self
python
def Reset(self): '''Reset the mock object state. Remove all mock objects from the bus and tidy up so the state is as if python-dbusmock had just been restarted. If the mock object was originally created with a template (from the command line, the Python API or by calling AddTemplate over D-Bus), it will be re-instantiated with that template. ''' # Clear other existing objects. for obj_name, obj in objects.items(): if obj_name != self.path: obj.remove_from_connection() objects.clear() # Reinitialise our state. Carefully remove new methods from our dict; # they don't not actually exist if they are a statically defined # template function for method_name in self.methods[self.interface]: try: delattr(self.__class__, method_name) except AttributeError: pass self._reset({}) if self._template is not None: self.AddTemplate(self._template, self._template_parameters) objects[self.path] = self
[ "def", "Reset", "(", "self", ")", ":", "# Clear other existing objects.", "for", "obj_name", ",", "obj", "in", "objects", ".", "items", "(", ")", ":", "if", "obj_name", "!=", "self", ".", "path", ":", "obj", ".", "remove_from_connection", "(", ")", "object...
Reset the mock object state. Remove all mock objects from the bus and tidy up so the state is as if python-dbusmock had just been restarted. If the mock object was originally created with a template (from the command line, the Python API or by calling AddTemplate over D-Bus), it will be re-instantiated with that template.
[ "Reset", "the", "mock", "object", "state", "." ]
26f65f78bc0ed347233f699a8d6ee0e6880e7eb0
https://github.com/martinpitt/python-dbusmock/blob/26f65f78bc0ed347233f699a8d6ee0e6880e7eb0/dbusmock/mockobject.py#L262-L291
train
24,274
martinpitt/python-dbusmock
dbusmock/mockobject.py
DBusMockObject.AddMethod
def AddMethod(self, interface, name, in_sig, out_sig, code): '''Add a method to this object interface: D-Bus interface to add this to. For convenience you can specify '' here to add the method to the object's main interface (as specified on construction). name: Name of the method in_sig: Signature of input arguments; for example "ias" for a method that takes an int32 and a string array as arguments; see http://dbus.freedesktop.org/doc/dbus-specification.html#message-protocol-signatures out_sig: Signature of output arguments; for example "s" for a method that returns a string; use '' for methods that do not return anything. code: Python 3 code to run in the method call; you have access to the arguments through the "args" list, and can set the return value by assigning a value to the "ret" variable. You can also read the global "objects" variable, which is a dictionary mapping object paths to DBusMockObject instances. For keeping state across method calls, you are free to use normal Python members of the "self" object, which will be persistent for the whole mock's life time. E. g. you can have a method with "self.my_state = True", and another method that returns it with "ret = self.my_state". When specifying '', the method will not do anything (except logging) and return None. ''' if not interface: interface = self.interface n_args = len(dbus.Signature(in_sig)) # we need to have separate methods for dbus-python, so clone # mock_method(); using message_keyword with this dynamic approach fails # because inspect cannot handle those, so pass on interface and method # name as first positional arguments method = lambda self, *args, **kwargs: DBusMockObject.mock_method( self, interface, name, in_sig, *args, **kwargs) # we cannot specify in_signature here, as that trips over a consistency # check in dbus-python; we need to set it manually instead dbus_method = dbus.service.method(interface, out_signature=out_sig)(method) dbus_method.__name__ = str(name) dbus_method._dbus_in_signature = in_sig dbus_method._dbus_args = ['arg%i' % i for i in range(1, n_args + 1)] # for convenience, add mocked methods on the primary interface as # callable methods if interface == self.interface: setattr(self.__class__, name, dbus_method) self.methods.setdefault(interface, {})[str(name)] = (in_sig, out_sig, code, dbus_method)
python
def AddMethod(self, interface, name, in_sig, out_sig, code): '''Add a method to this object interface: D-Bus interface to add this to. For convenience you can specify '' here to add the method to the object's main interface (as specified on construction). name: Name of the method in_sig: Signature of input arguments; for example "ias" for a method that takes an int32 and a string array as arguments; see http://dbus.freedesktop.org/doc/dbus-specification.html#message-protocol-signatures out_sig: Signature of output arguments; for example "s" for a method that returns a string; use '' for methods that do not return anything. code: Python 3 code to run in the method call; you have access to the arguments through the "args" list, and can set the return value by assigning a value to the "ret" variable. You can also read the global "objects" variable, which is a dictionary mapping object paths to DBusMockObject instances. For keeping state across method calls, you are free to use normal Python members of the "self" object, which will be persistent for the whole mock's life time. E. g. you can have a method with "self.my_state = True", and another method that returns it with "ret = self.my_state". When specifying '', the method will not do anything (except logging) and return None. ''' if not interface: interface = self.interface n_args = len(dbus.Signature(in_sig)) # we need to have separate methods for dbus-python, so clone # mock_method(); using message_keyword with this dynamic approach fails # because inspect cannot handle those, so pass on interface and method # name as first positional arguments method = lambda self, *args, **kwargs: DBusMockObject.mock_method( self, interface, name, in_sig, *args, **kwargs) # we cannot specify in_signature here, as that trips over a consistency # check in dbus-python; we need to set it manually instead dbus_method = dbus.service.method(interface, out_signature=out_sig)(method) dbus_method.__name__ = str(name) dbus_method._dbus_in_signature = in_sig dbus_method._dbus_args = ['arg%i' % i for i in range(1, n_args + 1)] # for convenience, add mocked methods on the primary interface as # callable methods if interface == self.interface: setattr(self.__class__, name, dbus_method) self.methods.setdefault(interface, {})[str(name)] = (in_sig, out_sig, code, dbus_method)
[ "def", "AddMethod", "(", "self", ",", "interface", ",", "name", ",", "in_sig", ",", "out_sig", ",", "code", ")", ":", "if", "not", "interface", ":", "interface", "=", "self", ".", "interface", "n_args", "=", "len", "(", "dbus", ".", "Signature", "(", ...
Add a method to this object interface: D-Bus interface to add this to. For convenience you can specify '' here to add the method to the object's main interface (as specified on construction). name: Name of the method in_sig: Signature of input arguments; for example "ias" for a method that takes an int32 and a string array as arguments; see http://dbus.freedesktop.org/doc/dbus-specification.html#message-protocol-signatures out_sig: Signature of output arguments; for example "s" for a method that returns a string; use '' for methods that do not return anything. code: Python 3 code to run in the method call; you have access to the arguments through the "args" list, and can set the return value by assigning a value to the "ret" variable. You can also read the global "objects" variable, which is a dictionary mapping object paths to DBusMockObject instances. For keeping state across method calls, you are free to use normal Python members of the "self" object, which will be persistent for the whole mock's life time. E. g. you can have a method with "self.my_state = True", and another method that returns it with "ret = self.my_state". When specifying '', the method will not do anything (except logging) and return None.
[ "Add", "a", "method", "to", "this", "object" ]
26f65f78bc0ed347233f699a8d6ee0e6880e7eb0
https://github.com/martinpitt/python-dbusmock/blob/26f65f78bc0ed347233f699a8d6ee0e6880e7eb0/dbusmock/mockobject.py#L296-L348
train
24,275
martinpitt/python-dbusmock
dbusmock/mockobject.py
DBusMockObject.AddMethods
def AddMethods(self, interface, methods): '''Add several methods to this object interface: D-Bus interface to add this to. For convenience you can specify '' here to add the method to the object's main interface (as specified on construction). methods: list of 4-tuples (name, in_sig, out_sig, code) describing one method each. See AddMethod() for details of the tuple values. ''' for method in methods: self.AddMethod(interface, *method)
python
def AddMethods(self, interface, methods): '''Add several methods to this object interface: D-Bus interface to add this to. For convenience you can specify '' here to add the method to the object's main interface (as specified on construction). methods: list of 4-tuples (name, in_sig, out_sig, code) describing one method each. See AddMethod() for details of the tuple values. ''' for method in methods: self.AddMethod(interface, *method)
[ "def", "AddMethods", "(", "self", ",", "interface", ",", "methods", ")", ":", "for", "method", "in", "methods", ":", "self", ".", "AddMethod", "(", "interface", ",", "*", "method", ")" ]
Add several methods to this object interface: D-Bus interface to add this to. For convenience you can specify '' here to add the method to the object's main interface (as specified on construction). methods: list of 4-tuples (name, in_sig, out_sig, code) describing one method each. See AddMethod() for details of the tuple values.
[ "Add", "several", "methods", "to", "this", "object" ]
26f65f78bc0ed347233f699a8d6ee0e6880e7eb0
https://github.com/martinpitt/python-dbusmock/blob/26f65f78bc0ed347233f699a8d6ee0e6880e7eb0/dbusmock/mockobject.py#L353-L363
train
24,276
martinpitt/python-dbusmock
dbusmock/mockobject.py
DBusMockObject.AddProperty
def AddProperty(self, interface, name, value): '''Add property to this object interface: D-Bus interface to add this to. For convenience you can specify '' here to add the property to the object's main interface (as specified on construction). name: Property name. value: Property value. ''' if not interface: interface = self.interface try: self.props[interface][name] raise dbus.exceptions.DBusException( 'property %s already exists' % name, name=self.interface + '.PropertyExists') except KeyError: # this is what we expect pass # copy.copy removes one level of variant-ness, which means that the # types get exported in introspection data correctly, but we can't do # this for container types. if not (isinstance(value, dbus.Dictionary) or isinstance(value, dbus.Array)): value = copy.copy(value) self.props.setdefault(interface, {})[name] = value
python
def AddProperty(self, interface, name, value): '''Add property to this object interface: D-Bus interface to add this to. For convenience you can specify '' here to add the property to the object's main interface (as specified on construction). name: Property name. value: Property value. ''' if not interface: interface = self.interface try: self.props[interface][name] raise dbus.exceptions.DBusException( 'property %s already exists' % name, name=self.interface + '.PropertyExists') except KeyError: # this is what we expect pass # copy.copy removes one level of variant-ness, which means that the # types get exported in introspection data correctly, but we can't do # this for container types. if not (isinstance(value, dbus.Dictionary) or isinstance(value, dbus.Array)): value = copy.copy(value) self.props.setdefault(interface, {})[name] = value
[ "def", "AddProperty", "(", "self", ",", "interface", ",", "name", ",", "value", ")", ":", "if", "not", "interface", ":", "interface", "=", "self", ".", "interface", "try", ":", "self", ".", "props", "[", "interface", "]", "[", "name", "]", "raise", "...
Add property to this object interface: D-Bus interface to add this to. For convenience you can specify '' here to add the property to the object's main interface (as specified on construction). name: Property name. value: Property value.
[ "Add", "property", "to", "this", "object" ]
26f65f78bc0ed347233f699a8d6ee0e6880e7eb0
https://github.com/martinpitt/python-dbusmock/blob/26f65f78bc0ed347233f699a8d6ee0e6880e7eb0/dbusmock/mockobject.py#L368-L394
train
24,277
martinpitt/python-dbusmock
dbusmock/mockobject.py
DBusMockObject.AddProperties
def AddProperties(self, interface, properties): '''Add several properties to this object interface: D-Bus interface to add this to. For convenience you can specify '' here to add the property to the object's main interface (as specified on construction). properties: A property_name (string) → value map ''' for k, v in properties.items(): self.AddProperty(interface, k, v)
python
def AddProperties(self, interface, properties): '''Add several properties to this object interface: D-Bus interface to add this to. For convenience you can specify '' here to add the property to the object's main interface (as specified on construction). properties: A property_name (string) → value map ''' for k, v in properties.items(): self.AddProperty(interface, k, v)
[ "def", "AddProperties", "(", "self", ",", "interface", ",", "properties", ")", ":", "for", "k", ",", "v", "in", "properties", ".", "items", "(", ")", ":", "self", ".", "AddProperty", "(", "interface", ",", "k", ",", "v", ")" ]
Add several properties to this object interface: D-Bus interface to add this to. For convenience you can specify '' here to add the property to the object's main interface (as specified on construction). properties: A property_name (string) → value map
[ "Add", "several", "properties", "to", "this", "object" ]
26f65f78bc0ed347233f699a8d6ee0e6880e7eb0
https://github.com/martinpitt/python-dbusmock/blob/26f65f78bc0ed347233f699a8d6ee0e6880e7eb0/dbusmock/mockobject.py#L399-L408
train
24,278
martinpitt/python-dbusmock
dbusmock/mockobject.py
DBusMockObject.AddTemplate
def AddTemplate(self, template, parameters): '''Load a template into the mock. python-dbusmock ships a set of standard mocks for common system services such as UPower and NetworkManager. With these the actual tests become a lot simpler, as they only have to set up the particular properties for the tests, and not the skeleton of common properties, interfaces, and methods. template: Name of the template to load or the full path to a *.py file for custom templates. See "pydoc dbusmock.templates" for a list of available templates from python-dbusmock package, and "pydoc dbusmock.templates.NAME" for documentation about template NAME. parameters: A parameter (string) → value (variant) map, for parameterizing templates. Each template can define their own, see documentation of that particular template for details. ''' try: module = load_module(template) except ImportError as e: raise dbus.exceptions.DBusException('Cannot add template %s: %s' % (template, str(e)), name='org.freedesktop.DBus.Mock.TemplateError') # If the template specifies this is an ObjectManager, set that up if hasattr(module, 'IS_OBJECT_MANAGER') and module.IS_OBJECT_MANAGER: self._set_up_object_manager() # pick out all D-Bus service methods and add them to our interface for symbol in dir(module): fn = getattr(module, symbol) if ('_dbus_interface' in dir(fn) and ('_dbus_is_signal' not in dir(fn) or not fn._dbus_is_signal)): # for dbus-python compatibility, add methods as callables setattr(self.__class__, symbol, fn) self.methods.setdefault(fn._dbus_interface, {})[str(symbol)] = ( fn._dbus_in_signature, fn._dbus_out_signature, '', fn ) if parameters is None: parameters = {} module.load(self, parameters) # save the given template and parameters for re-instantiation on # Reset() self._template = template self._template_parameters = parameters
python
def AddTemplate(self, template, parameters): '''Load a template into the mock. python-dbusmock ships a set of standard mocks for common system services such as UPower and NetworkManager. With these the actual tests become a lot simpler, as they only have to set up the particular properties for the tests, and not the skeleton of common properties, interfaces, and methods. template: Name of the template to load or the full path to a *.py file for custom templates. See "pydoc dbusmock.templates" for a list of available templates from python-dbusmock package, and "pydoc dbusmock.templates.NAME" for documentation about template NAME. parameters: A parameter (string) → value (variant) map, for parameterizing templates. Each template can define their own, see documentation of that particular template for details. ''' try: module = load_module(template) except ImportError as e: raise dbus.exceptions.DBusException('Cannot add template %s: %s' % (template, str(e)), name='org.freedesktop.DBus.Mock.TemplateError') # If the template specifies this is an ObjectManager, set that up if hasattr(module, 'IS_OBJECT_MANAGER') and module.IS_OBJECT_MANAGER: self._set_up_object_manager() # pick out all D-Bus service methods and add them to our interface for symbol in dir(module): fn = getattr(module, symbol) if ('_dbus_interface' in dir(fn) and ('_dbus_is_signal' not in dir(fn) or not fn._dbus_is_signal)): # for dbus-python compatibility, add methods as callables setattr(self.__class__, symbol, fn) self.methods.setdefault(fn._dbus_interface, {})[str(symbol)] = ( fn._dbus_in_signature, fn._dbus_out_signature, '', fn ) if parameters is None: parameters = {} module.load(self, parameters) # save the given template and parameters for re-instantiation on # Reset() self._template = template self._template_parameters = parameters
[ "def", "AddTemplate", "(", "self", ",", "template", ",", "parameters", ")", ":", "try", ":", "module", "=", "load_module", "(", "template", ")", "except", "ImportError", "as", "e", ":", "raise", "dbus", ".", "exceptions", ".", "DBusException", "(", "'Canno...
Load a template into the mock. python-dbusmock ships a set of standard mocks for common system services such as UPower and NetworkManager. With these the actual tests become a lot simpler, as they only have to set up the particular properties for the tests, and not the skeleton of common properties, interfaces, and methods. template: Name of the template to load or the full path to a *.py file for custom templates. See "pydoc dbusmock.templates" for a list of available templates from python-dbusmock package, and "pydoc dbusmock.templates.NAME" for documentation about template NAME. parameters: A parameter (string) → value (variant) map, for parameterizing templates. Each template can define their own, see documentation of that particular template for details.
[ "Load", "a", "template", "into", "the", "mock", "." ]
26f65f78bc0ed347233f699a8d6ee0e6880e7eb0
https://github.com/martinpitt/python-dbusmock/blob/26f65f78bc0ed347233f699a8d6ee0e6880e7eb0/dbusmock/mockobject.py#L413-L460
train
24,279
martinpitt/python-dbusmock
dbusmock/mockobject.py
DBusMockObject.EmitSignal
def EmitSignal(self, interface, name, signature, args): '''Emit a signal from the object. interface: D-Bus interface to send the signal from. For convenience you can specify '' here to add the method to the object's main interface (as specified on construction). name: Name of the signal signature: Signature of input arguments; for example "ias" for a signal that takes an int32 and a string array as arguments; see http://dbus.freedesktop.org/doc/dbus-specification.html#message-protocol-signatures args: variant array with signal arguments; must match order and type in "signature" ''' if not interface: interface = self.interface # convert types of arguments according to signature, using # MethodCallMessage.append(); this will also provide type/length # checks, except for the case of an empty signature if signature == '' and len(args) > 0: raise TypeError('Fewer items found in D-Bus signature than in Python arguments') m = dbus.connection.MethodCallMessage('a.b', '/a', 'a.b', 'a') m.append(signature=signature, *args) args = m.get_args_list() fn = lambda self, *args: self.log('emit %s.%s%s' % (interface, name, self.format_args(args))) fn.__name__ = str(name) dbus_fn = dbus.service.signal(interface)(fn) dbus_fn._dbus_signature = signature dbus_fn._dbus_args = ['arg%i' % i for i in range(1, len(args) + 1)] dbus_fn(self, *args)
python
def EmitSignal(self, interface, name, signature, args): '''Emit a signal from the object. interface: D-Bus interface to send the signal from. For convenience you can specify '' here to add the method to the object's main interface (as specified on construction). name: Name of the signal signature: Signature of input arguments; for example "ias" for a signal that takes an int32 and a string array as arguments; see http://dbus.freedesktop.org/doc/dbus-specification.html#message-protocol-signatures args: variant array with signal arguments; must match order and type in "signature" ''' if not interface: interface = self.interface # convert types of arguments according to signature, using # MethodCallMessage.append(); this will also provide type/length # checks, except for the case of an empty signature if signature == '' and len(args) > 0: raise TypeError('Fewer items found in D-Bus signature than in Python arguments') m = dbus.connection.MethodCallMessage('a.b', '/a', 'a.b', 'a') m.append(signature=signature, *args) args = m.get_args_list() fn = lambda self, *args: self.log('emit %s.%s%s' % (interface, name, self.format_args(args))) fn.__name__ = str(name) dbus_fn = dbus.service.signal(interface)(fn) dbus_fn._dbus_signature = signature dbus_fn._dbus_args = ['arg%i' % i for i in range(1, len(args) + 1)] dbus_fn(self, *args)
[ "def", "EmitSignal", "(", "self", ",", "interface", ",", "name", ",", "signature", ",", "args", ")", ":", "if", "not", "interface", ":", "interface", "=", "self", ".", "interface", "# convert types of arguments according to signature, using", "# MethodCallMessage.appe...
Emit a signal from the object. interface: D-Bus interface to send the signal from. For convenience you can specify '' here to add the method to the object's main interface (as specified on construction). name: Name of the signal signature: Signature of input arguments; for example "ias" for a signal that takes an int32 and a string array as arguments; see http://dbus.freedesktop.org/doc/dbus-specification.html#message-protocol-signatures args: variant array with signal arguments; must match order and type in "signature"
[ "Emit", "a", "signal", "from", "the", "object", "." ]
26f65f78bc0ed347233f699a8d6ee0e6880e7eb0
https://github.com/martinpitt/python-dbusmock/blob/26f65f78bc0ed347233f699a8d6ee0e6880e7eb0/dbusmock/mockobject.py#L465-L496
train
24,280
martinpitt/python-dbusmock
dbusmock/mockobject.py
DBusMockObject.GetMethodCalls
def GetMethodCalls(self, method): '''List all the logged calls of a particular method. Return a list of (timestamp, args_list) tuples. ''' return [(row[0], row[2]) for row in self.call_log if row[1] == method]
python
def GetMethodCalls(self, method): '''List all the logged calls of a particular method. Return a list of (timestamp, args_list) tuples. ''' return [(row[0], row[2]) for row in self.call_log if row[1] == method]
[ "def", "GetMethodCalls", "(", "self", ",", "method", ")", ":", "return", "[", "(", "row", "[", "0", "]", ",", "row", "[", "2", "]", ")", "for", "row", "in", "self", ".", "call_log", "if", "row", "[", "1", "]", "==", "method", "]" ]
List all the logged calls of a particular method. Return a list of (timestamp, args_list) tuples.
[ "List", "all", "the", "logged", "calls", "of", "a", "particular", "method", "." ]
26f65f78bc0ed347233f699a8d6ee0e6880e7eb0
https://github.com/martinpitt/python-dbusmock/blob/26f65f78bc0ed347233f699a8d6ee0e6880e7eb0/dbusmock/mockobject.py#L511-L516
train
24,281
martinpitt/python-dbusmock
dbusmock/mockobject.py
DBusMockObject.mock_method
def mock_method(self, interface, dbus_method, in_signature, *args, **kwargs): '''Master mock method. This gets "instantiated" in AddMethod(). Execute the code snippet of the method and return the "ret" variable if it was set. ''' # print('mock_method', dbus_method, self, in_signature, args, kwargs, file=sys.stderr) # convert types of arguments according to signature, using # MethodCallMessage.append(); this will also provide type/length # checks, except for the case of an empty signature if in_signature == '' and len(args) > 0: raise TypeError('Fewer items found in D-Bus signature than in Python arguments') m = dbus.connection.MethodCallMessage('a.b', '/a', 'a.b', 'a') m.append(signature=in_signature, *args) args = m.get_args_list() self.log(dbus_method + self.format_args(args)) self.call_log.append((int(time.time()), str(dbus_method), args)) self.MethodCalled(dbus_method, args) # The code may be a Python 3 string to interpret, or may be a function # object (if AddMethod was called from within Python itself, rather than # over D-Bus). code = self.methods[interface][dbus_method][2] if code and isinstance(code, types.FunctionType): return code(self, *args) elif code: loc = locals().copy() exec(code, globals(), loc) if 'ret' in loc: return loc['ret']
python
def mock_method(self, interface, dbus_method, in_signature, *args, **kwargs): '''Master mock method. This gets "instantiated" in AddMethod(). Execute the code snippet of the method and return the "ret" variable if it was set. ''' # print('mock_method', dbus_method, self, in_signature, args, kwargs, file=sys.stderr) # convert types of arguments according to signature, using # MethodCallMessage.append(); this will also provide type/length # checks, except for the case of an empty signature if in_signature == '' and len(args) > 0: raise TypeError('Fewer items found in D-Bus signature than in Python arguments') m = dbus.connection.MethodCallMessage('a.b', '/a', 'a.b', 'a') m.append(signature=in_signature, *args) args = m.get_args_list() self.log(dbus_method + self.format_args(args)) self.call_log.append((int(time.time()), str(dbus_method), args)) self.MethodCalled(dbus_method, args) # The code may be a Python 3 string to interpret, or may be a function # object (if AddMethod was called from within Python itself, rather than # over D-Bus). code = self.methods[interface][dbus_method][2] if code and isinstance(code, types.FunctionType): return code(self, *args) elif code: loc = locals().copy() exec(code, globals(), loc) if 'ret' in loc: return loc['ret']
[ "def", "mock_method", "(", "self", ",", "interface", ",", "dbus_method", ",", "in_signature", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "# print('mock_method', dbus_method, self, in_signature, args, kwargs, file=sys.stderr)", "# convert types of arguments according...
Master mock method. This gets "instantiated" in AddMethod(). Execute the code snippet of the method and return the "ret" variable if it was set.
[ "Master", "mock", "method", "." ]
26f65f78bc0ed347233f699a8d6ee0e6880e7eb0
https://github.com/martinpitt/python-dbusmock/blob/26f65f78bc0ed347233f699a8d6ee0e6880e7eb0/dbusmock/mockobject.py#L548-L579
train
24,282
martinpitt/python-dbusmock
dbusmock/mockobject.py
DBusMockObject.format_args
def format_args(self, args): '''Format a D-Bus argument tuple into an appropriate logging string.''' def format_arg(a): if isinstance(a, dbus.Boolean): return str(bool(a)) if isinstance(a, dbus.Byte): return str(int(a)) if isinstance(a, int) or isinstance(a, long): return str(a) if isinstance(a, str): return '"' + str(a) + '"' if isinstance(a, unicode): # Python 2 only return '"' + repr(a.encode('UTF-8'))[1:-1] + '"' if isinstance(a, list): return '[' + ', '.join([format_arg(x) for x in a]) + ']' if isinstance(a, dict): fmta = '{' first = True for k, v in a.items(): if first: first = False else: fmta += ', ' fmta += format_arg(k) + ': ' + format_arg(v) return fmta + '}' # fallback return repr(a) s = '' for a in args: if s: s += ' ' s += format_arg(a) if s: s = ' ' + s return s
python
def format_args(self, args): '''Format a D-Bus argument tuple into an appropriate logging string.''' def format_arg(a): if isinstance(a, dbus.Boolean): return str(bool(a)) if isinstance(a, dbus.Byte): return str(int(a)) if isinstance(a, int) or isinstance(a, long): return str(a) if isinstance(a, str): return '"' + str(a) + '"' if isinstance(a, unicode): # Python 2 only return '"' + repr(a.encode('UTF-8'))[1:-1] + '"' if isinstance(a, list): return '[' + ', '.join([format_arg(x) for x in a]) + ']' if isinstance(a, dict): fmta = '{' first = True for k, v in a.items(): if first: first = False else: fmta += ', ' fmta += format_arg(k) + ': ' + format_arg(v) return fmta + '}' # fallback return repr(a) s = '' for a in args: if s: s += ' ' s += format_arg(a) if s: s = ' ' + s return s
[ "def", "format_args", "(", "self", ",", "args", ")", ":", "def", "format_arg", "(", "a", ")", ":", "if", "isinstance", "(", "a", ",", "dbus", ".", "Boolean", ")", ":", "return", "str", "(", "bool", "(", "a", ")", ")", "if", "isinstance", "(", "a"...
Format a D-Bus argument tuple into an appropriate logging string.
[ "Format", "a", "D", "-", "Bus", "argument", "tuple", "into", "an", "appropriate", "logging", "string", "." ]
26f65f78bc0ed347233f699a8d6ee0e6880e7eb0
https://github.com/martinpitt/python-dbusmock/blob/26f65f78bc0ed347233f699a8d6ee0e6880e7eb0/dbusmock/mockobject.py#L581-L618
train
24,283
martinpitt/python-dbusmock
dbusmock/mockobject.py
DBusMockObject.log
def log(self, msg): '''Log a message, prefixed with a timestamp. If a log file was specified in the constructor, it is written there, otherwise it goes to stdout. ''' if self.logfile: fd = self.logfile.fileno() else: fd = sys.stdout.fileno() os.write(fd, ('%.3f %s\n' % (time.time(), msg)).encode('UTF-8'))
python
def log(self, msg): '''Log a message, prefixed with a timestamp. If a log file was specified in the constructor, it is written there, otherwise it goes to stdout. ''' if self.logfile: fd = self.logfile.fileno() else: fd = sys.stdout.fileno() os.write(fd, ('%.3f %s\n' % (time.time(), msg)).encode('UTF-8'))
[ "def", "log", "(", "self", ",", "msg", ")", ":", "if", "self", ".", "logfile", ":", "fd", "=", "self", ".", "logfile", ".", "fileno", "(", ")", "else", ":", "fd", "=", "sys", ".", "stdout", ".", "fileno", "(", ")", "os", ".", "write", "(", "f...
Log a message, prefixed with a timestamp. If a log file was specified in the constructor, it is written there, otherwise it goes to stdout.
[ "Log", "a", "message", "prefixed", "with", "a", "timestamp", "." ]
26f65f78bc0ed347233f699a8d6ee0e6880e7eb0
https://github.com/martinpitt/python-dbusmock/blob/26f65f78bc0ed347233f699a8d6ee0e6880e7eb0/dbusmock/mockobject.py#L620-L631
train
24,284
martinpitt/python-dbusmock
dbusmock/mockobject.py
DBusMockObject.Introspect
def Introspect(self, object_path, connection): '''Return XML description of this object's interfaces, methods and signals. This wraps dbus-python's Introspect() method to include the dynamic methods and properties. ''' # temporarily add our dynamic methods cls = self.__class__.__module__ + '.' + self.__class__.__name__ orig_interfaces = self._dbus_class_table[cls] mock_interfaces = orig_interfaces.copy() for interface, methods in self.methods.items(): for method in methods: mock_interfaces.setdefault(interface, {})[method] = self.methods[interface][method][3] self._dbus_class_table[cls] = mock_interfaces xml = dbus.service.Object.Introspect(self, object_path, connection) tree = ElementTree.fromstring(xml) for name in self.props: # We might have properties for new interfaces we don't know about # yet. Try to find an existing <interface> node named after our # interface to append to, and create one if we can't. interface = tree.find(".//interface[@name='%s']" % name) if interface is None: interface = ElementTree.Element("interface", {"name": name}) tree.append(interface) for prop, val in self.props[name].items(): if val is None: # can't guess type from None, skip continue elem = ElementTree.Element("property", { "name": prop, # We don't store the signature anywhere, so guess it. "type": dbus.lowlevel.Message.guess_signature(val), "access": "readwrite"}) interface.append(elem) xml = ElementTree.tostring(tree, encoding='utf8', method='xml').decode('utf8') # restore original class table self._dbus_class_table[cls] = orig_interfaces return xml
python
def Introspect(self, object_path, connection): '''Return XML description of this object's interfaces, methods and signals. This wraps dbus-python's Introspect() method to include the dynamic methods and properties. ''' # temporarily add our dynamic methods cls = self.__class__.__module__ + '.' + self.__class__.__name__ orig_interfaces = self._dbus_class_table[cls] mock_interfaces = orig_interfaces.copy() for interface, methods in self.methods.items(): for method in methods: mock_interfaces.setdefault(interface, {})[method] = self.methods[interface][method][3] self._dbus_class_table[cls] = mock_interfaces xml = dbus.service.Object.Introspect(self, object_path, connection) tree = ElementTree.fromstring(xml) for name in self.props: # We might have properties for new interfaces we don't know about # yet. Try to find an existing <interface> node named after our # interface to append to, and create one if we can't. interface = tree.find(".//interface[@name='%s']" % name) if interface is None: interface = ElementTree.Element("interface", {"name": name}) tree.append(interface) for prop, val in self.props[name].items(): if val is None: # can't guess type from None, skip continue elem = ElementTree.Element("property", { "name": prop, # We don't store the signature anywhere, so guess it. "type": dbus.lowlevel.Message.guess_signature(val), "access": "readwrite"}) interface.append(elem) xml = ElementTree.tostring(tree, encoding='utf8', method='xml').decode('utf8') # restore original class table self._dbus_class_table[cls] = orig_interfaces return xml
[ "def", "Introspect", "(", "self", ",", "object_path", ",", "connection", ")", ":", "# temporarily add our dynamic methods", "cls", "=", "self", ".", "__class__", ".", "__module__", "+", "'.'", "+", "self", ".", "__class__", ".", "__name__", "orig_interfaces", "=...
Return XML description of this object's interfaces, methods and signals. This wraps dbus-python's Introspect() method to include the dynamic methods and properties.
[ "Return", "XML", "description", "of", "this", "object", "s", "interfaces", "methods", "and", "signals", "." ]
26f65f78bc0ed347233f699a8d6ee0e6880e7eb0
https://github.com/martinpitt/python-dbusmock/blob/26f65f78bc0ed347233f699a8d6ee0e6880e7eb0/dbusmock/mockobject.py#L638-L684
train
24,285
martinpitt/python-dbusmock
dbusmock/templates/bluez5-obex.py
CreateSession
def CreateSession(self, destination, args): '''OBEX method to create a new transfer session. The destination must be the address of the destination Bluetooth device. The given arguments must be a map from well-known keys to values, containing at least the ‘Target’ key, whose value must be ‘PBAP’ (other keys and values are accepted by the real daemon, but not by this mock daemon at the moment). If the target is missing or incorrect, an Unsupported error is returned on the bus. Returns the path of a new Session object. ''' if 'Target' not in args or args['Target'].upper() != 'PBAP': raise dbus.exceptions.DBusException( 'Non-PBAP targets are not currently supported by this python-dbusmock template.', name=OBEX_MOCK_IFACE + '.Unsupported') # Find the first unused session ID. client_path = '/org/bluez/obex/client' session_id = 0 while client_path + '/session' + str(session_id) in mockobject.objects: session_id += 1 path = client_path + '/session' + str(session_id) properties = { 'Source': dbus.String('FIXME', variant_level=1), 'Destination': dbus.String(destination, variant_level=1), 'Channel': dbus.Byte(0, variant_level=1), 'Target': dbus.String('FIXME', variant_level=1), 'Root': dbus.String('FIXME', variant_level=1), } self.AddObject(path, SESSION_IFACE, # Properties properties, # Methods [ ('GetCapabilities', '', 's', ''), # Currently a no-op ]) session = mockobject.objects[path] session.AddMethods(PHONEBOOK_ACCESS_IFACE, [ ('Select', 'ss', '', ''), # Currently a no-op # Currently a no-op ('List', 'a{sv}', 'a(ss)', 'ret = dbus.Array(signature="(ss)")'), # Currently a no-op ('ListFilterFields', '', 'as', 'ret = dbus.Array(signature="(s)")'), ('PullAll', 'sa{sv}', 'sa{sv}', PullAll), ('GetSize', '', 'q', 'ret = 0'), # TODO ]) manager = mockobject.objects['/'] manager.EmitSignal(OBJECT_MANAGER_IFACE, 'InterfacesAdded', 'oa{sa{sv}}', [ dbus.ObjectPath(path), {SESSION_IFACE: properties}, ]) return path
python
def CreateSession(self, destination, args): '''OBEX method to create a new transfer session. The destination must be the address of the destination Bluetooth device. The given arguments must be a map from well-known keys to values, containing at least the ‘Target’ key, whose value must be ‘PBAP’ (other keys and values are accepted by the real daemon, but not by this mock daemon at the moment). If the target is missing or incorrect, an Unsupported error is returned on the bus. Returns the path of a new Session object. ''' if 'Target' not in args or args['Target'].upper() != 'PBAP': raise dbus.exceptions.DBusException( 'Non-PBAP targets are not currently supported by this python-dbusmock template.', name=OBEX_MOCK_IFACE + '.Unsupported') # Find the first unused session ID. client_path = '/org/bluez/obex/client' session_id = 0 while client_path + '/session' + str(session_id) in mockobject.objects: session_id += 1 path = client_path + '/session' + str(session_id) properties = { 'Source': dbus.String('FIXME', variant_level=1), 'Destination': dbus.String(destination, variant_level=1), 'Channel': dbus.Byte(0, variant_level=1), 'Target': dbus.String('FIXME', variant_level=1), 'Root': dbus.String('FIXME', variant_level=1), } self.AddObject(path, SESSION_IFACE, # Properties properties, # Methods [ ('GetCapabilities', '', 's', ''), # Currently a no-op ]) session = mockobject.objects[path] session.AddMethods(PHONEBOOK_ACCESS_IFACE, [ ('Select', 'ss', '', ''), # Currently a no-op # Currently a no-op ('List', 'a{sv}', 'a(ss)', 'ret = dbus.Array(signature="(ss)")'), # Currently a no-op ('ListFilterFields', '', 'as', 'ret = dbus.Array(signature="(s)")'), ('PullAll', 'sa{sv}', 'sa{sv}', PullAll), ('GetSize', '', 'q', 'ret = 0'), # TODO ]) manager = mockobject.objects['/'] manager.EmitSignal(OBJECT_MANAGER_IFACE, 'InterfacesAdded', 'oa{sa{sv}}', [ dbus.ObjectPath(path), {SESSION_IFACE: properties}, ]) return path
[ "def", "CreateSession", "(", "self", ",", "destination", ",", "args", ")", ":", "if", "'Target'", "not", "in", "args", "or", "args", "[", "'Target'", "]", ".", "upper", "(", ")", "!=", "'PBAP'", ":", "raise", "dbus", ".", "exceptions", ".", "DBusExcept...
OBEX method to create a new transfer session. The destination must be the address of the destination Bluetooth device. The given arguments must be a map from well-known keys to values, containing at least the ‘Target’ key, whose value must be ‘PBAP’ (other keys and values are accepted by the real daemon, but not by this mock daemon at the moment). If the target is missing or incorrect, an Unsupported error is returned on the bus. Returns the path of a new Session object.
[ "OBEX", "method", "to", "create", "a", "new", "transfer", "session", "." ]
26f65f78bc0ed347233f699a8d6ee0e6880e7eb0
https://github.com/martinpitt/python-dbusmock/blob/26f65f78bc0ed347233f699a8d6ee0e6880e7eb0/dbusmock/templates/bluez5-obex.py#L58-L118
train
24,286
martinpitt/python-dbusmock
dbusmock/templates/bluez5-obex.py
RemoveSession
def RemoveSession(self, session_path): '''OBEX method to remove an existing transfer session. This takes the path of the transfer Session object and removes it. ''' manager = mockobject.objects['/'] # Remove all the session's transfers. transfer_id = 0 while session_path + '/transfer' + str(transfer_id) in mockobject.objects: transfer_path = session_path + '/transfer' + str(transfer_id) transfer_id += 1 self.RemoveObject(transfer_path) manager.EmitSignal(OBJECT_MANAGER_IFACE, 'InterfacesRemoved', 'oas', [ dbus.ObjectPath(transfer_path), [TRANSFER_IFACE], ]) # Remove the session itself. self.RemoveObject(session_path) manager.EmitSignal(OBJECT_MANAGER_IFACE, 'InterfacesRemoved', 'oas', [ dbus.ObjectPath(session_path), [SESSION_IFACE, PHONEBOOK_ACCESS_IFACE], ])
python
def RemoveSession(self, session_path): '''OBEX method to remove an existing transfer session. This takes the path of the transfer Session object and removes it. ''' manager = mockobject.objects['/'] # Remove all the session's transfers. transfer_id = 0 while session_path + '/transfer' + str(transfer_id) in mockobject.objects: transfer_path = session_path + '/transfer' + str(transfer_id) transfer_id += 1 self.RemoveObject(transfer_path) manager.EmitSignal(OBJECT_MANAGER_IFACE, 'InterfacesRemoved', 'oas', [ dbus.ObjectPath(transfer_path), [TRANSFER_IFACE], ]) # Remove the session itself. self.RemoveObject(session_path) manager.EmitSignal(OBJECT_MANAGER_IFACE, 'InterfacesRemoved', 'oas', [ dbus.ObjectPath(session_path), [SESSION_IFACE, PHONEBOOK_ACCESS_IFACE], ])
[ "def", "RemoveSession", "(", "self", ",", "session_path", ")", ":", "manager", "=", "mockobject", ".", "objects", "[", "'/'", "]", "# Remove all the session's transfers.", "transfer_id", "=", "0", "while", "session_path", "+", "'/transfer'", "+", "str", "(", "tr...
OBEX method to remove an existing transfer session. This takes the path of the transfer Session object and removes it.
[ "OBEX", "method", "to", "remove", "an", "existing", "transfer", "session", "." ]
26f65f78bc0ed347233f699a8d6ee0e6880e7eb0
https://github.com/martinpitt/python-dbusmock/blob/26f65f78bc0ed347233f699a8d6ee0e6880e7eb0/dbusmock/templates/bluez5-obex.py#L123-L152
train
24,287
martinpitt/python-dbusmock
dbusmock/templates/bluez5-obex.py
PullAll
def PullAll(self, target_file, filters): '''OBEX method to start a pull transfer of a phone book. This doesn't complete the transfer; code to mock up activating and completing the transfer must be provided by the test driver, as it’s too complex and test-specific to put here. The target_file is the absolute path for a file which will have zero or more vCards, separated by new-line characters, written to it if the method is successful (and the transfer is completed). This target_file is actually emitted in a TransferCreated signal, which is a special part of the mock interface designed to be handled by the test driver, which should then populate that file and call UpdateStatus on the Transfer object. The test driver is responsible for deleting the file once the test is complete. The filters parameter is a map of filters to be applied to the results device-side before transmitting them back to the adapter. Returns a tuple containing the path for a new Transfer D-Bus object representing the transfer, and a map of the initial properties of that Transfer object. ''' # Find the first unused session ID. session_path = self.path transfer_id = 0 while session_path + '/transfer' + str(transfer_id) in mockobject.objects: transfer_id += 1 transfer_path = session_path + '/transfer' + str(transfer_id) # Create a new temporary file to transfer to. temp_file = tempfile.NamedTemporaryFile(suffix='.vcf', prefix='tmp-bluez5-obex-PullAll_', delete=False) filename = os.path.abspath(temp_file.name) props = { 'Status': dbus.String('queued', variant_level=1), 'Session': dbus.ObjectPath(session_path, variant_level=1), 'Name': dbus.String(target_file, variant_level=1), 'Filename': dbus.String(filename, variant_level=1), 'Transferred': dbus.UInt64(0, variant_level=1), } self.AddObject(transfer_path, TRANSFER_IFACE, # Properties props, # Methods [ ('Cancel', '', '', ''), # Currently a no-op ]) transfer = mockobject.objects[transfer_path] transfer.AddMethods(TRANSFER_MOCK_IFACE, [ ('UpdateStatus', 'b', '', UpdateStatus), ]) manager = mockobject.objects['/'] manager.EmitSignal(OBJECT_MANAGER_IFACE, 'InterfacesAdded', 'oa{sa{sv}}', [ dbus.ObjectPath(transfer_path), {TRANSFER_IFACE: props}, ]) # Emit a behind-the-scenes signal that a new transfer has been created. manager.EmitSignal(OBEX_MOCK_IFACE, 'TransferCreated', 'sa{sv}s', [transfer_path, filters, filename]) return (transfer_path, props)
python
def PullAll(self, target_file, filters): '''OBEX method to start a pull transfer of a phone book. This doesn't complete the transfer; code to mock up activating and completing the transfer must be provided by the test driver, as it’s too complex and test-specific to put here. The target_file is the absolute path for a file which will have zero or more vCards, separated by new-line characters, written to it if the method is successful (and the transfer is completed). This target_file is actually emitted in a TransferCreated signal, which is a special part of the mock interface designed to be handled by the test driver, which should then populate that file and call UpdateStatus on the Transfer object. The test driver is responsible for deleting the file once the test is complete. The filters parameter is a map of filters to be applied to the results device-side before transmitting them back to the adapter. Returns a tuple containing the path for a new Transfer D-Bus object representing the transfer, and a map of the initial properties of that Transfer object. ''' # Find the first unused session ID. session_path = self.path transfer_id = 0 while session_path + '/transfer' + str(transfer_id) in mockobject.objects: transfer_id += 1 transfer_path = session_path + '/transfer' + str(transfer_id) # Create a new temporary file to transfer to. temp_file = tempfile.NamedTemporaryFile(suffix='.vcf', prefix='tmp-bluez5-obex-PullAll_', delete=False) filename = os.path.abspath(temp_file.name) props = { 'Status': dbus.String('queued', variant_level=1), 'Session': dbus.ObjectPath(session_path, variant_level=1), 'Name': dbus.String(target_file, variant_level=1), 'Filename': dbus.String(filename, variant_level=1), 'Transferred': dbus.UInt64(0, variant_level=1), } self.AddObject(transfer_path, TRANSFER_IFACE, # Properties props, # Methods [ ('Cancel', '', '', ''), # Currently a no-op ]) transfer = mockobject.objects[transfer_path] transfer.AddMethods(TRANSFER_MOCK_IFACE, [ ('UpdateStatus', 'b', '', UpdateStatus), ]) manager = mockobject.objects['/'] manager.EmitSignal(OBJECT_MANAGER_IFACE, 'InterfacesAdded', 'oa{sa{sv}}', [ dbus.ObjectPath(transfer_path), {TRANSFER_IFACE: props}, ]) # Emit a behind-the-scenes signal that a new transfer has been created. manager.EmitSignal(OBEX_MOCK_IFACE, 'TransferCreated', 'sa{sv}s', [transfer_path, filters, filename]) return (transfer_path, props)
[ "def", "PullAll", "(", "self", ",", "target_file", ",", "filters", ")", ":", "# Find the first unused session ID.", "session_path", "=", "self", ".", "path", "transfer_id", "=", "0", "while", "session_path", "+", "'/transfer'", "+", "str", "(", "transfer_id", ")...
OBEX method to start a pull transfer of a phone book. This doesn't complete the transfer; code to mock up activating and completing the transfer must be provided by the test driver, as it’s too complex and test-specific to put here. The target_file is the absolute path for a file which will have zero or more vCards, separated by new-line characters, written to it if the method is successful (and the transfer is completed). This target_file is actually emitted in a TransferCreated signal, which is a special part of the mock interface designed to be handled by the test driver, which should then populate that file and call UpdateStatus on the Transfer object. The test driver is responsible for deleting the file once the test is complete. The filters parameter is a map of filters to be applied to the results device-side before transmitting them back to the adapter. Returns a tuple containing the path for a new Transfer D-Bus object representing the transfer, and a map of the initial properties of that Transfer object.
[ "OBEX", "method", "to", "start", "a", "pull", "transfer", "of", "a", "phone", "book", "." ]
26f65f78bc0ed347233f699a8d6ee0e6880e7eb0
https://github.com/martinpitt/python-dbusmock/blob/26f65f78bc0ed347233f699a8d6ee0e6880e7eb0/dbusmock/templates/bluez5-obex.py#L157-L228
train
24,288
martinpitt/python-dbusmock
dbusmock/templates/bluez5-obex.py
UpdateStatus
def UpdateStatus(self, is_complete): '''Mock method to update the transfer status. If is_complete is False, this marks the transfer is active; otherwise it marks the transfer as complete. It is an error to call this method after calling it with is_complete as True. In both cases, it updates the number of bytes transferred to be the current size of the transfer file (whose filename was emitted in the TransferCreated signal). ''' status = 'complete' if is_complete else 'active' transferred = os.path.getsize(self.props[TRANSFER_IFACE]['Filename']) self.props[TRANSFER_IFACE]['Status'] = status self.props[TRANSFER_IFACE]['Transferred'] = dbus.UInt64(transferred, variant_level=1) self.EmitSignal(dbus.PROPERTIES_IFACE, 'PropertiesChanged', 'sa{sv}as', [ TRANSFER_IFACE, { 'Status': dbus.String(status, variant_level=1), 'Transferred': dbus.UInt64(transferred, variant_level=1), }, [], ])
python
def UpdateStatus(self, is_complete): '''Mock method to update the transfer status. If is_complete is False, this marks the transfer is active; otherwise it marks the transfer as complete. It is an error to call this method after calling it with is_complete as True. In both cases, it updates the number of bytes transferred to be the current size of the transfer file (whose filename was emitted in the TransferCreated signal). ''' status = 'complete' if is_complete else 'active' transferred = os.path.getsize(self.props[TRANSFER_IFACE]['Filename']) self.props[TRANSFER_IFACE]['Status'] = status self.props[TRANSFER_IFACE]['Transferred'] = dbus.UInt64(transferred, variant_level=1) self.EmitSignal(dbus.PROPERTIES_IFACE, 'PropertiesChanged', 'sa{sv}as', [ TRANSFER_IFACE, { 'Status': dbus.String(status, variant_level=1), 'Transferred': dbus.UInt64(transferred, variant_level=1), }, [], ])
[ "def", "UpdateStatus", "(", "self", ",", "is_complete", ")", ":", "status", "=", "'complete'", "if", "is_complete", "else", "'active'", "transferred", "=", "os", ".", "path", ".", "getsize", "(", "self", ".", "props", "[", "TRANSFER_IFACE", "]", "[", "'Fil...
Mock method to update the transfer status. If is_complete is False, this marks the transfer is active; otherwise it marks the transfer as complete. It is an error to call this method after calling it with is_complete as True. In both cases, it updates the number of bytes transferred to be the current size of the transfer file (whose filename was emitted in the TransferCreated signal).
[ "Mock", "method", "to", "update", "the", "transfer", "status", "." ]
26f65f78bc0ed347233f699a8d6ee0e6880e7eb0
https://github.com/martinpitt/python-dbusmock/blob/26f65f78bc0ed347233f699a8d6ee0e6880e7eb0/dbusmock/templates/bluez5-obex.py#L261-L285
train
24,289
martinpitt/python-dbusmock
dbusmock/templates/ofono.py
AddModem
def AddModem(self, name, properties): '''Convenience method to add a modem You have to specify a device name which must be a valid part of an object path, e. g. "mock_ac". For future extensions you can specify a "properties" array, but no extra properties are supported for now. Returns the new object path. ''' path = '/' + name self.AddObject(path, 'org.ofono.Modem', { 'Online': dbus.Boolean(True, variant_level=1), 'Powered': dbus.Boolean(True, variant_level=1), 'Lockdown': dbus.Boolean(False, variant_level=1), 'Emergency': dbus.Boolean(False, variant_level=1), 'Manufacturer': dbus.String('Fakesys', variant_level=1), 'Model': dbus.String('Mock Modem', variant_level=1), 'Revision': dbus.String('0815.42', variant_level=1), 'Serial': dbus.String(new_modem_serial(self), variant_level=1), 'Type': dbus.String('hardware', variant_level=1), 'Interfaces': ['org.ofono.CallVolume', 'org.ofono.VoiceCallManager', 'org.ofono.NetworkRegistration', 'org.ofono.SimManager', # 'org.ofono.MessageManager', 'org.ofono.ConnectionManager', # 'org.ofono.NetworkTime' ], # 'Features': ['sms', 'net', 'gprs', 'sim'] 'Features': ['gprs', 'net'], }, [ ('GetProperties', '', 'a{sv}', 'ret = self.GetAll("org.ofono.Modem")'), ('SetProperty', 'sv', '', 'self.Set("org.ofono.Modem", args[0], args[1]); ' 'self.EmitSignal("org.ofono.Modem", "PropertyChanged",' ' "sv", [args[0], args[1]])'), ] ) obj = dbusmock.mockobject.objects[path] obj.name = name add_voice_call_api(obj) add_netreg_api(obj) add_simmanager_api(self, obj) add_connectionmanager_api(obj) self.modems.append(path) props = obj.GetAll('org.ofono.Modem', dbus_interface=dbus.PROPERTIES_IFACE) self.EmitSignal(MAIN_IFACE, 'ModemAdded', 'oa{sv}', [path, props]) return path
python
def AddModem(self, name, properties): '''Convenience method to add a modem You have to specify a device name which must be a valid part of an object path, e. g. "mock_ac". For future extensions you can specify a "properties" array, but no extra properties are supported for now. Returns the new object path. ''' path = '/' + name self.AddObject(path, 'org.ofono.Modem', { 'Online': dbus.Boolean(True, variant_level=1), 'Powered': dbus.Boolean(True, variant_level=1), 'Lockdown': dbus.Boolean(False, variant_level=1), 'Emergency': dbus.Boolean(False, variant_level=1), 'Manufacturer': dbus.String('Fakesys', variant_level=1), 'Model': dbus.String('Mock Modem', variant_level=1), 'Revision': dbus.String('0815.42', variant_level=1), 'Serial': dbus.String(new_modem_serial(self), variant_level=1), 'Type': dbus.String('hardware', variant_level=1), 'Interfaces': ['org.ofono.CallVolume', 'org.ofono.VoiceCallManager', 'org.ofono.NetworkRegistration', 'org.ofono.SimManager', # 'org.ofono.MessageManager', 'org.ofono.ConnectionManager', # 'org.ofono.NetworkTime' ], # 'Features': ['sms', 'net', 'gprs', 'sim'] 'Features': ['gprs', 'net'], }, [ ('GetProperties', '', 'a{sv}', 'ret = self.GetAll("org.ofono.Modem")'), ('SetProperty', 'sv', '', 'self.Set("org.ofono.Modem", args[0], args[1]); ' 'self.EmitSignal("org.ofono.Modem", "PropertyChanged",' ' "sv", [args[0], args[1]])'), ] ) obj = dbusmock.mockobject.objects[path] obj.name = name add_voice_call_api(obj) add_netreg_api(obj) add_simmanager_api(self, obj) add_connectionmanager_api(obj) self.modems.append(path) props = obj.GetAll('org.ofono.Modem', dbus_interface=dbus.PROPERTIES_IFACE) self.EmitSignal(MAIN_IFACE, 'ModemAdded', 'oa{sv}', [path, props]) return path
[ "def", "AddModem", "(", "self", ",", "name", ",", "properties", ")", ":", "path", "=", "'/'", "+", "name", "self", ".", "AddObject", "(", "path", ",", "'org.ofono.Modem'", ",", "{", "'Online'", ":", "dbus", ".", "Boolean", "(", "True", ",", "variant_le...
Convenience method to add a modem You have to specify a device name which must be a valid part of an object path, e. g. "mock_ac". For future extensions you can specify a "properties" array, but no extra properties are supported for now. Returns the new object path.
[ "Convenience", "method", "to", "add", "a", "modem" ]
26f65f78bc0ed347233f699a8d6ee0e6880e7eb0
https://github.com/martinpitt/python-dbusmock/blob/26f65f78bc0ed347233f699a8d6ee0e6880e7eb0/dbusmock/templates/ofono.py#L65-L114
train
24,290
martinpitt/python-dbusmock
dbusmock/templates/ofono.py
add_voice_call_api
def add_voice_call_api(mock): '''Add org.ofono.VoiceCallManager API to a mock''' # also add an emergency number which is not a real one, in case one runs a # test case against a production ofono :-) mock.AddProperty('org.ofono.VoiceCallManager', 'EmergencyNumbers', ['911', '13373']) mock.calls = [] # object paths mock.AddMethods('org.ofono.VoiceCallManager', [ ('GetProperties', '', 'a{sv}', 'ret = self.GetAll("org.ofono.VoiceCallManager")'), ('Transfer', '', '', ''), ('SwapCalls', '', '', ''), ('ReleaseAndAnswer', '', '', ''), ('ReleaseAndSwap', '', '', ''), ('HoldAndAnswer', '', '', ''), ('SendTones', 's', '', ''), ('PrivateChat', 'o', 'ao', NOT_IMPLEMENTED), ('CreateMultiparty', '', 'o', NOT_IMPLEMENTED), ('HangupMultiparty', '', '', NOT_IMPLEMENTED), ('GetCalls', '', 'a(oa{sv})', 'ret = [(c, objects[c].GetAll("org.ofono.VoiceCall")) for c in self.calls]') ])
python
def add_voice_call_api(mock): '''Add org.ofono.VoiceCallManager API to a mock''' # also add an emergency number which is not a real one, in case one runs a # test case against a production ofono :-) mock.AddProperty('org.ofono.VoiceCallManager', 'EmergencyNumbers', ['911', '13373']) mock.calls = [] # object paths mock.AddMethods('org.ofono.VoiceCallManager', [ ('GetProperties', '', 'a{sv}', 'ret = self.GetAll("org.ofono.VoiceCallManager")'), ('Transfer', '', '', ''), ('SwapCalls', '', '', ''), ('ReleaseAndAnswer', '', '', ''), ('ReleaseAndSwap', '', '', ''), ('HoldAndAnswer', '', '', ''), ('SendTones', 's', '', ''), ('PrivateChat', 'o', 'ao', NOT_IMPLEMENTED), ('CreateMultiparty', '', 'o', NOT_IMPLEMENTED), ('HangupMultiparty', '', '', NOT_IMPLEMENTED), ('GetCalls', '', 'a(oa{sv})', 'ret = [(c, objects[c].GetAll("org.ofono.VoiceCall")) for c in self.calls]') ])
[ "def", "add_voice_call_api", "(", "mock", ")", ":", "# also add an emergency number which is not a real one, in case one runs a", "# test case against a production ofono :-)", "mock", ".", "AddProperty", "(", "'org.ofono.VoiceCallManager'", ",", "'EmergencyNumbers'", ",", "[", "'91...
Add org.ofono.VoiceCallManager API to a mock
[ "Add", "org", ".", "ofono", ".", "VoiceCallManager", "API", "to", "a", "mock" ]
26f65f78bc0ed347233f699a8d6ee0e6880e7eb0
https://github.com/martinpitt/python-dbusmock/blob/26f65f78bc0ed347233f699a8d6ee0e6880e7eb0/dbusmock/templates/ofono.py#L169-L190
train
24,291
martinpitt/python-dbusmock
dbusmock/templates/ofono.py
add_netreg_api
def add_netreg_api(mock): '''Add org.ofono.NetworkRegistration API to a mock''' # also add an emergency number which is not a real one, in case one runs a # test case against a production ofono :-) mock.AddProperties('org.ofono.NetworkRegistration', { 'Mode': 'auto', 'Status': 'registered', 'LocationAreaCode': _parameters.get('LocationAreaCode', 987), 'CellId': _parameters.get('CellId', 10203), 'MobileCountryCode': _parameters.get('MobileCountryCode', '777'), 'MobileNetworkCode': _parameters.get('MobileNetworkCode', '11'), 'Technology': _parameters.get('Technology', 'gsm'), 'Name': _parameters.get('Name', 'fake.tel'), 'Strength': _parameters.get('Strength', dbus.Byte(80)), 'BaseStation': _parameters.get('BaseStation', ''), }) mock.AddObject('/%s/operator/op1' % mock.name, 'org.ofono.NetworkOperator', { 'Name': _parameters.get('Name', 'fake.tel'), 'Status': 'current', 'MobileCountryCode': _parameters.get('MobileCountryCode', '777'), 'MobileNetworkCode': _parameters.get('MobileNetworkCode', '11'), 'Technologies': [_parameters.get('Technology', 'gsm')], }, [ ('GetProperties', '', 'a{sv}', 'ret = self.GetAll("org.ofono.NetworkOperator")'), ('Register', '', '', ''), ] # noqa: silly pep8 error here about hanging indent ) mock.AddMethods('org.ofono.NetworkRegistration', [ ('GetProperties', '', 'a{sv}', 'ret = self.GetAll("org.ofono.NetworkRegistration")'), ('SetProperty', 'sv', '', 'self.Set("%(i)s", args[0], args[1]); ' 'self.EmitSignal("%(i)s", "PropertyChanged", "sv", [args[0], args[1]])' % {'i': 'org.ofono.NetworkRegistration'}), ('Register', '', '', ''), ('GetOperators', '', 'a(oa{sv})', get_all_operators(mock)), ('Scan', '', 'a(oa{sv})', get_all_operators(mock)), ])
python
def add_netreg_api(mock): '''Add org.ofono.NetworkRegistration API to a mock''' # also add an emergency number which is not a real one, in case one runs a # test case against a production ofono :-) mock.AddProperties('org.ofono.NetworkRegistration', { 'Mode': 'auto', 'Status': 'registered', 'LocationAreaCode': _parameters.get('LocationAreaCode', 987), 'CellId': _parameters.get('CellId', 10203), 'MobileCountryCode': _parameters.get('MobileCountryCode', '777'), 'MobileNetworkCode': _parameters.get('MobileNetworkCode', '11'), 'Technology': _parameters.get('Technology', 'gsm'), 'Name': _parameters.get('Name', 'fake.tel'), 'Strength': _parameters.get('Strength', dbus.Byte(80)), 'BaseStation': _parameters.get('BaseStation', ''), }) mock.AddObject('/%s/operator/op1' % mock.name, 'org.ofono.NetworkOperator', { 'Name': _parameters.get('Name', 'fake.tel'), 'Status': 'current', 'MobileCountryCode': _parameters.get('MobileCountryCode', '777'), 'MobileNetworkCode': _parameters.get('MobileNetworkCode', '11'), 'Technologies': [_parameters.get('Technology', 'gsm')], }, [ ('GetProperties', '', 'a{sv}', 'ret = self.GetAll("org.ofono.NetworkOperator")'), ('Register', '', '', ''), ] # noqa: silly pep8 error here about hanging indent ) mock.AddMethods('org.ofono.NetworkRegistration', [ ('GetProperties', '', 'a{sv}', 'ret = self.GetAll("org.ofono.NetworkRegistration")'), ('SetProperty', 'sv', '', 'self.Set("%(i)s", args[0], args[1]); ' 'self.EmitSignal("%(i)s", "PropertyChanged", "sv", [args[0], args[1]])' % {'i': 'org.ofono.NetworkRegistration'}), ('Register', '', '', ''), ('GetOperators', '', 'a(oa{sv})', get_all_operators(mock)), ('Scan', '', 'a(oa{sv})', get_all_operators(mock)), ])
[ "def", "add_netreg_api", "(", "mock", ")", ":", "# also add an emergency number which is not a real one, in case one runs a", "# test case against a production ofono :-)", "mock", ".", "AddProperties", "(", "'org.ofono.NetworkRegistration'", ",", "{", "'Mode'", ":", "'auto'", ","...
Add org.ofono.NetworkRegistration API to a mock
[ "Add", "org", ".", "ofono", ".", "NetworkRegistration", "API", "to", "a", "mock" ]
26f65f78bc0ed347233f699a8d6ee0e6880e7eb0
https://github.com/martinpitt/python-dbusmock/blob/26f65f78bc0ed347233f699a8d6ee0e6880e7eb0/dbusmock/templates/ofono.py#L262-L302
train
24,292
martinpitt/python-dbusmock
dbusmock/templates/ofono.py
add_simmanager_api
def add_simmanager_api(self, mock): '''Add org.ofono.SimManager API to a mock''' iface = 'org.ofono.SimManager' mock.AddProperties(iface, { 'BarredDialing': _parameters.get('BarredDialing', False), 'CardIdentifier': _parameters.get('CardIdentifier', new_iccid(self)), 'FixedDialing': _parameters.get('FixedDialing', False), 'LockedPins': _parameters.get('LockedPins', dbus.Array([], signature='s')), 'MobileCountryCode': _parameters.get('MobileCountryCode', '310'), 'MobileNetworkCode': _parameters.get('MobileNetworkCode', '150'), 'PreferredLanguages': _parameters.get('PreferredLanguages', ['en']), 'Present': _parameters.get('Present', dbus.Boolean(True)), 'Retries': _parameters.get('Retries', dbus.Dictionary([["pin", dbus.Byte(3)], ["puk", dbus.Byte(10)]])), 'PinRequired': _parameters.get('PinRequired', "none"), 'SubscriberNumbers': _parameters.get('SubscriberNumbers', ['123456789', '234567890']), 'SubscriberIdentity': _parameters.get('SubscriberIdentity', new_imsi(self)), }) mock.AddMethods(iface, [ ('GetProperties', '', 'a{sv}', 'ret = self.GetAll("%s")' % iface), ('SetProperty', 'sv', '', 'self.Set("%(i)s", args[0], args[1]); ' 'self.EmitSignal("%(i)s", "PropertyChanged", "sv", [args[0], args[1]])' % {'i': iface}), ('ChangePin', 'sss', '', ''), ('EnterPin', 'ss', '', 'correctPin = "1234"\n' 'newRetries = self.Get("%(i)s", "Retries")\n' 'if args[0] == "pin" and args[1] != correctPin:\n' ' newRetries["pin"] = dbus.Byte(newRetries["pin"] - 1)\n' 'elif args[0] == "pin":\n' ' newRetries["pin"] = dbus.Byte(3)\n' 'self.Set("%(i)s", "Retries", newRetries)\n' 'self.EmitSignal("%(i)s", "PropertyChanged", "sv", ["Retries", newRetries])\n' 'if args[0] == "pin" and args[1] != correctPin:\n' ' class Failed(dbus.exceptions.DBusException):\n' ' _dbus_error_name = "org.ofono.Error.Failed"\n' ' raise Failed("Operation failed")' % {'i': iface}), ('ResetPin', 'sss', '', 'correctPuk = "12345678"\n' 'newRetries = self.Get("%(i)s", "Retries")\n' 'if args[0] == "puk" and args[1] != correctPuk:\n' ' newRetries["puk"] = dbus.Byte(newRetries["puk"] - 1)\n' 'elif args[0] == "puk":\n' ' newRetries["pin"] = dbus.Byte(3)\n' ' newRetries["puk"] = dbus.Byte(10)\n' 'self.Set("%(i)s", "Retries", newRetries)\n' 'self.EmitSignal("%(i)s", "PropertyChanged", "sv", ["Retries", newRetries])\n' 'if args[0] == "puk" and args[1] != correctPuk:\n' ' class Failed(dbus.exceptions.DBusException):\n' ' _dbus_error_name = "org.ofono.Error.Failed"\n' ' raise Failed("Operation failed")' % {'i': iface}), ('LockPin', 'ss', '', ''), ('UnlockPin', 'ss', '', ''), ])
python
def add_simmanager_api(self, mock): '''Add org.ofono.SimManager API to a mock''' iface = 'org.ofono.SimManager' mock.AddProperties(iface, { 'BarredDialing': _parameters.get('BarredDialing', False), 'CardIdentifier': _parameters.get('CardIdentifier', new_iccid(self)), 'FixedDialing': _parameters.get('FixedDialing', False), 'LockedPins': _parameters.get('LockedPins', dbus.Array([], signature='s')), 'MobileCountryCode': _parameters.get('MobileCountryCode', '310'), 'MobileNetworkCode': _parameters.get('MobileNetworkCode', '150'), 'PreferredLanguages': _parameters.get('PreferredLanguages', ['en']), 'Present': _parameters.get('Present', dbus.Boolean(True)), 'Retries': _parameters.get('Retries', dbus.Dictionary([["pin", dbus.Byte(3)], ["puk", dbus.Byte(10)]])), 'PinRequired': _parameters.get('PinRequired', "none"), 'SubscriberNumbers': _parameters.get('SubscriberNumbers', ['123456789', '234567890']), 'SubscriberIdentity': _parameters.get('SubscriberIdentity', new_imsi(self)), }) mock.AddMethods(iface, [ ('GetProperties', '', 'a{sv}', 'ret = self.GetAll("%s")' % iface), ('SetProperty', 'sv', '', 'self.Set("%(i)s", args[0], args[1]); ' 'self.EmitSignal("%(i)s", "PropertyChanged", "sv", [args[0], args[1]])' % {'i': iface}), ('ChangePin', 'sss', '', ''), ('EnterPin', 'ss', '', 'correctPin = "1234"\n' 'newRetries = self.Get("%(i)s", "Retries")\n' 'if args[0] == "pin" and args[1] != correctPin:\n' ' newRetries["pin"] = dbus.Byte(newRetries["pin"] - 1)\n' 'elif args[0] == "pin":\n' ' newRetries["pin"] = dbus.Byte(3)\n' 'self.Set("%(i)s", "Retries", newRetries)\n' 'self.EmitSignal("%(i)s", "PropertyChanged", "sv", ["Retries", newRetries])\n' 'if args[0] == "pin" and args[1] != correctPin:\n' ' class Failed(dbus.exceptions.DBusException):\n' ' _dbus_error_name = "org.ofono.Error.Failed"\n' ' raise Failed("Operation failed")' % {'i': iface}), ('ResetPin', 'sss', '', 'correctPuk = "12345678"\n' 'newRetries = self.Get("%(i)s", "Retries")\n' 'if args[0] == "puk" and args[1] != correctPuk:\n' ' newRetries["puk"] = dbus.Byte(newRetries["puk"] - 1)\n' 'elif args[0] == "puk":\n' ' newRetries["pin"] = dbus.Byte(3)\n' ' newRetries["puk"] = dbus.Byte(10)\n' 'self.Set("%(i)s", "Retries", newRetries)\n' 'self.EmitSignal("%(i)s", "PropertyChanged", "sv", ["Retries", newRetries])\n' 'if args[0] == "puk" and args[1] != correctPuk:\n' ' class Failed(dbus.exceptions.DBusException):\n' ' _dbus_error_name = "org.ofono.Error.Failed"\n' ' raise Failed("Operation failed")' % {'i': iface}), ('LockPin', 'ss', '', ''), ('UnlockPin', 'ss', '', ''), ])
[ "def", "add_simmanager_api", "(", "self", ",", "mock", ")", ":", "iface", "=", "'org.ofono.SimManager'", "mock", ".", "AddProperties", "(", "iface", ",", "{", "'BarredDialing'", ":", "_parameters", ".", "get", "(", "'BarredDialing'", ",", "False", ")", ",", ...
Add org.ofono.SimManager API to a mock
[ "Add", "org", ".", "ofono", ".", "SimManager", "API", "to", "a", "mock" ]
26f65f78bc0ed347233f699a8d6ee0e6880e7eb0
https://github.com/martinpitt/python-dbusmock/blob/26f65f78bc0ed347233f699a8d6ee0e6880e7eb0/dbusmock/templates/ofono.py#L329-L388
train
24,293
martinpitt/python-dbusmock
dbusmock/templates/ofono.py
add_connectionmanager_api
def add_connectionmanager_api(mock): '''Add org.ofono.ConnectionManager API to a mock''' iface = 'org.ofono.ConnectionManager' mock.AddProperties(iface, { 'Attached': _parameters.get('Attached', True), 'Bearer': _parameters.get('Bearer', 'gprs'), 'RoamingAllowed': _parameters.get('RoamingAllowed', False), 'Powered': _parameters.get('ConnectionPowered', True), }) mock.AddMethods(iface, [ ('GetProperties', '', 'a{sv}', 'ret = self.GetAll("%s")' % iface), ('SetProperty', 'sv', '', 'self.Set("%(i)s", args[0], args[1]); ' 'self.EmitSignal("%(i)s", "PropertyChanged", "sv", [args[0], args[1]])' % {'i': iface}), ('AddContext', 's', 'o', 'ret = "/"'), ('RemoveContext', 'o', '', ''), ('DeactivateAll', '', '', ''), ('GetContexts', '', 'a(oa{sv})', 'ret = dbus.Array([])'), ])
python
def add_connectionmanager_api(mock): '''Add org.ofono.ConnectionManager API to a mock''' iface = 'org.ofono.ConnectionManager' mock.AddProperties(iface, { 'Attached': _parameters.get('Attached', True), 'Bearer': _parameters.get('Bearer', 'gprs'), 'RoamingAllowed': _parameters.get('RoamingAllowed', False), 'Powered': _parameters.get('ConnectionPowered', True), }) mock.AddMethods(iface, [ ('GetProperties', '', 'a{sv}', 'ret = self.GetAll("%s")' % iface), ('SetProperty', 'sv', '', 'self.Set("%(i)s", args[0], args[1]); ' 'self.EmitSignal("%(i)s", "PropertyChanged", "sv", [args[0], args[1]])' % {'i': iface}), ('AddContext', 's', 'o', 'ret = "/"'), ('RemoveContext', 'o', '', ''), ('DeactivateAll', '', '', ''), ('GetContexts', '', 'a(oa{sv})', 'ret = dbus.Array([])'), ])
[ "def", "add_connectionmanager_api", "(", "mock", ")", ":", "iface", "=", "'org.ofono.ConnectionManager'", "mock", ".", "AddProperties", "(", "iface", ",", "{", "'Attached'", ":", "_parameters", ".", "get", "(", "'Attached'", ",", "True", ")", ",", "'Bearer'", ...
Add org.ofono.ConnectionManager API to a mock
[ "Add", "org", ".", "ofono", ".", "ConnectionManager", "API", "to", "a", "mock" ]
26f65f78bc0ed347233f699a8d6ee0e6880e7eb0
https://github.com/martinpitt/python-dbusmock/blob/26f65f78bc0ed347233f699a8d6ee0e6880e7eb0/dbusmock/templates/ofono.py#L408-L426
train
24,294
martinpitt/python-dbusmock
dbusmock/templates/bluez5.py
BlockDevice
def BlockDevice(self, adapter_device_name, device_address): '''Convenience method to mark an existing device as blocked. You have to specify a device address which must be a valid Bluetooth address (e.g. 'AA:BB:CC:DD:EE:FF'). The adapter device name is the device_name passed to AddAdapter. This disconnects the device if it was connected. If the specified adapter or device don’t exist, a NoSuchAdapter or NoSuchDevice error will be returned on the bus. Returns nothing. ''' device_name = 'dev_' + device_address.replace(':', '_').upper() adapter_path = '/org/bluez/' + adapter_device_name device_path = adapter_path + '/' + device_name if adapter_path not in mockobject.objects: raise dbus.exceptions.DBusException( 'Adapter %s does not exist.' % adapter_device_name, name=BLUEZ_MOCK_IFACE + '.NoSuchAdapter') if device_path not in mockobject.objects: raise dbus.exceptions.DBusException( 'Device %s does not exist.' % device_name, name=BLUEZ_MOCK_IFACE + '.NoSuchDevice') device = mockobject.objects[device_path] device.props[DEVICE_IFACE]['Blocked'] = dbus.Boolean(True, variant_level=1) device.props[DEVICE_IFACE]['Connected'] = dbus.Boolean(False, variant_level=1) device.EmitSignal(dbus.PROPERTIES_IFACE, 'PropertiesChanged', 'sa{sv}as', [ DEVICE_IFACE, { 'Blocked': dbus.Boolean(True, variant_level=1), 'Connected': dbus.Boolean(False, variant_level=1), }, [], ])
python
def BlockDevice(self, adapter_device_name, device_address): '''Convenience method to mark an existing device as blocked. You have to specify a device address which must be a valid Bluetooth address (e.g. 'AA:BB:CC:DD:EE:FF'). The adapter device name is the device_name passed to AddAdapter. This disconnects the device if it was connected. If the specified adapter or device don’t exist, a NoSuchAdapter or NoSuchDevice error will be returned on the bus. Returns nothing. ''' device_name = 'dev_' + device_address.replace(':', '_').upper() adapter_path = '/org/bluez/' + adapter_device_name device_path = adapter_path + '/' + device_name if adapter_path not in mockobject.objects: raise dbus.exceptions.DBusException( 'Adapter %s does not exist.' % adapter_device_name, name=BLUEZ_MOCK_IFACE + '.NoSuchAdapter') if device_path not in mockobject.objects: raise dbus.exceptions.DBusException( 'Device %s does not exist.' % device_name, name=BLUEZ_MOCK_IFACE + '.NoSuchDevice') device = mockobject.objects[device_path] device.props[DEVICE_IFACE]['Blocked'] = dbus.Boolean(True, variant_level=1) device.props[DEVICE_IFACE]['Connected'] = dbus.Boolean(False, variant_level=1) device.EmitSignal(dbus.PROPERTIES_IFACE, 'PropertiesChanged', 'sa{sv}as', [ DEVICE_IFACE, { 'Blocked': dbus.Boolean(True, variant_level=1), 'Connected': dbus.Boolean(False, variant_level=1), }, [], ])
[ "def", "BlockDevice", "(", "self", ",", "adapter_device_name", ",", "device_address", ")", ":", "device_name", "=", "'dev_'", "+", "device_address", ".", "replace", "(", "':'", ",", "'_'", ")", ".", "upper", "(", ")", "adapter_path", "=", "'/org/bluez/'", "+...
Convenience method to mark an existing device as blocked. You have to specify a device address which must be a valid Bluetooth address (e.g. 'AA:BB:CC:DD:EE:FF'). The adapter device name is the device_name passed to AddAdapter. This disconnects the device if it was connected. If the specified adapter or device don’t exist, a NoSuchAdapter or NoSuchDevice error will be returned on the bus. Returns nothing.
[ "Convenience", "method", "to", "mark", "an", "existing", "device", "as", "blocked", "." ]
26f65f78bc0ed347233f699a8d6ee0e6880e7eb0
https://github.com/martinpitt/python-dbusmock/blob/26f65f78bc0ed347233f699a8d6ee0e6880e7eb0/dbusmock/templates/bluez5.py#L268-L308
train
24,295
briancappello/flask-unchained
flask_unchained/bundles/api/model_resource.py
ModelResource.create
def create(self, instance, errors): """ Create an instance of a model. :param instance: The created model instance. :param errors: Any errors. :return: The created model instance, or a dictionary of errors. """ if errors: return self.errors(errors) return self.created(instance)
python
def create(self, instance, errors): """ Create an instance of a model. :param instance: The created model instance. :param errors: Any errors. :return: The created model instance, or a dictionary of errors. """ if errors: return self.errors(errors) return self.created(instance)
[ "def", "create", "(", "self", ",", "instance", ",", "errors", ")", ":", "if", "errors", ":", "return", "self", ".", "errors", "(", "errors", ")", "return", "self", ".", "created", "(", "instance", ")" ]
Create an instance of a model. :param instance: The created model instance. :param errors: Any errors. :return: The created model instance, or a dictionary of errors.
[ "Create", "an", "instance", "of", "a", "model", "." ]
4d536cb90e2cc4829c1c05f2c74d3e22901a1399
https://github.com/briancappello/flask-unchained/blob/4d536cb90e2cc4829c1c05f2c74d3e22901a1399/flask_unchained/bundles/api/model_resource.py#L300-L310
train
24,296
briancappello/flask-unchained
flask_unchained/bundles/api/model_resource.py
ModelResource.patch
def patch(self, instance, errors): """ Partially update a model instance. :param instance: The model instance. :param errors: Any errors. :return: The updated model instance, or a dictionary of errors. """ if errors: return self.errors(errors) return self.updated(instance)
python
def patch(self, instance, errors): """ Partially update a model instance. :param instance: The model instance. :param errors: Any errors. :return: The updated model instance, or a dictionary of errors. """ if errors: return self.errors(errors) return self.updated(instance)
[ "def", "patch", "(", "self", ",", "instance", ",", "errors", ")", ":", "if", "errors", ":", "return", "self", ".", "errors", "(", "errors", ")", "return", "self", ".", "updated", "(", "instance", ")" ]
Partially update a model instance. :param instance: The model instance. :param errors: Any errors. :return: The updated model instance, or a dictionary of errors.
[ "Partially", "update", "a", "model", "instance", "." ]
4d536cb90e2cc4829c1c05f2c74d3e22901a1399
https://github.com/briancappello/flask-unchained/blob/4d536cb90e2cc4829c1c05f2c74d3e22901a1399/flask_unchained/bundles/api/model_resource.py#L323-L333
train
24,297
briancappello/flask-unchained
flask_unchained/bundles/api/model_resource.py
ModelResource.put
def put(self, instance, errors): """ Update a model instance. :param instance: The model instance. :param errors: Any errors. :return: The updated model instance, or a dictionary of errors. """ if errors: return self.errors(errors) return self.updated(instance)
python
def put(self, instance, errors): """ Update a model instance. :param instance: The model instance. :param errors: Any errors. :return: The updated model instance, or a dictionary of errors. """ if errors: return self.errors(errors) return self.updated(instance)
[ "def", "put", "(", "self", ",", "instance", ",", "errors", ")", ":", "if", "errors", ":", "return", "self", ".", "errors", "(", "errors", ")", "return", "self", ".", "updated", "(", "instance", ")" ]
Update a model instance. :param instance: The model instance. :param errors: Any errors. :return: The updated model instance, or a dictionary of errors.
[ "Update", "a", "model", "instance", "." ]
4d536cb90e2cc4829c1c05f2c74d3e22901a1399
https://github.com/briancappello/flask-unchained/blob/4d536cb90e2cc4829c1c05f2c74d3e22901a1399/flask_unchained/bundles/api/model_resource.py#L336-L346
train
24,298
briancappello/flask-unchained
flask_unchained/bundles/controller/__init__.py
ControllerBundle.before_init_app
def before_init_app(self, app: FlaskUnchained): """ Configure the Jinja environment and template loader. """ from .templates import (UnchainedJinjaEnvironment, UnchainedJinjaLoader) app.jinja_environment = UnchainedJinjaEnvironment app.jinja_options = {**app.jinja_options, 'loader': UnchainedJinjaLoader(app)} app.jinja_env.globals['url_for'] = url_for for name in ['string', 'str']: app.url_map.converters[name] = StringConverter
python
def before_init_app(self, app: FlaskUnchained): """ Configure the Jinja environment and template loader. """ from .templates import (UnchainedJinjaEnvironment, UnchainedJinjaLoader) app.jinja_environment = UnchainedJinjaEnvironment app.jinja_options = {**app.jinja_options, 'loader': UnchainedJinjaLoader(app)} app.jinja_env.globals['url_for'] = url_for for name in ['string', 'str']: app.url_map.converters[name] = StringConverter
[ "def", "before_init_app", "(", "self", ",", "app", ":", "FlaskUnchained", ")", ":", "from", ".", "templates", "import", "(", "UnchainedJinjaEnvironment", ",", "UnchainedJinjaLoader", ")", "app", ".", "jinja_environment", "=", "UnchainedJinjaEnvironment", "app", ".",...
Configure the Jinja environment and template loader.
[ "Configure", "the", "Jinja", "environment", "and", "template", "loader", "." ]
4d536cb90e2cc4829c1c05f2c74d3e22901a1399
https://github.com/briancappello/flask-unchained/blob/4d536cb90e2cc4829c1c05f2c74d3e22901a1399/flask_unchained/bundles/controller/__init__.py#L43-L55
train
24,299