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
python-bugzilla/python-bugzilla
bugzilla/base.py
Bugzilla.logged_in
def logged_in(self): """ This is True if this instance is logged in else False. We test if this session is authenticated by calling the User.get() XMLRPC method with ids set. Logged-out users cannot pass the 'ids' parameter and will result in a 505 error. If we tried to login with a token, but the token was incorrect or expired, the server returns a 32000 error. For Bugzilla 5 and later, a new method, User.valid_login is available to test the validity of the token. However, this will require that the username be cached along with the token in order to work effectively in all scenarios and is not currently used. For more information, refer to the following url. http://bugzilla.readthedocs.org/en/latest/api/core/v1/user.html#valid-login """ try: self._proxy.User.get({'ids': []}) return True except Fault as e: if e.faultCode == 505 or e.faultCode == 32000: return False raise e
python
def logged_in(self): """ This is True if this instance is logged in else False. We test if this session is authenticated by calling the User.get() XMLRPC method with ids set. Logged-out users cannot pass the 'ids' parameter and will result in a 505 error. If we tried to login with a token, but the token was incorrect or expired, the server returns a 32000 error. For Bugzilla 5 and later, a new method, User.valid_login is available to test the validity of the token. However, this will require that the username be cached along with the token in order to work effectively in all scenarios and is not currently used. For more information, refer to the following url. http://bugzilla.readthedocs.org/en/latest/api/core/v1/user.html#valid-login """ try: self._proxy.User.get({'ids': []}) return True except Fault as e: if e.faultCode == 505 or e.faultCode == 32000: return False raise e
[ "def", "logged_in", "(", "self", ")", ":", "try", ":", "self", ".", "_proxy", ".", "User", ".", "get", "(", "{", "'ids'", ":", "[", "]", "}", ")", "return", "True", "except", "Fault", "as", "e", ":", "if", "e", ".", "faultCode", "==", "505", "o...
This is True if this instance is logged in else False. We test if this session is authenticated by calling the User.get() XMLRPC method with ids set. Logged-out users cannot pass the 'ids' parameter and will result in a 505 error. If we tried to login with a token, but the token was incorrect or expired, the server returns a 32000 error. For Bugzilla 5 and later, a new method, User.valid_login is available to test the validity of the token. However, this will require that the username be cached along with the token in order to work effectively in all scenarios and is not currently used. For more information, refer to the following url. http://bugzilla.readthedocs.org/en/latest/api/core/v1/user.html#valid-login
[ "This", "is", "True", "if", "this", "instance", "is", "logged", "in", "else", "False", "." ]
7de8b225104f24a1eee3e837bf1e02d60aefe69f
https://github.com/python-bugzilla/python-bugzilla/blob/7de8b225104f24a1eee3e837bf1e02d60aefe69f/bugzilla/base.py#L658-L682
train
25,100
python-bugzilla/python-bugzilla
bugzilla/base.py
Bugzilla._getbugfields
def _getbugfields(self): """ Get the list of valid fields for Bug objects """ r = self._proxy.Bug.fields({'include_fields': ['name']}) return [f['name'] for f in r['fields']]
python
def _getbugfields(self): """ Get the list of valid fields for Bug objects """ r = self._proxy.Bug.fields({'include_fields': ['name']}) return [f['name'] for f in r['fields']]
[ "def", "_getbugfields", "(", "self", ")", ":", "r", "=", "self", ".", "_proxy", ".", "Bug", ".", "fields", "(", "{", "'include_fields'", ":", "[", "'name'", "]", "}", ")", "return", "[", "f", "[", "'name'", "]", "for", "f", "in", "r", "[", "'fiel...
Get the list of valid fields for Bug objects
[ "Get", "the", "list", "of", "valid", "fields", "for", "Bug", "objects" ]
7de8b225104f24a1eee3e837bf1e02d60aefe69f
https://github.com/python-bugzilla/python-bugzilla/blob/7de8b225104f24a1eee3e837bf1e02d60aefe69f/bugzilla/base.py#L689-L694
train
25,101
python-bugzilla/python-bugzilla
bugzilla/base.py
Bugzilla.getbugfields
def getbugfields(self, force_refresh=False): """ Calls getBugFields, which returns a list of fields in each bug for this bugzilla instance. This can be used to set the list of attrs on the Bug object. """ if force_refresh or not self._cache.bugfields: log.debug("Refreshing bugfields") self._cache.bugfields = self._getbugfields() self._cache.bugfields.sort() log.debug("bugfields = %s", self._cache.bugfields) return self._cache.bugfields
python
def getbugfields(self, force_refresh=False): """ Calls getBugFields, which returns a list of fields in each bug for this bugzilla instance. This can be used to set the list of attrs on the Bug object. """ if force_refresh or not self._cache.bugfields: log.debug("Refreshing bugfields") self._cache.bugfields = self._getbugfields() self._cache.bugfields.sort() log.debug("bugfields = %s", self._cache.bugfields) return self._cache.bugfields
[ "def", "getbugfields", "(", "self", ",", "force_refresh", "=", "False", ")", ":", "if", "force_refresh", "or", "not", "self", ".", "_cache", ".", "bugfields", ":", "log", ".", "debug", "(", "\"Refreshing bugfields\"", ")", "self", ".", "_cache", ".", "bugf...
Calls getBugFields, which returns a list of fields in each bug for this bugzilla instance. This can be used to set the list of attrs on the Bug object.
[ "Calls", "getBugFields", "which", "returns", "a", "list", "of", "fields", "in", "each", "bug", "for", "this", "bugzilla", "instance", ".", "This", "can", "be", "used", "to", "set", "the", "list", "of", "attrs", "on", "the", "Bug", "object", "." ]
7de8b225104f24a1eee3e837bf1e02d60aefe69f
https://github.com/python-bugzilla/python-bugzilla/blob/7de8b225104f24a1eee3e837bf1e02d60aefe69f/bugzilla/base.py#L696-L708
train
25,102
python-bugzilla/python-bugzilla
bugzilla/base.py
Bugzilla.refresh_products
def refresh_products(self, **kwargs): """ Refresh a product's cached info. Basically calls product_get with the passed arguments, and tries to intelligently update our product cache. For example, if we already have cached info for product=foo, and you pass in names=["bar", "baz"], the new cache will have info for products foo, bar, baz. Individual product fields are also updated. """ for product in self.product_get(**kwargs): updated = False for current in self._cache.products[:]: if (current.get("id", -1) != product.get("id", -2) and current.get("name", -1) != product.get("name", -2)): continue _nested_update(current, product) updated = True break if not updated: self._cache.products.append(product)
python
def refresh_products(self, **kwargs): """ Refresh a product's cached info. Basically calls product_get with the passed arguments, and tries to intelligently update our product cache. For example, if we already have cached info for product=foo, and you pass in names=["bar", "baz"], the new cache will have info for products foo, bar, baz. Individual product fields are also updated. """ for product in self.product_get(**kwargs): updated = False for current in self._cache.products[:]: if (current.get("id", -1) != product.get("id", -2) and current.get("name", -1) != product.get("name", -2)): continue _nested_update(current, product) updated = True break if not updated: self._cache.products.append(product)
[ "def", "refresh_products", "(", "self", ",", "*", "*", "kwargs", ")", ":", "for", "product", "in", "self", ".", "product_get", "(", "*", "*", "kwargs", ")", ":", "updated", "=", "False", "for", "current", "in", "self", ".", "_cache", ".", "products", ...
Refresh a product's cached info. Basically calls product_get with the passed arguments, and tries to intelligently update our product cache. For example, if we already have cached info for product=foo, and you pass in names=["bar", "baz"], the new cache will have info for products foo, bar, baz. Individual product fields are also updated.
[ "Refresh", "a", "product", "s", "cached", "info", ".", "Basically", "calls", "product_get", "with", "the", "passed", "arguments", "and", "tries", "to", "intelligently", "update", "our", "product", "cache", "." ]
7de8b225104f24a1eee3e837bf1e02d60aefe69f
https://github.com/python-bugzilla/python-bugzilla/blob/7de8b225104f24a1eee3e837bf1e02d60aefe69f/bugzilla/base.py#L765-L787
train
25,103
python-bugzilla/python-bugzilla
bugzilla/base.py
Bugzilla.getproducts
def getproducts(self, force_refresh=False, **kwargs): """ Query all products and return the raw dict info. Takes all the same arguments as product_get. On first invocation this will contact bugzilla and internally cache the results. Subsequent getproducts calls or accesses to self.products will return this cached data only. :param force_refresh: force refreshing via refresh_products() """ if force_refresh or not self._cache.products: self.refresh_products(**kwargs) return self._cache.products
python
def getproducts(self, force_refresh=False, **kwargs): """ Query all products and return the raw dict info. Takes all the same arguments as product_get. On first invocation this will contact bugzilla and internally cache the results. Subsequent getproducts calls or accesses to self.products will return this cached data only. :param force_refresh: force refreshing via refresh_products() """ if force_refresh or not self._cache.products: self.refresh_products(**kwargs) return self._cache.products
[ "def", "getproducts", "(", "self", ",", "force_refresh", "=", "False", ",", "*", "*", "kwargs", ")", ":", "if", "force_refresh", "or", "not", "self", ".", "_cache", ".", "products", ":", "self", ".", "refresh_products", "(", "*", "*", "kwargs", ")", "r...
Query all products and return the raw dict info. Takes all the same arguments as product_get. On first invocation this will contact bugzilla and internally cache the results. Subsequent getproducts calls or accesses to self.products will return this cached data only. :param force_refresh: force refreshing via refresh_products()
[ "Query", "all", "products", "and", "return", "the", "raw", "dict", "info", ".", "Takes", "all", "the", "same", "arguments", "as", "product_get", "." ]
7de8b225104f24a1eee3e837bf1e02d60aefe69f
https://github.com/python-bugzilla/python-bugzilla/blob/7de8b225104f24a1eee3e837bf1e02d60aefe69f/bugzilla/base.py#L789-L802
train
25,104
python-bugzilla/python-bugzilla
bugzilla/base.py
Bugzilla.getcomponentdetails
def getcomponentdetails(self, product, component, force_refresh=False): """ Helper for accessing a single component's info. This is a wrapper around getcomponentsdetails, see that for explanation """ d = self.getcomponentsdetails(product, force_refresh) return d[component]
python
def getcomponentdetails(self, product, component, force_refresh=False): """ Helper for accessing a single component's info. This is a wrapper around getcomponentsdetails, see that for explanation """ d = self.getcomponentsdetails(product, force_refresh) return d[component]
[ "def", "getcomponentdetails", "(", "self", ",", "product", ",", "component", ",", "force_refresh", "=", "False", ")", ":", "d", "=", "self", ".", "getcomponentsdetails", "(", "product", ",", "force_refresh", ")", "return", "d", "[", "component", "]" ]
Helper for accessing a single component's info. This is a wrapper around getcomponentsdetails, see that for explanation
[ "Helper", "for", "accessing", "a", "single", "component", "s", "info", ".", "This", "is", "a", "wrapper", "around", "getcomponentsdetails", "see", "that", "for", "explanation" ]
7de8b225104f24a1eee3e837bf1e02d60aefe69f
https://github.com/python-bugzilla/python-bugzilla/blob/7de8b225104f24a1eee3e837bf1e02d60aefe69f/bugzilla/base.py#L851-L857
train
25,105
python-bugzilla/python-bugzilla
bugzilla/base.py
Bugzilla.getcomponents
def getcomponents(self, product, force_refresh=False): """ Return a list of component names for the passed product. This can be implemented with Product.get, but behind the scenes it uses Bug.legal_values. Reason being that on bugzilla instances with tons of components, like bugzilla.redhat.com Product=Fedora for example, there's a 10x speed difference even with properly limited Product.get calls. On first invocation the value is cached, and subsequent calls will return the cached data. :param force_refresh: Force refreshing the cache, and return the new data """ proddict = self._lookup_product_in_cache(product) product_id = proddict.get("id", None) if (force_refresh or product_id is None or product_id not in self._cache.component_names): self.refresh_products(names=[product], include_fields=["name", "id"]) proddict = self._lookup_product_in_cache(product) if "id" not in proddict: raise BugzillaError("Product '%s' not found" % product) product_id = proddict["id"] opts = {'product_id': product_id, 'field': 'component'} names = self._proxy.Bug.legal_values(opts)["values"] self._cache.component_names[product_id] = names return self._cache.component_names[product_id]
python
def getcomponents(self, product, force_refresh=False): """ Return a list of component names for the passed product. This can be implemented with Product.get, but behind the scenes it uses Bug.legal_values. Reason being that on bugzilla instances with tons of components, like bugzilla.redhat.com Product=Fedora for example, there's a 10x speed difference even with properly limited Product.get calls. On first invocation the value is cached, and subsequent calls will return the cached data. :param force_refresh: Force refreshing the cache, and return the new data """ proddict = self._lookup_product_in_cache(product) product_id = proddict.get("id", None) if (force_refresh or product_id is None or product_id not in self._cache.component_names): self.refresh_products(names=[product], include_fields=["name", "id"]) proddict = self._lookup_product_in_cache(product) if "id" not in proddict: raise BugzillaError("Product '%s' not found" % product) product_id = proddict["id"] opts = {'product_id': product_id, 'field': 'component'} names = self._proxy.Bug.legal_values(opts)["values"] self._cache.component_names[product_id] = names return self._cache.component_names[product_id]
[ "def", "getcomponents", "(", "self", ",", "product", ",", "force_refresh", "=", "False", ")", ":", "proddict", "=", "self", ".", "_lookup_product_in_cache", "(", "product", ")", "product_id", "=", "proddict", ".", "get", "(", "\"id\"", ",", "None", ")", "i...
Return a list of component names for the passed product. This can be implemented with Product.get, but behind the scenes it uses Bug.legal_values. Reason being that on bugzilla instances with tons of components, like bugzilla.redhat.com Product=Fedora for example, there's a 10x speed difference even with properly limited Product.get calls. On first invocation the value is cached, and subsequent calls will return the cached data. :param force_refresh: Force refreshing the cache, and return the new data
[ "Return", "a", "list", "of", "component", "names", "for", "the", "passed", "product", "." ]
7de8b225104f24a1eee3e837bf1e02d60aefe69f
https://github.com/python-bugzilla/python-bugzilla/blob/7de8b225104f24a1eee3e837bf1e02d60aefe69f/bugzilla/base.py#L859-L892
train
25,106
python-bugzilla/python-bugzilla
bugzilla/base.py
Bugzilla._process_include_fields
def _process_include_fields(self, include_fields, exclude_fields, extra_fields): """ Internal helper to process include_fields lists """ def _convert_fields(_in): if not _in: return _in for newname, oldname in self._get_api_aliases(): if oldname in _in: _in.remove(oldname) if newname not in _in: _in.append(newname) return _in ret = {} if self._check_version(4, 0): if include_fields: include_fields = _convert_fields(include_fields) if "id" not in include_fields: include_fields.append("id") ret["include_fields"] = include_fields if exclude_fields: exclude_fields = _convert_fields(exclude_fields) ret["exclude_fields"] = exclude_fields if self._supports_getbug_extra_fields: if extra_fields: ret["extra_fields"] = _convert_fields(extra_fields) return ret
python
def _process_include_fields(self, include_fields, exclude_fields, extra_fields): """ Internal helper to process include_fields lists """ def _convert_fields(_in): if not _in: return _in for newname, oldname in self._get_api_aliases(): if oldname in _in: _in.remove(oldname) if newname not in _in: _in.append(newname) return _in ret = {} if self._check_version(4, 0): if include_fields: include_fields = _convert_fields(include_fields) if "id" not in include_fields: include_fields.append("id") ret["include_fields"] = include_fields if exclude_fields: exclude_fields = _convert_fields(exclude_fields) ret["exclude_fields"] = exclude_fields if self._supports_getbug_extra_fields: if extra_fields: ret["extra_fields"] = _convert_fields(extra_fields) return ret
[ "def", "_process_include_fields", "(", "self", ",", "include_fields", ",", "exclude_fields", ",", "extra_fields", ")", ":", "def", "_convert_fields", "(", "_in", ")", ":", "if", "not", "_in", ":", "return", "_in", "for", "newname", ",", "oldname", "in", "sel...
Internal helper to process include_fields lists
[ "Internal", "helper", "to", "process", "include_fields", "lists" ]
7de8b225104f24a1eee3e837bf1e02d60aefe69f
https://github.com/python-bugzilla/python-bugzilla/blob/7de8b225104f24a1eee3e837bf1e02d60aefe69f/bugzilla/base.py#L958-L987
train
25,107
python-bugzilla/python-bugzilla
bugzilla/base.py
Bugzilla._getbugs
def _getbugs(self, idlist, permissive, include_fields=None, exclude_fields=None, extra_fields=None): """ Return a list of dicts of full bug info for each given bug id. bug ids that couldn't be found will return None instead of a dict. """ oldidlist = idlist idlist = [] for i in oldidlist: try: idlist.append(int(i)) except ValueError: # String aliases can be passed as well idlist.append(i) extra_fields = self._listify(extra_fields or []) extra_fields += self._getbug_extra_fields getbugdata = {"ids": idlist} if permissive: getbugdata["permissive"] = 1 getbugdata.update(self._process_include_fields( include_fields, exclude_fields, extra_fields)) r = self._proxy.Bug.get(getbugdata) if self._check_version(4, 0): bugdict = dict([(b['id'], b) for b in r['bugs']]) else: bugdict = dict([(b['id'], b['internals']) for b in r['bugs']]) ret = [] for i in idlist: found = None if i in bugdict: found = bugdict[i] else: # Need to map an alias for valdict in bugdict.values(): if i in self._listify(valdict.get("alias", None)): found = valdict break ret.append(found) return ret
python
def _getbugs(self, idlist, permissive, include_fields=None, exclude_fields=None, extra_fields=None): """ Return a list of dicts of full bug info for each given bug id. bug ids that couldn't be found will return None instead of a dict. """ oldidlist = idlist idlist = [] for i in oldidlist: try: idlist.append(int(i)) except ValueError: # String aliases can be passed as well idlist.append(i) extra_fields = self._listify(extra_fields or []) extra_fields += self._getbug_extra_fields getbugdata = {"ids": idlist} if permissive: getbugdata["permissive"] = 1 getbugdata.update(self._process_include_fields( include_fields, exclude_fields, extra_fields)) r = self._proxy.Bug.get(getbugdata) if self._check_version(4, 0): bugdict = dict([(b['id'], b) for b in r['bugs']]) else: bugdict = dict([(b['id'], b['internals']) for b in r['bugs']]) ret = [] for i in idlist: found = None if i in bugdict: found = bugdict[i] else: # Need to map an alias for valdict in bugdict.values(): if i in self._listify(valdict.get("alias", None)): found = valdict break ret.append(found) return ret
[ "def", "_getbugs", "(", "self", ",", "idlist", ",", "permissive", ",", "include_fields", "=", "None", ",", "exclude_fields", "=", "None", ",", "extra_fields", "=", "None", ")", ":", "oldidlist", "=", "idlist", "idlist", "=", "[", "]", "for", "i", "in", ...
Return a list of dicts of full bug info for each given bug id. bug ids that couldn't be found will return None instead of a dict.
[ "Return", "a", "list", "of", "dicts", "of", "full", "bug", "info", "for", "each", "given", "bug", "id", ".", "bug", "ids", "that", "couldn", "t", "be", "found", "will", "return", "None", "instead", "of", "a", "dict", "." ]
7de8b225104f24a1eee3e837bf1e02d60aefe69f
https://github.com/python-bugzilla/python-bugzilla/blob/7de8b225104f24a1eee3e837bf1e02d60aefe69f/bugzilla/base.py#L1010-L1056
train
25,108
python-bugzilla/python-bugzilla
bugzilla/base.py
Bugzilla._getbug
def _getbug(self, objid, **kwargs): """ Thin wrapper around _getbugs to handle the slight argument tweaks for fetching a single bug. The main bit is permissive=False, which will tell bugzilla to raise an explicit error if we can't fetch that bug. This logic is called from Bug() too """ return self._getbugs([objid], permissive=False, **kwargs)[0]
python
def _getbug(self, objid, **kwargs): """ Thin wrapper around _getbugs to handle the slight argument tweaks for fetching a single bug. The main bit is permissive=False, which will tell bugzilla to raise an explicit error if we can't fetch that bug. This logic is called from Bug() too """ return self._getbugs([objid], permissive=False, **kwargs)[0]
[ "def", "_getbug", "(", "self", ",", "objid", ",", "*", "*", "kwargs", ")", ":", "return", "self", ".", "_getbugs", "(", "[", "objid", "]", ",", "permissive", "=", "False", ",", "*", "*", "kwargs", ")", "[", "0", "]" ]
Thin wrapper around _getbugs to handle the slight argument tweaks for fetching a single bug. The main bit is permissive=False, which will tell bugzilla to raise an explicit error if we can't fetch that bug. This logic is called from Bug() too
[ "Thin", "wrapper", "around", "_getbugs", "to", "handle", "the", "slight", "argument", "tweaks", "for", "fetching", "a", "single", "bug", ".", "The", "main", "bit", "is", "permissive", "=", "False", "which", "will", "tell", "bugzilla", "to", "raise", "an", ...
7de8b225104f24a1eee3e837bf1e02d60aefe69f
https://github.com/python-bugzilla/python-bugzilla/blob/7de8b225104f24a1eee3e837bf1e02d60aefe69f/bugzilla/base.py#L1058-L1067
train
25,109
python-bugzilla/python-bugzilla
bugzilla/base.py
Bugzilla.getbug
def getbug(self, objid, include_fields=None, exclude_fields=None, extra_fields=None): """ Return a Bug object with the full complement of bug data already loaded. """ data = self._getbug(objid, include_fields=include_fields, exclude_fields=exclude_fields, extra_fields=extra_fields) return Bug(self, dict=data, autorefresh=self.bug_autorefresh)
python
def getbug(self, objid, include_fields=None, exclude_fields=None, extra_fields=None): """ Return a Bug object with the full complement of bug data already loaded. """ data = self._getbug(objid, include_fields=include_fields, exclude_fields=exclude_fields, extra_fields=extra_fields) return Bug(self, dict=data, autorefresh=self.bug_autorefresh)
[ "def", "getbug", "(", "self", ",", "objid", ",", "include_fields", "=", "None", ",", "exclude_fields", "=", "None", ",", "extra_fields", "=", "None", ")", ":", "data", "=", "self", ".", "_getbug", "(", "objid", ",", "include_fields", "=", "include_fields",...
Return a Bug object with the full complement of bug data already loaded.
[ "Return", "a", "Bug", "object", "with", "the", "full", "complement", "of", "bug", "data", "already", "loaded", "." ]
7de8b225104f24a1eee3e837bf1e02d60aefe69f
https://github.com/python-bugzilla/python-bugzilla/blob/7de8b225104f24a1eee3e837bf1e02d60aefe69f/bugzilla/base.py#L1069-L1078
train
25,110
python-bugzilla/python-bugzilla
bugzilla/base.py
Bugzilla.getbugs
def getbugs(self, idlist, include_fields=None, exclude_fields=None, extra_fields=None, permissive=True): """ Return a list of Bug objects with the full complement of bug data already loaded. If there's a problem getting the data for a given id, the corresponding item in the returned list will be None. """ data = self._getbugs(idlist, include_fields=include_fields, exclude_fields=exclude_fields, extra_fields=extra_fields, permissive=permissive) return [(b and Bug(self, dict=b, autorefresh=self.bug_autorefresh)) or None for b in data]
python
def getbugs(self, idlist, include_fields=None, exclude_fields=None, extra_fields=None, permissive=True): """ Return a list of Bug objects with the full complement of bug data already loaded. If there's a problem getting the data for a given id, the corresponding item in the returned list will be None. """ data = self._getbugs(idlist, include_fields=include_fields, exclude_fields=exclude_fields, extra_fields=extra_fields, permissive=permissive) return [(b and Bug(self, dict=b, autorefresh=self.bug_autorefresh)) or None for b in data]
[ "def", "getbugs", "(", "self", ",", "idlist", ",", "include_fields", "=", "None", ",", "exclude_fields", "=", "None", ",", "extra_fields", "=", "None", ",", "permissive", "=", "True", ")", ":", "data", "=", "self", ".", "_getbugs", "(", "idlist", ",", ...
Return a list of Bug objects with the full complement of bug data already loaded. If there's a problem getting the data for a given id, the corresponding item in the returned list will be None.
[ "Return", "a", "list", "of", "Bug", "objects", "with", "the", "full", "complement", "of", "bug", "data", "already", "loaded", ".", "If", "there", "s", "a", "problem", "getting", "the", "data", "for", "a", "given", "id", "the", "corresponding", "item", "i...
7de8b225104f24a1eee3e837bf1e02d60aefe69f
https://github.com/python-bugzilla/python-bugzilla/blob/7de8b225104f24a1eee3e837bf1e02d60aefe69f/bugzilla/base.py#L1080-L1093
train
25,111
python-bugzilla/python-bugzilla
bugzilla/base.py
Bugzilla.update_tags
def update_tags(self, idlist, tags_add=None, tags_remove=None): """ Updates the 'tags' field for a bug. """ tags = {} if tags_add: tags["add"] = self._listify(tags_add) if tags_remove: tags["remove"] = self._listify(tags_remove) d = { "ids": self._listify(idlist), "tags": tags, } return self._proxy.Bug.update_tags(d)
python
def update_tags(self, idlist, tags_add=None, tags_remove=None): """ Updates the 'tags' field for a bug. """ tags = {} if tags_add: tags["add"] = self._listify(tags_add) if tags_remove: tags["remove"] = self._listify(tags_remove) d = { "ids": self._listify(idlist), "tags": tags, } return self._proxy.Bug.update_tags(d)
[ "def", "update_tags", "(", "self", ",", "idlist", ",", "tags_add", "=", "None", ",", "tags_remove", "=", "None", ")", ":", "tags", "=", "{", "}", "if", "tags_add", ":", "tags", "[", "\"add\"", "]", "=", "self", ".", "_listify", "(", "tags_add", ")", ...
Updates the 'tags' field for a bug.
[ "Updates", "the", "tags", "field", "for", "a", "bug", "." ]
7de8b225104f24a1eee3e837bf1e02d60aefe69f
https://github.com/python-bugzilla/python-bugzilla/blob/7de8b225104f24a1eee3e837bf1e02d60aefe69f/bugzilla/base.py#L1328-L1343
train
25,112
python-bugzilla/python-bugzilla
bugzilla/base.py
Bugzilla._attachment_uri
def _attachment_uri(self, attachid): """ Returns the URI for the given attachment ID. """ att_uri = self.url.replace('xmlrpc.cgi', 'attachment.cgi') att_uri = att_uri + '?id=%s' % attachid return att_uri
python
def _attachment_uri(self, attachid): """ Returns the URI for the given attachment ID. """ att_uri = self.url.replace('xmlrpc.cgi', 'attachment.cgi') att_uri = att_uri + '?id=%s' % attachid return att_uri
[ "def", "_attachment_uri", "(", "self", ",", "attachid", ")", ":", "att_uri", "=", "self", ".", "url", ".", "replace", "(", "'xmlrpc.cgi'", ",", "'attachment.cgi'", ")", "att_uri", "=", "att_uri", "+", "'?id=%s'", "%", "attachid", "return", "att_uri" ]
Returns the URI for the given attachment ID.
[ "Returns", "the", "URI", "for", "the", "given", "attachment", "ID", "." ]
7de8b225104f24a1eee3e837bf1e02d60aefe69f
https://github.com/python-bugzilla/python-bugzilla/blob/7de8b225104f24a1eee3e837bf1e02d60aefe69f/bugzilla/base.py#L1501-L1507
train
25,113
python-bugzilla/python-bugzilla
bugzilla/base.py
Bugzilla.attachfile
def attachfile(self, idlist, attachfile, description, **kwargs): """ Attach a file to the given bug IDs. Returns the ID of the attachment or raises XMLRPC Fault if something goes wrong. attachfile may be a filename (which will be opened) or a file-like object, which must provide a 'read' method. If it's not one of these, this method will raise a TypeError. description is the short description of this attachment. Optional keyword args are as follows: file_name: this will be used as the filename for the attachment. REQUIRED if attachfile is a file-like object with no 'name' attribute, otherwise the filename or .name attribute will be used. comment: An optional comment about this attachment. is_private: Set to True if the attachment should be marked private. is_patch: Set to True if the attachment is a patch. content_type: The mime-type of the attached file. Defaults to application/octet-stream if not set. NOTE that text files will *not* be viewable in bugzilla unless you remember to set this to text/plain. So remember that! Returns the list of attachment ids that were added. If only one attachment was added, we return the single int ID for back compat """ if isinstance(attachfile, str): f = open(attachfile, "rb") elif hasattr(attachfile, 'read'): f = attachfile else: raise TypeError("attachfile must be filename or file-like object") # Back compat if "contenttype" in kwargs: kwargs["content_type"] = kwargs.pop("contenttype") if "ispatch" in kwargs: kwargs["is_patch"] = kwargs.pop("ispatch") if "isprivate" in kwargs: kwargs["is_private"] = kwargs.pop("isprivate") if "filename" in kwargs: kwargs["file_name"] = kwargs.pop("filename") kwargs['summary'] = description data = f.read() if not isinstance(data, bytes): data = data.encode(locale.getpreferredencoding()) kwargs['data'] = Binary(data) kwargs['ids'] = self._listify(idlist) if 'file_name' not in kwargs and hasattr(f, "name"): kwargs['file_name'] = os.path.basename(f.name) if 'content_type' not in kwargs: ctype = None if kwargs['file_name']: ctype = mimetypes.guess_type( kwargs['file_name'], strict=False)[0] kwargs['content_type'] = ctype or 'application/octet-stream' ret = self._proxy.Bug.add_attachment(kwargs) if "attachments" in ret: # Up to BZ 4.2 ret = [int(k) for k in ret["attachments"].keys()] elif "ids" in ret: # BZ 4.4+ ret = ret["ids"] if isinstance(ret, list) and len(ret) == 1: ret = ret[0] return ret
python
def attachfile(self, idlist, attachfile, description, **kwargs): """ Attach a file to the given bug IDs. Returns the ID of the attachment or raises XMLRPC Fault if something goes wrong. attachfile may be a filename (which will be opened) or a file-like object, which must provide a 'read' method. If it's not one of these, this method will raise a TypeError. description is the short description of this attachment. Optional keyword args are as follows: file_name: this will be used as the filename for the attachment. REQUIRED if attachfile is a file-like object with no 'name' attribute, otherwise the filename or .name attribute will be used. comment: An optional comment about this attachment. is_private: Set to True if the attachment should be marked private. is_patch: Set to True if the attachment is a patch. content_type: The mime-type of the attached file. Defaults to application/octet-stream if not set. NOTE that text files will *not* be viewable in bugzilla unless you remember to set this to text/plain. So remember that! Returns the list of attachment ids that were added. If only one attachment was added, we return the single int ID for back compat """ if isinstance(attachfile, str): f = open(attachfile, "rb") elif hasattr(attachfile, 'read'): f = attachfile else: raise TypeError("attachfile must be filename or file-like object") # Back compat if "contenttype" in kwargs: kwargs["content_type"] = kwargs.pop("contenttype") if "ispatch" in kwargs: kwargs["is_patch"] = kwargs.pop("ispatch") if "isprivate" in kwargs: kwargs["is_private"] = kwargs.pop("isprivate") if "filename" in kwargs: kwargs["file_name"] = kwargs.pop("filename") kwargs['summary'] = description data = f.read() if not isinstance(data, bytes): data = data.encode(locale.getpreferredencoding()) kwargs['data'] = Binary(data) kwargs['ids'] = self._listify(idlist) if 'file_name' not in kwargs and hasattr(f, "name"): kwargs['file_name'] = os.path.basename(f.name) if 'content_type' not in kwargs: ctype = None if kwargs['file_name']: ctype = mimetypes.guess_type( kwargs['file_name'], strict=False)[0] kwargs['content_type'] = ctype or 'application/octet-stream' ret = self._proxy.Bug.add_attachment(kwargs) if "attachments" in ret: # Up to BZ 4.2 ret = [int(k) for k in ret["attachments"].keys()] elif "ids" in ret: # BZ 4.4+ ret = ret["ids"] if isinstance(ret, list) and len(ret) == 1: ret = ret[0] return ret
[ "def", "attachfile", "(", "self", ",", "idlist", ",", "attachfile", ",", "description", ",", "*", "*", "kwargs", ")", ":", "if", "isinstance", "(", "attachfile", ",", "str", ")", ":", "f", "=", "open", "(", "attachfile", ",", "\"rb\"", ")", "elif", "...
Attach a file to the given bug IDs. Returns the ID of the attachment or raises XMLRPC Fault if something goes wrong. attachfile may be a filename (which will be opened) or a file-like object, which must provide a 'read' method. If it's not one of these, this method will raise a TypeError. description is the short description of this attachment. Optional keyword args are as follows: file_name: this will be used as the filename for the attachment. REQUIRED if attachfile is a file-like object with no 'name' attribute, otherwise the filename or .name attribute will be used. comment: An optional comment about this attachment. is_private: Set to True if the attachment should be marked private. is_patch: Set to True if the attachment is a patch. content_type: The mime-type of the attached file. Defaults to application/octet-stream if not set. NOTE that text files will *not* be viewable in bugzilla unless you remember to set this to text/plain. So remember that! Returns the list of attachment ids that were added. If only one attachment was added, we return the single int ID for back compat
[ "Attach", "a", "file", "to", "the", "given", "bug", "IDs", ".", "Returns", "the", "ID", "of", "the", "attachment", "or", "raises", "XMLRPC", "Fault", "if", "something", "goes", "wrong", "." ]
7de8b225104f24a1eee3e837bf1e02d60aefe69f
https://github.com/python-bugzilla/python-bugzilla/blob/7de8b225104f24a1eee3e837bf1e02d60aefe69f/bugzilla/base.py#L1509-L1581
train
25,114
python-bugzilla/python-bugzilla
bugzilla/base.py
Bugzilla.openattachment
def openattachment(self, attachid): """ Get the contents of the attachment with the given attachment ID. Returns a file-like object. """ attachments = self.get_attachments(None, attachid) data = attachments["attachments"][str(attachid)] xmlrpcbinary = data["data"] ret = BytesIO() ret.write(xmlrpcbinary.data) ret.name = data["file_name"] ret.seek(0) return ret
python
def openattachment(self, attachid): """ Get the contents of the attachment with the given attachment ID. Returns a file-like object. """ attachments = self.get_attachments(None, attachid) data = attachments["attachments"][str(attachid)] xmlrpcbinary = data["data"] ret = BytesIO() ret.write(xmlrpcbinary.data) ret.name = data["file_name"] ret.seek(0) return ret
[ "def", "openattachment", "(", "self", ",", "attachid", ")", ":", "attachments", "=", "self", ".", "get_attachments", "(", "None", ",", "attachid", ")", "data", "=", "attachments", "[", "\"attachments\"", "]", "[", "str", "(", "attachid", ")", "]", "xmlrpcb...
Get the contents of the attachment with the given attachment ID. Returns a file-like object.
[ "Get", "the", "contents", "of", "the", "attachment", "with", "the", "given", "attachment", "ID", ".", "Returns", "a", "file", "-", "like", "object", "." ]
7de8b225104f24a1eee3e837bf1e02d60aefe69f
https://github.com/python-bugzilla/python-bugzilla/blob/7de8b225104f24a1eee3e837bf1e02d60aefe69f/bugzilla/base.py#L1584-L1597
train
25,115
python-bugzilla/python-bugzilla
bugzilla/base.py
Bugzilla.get_attachments
def get_attachments(self, ids, attachment_ids, include_fields=None, exclude_fields=None): """ Wrapper for Bug.attachments. One of ids or attachment_ids is required :param ids: Get attachments for this bug ID :param attachment_ids: Specific attachment ID to get https://bugzilla.readthedocs.io/en/latest/api/core/v1/attachment.html#get-attachment """ params = { "ids": self._listify(ids) or [], "attachment_ids": self._listify(attachment_ids) or [], } if include_fields: params["include_fields"] = self._listify(include_fields) if exclude_fields: params["exclude_fields"] = self._listify(exclude_fields) return self._proxy.Bug.attachments(params)
python
def get_attachments(self, ids, attachment_ids, include_fields=None, exclude_fields=None): """ Wrapper for Bug.attachments. One of ids or attachment_ids is required :param ids: Get attachments for this bug ID :param attachment_ids: Specific attachment ID to get https://bugzilla.readthedocs.io/en/latest/api/core/v1/attachment.html#get-attachment """ params = { "ids": self._listify(ids) or [], "attachment_ids": self._listify(attachment_ids) or [], } if include_fields: params["include_fields"] = self._listify(include_fields) if exclude_fields: params["exclude_fields"] = self._listify(exclude_fields) return self._proxy.Bug.attachments(params)
[ "def", "get_attachments", "(", "self", ",", "ids", ",", "attachment_ids", ",", "include_fields", "=", "None", ",", "exclude_fields", "=", "None", ")", ":", "params", "=", "{", "\"ids\"", ":", "self", ".", "_listify", "(", "ids", ")", "or", "[", "]", ",...
Wrapper for Bug.attachments. One of ids or attachment_ids is required :param ids: Get attachments for this bug ID :param attachment_ids: Specific attachment ID to get https://bugzilla.readthedocs.io/en/latest/api/core/v1/attachment.html#get-attachment
[ "Wrapper", "for", "Bug", ".", "attachments", ".", "One", "of", "ids", "or", "attachment_ids", "is", "required" ]
7de8b225104f24a1eee3e837bf1e02d60aefe69f
https://github.com/python-bugzilla/python-bugzilla/blob/7de8b225104f24a1eee3e837bf1e02d60aefe69f/bugzilla/base.py#L1616-L1635
train
25,116
python-bugzilla/python-bugzilla
bugzilla/base.py
Bugzilla.createbug
def createbug(self, *args, **kwargs): """ Create a bug with the given info. Returns a new Bug object. Check bugzilla API documentation for valid values, at least product, component, summary, version, and description need to be passed. """ data = self._validate_createbug(*args, **kwargs) rawbug = self._proxy.Bug.create(data) return Bug(self, bug_id=rawbug["id"], autorefresh=self.bug_autorefresh)
python
def createbug(self, *args, **kwargs): """ Create a bug with the given info. Returns a new Bug object. Check bugzilla API documentation for valid values, at least product, component, summary, version, and description need to be passed. """ data = self._validate_createbug(*args, **kwargs) rawbug = self._proxy.Bug.create(data) return Bug(self, bug_id=rawbug["id"], autorefresh=self.bug_autorefresh)
[ "def", "createbug", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "data", "=", "self", ".", "_validate_createbug", "(", "*", "args", ",", "*", "*", "kwargs", ")", "rawbug", "=", "self", ".", "_proxy", ".", "Bug", ".", "create", ...
Create a bug with the given info. Returns a new Bug object. Check bugzilla API documentation for valid values, at least product, component, summary, version, and description need to be passed.
[ "Create", "a", "bug", "with", "the", "given", "info", ".", "Returns", "a", "new", "Bug", "object", ".", "Check", "bugzilla", "API", "documentation", "for", "valid", "values", "at", "least", "product", "component", "summary", "version", "and", "description", ...
7de8b225104f24a1eee3e837bf1e02d60aefe69f
https://github.com/python-bugzilla/python-bugzilla/blob/7de8b225104f24a1eee3e837bf1e02d60aefe69f/bugzilla/base.py#L1739-L1749
train
25,117
python-bugzilla/python-bugzilla
bugzilla/base.py
Bugzilla._getusers
def _getusers(self, ids=None, names=None, match=None): """ Return a list of users that match criteria. :kwarg ids: list of user ids to return data on :kwarg names: list of user names to return data on :kwarg match: list of patterns. Returns users whose real name or login name match the pattern. :raises XMLRPC Fault: Code 51: if a Bad Login Name was sent to the names array. Code 304: if the user was not authorized to see user they requested. Code 505: user is logged out and can't use the match or ids parameter. Available in Bugzilla-3.4+ """ params = {} if ids: params['ids'] = self._listify(ids) if names: params['names'] = self._listify(names) if match: params['match'] = self._listify(match) if not params: raise BugzillaError('_get() needs one of ids, ' ' names, or match kwarg.') return self._proxy.User.get(params)
python
def _getusers(self, ids=None, names=None, match=None): """ Return a list of users that match criteria. :kwarg ids: list of user ids to return data on :kwarg names: list of user names to return data on :kwarg match: list of patterns. Returns users whose real name or login name match the pattern. :raises XMLRPC Fault: Code 51: if a Bad Login Name was sent to the names array. Code 304: if the user was not authorized to see user they requested. Code 505: user is logged out and can't use the match or ids parameter. Available in Bugzilla-3.4+ """ params = {} if ids: params['ids'] = self._listify(ids) if names: params['names'] = self._listify(names) if match: params['match'] = self._listify(match) if not params: raise BugzillaError('_get() needs one of ids, ' ' names, or match kwarg.') return self._proxy.User.get(params)
[ "def", "_getusers", "(", "self", ",", "ids", "=", "None", ",", "names", "=", "None", ",", "match", "=", "None", ")", ":", "params", "=", "{", "}", "if", "ids", ":", "params", "[", "'ids'", "]", "=", "self", ".", "_listify", "(", "ids", ")", "if...
Return a list of users that match criteria. :kwarg ids: list of user ids to return data on :kwarg names: list of user names to return data on :kwarg match: list of patterns. Returns users whose real name or login name match the pattern. :raises XMLRPC Fault: Code 51: if a Bad Login Name was sent to the names array. Code 304: if the user was not authorized to see user they requested. Code 505: user is logged out and can't use the match or ids parameter. Available in Bugzilla-3.4+
[ "Return", "a", "list", "of", "users", "that", "match", "criteria", "." ]
7de8b225104f24a1eee3e837bf1e02d60aefe69f
https://github.com/python-bugzilla/python-bugzilla/blob/7de8b225104f24a1eee3e837bf1e02d60aefe69f/bugzilla/base.py#L1756-L1784
train
25,118
python-bugzilla/python-bugzilla
bugzilla/base.py
Bugzilla.getusers
def getusers(self, userlist): """ Return a list of Users from . :userlist: List of usernames to lookup :returns: List of User records """ userobjs = [User(self, **rawuser) for rawuser in self._getusers(names=userlist).get('users', [])] # Return users in same order they were passed in ret = [] for u in userlist: for uobj in userobjs[:]: if uobj.email == u: userobjs.remove(uobj) ret.append(uobj) break ret += userobjs return ret
python
def getusers(self, userlist): """ Return a list of Users from . :userlist: List of usernames to lookup :returns: List of User records """ userobjs = [User(self, **rawuser) for rawuser in self._getusers(names=userlist).get('users', [])] # Return users in same order they were passed in ret = [] for u in userlist: for uobj in userobjs[:]: if uobj.email == u: userobjs.remove(uobj) ret.append(uobj) break ret += userobjs return ret
[ "def", "getusers", "(", "self", ",", "userlist", ")", ":", "userobjs", "=", "[", "User", "(", "self", ",", "*", "*", "rawuser", ")", "for", "rawuser", "in", "self", ".", "_getusers", "(", "names", "=", "userlist", ")", ".", "get", "(", "'users'", "...
Return a list of Users from . :userlist: List of usernames to lookup :returns: List of User records
[ "Return", "a", "list", "of", "Users", "from", "." ]
7de8b225104f24a1eee3e837bf1e02d60aefe69f
https://github.com/python-bugzilla/python-bugzilla/blob/7de8b225104f24a1eee3e837bf1e02d60aefe69f/bugzilla/base.py#L1797-L1816
train
25,119
python-bugzilla/python-bugzilla
bugzilla/base.py
Bugzilla.searchusers
def searchusers(self, pattern): """ Return a bugzilla User for the given list of patterns :arg pattern: List of patterns to match against. :returns: List of User records """ return [User(self, **rawuser) for rawuser in self._getusers(match=pattern).get('users', [])]
python
def searchusers(self, pattern): """ Return a bugzilla User for the given list of patterns :arg pattern: List of patterns to match against. :returns: List of User records """ return [User(self, **rawuser) for rawuser in self._getusers(match=pattern).get('users', [])]
[ "def", "searchusers", "(", "self", ",", "pattern", ")", ":", "return", "[", "User", "(", "self", ",", "*", "*", "rawuser", ")", "for", "rawuser", "in", "self", ".", "_getusers", "(", "match", "=", "pattern", ")", ".", "get", "(", "'users'", ",", "[...
Return a bugzilla User for the given list of patterns :arg pattern: List of patterns to match against. :returns: List of User records
[ "Return", "a", "bugzilla", "User", "for", "the", "given", "list", "of", "patterns" ]
7de8b225104f24a1eee3e837bf1e02d60aefe69f
https://github.com/python-bugzilla/python-bugzilla/blob/7de8b225104f24a1eee3e837bf1e02d60aefe69f/bugzilla/base.py#L1819-L1827
train
25,120
python-bugzilla/python-bugzilla
bugzilla/base.py
Bugzilla.createuser
def createuser(self, email, name='', password=''): """ Return a bugzilla User for the given username :arg email: The email address to use in bugzilla :kwarg name: Real name to associate with the account :kwarg password: Password to set for the bugzilla account :raises XMLRPC Fault: Code 501 if the username already exists Code 500 if the email address isn't valid Code 502 if the password is too short Code 503 if the password is too long :return: User record for the username """ self._proxy.User.create(email, name, password) return self.getuser(email)
python
def createuser(self, email, name='', password=''): """ Return a bugzilla User for the given username :arg email: The email address to use in bugzilla :kwarg name: Real name to associate with the account :kwarg password: Password to set for the bugzilla account :raises XMLRPC Fault: Code 501 if the username already exists Code 500 if the email address isn't valid Code 502 if the password is too short Code 503 if the password is too long :return: User record for the username """ self._proxy.User.create(email, name, password) return self.getuser(email)
[ "def", "createuser", "(", "self", ",", "email", ",", "name", "=", "''", ",", "password", "=", "''", ")", ":", "self", ".", "_proxy", ".", "User", ".", "create", "(", "email", ",", "name", ",", "password", ")", "return", "self", ".", "getuser", "(",...
Return a bugzilla User for the given username :arg email: The email address to use in bugzilla :kwarg name: Real name to associate with the account :kwarg password: Password to set for the bugzilla account :raises XMLRPC Fault: Code 501 if the username already exists Code 500 if the email address isn't valid Code 502 if the password is too short Code 503 if the password is too long :return: User record for the username
[ "Return", "a", "bugzilla", "User", "for", "the", "given", "username" ]
7de8b225104f24a1eee3e837bf1e02d60aefe69f
https://github.com/python-bugzilla/python-bugzilla/blob/7de8b225104f24a1eee3e837bf1e02d60aefe69f/bugzilla/base.py#L1829-L1843
train
25,121
python-bugzilla/python-bugzilla
bugzilla/bug.py
Bug.refresh
def refresh(self, include_fields=None, exclude_fields=None, extra_fields=None): """ Refresh the bug with the latest data from bugzilla """ # pylint: disable=protected-access r = self.bugzilla._getbug(self.bug_id, include_fields=include_fields, exclude_fields=exclude_fields, extra_fields=self._bug_fields + (extra_fields or [])) # pylint: enable=protected-access self._update_dict(r)
python
def refresh(self, include_fields=None, exclude_fields=None, extra_fields=None): """ Refresh the bug with the latest data from bugzilla """ # pylint: disable=protected-access r = self.bugzilla._getbug(self.bug_id, include_fields=include_fields, exclude_fields=exclude_fields, extra_fields=self._bug_fields + (extra_fields or [])) # pylint: enable=protected-access self._update_dict(r)
[ "def", "refresh", "(", "self", ",", "include_fields", "=", "None", ",", "exclude_fields", "=", "None", ",", "extra_fields", "=", "None", ")", ":", "# pylint: disable=protected-access", "r", "=", "self", ".", "bugzilla", ".", "_getbug", "(", "self", ".", "bug...
Refresh the bug with the latest data from bugzilla
[ "Refresh", "the", "bug", "with", "the", "latest", "data", "from", "bugzilla" ]
7de8b225104f24a1eee3e837bf1e02d60aefe69f
https://github.com/python-bugzilla/python-bugzilla/blob/7de8b225104f24a1eee3e837bf1e02d60aefe69f/bugzilla/bug.py#L117-L127
train
25,122
python-bugzilla/python-bugzilla
bugzilla/bug.py
Bug._update_dict
def _update_dict(self, newdict): """ Update internal dictionary, in a way that ensures no duplicate entries are stored WRT field aliases """ if self.bugzilla: self.bugzilla.post_translation({}, newdict) # pylint: disable=protected-access aliases = self.bugzilla._get_bug_aliases() # pylint: enable=protected-access for newname, oldname in aliases: if oldname not in newdict: continue if newname not in newdict: newdict[newname] = newdict[oldname] elif newdict[newname] != newdict[oldname]: log.debug("Update dict contained differing alias values " "d[%s]=%s and d[%s]=%s , dropping the value " "d[%s]", newname, newdict[newname], oldname, newdict[oldname], oldname) del(newdict[oldname]) for key in newdict.keys(): if key not in self._bug_fields: self._bug_fields.append(key) self.__dict__.update(newdict) if 'id' not in self.__dict__ and 'bug_id' not in self.__dict__: raise TypeError("Bug object needs a bug_id")
python
def _update_dict(self, newdict): """ Update internal dictionary, in a way that ensures no duplicate entries are stored WRT field aliases """ if self.bugzilla: self.bugzilla.post_translation({}, newdict) # pylint: disable=protected-access aliases = self.bugzilla._get_bug_aliases() # pylint: enable=protected-access for newname, oldname in aliases: if oldname not in newdict: continue if newname not in newdict: newdict[newname] = newdict[oldname] elif newdict[newname] != newdict[oldname]: log.debug("Update dict contained differing alias values " "d[%s]=%s and d[%s]=%s , dropping the value " "d[%s]", newname, newdict[newname], oldname, newdict[oldname], oldname) del(newdict[oldname]) for key in newdict.keys(): if key not in self._bug_fields: self._bug_fields.append(key) self.__dict__.update(newdict) if 'id' not in self.__dict__ and 'bug_id' not in self.__dict__: raise TypeError("Bug object needs a bug_id")
[ "def", "_update_dict", "(", "self", ",", "newdict", ")", ":", "if", "self", ".", "bugzilla", ":", "self", ".", "bugzilla", ".", "post_translation", "(", "{", "}", ",", "newdict", ")", "# pylint: disable=protected-access", "aliases", "=", "self", ".", "bugzil...
Update internal dictionary, in a way that ensures no duplicate entries are stored WRT field aliases
[ "Update", "internal", "dictionary", "in", "a", "way", "that", "ensures", "no", "duplicate", "entries", "are", "stored", "WRT", "field", "aliases" ]
7de8b225104f24a1eee3e837bf1e02d60aefe69f
https://github.com/python-bugzilla/python-bugzilla/blob/7de8b225104f24a1eee3e837bf1e02d60aefe69f/bugzilla/bug.py#L130-L161
train
25,123
python-bugzilla/python-bugzilla
bugzilla/bug.py
Bug.deletecc
def deletecc(self, cclist, comment=None): """ Removes the given email addresses from the CC list for this bug. """ vals = self.bugzilla.build_update(comment=comment, cc_remove=cclist) log.debug("deletecc: update=%s", vals) return self.bugzilla.update_bugs(self.bug_id, vals)
python
def deletecc(self, cclist, comment=None): """ Removes the given email addresses from the CC list for this bug. """ vals = self.bugzilla.build_update(comment=comment, cc_remove=cclist) log.debug("deletecc: update=%s", vals) return self.bugzilla.update_bugs(self.bug_id, vals)
[ "def", "deletecc", "(", "self", ",", "cclist", ",", "comment", "=", "None", ")", ":", "vals", "=", "self", ".", "bugzilla", ".", "build_update", "(", "comment", "=", "comment", ",", "cc_remove", "=", "cclist", ")", "log", ".", "debug", "(", "\"deletecc...
Removes the given email addresses from the CC list for this bug.
[ "Removes", "the", "given", "email", "addresses", "from", "the", "CC", "list", "for", "this", "bug", "." ]
7de8b225104f24a1eee3e837bf1e02d60aefe69f
https://github.com/python-bugzilla/python-bugzilla/blob/7de8b225104f24a1eee3e837bf1e02d60aefe69f/bugzilla/bug.py#L267-L275
train
25,124
python-bugzilla/python-bugzilla
bugzilla/bug.py
Bug.addcomment
def addcomment(self, comment, private=False): """ Add the given comment to this bug. Set private to True to mark this comment as private. """ # Note: fedora bodhi uses this function vals = self.bugzilla.build_update(comment=comment, comment_private=private) log.debug("addcomment: update=%s", vals) return self.bugzilla.update_bugs(self.bug_id, vals)
python
def addcomment(self, comment, private=False): """ Add the given comment to this bug. Set private to True to mark this comment as private. """ # Note: fedora bodhi uses this function vals = self.bugzilla.build_update(comment=comment, comment_private=private) log.debug("addcomment: update=%s", vals) return self.bugzilla.update_bugs(self.bug_id, vals)
[ "def", "addcomment", "(", "self", ",", "comment", ",", "private", "=", "False", ")", ":", "# Note: fedora bodhi uses this function", "vals", "=", "self", ".", "bugzilla", ".", "build_update", "(", "comment", "=", "comment", ",", "comment_private", "=", "private"...
Add the given comment to this bug. Set private to True to mark this comment as private.
[ "Add", "the", "given", "comment", "to", "this", "bug", ".", "Set", "private", "to", "True", "to", "mark", "this", "comment", "as", "private", "." ]
7de8b225104f24a1eee3e837bf1e02d60aefe69f
https://github.com/python-bugzilla/python-bugzilla/blob/7de8b225104f24a1eee3e837bf1e02d60aefe69f/bugzilla/bug.py#L282-L292
train
25,125
python-bugzilla/python-bugzilla
bugzilla/bug.py
Bug.getcomments
def getcomments(self): """ Returns an array of comment dictionaries for this bug """ comment_list = self.bugzilla.get_comments([self.bug_id]) return comment_list['bugs'][str(self.bug_id)]['comments']
python
def getcomments(self): """ Returns an array of comment dictionaries for this bug """ comment_list = self.bugzilla.get_comments([self.bug_id]) return comment_list['bugs'][str(self.bug_id)]['comments']
[ "def", "getcomments", "(", "self", ")", ":", "comment_list", "=", "self", ".", "bugzilla", ".", "get_comments", "(", "[", "self", ".", "bug_id", "]", ")", "return", "comment_list", "[", "'bugs'", "]", "[", "str", "(", "self", ".", "bug_id", ")", "]", ...
Returns an array of comment dictionaries for this bug
[ "Returns", "an", "array", "of", "comment", "dictionaries", "for", "this", "bug" ]
7de8b225104f24a1eee3e837bf1e02d60aefe69f
https://github.com/python-bugzilla/python-bugzilla/blob/7de8b225104f24a1eee3e837bf1e02d60aefe69f/bugzilla/bug.py#L294-L299
train
25,126
python-bugzilla/python-bugzilla
bugzilla/bug.py
Bug.get_flag_status
def get_flag_status(self, name): """ Return a flag 'status' field This method works only for simple flags that have only a 'status' field with no "requestee" info, and no multiple values. For more complex flags, use get_flags() to get extended flag value information. """ f = self.get_flags(name) if not f: return None # This method works only for simple flags that have only one # value set. assert len(f) <= 1 return f[0]['status']
python
def get_flag_status(self, name): """ Return a flag 'status' field This method works only for simple flags that have only a 'status' field with no "requestee" info, and no multiple values. For more complex flags, use get_flags() to get extended flag value information. """ f = self.get_flags(name) if not f: return None # This method works only for simple flags that have only one # value set. assert len(f) <= 1 return f[0]['status']
[ "def", "get_flag_status", "(", "self", ",", "name", ")", ":", "f", "=", "self", ".", "get_flags", "(", "name", ")", "if", "not", "f", ":", "return", "None", "# This method works only for simple flags that have only one", "# value set.", "assert", "len", "(", "f"...
Return a flag 'status' field This method works only for simple flags that have only a 'status' field with no "requestee" info, and no multiple values. For more complex flags, use get_flags() to get extended flag value information.
[ "Return", "a", "flag", "status", "field" ]
7de8b225104f24a1eee3e837bf1e02d60aefe69f
https://github.com/python-bugzilla/python-bugzilla/blob/7de8b225104f24a1eee3e837bf1e02d60aefe69f/bugzilla/bug.py#L328-L344
train
25,127
python-bugzilla/python-bugzilla
bugzilla/bug.py
Bug.get_attachments
def get_attachments(self, include_fields=None, exclude_fields=None): """ Helper call to Bugzilla.get_attachments. If you want to fetch specific attachment IDs, use that function instead """ if "attachments" in self.__dict__: return self.attachments data = self.bugzilla.get_attachments([self.bug_id], None, include_fields, exclude_fields) return data["bugs"][str(self.bug_id)]
python
def get_attachments(self, include_fields=None, exclude_fields=None): """ Helper call to Bugzilla.get_attachments. If you want to fetch specific attachment IDs, use that function instead """ if "attachments" in self.__dict__: return self.attachments data = self.bugzilla.get_attachments([self.bug_id], None, include_fields, exclude_fields) return data["bugs"][str(self.bug_id)]
[ "def", "get_attachments", "(", "self", ",", "include_fields", "=", "None", ",", "exclude_fields", "=", "None", ")", ":", "if", "\"attachments\"", "in", "self", ".", "__dict__", ":", "return", "self", ".", "attachments", "data", "=", "self", ".", "bugzilla", ...
Helper call to Bugzilla.get_attachments. If you want to fetch specific attachment IDs, use that function instead
[ "Helper", "call", "to", "Bugzilla", ".", "get_attachments", ".", "If", "you", "want", "to", "fetch", "specific", "attachment", "IDs", "use", "that", "function", "instead" ]
7de8b225104f24a1eee3e837bf1e02d60aefe69f
https://github.com/python-bugzilla/python-bugzilla/blob/7de8b225104f24a1eee3e837bf1e02d60aefe69f/bugzilla/bug.py#L366-L376
train
25,128
python-bugzilla/python-bugzilla
bugzilla/bug.py
User.refresh
def refresh(self): """ Update User object with latest info from bugzilla """ newuser = self.bugzilla.getuser(self.email) self.__dict__.update(newuser.__dict__)
python
def refresh(self): """ Update User object with latest info from bugzilla """ newuser = self.bugzilla.getuser(self.email) self.__dict__.update(newuser.__dict__)
[ "def", "refresh", "(", "self", ")", ":", "newuser", "=", "self", ".", "bugzilla", ".", "getuser", "(", "self", ".", "email", ")", "self", ".", "__dict__", ".", "update", "(", "newuser", ".", "__dict__", ")" ]
Update User object with latest info from bugzilla
[ "Update", "User", "object", "with", "latest", "info", "from", "bugzilla" ]
7de8b225104f24a1eee3e837bf1e02d60aefe69f
https://github.com/python-bugzilla/python-bugzilla/blob/7de8b225104f24a1eee3e837bf1e02d60aefe69f/bugzilla/bug.py#L441-L446
train
25,129
python-bugzilla/python-bugzilla
bugzilla/rhbugzilla.py
RHBugzilla.pre_translation
def pre_translation(self, query): """ Translates the query for possible aliases """ old = query.copy() if 'bug_id' in query: if not isinstance(query['bug_id'], list): query['id'] = query['bug_id'].split(',') else: query['id'] = query['bug_id'] del query['bug_id'] if 'component' in query: if not isinstance(query['component'], list): query['component'] = query['component'].split(',') if 'include_fields' not in query and 'column_list' not in query: return if 'include_fields' not in query: query['include_fields'] = [] if 'column_list' in query: query['include_fields'] = query['column_list'] del query['column_list'] # We need to do this for users here for users that # don't call build_query query.update(self._process_include_fields(query["include_fields"], None, None)) if old != query: log.debug("RHBugzilla pretranslated query to: %s", query)
python
def pre_translation(self, query): """ Translates the query for possible aliases """ old = query.copy() if 'bug_id' in query: if not isinstance(query['bug_id'], list): query['id'] = query['bug_id'].split(',') else: query['id'] = query['bug_id'] del query['bug_id'] if 'component' in query: if not isinstance(query['component'], list): query['component'] = query['component'].split(',') if 'include_fields' not in query and 'column_list' not in query: return if 'include_fields' not in query: query['include_fields'] = [] if 'column_list' in query: query['include_fields'] = query['column_list'] del query['column_list'] # We need to do this for users here for users that # don't call build_query query.update(self._process_include_fields(query["include_fields"], None, None)) if old != query: log.debug("RHBugzilla pretranslated query to: %s", query)
[ "def", "pre_translation", "(", "self", ",", "query", ")", ":", "old", "=", "query", ".", "copy", "(", ")", "if", "'bug_id'", "in", "query", ":", "if", "not", "isinstance", "(", "query", "[", "'bug_id'", "]", ",", "list", ")", ":", "query", "[", "'i...
Translates the query for possible aliases
[ "Translates", "the", "query", "for", "possible", "aliases" ]
7de8b225104f24a1eee3e837bf1e02d60aefe69f
https://github.com/python-bugzilla/python-bugzilla/blob/7de8b225104f24a1eee3e837bf1e02d60aefe69f/bugzilla/rhbugzilla.py#L252-L284
train
25,130
python-bugzilla/python-bugzilla
bugzilla/rhbugzilla.py
RHBugzilla.post_translation
def post_translation(self, query, bug): """ Convert the results of getbug back to the ancient RHBZ value formats """ ignore = query # RHBZ _still_ returns component and version as lists, which # deviates from upstream. Copy the list values to components # and versions respectively. if 'component' in bug and "components" not in bug: val = bug['component'] bug['components'] = isinstance(val, list) and val or [val] bug['component'] = bug['components'][0] if 'version' in bug and "versions" not in bug: val = bug['version'] bug['versions'] = isinstance(val, list) and val or [val] bug['version'] = bug['versions'][0] # sub_components isn't too friendly of a format, add a simpler # sub_component value if 'sub_components' in bug and 'sub_component' not in bug: val = bug['sub_components'] bug['sub_component'] = "" if isinstance(val, dict): values = [] for vallist in val.values(): values += vallist bug['sub_component'] = " ".join(values)
python
def post_translation(self, query, bug): """ Convert the results of getbug back to the ancient RHBZ value formats """ ignore = query # RHBZ _still_ returns component and version as lists, which # deviates from upstream. Copy the list values to components # and versions respectively. if 'component' in bug and "components" not in bug: val = bug['component'] bug['components'] = isinstance(val, list) and val or [val] bug['component'] = bug['components'][0] if 'version' in bug and "versions" not in bug: val = bug['version'] bug['versions'] = isinstance(val, list) and val or [val] bug['version'] = bug['versions'][0] # sub_components isn't too friendly of a format, add a simpler # sub_component value if 'sub_components' in bug and 'sub_component' not in bug: val = bug['sub_components'] bug['sub_component'] = "" if isinstance(val, dict): values = [] for vallist in val.values(): values += vallist bug['sub_component'] = " ".join(values)
[ "def", "post_translation", "(", "self", ",", "query", ",", "bug", ")", ":", "ignore", "=", "query", "# RHBZ _still_ returns component and version as lists, which", "# deviates from upstream. Copy the list values to components", "# and versions respectively.", "if", "'component'", ...
Convert the results of getbug back to the ancient RHBZ value formats
[ "Convert", "the", "results", "of", "getbug", "back", "to", "the", "ancient", "RHBZ", "value", "formats" ]
7de8b225104f24a1eee3e837bf1e02d60aefe69f
https://github.com/python-bugzilla/python-bugzilla/blob/7de8b225104f24a1eee3e837bf1e02d60aefe69f/bugzilla/rhbugzilla.py#L286-L315
train
25,131
kdeldycke/maildir-deduplicate
maildir_deduplicate/deduplicate.py
DuplicateSet.delete
def delete(self, mail): """ Delete a mail from the filesystem. """ self.stats['mail_deleted'] += 1 if self.conf.dry_run: logger.info("Skip deletion of {!r}.".format(mail)) return logger.debug("Deleting {!r}...".format(mail)) # XXX Investigate the use of maildir's .remove instead. See: https: # //github.com/python/cpython/blob/origin/2.7/Lib/mailbox.py#L329-L331 os.unlink(mail.path) logger.info("{} deleted.".format(mail.path))
python
def delete(self, mail): """ Delete a mail from the filesystem. """ self.stats['mail_deleted'] += 1 if self.conf.dry_run: logger.info("Skip deletion of {!r}.".format(mail)) return logger.debug("Deleting {!r}...".format(mail)) # XXX Investigate the use of maildir's .remove instead. See: https: # //github.com/python/cpython/blob/origin/2.7/Lib/mailbox.py#L329-L331 os.unlink(mail.path) logger.info("{} deleted.".format(mail.path))
[ "def", "delete", "(", "self", ",", "mail", ")", ":", "self", ".", "stats", "[", "'mail_deleted'", "]", "+=", "1", "if", "self", ".", "conf", ".", "dry_run", ":", "logger", ".", "info", "(", "\"Skip deletion of {!r}.\"", ".", "format", "(", "mail", ")",...
Delete a mail from the filesystem.
[ "Delete", "a", "mail", "from", "the", "filesystem", "." ]
f1c6ff25b80c6c1a4dc2dc7a65b34d808b0b7733
https://github.com/kdeldycke/maildir-deduplicate/blob/f1c6ff25b80c6c1a4dc2dc7a65b34d808b0b7733/maildir_deduplicate/deduplicate.py#L109-L120
train
25,132
kdeldycke/maildir-deduplicate
maildir_deduplicate/deduplicate.py
DuplicateSet.check_differences
def check_differences(self): """ In-depth check of mail differences. Compare all mails of the duplicate set with each other, both in size and content. Raise an error if we're not within the limits imposed by the threshold setting. """ logger.info("Check that mail differences are within the limits.") if self.conf.size_threshold < 0: logger.info("Skip checking for size differences.") if self.conf.content_threshold < 0: logger.info("Skip checking for content differences.") if self.conf.size_threshold < 0 and self.conf.content_threshold < 0: return # Compute differences of mail against one another. for mail_a, mail_b in combinations(self.pool, 2): # Compare mails on size. if self.conf.size_threshold > -1: size_difference = abs(mail_a.size - mail_b.size) logger.debug("{} and {} differs by {} bytes in size.".format( mail_a, mail_b, size_difference)) if size_difference > self.conf.size_threshold: raise SizeDiffAboveThreshold # Compare mails on content. if self.conf.content_threshold > -1: content_difference = self.diff(mail_a, mail_b) logger.debug( "{} and {} differs by {} bytes in content.".format( mail_a, mail_b, content_difference)) if content_difference > self.conf.content_threshold: if self.conf.show_diff: logger.info(self.pretty_diff(mail_a, mail_b)) raise ContentDiffAboveThreshold
python
def check_differences(self): """ In-depth check of mail differences. Compare all mails of the duplicate set with each other, both in size and content. Raise an error if we're not within the limits imposed by the threshold setting. """ logger.info("Check that mail differences are within the limits.") if self.conf.size_threshold < 0: logger.info("Skip checking for size differences.") if self.conf.content_threshold < 0: logger.info("Skip checking for content differences.") if self.conf.size_threshold < 0 and self.conf.content_threshold < 0: return # Compute differences of mail against one another. for mail_a, mail_b in combinations(self.pool, 2): # Compare mails on size. if self.conf.size_threshold > -1: size_difference = abs(mail_a.size - mail_b.size) logger.debug("{} and {} differs by {} bytes in size.".format( mail_a, mail_b, size_difference)) if size_difference > self.conf.size_threshold: raise SizeDiffAboveThreshold # Compare mails on content. if self.conf.content_threshold > -1: content_difference = self.diff(mail_a, mail_b) logger.debug( "{} and {} differs by {} bytes in content.".format( mail_a, mail_b, content_difference)) if content_difference > self.conf.content_threshold: if self.conf.show_diff: logger.info(self.pretty_diff(mail_a, mail_b)) raise ContentDiffAboveThreshold
[ "def", "check_differences", "(", "self", ")", ":", "logger", ".", "info", "(", "\"Check that mail differences are within the limits.\"", ")", "if", "self", ".", "conf", ".", "size_threshold", "<", "0", ":", "logger", ".", "info", "(", "\"Skip checking for size diffe...
In-depth check of mail differences. Compare all mails of the duplicate set with each other, both in size and content. Raise an error if we're not within the limits imposed by the threshold setting.
[ "In", "-", "depth", "check", "of", "mail", "differences", "." ]
f1c6ff25b80c6c1a4dc2dc7a65b34d808b0b7733
https://github.com/kdeldycke/maildir-deduplicate/blob/f1c6ff25b80c6c1a4dc2dc7a65b34d808b0b7733/maildir_deduplicate/deduplicate.py#L122-L157
train
25,133
kdeldycke/maildir-deduplicate
maildir_deduplicate/deduplicate.py
DuplicateSet.diff
def diff(self, mail_a, mail_b): """ Return difference in bytes between two mails' normalized body. TODO: rewrite the diff algorithm to not rely on naive unified diff result parsing. """ return len(''.join(unified_diff( mail_a.body_lines, mail_b.body_lines, # Ignore difference in filename lenghts and timestamps. fromfile='a', tofile='b', fromfiledate='', tofiledate='', n=0, lineterm='\n')))
python
def diff(self, mail_a, mail_b): """ Return difference in bytes between two mails' normalized body. TODO: rewrite the diff algorithm to not rely on naive unified diff result parsing. """ return len(''.join(unified_diff( mail_a.body_lines, mail_b.body_lines, # Ignore difference in filename lenghts and timestamps. fromfile='a', tofile='b', fromfiledate='', tofiledate='', n=0, lineterm='\n')))
[ "def", "diff", "(", "self", ",", "mail_a", ",", "mail_b", ")", ":", "return", "len", "(", "''", ".", "join", "(", "unified_diff", "(", "mail_a", ".", "body_lines", ",", "mail_b", ".", "body_lines", ",", "# Ignore difference in filename lenghts and timestamps.", ...
Return difference in bytes between two mails' normalized body. TODO: rewrite the diff algorithm to not rely on naive unified diff result parsing.
[ "Return", "difference", "in", "bytes", "between", "two", "mails", "normalized", "body", "." ]
f1c6ff25b80c6c1a4dc2dc7a65b34d808b0b7733
https://github.com/kdeldycke/maildir-deduplicate/blob/f1c6ff25b80c6c1a4dc2dc7a65b34d808b0b7733/maildir_deduplicate/deduplicate.py#L159-L170
train
25,134
kdeldycke/maildir-deduplicate
maildir_deduplicate/deduplicate.py
DuplicateSet.pretty_diff
def pretty_diff(self, mail_a, mail_b): """ Returns a verbose unified diff between two mails' normalized body. """ return ''.join(unified_diff( mail_a.body_lines, mail_b.body_lines, fromfile='Normalized body of {}'.format(mail_a.path), tofile='Normalized body of {}'.format(mail_b.path), fromfiledate='{:0.2f}'.format(mail_a.timestamp), tofiledate='{:0.2f}'.format(mail_b.timestamp), n=0, lineterm='\n'))
python
def pretty_diff(self, mail_a, mail_b): """ Returns a verbose unified diff between two mails' normalized body. """ return ''.join(unified_diff( mail_a.body_lines, mail_b.body_lines, fromfile='Normalized body of {}'.format(mail_a.path), tofile='Normalized body of {}'.format(mail_b.path), fromfiledate='{:0.2f}'.format(mail_a.timestamp), tofiledate='{:0.2f}'.format(mail_b.timestamp), n=0, lineterm='\n'))
[ "def", "pretty_diff", "(", "self", ",", "mail_a", ",", "mail_b", ")", ":", "return", "''", ".", "join", "(", "unified_diff", "(", "mail_a", ".", "body_lines", ",", "mail_b", ".", "body_lines", ",", "fromfile", "=", "'Normalized body of {}'", ".", "format", ...
Returns a verbose unified diff between two mails' normalized body.
[ "Returns", "a", "verbose", "unified", "diff", "between", "two", "mails", "normalized", "body", "." ]
f1c6ff25b80c6c1a4dc2dc7a65b34d808b0b7733
https://github.com/kdeldycke/maildir-deduplicate/blob/f1c6ff25b80c6c1a4dc2dc7a65b34d808b0b7733/maildir_deduplicate/deduplicate.py#L172-L181
train
25,135
kdeldycke/maildir-deduplicate
maildir_deduplicate/deduplicate.py
DuplicateSet.apply_strategy
def apply_strategy(self): """ Apply deduplication with the configured strategy. Transform strategy keyword into its method ID, and call it. """ method_id = self.conf.strategy.replace('-', '_') if not hasattr(DuplicateSet, method_id): raise NotImplementedError( "DuplicateSet.{}() method.".format(method_id)) return getattr(self, method_id)()
python
def apply_strategy(self): """ Apply deduplication with the configured strategy. Transform strategy keyword into its method ID, and call it. """ method_id = self.conf.strategy.replace('-', '_') if not hasattr(DuplicateSet, method_id): raise NotImplementedError( "DuplicateSet.{}() method.".format(method_id)) return getattr(self, method_id)()
[ "def", "apply_strategy", "(", "self", ")", ":", "method_id", "=", "self", ".", "conf", ".", "strategy", ".", "replace", "(", "'-'", ",", "'_'", ")", "if", "not", "hasattr", "(", "DuplicateSet", ",", "method_id", ")", ":", "raise", "NotImplementedError", ...
Apply deduplication with the configured strategy. Transform strategy keyword into its method ID, and call it.
[ "Apply", "deduplication", "with", "the", "configured", "strategy", "." ]
f1c6ff25b80c6c1a4dc2dc7a65b34d808b0b7733
https://github.com/kdeldycke/maildir-deduplicate/blob/f1c6ff25b80c6c1a4dc2dc7a65b34d808b0b7733/maildir_deduplicate/deduplicate.py#L183-L192
train
25,136
kdeldycke/maildir-deduplicate
maildir_deduplicate/deduplicate.py
DuplicateSet.dedupe
def dedupe(self): """ Performs the deduplication and its preliminary checks. """ if len(self.pool) == 1: logger.debug("Ignore set: only one message found.") self.stats['mail_unique'] += 1 self.stats['set_ignored'] += 1 return try: # Fine-grained checks on mail differences. self.check_differences() # Call the deduplication strategy. self.apply_strategy() except UnicodeDecodeError as expt: self.stats['set_rejected_encoding'] += 1 logger.warning( "Reject set: unparseable mails due to bad encoding.") logger.debug(str(expt)) except SizeDiffAboveThreshold: self.stats['set_rejected_size'] += 1 logger.warning("Reject set: mails are too dissimilar in size.") except ContentDiffAboveThreshold: self.stats['set_rejected_content'] += 1 logger.warning("Reject set: mails are too dissimilar in content.") else: # Count duplicate sets without deletion as skipped. if not self.stats['mail_deleted']: logger.info("Skip set: no deletion happened.") self.stats['set_skipped'] += 1 else: self.stats['set_deduplicated'] += 1
python
def dedupe(self): """ Performs the deduplication and its preliminary checks. """ if len(self.pool) == 1: logger.debug("Ignore set: only one message found.") self.stats['mail_unique'] += 1 self.stats['set_ignored'] += 1 return try: # Fine-grained checks on mail differences. self.check_differences() # Call the deduplication strategy. self.apply_strategy() except UnicodeDecodeError as expt: self.stats['set_rejected_encoding'] += 1 logger.warning( "Reject set: unparseable mails due to bad encoding.") logger.debug(str(expt)) except SizeDiffAboveThreshold: self.stats['set_rejected_size'] += 1 logger.warning("Reject set: mails are too dissimilar in size.") except ContentDiffAboveThreshold: self.stats['set_rejected_content'] += 1 logger.warning("Reject set: mails are too dissimilar in content.") else: # Count duplicate sets without deletion as skipped. if not self.stats['mail_deleted']: logger.info("Skip set: no deletion happened.") self.stats['set_skipped'] += 1 else: self.stats['set_deduplicated'] += 1
[ "def", "dedupe", "(", "self", ")", ":", "if", "len", "(", "self", ".", "pool", ")", "==", "1", ":", "logger", ".", "debug", "(", "\"Ignore set: only one message found.\"", ")", "self", ".", "stats", "[", "'mail_unique'", "]", "+=", "1", "self", ".", "s...
Performs the deduplication and its preliminary checks.
[ "Performs", "the", "deduplication", "and", "its", "preliminary", "checks", "." ]
f1c6ff25b80c6c1a4dc2dc7a65b34d808b0b7733
https://github.com/kdeldycke/maildir-deduplicate/blob/f1c6ff25b80c6c1a4dc2dc7a65b34d808b0b7733/maildir_deduplicate/deduplicate.py#L194-L224
train
25,137
kdeldycke/maildir-deduplicate
maildir_deduplicate/deduplicate.py
DuplicateSet.delete_older
def delete_older(self): """ Delete all older duplicates. Only keeps the subset sharing the most recent timestamp. """ logger.info( "Deleting all mails strictly older than the {} timestamp..." "".format(self.newest_timestamp)) # Select candidates for deletion. candidates = [ mail for mail in self.pool if mail.timestamp < self.newest_timestamp] if len(candidates) == self.size: logger.warning( "Skip deletion: all {} mails share the same timestamp." "".format(self.size)) logger.info( "{} candidates found for deletion.".format(len(candidates))) for mail in candidates: self.delete(mail)
python
def delete_older(self): """ Delete all older duplicates. Only keeps the subset sharing the most recent timestamp. """ logger.info( "Deleting all mails strictly older than the {} timestamp..." "".format(self.newest_timestamp)) # Select candidates for deletion. candidates = [ mail for mail in self.pool if mail.timestamp < self.newest_timestamp] if len(candidates) == self.size: logger.warning( "Skip deletion: all {} mails share the same timestamp." "".format(self.size)) logger.info( "{} candidates found for deletion.".format(len(candidates))) for mail in candidates: self.delete(mail)
[ "def", "delete_older", "(", "self", ")", ":", "logger", ".", "info", "(", "\"Deleting all mails strictly older than the {} timestamp...\"", "\"\"", ".", "format", "(", "self", ".", "newest_timestamp", ")", ")", "# Select candidates for deletion.", "candidates", "=", "["...
Delete all older duplicates. Only keeps the subset sharing the most recent timestamp.
[ "Delete", "all", "older", "duplicates", "." ]
f1c6ff25b80c6c1a4dc2dc7a65b34d808b0b7733
https://github.com/kdeldycke/maildir-deduplicate/blob/f1c6ff25b80c6c1a4dc2dc7a65b34d808b0b7733/maildir_deduplicate/deduplicate.py#L228-L247
train
25,138
kdeldycke/maildir-deduplicate
maildir_deduplicate/deduplicate.py
DuplicateSet.delete_oldest
def delete_oldest(self): """ Delete all the oldest duplicates. Keeps all mail of the duplicate set but those sharing the oldest timestamp. """ logger.info( "Deleting all mails sharing the oldest {} timestamp...".format( self.oldest_timestamp)) # Select candidates for deletion. candidates = [ mail for mail in self.pool if mail.timestamp == self.oldest_timestamp] if len(candidates) == self.size: logger.warning( "Skip deletion: all {} mails share the same timestamp." "".format(self.size)) return logger.info( "{} candidates found for deletion.".format(len(candidates))) for mail in candidates: self.delete(mail)
python
def delete_oldest(self): """ Delete all the oldest duplicates. Keeps all mail of the duplicate set but those sharing the oldest timestamp. """ logger.info( "Deleting all mails sharing the oldest {} timestamp...".format( self.oldest_timestamp)) # Select candidates for deletion. candidates = [ mail for mail in self.pool if mail.timestamp == self.oldest_timestamp] if len(candidates) == self.size: logger.warning( "Skip deletion: all {} mails share the same timestamp." "".format(self.size)) return logger.info( "{} candidates found for deletion.".format(len(candidates))) for mail in candidates: self.delete(mail)
[ "def", "delete_oldest", "(", "self", ")", ":", "logger", ".", "info", "(", "\"Deleting all mails sharing the oldest {} timestamp...\"", ".", "format", "(", "self", ".", "oldest_timestamp", ")", ")", "# Select candidates for deletion.", "candidates", "=", "[", "mail", ...
Delete all the oldest duplicates. Keeps all mail of the duplicate set but those sharing the oldest timestamp.
[ "Delete", "all", "the", "oldest", "duplicates", "." ]
f1c6ff25b80c6c1a4dc2dc7a65b34d808b0b7733
https://github.com/kdeldycke/maildir-deduplicate/blob/f1c6ff25b80c6c1a4dc2dc7a65b34d808b0b7733/maildir_deduplicate/deduplicate.py#L249-L270
train
25,139
kdeldycke/maildir-deduplicate
maildir_deduplicate/deduplicate.py
DuplicateSet.delete_bigger
def delete_bigger(self): """ Delete all bigger duplicates. Only keeps the subset sharing the smallest size. """ logger.info( "Deleting all mails strictly bigger than {} bytes...".format( self.smallest_size)) # Select candidates for deletion. candidates = [ mail for mail in self.pool if mail.size > self.smallest_size] if len(candidates) == self.size: logger.warning( "Skip deletion: all {} mails share the same size." "".format(self.size)) logger.info( "{} candidates found for deletion.".format(len(candidates))) for mail in candidates: self.delete(mail)
python
def delete_bigger(self): """ Delete all bigger duplicates. Only keeps the subset sharing the smallest size. """ logger.info( "Deleting all mails strictly bigger than {} bytes...".format( self.smallest_size)) # Select candidates for deletion. candidates = [ mail for mail in self.pool if mail.size > self.smallest_size] if len(candidates) == self.size: logger.warning( "Skip deletion: all {} mails share the same size." "".format(self.size)) logger.info( "{} candidates found for deletion.".format(len(candidates))) for mail in candidates: self.delete(mail)
[ "def", "delete_bigger", "(", "self", ")", ":", "logger", ".", "info", "(", "\"Deleting all mails strictly bigger than {} bytes...\"", ".", "format", "(", "self", ".", "smallest_size", ")", ")", "# Select candidates for deletion.", "candidates", "=", "[", "mail", "for"...
Delete all bigger duplicates. Only keeps the subset sharing the smallest size.
[ "Delete", "all", "bigger", "duplicates", "." ]
f1c6ff25b80c6c1a4dc2dc7a65b34d808b0b7733
https://github.com/kdeldycke/maildir-deduplicate/blob/f1c6ff25b80c6c1a4dc2dc7a65b34d808b0b7733/maildir_deduplicate/deduplicate.py#L361-L380
train
25,140
kdeldycke/maildir-deduplicate
maildir_deduplicate/deduplicate.py
DuplicateSet.delete_biggest
def delete_biggest(self): """ Delete all the biggest duplicates. Keeps all mail of the duplicate set but those sharing the biggest size. """ logger.info( "Deleting all mails sharing the biggest size of {} bytes..." "".format(self.biggest_size)) # Select candidates for deletion. candidates = [ mail for mail in self.pool if mail.size == self.biggest_size] if len(candidates) == self.size: logger.warning( "Skip deletion: all {} mails share the same size." "".format(self.size)) return logger.info( "{} candidates found for deletion.".format(len(candidates))) for mail in candidates: self.delete(mail)
python
def delete_biggest(self): """ Delete all the biggest duplicates. Keeps all mail of the duplicate set but those sharing the biggest size. """ logger.info( "Deleting all mails sharing the biggest size of {} bytes..." "".format(self.biggest_size)) # Select candidates for deletion. candidates = [ mail for mail in self.pool if mail.size == self.biggest_size] if len(candidates) == self.size: logger.warning( "Skip deletion: all {} mails share the same size." "".format(self.size)) return logger.info( "{} candidates found for deletion.".format(len(candidates))) for mail in candidates: self.delete(mail)
[ "def", "delete_biggest", "(", "self", ")", ":", "logger", ".", "info", "(", "\"Deleting all mails sharing the biggest size of {} bytes...\"", "\"\"", ".", "format", "(", "self", ".", "biggest_size", ")", ")", "# Select candidates for deletion.", "candidates", "=", "[", ...
Delete all the biggest duplicates. Keeps all mail of the duplicate set but those sharing the biggest size.
[ "Delete", "all", "the", "biggest", "duplicates", "." ]
f1c6ff25b80c6c1a4dc2dc7a65b34d808b0b7733
https://github.com/kdeldycke/maildir-deduplicate/blob/f1c6ff25b80c6c1a4dc2dc7a65b34d808b0b7733/maildir_deduplicate/deduplicate.py#L382-L403
train
25,141
kdeldycke/maildir-deduplicate
maildir_deduplicate/deduplicate.py
DuplicateSet.delete_matching_path
def delete_matching_path(self): """ Delete all duplicates whose file path match the regexp. """ logger.info( "Deleting all mails with file path matching the {} regexp..." "".format(self.conf.regexp.pattern)) # Select candidates for deletion. candidates = [ mail for mail in self.pool if re.search(self.conf.regexp, mail.path)] if len(candidates) == self.size: logger.warning( "Skip deletion: all {} mails matches the rexexp.".format( self.size)) return logger.info( "{} candidates found for deletion.".format(len(candidates))) for mail in candidates: self.delete(mail)
python
def delete_matching_path(self): """ Delete all duplicates whose file path match the regexp. """ logger.info( "Deleting all mails with file path matching the {} regexp..." "".format(self.conf.regexp.pattern)) # Select candidates for deletion. candidates = [ mail for mail in self.pool if re.search(self.conf.regexp, mail.path)] if len(candidates) == self.size: logger.warning( "Skip deletion: all {} mails matches the rexexp.".format( self.size)) return logger.info( "{} candidates found for deletion.".format(len(candidates))) for mail in candidates: self.delete(mail)
[ "def", "delete_matching_path", "(", "self", ")", ":", "logger", ".", "info", "(", "\"Deleting all mails with file path matching the {} regexp...\"", "\"\"", ".", "format", "(", "self", ".", "conf", ".", "regexp", ".", "pattern", ")", ")", "# Select candidates for dele...
Delete all duplicates whose file path match the regexp.
[ "Delete", "all", "duplicates", "whose", "file", "path", "match", "the", "regexp", "." ]
f1c6ff25b80c6c1a4dc2dc7a65b34d808b0b7733
https://github.com/kdeldycke/maildir-deduplicate/blob/f1c6ff25b80c6c1a4dc2dc7a65b34d808b0b7733/maildir_deduplicate/deduplicate.py#L405-L422
train
25,142
kdeldycke/maildir-deduplicate
maildir_deduplicate/deduplicate.py
Deduplicate.canonical_path
def canonical_path(path): """ Return a normalized, canonical path to a file or folder. Removes all symbolic links encountered in the path to detect natural mail and maildir duplicates on the fly. """ return os.path.normcase(os.path.realpath(os.path.abspath( os.path.expanduser(path))))
python
def canonical_path(path): """ Return a normalized, canonical path to a file or folder. Removes all symbolic links encountered in the path to detect natural mail and maildir duplicates on the fly. """ return os.path.normcase(os.path.realpath(os.path.abspath( os.path.expanduser(path))))
[ "def", "canonical_path", "(", "path", ")", ":", "return", "os", ".", "path", ".", "normcase", "(", "os", ".", "path", ".", "realpath", "(", "os", ".", "path", ".", "abspath", "(", "os", ".", "path", ".", "expanduser", "(", "path", ")", ")", ")", ...
Return a normalized, canonical path to a file or folder. Removes all symbolic links encountered in the path to detect natural mail and maildir duplicates on the fly.
[ "Return", "a", "normalized", "canonical", "path", "to", "a", "file", "or", "folder", "." ]
f1c6ff25b80c6c1a4dc2dc7a65b34d808b0b7733
https://github.com/kdeldycke/maildir-deduplicate/blob/f1c6ff25b80c6c1a4dc2dc7a65b34d808b0b7733/maildir_deduplicate/deduplicate.py#L489-L496
train
25,143
kdeldycke/maildir-deduplicate
maildir_deduplicate/deduplicate.py
Deduplicate.add_maildir
def add_maildir(self, maildir_path): """ Load up a maildir and compute hash for each mail found. """ maildir_path = self.canonical_path(maildir_path) logger.info("Opening maildir at {} ...".format(maildir_path)) # Maildir parser requires a string, not a unicode, as path. maildir = Maildir(str(maildir_path), factory=None, create=False) # Group folders by hash. logger.info("{} mails found.".format(len(maildir))) if self.conf.progress: bar = ProgressBar(widgets=[Percentage(), Bar()], max_value=len(maildir), redirect_stderr=True, redirect_stdout=True) else: def bar(x): return x for mail_id in bar(maildir.iterkeys()): self.stats['mail_found'] += 1 mail_path = self.canonical_path(os.path.join( maildir._path, maildir._lookup(mail_id))) mail = Mail(mail_path, self.conf) try: mail_hash = mail.hash_key except (InsufficientHeadersError, MissingMessageID) as expt: logger.warning( "Rejecting {}: {}".format(mail_path, expt.args[0])) self.stats['mail_rejected'] += 1 else: logger.debug( "Hash is {} for mail {!r}.".format(mail_hash, mail_id)) # Use a set to deduplicate entries pointing to the same file. self.mails.setdefault(mail_hash, set()).add(mail_path) self.stats['mail_kept'] += 1
python
def add_maildir(self, maildir_path): """ Load up a maildir and compute hash for each mail found. """ maildir_path = self.canonical_path(maildir_path) logger.info("Opening maildir at {} ...".format(maildir_path)) # Maildir parser requires a string, not a unicode, as path. maildir = Maildir(str(maildir_path), factory=None, create=False) # Group folders by hash. logger.info("{} mails found.".format(len(maildir))) if self.conf.progress: bar = ProgressBar(widgets=[Percentage(), Bar()], max_value=len(maildir), redirect_stderr=True, redirect_stdout=True) else: def bar(x): return x for mail_id in bar(maildir.iterkeys()): self.stats['mail_found'] += 1 mail_path = self.canonical_path(os.path.join( maildir._path, maildir._lookup(mail_id))) mail = Mail(mail_path, self.conf) try: mail_hash = mail.hash_key except (InsufficientHeadersError, MissingMessageID) as expt: logger.warning( "Rejecting {}: {}".format(mail_path, expt.args[0])) self.stats['mail_rejected'] += 1 else: logger.debug( "Hash is {} for mail {!r}.".format(mail_hash, mail_id)) # Use a set to deduplicate entries pointing to the same file. self.mails.setdefault(mail_hash, set()).add(mail_path) self.stats['mail_kept'] += 1
[ "def", "add_maildir", "(", "self", ",", "maildir_path", ")", ":", "maildir_path", "=", "self", ".", "canonical_path", "(", "maildir_path", ")", "logger", ".", "info", "(", "\"Opening maildir at {} ...\"", ".", "format", "(", "maildir_path", ")", ")", "# Maildir ...
Load up a maildir and compute hash for each mail found.
[ "Load", "up", "a", "maildir", "and", "compute", "hash", "for", "each", "mail", "found", "." ]
f1c6ff25b80c6c1a4dc2dc7a65b34d808b0b7733
https://github.com/kdeldycke/maildir-deduplicate/blob/f1c6ff25b80c6c1a4dc2dc7a65b34d808b0b7733/maildir_deduplicate/deduplicate.py#L498-L533
train
25,144
kdeldycke/maildir-deduplicate
maildir_deduplicate/deduplicate.py
Deduplicate.run
def run(self): """ Run the deduplication process. We apply the removal strategy one duplicate set at a time to keep memory footprint low and make the log of actions easier to read. """ logger.info( "The {} strategy will be applied on each duplicate set.".format( self.conf.strategy)) self.stats['set_total'] = len(self.mails) for hash_key, mail_path_set in self.mails.items(): # Print visual clue to separate duplicate sets. logger.info('---') duplicates = DuplicateSet(hash_key, mail_path_set, self.conf) # Perfom the deduplication. duplicates.dedupe() # Merge stats resulting of actions on duplicate sets. self.stats += duplicates.stats
python
def run(self): """ Run the deduplication process. We apply the removal strategy one duplicate set at a time to keep memory footprint low and make the log of actions easier to read. """ logger.info( "The {} strategy will be applied on each duplicate set.".format( self.conf.strategy)) self.stats['set_total'] = len(self.mails) for hash_key, mail_path_set in self.mails.items(): # Print visual clue to separate duplicate sets. logger.info('---') duplicates = DuplicateSet(hash_key, mail_path_set, self.conf) # Perfom the deduplication. duplicates.dedupe() # Merge stats resulting of actions on duplicate sets. self.stats += duplicates.stats
[ "def", "run", "(", "self", ")", ":", "logger", ".", "info", "(", "\"The {} strategy will be applied on each duplicate set.\"", ".", "format", "(", "self", ".", "conf", ".", "strategy", ")", ")", "self", ".", "stats", "[", "'set_total'", "]", "=", "len", "(",...
Run the deduplication process. We apply the removal strategy one duplicate set at a time to keep memory footprint low and make the log of actions easier to read.
[ "Run", "the", "deduplication", "process", "." ]
f1c6ff25b80c6c1a4dc2dc7a65b34d808b0b7733
https://github.com/kdeldycke/maildir-deduplicate/blob/f1c6ff25b80c6c1a4dc2dc7a65b34d808b0b7733/maildir_deduplicate/deduplicate.py#L535-L557
train
25,145
kdeldycke/maildir-deduplicate
maildir_deduplicate/deduplicate.py
Deduplicate.report
def report(self): """ Print user-friendly statistics and metrics. """ table = [["Mails", "Metric"]] table.append(["Found", self.stats['mail_found']]) table.append(["Skipped", self.stats['mail_skipped']]) table.append(["Rejected", self.stats['mail_rejected']]) table.append(["Kept", self.stats['mail_kept']]) table.append(["Unique", self.stats['mail_unique']]) table.append(["Duplicates", self.stats['mail_duplicates']]) table.append(["Deleted", self.stats['mail_deleted']]) logger.info(tabulate(table, tablefmt='fancy_grid', headers='firstrow')) table = [["Duplicate sets", "Metric"]] table.append(["Total", self.stats['set_total']]) table.append(["Ignored", self.stats['set_ignored']]) table.append(["Skipped", self.stats['set_skipped']]) table.append([ "Rejected (bad encoding)", self.stats['set_rejected_encoding']]) table.append([ "Rejected (too dissimilar in size)", self.stats['set_rejected_size']]) table.append([ "Rejected (too dissimilar in content)", self.stats['set_rejected_content']]) table.append(["Deduplicated", self.stats['set_deduplicated']]) logger.info(tabulate(table, tablefmt='fancy_grid', headers='firstrow')) # Perform some high-level consistency checks on metrics. assert self.stats['mail_found'] == ( self.stats['mail_skipped'] + self.stats['mail_rejected'] + self.stats['mail_kept']) assert self.stats['mail_kept'] >= self.stats['mail_unique'] assert self.stats['mail_kept'] >= self.stats['mail_duplicates'] assert self.stats['mail_kept'] >= self.stats['mail_deleted'] assert self.stats['mail_kept'] == ( self.stats['mail_unique'] + self.stats['mail_duplicates']) assert self.stats['mail_duplicates'] > self.stats['mail_deleted'] assert self.stats['set_ignored'] == self.stats['mail_unique'] assert self.stats['set_total'] == ( self.stats['set_ignored'] + self.stats['set_skipped'] + self.stats['set_rejected_encoding'] + self.stats['set_rejected_size'] + self.stats['set_rejected_content'] + self.stats['set_deduplicated'])
python
def report(self): """ Print user-friendly statistics and metrics. """ table = [["Mails", "Metric"]] table.append(["Found", self.stats['mail_found']]) table.append(["Skipped", self.stats['mail_skipped']]) table.append(["Rejected", self.stats['mail_rejected']]) table.append(["Kept", self.stats['mail_kept']]) table.append(["Unique", self.stats['mail_unique']]) table.append(["Duplicates", self.stats['mail_duplicates']]) table.append(["Deleted", self.stats['mail_deleted']]) logger.info(tabulate(table, tablefmt='fancy_grid', headers='firstrow')) table = [["Duplicate sets", "Metric"]] table.append(["Total", self.stats['set_total']]) table.append(["Ignored", self.stats['set_ignored']]) table.append(["Skipped", self.stats['set_skipped']]) table.append([ "Rejected (bad encoding)", self.stats['set_rejected_encoding']]) table.append([ "Rejected (too dissimilar in size)", self.stats['set_rejected_size']]) table.append([ "Rejected (too dissimilar in content)", self.stats['set_rejected_content']]) table.append(["Deduplicated", self.stats['set_deduplicated']]) logger.info(tabulate(table, tablefmt='fancy_grid', headers='firstrow')) # Perform some high-level consistency checks on metrics. assert self.stats['mail_found'] == ( self.stats['mail_skipped'] + self.stats['mail_rejected'] + self.stats['mail_kept']) assert self.stats['mail_kept'] >= self.stats['mail_unique'] assert self.stats['mail_kept'] >= self.stats['mail_duplicates'] assert self.stats['mail_kept'] >= self.stats['mail_deleted'] assert self.stats['mail_kept'] == ( self.stats['mail_unique'] + self.stats['mail_duplicates']) assert self.stats['mail_duplicates'] > self.stats['mail_deleted'] assert self.stats['set_ignored'] == self.stats['mail_unique'] assert self.stats['set_total'] == ( self.stats['set_ignored'] + self.stats['set_skipped'] + self.stats['set_rejected_encoding'] + self.stats['set_rejected_size'] + self.stats['set_rejected_content'] + self.stats['set_deduplicated'])
[ "def", "report", "(", "self", ")", ":", "table", "=", "[", "[", "\"Mails\"", ",", "\"Metric\"", "]", "]", "table", ".", "append", "(", "[", "\"Found\"", ",", "self", ".", "stats", "[", "'mail_found'", "]", "]", ")", "table", ".", "append", "(", "["...
Print user-friendly statistics and metrics.
[ "Print", "user", "-", "friendly", "statistics", "and", "metrics", "." ]
f1c6ff25b80c6c1a4dc2dc7a65b34d808b0b7733
https://github.com/kdeldycke/maildir-deduplicate/blob/f1c6ff25b80c6c1a4dc2dc7a65b34d808b0b7733/maildir_deduplicate/deduplicate.py#L559-L608
train
25,146
kdeldycke/maildir-deduplicate
maildir_deduplicate/cli.py
cli
def cli(ctx): """ CLI for maildirs content analysis and deletion. """ level = logger.level try: level_to_name = logging._levelToName # Fallback to pre-Python 3.4 internals. except AttributeError: level_to_name = logging._levelNames level_name = level_to_name.get(level, level) logger.debug('Verbosity set to {}.'.format(level_name)) # Print help screen and exit if no sub-commands provided. if ctx.invoked_subcommand is None: click.echo(ctx.get_help()) ctx.exit() # Load up global options to the context. ctx.obj = {}
python
def cli(ctx): """ CLI for maildirs content analysis and deletion. """ level = logger.level try: level_to_name = logging._levelToName # Fallback to pre-Python 3.4 internals. except AttributeError: level_to_name = logging._levelNames level_name = level_to_name.get(level, level) logger.debug('Verbosity set to {}.'.format(level_name)) # Print help screen and exit if no sub-commands provided. if ctx.invoked_subcommand is None: click.echo(ctx.get_help()) ctx.exit() # Load up global options to the context. ctx.obj = {}
[ "def", "cli", "(", "ctx", ")", ":", "level", "=", "logger", ".", "level", "try", ":", "level_to_name", "=", "logging", ".", "_levelToName", "# Fallback to pre-Python 3.4 internals.", "except", "AttributeError", ":", "level_to_name", "=", "logging", ".", "_levelNam...
CLI for maildirs content analysis and deletion.
[ "CLI", "for", "maildirs", "content", "analysis", "and", "deletion", "." ]
f1c6ff25b80c6c1a4dc2dc7a65b34d808b0b7733
https://github.com/kdeldycke/maildir-deduplicate/blob/f1c6ff25b80c6c1a4dc2dc7a65b34d808b0b7733/maildir_deduplicate/cli.py#L59-L76
train
25,147
kdeldycke/maildir-deduplicate
maildir_deduplicate/cli.py
validate_regexp
def validate_regexp(ctx, param, value): """ Validate and compile regular expression. """ if value: try: value = re.compile(value) except ValueError: raise click.BadParameter('invalid regular expression.') return value
python
def validate_regexp(ctx, param, value): """ Validate and compile regular expression. """ if value: try: value = re.compile(value) except ValueError: raise click.BadParameter('invalid regular expression.') return value
[ "def", "validate_regexp", "(", "ctx", ",", "param", ",", "value", ")", ":", "if", "value", ":", "try", ":", "value", "=", "re", ".", "compile", "(", "value", ")", "except", "ValueError", ":", "raise", "click", ".", "BadParameter", "(", "'invalid regular ...
Validate and compile regular expression.
[ "Validate", "and", "compile", "regular", "expression", "." ]
f1c6ff25b80c6c1a4dc2dc7a65b34d808b0b7733
https://github.com/kdeldycke/maildir-deduplicate/blob/f1c6ff25b80c6c1a4dc2dc7a65b34d808b0b7733/maildir_deduplicate/cli.py#L79-L86
train
25,148
kdeldycke/maildir-deduplicate
maildir_deduplicate/cli.py
validate_maildirs
def validate_maildirs(ctx, param, value): """ Check that folders are maildirs. """ for path in value: for subdir in MD_SUBDIRS: if not os.path.isdir(os.path.join(path, subdir)): raise click.BadParameter( '{} is not a maildir (missing {!r} sub-directory).'.format( path, subdir)) return value
python
def validate_maildirs(ctx, param, value): """ Check that folders are maildirs. """ for path in value: for subdir in MD_SUBDIRS: if not os.path.isdir(os.path.join(path, subdir)): raise click.BadParameter( '{} is not a maildir (missing {!r} sub-directory).'.format( path, subdir)) return value
[ "def", "validate_maildirs", "(", "ctx", ",", "param", ",", "value", ")", ":", "for", "path", "in", "value", ":", "for", "subdir", "in", "MD_SUBDIRS", ":", "if", "not", "os", ".", "path", ".", "isdir", "(", "os", ".", "path", ".", "join", "(", "path...
Check that folders are maildirs.
[ "Check", "that", "folders", "are", "maildirs", "." ]
f1c6ff25b80c6c1a4dc2dc7a65b34d808b0b7733
https://github.com/kdeldycke/maildir-deduplicate/blob/f1c6ff25b80c6c1a4dc2dc7a65b34d808b0b7733/maildir_deduplicate/cli.py#L89-L97
train
25,149
kdeldycke/maildir-deduplicate
maildir_deduplicate/cli.py
deduplicate
def deduplicate( ctx, strategy, time_source, regexp, dry_run, message_id, size_threshold, content_threshold, show_diff, maildirs): """ Deduplicate mails from a set of maildir folders. Run a first pass computing the canonical hash of each encountered mail from their headers, then a second pass to apply the deletion strategy on each subset of duplicate mails. \b Removal strategies for each subsets of duplicate mails: - delete-older: Deletes the olders, keeps the newests. - delete-oldest: Deletes the oldests, keeps the newers. - delete-newer: Deletes the newers, keeps the oldests. - delete-newest: Deletes the newests, keeps the olders. - delete-smaller: Deletes the smallers, keeps the biggests. - delete-smallest: Deletes the smallests, keeps the biggers. - delete-bigger: Deletes the biggers, keeps the smallests. - delete-biggest: Deletes the biggests, keeps the smallers. - delete-matching-path: Deletes all duplicates whose file path match the regular expression provided via the --regexp parameter. - delete-non-matching-path: Deletes all duplicates whose file path doesn't match the regular expression provided via the --regexp parameter. Deletion strategy on a duplicate set only applies if no major differences between mails are uncovered during a fine-grained check differences during the second pass. Limits can be set via the threshold options. """ # Print help screen and exit if no maildir folder provided. if not maildirs: click.echo(ctx.get_help()) ctx.exit() # Validate exclusive options requirement depending on strategy. requirements = [ (time_source, '-t/--time-source', [ DELETE_OLDER, DELETE_OLDEST, DELETE_NEWER, DELETE_NEWEST]), (regexp, '-r/--regexp', [ DELETE_MATCHING_PATH, DELETE_NON_MATCHING_PATH])] for param_value, param_name, required_strategies in requirements: if strategy in required_strategies: if not param_value: raise click.BadParameter( '{} strategy requires the {} parameter.'.format( strategy, param_name)) elif param_value: raise click.BadParameter( '{} parameter not allowed in {} strategy.'.format( param_name, strategy)) conf = Config( strategy=strategy, time_source=time_source, regexp=regexp, dry_run=dry_run, show_diff=show_diff, message_id=message_id, size_threshold=size_threshold, content_threshold=content_threshold, # progress=progress, ) dedup = Deduplicate(conf) logger.info('=== Start phase #1: load mails and compute hashes.') for maildir in maildirs: dedup.add_maildir(maildir) logger.info('=== Start phase #2: deduplicate mails.') dedup.run() dedup.report()
python
def deduplicate( ctx, strategy, time_source, regexp, dry_run, message_id, size_threshold, content_threshold, show_diff, maildirs): """ Deduplicate mails from a set of maildir folders. Run a first pass computing the canonical hash of each encountered mail from their headers, then a second pass to apply the deletion strategy on each subset of duplicate mails. \b Removal strategies for each subsets of duplicate mails: - delete-older: Deletes the olders, keeps the newests. - delete-oldest: Deletes the oldests, keeps the newers. - delete-newer: Deletes the newers, keeps the oldests. - delete-newest: Deletes the newests, keeps the olders. - delete-smaller: Deletes the smallers, keeps the biggests. - delete-smallest: Deletes the smallests, keeps the biggers. - delete-bigger: Deletes the biggers, keeps the smallests. - delete-biggest: Deletes the biggests, keeps the smallers. - delete-matching-path: Deletes all duplicates whose file path match the regular expression provided via the --regexp parameter. - delete-non-matching-path: Deletes all duplicates whose file path doesn't match the regular expression provided via the --regexp parameter. Deletion strategy on a duplicate set only applies if no major differences between mails are uncovered during a fine-grained check differences during the second pass. Limits can be set via the threshold options. """ # Print help screen and exit if no maildir folder provided. if not maildirs: click.echo(ctx.get_help()) ctx.exit() # Validate exclusive options requirement depending on strategy. requirements = [ (time_source, '-t/--time-source', [ DELETE_OLDER, DELETE_OLDEST, DELETE_NEWER, DELETE_NEWEST]), (regexp, '-r/--regexp', [ DELETE_MATCHING_PATH, DELETE_NON_MATCHING_PATH])] for param_value, param_name, required_strategies in requirements: if strategy in required_strategies: if not param_value: raise click.BadParameter( '{} strategy requires the {} parameter.'.format( strategy, param_name)) elif param_value: raise click.BadParameter( '{} parameter not allowed in {} strategy.'.format( param_name, strategy)) conf = Config( strategy=strategy, time_source=time_source, regexp=regexp, dry_run=dry_run, show_diff=show_diff, message_id=message_id, size_threshold=size_threshold, content_threshold=content_threshold, # progress=progress, ) dedup = Deduplicate(conf) logger.info('=== Start phase #1: load mails and compute hashes.') for maildir in maildirs: dedup.add_maildir(maildir) logger.info('=== Start phase #2: deduplicate mails.') dedup.run() dedup.report()
[ "def", "deduplicate", "(", "ctx", ",", "strategy", ",", "time_source", ",", "regexp", ",", "dry_run", ",", "message_id", ",", "size_threshold", ",", "content_threshold", ",", "show_diff", ",", "maildirs", ")", ":", "# Print help screen and exit if no maildir folder pr...
Deduplicate mails from a set of maildir folders. Run a first pass computing the canonical hash of each encountered mail from their headers, then a second pass to apply the deletion strategy on each subset of duplicate mails. \b Removal strategies for each subsets of duplicate mails: - delete-older: Deletes the olders, keeps the newests. - delete-oldest: Deletes the oldests, keeps the newers. - delete-newer: Deletes the newers, keeps the oldests. - delete-newest: Deletes the newests, keeps the olders. - delete-smaller: Deletes the smallers, keeps the biggests. - delete-smallest: Deletes the smallests, keeps the biggers. - delete-bigger: Deletes the biggers, keeps the smallests. - delete-biggest: Deletes the biggests, keeps the smallers. - delete-matching-path: Deletes all duplicates whose file path match the regular expression provided via the --regexp parameter. - delete-non-matching-path: Deletes all duplicates whose file path doesn't match the regular expression provided via the --regexp parameter. Deletion strategy on a duplicate set only applies if no major differences between mails are uncovered during a fine-grained check differences during the second pass. Limits can be set via the threshold options.
[ "Deduplicate", "mails", "from", "a", "set", "of", "maildir", "folders", "." ]
f1c6ff25b80c6c1a4dc2dc7a65b34d808b0b7733
https://github.com/kdeldycke/maildir-deduplicate/blob/f1c6ff25b80c6c1a4dc2dc7a65b34d808b0b7733/maildir_deduplicate/cli.py#L140-L211
train
25,150
kdeldycke/maildir-deduplicate
maildir_deduplicate/cli.py
hash
def hash(ctx, message_id, message): """ Take a single mail message and show its canonicalised form and hash. Mainly used to debug message hashing. """ conf = Config(message_id=message_id) mail = Mail(message, conf) logger.info(mail.header_text) logger.info('-' * 70) logger.info('Hash: {}'.format(mail.hash_key))
python
def hash(ctx, message_id, message): """ Take a single mail message and show its canonicalised form and hash. Mainly used to debug message hashing. """ conf = Config(message_id=message_id) mail = Mail(message, conf) logger.info(mail.header_text) logger.info('-' * 70) logger.info('Hash: {}'.format(mail.hash_key))
[ "def", "hash", "(", "ctx", ",", "message_id", ",", "message", ")", ":", "conf", "=", "Config", "(", "message_id", "=", "message_id", ")", "mail", "=", "Mail", "(", "message", ",", "conf", ")", "logger", ".", "info", "(", "mail", ".", "header_text", "...
Take a single mail message and show its canonicalised form and hash. Mainly used to debug message hashing.
[ "Take", "a", "single", "mail", "message", "and", "show", "its", "canonicalised", "form", "and", "hash", "." ]
f1c6ff25b80c6c1a4dc2dc7a65b34d808b0b7733
https://github.com/kdeldycke/maildir-deduplicate/blob/f1c6ff25b80c6c1a4dc2dc7a65b34d808b0b7733/maildir_deduplicate/cli.py#L224-L235
train
25,151
kdeldycke/maildir-deduplicate
setup.py
read_file
def read_file(*relative_path_elements): """ Return content of a file relative to this ``setup.py``. """ file_path = path.join(path.dirname(__file__), *relative_path_elements) return io.open(file_path, encoding='utf8').read().strip()
python
def read_file(*relative_path_elements): """ Return content of a file relative to this ``setup.py``. """ file_path = path.join(path.dirname(__file__), *relative_path_elements) return io.open(file_path, encoding='utf8').read().strip()
[ "def", "read_file", "(", "*", "relative_path_elements", ")", ":", "file_path", "=", "path", ".", "join", "(", "path", ".", "dirname", "(", "__file__", ")", ",", "*", "relative_path_elements", ")", "return", "io", ".", "open", "(", "file_path", ",", "encodi...
Return content of a file relative to this ``setup.py``.
[ "Return", "content", "of", "a", "file", "relative", "to", "this", "setup", ".", "py", "." ]
f1c6ff25b80c6c1a4dc2dc7a65b34d808b0b7733
https://github.com/kdeldycke/maildir-deduplicate/blob/f1c6ff25b80c6c1a4dc2dc7a65b34d808b0b7733/setup.py#L68-L71
train
25,152
kdeldycke/maildir-deduplicate
maildir_deduplicate/mail.py
Mail.message
def message(self): """ Read mail, parse it and return a Message instance. """ logger.debug("Parsing mail at {} ...".format(self.path)) with open(self.path, 'rb') as mail_file: if PY2: message = email.message_from_file(mail_file) else: message = email.message_from_binary_file(mail_file) return message
python
def message(self): """ Read mail, parse it and return a Message instance. """ logger.debug("Parsing mail at {} ...".format(self.path)) with open(self.path, 'rb') as mail_file: if PY2: message = email.message_from_file(mail_file) else: message = email.message_from_binary_file(mail_file) return message
[ "def", "message", "(", "self", ")", ":", "logger", ".", "debug", "(", "\"Parsing mail at {} ...\"", ".", "format", "(", "self", ".", "path", ")", ")", "with", "open", "(", "self", ".", "path", ",", "'rb'", ")", "as", "mail_file", ":", "if", "PY2", ":...
Read mail, parse it and return a Message instance.
[ "Read", "mail", "parse", "it", "and", "return", "a", "Message", "instance", "." ]
f1c6ff25b80c6c1a4dc2dc7a65b34d808b0b7733
https://github.com/kdeldycke/maildir-deduplicate/blob/f1c6ff25b80c6c1a4dc2dc7a65b34d808b0b7733/maildir_deduplicate/mail.py#L60-L68
train
25,153
kdeldycke/maildir-deduplicate
maildir_deduplicate/mail.py
Mail.timestamp
def timestamp(self): """ Compute the normalized canonical timestamp of the mail. """ # XXX ctime does not refer to creation time on POSIX systems, but # rather the last time the inode data changed. Source: # https://userprimary.net/posts/2007/11/18 # /ctime-in-unix-means-last-change-time-not-create-time/ if self.conf.time_source == CTIME: return os.path.getctime(self.path) # Fetch from the date header. return email.utils.mktime_tz(email.utils.parsedate_tz( self.message.get('Date')))
python
def timestamp(self): """ Compute the normalized canonical timestamp of the mail. """ # XXX ctime does not refer to creation time on POSIX systems, but # rather the last time the inode data changed. Source: # https://userprimary.net/posts/2007/11/18 # /ctime-in-unix-means-last-change-time-not-create-time/ if self.conf.time_source == CTIME: return os.path.getctime(self.path) # Fetch from the date header. return email.utils.mktime_tz(email.utils.parsedate_tz( self.message.get('Date')))
[ "def", "timestamp", "(", "self", ")", ":", "# XXX ctime does not refer to creation time on POSIX systems, but", "# rather the last time the inode data changed. Source:", "# https://userprimary.net/posts/2007/11/18", "# /ctime-in-unix-means-last-change-time-not-create-time/", "if", "self", "....
Compute the normalized canonical timestamp of the mail.
[ "Compute", "the", "normalized", "canonical", "timestamp", "of", "the", "mail", "." ]
f1c6ff25b80c6c1a4dc2dc7a65b34d808b0b7733
https://github.com/kdeldycke/maildir-deduplicate/blob/f1c6ff25b80c6c1a4dc2dc7a65b34d808b0b7733/maildir_deduplicate/mail.py#L71-L82
train
25,154
kdeldycke/maildir-deduplicate
maildir_deduplicate/mail.py
Mail.body_lines
def body_lines(self): """ Return a normalized list of lines from message's body. """ if not self.message.is_multipart(): body = self.message.get_payload(None, decode=True) else: _, _, body = self.message.as_string().partition("\n\n") if isinstance(body, bytes): for enc in ['ascii', 'utf-8']: try: body = body.decode(enc) break except UnicodeDecodeError: continue else: body = self.message.get_payload(None, decode=False) return body.splitlines(True)
python
def body_lines(self): """ Return a normalized list of lines from message's body. """ if not self.message.is_multipart(): body = self.message.get_payload(None, decode=True) else: _, _, body = self.message.as_string().partition("\n\n") if isinstance(body, bytes): for enc in ['ascii', 'utf-8']: try: body = body.decode(enc) break except UnicodeDecodeError: continue else: body = self.message.get_payload(None, decode=False) return body.splitlines(True)
[ "def", "body_lines", "(", "self", ")", ":", "if", "not", "self", ".", "message", ".", "is_multipart", "(", ")", ":", "body", "=", "self", ".", "message", ".", "get_payload", "(", "None", ",", "decode", "=", "True", ")", "else", ":", "_", ",", "_", ...
Return a normalized list of lines from message's body.
[ "Return", "a", "normalized", "list", "of", "lines", "from", "message", "s", "body", "." ]
f1c6ff25b80c6c1a4dc2dc7a65b34d808b0b7733
https://github.com/kdeldycke/maildir-deduplicate/blob/f1c6ff25b80c6c1a4dc2dc7a65b34d808b0b7733/maildir_deduplicate/mail.py#L99-L114
train
25,155
kdeldycke/maildir-deduplicate
maildir_deduplicate/mail.py
Mail.subject
def subject(self): """ Normalized subject. Only used for debugging and human-friendly logging. """ # Fetch subject from first message. subject = self.message.get('Subject', '') subject, _ = re.subn(r'\s+', ' ', subject) return subject
python
def subject(self): """ Normalized subject. Only used for debugging and human-friendly logging. """ # Fetch subject from first message. subject = self.message.get('Subject', '') subject, _ = re.subn(r'\s+', ' ', subject) return subject
[ "def", "subject", "(", "self", ")", ":", "# Fetch subject from first message.", "subject", "=", "self", ".", "message", ".", "get", "(", "'Subject'", ",", "''", ")", "subject", ",", "_", "=", "re", ".", "subn", "(", "r'\\s+'", ",", "' '", ",", "subject",...
Normalized subject. Only used for debugging and human-friendly logging.
[ "Normalized", "subject", "." ]
f1c6ff25b80c6c1a4dc2dc7a65b34d808b0b7733
https://github.com/kdeldycke/maildir-deduplicate/blob/f1c6ff25b80c6c1a4dc2dc7a65b34d808b0b7733/maildir_deduplicate/mail.py#L117-L125
train
25,156
kdeldycke/maildir-deduplicate
maildir_deduplicate/mail.py
Mail.hash_key
def hash_key(self): """ Returns the canonical hash of a mail. """ if self.conf.message_id: message_id = self.message.get('Message-Id') if message_id: return message_id.strip() logger.error( "No Message-ID in {}: {}".format(self.path, self.header_text)) raise MissingMessageID return hashlib.sha224(self.canonical_headers).hexdigest()
python
def hash_key(self): """ Returns the canonical hash of a mail. """ if self.conf.message_id: message_id = self.message.get('Message-Id') if message_id: return message_id.strip() logger.error( "No Message-ID in {}: {}".format(self.path, self.header_text)) raise MissingMessageID return hashlib.sha224(self.canonical_headers).hexdigest()
[ "def", "hash_key", "(", "self", ")", ":", "if", "self", ".", "conf", ".", "message_id", ":", "message_id", "=", "self", ".", "message", ".", "get", "(", "'Message-Id'", ")", "if", "message_id", ":", "return", "message_id", ".", "strip", "(", ")", "logg...
Returns the canonical hash of a mail.
[ "Returns", "the", "canonical", "hash", "of", "a", "mail", "." ]
f1c6ff25b80c6c1a4dc2dc7a65b34d808b0b7733
https://github.com/kdeldycke/maildir-deduplicate/blob/f1c6ff25b80c6c1a4dc2dc7a65b34d808b0b7733/maildir_deduplicate/mail.py#L128-L138
train
25,157
kdeldycke/maildir-deduplicate
maildir_deduplicate/mail.py
Mail.canonical_headers
def canonical_headers(self): """ Copy selected headers into a new string. """ canonical_headers = '' for header in HEADERS: if header not in self.message: continue for value in self.message.get_all(header): canonical_value = self.canonical_header_value(header, value) if re.search(r'\S', canonical_value): canonical_headers += '{}: {}\n'.format( header, canonical_value) canonical_headers = canonical_headers.encode('utf-8') if len(canonical_headers) > 50: return canonical_headers # At this point we should have at absolute minimum 3 or 4 headers, e.g. # From/To/Date/Subject; if not, something went badly wrong. if len(canonical_headers) == 0: raise InsufficientHeadersError("No canonical headers found") err = textwrap.dedent("""\ Not enough data from canonical headers to compute reliable hash! Headers: --------- 8< --------- 8< --------- 8< --------- 8< --------- {} --------- 8< --------- 8< --------- 8< --------- 8< ---------""") raise InsufficientHeadersError(err.format(canonical_headers))
python
def canonical_headers(self): """ Copy selected headers into a new string. """ canonical_headers = '' for header in HEADERS: if header not in self.message: continue for value in self.message.get_all(header): canonical_value = self.canonical_header_value(header, value) if re.search(r'\S', canonical_value): canonical_headers += '{}: {}\n'.format( header, canonical_value) canonical_headers = canonical_headers.encode('utf-8') if len(canonical_headers) > 50: return canonical_headers # At this point we should have at absolute minimum 3 or 4 headers, e.g. # From/To/Date/Subject; if not, something went badly wrong. if len(canonical_headers) == 0: raise InsufficientHeadersError("No canonical headers found") err = textwrap.dedent("""\ Not enough data from canonical headers to compute reliable hash! Headers: --------- 8< --------- 8< --------- 8< --------- 8< --------- {} --------- 8< --------- 8< --------- 8< --------- 8< ---------""") raise InsufficientHeadersError(err.format(canonical_headers))
[ "def", "canonical_headers", "(", "self", ")", ":", "canonical_headers", "=", "''", "for", "header", "in", "HEADERS", ":", "if", "header", "not", "in", "self", ".", "message", ":", "continue", "for", "value", "in", "self", ".", "message", ".", "get_all", ...
Copy selected headers into a new string.
[ "Copy", "selected", "headers", "into", "a", "new", "string", "." ]
f1c6ff25b80c6c1a4dc2dc7a65b34d808b0b7733
https://github.com/kdeldycke/maildir-deduplicate/blob/f1c6ff25b80c6c1a4dc2dc7a65b34d808b0b7733/maildir_deduplicate/mail.py#L148-L178
train
25,158
keepkey/python-keepkey
keepkeylib/transport_hid.py
HidTransport.enumerate
def enumerate(cls): """ Return a list of available KeepKey devices. """ devices = {} for d in hid.enumerate(0, 0): vendor_id = d['vendor_id'] product_id = d['product_id'] serial_number = d['serial_number'] interface_number = d['interface_number'] path = d['path'] # HIDAPI on Mac cannot detect correct HID interfaces, so device with # DebugLink doesn't work on Mac... if devices.get(serial_number) != None and devices[serial_number][0] == path: raise Exception("Two devices with the same path and S/N found. This is Mac, right? :-/") if (vendor_id, product_id) in DEVICE_IDS: devices.setdefault(serial_number, [None, None, None]) if is_normal_link(d): devices[serial_number][0] = path elif is_debug_link(d): devices[serial_number][1] = path else: raise Exception("Unknown USB interface number: %d" % interface_number) # List of two-tuples (path_normal, path_debuglink) return list(devices.values())
python
def enumerate(cls): """ Return a list of available KeepKey devices. """ devices = {} for d in hid.enumerate(0, 0): vendor_id = d['vendor_id'] product_id = d['product_id'] serial_number = d['serial_number'] interface_number = d['interface_number'] path = d['path'] # HIDAPI on Mac cannot detect correct HID interfaces, so device with # DebugLink doesn't work on Mac... if devices.get(serial_number) != None and devices[serial_number][0] == path: raise Exception("Two devices with the same path and S/N found. This is Mac, right? :-/") if (vendor_id, product_id) in DEVICE_IDS: devices.setdefault(serial_number, [None, None, None]) if is_normal_link(d): devices[serial_number][0] = path elif is_debug_link(d): devices[serial_number][1] = path else: raise Exception("Unknown USB interface number: %d" % interface_number) # List of two-tuples (path_normal, path_debuglink) return list(devices.values())
[ "def", "enumerate", "(", "cls", ")", ":", "devices", "=", "{", "}", "for", "d", "in", "hid", ".", "enumerate", "(", "0", ",", "0", ")", ":", "vendor_id", "=", "d", "[", "'vendor_id'", "]", "product_id", "=", "d", "[", "'product_id'", "]", "serial_n...
Return a list of available KeepKey devices.
[ "Return", "a", "list", "of", "available", "KeepKey", "devices", "." ]
8318e3a8c4025d499342130ce4305881a325c013
https://github.com/keepkey/python-keepkey/blob/8318e3a8c4025d499342130ce4305881a325c013/keepkeylib/transport_hid.py#L75-L102
train
25,159
keepkey/python-keepkey
keepkeylib/transport_hid.py
HidTransport.is_connected
def is_connected(self): """ Check if the device is still connected. """ for d in hid.enumerate(0, 0): if d['path'] == self.device: return True return False
python
def is_connected(self): """ Check if the device is still connected. """ for d in hid.enumerate(0, 0): if d['path'] == self.device: return True return False
[ "def", "is_connected", "(", "self", ")", ":", "for", "d", "in", "hid", ".", "enumerate", "(", "0", ",", "0", ")", ":", "if", "d", "[", "'path'", "]", "==", "self", ".", "device", ":", "return", "True", "return", "False" ]
Check if the device is still connected.
[ "Check", "if", "the", "device", "is", "still", "connected", "." ]
8318e3a8c4025d499342130ce4305881a325c013
https://github.com/keepkey/python-keepkey/blob/8318e3a8c4025d499342130ce4305881a325c013/keepkeylib/transport_hid.py#L104-L111
train
25,160
keepkey/python-keepkey
keepkeylib/transport.py
Transport.session_end
def session_end(self): """ End a session. Se session_begin for an in depth description of TREZOR sessions. """ self.session_depth -= 1 self.session_depth = max(0, self.session_depth) if self.session_depth == 0: self._session_end()
python
def session_end(self): """ End a session. Se session_begin for an in depth description of TREZOR sessions. """ self.session_depth -= 1 self.session_depth = max(0, self.session_depth) if self.session_depth == 0: self._session_end()
[ "def", "session_end", "(", "self", ")", ":", "self", ".", "session_depth", "-=", "1", "self", ".", "session_depth", "=", "max", "(", "0", ",", "self", ".", "session_depth", ")", "if", "self", ".", "session_depth", "==", "0", ":", "self", ".", "_session...
End a session. Se session_begin for an in depth description of TREZOR sessions.
[ "End", "a", "session", ".", "Se", "session_begin", "for", "an", "in", "depth", "description", "of", "TREZOR", "sessions", "." ]
8318e3a8c4025d499342130ce4305881a325c013
https://github.com/keepkey/python-keepkey/blob/8318e3a8c4025d499342130ce4305881a325c013/keepkeylib/transport.py#L48-L55
train
25,161
keepkey/python-keepkey
keepkeylib/transport.py
Transport.read
def read(self): """ If there is data available to be read from the transport, reads the data and tries to parse it as a protobuf message. If the parsing succeeds, return a protobuf object. Otherwise, returns None. """ if not self.ready_to_read(): return None data = self._read() if data is None: return None return self._parse_message(data)
python
def read(self): """ If there is data available to be read from the transport, reads the data and tries to parse it as a protobuf message. If the parsing succeeds, return a protobuf object. Otherwise, returns None. """ if not self.ready_to_read(): return None data = self._read() if data is None: return None return self._parse_message(data)
[ "def", "read", "(", "self", ")", ":", "if", "not", "self", ".", "ready_to_read", "(", ")", ":", "return", "None", "data", "=", "self", ".", "_read", "(", ")", "if", "data", "is", "None", ":", "return", "None", "return", "self", ".", "_parse_message",...
If there is data available to be read from the transport, reads the data and tries to parse it as a protobuf message. If the parsing succeeds, return a protobuf object. Otherwise, returns None.
[ "If", "there", "is", "data", "available", "to", "be", "read", "from", "the", "transport", "reads", "the", "data", "and", "tries", "to", "parse", "it", "as", "a", "protobuf", "message", ".", "If", "the", "parsing", "succeeds", "return", "a", "protobuf", "...
8318e3a8c4025d499342130ce4305881a325c013
https://github.com/keepkey/python-keepkey/blob/8318e3a8c4025d499342130ce4305881a325c013/keepkeylib/transport.py#L71-L83
train
25,162
keepkey/python-keepkey
keepkeylib/transport.py
Transport.read_blocking
def read_blocking(self): """ Same as read, except blocks untill data is available to be read. """ while True: data = self._read() if data != None: break return self._parse_message(data)
python
def read_blocking(self): """ Same as read, except blocks untill data is available to be read. """ while True: data = self._read() if data != None: break return self._parse_message(data)
[ "def", "read_blocking", "(", "self", ")", ":", "while", "True", ":", "data", "=", "self", ".", "_read", "(", ")", "if", "data", "!=", "None", ":", "break", "return", "self", ".", "_parse_message", "(", "data", ")" ]
Same as read, except blocks untill data is available to be read.
[ "Same", "as", "read", "except", "blocks", "untill", "data", "is", "available", "to", "be", "read", "." ]
8318e3a8c4025d499342130ce4305881a325c013
https://github.com/keepkey/python-keepkey/blob/8318e3a8c4025d499342130ce4305881a325c013/keepkeylib/transport.py#L85-L94
train
25,163
keepkey/python-keepkey
keepkeylib/filecache.py
_get_cache_name
def _get_cache_name(function): """ returns a name for the module's cache db. """ module_name = _inspect.getfile(function) module_name = _os.path.abspath(module_name) cache_name = module_name # fix for '<string>' or '<stdin>' in exec or interpreter usage. cache_name = cache_name.replace('<', '_lt_') cache_name = cache_name.replace('>', '_gt_') tmpdir = _os.getenv('TMPDIR') or _os.getenv('TEMP') or _os.getenv('TMP') if tmpdir: cache_name = tmpdir + '/filecache_' + cache_name.replace(_os.sep, '@') cache_name += '.cache' return cache_name
python
def _get_cache_name(function): """ returns a name for the module's cache db. """ module_name = _inspect.getfile(function) module_name = _os.path.abspath(module_name) cache_name = module_name # fix for '<string>' or '<stdin>' in exec or interpreter usage. cache_name = cache_name.replace('<', '_lt_') cache_name = cache_name.replace('>', '_gt_') tmpdir = _os.getenv('TMPDIR') or _os.getenv('TEMP') or _os.getenv('TMP') if tmpdir: cache_name = tmpdir + '/filecache_' + cache_name.replace(_os.sep, '@') cache_name += '.cache' return cache_name
[ "def", "_get_cache_name", "(", "function", ")", ":", "module_name", "=", "_inspect", ".", "getfile", "(", "function", ")", "module_name", "=", "_os", ".", "path", ".", "abspath", "(", "module_name", ")", "cache_name", "=", "module_name", "# fix for '<string>' or...
returns a name for the module's cache db.
[ "returns", "a", "name", "for", "the", "module", "s", "cache", "db", "." ]
8318e3a8c4025d499342130ce4305881a325c013
https://github.com/keepkey/python-keepkey/blob/8318e3a8c4025d499342130ce4305881a325c013/keepkeylib/filecache.py#L81-L98
train
25,164
keepkey/python-keepkey
keepkeylib/filecache.py
filecache
def filecache(seconds_of_validity=None, fail_silently=False): ''' filecache is called and the decorator should be returned. ''' def filecache_decorator(function): @_functools.wraps(function) def function_with_cache(*args, **kwargs): try: key = _args_key(function, args, kwargs) if key in function._db: rv = function._db[key] if seconds_of_validity is None or _time.time() - rv.timesig < seconds_of_validity: return rv.data except Exception: # in any case of failure, don't let filecache break the program error_str = _traceback.format_exc() _log_error(error_str) if not fail_silently: raise retval = function(*args, **kwargs) # store in cache # NOTE: no need to _db.sync() because there was no mutation # NOTE: it's importatnt to do _db.sync() because otherwise the cache doesn't survive Ctrl-Break! try: function._db[key] = _retval(_time.time(), retval) function._db.sync() except Exception: # in any case of failure, don't let filecache break the program error_str = _traceback.format_exc() _log_error(error_str) if not fail_silently: raise return retval # make sure cache is loaded if not hasattr(function, '_db'): cache_name = _get_cache_name(function) if cache_name in OPEN_DBS: function._db = OPEN_DBS[cache_name] else: function._db = _shelve.open(cache_name) OPEN_DBS[cache_name] = function._db atexit.register(function._db.close) function_with_cache._db = function._db return function_with_cache if type(seconds_of_validity) == types.FunctionType: # support for when people use '@filecache.filecache' instead of '@filecache.filecache()' func = seconds_of_validity seconds_of_validity = None return filecache_decorator(func) return filecache_decorator
python
def filecache(seconds_of_validity=None, fail_silently=False): ''' filecache is called and the decorator should be returned. ''' def filecache_decorator(function): @_functools.wraps(function) def function_with_cache(*args, **kwargs): try: key = _args_key(function, args, kwargs) if key in function._db: rv = function._db[key] if seconds_of_validity is None or _time.time() - rv.timesig < seconds_of_validity: return rv.data except Exception: # in any case of failure, don't let filecache break the program error_str = _traceback.format_exc() _log_error(error_str) if not fail_silently: raise retval = function(*args, **kwargs) # store in cache # NOTE: no need to _db.sync() because there was no mutation # NOTE: it's importatnt to do _db.sync() because otherwise the cache doesn't survive Ctrl-Break! try: function._db[key] = _retval(_time.time(), retval) function._db.sync() except Exception: # in any case of failure, don't let filecache break the program error_str = _traceback.format_exc() _log_error(error_str) if not fail_silently: raise return retval # make sure cache is loaded if not hasattr(function, '_db'): cache_name = _get_cache_name(function) if cache_name in OPEN_DBS: function._db = OPEN_DBS[cache_name] else: function._db = _shelve.open(cache_name) OPEN_DBS[cache_name] = function._db atexit.register(function._db.close) function_with_cache._db = function._db return function_with_cache if type(seconds_of_validity) == types.FunctionType: # support for when people use '@filecache.filecache' instead of '@filecache.filecache()' func = seconds_of_validity seconds_of_validity = None return filecache_decorator(func) return filecache_decorator
[ "def", "filecache", "(", "seconds_of_validity", "=", "None", ",", "fail_silently", "=", "False", ")", ":", "def", "filecache_decorator", "(", "function", ")", ":", "@", "_functools", ".", "wraps", "(", "function", ")", "def", "function_with_cache", "(", "*", ...
filecache is called and the decorator should be returned.
[ "filecache", "is", "called", "and", "the", "decorator", "should", "be", "returned", "." ]
8318e3a8c4025d499342130ce4305881a325c013
https://github.com/keepkey/python-keepkey/blob/8318e3a8c4025d499342130ce4305881a325c013/keepkeylib/filecache.py#L129-L187
train
25,165
juju/python-libjuju
juju/model.py
ModelState.entity_data
def entity_data(self, entity_type, entity_id, history_index): """Return the data dict for an entity at a specific index of its history. """ return self.entity_history(entity_type, entity_id)[history_index]
python
def entity_data(self, entity_type, entity_id, history_index): """Return the data dict for an entity at a specific index of its history. """ return self.entity_history(entity_type, entity_id)[history_index]
[ "def", "entity_data", "(", "self", ",", "entity_type", ",", "entity_id", ",", "history_index", ")", ":", "return", "self", ".", "entity_history", "(", "entity_type", ",", "entity_id", ")", "[", "history_index", "]" ]
Return the data dict for an entity at a specific index of its history.
[ "Return", "the", "data", "dict", "for", "an", "entity", "at", "a", "specific", "index", "of", "its", "history", "." ]
58f0011f4c57cd68830258952fa952eaadca6b38
https://github.com/juju/python-libjuju/blob/58f0011f4c57cd68830258952fa952eaadca6b38/juju/model.py#L164-L169
train
25,166
juju/python-libjuju
juju/model.py
ModelState.get_entity
def get_entity( self, entity_type, entity_id, history_index=-1, connected=True): """Return an object instance for the given entity_type and id. By default the object state matches the most recent state from Juju. To get an instance of the object in an older state, pass history_index, an index into the history deque for the entity. """ if history_index < 0 and history_index != -1: history_index += len(self.entity_history(entity_type, entity_id)) if history_index < 0: return None try: self.entity_data(entity_type, entity_id, history_index) except IndexError: return None entity_class = get_entity_class(entity_type) return entity_class( entity_id, self.model, history_index=history_index, connected=connected)
python
def get_entity( self, entity_type, entity_id, history_index=-1, connected=True): """Return an object instance for the given entity_type and id. By default the object state matches the most recent state from Juju. To get an instance of the object in an older state, pass history_index, an index into the history deque for the entity. """ if history_index < 0 and history_index != -1: history_index += len(self.entity_history(entity_type, entity_id)) if history_index < 0: return None try: self.entity_data(entity_type, entity_id, history_index) except IndexError: return None entity_class = get_entity_class(entity_type) return entity_class( entity_id, self.model, history_index=history_index, connected=connected)
[ "def", "get_entity", "(", "self", ",", "entity_type", ",", "entity_id", ",", "history_index", "=", "-", "1", ",", "connected", "=", "True", ")", ":", "if", "history_index", "<", "0", "and", "history_index", "!=", "-", "1", ":", "history_index", "+=", "le...
Return an object instance for the given entity_type and id. By default the object state matches the most recent state from Juju. To get an instance of the object in an older state, pass history_index, an index into the history deque for the entity.
[ "Return", "an", "object", "instance", "for", "the", "given", "entity_type", "and", "id", "." ]
58f0011f4c57cd68830258952fa952eaadca6b38
https://github.com/juju/python-libjuju/blob/58f0011f4c57cd68830258952fa952eaadca6b38/juju/model.py#L197-L220
train
25,167
juju/python-libjuju
juju/model.py
ModelEntity.on_change
def on_change(self, callable_): """Add a change observer to this entity. """ self.model.add_observer( callable_, self.entity_type, 'change', self.entity_id)
python
def on_change(self, callable_): """Add a change observer to this entity. """ self.model.add_observer( callable_, self.entity_type, 'change', self.entity_id)
[ "def", "on_change", "(", "self", ",", "callable_", ")", ":", "self", ".", "model", ".", "add_observer", "(", "callable_", ",", "self", ".", "entity_type", ",", "'change'", ",", "self", ".", "entity_id", ")" ]
Add a change observer to this entity.
[ "Add", "a", "change", "observer", "to", "this", "entity", "." ]
58f0011f4c57cd68830258952fa952eaadca6b38
https://github.com/juju/python-libjuju/blob/58f0011f4c57cd68830258952fa952eaadca6b38/juju/model.py#L265-L270
train
25,168
juju/python-libjuju
juju/model.py
ModelEntity.on_remove
def on_remove(self, callable_): """Add a remove observer to this entity. """ self.model.add_observer( callable_, self.entity_type, 'remove', self.entity_id)
python
def on_remove(self, callable_): """Add a remove observer to this entity. """ self.model.add_observer( callable_, self.entity_type, 'remove', self.entity_id)
[ "def", "on_remove", "(", "self", ",", "callable_", ")", ":", "self", ".", "model", ".", "add_observer", "(", "callable_", ",", "self", ".", "entity_type", ",", "'remove'", ",", "self", ".", "entity_id", ")" ]
Add a remove observer to this entity.
[ "Add", "a", "remove", "observer", "to", "this", "entity", "." ]
58f0011f4c57cd68830258952fa952eaadca6b38
https://github.com/juju/python-libjuju/blob/58f0011f4c57cd68830258952fa952eaadca6b38/juju/model.py#L272-L277
train
25,169
juju/python-libjuju
juju/model.py
ModelEntity.dead
def dead(self): """Returns True if this entity no longer exists in the underlying model. """ return ( self.data is None or self.model.state.entity_data( self.entity_type, self.entity_id, -1) is None )
python
def dead(self): """Returns True if this entity no longer exists in the underlying model. """ return ( self.data is None or self.model.state.entity_data( self.entity_type, self.entity_id, -1) is None )
[ "def", "dead", "(", "self", ")", ":", "return", "(", "self", ".", "data", "is", "None", "or", "self", ".", "model", ".", "state", ".", "entity_data", "(", "self", ".", "entity_type", ",", "self", ".", "entity_id", ",", "-", "1", ")", "is", "None", ...
Returns True if this entity no longer exists in the underlying model.
[ "Returns", "True", "if", "this", "entity", "no", "longer", "exists", "in", "the", "underlying", "model", "." ]
58f0011f4c57cd68830258952fa952eaadca6b38
https://github.com/juju/python-libjuju/blob/58f0011f4c57cd68830258952fa952eaadca6b38/juju/model.py#L300-L309
train
25,170
juju/python-libjuju
juju/model.py
ModelEntity.previous
def previous(self): """Return a copy of this object as was at its previous state in history. Returns None if this object is new (and therefore has no history). The returned object is always "disconnected", i.e. does not receive live updates. """ return self.model.state.get_entity( self.entity_type, self.entity_id, self._history_index - 1, connected=False)
python
def previous(self): """Return a copy of this object as was at its previous state in history. Returns None if this object is new (and therefore has no history). The returned object is always "disconnected", i.e. does not receive live updates. """ return self.model.state.get_entity( self.entity_type, self.entity_id, self._history_index - 1, connected=False)
[ "def", "previous", "(", "self", ")", ":", "return", "self", ".", "model", ".", "state", ".", "get_entity", "(", "self", ".", "entity_type", ",", "self", ".", "entity_id", ",", "self", ".", "_history_index", "-", "1", ",", "connected", "=", "False", ")"...
Return a copy of this object as was at its previous state in history. Returns None if this object is new (and therefore has no history). The returned object is always "disconnected", i.e. does not receive live updates.
[ "Return", "a", "copy", "of", "this", "object", "as", "was", "at", "its", "previous", "state", "in", "history", "." ]
58f0011f4c57cd68830258952fa952eaadca6b38
https://github.com/juju/python-libjuju/blob/58f0011f4c57cd68830258952fa952eaadca6b38/juju/model.py#L343-L355
train
25,171
juju/python-libjuju
juju/model.py
ModelEntity.next
def next(self): """Return a copy of this object at its next state in history. Returns None if this object is already the latest. The returned object is "disconnected", i.e. does not receive live updates, unless it is current (latest). """ if self._history_index == -1: return None new_index = self._history_index + 1 connected = ( new_index == len(self.model.state.entity_history( self.entity_type, self.entity_id)) - 1 ) return self.model.state.get_entity( self.entity_type, self.entity_id, self._history_index - 1, connected=connected)
python
def next(self): """Return a copy of this object at its next state in history. Returns None if this object is already the latest. The returned object is "disconnected", i.e. does not receive live updates, unless it is current (latest). """ if self._history_index == -1: return None new_index = self._history_index + 1 connected = ( new_index == len(self.model.state.entity_history( self.entity_type, self.entity_id)) - 1 ) return self.model.state.get_entity( self.entity_type, self.entity_id, self._history_index - 1, connected=connected)
[ "def", "next", "(", "self", ")", ":", "if", "self", ".", "_history_index", "==", "-", "1", ":", "return", "None", "new_index", "=", "self", ".", "_history_index", "+", "1", "connected", "=", "(", "new_index", "==", "len", "(", "self", ".", "model", "...
Return a copy of this object at its next state in history. Returns None if this object is already the latest. The returned object is "disconnected", i.e. does not receive live updates, unless it is current (latest).
[ "Return", "a", "copy", "of", "this", "object", "at", "its", "next", "state", "in", "history", "." ]
58f0011f4c57cd68830258952fa952eaadca6b38
https://github.com/juju/python-libjuju/blob/58f0011f4c57cd68830258952fa952eaadca6b38/juju/model.py#L357-L377
train
25,172
juju/python-libjuju
juju/model.py
Model.connect
async def connect(self, *args, **kwargs): """Connect to a juju model. This supports two calling conventions: The model and (optionally) authentication information can be taken from the data files created by the Juju CLI. This convention will be used if a ``model_name`` is specified, or if the ``endpoint`` and ``uuid`` are not. Otherwise, all of the ``endpoint``, ``uuid``, and authentication information (``username`` and ``password``, or ``bakery_client`` and/or ``macaroons``) are required. If a single positional argument is given, it will be assumed to be the ``model_name``. Otherwise, the first positional argument, if any, must be the ``endpoint``. Available parameters are: :param model_name: Format [controller:][user/]model :param str endpoint: The hostname:port of the controller to connect to. :param str uuid: The model UUID to connect to. :param str username: The username for controller-local users (or None to use macaroon-based login.) :param str password: The password for controller-local users. :param str cacert: The CA certificate of the controller (PEM formatted). :param httpbakery.Client bakery_client: The macaroon bakery client to to use when performing macaroon-based login. Macaroon tokens acquired when logging will be saved to bakery_client.cookies. If this is None, a default bakery_client will be used. :param list macaroons: List of macaroons to load into the ``bakery_client``. :param asyncio.BaseEventLoop loop: The event loop to use for async operations. :param int max_frame_size: The maximum websocket frame size to allow. """ await self.disconnect() if 'endpoint' not in kwargs and len(args) < 2: if args and 'model_name' in kwargs: raise TypeError('connect() got multiple values for model_name') elif args: model_name = args[0] else: model_name = kwargs.pop('model_name', None) await self._connector.connect_model(model_name, **kwargs) else: if 'model_name' in kwargs: raise TypeError('connect() got values for both ' 'model_name and endpoint') if args and 'endpoint' in kwargs: raise TypeError('connect() got multiple values for endpoint') if len(args) < 2 and 'uuid' not in kwargs: raise TypeError('connect() missing value for uuid') has_userpass = (len(args) >= 4 or {'username', 'password'}.issubset(kwargs)) has_macaroons = (len(args) >= 6 or not {'bakery_client', 'macaroons'}.isdisjoint(kwargs)) if not (has_userpass or has_macaroons): raise TypeError('connect() missing auth params') arg_names = [ 'endpoint', 'uuid', 'username', 'password', 'cacert', 'bakery_client', 'macaroons', 'loop', 'max_frame_size', ] for i, arg in enumerate(args): kwargs[arg_names[i]] = arg if not {'endpoint', 'uuid'}.issubset(kwargs): raise ValueError('endpoint and uuid are required ' 'if model_name not given') if not ({'username', 'password'}.issubset(kwargs) or {'bakery_client', 'macaroons'}.intersection(kwargs)): raise ValueError('Authentication parameters are required ' 'if model_name not given') await self._connector.connect(**kwargs) await self._after_connect()
python
async def connect(self, *args, **kwargs): """Connect to a juju model. This supports two calling conventions: The model and (optionally) authentication information can be taken from the data files created by the Juju CLI. This convention will be used if a ``model_name`` is specified, or if the ``endpoint`` and ``uuid`` are not. Otherwise, all of the ``endpoint``, ``uuid``, and authentication information (``username`` and ``password``, or ``bakery_client`` and/or ``macaroons``) are required. If a single positional argument is given, it will be assumed to be the ``model_name``. Otherwise, the first positional argument, if any, must be the ``endpoint``. Available parameters are: :param model_name: Format [controller:][user/]model :param str endpoint: The hostname:port of the controller to connect to. :param str uuid: The model UUID to connect to. :param str username: The username for controller-local users (or None to use macaroon-based login.) :param str password: The password for controller-local users. :param str cacert: The CA certificate of the controller (PEM formatted). :param httpbakery.Client bakery_client: The macaroon bakery client to to use when performing macaroon-based login. Macaroon tokens acquired when logging will be saved to bakery_client.cookies. If this is None, a default bakery_client will be used. :param list macaroons: List of macaroons to load into the ``bakery_client``. :param asyncio.BaseEventLoop loop: The event loop to use for async operations. :param int max_frame_size: The maximum websocket frame size to allow. """ await self.disconnect() if 'endpoint' not in kwargs and len(args) < 2: if args and 'model_name' in kwargs: raise TypeError('connect() got multiple values for model_name') elif args: model_name = args[0] else: model_name = kwargs.pop('model_name', None) await self._connector.connect_model(model_name, **kwargs) else: if 'model_name' in kwargs: raise TypeError('connect() got values for both ' 'model_name and endpoint') if args and 'endpoint' in kwargs: raise TypeError('connect() got multiple values for endpoint') if len(args) < 2 and 'uuid' not in kwargs: raise TypeError('connect() missing value for uuid') has_userpass = (len(args) >= 4 or {'username', 'password'}.issubset(kwargs)) has_macaroons = (len(args) >= 6 or not {'bakery_client', 'macaroons'}.isdisjoint(kwargs)) if not (has_userpass or has_macaroons): raise TypeError('connect() missing auth params') arg_names = [ 'endpoint', 'uuid', 'username', 'password', 'cacert', 'bakery_client', 'macaroons', 'loop', 'max_frame_size', ] for i, arg in enumerate(args): kwargs[arg_names[i]] = arg if not {'endpoint', 'uuid'}.issubset(kwargs): raise ValueError('endpoint and uuid are required ' 'if model_name not given') if not ({'username', 'password'}.issubset(kwargs) or {'bakery_client', 'macaroons'}.intersection(kwargs)): raise ValueError('Authentication parameters are required ' 'if model_name not given') await self._connector.connect(**kwargs) await self._after_connect()
[ "async", "def", "connect", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "await", "self", ".", "disconnect", "(", ")", "if", "'endpoint'", "not", "in", "kwargs", "and", "len", "(", "args", ")", "<", "2", ":", "if", "args", "an...
Connect to a juju model. This supports two calling conventions: The model and (optionally) authentication information can be taken from the data files created by the Juju CLI. This convention will be used if a ``model_name`` is specified, or if the ``endpoint`` and ``uuid`` are not. Otherwise, all of the ``endpoint``, ``uuid``, and authentication information (``username`` and ``password``, or ``bakery_client`` and/or ``macaroons``) are required. If a single positional argument is given, it will be assumed to be the ``model_name``. Otherwise, the first positional argument, if any, must be the ``endpoint``. Available parameters are: :param model_name: Format [controller:][user/]model :param str endpoint: The hostname:port of the controller to connect to. :param str uuid: The model UUID to connect to. :param str username: The username for controller-local users (or None to use macaroon-based login.) :param str password: The password for controller-local users. :param str cacert: The CA certificate of the controller (PEM formatted). :param httpbakery.Client bakery_client: The macaroon bakery client to to use when performing macaroon-based login. Macaroon tokens acquired when logging will be saved to bakery_client.cookies. If this is None, a default bakery_client will be used. :param list macaroons: List of macaroons to load into the ``bakery_client``. :param asyncio.BaseEventLoop loop: The event loop to use for async operations. :param int max_frame_size: The maximum websocket frame size to allow.
[ "Connect", "to", "a", "juju", "model", "." ]
58f0011f4c57cd68830258952fa952eaadca6b38
https://github.com/juju/python-libjuju/blob/58f0011f4c57cd68830258952fa952eaadca6b38/juju/model.py#L465-L547
train
25,173
juju/python-libjuju
juju/model.py
Model.add_local_charm_dir
async def add_local_charm_dir(self, charm_dir, series): """Upload a local charm to the model. This will automatically generate an archive from the charm dir. :param charm_dir: Path to the charm directory :param series: Charm series """ fh = tempfile.NamedTemporaryFile() CharmArchiveGenerator(charm_dir).make_archive(fh.name) with fh: func = partial( self.add_local_charm, fh, series, os.stat(fh.name).st_size) charm_url = await self._connector.loop.run_in_executor(None, func) log.debug('Uploaded local charm: %s -> %s', charm_dir, charm_url) return charm_url
python
async def add_local_charm_dir(self, charm_dir, series): """Upload a local charm to the model. This will automatically generate an archive from the charm dir. :param charm_dir: Path to the charm directory :param series: Charm series """ fh = tempfile.NamedTemporaryFile() CharmArchiveGenerator(charm_dir).make_archive(fh.name) with fh: func = partial( self.add_local_charm, fh, series, os.stat(fh.name).st_size) charm_url = await self._connector.loop.run_in_executor(None, func) log.debug('Uploaded local charm: %s -> %s', charm_dir, charm_url) return charm_url
[ "async", "def", "add_local_charm_dir", "(", "self", ",", "charm_dir", ",", "series", ")", ":", "fh", "=", "tempfile", ".", "NamedTemporaryFile", "(", ")", "CharmArchiveGenerator", "(", "charm_dir", ")", ".", "make_archive", "(", "fh", ".", "name", ")", "with...
Upload a local charm to the model. This will automatically generate an archive from the charm dir. :param charm_dir: Path to the charm directory :param series: Charm series
[ "Upload", "a", "local", "charm", "to", "the", "model", "." ]
58f0011f4c57cd68830258952fa952eaadca6b38
https://github.com/juju/python-libjuju/blob/58f0011f4c57cd68830258952fa952eaadca6b38/juju/model.py#L597-L615
train
25,174
juju/python-libjuju
juju/model.py
Model.add_local_charm
def add_local_charm(self, charm_file, series, size=None): """Upload a local charm archive to the model. Returns the 'local:...' url that should be used to deploy the charm. :param charm_file: Path to charm zip archive :param series: Charm series :param size: Size of the archive, in bytes :return str: 'local:...' url for deploying the charm :raises: :class:`JujuError` if the upload fails Uses an https endpoint at the same host:port as the wss. Supports large file uploads. .. warning:: This method will block. Consider using :meth:`add_local_charm_dir` instead. """ conn, headers, path_prefix = self.connection().https_connection() path = "%s/charms?series=%s" % (path_prefix, series) headers['Content-Type'] = 'application/zip' if size: headers['Content-Length'] = size conn.request("POST", path, charm_file, headers) response = conn.getresponse() result = response.read().decode() if not response.status == 200: raise JujuError(result) result = json.loads(result) return result['charm-url']
python
def add_local_charm(self, charm_file, series, size=None): """Upload a local charm archive to the model. Returns the 'local:...' url that should be used to deploy the charm. :param charm_file: Path to charm zip archive :param series: Charm series :param size: Size of the archive, in bytes :return str: 'local:...' url for deploying the charm :raises: :class:`JujuError` if the upload fails Uses an https endpoint at the same host:port as the wss. Supports large file uploads. .. warning:: This method will block. Consider using :meth:`add_local_charm_dir` instead. """ conn, headers, path_prefix = self.connection().https_connection() path = "%s/charms?series=%s" % (path_prefix, series) headers['Content-Type'] = 'application/zip' if size: headers['Content-Length'] = size conn.request("POST", path, charm_file, headers) response = conn.getresponse() result = response.read().decode() if not response.status == 200: raise JujuError(result) result = json.loads(result) return result['charm-url']
[ "def", "add_local_charm", "(", "self", ",", "charm_file", ",", "series", ",", "size", "=", "None", ")", ":", "conn", ",", "headers", ",", "path_prefix", "=", "self", ".", "connection", "(", ")", ".", "https_connection", "(", ")", "path", "=", "\"%s/charm...
Upload a local charm archive to the model. Returns the 'local:...' url that should be used to deploy the charm. :param charm_file: Path to charm zip archive :param series: Charm series :param size: Size of the archive, in bytes :return str: 'local:...' url for deploying the charm :raises: :class:`JujuError` if the upload fails Uses an https endpoint at the same host:port as the wss. Supports large file uploads. .. warning:: This method will block. Consider using :meth:`add_local_charm_dir` instead.
[ "Upload", "a", "local", "charm", "archive", "to", "the", "model", "." ]
58f0011f4c57cd68830258952fa952eaadca6b38
https://github.com/juju/python-libjuju/blob/58f0011f4c57cd68830258952fa952eaadca6b38/juju/model.py#L617-L648
train
25,175
juju/python-libjuju
juju/model.py
Model.all_units_idle
def all_units_idle(self): """Return True if all units are idle. """ for unit in self.units.values(): unit_status = unit.data['agent-status']['current'] if unit_status != 'idle': return False return True
python
def all_units_idle(self): """Return True if all units are idle. """ for unit in self.units.values(): unit_status = unit.data['agent-status']['current'] if unit_status != 'idle': return False return True
[ "def", "all_units_idle", "(", "self", ")", ":", "for", "unit", "in", "self", ".", "units", ".", "values", "(", ")", ":", "unit_status", "=", "unit", ".", "data", "[", "'agent-status'", "]", "[", "'current'", "]", "if", "unit_status", "!=", "'idle'", ":...
Return True if all units are idle.
[ "Return", "True", "if", "all", "units", "are", "idle", "." ]
58f0011f4c57cd68830258952fa952eaadca6b38
https://github.com/juju/python-libjuju/blob/58f0011f4c57cd68830258952fa952eaadca6b38/juju/model.py#L650-L658
train
25,176
juju/python-libjuju
juju/model.py
Model.reset
async def reset(self, force=False): """Reset the model to a clean state. :param bool force: Force-terminate machines. This returns only after the model has reached a clean state. "Clean" means no applications or machines exist in the model. """ log.debug('Resetting model') for app in self.applications.values(): await app.destroy() for machine in self.machines.values(): await machine.destroy(force=force) await self.block_until( lambda: len(self.machines) == 0 )
python
async def reset(self, force=False): """Reset the model to a clean state. :param bool force: Force-terminate machines. This returns only after the model has reached a clean state. "Clean" means no applications or machines exist in the model. """ log.debug('Resetting model') for app in self.applications.values(): await app.destroy() for machine in self.machines.values(): await machine.destroy(force=force) await self.block_until( lambda: len(self.machines) == 0 )
[ "async", "def", "reset", "(", "self", ",", "force", "=", "False", ")", ":", "log", ".", "debug", "(", "'Resetting model'", ")", "for", "app", "in", "self", ".", "applications", ".", "values", "(", ")", ":", "await", "app", ".", "destroy", "(", ")", ...
Reset the model to a clean state. :param bool force: Force-terminate machines. This returns only after the model has reached a clean state. "Clean" means no applications or machines exist in the model.
[ "Reset", "the", "model", "to", "a", "clean", "state", "." ]
58f0011f4c57cd68830258952fa952eaadca6b38
https://github.com/juju/python-libjuju/blob/58f0011f4c57cd68830258952fa952eaadca6b38/juju/model.py#L660-L676
train
25,177
juju/python-libjuju
juju/model.py
Model.get_info
async def get_info(self): """Return a client.ModelInfo object for this Model. Retrieves latest info for this Model from the api server. The return value is cached on the Model.info attribute so that the valued may be accessed again without another api call, if desired. This method is called automatically when the Model is connected, resulting in Model.info being initialized without requiring an explicit call to this method. """ facade = client.ClientFacade.from_connection(self.connection()) self._info = await facade.ModelInfo() log.debug('Got ModelInfo: %s', vars(self.info)) return self.info
python
async def get_info(self): """Return a client.ModelInfo object for this Model. Retrieves latest info for this Model from the api server. The return value is cached on the Model.info attribute so that the valued may be accessed again without another api call, if desired. This method is called automatically when the Model is connected, resulting in Model.info being initialized without requiring an explicit call to this method. """ facade = client.ClientFacade.from_connection(self.connection()) self._info = await facade.ModelInfo() log.debug('Got ModelInfo: %s', vars(self.info)) return self.info
[ "async", "def", "get_info", "(", "self", ")", ":", "facade", "=", "client", ".", "ClientFacade", ".", "from_connection", "(", "self", ".", "connection", "(", ")", ")", "self", ".", "_info", "=", "await", "facade", ".", "ModelInfo", "(", ")", "log", "."...
Return a client.ModelInfo object for this Model. Retrieves latest info for this Model from the api server. The return value is cached on the Model.info attribute so that the valued may be accessed again without another api call, if desired. This method is called automatically when the Model is connected, resulting in Model.info being initialized without requiring an explicit call to this method.
[ "Return", "a", "client", ".", "ModelInfo", "object", "for", "this", "Model", "." ]
58f0011f4c57cd68830258952fa952eaadca6b38
https://github.com/juju/python-libjuju/blob/58f0011f4c57cd68830258952fa952eaadca6b38/juju/model.py#L731-L749
train
25,178
juju/python-libjuju
juju/model.py
Model.add_observer
def add_observer( self, callable_, entity_type=None, action=None, entity_id=None, predicate=None): """Register an "on-model-change" callback Once the model is connected, ``callable_`` will be called each time the model changes. ``callable_`` should be Awaitable and accept the following positional arguments: delta - An instance of :class:`juju.delta.EntityDelta` containing the raw delta data recv'd from the Juju websocket. old_obj - If the delta modifies an existing object in the model, old_obj will be a copy of that object, as it was before the delta was applied. Will be None if the delta creates a new entity in the model. new_obj - A copy of the new or updated object, after the delta is applied. Will be None if the delta removes an entity from the model. model - The :class:`Model` itself. Events for which ``callable_`` is called can be specified by passing entity_type, action, and/or entitiy_id filter criteria, e.g.:: add_observer( myfunc, entity_type='application', action='add', entity_id='ubuntu') For more complex filtering conditions, pass a predicate function. It will be called with a delta as its only argument. If the predicate function returns True, the ``callable_`` will be called. """ observer = _Observer( callable_, entity_type, action, entity_id, predicate) self._observers[observer] = callable_
python
def add_observer( self, callable_, entity_type=None, action=None, entity_id=None, predicate=None): """Register an "on-model-change" callback Once the model is connected, ``callable_`` will be called each time the model changes. ``callable_`` should be Awaitable and accept the following positional arguments: delta - An instance of :class:`juju.delta.EntityDelta` containing the raw delta data recv'd from the Juju websocket. old_obj - If the delta modifies an existing object in the model, old_obj will be a copy of that object, as it was before the delta was applied. Will be None if the delta creates a new entity in the model. new_obj - A copy of the new or updated object, after the delta is applied. Will be None if the delta removes an entity from the model. model - The :class:`Model` itself. Events for which ``callable_`` is called can be specified by passing entity_type, action, and/or entitiy_id filter criteria, e.g.:: add_observer( myfunc, entity_type='application', action='add', entity_id='ubuntu') For more complex filtering conditions, pass a predicate function. It will be called with a delta as its only argument. If the predicate function returns True, the ``callable_`` will be called. """ observer = _Observer( callable_, entity_type, action, entity_id, predicate) self._observers[observer] = callable_
[ "def", "add_observer", "(", "self", ",", "callable_", ",", "entity_type", "=", "None", ",", "action", "=", "None", ",", "entity_id", "=", "None", ",", "predicate", "=", "None", ")", ":", "observer", "=", "_Observer", "(", "callable_", ",", "entity_type", ...
Register an "on-model-change" callback Once the model is connected, ``callable_`` will be called each time the model changes. ``callable_`` should be Awaitable and accept the following positional arguments: delta - An instance of :class:`juju.delta.EntityDelta` containing the raw delta data recv'd from the Juju websocket. old_obj - If the delta modifies an existing object in the model, old_obj will be a copy of that object, as it was before the delta was applied. Will be None if the delta creates a new entity in the model. new_obj - A copy of the new or updated object, after the delta is applied. Will be None if the delta removes an entity from the model. model - The :class:`Model` itself. Events for which ``callable_`` is called can be specified by passing entity_type, action, and/or entitiy_id filter criteria, e.g.:: add_observer( myfunc, entity_type='application', action='add', entity_id='ubuntu') For more complex filtering conditions, pass a predicate function. It will be called with a delta as its only argument. If the predicate function returns True, the ``callable_`` will be called.
[ "Register", "an", "on", "-", "model", "-", "change", "callback" ]
58f0011f4c57cd68830258952fa952eaadca6b38
https://github.com/juju/python-libjuju/blob/58f0011f4c57cd68830258952fa952eaadca6b38/juju/model.py#L759-L797
train
25,179
juju/python-libjuju
juju/model.py
Model._watch
def _watch(self): """Start an asynchronous watch against this model. See :meth:`add_observer` to register an onchange callback. """ async def _all_watcher(): try: allwatcher = client.AllWatcherFacade.from_connection( self.connection()) while not self._watch_stopping.is_set(): try: results = await utils.run_with_interrupt( allwatcher.Next(), self._watch_stopping, loop=self._connector.loop) except JujuAPIError as e: if 'watcher was stopped' not in str(e): raise if self._watch_stopping.is_set(): # this shouldn't ever actually happen, because # the event should trigger before the controller # has a chance to tell us the watcher is stopped # but handle it gracefully, just in case break # controller stopped our watcher for some reason # but we're not actually stopping, so just restart it log.warning( 'Watcher: watcher stopped, restarting') del allwatcher.Id continue except websockets.ConnectionClosed: monitor = self.connection().monitor if monitor.status == monitor.ERROR: # closed unexpectedly, try to reopen log.warning( 'Watcher: connection closed, reopening') await self.connection().reconnect() if monitor.status != monitor.CONNECTED: # reconnect failed; abort and shutdown log.error('Watcher: automatic reconnect ' 'failed; stopping watcher') break del allwatcher.Id continue else: # closed on request, go ahead and shutdown break if self._watch_stopping.is_set(): try: await allwatcher.Stop() except websockets.ConnectionClosed: pass # can't stop on a closed conn break for delta in results.deltas: try: delta = get_entity_delta(delta) old_obj, new_obj = self.state.apply_delta(delta) await self._notify_observers(delta, old_obj, new_obj) except KeyError as e: log.debug("unknown delta type: %s", e.args[0]) self._watch_received.set() except CancelledError: pass except Exception: log.exception('Error in watcher') raise finally: self._watch_stopped.set() log.debug('Starting watcher task') self._watch_received.clear() self._watch_stopping.clear() self._watch_stopped.clear() self._connector.loop.create_task(_all_watcher())
python
def _watch(self): """Start an asynchronous watch against this model. See :meth:`add_observer` to register an onchange callback. """ async def _all_watcher(): try: allwatcher = client.AllWatcherFacade.from_connection( self.connection()) while not self._watch_stopping.is_set(): try: results = await utils.run_with_interrupt( allwatcher.Next(), self._watch_stopping, loop=self._connector.loop) except JujuAPIError as e: if 'watcher was stopped' not in str(e): raise if self._watch_stopping.is_set(): # this shouldn't ever actually happen, because # the event should trigger before the controller # has a chance to tell us the watcher is stopped # but handle it gracefully, just in case break # controller stopped our watcher for some reason # but we're not actually stopping, so just restart it log.warning( 'Watcher: watcher stopped, restarting') del allwatcher.Id continue except websockets.ConnectionClosed: monitor = self.connection().monitor if monitor.status == monitor.ERROR: # closed unexpectedly, try to reopen log.warning( 'Watcher: connection closed, reopening') await self.connection().reconnect() if monitor.status != monitor.CONNECTED: # reconnect failed; abort and shutdown log.error('Watcher: automatic reconnect ' 'failed; stopping watcher') break del allwatcher.Id continue else: # closed on request, go ahead and shutdown break if self._watch_stopping.is_set(): try: await allwatcher.Stop() except websockets.ConnectionClosed: pass # can't stop on a closed conn break for delta in results.deltas: try: delta = get_entity_delta(delta) old_obj, new_obj = self.state.apply_delta(delta) await self._notify_observers(delta, old_obj, new_obj) except KeyError as e: log.debug("unknown delta type: %s", e.args[0]) self._watch_received.set() except CancelledError: pass except Exception: log.exception('Error in watcher') raise finally: self._watch_stopped.set() log.debug('Starting watcher task') self._watch_received.clear() self._watch_stopping.clear() self._watch_stopped.clear() self._connector.loop.create_task(_all_watcher())
[ "def", "_watch", "(", "self", ")", ":", "async", "def", "_all_watcher", "(", ")", ":", "try", ":", "allwatcher", "=", "client", ".", "AllWatcherFacade", ".", "from_connection", "(", "self", ".", "connection", "(", ")", ")", "while", "not", "self", ".", ...
Start an asynchronous watch against this model. See :meth:`add_observer` to register an onchange callback.
[ "Start", "an", "asynchronous", "watch", "against", "this", "model", "." ]
58f0011f4c57cd68830258952fa952eaadca6b38
https://github.com/juju/python-libjuju/blob/58f0011f4c57cd68830258952fa952eaadca6b38/juju/model.py#L799-L873
train
25,180
juju/python-libjuju
juju/model.py
Model._notify_observers
async def _notify_observers(self, delta, old_obj, new_obj): """Call observing callbacks, notifying them of a change in model state :param delta: The raw change from the watcher (:class:`juju.client.overrides.Delta`) :param old_obj: The object in the model that this delta updates. May be None. :param new_obj: The object in the model that is created or updated by applying this delta. """ if new_obj and not old_obj: delta.type = 'add' log.debug( 'Model changed: %s %s %s', delta.entity, delta.type, delta.get_id()) for o in self._observers: if o.cares_about(delta): asyncio.ensure_future(o(delta, old_obj, new_obj, self), loop=self._connector.loop)
python
async def _notify_observers(self, delta, old_obj, new_obj): """Call observing callbacks, notifying them of a change in model state :param delta: The raw change from the watcher (:class:`juju.client.overrides.Delta`) :param old_obj: The object in the model that this delta updates. May be None. :param new_obj: The object in the model that is created or updated by applying this delta. """ if new_obj and not old_obj: delta.type = 'add' log.debug( 'Model changed: %s %s %s', delta.entity, delta.type, delta.get_id()) for o in self._observers: if o.cares_about(delta): asyncio.ensure_future(o(delta, old_obj, new_obj, self), loop=self._connector.loop)
[ "async", "def", "_notify_observers", "(", "self", ",", "delta", ",", "old_obj", ",", "new_obj", ")", ":", "if", "new_obj", "and", "not", "old_obj", ":", "delta", ".", "type", "=", "'add'", "log", ".", "debug", "(", "'Model changed: %s %s %s'", ",", "delta"...
Call observing callbacks, notifying them of a change in model state :param delta: The raw change from the watcher (:class:`juju.client.overrides.Delta`) :param old_obj: The object in the model that this delta updates. May be None. :param new_obj: The object in the model that is created or updated by applying this delta.
[ "Call", "observing", "callbacks", "notifying", "them", "of", "a", "change", "in", "model", "state" ]
58f0011f4c57cd68830258952fa952eaadca6b38
https://github.com/juju/python-libjuju/blob/58f0011f4c57cd68830258952fa952eaadca6b38/juju/model.py#L875-L896
train
25,181
juju/python-libjuju
juju/model.py
Model._wait
async def _wait(self, entity_type, entity_id, action, predicate=None): """ Block the calling routine until a given action has happened to the given entity :param entity_type: The entity's type. :param entity_id: The entity's id. :param action: the type of action (e.g., 'add', 'change', or 'remove') :param predicate: optional callable that must take as an argument a delta, and must return a boolean, indicating whether the delta contains the specific action we're looking for. For example, you might check to see whether a 'change' has a 'completed' status. See the _Observer class for details. """ q = asyncio.Queue(loop=self._connector.loop) async def callback(delta, old, new, model): await q.put(delta.get_id()) self.add_observer(callback, entity_type, action, entity_id, predicate) entity_id = await q.get() # object might not be in the entity_map if we were waiting for a # 'remove' action return self.state._live_entity_map(entity_type).get(entity_id)
python
async def _wait(self, entity_type, entity_id, action, predicate=None): """ Block the calling routine until a given action has happened to the given entity :param entity_type: The entity's type. :param entity_id: The entity's id. :param action: the type of action (e.g., 'add', 'change', or 'remove') :param predicate: optional callable that must take as an argument a delta, and must return a boolean, indicating whether the delta contains the specific action we're looking for. For example, you might check to see whether a 'change' has a 'completed' status. See the _Observer class for details. """ q = asyncio.Queue(loop=self._connector.loop) async def callback(delta, old, new, model): await q.put(delta.get_id()) self.add_observer(callback, entity_type, action, entity_id, predicate) entity_id = await q.get() # object might not be in the entity_map if we were waiting for a # 'remove' action return self.state._live_entity_map(entity_type).get(entity_id)
[ "async", "def", "_wait", "(", "self", ",", "entity_type", ",", "entity_id", ",", "action", ",", "predicate", "=", "None", ")", ":", "q", "=", "asyncio", ".", "Queue", "(", "loop", "=", "self", ".", "_connector", ".", "loop", ")", "async", "def", "cal...
Block the calling routine until a given action has happened to the given entity :param entity_type: The entity's type. :param entity_id: The entity's id. :param action: the type of action (e.g., 'add', 'change', or 'remove') :param predicate: optional callable that must take as an argument a delta, and must return a boolean, indicating whether the delta contains the specific action we're looking for. For example, you might check to see whether a 'change' has a 'completed' status. See the _Observer class for details.
[ "Block", "the", "calling", "routine", "until", "a", "given", "action", "has", "happened", "to", "the", "given", "entity" ]
58f0011f4c57cd68830258952fa952eaadca6b38
https://github.com/juju/python-libjuju/blob/58f0011f4c57cd68830258952fa952eaadca6b38/juju/model.py#L898-L922
train
25,182
juju/python-libjuju
juju/model.py
Model._wait_for_new
async def _wait_for_new(self, entity_type, entity_id): """Wait for a new object to appear in the Model and return it. Waits for an object of type ``entity_type`` with id ``entity_id`` to appear in the model. This is similar to watching for the object using ``block_until``, but uses the watcher rather than polling. """ # if the entity is already in the model, just return it if entity_id in self.state._live_entity_map(entity_type): return self.state._live_entity_map(entity_type)[entity_id] return await self._wait(entity_type, entity_id, None)
python
async def _wait_for_new(self, entity_type, entity_id): """Wait for a new object to appear in the Model and return it. Waits for an object of type ``entity_type`` with id ``entity_id`` to appear in the model. This is similar to watching for the object using ``block_until``, but uses the watcher rather than polling. """ # if the entity is already in the model, just return it if entity_id in self.state._live_entity_map(entity_type): return self.state._live_entity_map(entity_type)[entity_id] return await self._wait(entity_type, entity_id, None)
[ "async", "def", "_wait_for_new", "(", "self", ",", "entity_type", ",", "entity_id", ")", ":", "# if the entity is already in the model, just return it", "if", "entity_id", "in", "self", ".", "state", ".", "_live_entity_map", "(", "entity_type", ")", ":", "return", "...
Wait for a new object to appear in the Model and return it. Waits for an object of type ``entity_type`` with id ``entity_id`` to appear in the model. This is similar to watching for the object using ``block_until``, but uses the watcher rather than polling.
[ "Wait", "for", "a", "new", "object", "to", "appear", "in", "the", "Model", "and", "return", "it", "." ]
58f0011f4c57cd68830258952fa952eaadca6b38
https://github.com/juju/python-libjuju/blob/58f0011f4c57cd68830258952fa952eaadca6b38/juju/model.py#L924-L936
train
25,183
juju/python-libjuju
juju/model.py
Model.wait_for_action
async def wait_for_action(self, action_id): """Given an action, wait for it to complete.""" if action_id.startswith("action-"): # if we've been passed action.tag, transform it into the # id that the api deltas will use. action_id = action_id[7:] def predicate(delta): return delta.data['status'] in ('completed', 'failed') return await self._wait('action', action_id, None, predicate)
python
async def wait_for_action(self, action_id): """Given an action, wait for it to complete.""" if action_id.startswith("action-"): # if we've been passed action.tag, transform it into the # id that the api deltas will use. action_id = action_id[7:] def predicate(delta): return delta.data['status'] in ('completed', 'failed') return await self._wait('action', action_id, None, predicate)
[ "async", "def", "wait_for_action", "(", "self", ",", "action_id", ")", ":", "if", "action_id", ".", "startswith", "(", "\"action-\"", ")", ":", "# if we've been passed action.tag, transform it into the", "# id that the api deltas will use.", "action_id", "=", "action_id", ...
Given an action, wait for it to complete.
[ "Given", "an", "action", "wait", "for", "it", "to", "complete", "." ]
58f0011f4c57cd68830258952fa952eaadca6b38
https://github.com/juju/python-libjuju/blob/58f0011f4c57cd68830258952fa952eaadca6b38/juju/model.py#L938-L949
train
25,184
juju/python-libjuju
juju/model.py
Model.add_machine
async def add_machine( self, spec=None, constraints=None, disks=None, series=None): """Start a new, empty machine and optionally a container, or add a container to a machine. :param str spec: Machine specification Examples:: (None) - starts a new machine 'lxd' - starts a new machine with one lxd container 'lxd:4' - starts a new lxd container on machine 4 'ssh:user@10.10.0.3:/path/to/private/key' - manually provision a machine with ssh and the private key used for authentication 'zone=us-east-1a' - starts a machine in zone us-east-1s on AWS 'maas2.name' - acquire machine maas2.name on MAAS :param dict constraints: Machine constraints, which can contain the the following keys:: arch : str container : str cores : int cpu_power : int instance_type : str mem : int root_disk : int spaces : list(str) tags : list(str) virt_type : str Example:: constraints={ 'mem': 256 * MB, 'tags': ['virtual'], } :param list disks: List of disk constraint dictionaries, which can contain the following keys:: count : int pool : str size : int Example:: disks=[{ 'pool': 'rootfs', 'size': 10 * GB, 'count': 1, }] :param str series: Series, e.g. 'xenial' Supported container types are: lxd, kvm When deploying a container to an existing machine, constraints cannot be used. """ params = client.AddMachineParams() if spec: if spec.startswith("ssh:"): placement, target, private_key_path = spec.split(":") user, host = target.split("@") sshProvisioner = provisioner.SSHProvisioner( host=host, user=user, private_key_path=private_key_path, ) params = sshProvisioner.provision_machine() else: placement = parse_placement(spec) if placement: params.placement = placement[0] params.jobs = ['JobHostUnits'] if constraints: params.constraints = client.Value.from_json(constraints) if disks: params.disks = [ client.Constraints.from_json(o) for o in disks] if series: params.series = series # Submit the request. client_facade = client.ClientFacade.from_connection(self.connection()) results = await client_facade.AddMachines([params]) error = results.machines[0].error if error: raise ValueError("Error adding machine: %s" % error.message) machine_id = results.machines[0].machine if spec: if spec.startswith("ssh:"): # Need to run this after AddMachines has been called, # as we need the machine_id await sshProvisioner.install_agent( self.connection(), params.nonce, machine_id, ) log.debug('Added new machine %s', machine_id) return await self._wait_for_new('machine', machine_id)
python
async def add_machine( self, spec=None, constraints=None, disks=None, series=None): """Start a new, empty machine and optionally a container, or add a container to a machine. :param str spec: Machine specification Examples:: (None) - starts a new machine 'lxd' - starts a new machine with one lxd container 'lxd:4' - starts a new lxd container on machine 4 'ssh:user@10.10.0.3:/path/to/private/key' - manually provision a machine with ssh and the private key used for authentication 'zone=us-east-1a' - starts a machine in zone us-east-1s on AWS 'maas2.name' - acquire machine maas2.name on MAAS :param dict constraints: Machine constraints, which can contain the the following keys:: arch : str container : str cores : int cpu_power : int instance_type : str mem : int root_disk : int spaces : list(str) tags : list(str) virt_type : str Example:: constraints={ 'mem': 256 * MB, 'tags': ['virtual'], } :param list disks: List of disk constraint dictionaries, which can contain the following keys:: count : int pool : str size : int Example:: disks=[{ 'pool': 'rootfs', 'size': 10 * GB, 'count': 1, }] :param str series: Series, e.g. 'xenial' Supported container types are: lxd, kvm When deploying a container to an existing machine, constraints cannot be used. """ params = client.AddMachineParams() if spec: if spec.startswith("ssh:"): placement, target, private_key_path = spec.split(":") user, host = target.split("@") sshProvisioner = provisioner.SSHProvisioner( host=host, user=user, private_key_path=private_key_path, ) params = sshProvisioner.provision_machine() else: placement = parse_placement(spec) if placement: params.placement = placement[0] params.jobs = ['JobHostUnits'] if constraints: params.constraints = client.Value.from_json(constraints) if disks: params.disks = [ client.Constraints.from_json(o) for o in disks] if series: params.series = series # Submit the request. client_facade = client.ClientFacade.from_connection(self.connection()) results = await client_facade.AddMachines([params]) error = results.machines[0].error if error: raise ValueError("Error adding machine: %s" % error.message) machine_id = results.machines[0].machine if spec: if spec.startswith("ssh:"): # Need to run this after AddMachines has been called, # as we need the machine_id await sshProvisioner.install_agent( self.connection(), params.nonce, machine_id, ) log.debug('Added new machine %s', machine_id) return await self._wait_for_new('machine', machine_id)
[ "async", "def", "add_machine", "(", "self", ",", "spec", "=", "None", ",", "constraints", "=", "None", ",", "disks", "=", "None", ",", "series", "=", "None", ")", ":", "params", "=", "client", ".", "AddMachineParams", "(", ")", "if", "spec", ":", "if...
Start a new, empty machine and optionally a container, or add a container to a machine. :param str spec: Machine specification Examples:: (None) - starts a new machine 'lxd' - starts a new machine with one lxd container 'lxd:4' - starts a new lxd container on machine 4 'ssh:user@10.10.0.3:/path/to/private/key' - manually provision a machine with ssh and the private key used for authentication 'zone=us-east-1a' - starts a machine in zone us-east-1s on AWS 'maas2.name' - acquire machine maas2.name on MAAS :param dict constraints: Machine constraints, which can contain the the following keys:: arch : str container : str cores : int cpu_power : int instance_type : str mem : int root_disk : int spaces : list(str) tags : list(str) virt_type : str Example:: constraints={ 'mem': 256 * MB, 'tags': ['virtual'], } :param list disks: List of disk constraint dictionaries, which can contain the following keys:: count : int pool : str size : int Example:: disks=[{ 'pool': 'rootfs', 'size': 10 * GB, 'count': 1, }] :param str series: Series, e.g. 'xenial' Supported container types are: lxd, kvm When deploying a container to an existing machine, constraints cannot be used.
[ "Start", "a", "new", "empty", "machine", "and", "optionally", "a", "container", "or", "add", "a", "container", "to", "a", "machine", "." ]
58f0011f4c57cd68830258952fa952eaadca6b38
https://github.com/juju/python-libjuju/blob/58f0011f4c57cd68830258952fa952eaadca6b38/juju/model.py#L967-L1077
train
25,185
juju/python-libjuju
juju/model.py
Model.add_relation
async def add_relation(self, relation1, relation2): """Add a relation between two applications. :param str relation1: '<application>[:<relation_name>]' :param str relation2: '<application>[:<relation_name>]' """ connection = self.connection() app_facade = client.ApplicationFacade.from_connection(connection) log.debug( 'Adding relation %s <-> %s', relation1, relation2) def _find_relation(*specs): for rel in self.relations: if rel.matches(*specs): return rel return None try: result = await app_facade.AddRelation([relation1, relation2]) except JujuAPIError as e: if 'relation already exists' not in e.message: raise rel = _find_relation(relation1, relation2) if rel: return rel raise JujuError('Relation {} {} exists but not in model'.format( relation1, relation2)) specs = ['{}:{}'.format(app, data['name']) for app, data in result.endpoints.items()] await self.block_until(lambda: _find_relation(*specs) is not None) return _find_relation(*specs)
python
async def add_relation(self, relation1, relation2): """Add a relation between two applications. :param str relation1: '<application>[:<relation_name>]' :param str relation2: '<application>[:<relation_name>]' """ connection = self.connection() app_facade = client.ApplicationFacade.from_connection(connection) log.debug( 'Adding relation %s <-> %s', relation1, relation2) def _find_relation(*specs): for rel in self.relations: if rel.matches(*specs): return rel return None try: result = await app_facade.AddRelation([relation1, relation2]) except JujuAPIError as e: if 'relation already exists' not in e.message: raise rel = _find_relation(relation1, relation2) if rel: return rel raise JujuError('Relation {} {} exists but not in model'.format( relation1, relation2)) specs = ['{}:{}'.format(app, data['name']) for app, data in result.endpoints.items()] await self.block_until(lambda: _find_relation(*specs) is not None) return _find_relation(*specs)
[ "async", "def", "add_relation", "(", "self", ",", "relation1", ",", "relation2", ")", ":", "connection", "=", "self", ".", "connection", "(", ")", "app_facade", "=", "client", ".", "ApplicationFacade", ".", "from_connection", "(", "connection", ")", "log", "...
Add a relation between two applications. :param str relation1: '<application>[:<relation_name>]' :param str relation2: '<application>[:<relation_name>]'
[ "Add", "a", "relation", "between", "two", "applications", "." ]
58f0011f4c57cd68830258952fa952eaadca6b38
https://github.com/juju/python-libjuju/blob/58f0011f4c57cd68830258952fa952eaadca6b38/juju/model.py#L1079-L1113
train
25,186
juju/python-libjuju
juju/model.py
Model.add_ssh_key
async def add_ssh_key(self, user, key): """Add a public SSH key to this model. :param str user: The username of the user :param str key: The public ssh key """ key_facade = client.KeyManagerFacade.from_connection(self.connection()) return await key_facade.AddKeys([key], user)
python
async def add_ssh_key(self, user, key): """Add a public SSH key to this model. :param str user: The username of the user :param str key: The public ssh key """ key_facade = client.KeyManagerFacade.from_connection(self.connection()) return await key_facade.AddKeys([key], user)
[ "async", "def", "add_ssh_key", "(", "self", ",", "user", ",", "key", ")", ":", "key_facade", "=", "client", ".", "KeyManagerFacade", ".", "from_connection", "(", "self", ".", "connection", "(", ")", ")", "return", "await", "key_facade", ".", "AddKeys", "("...
Add a public SSH key to this model. :param str user: The username of the user :param str key: The public ssh key
[ "Add", "a", "public", "SSH", "key", "to", "this", "model", "." ]
58f0011f4c57cd68830258952fa952eaadca6b38
https://github.com/juju/python-libjuju/blob/58f0011f4c57cd68830258952fa952eaadca6b38/juju/model.py#L1127-L1135
train
25,187
juju/python-libjuju
juju/model.py
Model.debug_log
def debug_log( self, no_tail=False, exclude_module=None, include_module=None, include=None, level=None, limit=0, lines=10, replay=False, exclude=None): """Get log messages for this model. :param bool no_tail: Stop after returning existing log messages :param list exclude_module: Do not show log messages for these logging modules :param list include_module: Only show log messages for these logging modules :param list include: Only show log messages for these entities :param str level: Log level to show, valid options are 'TRACE', 'DEBUG', 'INFO', 'WARNING', 'ERROR, :param int limit: Return this many of the most recent (possibly filtered) lines are shown :param int lines: Yield this many of the most recent lines, and keep yielding :param bool replay: Yield the entire log, and keep yielding :param list exclude: Do not show log messages for these entities """ raise NotImplementedError()
python
def debug_log( self, no_tail=False, exclude_module=None, include_module=None, include=None, level=None, limit=0, lines=10, replay=False, exclude=None): """Get log messages for this model. :param bool no_tail: Stop after returning existing log messages :param list exclude_module: Do not show log messages for these logging modules :param list include_module: Only show log messages for these logging modules :param list include: Only show log messages for these entities :param str level: Log level to show, valid options are 'TRACE', 'DEBUG', 'INFO', 'WARNING', 'ERROR, :param int limit: Return this many of the most recent (possibly filtered) lines are shown :param int lines: Yield this many of the most recent lines, and keep yielding :param bool replay: Yield the entire log, and keep yielding :param list exclude: Do not show log messages for these entities """ raise NotImplementedError()
[ "def", "debug_log", "(", "self", ",", "no_tail", "=", "False", ",", "exclude_module", "=", "None", ",", "include_module", "=", "None", ",", "include", "=", "None", ",", "level", "=", "None", ",", "limit", "=", "0", ",", "lines", "=", "10", ",", "repl...
Get log messages for this model. :param bool no_tail: Stop after returning existing log messages :param list exclude_module: Do not show log messages for these logging modules :param list include_module: Only show log messages for these logging modules :param list include: Only show log messages for these entities :param str level: Log level to show, valid options are 'TRACE', 'DEBUG', 'INFO', 'WARNING', 'ERROR, :param int limit: Return this many of the most recent (possibly filtered) lines are shown :param int lines: Yield this many of the most recent lines, and keep yielding :param bool replay: Yield the entire log, and keep yielding :param list exclude: Do not show log messages for these entities
[ "Get", "log", "messages", "for", "this", "model", "." ]
58f0011f4c57cd68830258952fa952eaadca6b38
https://github.com/juju/python-libjuju/blob/58f0011f4c57cd68830258952fa952eaadca6b38/juju/model.py#L1199-L1221
train
25,188
juju/python-libjuju
juju/model.py
Model._deploy
async def _deploy(self, charm_url, application, series, config, constraints, endpoint_bindings, resources, storage, channel=None, num_units=None, placement=None, devices=None): """Logic shared between `Model.deploy` and `BundleHandler.deploy`. """ log.info('Deploying %s', charm_url) # stringify all config values for API, and convert to YAML config = {k: str(v) for k, v in config.items()} config = yaml.dump({application: config}, default_flow_style=False) app_facade = client.ApplicationFacade.from_connection( self.connection()) app = client.ApplicationDeploy( charm_url=charm_url, application=application, series=series, channel=channel, config_yaml=config, constraints=parse_constraints(constraints), endpoint_bindings=endpoint_bindings, num_units=num_units, resources=resources, storage=storage, placement=placement, devices=devices, ) result = await app_facade.Deploy([app]) errors = [r.error.message for r in result.results if r.error] if errors: raise JujuError('\n'.join(errors)) return await self._wait_for_new('application', application)
python
async def _deploy(self, charm_url, application, series, config, constraints, endpoint_bindings, resources, storage, channel=None, num_units=None, placement=None, devices=None): """Logic shared between `Model.deploy` and `BundleHandler.deploy`. """ log.info('Deploying %s', charm_url) # stringify all config values for API, and convert to YAML config = {k: str(v) for k, v in config.items()} config = yaml.dump({application: config}, default_flow_style=False) app_facade = client.ApplicationFacade.from_connection( self.connection()) app = client.ApplicationDeploy( charm_url=charm_url, application=application, series=series, channel=channel, config_yaml=config, constraints=parse_constraints(constraints), endpoint_bindings=endpoint_bindings, num_units=num_units, resources=resources, storage=storage, placement=placement, devices=devices, ) result = await app_facade.Deploy([app]) errors = [r.error.message for r in result.results if r.error] if errors: raise JujuError('\n'.join(errors)) return await self._wait_for_new('application', application)
[ "async", "def", "_deploy", "(", "self", ",", "charm_url", ",", "application", ",", "series", ",", "config", ",", "constraints", ",", "endpoint_bindings", ",", "resources", ",", "storage", ",", "channel", "=", "None", ",", "num_units", "=", "None", ",", "pl...
Logic shared between `Model.deploy` and `BundleHandler.deploy`.
[ "Logic", "shared", "between", "Model", ".", "deploy", "and", "BundleHandler", ".", "deploy", "." ]
58f0011f4c57cd68830258952fa952eaadca6b38
https://github.com/juju/python-libjuju/blob/58f0011f4c57cd68830258952fa952eaadca6b38/juju/model.py#L1407-L1441
train
25,189
juju/python-libjuju
juju/model.py
Model.destroy_unit
async def destroy_unit(self, *unit_names): """Destroy units by name. """ connection = self.connection() app_facade = client.ApplicationFacade.from_connection(connection) log.debug( 'Destroying unit%s %s', 's' if len(unit_names) == 1 else '', ' '.join(unit_names)) return await app_facade.DestroyUnits(list(unit_names))
python
async def destroy_unit(self, *unit_names): """Destroy units by name. """ connection = self.connection() app_facade = client.ApplicationFacade.from_connection(connection) log.debug( 'Destroying unit%s %s', 's' if len(unit_names) == 1 else '', ' '.join(unit_names)) return await app_facade.DestroyUnits(list(unit_names))
[ "async", "def", "destroy_unit", "(", "self", ",", "*", "unit_names", ")", ":", "connection", "=", "self", ".", "connection", "(", ")", "app_facade", "=", "client", ".", "ApplicationFacade", ".", "from_connection", "(", "connection", ")", "log", ".", "debug",...
Destroy units by name.
[ "Destroy", "units", "by", "name", "." ]
58f0011f4c57cd68830258952fa952eaadca6b38
https://github.com/juju/python-libjuju/blob/58f0011f4c57cd68830258952fa952eaadca6b38/juju/model.py#L1449-L1461
train
25,190
juju/python-libjuju
juju/model.py
Model.get_config
async def get_config(self): """Return the configuration settings for this model. :returns: A ``dict`` mapping keys to `ConfigValue` instances, which have `source` and `value` attributes. """ config_facade = client.ModelConfigFacade.from_connection( self.connection() ) result = await config_facade.ModelGet() config = result.config for key, value in config.items(): config[key] = ConfigValue.from_json(value) return config
python
async def get_config(self): """Return the configuration settings for this model. :returns: A ``dict`` mapping keys to `ConfigValue` instances, which have `source` and `value` attributes. """ config_facade = client.ModelConfigFacade.from_connection( self.connection() ) result = await config_facade.ModelGet() config = result.config for key, value in config.items(): config[key] = ConfigValue.from_json(value) return config
[ "async", "def", "get_config", "(", "self", ")", ":", "config_facade", "=", "client", ".", "ModelConfigFacade", ".", "from_connection", "(", "self", ".", "connection", "(", ")", ")", "result", "=", "await", "config_facade", ".", "ModelGet", "(", ")", "config"...
Return the configuration settings for this model. :returns: A ``dict`` mapping keys to `ConfigValue` instances, which have `source` and `value` attributes.
[ "Return", "the", "configuration", "settings", "for", "this", "model", "." ]
58f0011f4c57cd68830258952fa952eaadca6b38
https://github.com/juju/python-libjuju/blob/58f0011f4c57cd68830258952fa952eaadca6b38/juju/model.py#L1492-L1505
train
25,191
juju/python-libjuju
juju/model.py
Model.get_constraints
async def get_constraints(self): """Return the machine constraints for this model. :returns: A ``dict`` of constraints. """ constraints = {} client_facade = client.ClientFacade.from_connection(self.connection()) result = await client_facade.GetModelConstraints() # GetModelConstraints returns GetConstraintsResults which has a # 'constraints' attribute. If no constraints have been set # GetConstraintsResults.constraints is None. Otherwise # GetConstraintsResults.constraints has an attribute for each possible # constraint, each of these in turn will be None if they have not been # set. if result.constraints: constraint_types = [a for a in dir(result.constraints) if a in Value._toSchema.keys()] for constraint in constraint_types: value = getattr(result.constraints, constraint) if value is not None: constraints[constraint] = getattr(result.constraints, constraint) return constraints
python
async def get_constraints(self): """Return the machine constraints for this model. :returns: A ``dict`` of constraints. """ constraints = {} client_facade = client.ClientFacade.from_connection(self.connection()) result = await client_facade.GetModelConstraints() # GetModelConstraints returns GetConstraintsResults which has a # 'constraints' attribute. If no constraints have been set # GetConstraintsResults.constraints is None. Otherwise # GetConstraintsResults.constraints has an attribute for each possible # constraint, each of these in turn will be None if they have not been # set. if result.constraints: constraint_types = [a for a in dir(result.constraints) if a in Value._toSchema.keys()] for constraint in constraint_types: value = getattr(result.constraints, constraint) if value is not None: constraints[constraint] = getattr(result.constraints, constraint) return constraints
[ "async", "def", "get_constraints", "(", "self", ")", ":", "constraints", "=", "{", "}", "client_facade", "=", "client", ".", "ClientFacade", ".", "from_connection", "(", "self", ".", "connection", "(", ")", ")", "result", "=", "await", "client_facade", ".", ...
Return the machine constraints for this model. :returns: A ``dict`` of constraints.
[ "Return", "the", "machine", "constraints", "for", "this", "model", "." ]
58f0011f4c57cd68830258952fa952eaadca6b38
https://github.com/juju/python-libjuju/blob/58f0011f4c57cd68830258952fa952eaadca6b38/juju/model.py#L1507-L1530
train
25,192
juju/python-libjuju
juju/model.py
Model.restore_backup
def restore_backup( self, bootstrap=False, constraints=None, archive=None, backup_id=None, upload_tools=False): """Restore a backup archive to a new controller. :param bool bootstrap: Bootstrap a new state machine :param constraints: Model constraints :type constraints: :class:`juju.Constraints` :param str archive: Path to backup archive to restore :param str backup_id: Id of backup to restore :param bool upload_tools: Upload tools if bootstrapping a new machine """ raise NotImplementedError()
python
def restore_backup( self, bootstrap=False, constraints=None, archive=None, backup_id=None, upload_tools=False): """Restore a backup archive to a new controller. :param bool bootstrap: Bootstrap a new state machine :param constraints: Model constraints :type constraints: :class:`juju.Constraints` :param str archive: Path to backup archive to restore :param str backup_id: Id of backup to restore :param bool upload_tools: Upload tools if bootstrapping a new machine """ raise NotImplementedError()
[ "def", "restore_backup", "(", "self", ",", "bootstrap", "=", "False", ",", "constraints", "=", "None", ",", "archive", "=", "None", ",", "backup_id", "=", "None", ",", "upload_tools", "=", "False", ")", ":", "raise", "NotImplementedError", "(", ")" ]
Restore a backup archive to a new controller. :param bool bootstrap: Bootstrap a new state machine :param constraints: Model constraints :type constraints: :class:`juju.Constraints` :param str archive: Path to backup archive to restore :param str backup_id: Id of backup to restore :param bool upload_tools: Upload tools if bootstrapping a new machine
[ "Restore", "a", "backup", "archive", "to", "a", "new", "controller", "." ]
58f0011f4c57cd68830258952fa952eaadca6b38
https://github.com/juju/python-libjuju/blob/58f0011f4c57cd68830258952fa952eaadca6b38/juju/model.py#L1645-L1658
train
25,193
juju/python-libjuju
juju/model.py
Model.set_config
async def set_config(self, config): """Set configuration keys on this model. :param dict config: Mapping of config keys to either string values or `ConfigValue` instances, as returned by `get_config`. """ config_facade = client.ModelConfigFacade.from_connection( self.connection() ) for key, value in config.items(): if isinstance(value, ConfigValue): config[key] = value.value await config_facade.ModelSet(config)
python
async def set_config(self, config): """Set configuration keys on this model. :param dict config: Mapping of config keys to either string values or `ConfigValue` instances, as returned by `get_config`. """ config_facade = client.ModelConfigFacade.from_connection( self.connection() ) for key, value in config.items(): if isinstance(value, ConfigValue): config[key] = value.value await config_facade.ModelSet(config)
[ "async", "def", "set_config", "(", "self", ",", "config", ")", ":", "config_facade", "=", "client", ".", "ModelConfigFacade", ".", "from_connection", "(", "self", ".", "connection", "(", ")", ")", "for", "key", ",", "value", "in", "config", ".", "items", ...
Set configuration keys on this model. :param dict config: Mapping of config keys to either string values or `ConfigValue` instances, as returned by `get_config`.
[ "Set", "configuration", "keys", "on", "this", "model", "." ]
58f0011f4c57cd68830258952fa952eaadca6b38
https://github.com/juju/python-libjuju/blob/58f0011f4c57cd68830258952fa952eaadca6b38/juju/model.py#L1675-L1687
train
25,194
juju/python-libjuju
juju/model.py
Model.set_constraints
async def set_constraints(self, constraints): """Set machine constraints on this model. :param dict config: Mapping of model constraints """ client_facade = client.ClientFacade.from_connection(self.connection()) await client_facade.SetModelConstraints( application='', constraints=constraints)
python
async def set_constraints(self, constraints): """Set machine constraints on this model. :param dict config: Mapping of model constraints """ client_facade = client.ClientFacade.from_connection(self.connection()) await client_facade.SetModelConstraints( application='', constraints=constraints)
[ "async", "def", "set_constraints", "(", "self", ",", "constraints", ")", ":", "client_facade", "=", "client", ".", "ClientFacade", ".", "from_connection", "(", "self", ".", "connection", "(", ")", ")", "await", "client_facade", ".", "SetModelConstraints", "(", ...
Set machine constraints on this model. :param dict config: Mapping of model constraints
[ "Set", "machine", "constraints", "on", "this", "model", "." ]
58f0011f4c57cd68830258952fa952eaadca6b38
https://github.com/juju/python-libjuju/blob/58f0011f4c57cd68830258952fa952eaadca6b38/juju/model.py#L1689-L1697
train
25,195
juju/python-libjuju
juju/model.py
Model.get_action_output
async def get_action_output(self, action_uuid, wait=None): """Get the results of an action by ID. :param str action_uuid: Id of the action :param int wait: Time in seconds to wait for action to complete. :return dict: Output from action :raises: :class:`JujuError` if invalid action_uuid """ action_facade = client.ActionFacade.from_connection( self.connection() ) entity = [{'tag': tag.action(action_uuid)}] # Cannot use self.wait_for_action as the action event has probably # already happened and self.wait_for_action works by processing # model deltas and checking if they match our type. If the action # has already occured then the delta has gone. async def _wait_for_action_status(): while True: action_output = await action_facade.Actions(entity) if action_output.results[0].status in ('completed', 'failed'): return else: await asyncio.sleep(1) await asyncio.wait_for( _wait_for_action_status(), timeout=wait) action_output = await action_facade.Actions(entity) # ActionResult.output is None if the action produced no output if action_output.results[0].output is None: output = {} else: output = action_output.results[0].output return output
python
async def get_action_output(self, action_uuid, wait=None): """Get the results of an action by ID. :param str action_uuid: Id of the action :param int wait: Time in seconds to wait for action to complete. :return dict: Output from action :raises: :class:`JujuError` if invalid action_uuid """ action_facade = client.ActionFacade.from_connection( self.connection() ) entity = [{'tag': tag.action(action_uuid)}] # Cannot use self.wait_for_action as the action event has probably # already happened and self.wait_for_action works by processing # model deltas and checking if they match our type. If the action # has already occured then the delta has gone. async def _wait_for_action_status(): while True: action_output = await action_facade.Actions(entity) if action_output.results[0].status in ('completed', 'failed'): return else: await asyncio.sleep(1) await asyncio.wait_for( _wait_for_action_status(), timeout=wait) action_output = await action_facade.Actions(entity) # ActionResult.output is None if the action produced no output if action_output.results[0].output is None: output = {} else: output = action_output.results[0].output return output
[ "async", "def", "get_action_output", "(", "self", ",", "action_uuid", ",", "wait", "=", "None", ")", ":", "action_facade", "=", "client", ".", "ActionFacade", ".", "from_connection", "(", "self", ".", "connection", "(", ")", ")", "entity", "=", "[", "{", ...
Get the results of an action by ID. :param str action_uuid: Id of the action :param int wait: Time in seconds to wait for action to complete. :return dict: Output from action :raises: :class:`JujuError` if invalid action_uuid
[ "Get", "the", "results", "of", "an", "action", "by", "ID", "." ]
58f0011f4c57cd68830258952fa952eaadca6b38
https://github.com/juju/python-libjuju/blob/58f0011f4c57cd68830258952fa952eaadca6b38/juju/model.py#L1699-L1732
train
25,196
juju/python-libjuju
juju/model.py
Model.get_action_status
async def get_action_status(self, uuid_or_prefix=None, name=None): """Get the status of all actions, filtered by ID, ID prefix, or name. :param str uuid_or_prefix: Filter by action uuid or prefix :param str name: Filter by action name """ results = {} action_results = [] action_facade = client.ActionFacade.from_connection( self.connection() ) if name: name_results = await action_facade.FindActionsByNames([name]) action_results.extend(name_results.actions[0].actions) if uuid_or_prefix: # Collect list of actions matching uuid or prefix matching_actions = await action_facade.FindActionTagsByPrefix( [uuid_or_prefix]) entities = [] for actions in matching_actions.matches.values(): entities = [{'tag': a.tag} for a in actions] # Get action results matching action tags uuid_results = await action_facade.Actions(entities) action_results.extend(uuid_results.results) for a in action_results: results[tag.untag('action-', a.action.tag)] = a.status return results
python
async def get_action_status(self, uuid_or_prefix=None, name=None): """Get the status of all actions, filtered by ID, ID prefix, or name. :param str uuid_or_prefix: Filter by action uuid or prefix :param str name: Filter by action name """ results = {} action_results = [] action_facade = client.ActionFacade.from_connection( self.connection() ) if name: name_results = await action_facade.FindActionsByNames([name]) action_results.extend(name_results.actions[0].actions) if uuid_or_prefix: # Collect list of actions matching uuid or prefix matching_actions = await action_facade.FindActionTagsByPrefix( [uuid_or_prefix]) entities = [] for actions in matching_actions.matches.values(): entities = [{'tag': a.tag} for a in actions] # Get action results matching action tags uuid_results = await action_facade.Actions(entities) action_results.extend(uuid_results.results) for a in action_results: results[tag.untag('action-', a.action.tag)] = a.status return results
[ "async", "def", "get_action_status", "(", "self", ",", "uuid_or_prefix", "=", "None", ",", "name", "=", "None", ")", ":", "results", "=", "{", "}", "action_results", "=", "[", "]", "action_facade", "=", "client", ".", "ActionFacade", ".", "from_connection", ...
Get the status of all actions, filtered by ID, ID prefix, or name. :param str uuid_or_prefix: Filter by action uuid or prefix :param str name: Filter by action name
[ "Get", "the", "status", "of", "all", "actions", "filtered", "by", "ID", "ID", "prefix", "or", "name", "." ]
58f0011f4c57cd68830258952fa952eaadca6b38
https://github.com/juju/python-libjuju/blob/58f0011f4c57cd68830258952fa952eaadca6b38/juju/model.py#L1734-L1761
train
25,197
juju/python-libjuju
juju/model.py
Model.get_status
async def get_status(self, filters=None, utc=False): """Return the status of the model. :param str filters: Optional list of applications, units, or machines to include, which can use wildcards ('*'). :param bool utc: Display time as UTC in RFC3339 format """ client_facade = client.ClientFacade.from_connection(self.connection()) return await client_facade.FullStatus(filters)
python
async def get_status(self, filters=None, utc=False): """Return the status of the model. :param str filters: Optional list of applications, units, or machines to include, which can use wildcards ('*'). :param bool utc: Display time as UTC in RFC3339 format """ client_facade = client.ClientFacade.from_connection(self.connection()) return await client_facade.FullStatus(filters)
[ "async", "def", "get_status", "(", "self", ",", "filters", "=", "None", ",", "utc", "=", "False", ")", ":", "client_facade", "=", "client", ".", "ClientFacade", ".", "from_connection", "(", "self", ".", "connection", "(", ")", ")", "return", "await", "cl...
Return the status of the model. :param str filters: Optional list of applications, units, or machines to include, which can use wildcards ('*'). :param bool utc: Display time as UTC in RFC3339 format
[ "Return", "the", "status", "of", "the", "model", "." ]
58f0011f4c57cd68830258952fa952eaadca6b38
https://github.com/juju/python-libjuju/blob/58f0011f4c57cd68830258952fa952eaadca6b38/juju/model.py#L1771-L1780
train
25,198
juju/python-libjuju
juju/model.py
Model.sync_tools
def sync_tools( self, all_=False, destination=None, dry_run=False, public=False, source=None, stream=None, version=None): """Copy Juju tools into this model. :param bool all_: Copy all versions, not just the latest :param str destination: Path to local destination directory :param bool dry_run: Don't do the actual copy :param bool public: Tools are for a public cloud, so generate mirrors information :param str source: Path to local source directory :param str stream: Simplestreams stream for which to sync metadata :param str version: Copy a specific major.minor version """ raise NotImplementedError()
python
def sync_tools( self, all_=False, destination=None, dry_run=False, public=False, source=None, stream=None, version=None): """Copy Juju tools into this model. :param bool all_: Copy all versions, not just the latest :param str destination: Path to local destination directory :param bool dry_run: Don't do the actual copy :param bool public: Tools are for a public cloud, so generate mirrors information :param str source: Path to local source directory :param str stream: Simplestreams stream for which to sync metadata :param str version: Copy a specific major.minor version """ raise NotImplementedError()
[ "def", "sync_tools", "(", "self", ",", "all_", "=", "False", ",", "destination", "=", "None", ",", "dry_run", "=", "False", ",", "public", "=", "False", ",", "source", "=", "None", ",", "stream", "=", "None", ",", "version", "=", "None", ")", ":", ...
Copy Juju tools into this model. :param bool all_: Copy all versions, not just the latest :param str destination: Path to local destination directory :param bool dry_run: Don't do the actual copy :param bool public: Tools are for a public cloud, so generate mirrors information :param str source: Path to local source directory :param str stream: Simplestreams stream for which to sync metadata :param str version: Copy a specific major.minor version
[ "Copy", "Juju", "tools", "into", "this", "model", "." ]
58f0011f4c57cd68830258952fa952eaadca6b38
https://github.com/juju/python-libjuju/blob/58f0011f4c57cd68830258952fa952eaadca6b38/juju/model.py#L1782-L1797
train
25,199