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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
Sheeprider/BitBucket-api | bitbucket/repository.py | Repository.public | def public(self, username=None):
""" Returns all public repositories from an user.
If username is not defined, tries to return own public repos.
"""
username = username or self.bitbucket.username or ''
url = self.bitbucket.url('GET_USER', username=username)
response = self.bitbucket.dispatch('GET', url)
try:
return (response[0], response[1]['repositories'])
except TypeError:
pass
return response | python | def public(self, username=None):
""" Returns all public repositories from an user.
If username is not defined, tries to return own public repos.
"""
username = username or self.bitbucket.username or ''
url = self.bitbucket.url('GET_USER', username=username)
response = self.bitbucket.dispatch('GET', url)
try:
return (response[0], response[1]['repositories'])
except TypeError:
pass
return response | [
"def",
"public",
"(",
"self",
",",
"username",
"=",
"None",
")",
":",
"username",
"=",
"username",
"or",
"self",
".",
"bitbucket",
".",
"username",
"or",
"''",
"url",
"=",
"self",
".",
"bitbucket",
".",
"url",
"(",
"'GET_USER'",
",",
"username",
"=",
... | Returns all public repositories from an user.
If username is not defined, tries to return own public repos. | [
"Returns",
"all",
"public",
"repositories",
"from",
"an",
"user",
".",
"If",
"username",
"is",
"not",
"defined",
"tries",
"to",
"return",
"own",
"public",
"repos",
"."
] | be45515d506d87f14807a676f3c2f20d79674b75 | https://github.com/Sheeprider/BitBucket-api/blob/be45515d506d87f14807a676f3c2f20d79674b75/bitbucket/repository.py#L50-L61 | train | 39,200 |
Sheeprider/BitBucket-api | bitbucket/repository.py | Repository.all | def all(self):
""" Return own repositories."""
url = self.bitbucket.url('GET_USER', username=self.bitbucket.username)
response = self.bitbucket.dispatch('GET', url, auth=self.bitbucket.auth)
try:
return (response[0], response[1]['repositories'])
except TypeError:
pass
return response | python | def all(self):
""" Return own repositories."""
url = self.bitbucket.url('GET_USER', username=self.bitbucket.username)
response = self.bitbucket.dispatch('GET', url, auth=self.bitbucket.auth)
try:
return (response[0], response[1]['repositories'])
except TypeError:
pass
return response | [
"def",
"all",
"(",
"self",
")",
":",
"url",
"=",
"self",
".",
"bitbucket",
".",
"url",
"(",
"'GET_USER'",
",",
"username",
"=",
"self",
".",
"bitbucket",
".",
"username",
")",
"response",
"=",
"self",
".",
"bitbucket",
".",
"dispatch",
"(",
"'GET'",
... | Return own repositories. | [
"Return",
"own",
"repositories",
"."
] | be45515d506d87f14807a676f3c2f20d79674b75 | https://github.com/Sheeprider/BitBucket-api/blob/be45515d506d87f14807a676f3c2f20d79674b75/bitbucket/repository.py#L63-L71 | train | 39,201 |
Sheeprider/BitBucket-api | bitbucket/repository.py | Repository.create | def create(self, repo_name, scm='git', private=True, **kwargs):
""" Creates a new repository on own Bitbucket account and return it."""
url = self.bitbucket.url('CREATE_REPO')
return self.bitbucket.dispatch('POST', url, auth=self.bitbucket.auth, name=repo_name, scm=scm, is_private=private, **kwargs) | python | def create(self, repo_name, scm='git', private=True, **kwargs):
""" Creates a new repository on own Bitbucket account and return it."""
url = self.bitbucket.url('CREATE_REPO')
return self.bitbucket.dispatch('POST', url, auth=self.bitbucket.auth, name=repo_name, scm=scm, is_private=private, **kwargs) | [
"def",
"create",
"(",
"self",
",",
"repo_name",
",",
"scm",
"=",
"'git'",
",",
"private",
"=",
"True",
",",
"*",
"*",
"kwargs",
")",
":",
"url",
"=",
"self",
".",
"bitbucket",
".",
"url",
"(",
"'CREATE_REPO'",
")",
"return",
"self",
".",
"bitbucket",... | Creates a new repository on own Bitbucket account and return it. | [
"Creates",
"a",
"new",
"repository",
"on",
"own",
"Bitbucket",
"account",
"and",
"return",
"it",
"."
] | be45515d506d87f14807a676f3c2f20d79674b75 | https://github.com/Sheeprider/BitBucket-api/blob/be45515d506d87f14807a676f3c2f20d79674b75/bitbucket/repository.py#L79-L82 | train | 39,202 |
Sheeprider/BitBucket-api | bitbucket/repository.py | Repository.archive | def archive(self, repo_slug=None, format='zip', prefix=''):
""" Get one of your repositories and compress it as an archive.
Return the path of the archive.
format parameter is curently not supported.
"""
prefix = '%s'.lstrip('/') % prefix
self._get_files_in_dir(repo_slug=repo_slug, dir='/')
if self.bitbucket.repo_tree:
with NamedTemporaryFile(delete=False) as archive:
with ZipFile(archive, 'w') as zip_archive:
for name, file in self.bitbucket.repo_tree.items():
with NamedTemporaryFile(delete=False) as temp_file:
temp_file.write(file.encode('utf-8'))
zip_archive.write(temp_file.name, prefix + name)
return (True, archive.name)
return (False, 'Could not archive your project.') | python | def archive(self, repo_slug=None, format='zip', prefix=''):
""" Get one of your repositories and compress it as an archive.
Return the path of the archive.
format parameter is curently not supported.
"""
prefix = '%s'.lstrip('/') % prefix
self._get_files_in_dir(repo_slug=repo_slug, dir='/')
if self.bitbucket.repo_tree:
with NamedTemporaryFile(delete=False) as archive:
with ZipFile(archive, 'w') as zip_archive:
for name, file in self.bitbucket.repo_tree.items():
with NamedTemporaryFile(delete=False) as temp_file:
temp_file.write(file.encode('utf-8'))
zip_archive.write(temp_file.name, prefix + name)
return (True, archive.name)
return (False, 'Could not archive your project.') | [
"def",
"archive",
"(",
"self",
",",
"repo_slug",
"=",
"None",
",",
"format",
"=",
"'zip'",
",",
"prefix",
"=",
"''",
")",
":",
"prefix",
"=",
"'%s'",
".",
"lstrip",
"(",
"'/'",
")",
"%",
"prefix",
"self",
".",
"_get_files_in_dir",
"(",
"repo_slug",
"... | Get one of your repositories and compress it as an archive.
Return the path of the archive.
format parameter is curently not supported. | [
"Get",
"one",
"of",
"your",
"repositories",
"and",
"compress",
"it",
"as",
"an",
"archive",
".",
"Return",
"the",
"path",
"of",
"the",
"archive",
"."
] | be45515d506d87f14807a676f3c2f20d79674b75 | https://github.com/Sheeprider/BitBucket-api/blob/be45515d506d87f14807a676f3c2f20d79674b75/bitbucket/repository.py#L98-L114 | train | 39,203 |
Sheeprider/BitBucket-api | bitbucket/issue_comment.py | IssueComment.create | def create(self, issue_id=None, repo_slug=None, **kwargs):
""" Add an issue comment to one of your repositories.
Each issue comment require only the content data field
the system autopopulate the rest.
"""
issue_id = issue_id or self.issue_id
repo_slug = repo_slug or self.bitbucket.repo_slug or ''
url = self.bitbucket.url('CREATE_COMMENT',
username=self.bitbucket.username,
repo_slug=repo_slug,
issue_id=issue_id)
return self.bitbucket.dispatch('POST', url, auth=self.bitbucket.auth, **kwargs) | python | def create(self, issue_id=None, repo_slug=None, **kwargs):
""" Add an issue comment to one of your repositories.
Each issue comment require only the content data field
the system autopopulate the rest.
"""
issue_id = issue_id or self.issue_id
repo_slug = repo_slug or self.bitbucket.repo_slug or ''
url = self.bitbucket.url('CREATE_COMMENT',
username=self.bitbucket.username,
repo_slug=repo_slug,
issue_id=issue_id)
return self.bitbucket.dispatch('POST', url, auth=self.bitbucket.auth, **kwargs) | [
"def",
"create",
"(",
"self",
",",
"issue_id",
"=",
"None",
",",
"repo_slug",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"issue_id",
"=",
"issue_id",
"or",
"self",
".",
"issue_id",
"repo_slug",
"=",
"repo_slug",
"or",
"self",
".",
"bitbucket",
"."... | Add an issue comment to one of your repositories.
Each issue comment require only the content data field
the system autopopulate the rest. | [
"Add",
"an",
"issue",
"comment",
"to",
"one",
"of",
"your",
"repositories",
".",
"Each",
"issue",
"comment",
"require",
"only",
"the",
"content",
"data",
"field",
"the",
"system",
"autopopulate",
"the",
"rest",
"."
] | be45515d506d87f14807a676f3c2f20d79674b75 | https://github.com/Sheeprider/BitBucket-api/blob/be45515d506d87f14807a676f3c2f20d79674b75/bitbucket/issue_comment.py#L44-L55 | train | 39,204 |
Sheeprider/BitBucket-api | bitbucket/issue_comment.py | IssueComment.delete | def delete(self, comment_id, issue_id=None, repo_slug=None):
""" Delete an issue from one of your repositories.
"""
issue_id = issue_id or self.issue_id
repo_slug = repo_slug or self.bitbucket.repo_slug or ''
url = self.bitbucket.url('DELETE_COMMENT',
username=self.bitbucket.username,
repo_slug=repo_slug,
issue_id=issue_id,
comment_id=comment_id)
return self.bitbucket.dispatch('DELETE', url, auth=self.bitbucket.auth) | python | def delete(self, comment_id, issue_id=None, repo_slug=None):
""" Delete an issue from one of your repositories.
"""
issue_id = issue_id or self.issue_id
repo_slug = repo_slug or self.bitbucket.repo_slug or ''
url = self.bitbucket.url('DELETE_COMMENT',
username=self.bitbucket.username,
repo_slug=repo_slug,
issue_id=issue_id,
comment_id=comment_id)
return self.bitbucket.dispatch('DELETE', url, auth=self.bitbucket.auth) | [
"def",
"delete",
"(",
"self",
",",
"comment_id",
",",
"issue_id",
"=",
"None",
",",
"repo_slug",
"=",
"None",
")",
":",
"issue_id",
"=",
"issue_id",
"or",
"self",
".",
"issue_id",
"repo_slug",
"=",
"repo_slug",
"or",
"self",
".",
"bitbucket",
".",
"repo_... | Delete an issue from one of your repositories. | [
"Delete",
"an",
"issue",
"from",
"one",
"of",
"your",
"repositories",
"."
] | be45515d506d87f14807a676f3c2f20d79674b75 | https://github.com/Sheeprider/BitBucket-api/blob/be45515d506d87f14807a676f3c2f20d79674b75/bitbucket/issue_comment.py#L71-L81 | train | 39,205 |
Sheeprider/BitBucket-api | bitbucket/ssh.py | SSH.all | def all(self):
""" Get all ssh keys associated with your account.
"""
url = self.bitbucket.url('GET_SSH_KEYS')
return self.bitbucket.dispatch('GET', url, auth=self.bitbucket.auth) | python | def all(self):
""" Get all ssh keys associated with your account.
"""
url = self.bitbucket.url('GET_SSH_KEYS')
return self.bitbucket.dispatch('GET', url, auth=self.bitbucket.auth) | [
"def",
"all",
"(",
"self",
")",
":",
"url",
"=",
"self",
".",
"bitbucket",
".",
"url",
"(",
"'GET_SSH_KEYS'",
")",
"return",
"self",
".",
"bitbucket",
".",
"dispatch",
"(",
"'GET'",
",",
"url",
",",
"auth",
"=",
"self",
".",
"bitbucket",
".",
"auth",... | Get all ssh keys associated with your account. | [
"Get",
"all",
"ssh",
"keys",
"associated",
"with",
"your",
"account",
"."
] | be45515d506d87f14807a676f3c2f20d79674b75 | https://github.com/Sheeprider/BitBucket-api/blob/be45515d506d87f14807a676f3c2f20d79674b75/bitbucket/ssh.py#L18-L22 | train | 39,206 |
Sheeprider/BitBucket-api | bitbucket/ssh.py | SSH.get | def get(self, key_id=None):
""" Get one of the ssh keys associated with your account.
"""
url = self.bitbucket.url('GET_SSH_KEY', key_id=key_id)
return self.bitbucket.dispatch('GET', url, auth=self.bitbucket.auth) | python | def get(self, key_id=None):
""" Get one of the ssh keys associated with your account.
"""
url = self.bitbucket.url('GET_SSH_KEY', key_id=key_id)
return self.bitbucket.dispatch('GET', url, auth=self.bitbucket.auth) | [
"def",
"get",
"(",
"self",
",",
"key_id",
"=",
"None",
")",
":",
"url",
"=",
"self",
".",
"bitbucket",
".",
"url",
"(",
"'GET_SSH_KEY'",
",",
"key_id",
"=",
"key_id",
")",
"return",
"self",
".",
"bitbucket",
".",
"dispatch",
"(",
"'GET'",
",",
"url",... | Get one of the ssh keys associated with your account. | [
"Get",
"one",
"of",
"the",
"ssh",
"keys",
"associated",
"with",
"your",
"account",
"."
] | be45515d506d87f14807a676f3c2f20d79674b75 | https://github.com/Sheeprider/BitBucket-api/blob/be45515d506d87f14807a676f3c2f20d79674b75/bitbucket/ssh.py#L24-L28 | train | 39,207 |
Sheeprider/BitBucket-api | bitbucket/ssh.py | SSH.create | def create(self, key=None, label=None):
""" Associate an ssh key with your account and return it.
"""
key = '%s' % key
url = self.bitbucket.url('SET_SSH_KEY')
return self.bitbucket.dispatch('POST', url, auth=self.bitbucket.auth, key=key, label=label) | python | def create(self, key=None, label=None):
""" Associate an ssh key with your account and return it.
"""
key = '%s' % key
url = self.bitbucket.url('SET_SSH_KEY')
return self.bitbucket.dispatch('POST', url, auth=self.bitbucket.auth, key=key, label=label) | [
"def",
"create",
"(",
"self",
",",
"key",
"=",
"None",
",",
"label",
"=",
"None",
")",
":",
"key",
"=",
"'%s'",
"%",
"key",
"url",
"=",
"self",
".",
"bitbucket",
".",
"url",
"(",
"'SET_SSH_KEY'",
")",
"return",
"self",
".",
"bitbucket",
".",
"dispa... | Associate an ssh key with your account and return it. | [
"Associate",
"an",
"ssh",
"key",
"with",
"your",
"account",
"and",
"return",
"it",
"."
] | be45515d506d87f14807a676f3c2f20d79674b75 | https://github.com/Sheeprider/BitBucket-api/blob/be45515d506d87f14807a676f3c2f20d79674b75/bitbucket/ssh.py#L30-L35 | train | 39,208 |
Sheeprider/BitBucket-api | bitbucket/ssh.py | SSH.delete | def delete(self, key_id=None):
""" Delete one of the ssh keys associated with your account.
Please use with caution as there is NO confimation and NO undo.
"""
url = self.bitbucket.url('DELETE_SSH_KEY', key_id=key_id)
return self.bitbucket.dispatch('DELETE', url, auth=self.bitbucket.auth) | python | def delete(self, key_id=None):
""" Delete one of the ssh keys associated with your account.
Please use with caution as there is NO confimation and NO undo.
"""
url = self.bitbucket.url('DELETE_SSH_KEY', key_id=key_id)
return self.bitbucket.dispatch('DELETE', url, auth=self.bitbucket.auth) | [
"def",
"delete",
"(",
"self",
",",
"key_id",
"=",
"None",
")",
":",
"url",
"=",
"self",
".",
"bitbucket",
".",
"url",
"(",
"'DELETE_SSH_KEY'",
",",
"key_id",
"=",
"key_id",
")",
"return",
"self",
".",
"bitbucket",
".",
"dispatch",
"(",
"'DELETE'",
",",... | Delete one of the ssh keys associated with your account.
Please use with caution as there is NO confimation and NO undo. | [
"Delete",
"one",
"of",
"the",
"ssh",
"keys",
"associated",
"with",
"your",
"account",
".",
"Please",
"use",
"with",
"caution",
"as",
"there",
"is",
"NO",
"confimation",
"and",
"NO",
"undo",
"."
] | be45515d506d87f14807a676f3c2f20d79674b75 | https://github.com/Sheeprider/BitBucket-api/blob/be45515d506d87f14807a676f3c2f20d79674b75/bitbucket/ssh.py#L37-L42 | train | 39,209 |
todddeluca/python-vagrant | vagrant/__init__.py | make_file_cm | def make_file_cm(filename, mode='a'):
'''
Open a file for appending and yield the open filehandle. Close the
filehandle after yielding it. This is useful for creating a context
manager for logging the output of a `Vagrant` instance.
filename: a path to a file
mode: The mode in which to open the file. Defaults to 'a', append
Usage example:
log_cm = make_file_cm('application.log')
v = Vagrant(out_cm=log_cm, err_cm=log_cm)
'''
@contextlib.contextmanager
def cm():
with open(filename, mode=mode) as fh:
yield fh
return cm | python | def make_file_cm(filename, mode='a'):
'''
Open a file for appending and yield the open filehandle. Close the
filehandle after yielding it. This is useful for creating a context
manager for logging the output of a `Vagrant` instance.
filename: a path to a file
mode: The mode in which to open the file. Defaults to 'a', append
Usage example:
log_cm = make_file_cm('application.log')
v = Vagrant(out_cm=log_cm, err_cm=log_cm)
'''
@contextlib.contextmanager
def cm():
with open(filename, mode=mode) as fh:
yield fh
return cm | [
"def",
"make_file_cm",
"(",
"filename",
",",
"mode",
"=",
"'a'",
")",
":",
"@",
"contextlib",
".",
"contextmanager",
"def",
"cm",
"(",
")",
":",
"with",
"open",
"(",
"filename",
",",
"mode",
"=",
"mode",
")",
"as",
"fh",
":",
"yield",
"fh",
"return",... | Open a file for appending and yield the open filehandle. Close the
filehandle after yielding it. This is useful for creating a context
manager for logging the output of a `Vagrant` instance.
filename: a path to a file
mode: The mode in which to open the file. Defaults to 'a', append
Usage example:
log_cm = make_file_cm('application.log')
v = Vagrant(out_cm=log_cm, err_cm=log_cm) | [
"Open",
"a",
"file",
"for",
"appending",
"and",
"yield",
"the",
"open",
"filehandle",
".",
"Close",
"the",
"filehandle",
"after",
"yielding",
"it",
".",
"This",
"is",
"useful",
"for",
"creating",
"a",
"context",
"manager",
"for",
"logging",
"the",
"output",
... | 83b26f9337b1f2cb6314210923bbd189e7c9199e | https://github.com/todddeluca/python-vagrant/blob/83b26f9337b1f2cb6314210923bbd189e7c9199e/vagrant/__init__.py#L171-L190 | train | 39,210 |
todddeluca/python-vagrant | vagrant/__init__.py | Vagrant.halt | def halt(self, vm_name=None, force=False):
'''
Halt the Vagrant box.
force: If True, force shut down.
'''
force_opt = '--force' if force else None
self._call_vagrant_command(['halt', vm_name, force_opt])
self._cached_conf[vm_name] = None | python | def halt(self, vm_name=None, force=False):
'''
Halt the Vagrant box.
force: If True, force shut down.
'''
force_opt = '--force' if force else None
self._call_vagrant_command(['halt', vm_name, force_opt])
self._cached_conf[vm_name] = None | [
"def",
"halt",
"(",
"self",
",",
"vm_name",
"=",
"None",
",",
"force",
"=",
"False",
")",
":",
"force_opt",
"=",
"'--force'",
"if",
"force",
"else",
"None",
"self",
".",
"_call_vagrant_command",
"(",
"[",
"'halt'",
",",
"vm_name",
",",
"force_opt",
"]",
... | Halt the Vagrant box.
force: If True, force shut down. | [
"Halt",
"the",
"Vagrant",
"box",
"."
] | 83b26f9337b1f2cb6314210923bbd189e7c9199e | https://github.com/todddeluca/python-vagrant/blob/83b26f9337b1f2cb6314210923bbd189e7c9199e/vagrant/__init__.py#L403-L411 | train | 39,211 |
todddeluca/python-vagrant | vagrant/__init__.py | Vagrant._parse_status | def _parse_status(self, output):
'''
Unit testing is so much easier when Vagrant is removed from the
equation.
'''
parsed = self._parse_machine_readable_output(output)
statuses = []
# group tuples by target name
# assuming tuples are sorted by target name, this should group all
# the tuples with info for each target.
for target, tuples in itertools.groupby(parsed, lambda tup: tup[1]):
# transform tuples into a dict mapping "type" to "data"
info = {kind: data for timestamp, _, kind, data in tuples}
status = Status(name=target, state=info.get('state'),
provider=info.get('provider-name'))
statuses.append(status)
return statuses | python | def _parse_status(self, output):
'''
Unit testing is so much easier when Vagrant is removed from the
equation.
'''
parsed = self._parse_machine_readable_output(output)
statuses = []
# group tuples by target name
# assuming tuples are sorted by target name, this should group all
# the tuples with info for each target.
for target, tuples in itertools.groupby(parsed, lambda tup: tup[1]):
# transform tuples into a dict mapping "type" to "data"
info = {kind: data for timestamp, _, kind, data in tuples}
status = Status(name=target, state=info.get('state'),
provider=info.get('provider-name'))
statuses.append(status)
return statuses | [
"def",
"_parse_status",
"(",
"self",
",",
"output",
")",
":",
"parsed",
"=",
"self",
".",
"_parse_machine_readable_output",
"(",
"output",
")",
"statuses",
"=",
"[",
"]",
"# group tuples by target name",
"# assuming tuples are sorted by target name, this should group all",
... | Unit testing is so much easier when Vagrant is removed from the
equation. | [
"Unit",
"testing",
"is",
"so",
"much",
"easier",
"when",
"Vagrant",
"is",
"removed",
"from",
"the",
"equation",
"."
] | 83b26f9337b1f2cb6314210923bbd189e7c9199e | https://github.com/todddeluca/python-vagrant/blob/83b26f9337b1f2cb6314210923bbd189e7c9199e/vagrant/__init__.py#L496-L513 | train | 39,212 |
todddeluca/python-vagrant | vagrant/__init__.py | Vagrant.box_add | def box_add(self, name, url, provider=None, force=False):
'''
Adds a box with given name, from given url.
force: If True, overwrite an existing box if it exists.
'''
force_opt = '--force' if force else None
cmd = ['box', 'add', name, url, force_opt]
if provider is not None:
cmd += ['--provider', provider]
self._call_vagrant_command(cmd) | python | def box_add(self, name, url, provider=None, force=False):
'''
Adds a box with given name, from given url.
force: If True, overwrite an existing box if it exists.
'''
force_opt = '--force' if force else None
cmd = ['box', 'add', name, url, force_opt]
if provider is not None:
cmd += ['--provider', provider]
self._call_vagrant_command(cmd) | [
"def",
"box_add",
"(",
"self",
",",
"name",
",",
"url",
",",
"provider",
"=",
"None",
",",
"force",
"=",
"False",
")",
":",
"force_opt",
"=",
"'--force'",
"if",
"force",
"else",
"None",
"cmd",
"=",
"[",
"'box'",
",",
"'add'",
",",
"name",
",",
"url... | Adds a box with given name, from given url.
force: If True, overwrite an existing box if it exists. | [
"Adds",
"a",
"box",
"with",
"given",
"name",
"from",
"given",
"url",
"."
] | 83b26f9337b1f2cb6314210923bbd189e7c9199e | https://github.com/todddeluca/python-vagrant/blob/83b26f9337b1f2cb6314210923bbd189e7c9199e/vagrant/__init__.py#L643-L654 | train | 39,213 |
todddeluca/python-vagrant | vagrant/__init__.py | Vagrant.package | def package(self, vm_name=None, base=None, output=None, vagrantfile=None):
'''
Packages a running vagrant environment into a box.
vm_name=None: name of VM.
base=None: name of a VM in virtualbox to package as a base box
output=None: name of the file to output
vagrantfile=None: Vagrantfile to package with this box
'''
cmd = ['package', vm_name]
if output is not None:
cmd += ['--output', output]
if vagrantfile is not None:
cmd += ['--vagrantfile', vagrantfile]
self._call_vagrant_command(cmd) | python | def package(self, vm_name=None, base=None, output=None, vagrantfile=None):
'''
Packages a running vagrant environment into a box.
vm_name=None: name of VM.
base=None: name of a VM in virtualbox to package as a base box
output=None: name of the file to output
vagrantfile=None: Vagrantfile to package with this box
'''
cmd = ['package', vm_name]
if output is not None:
cmd += ['--output', output]
if vagrantfile is not None:
cmd += ['--vagrantfile', vagrantfile]
self._call_vagrant_command(cmd) | [
"def",
"package",
"(",
"self",
",",
"vm_name",
"=",
"None",
",",
"base",
"=",
"None",
",",
"output",
"=",
"None",
",",
"vagrantfile",
"=",
"None",
")",
":",
"cmd",
"=",
"[",
"'package'",
",",
"vm_name",
"]",
"if",
"output",
"is",
"not",
"None",
":"... | Packages a running vagrant environment into a box.
vm_name=None: name of VM.
base=None: name of a VM in virtualbox to package as a base box
output=None: name of the file to output
vagrantfile=None: Vagrantfile to package with this box | [
"Packages",
"a",
"running",
"vagrant",
"environment",
"into",
"a",
"box",
"."
] | 83b26f9337b1f2cb6314210923bbd189e7c9199e | https://github.com/todddeluca/python-vagrant/blob/83b26f9337b1f2cb6314210923bbd189e7c9199e/vagrant/__init__.py#L690-L705 | train | 39,214 |
todddeluca/python-vagrant | vagrant/__init__.py | Vagrant.snapshot_list | def snapshot_list(self):
'''
This command will list all the snapshots taken.
'''
NO_SNAPSHOTS_TAKEN = 'No snapshots have been taken yet!'
output = self._run_vagrant_command(['snapshot', 'list'])
if NO_SNAPSHOTS_TAKEN in output:
return []
else:
return output.splitlines() | python | def snapshot_list(self):
'''
This command will list all the snapshots taken.
'''
NO_SNAPSHOTS_TAKEN = 'No snapshots have been taken yet!'
output = self._run_vagrant_command(['snapshot', 'list'])
if NO_SNAPSHOTS_TAKEN in output:
return []
else:
return output.splitlines() | [
"def",
"snapshot_list",
"(",
"self",
")",
":",
"NO_SNAPSHOTS_TAKEN",
"=",
"'No snapshots have been taken yet!'",
"output",
"=",
"self",
".",
"_run_vagrant_command",
"(",
"[",
"'snapshot'",
",",
"'list'",
"]",
")",
"if",
"NO_SNAPSHOTS_TAKEN",
"in",
"output",
":",
"... | This command will list all the snapshots taken. | [
"This",
"command",
"will",
"list",
"all",
"the",
"snapshots",
"taken",
"."
] | 83b26f9337b1f2cb6314210923bbd189e7c9199e | https://github.com/todddeluca/python-vagrant/blob/83b26f9337b1f2cb6314210923bbd189e7c9199e/vagrant/__init__.py#L735-L744 | train | 39,215 |
todddeluca/python-vagrant | vagrant/__init__.py | Vagrant._parse_box_list | def _parse_box_list(self, output):
'''
Remove Vagrant usage for unit testing
'''
# Parse box list output
boxes = []
# initialize box values
name = provider = version = None
for timestamp, target, kind, data in self._parse_machine_readable_output(output):
if kind == 'box-name':
# finish the previous box, if any
if name is not None:
boxes.append(Box(name=name, provider=provider, version=version))
# start a new box
name = data # box name
provider = version = None
elif kind == 'box-provider':
provider = data
elif kind == 'box-version':
version = data
# finish the previous box, if any
if name is not None:
boxes.append(Box(name=name, provider=provider, version=version))
return boxes | python | def _parse_box_list(self, output):
'''
Remove Vagrant usage for unit testing
'''
# Parse box list output
boxes = []
# initialize box values
name = provider = version = None
for timestamp, target, kind, data in self._parse_machine_readable_output(output):
if kind == 'box-name':
# finish the previous box, if any
if name is not None:
boxes.append(Box(name=name, provider=provider, version=version))
# start a new box
name = data # box name
provider = version = None
elif kind == 'box-provider':
provider = data
elif kind == 'box-version':
version = data
# finish the previous box, if any
if name is not None:
boxes.append(Box(name=name, provider=provider, version=version))
return boxes | [
"def",
"_parse_box_list",
"(",
"self",
",",
"output",
")",
":",
"# Parse box list output",
"boxes",
"=",
"[",
"]",
"# initialize box values",
"name",
"=",
"provider",
"=",
"version",
"=",
"None",
"for",
"timestamp",
",",
"target",
",",
"kind",
",",
"data",
"... | Remove Vagrant usage for unit testing | [
"Remove",
"Vagrant",
"usage",
"for",
"unit",
"testing"
] | 83b26f9337b1f2cb6314210923bbd189e7c9199e | https://github.com/todddeluca/python-vagrant/blob/83b26f9337b1f2cb6314210923bbd189e7c9199e/vagrant/__init__.py#L765-L792 | train | 39,216 |
todddeluca/python-vagrant | vagrant/__init__.py | Vagrant._parse_plugin_list | def _parse_plugin_list(self, output):
'''
Remove Vagrant from the equation for unit testing.
'''
ENCODED_COMMA = '%!(VAGRANT_COMMA)'
plugins = []
# initialize plugin values
name = None
version = None
system = False
for timestamp, target, kind, data in self._parse_machine_readable_output(output):
if kind == 'plugin-name':
# finish the previous plugin, if any
if name is not None:
plugins.append(Plugin(name=name, version=version, system=system))
# start a new plugin
name = data # plugin name
version = None
system = False
elif kind == 'plugin-version':
if ENCODED_COMMA in data:
version, etc = data.split(ENCODED_COMMA)
system = (etc.strip().lower() == 'system')
else:
version = data
system = False
# finish the previous plugin, if any
if name is not None:
plugins.append(Plugin(name=name, version=version, system=system))
return plugins | python | def _parse_plugin_list(self, output):
'''
Remove Vagrant from the equation for unit testing.
'''
ENCODED_COMMA = '%!(VAGRANT_COMMA)'
plugins = []
# initialize plugin values
name = None
version = None
system = False
for timestamp, target, kind, data in self._parse_machine_readable_output(output):
if kind == 'plugin-name':
# finish the previous plugin, if any
if name is not None:
plugins.append(Plugin(name=name, version=version, system=system))
# start a new plugin
name = data # plugin name
version = None
system = False
elif kind == 'plugin-version':
if ENCODED_COMMA in data:
version, etc = data.split(ENCODED_COMMA)
system = (etc.strip().lower() == 'system')
else:
version = data
system = False
# finish the previous plugin, if any
if name is not None:
plugins.append(Plugin(name=name, version=version, system=system))
return plugins | [
"def",
"_parse_plugin_list",
"(",
"self",
",",
"output",
")",
":",
"ENCODED_COMMA",
"=",
"'%!(VAGRANT_COMMA)'",
"plugins",
"=",
"[",
"]",
"# initialize plugin values",
"name",
"=",
"None",
"version",
"=",
"None",
"system",
"=",
"False",
"for",
"timestamp",
",",
... | Remove Vagrant from the equation for unit testing. | [
"Remove",
"Vagrant",
"from",
"the",
"equation",
"for",
"unit",
"testing",
"."
] | 83b26f9337b1f2cb6314210923bbd189e7c9199e | https://github.com/todddeluca/python-vagrant/blob/83b26f9337b1f2cb6314210923bbd189e7c9199e/vagrant/__init__.py#L844-L877 | train | 39,217 |
todddeluca/python-vagrant | vagrant/__init__.py | Vagrant._stream_vagrant_command | def _stream_vagrant_command(self, args):
"""
Execute a vagrant command, returning a generator of the output lines.
Caller should consume the entire generator to avoid the hanging the
subprocess.
:param args: Arguments for the Vagrant command.
:return: generator that yields each line of the command stdout.
:rtype: generator iterator
"""
py3 = sys.version_info > (3, 0)
# Make subprocess command
command = self._make_vagrant_command(args)
with self.err_cm() as err_fh:
sp_args = dict(args=command, cwd=self.root, env=self.env,
stdout=subprocess.PIPE, stderr=err_fh, bufsize=1)
# Iterate over output lines.
# See http://stackoverflow.com/questions/2715847/python-read-streaming-input-from-subprocess-communicate#17698359
p = subprocess.Popen(**sp_args)
with p.stdout:
for line in iter(p.stdout.readline, b''):
yield compat.decode(line) # if PY3 decode bytestrings
p.wait()
# Raise CalledProcessError for consistency with _call_vagrant_command
if p.returncode != 0:
raise subprocess.CalledProcessError(p.returncode, command) | python | def _stream_vagrant_command(self, args):
"""
Execute a vagrant command, returning a generator of the output lines.
Caller should consume the entire generator to avoid the hanging the
subprocess.
:param args: Arguments for the Vagrant command.
:return: generator that yields each line of the command stdout.
:rtype: generator iterator
"""
py3 = sys.version_info > (3, 0)
# Make subprocess command
command = self._make_vagrant_command(args)
with self.err_cm() as err_fh:
sp_args = dict(args=command, cwd=self.root, env=self.env,
stdout=subprocess.PIPE, stderr=err_fh, bufsize=1)
# Iterate over output lines.
# See http://stackoverflow.com/questions/2715847/python-read-streaming-input-from-subprocess-communicate#17698359
p = subprocess.Popen(**sp_args)
with p.stdout:
for line in iter(p.stdout.readline, b''):
yield compat.decode(line) # if PY3 decode bytestrings
p.wait()
# Raise CalledProcessError for consistency with _call_vagrant_command
if p.returncode != 0:
raise subprocess.CalledProcessError(p.returncode, command) | [
"def",
"_stream_vagrant_command",
"(",
"self",
",",
"args",
")",
":",
"py3",
"=",
"sys",
".",
"version_info",
">",
"(",
"3",
",",
"0",
")",
"# Make subprocess command",
"command",
"=",
"self",
".",
"_make_vagrant_command",
"(",
"args",
")",
"with",
"self",
... | Execute a vagrant command, returning a generator of the output lines.
Caller should consume the entire generator to avoid the hanging the
subprocess.
:param args: Arguments for the Vagrant command.
:return: generator that yields each line of the command stdout.
:rtype: generator iterator | [
"Execute",
"a",
"vagrant",
"command",
"returning",
"a",
"generator",
"of",
"the",
"output",
"lines",
".",
"Caller",
"should",
"consume",
"the",
"entire",
"generator",
"to",
"avoid",
"the",
"hanging",
"the",
"subprocess",
"."
] | 83b26f9337b1f2cb6314210923bbd189e7c9199e | https://github.com/todddeluca/python-vagrant/blob/83b26f9337b1f2cb6314210923bbd189e7c9199e/vagrant/__init__.py#L978-L1005 | train | 39,218 |
todddeluca/python-vagrant | vagrant/__init__.py | SandboxVagrant.sandbox_status | def sandbox_status(self, vm_name=None):
'''
Returns the status of the sandbox mode.
Possible values are:
- on
- off
- unknown
- not installed
'''
vagrant_sandbox_output = self._run_sandbox_command(['status', vm_name])
return self._parse_vagrant_sandbox_status(vagrant_sandbox_output) | python | def sandbox_status(self, vm_name=None):
'''
Returns the status of the sandbox mode.
Possible values are:
- on
- off
- unknown
- not installed
'''
vagrant_sandbox_output = self._run_sandbox_command(['status', vm_name])
return self._parse_vagrant_sandbox_status(vagrant_sandbox_output) | [
"def",
"sandbox_status",
"(",
"self",
",",
"vm_name",
"=",
"None",
")",
":",
"vagrant_sandbox_output",
"=",
"self",
".",
"_run_sandbox_command",
"(",
"[",
"'status'",
",",
"vm_name",
"]",
")",
"return",
"self",
".",
"_parse_vagrant_sandbox_status",
"(",
"vagrant... | Returns the status of the sandbox mode.
Possible values are:
- on
- off
- unknown
- not installed | [
"Returns",
"the",
"status",
"of",
"the",
"sandbox",
"mode",
"."
] | 83b26f9337b1f2cb6314210923bbd189e7c9199e | https://github.com/todddeluca/python-vagrant/blob/83b26f9337b1f2cb6314210923bbd189e7c9199e/vagrant/__init__.py#L1043-L1054 | train | 39,219 |
todddeluca/python-vagrant | vagrant/__init__.py | SandboxVagrant._parse_vagrant_sandbox_status | def _parse_vagrant_sandbox_status(self, vagrant_output):
'''
Returns the status of the sandbox mode given output from
'vagrant sandbox status'.
'''
# typical output
# [default] - snapshot mode is off
# or
# [default] - machine not created
# if the box VM is down
tokens = [token.strip() for token in vagrant_output.split(' ')]
if tokens[0] == 'Usage:':
sahara_status = 'not installed'
elif "{} {}".format(tokens[-2], tokens[-1]) == 'not created':
sahara_status = 'unknown'
else:
sahara_status = tokens[-1]
return sahara_status | python | def _parse_vagrant_sandbox_status(self, vagrant_output):
'''
Returns the status of the sandbox mode given output from
'vagrant sandbox status'.
'''
# typical output
# [default] - snapshot mode is off
# or
# [default] - machine not created
# if the box VM is down
tokens = [token.strip() for token in vagrant_output.split(' ')]
if tokens[0] == 'Usage:':
sahara_status = 'not installed'
elif "{} {}".format(tokens[-2], tokens[-1]) == 'not created':
sahara_status = 'unknown'
else:
sahara_status = tokens[-1]
return sahara_status | [
"def",
"_parse_vagrant_sandbox_status",
"(",
"self",
",",
"vagrant_output",
")",
":",
"# typical output",
"# [default] - snapshot mode is off",
"# or",
"# [default] - machine not created",
"# if the box VM is down",
"tokens",
"=",
"[",
"token",
".",
"strip",
"(",
")",
"for"... | Returns the status of the sandbox mode given output from
'vagrant sandbox status'. | [
"Returns",
"the",
"status",
"of",
"the",
"sandbox",
"mode",
"given",
"output",
"from",
"vagrant",
"sandbox",
"status",
"."
] | 83b26f9337b1f2cb6314210923bbd189e7c9199e | https://github.com/todddeluca/python-vagrant/blob/83b26f9337b1f2cb6314210923bbd189e7c9199e/vagrant/__init__.py#L1056-L1073 | train | 39,220 |
garnaat/placebo | placebo/serializer.py | deserialize | def deserialize(obj):
"""Convert JSON dicts back into objects."""
# Be careful of shallow copy here
target = dict(obj)
class_name = None
if '__class__' in target:
class_name = target.pop('__class__')
if '__module__' in obj:
obj.pop('__module__')
# Use getattr(module, class_name) for custom types if needed
if class_name == 'datetime':
return datetime.datetime(tzinfo=utc, **target)
if class_name == 'StreamingBody':
return StringIO(target['body'])
# Return unrecognized structures as-is
return obj | python | def deserialize(obj):
"""Convert JSON dicts back into objects."""
# Be careful of shallow copy here
target = dict(obj)
class_name = None
if '__class__' in target:
class_name = target.pop('__class__')
if '__module__' in obj:
obj.pop('__module__')
# Use getattr(module, class_name) for custom types if needed
if class_name == 'datetime':
return datetime.datetime(tzinfo=utc, **target)
if class_name == 'StreamingBody':
return StringIO(target['body'])
# Return unrecognized structures as-is
return obj | [
"def",
"deserialize",
"(",
"obj",
")",
":",
"# Be careful of shallow copy here",
"target",
"=",
"dict",
"(",
"obj",
")",
"class_name",
"=",
"None",
"if",
"'__class__'",
"in",
"target",
":",
"class_name",
"=",
"target",
".",
"pop",
"(",
"'__class__'",
")",
"i... | Convert JSON dicts back into objects. | [
"Convert",
"JSON",
"dicts",
"back",
"into",
"objects",
"."
] | 1e8ab91b92fa7c5bb1fdbce2331f0c55455093d7 | https://github.com/garnaat/placebo/blob/1e8ab91b92fa7c5bb1fdbce2331f0c55455093d7/placebo/serializer.py#L68-L83 | train | 39,221 |
garnaat/placebo | placebo/serializer.py | serialize | def serialize(obj):
"""Convert objects into JSON structures."""
# Record class and module information for deserialization
result = {'__class__': obj.__class__.__name__}
try:
result['__module__'] = obj.__module__
except AttributeError:
pass
# Convert objects to dictionary representation based on type
if isinstance(obj, datetime.datetime):
result['year'] = obj.year
result['month'] = obj.month
result['day'] = obj.day
result['hour'] = obj.hour
result['minute'] = obj.minute
result['second'] = obj.second
result['microsecond'] = obj.microsecond
return result
if isinstance(obj, StreamingBody):
result['body'] = obj.read()
obj._raw_stream = StringIO(result['body'])
obj._amount_read = 0
return result
# Raise a TypeError if the object isn't recognized
raise TypeError("Type not serializable") | python | def serialize(obj):
"""Convert objects into JSON structures."""
# Record class and module information for deserialization
result = {'__class__': obj.__class__.__name__}
try:
result['__module__'] = obj.__module__
except AttributeError:
pass
# Convert objects to dictionary representation based on type
if isinstance(obj, datetime.datetime):
result['year'] = obj.year
result['month'] = obj.month
result['day'] = obj.day
result['hour'] = obj.hour
result['minute'] = obj.minute
result['second'] = obj.second
result['microsecond'] = obj.microsecond
return result
if isinstance(obj, StreamingBody):
result['body'] = obj.read()
obj._raw_stream = StringIO(result['body'])
obj._amount_read = 0
return result
# Raise a TypeError if the object isn't recognized
raise TypeError("Type not serializable") | [
"def",
"serialize",
"(",
"obj",
")",
":",
"# Record class and module information for deserialization",
"result",
"=",
"{",
"'__class__'",
":",
"obj",
".",
"__class__",
".",
"__name__",
"}",
"try",
":",
"result",
"[",
"'__module__'",
"]",
"=",
"obj",
".",
"__modu... | Convert objects into JSON structures. | [
"Convert",
"objects",
"into",
"JSON",
"structures",
"."
] | 1e8ab91b92fa7c5bb1fdbce2331f0c55455093d7 | https://github.com/garnaat/placebo/blob/1e8ab91b92fa7c5bb1fdbce2331f0c55455093d7/placebo/serializer.py#L86-L110 | train | 39,222 |
garnaat/placebo | placebo/serializer.py | _serialize_json | def _serialize_json(obj, fp):
""" Serialize ``obj`` as a JSON formatted stream to ``fp`` """
json.dump(obj, fp, indent=4, default=serialize) | python | def _serialize_json(obj, fp):
""" Serialize ``obj`` as a JSON formatted stream to ``fp`` """
json.dump(obj, fp, indent=4, default=serialize) | [
"def",
"_serialize_json",
"(",
"obj",
",",
"fp",
")",
":",
"json",
".",
"dump",
"(",
"obj",
",",
"fp",
",",
"indent",
"=",
"4",
",",
"default",
"=",
"serialize",
")"
] | Serialize ``obj`` as a JSON formatted stream to ``fp`` | [
"Serialize",
"obj",
"as",
"a",
"JSON",
"formatted",
"stream",
"to",
"fp"
] | 1e8ab91b92fa7c5bb1fdbce2331f0c55455093d7 | https://github.com/garnaat/placebo/blob/1e8ab91b92fa7c5bb1fdbce2331f0c55455093d7/placebo/serializer.py#L113-L115 | train | 39,223 |
garnaat/placebo | placebo/serializer.py | get_serializer | def get_serializer(serializer_format):
""" Get the serializer for a specific format """
if serializer_format == Format.JSON:
return _serialize_json
if serializer_format == Format.PICKLE:
return _serialize_pickle | python | def get_serializer(serializer_format):
""" Get the serializer for a specific format """
if serializer_format == Format.JSON:
return _serialize_json
if serializer_format == Format.PICKLE:
return _serialize_pickle | [
"def",
"get_serializer",
"(",
"serializer_format",
")",
":",
"if",
"serializer_format",
"==",
"Format",
".",
"JSON",
":",
"return",
"_serialize_json",
"if",
"serializer_format",
"==",
"Format",
".",
"PICKLE",
":",
"return",
"_serialize_pickle"
] | Get the serializer for a specific format | [
"Get",
"the",
"serializer",
"for",
"a",
"specific",
"format"
] | 1e8ab91b92fa7c5bb1fdbce2331f0c55455093d7 | https://github.com/garnaat/placebo/blob/1e8ab91b92fa7c5bb1fdbce2331f0c55455093d7/placebo/serializer.py#L133-L138 | train | 39,224 |
garnaat/placebo | placebo/serializer.py | get_deserializer | def get_deserializer(serializer_format):
""" Get the deserializer for a specific format """
if serializer_format == Format.JSON:
return _deserialize_json
if serializer_format == Format.PICKLE:
return _deserialize_pickle | python | def get_deserializer(serializer_format):
""" Get the deserializer for a specific format """
if serializer_format == Format.JSON:
return _deserialize_json
if serializer_format == Format.PICKLE:
return _deserialize_pickle | [
"def",
"get_deserializer",
"(",
"serializer_format",
")",
":",
"if",
"serializer_format",
"==",
"Format",
".",
"JSON",
":",
"return",
"_deserialize_json",
"if",
"serializer_format",
"==",
"Format",
".",
"PICKLE",
":",
"return",
"_deserialize_pickle"
] | Get the deserializer for a specific format | [
"Get",
"the",
"deserializer",
"for",
"a",
"specific",
"format"
] | 1e8ab91b92fa7c5bb1fdbce2331f0c55455093d7 | https://github.com/garnaat/placebo/blob/1e8ab91b92fa7c5bb1fdbce2331f0c55455093d7/placebo/serializer.py#L141-L146 | train | 39,225 |
garnaat/placebo | placebo/pill.py | Pill.get_next_file_path | def get_next_file_path(self, service, operation):
"""
Returns a tuple with the next file to read and the serializer
format used
"""
base_name = '{0}.{1}'.format(service, operation)
if self.prefix:
base_name = '{0}.{1}'.format(self.prefix, base_name)
LOG.debug('get_next_file_path: %s', base_name)
next_file = None
serializer_format = None
index = self._index.setdefault(base_name, 1)
while not next_file:
file_name = os.path.join(
self._data_path, base_name + '_{0}'.format(index))
next_file, serializer_format = self.find_file_format(file_name)
if next_file:
self._index[base_name] += 1
elif index != 1:
index = 1
self._index[base_name] = 1
else:
raise IOError('response file ({0}.[{1}]) not found'.format(
file_name, "|".join(Format.ALLOWED)))
return next_file, serializer_format | python | def get_next_file_path(self, service, operation):
"""
Returns a tuple with the next file to read and the serializer
format used
"""
base_name = '{0}.{1}'.format(service, operation)
if self.prefix:
base_name = '{0}.{1}'.format(self.prefix, base_name)
LOG.debug('get_next_file_path: %s', base_name)
next_file = None
serializer_format = None
index = self._index.setdefault(base_name, 1)
while not next_file:
file_name = os.path.join(
self._data_path, base_name + '_{0}'.format(index))
next_file, serializer_format = self.find_file_format(file_name)
if next_file:
self._index[base_name] += 1
elif index != 1:
index = 1
self._index[base_name] = 1
else:
raise IOError('response file ({0}.[{1}]) not found'.format(
file_name, "|".join(Format.ALLOWED)))
return next_file, serializer_format | [
"def",
"get_next_file_path",
"(",
"self",
",",
"service",
",",
"operation",
")",
":",
"base_name",
"=",
"'{0}.{1}'",
".",
"format",
"(",
"service",
",",
"operation",
")",
"if",
"self",
".",
"prefix",
":",
"base_name",
"=",
"'{0}.{1}'",
".",
"format",
"(",
... | Returns a tuple with the next file to read and the serializer
format used | [
"Returns",
"a",
"tuple",
"with",
"the",
"next",
"file",
"to",
"read",
"and",
"the",
"serializer",
"format",
"used"
] | 1e8ab91b92fa7c5bb1fdbce2331f0c55455093d7 | https://github.com/garnaat/placebo/blob/1e8ab91b92fa7c5bb1fdbce2331f0c55455093d7/placebo/pill.py#L233-L259 | train | 39,226 |
garnaat/placebo | placebo/pill.py | Pill._mock_request | def _mock_request(self, **kwargs):
"""
A mocked out make_request call that bypasses all network calls
and simply returns any mocked responses defined.
"""
model = kwargs.get('model')
service = model.service_model.endpoint_prefix
operation = model.name
LOG.debug('_make_request: %s.%s', service, operation)
return self.load_response(service, operation) | python | def _mock_request(self, **kwargs):
"""
A mocked out make_request call that bypasses all network calls
and simply returns any mocked responses defined.
"""
model = kwargs.get('model')
service = model.service_model.endpoint_prefix
operation = model.name
LOG.debug('_make_request: %s.%s', service, operation)
return self.load_response(service, operation) | [
"def",
"_mock_request",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"model",
"=",
"kwargs",
".",
"get",
"(",
"'model'",
")",
"service",
"=",
"model",
".",
"service_model",
".",
"endpoint_prefix",
"operation",
"=",
"model",
".",
"name",
"LOG",
".",
... | A mocked out make_request call that bypasses all network calls
and simply returns any mocked responses defined. | [
"A",
"mocked",
"out",
"make_request",
"call",
"that",
"bypasses",
"all",
"network",
"calls",
"and",
"simply",
"returns",
"any",
"mocked",
"responses",
"defined",
"."
] | 1e8ab91b92fa7c5bb1fdbce2331f0c55455093d7 | https://github.com/garnaat/placebo/blob/1e8ab91b92fa7c5bb1fdbce2331f0c55455093d7/placebo/pill.py#L290-L299 | train | 39,227 |
IdentityPython/pyop | src/pyop/provider.py | Provider.parse_authentication_request | def parse_authentication_request(self, request_body, http_headers=None):
# type: (str, Optional[Mapping[str, str]]) -> oic.oic.message.AuthorizationRequest
"""
Parses and verifies an authentication request.
:param request_body: urlencoded authentication request
:param http_headers: http headers
"""
auth_req = AuthorizationRequest().deserialize(request_body)
for validator in self.authentication_request_validators:
validator(auth_req)
logger.debug('parsed authentication_request: %s', auth_req)
return auth_req | python | def parse_authentication_request(self, request_body, http_headers=None):
# type: (str, Optional[Mapping[str, str]]) -> oic.oic.message.AuthorizationRequest
"""
Parses and verifies an authentication request.
:param request_body: urlencoded authentication request
:param http_headers: http headers
"""
auth_req = AuthorizationRequest().deserialize(request_body)
for validator in self.authentication_request_validators:
validator(auth_req)
logger.debug('parsed authentication_request: %s', auth_req)
return auth_req | [
"def",
"parse_authentication_request",
"(",
"self",
",",
"request_body",
",",
"http_headers",
"=",
"None",
")",
":",
"# type: (str, Optional[Mapping[str, str]]) -> oic.oic.message.AuthorizationRequest",
"auth_req",
"=",
"AuthorizationRequest",
"(",
")",
".",
"deserialize",
"(... | Parses and verifies an authentication request.
:param request_body: urlencoded authentication request
:param http_headers: http headers | [
"Parses",
"and",
"verifies",
"an",
"authentication",
"request",
"."
] | 7b1385964f079c39752fce5f2dbcf458b8a92e56 | https://github.com/IdentityPython/pyop/blob/7b1385964f079c39752fce5f2dbcf458b8a92e56/src/pyop/provider.py#L116-L131 | train | 39,228 |
IdentityPython/pyop | src/pyop/provider.py | Provider.authorize | def authorize(self, authentication_request, # type: oic.oic.message.AuthorizationRequest
user_id, # type: str
extra_id_token_claims=None
# type: Optional[Union[Mapping[str, Union[str, List[str]]], Callable[[str, str], Mapping[str, Union[str, List[str]]]]]
):
# type: (...) -> oic.oic.message.AuthorizationResponse
"""
Creates an Authentication Response for the specified authentication request and local identifier of the
authenticated user.
"""
custom_sub = self.userinfo[user_id].get('sub')
if custom_sub:
self.authz_state.subject_identifiers[user_id] = {'public': custom_sub}
sub = custom_sub
else:
sub = self._create_subject_identifier(user_id, authentication_request['client_id'],
authentication_request['redirect_uri'])
self._check_subject_identifier_matches_requested(authentication_request, sub)
response = AuthorizationResponse()
authz_code = None
if 'code' in authentication_request['response_type']:
authz_code = self.authz_state.create_authorization_code(authentication_request, sub)
response['code'] = authz_code
access_token_value = None
if 'token' in authentication_request['response_type']:
access_token = self.authz_state.create_access_token(authentication_request, sub)
access_token_value = access_token.value
self._add_access_token_to_response(response, access_token)
if 'id_token' in authentication_request['response_type']:
if extra_id_token_claims is None:
extra_id_token_claims = {}
elif callable(extra_id_token_claims):
extra_id_token_claims = extra_id_token_claims(user_id, authentication_request['client_id'])
requested_claims = self._get_requested_claims_in(authentication_request, 'id_token')
if len(authentication_request['response_type']) == 1:
# only id token is issued -> no way of doing userinfo request, so include all claims in ID Token,
# even those requested by the scope parameter
requested_claims.update(
scope2claims(
authentication_request['scope'], extra_scope_dict=self.extra_scopes
)
)
user_claims = self.userinfo.get_claims_for(user_id, requested_claims)
response['id_token'] = self._create_signed_id_token(authentication_request['client_id'], sub,
user_claims,
authentication_request.get('nonce'),
authz_code, access_token_value, extra_id_token_claims)
logger.debug('issued id_token=%s from requested_claims=%s userinfo=%s extra_claims=%s',
response['id_token'], requested_claims, user_claims, extra_id_token_claims)
if 'state' in authentication_request:
response['state'] = authentication_request['state']
return response | python | def authorize(self, authentication_request, # type: oic.oic.message.AuthorizationRequest
user_id, # type: str
extra_id_token_claims=None
# type: Optional[Union[Mapping[str, Union[str, List[str]]], Callable[[str, str], Mapping[str, Union[str, List[str]]]]]
):
# type: (...) -> oic.oic.message.AuthorizationResponse
"""
Creates an Authentication Response for the specified authentication request and local identifier of the
authenticated user.
"""
custom_sub = self.userinfo[user_id].get('sub')
if custom_sub:
self.authz_state.subject_identifiers[user_id] = {'public': custom_sub}
sub = custom_sub
else:
sub = self._create_subject_identifier(user_id, authentication_request['client_id'],
authentication_request['redirect_uri'])
self._check_subject_identifier_matches_requested(authentication_request, sub)
response = AuthorizationResponse()
authz_code = None
if 'code' in authentication_request['response_type']:
authz_code = self.authz_state.create_authorization_code(authentication_request, sub)
response['code'] = authz_code
access_token_value = None
if 'token' in authentication_request['response_type']:
access_token = self.authz_state.create_access_token(authentication_request, sub)
access_token_value = access_token.value
self._add_access_token_to_response(response, access_token)
if 'id_token' in authentication_request['response_type']:
if extra_id_token_claims is None:
extra_id_token_claims = {}
elif callable(extra_id_token_claims):
extra_id_token_claims = extra_id_token_claims(user_id, authentication_request['client_id'])
requested_claims = self._get_requested_claims_in(authentication_request, 'id_token')
if len(authentication_request['response_type']) == 1:
# only id token is issued -> no way of doing userinfo request, so include all claims in ID Token,
# even those requested by the scope parameter
requested_claims.update(
scope2claims(
authentication_request['scope'], extra_scope_dict=self.extra_scopes
)
)
user_claims = self.userinfo.get_claims_for(user_id, requested_claims)
response['id_token'] = self._create_signed_id_token(authentication_request['client_id'], sub,
user_claims,
authentication_request.get('nonce'),
authz_code, access_token_value, extra_id_token_claims)
logger.debug('issued id_token=%s from requested_claims=%s userinfo=%s extra_claims=%s',
response['id_token'], requested_claims, user_claims, extra_id_token_claims)
if 'state' in authentication_request:
response['state'] = authentication_request['state']
return response | [
"def",
"authorize",
"(",
"self",
",",
"authentication_request",
",",
"# type: oic.oic.message.AuthorizationRequest",
"user_id",
",",
"# type: str",
"extra_id_token_claims",
"=",
"None",
"# type: Optional[Union[Mapping[str, Union[str, List[str]]], Callable[[str, str], Mapping[str, Union[s... | Creates an Authentication Response for the specified authentication request and local identifier of the
authenticated user. | [
"Creates",
"an",
"Authentication",
"Response",
"for",
"the",
"specified",
"authentication",
"request",
"and",
"local",
"identifier",
"of",
"the",
"authenticated",
"user",
"."
] | 7b1385964f079c39752fce5f2dbcf458b8a92e56 | https://github.com/IdentityPython/pyop/blob/7b1385964f079c39752fce5f2dbcf458b8a92e56/src/pyop/provider.py#L133-L191 | train | 39,229 |
IdentityPython/pyop | src/pyop/provider.py | Provider._add_access_token_to_response | def _add_access_token_to_response(self, response, access_token):
# type: (oic.message.AccessTokenResponse, se_leg_op.access_token.AccessToken) -> None
"""
Adds the Access Token and the associated parameters to the Token Response.
"""
response['access_token'] = access_token.value
response['token_type'] = access_token.type
response['expires_in'] = access_token.expires_in | python | def _add_access_token_to_response(self, response, access_token):
# type: (oic.message.AccessTokenResponse, se_leg_op.access_token.AccessToken) -> None
"""
Adds the Access Token and the associated parameters to the Token Response.
"""
response['access_token'] = access_token.value
response['token_type'] = access_token.type
response['expires_in'] = access_token.expires_in | [
"def",
"_add_access_token_to_response",
"(",
"self",
",",
"response",
",",
"access_token",
")",
":",
"# type: (oic.message.AccessTokenResponse, se_leg_op.access_token.AccessToken) -> None",
"response",
"[",
"'access_token'",
"]",
"=",
"access_token",
".",
"value",
"response",
... | Adds the Access Token and the associated parameters to the Token Response. | [
"Adds",
"the",
"Access",
"Token",
"and",
"the",
"associated",
"parameters",
"to",
"the",
"Token",
"Response",
"."
] | 7b1385964f079c39752fce5f2dbcf458b8a92e56 | https://github.com/IdentityPython/pyop/blob/7b1385964f079c39752fce5f2dbcf458b8a92e56/src/pyop/provider.py#L193-L200 | train | 39,230 |
IdentityPython/pyop | src/pyop/storage.py | _format_mongodb_uri | def _format_mongodb_uri(parsed_uri):
"""
Painstakingly reconstruct a MongoDB URI parsed using pymongo.uri_parser.parse_uri.
:param parsed_uri: Result of pymongo.uri_parser.parse_uri
:type parsed_uri: dict
:return: New URI
:rtype: str | unicode
"""
user_pass = ''
if parsed_uri.get('username') and parsed_uri.get('password'):
user_pass = '{username!s}:{password!s}@'.format(**parsed_uri)
_nodes = []
for host, port in parsed_uri.get('nodelist'):
if ':' in host and not host.endswith(']'):
# IPv6 address without brackets
host = '[{!s}]'.format(host)
if port == 27017:
_nodes.append(host)
else:
_nodes.append('{!s}:{!s}'.format(host, port))
nodelist = ','.join(_nodes)
options = ''
if parsed_uri.get('options'):
_opt_list = []
for key, value in parsed_uri.get('options').items():
if isinstance(value, bool):
value = str(value).lower()
_opt_list.append('{!s}={!s}'.format(key, value))
options = '?' + '&'.join(_opt_list)
db_name = parsed_uri.get('database') or ''
res = "mongodb://{user_pass!s}{nodelist!s}/{db_name!s}{options!s}".format(
user_pass=user_pass,
nodelist=nodelist,
db_name=db_name,
# collection is ignored
options=options)
return res | python | def _format_mongodb_uri(parsed_uri):
"""
Painstakingly reconstruct a MongoDB URI parsed using pymongo.uri_parser.parse_uri.
:param parsed_uri: Result of pymongo.uri_parser.parse_uri
:type parsed_uri: dict
:return: New URI
:rtype: str | unicode
"""
user_pass = ''
if parsed_uri.get('username') and parsed_uri.get('password'):
user_pass = '{username!s}:{password!s}@'.format(**parsed_uri)
_nodes = []
for host, port in parsed_uri.get('nodelist'):
if ':' in host and not host.endswith(']'):
# IPv6 address without brackets
host = '[{!s}]'.format(host)
if port == 27017:
_nodes.append(host)
else:
_nodes.append('{!s}:{!s}'.format(host, port))
nodelist = ','.join(_nodes)
options = ''
if parsed_uri.get('options'):
_opt_list = []
for key, value in parsed_uri.get('options').items():
if isinstance(value, bool):
value = str(value).lower()
_opt_list.append('{!s}={!s}'.format(key, value))
options = '?' + '&'.join(_opt_list)
db_name = parsed_uri.get('database') or ''
res = "mongodb://{user_pass!s}{nodelist!s}/{db_name!s}{options!s}".format(
user_pass=user_pass,
nodelist=nodelist,
db_name=db_name,
# collection is ignored
options=options)
return res | [
"def",
"_format_mongodb_uri",
"(",
"parsed_uri",
")",
":",
"user_pass",
"=",
"''",
"if",
"parsed_uri",
".",
"get",
"(",
"'username'",
")",
"and",
"parsed_uri",
".",
"get",
"(",
"'password'",
")",
":",
"user_pass",
"=",
"'{username!s}:{password!s}@'",
".",
"for... | Painstakingly reconstruct a MongoDB URI parsed using pymongo.uri_parser.parse_uri.
:param parsed_uri: Result of pymongo.uri_parser.parse_uri
:type parsed_uri: dict
:return: New URI
:rtype: str | unicode | [
"Painstakingly",
"reconstruct",
"a",
"MongoDB",
"URI",
"parsed",
"using",
"pymongo",
".",
"uri_parser",
".",
"parse_uri",
"."
] | 7b1385964f079c39752fce5f2dbcf458b8a92e56 | https://github.com/IdentityPython/pyop/blob/7b1385964f079c39752fce5f2dbcf458b8a92e56/src/pyop/storage.py#L173-L215 | train | 39,231 |
IdentityPython/pyop | src/pyop/storage.py | MongoDB.sanitized_uri | def sanitized_uri(self):
"""
Return the database URI we're using in a format sensible for logging etc.
:return: db_uri
"""
if self._sanitized_uri is None:
_parsed = copy.copy(self._parsed_uri)
if 'username' in _parsed:
_parsed['password'] = 'secret'
_parsed['nodelist'] = [_parsed['nodelist'][0]]
self._sanitized_uri = _format_mongodb_uri(_parsed)
return self._sanitized_uri | python | def sanitized_uri(self):
"""
Return the database URI we're using in a format sensible for logging etc.
:return: db_uri
"""
if self._sanitized_uri is None:
_parsed = copy.copy(self._parsed_uri)
if 'username' in _parsed:
_parsed['password'] = 'secret'
_parsed['nodelist'] = [_parsed['nodelist'][0]]
self._sanitized_uri = _format_mongodb_uri(_parsed)
return self._sanitized_uri | [
"def",
"sanitized_uri",
"(",
"self",
")",
":",
"if",
"self",
".",
"_sanitized_uri",
"is",
"None",
":",
"_parsed",
"=",
"copy",
".",
"copy",
"(",
"self",
".",
"_parsed_uri",
")",
"if",
"'username'",
"in",
"_parsed",
":",
"_parsed",
"[",
"'password'",
"]",... | Return the database URI we're using in a format sensible for logging etc.
:return: db_uri | [
"Return",
"the",
"database",
"URI",
"we",
"re",
"using",
"in",
"a",
"format",
"sensible",
"for",
"logging",
"etc",
"."
] | 7b1385964f079c39752fce5f2dbcf458b8a92e56 | https://github.com/IdentityPython/pyop/blob/7b1385964f079c39752fce5f2dbcf458b8a92e56/src/pyop/storage.py#L102-L114 | train | 39,232 |
IdentityPython/pyop | src/pyop/storage.py | MongoDB.get_database | def get_database(self, database_name=None, username=None, password=None):
"""
Get a pymongo database handle, after authenticating.
Authenticates using the username/password in the DB URI given to
__init__() unless username/password is supplied as arguments.
:param database_name: (optional) Name of database
:param username: (optional) Username to login with
:param password: (optional) Password to login with
:return: Pymongo database object
"""
if database_name is None:
database_name = self._database_name
if database_name is None:
raise ValueError('No database_name supplied, and no default provided to __init__')
db = self._connection[database_name]
if username and password:
db.authenticate(username, password)
elif self._parsed_uri.get("username", None):
if 'authSource' in self._options and self._options['authSource'] is not None:
db.authenticate(
self._parsed_uri.get("username", None),
self._parsed_uri.get("password", None),
source=self._options['authSource']
)
else:
db.authenticate(
self._parsed_uri.get("username", None),
self._parsed_uri.get("password", None)
)
return db | python | def get_database(self, database_name=None, username=None, password=None):
"""
Get a pymongo database handle, after authenticating.
Authenticates using the username/password in the DB URI given to
__init__() unless username/password is supplied as arguments.
:param database_name: (optional) Name of database
:param username: (optional) Username to login with
:param password: (optional) Password to login with
:return: Pymongo database object
"""
if database_name is None:
database_name = self._database_name
if database_name is None:
raise ValueError('No database_name supplied, and no default provided to __init__')
db = self._connection[database_name]
if username and password:
db.authenticate(username, password)
elif self._parsed_uri.get("username", None):
if 'authSource' in self._options and self._options['authSource'] is not None:
db.authenticate(
self._parsed_uri.get("username", None),
self._parsed_uri.get("password", None),
source=self._options['authSource']
)
else:
db.authenticate(
self._parsed_uri.get("username", None),
self._parsed_uri.get("password", None)
)
return db | [
"def",
"get_database",
"(",
"self",
",",
"database_name",
"=",
"None",
",",
"username",
"=",
"None",
",",
"password",
"=",
"None",
")",
":",
"if",
"database_name",
"is",
"None",
":",
"database_name",
"=",
"self",
".",
"_database_name",
"if",
"database_name",... | Get a pymongo database handle, after authenticating.
Authenticates using the username/password in the DB URI given to
__init__() unless username/password is supplied as arguments.
:param database_name: (optional) Name of database
:param username: (optional) Username to login with
:param password: (optional) Password to login with
:return: Pymongo database object | [
"Get",
"a",
"pymongo",
"database",
"handle",
"after",
"authenticating",
"."
] | 7b1385964f079c39752fce5f2dbcf458b8a92e56 | https://github.com/IdentityPython/pyop/blob/7b1385964f079c39752fce5f2dbcf458b8a92e56/src/pyop/storage.py#L123-L154 | train | 39,233 |
IdentityPython/pyop | src/pyop/storage.py | MongoDB.get_collection | def get_collection(self, collection, database_name=None, username=None, password=None):
"""
Get a pymongo collection handle.
:param collection: Name of collection
:param database_name: (optional) Name of database
:param username: (optional) Username to login with
:param password: (optional) Password to login with
:return: Pymongo collection object
"""
_db = self.get_database(database_name, username, password)
return _db[collection] | python | def get_collection(self, collection, database_name=None, username=None, password=None):
"""
Get a pymongo collection handle.
:param collection: Name of collection
:param database_name: (optional) Name of database
:param username: (optional) Username to login with
:param password: (optional) Password to login with
:return: Pymongo collection object
"""
_db = self.get_database(database_name, username, password)
return _db[collection] | [
"def",
"get_collection",
"(",
"self",
",",
"collection",
",",
"database_name",
"=",
"None",
",",
"username",
"=",
"None",
",",
"password",
"=",
"None",
")",
":",
"_db",
"=",
"self",
".",
"get_database",
"(",
"database_name",
",",
"username",
",",
"password... | Get a pymongo collection handle.
:param collection: Name of collection
:param database_name: (optional) Name of database
:param username: (optional) Username to login with
:param password: (optional) Password to login with
:return: Pymongo collection object | [
"Get",
"a",
"pymongo",
"collection",
"handle",
"."
] | 7b1385964f079c39752fce5f2dbcf458b8a92e56 | https://github.com/IdentityPython/pyop/blob/7b1385964f079c39752fce5f2dbcf458b8a92e56/src/pyop/storage.py#L156-L167 | train | 39,234 |
slinderman/pypolyagamma | pypolyagamma/binary_trees.py | balanced_binary_tree | def balanced_binary_tree(n_leaves):
"""
Create a balanced binary tree
"""
def _balanced_subtree(leaves):
if len(leaves) == 1:
return leaves[0]
elif len(leaves) == 2:
return (leaves[0], leaves[1])
else:
split = len(leaves) // 2
return (_balanced_subtree(leaves[:split]),
_balanced_subtree(leaves[split:]))
return _balanced_subtree(np.arange(n_leaves)) | python | def balanced_binary_tree(n_leaves):
"""
Create a balanced binary tree
"""
def _balanced_subtree(leaves):
if len(leaves) == 1:
return leaves[0]
elif len(leaves) == 2:
return (leaves[0], leaves[1])
else:
split = len(leaves) // 2
return (_balanced_subtree(leaves[:split]),
_balanced_subtree(leaves[split:]))
return _balanced_subtree(np.arange(n_leaves)) | [
"def",
"balanced_binary_tree",
"(",
"n_leaves",
")",
":",
"def",
"_balanced_subtree",
"(",
"leaves",
")",
":",
"if",
"len",
"(",
"leaves",
")",
"==",
"1",
":",
"return",
"leaves",
"[",
"0",
"]",
"elif",
"len",
"(",
"leaves",
")",
"==",
"2",
":",
"ret... | Create a balanced binary tree | [
"Create",
"a",
"balanced",
"binary",
"tree"
] | abdc0c53e5114092998f51bf66f1900bc567f0bd | https://github.com/slinderman/pypolyagamma/blob/abdc0c53e5114092998f51bf66f1900bc567f0bd/pypolyagamma/binary_trees.py#L32-L46 | train | 39,235 |
slinderman/pypolyagamma | pypolyagamma/binary_trees.py | decision_list | def decision_list(n_leaves):
"""
Create a decision list
"""
def _list(leaves):
if len(leaves) == 2:
return (leaves[0], leaves[1])
else:
return (leaves[0], _list(leaves[1:]))
return _list(np.arange(n_leaves)) | python | def decision_list(n_leaves):
"""
Create a decision list
"""
def _list(leaves):
if len(leaves) == 2:
return (leaves[0], leaves[1])
else:
return (leaves[0], _list(leaves[1:]))
return _list(np.arange(n_leaves)) | [
"def",
"decision_list",
"(",
"n_leaves",
")",
":",
"def",
"_list",
"(",
"leaves",
")",
":",
"if",
"len",
"(",
"leaves",
")",
"==",
"2",
":",
"return",
"(",
"leaves",
"[",
"0",
"]",
",",
"leaves",
"[",
"1",
"]",
")",
"else",
":",
"return",
"(",
... | Create a decision list | [
"Create",
"a",
"decision",
"list"
] | abdc0c53e5114092998f51bf66f1900bc567f0bd | https://github.com/slinderman/pypolyagamma/blob/abdc0c53e5114092998f51bf66f1900bc567f0bd/pypolyagamma/binary_trees.py#L48-L57 | train | 39,236 |
slinderman/pypolyagamma | pypolyagamma/binary_trees.py | random_tree | def random_tree(n_leaves):
"""
Randomly partition the nodes
"""
def _random_subtree(leaves):
if len(leaves) == 1:
return leaves[0]
elif len(leaves) == 2:
return (leaves[0], leaves[1])
else:
split = npr.randint(1, len(leaves)-1)
return (_random_subtree(leaves[:split]),
_random_subtree(leaves[split:]))
return _random_subtree(np.arange(n_leaves)) | python | def random_tree(n_leaves):
"""
Randomly partition the nodes
"""
def _random_subtree(leaves):
if len(leaves) == 1:
return leaves[0]
elif len(leaves) == 2:
return (leaves[0], leaves[1])
else:
split = npr.randint(1, len(leaves)-1)
return (_random_subtree(leaves[:split]),
_random_subtree(leaves[split:]))
return _random_subtree(np.arange(n_leaves)) | [
"def",
"random_tree",
"(",
"n_leaves",
")",
":",
"def",
"_random_subtree",
"(",
"leaves",
")",
":",
"if",
"len",
"(",
"leaves",
")",
"==",
"1",
":",
"return",
"leaves",
"[",
"0",
"]",
"elif",
"len",
"(",
"leaves",
")",
"==",
"2",
":",
"return",
"("... | Randomly partition the nodes | [
"Randomly",
"partition",
"the",
"nodes"
] | abdc0c53e5114092998f51bf66f1900bc567f0bd | https://github.com/slinderman/pypolyagamma/blob/abdc0c53e5114092998f51bf66f1900bc567f0bd/pypolyagamma/binary_trees.py#L60-L74 | train | 39,237 |
slinderman/pypolyagamma | pypolyagamma/binary_trees.py | leaves | def leaves(tree):
"""
Return the leaves in this subtree.
"""
lvs = []
def _leaves(node):
if np.isscalar(node):
lvs.append(node)
elif isinstance(node, tuple) and len(node) == 2:
_leaves(node[0])
_leaves(node[1])
else:
raise Exception("Not a tree!")
_leaves(tree)
return lvs | python | def leaves(tree):
"""
Return the leaves in this subtree.
"""
lvs = []
def _leaves(node):
if np.isscalar(node):
lvs.append(node)
elif isinstance(node, tuple) and len(node) == 2:
_leaves(node[0])
_leaves(node[1])
else:
raise Exception("Not a tree!")
_leaves(tree)
return lvs | [
"def",
"leaves",
"(",
"tree",
")",
":",
"lvs",
"=",
"[",
"]",
"def",
"_leaves",
"(",
"node",
")",
":",
"if",
"np",
".",
"isscalar",
"(",
"node",
")",
":",
"lvs",
".",
"append",
"(",
"node",
")",
"elif",
"isinstance",
"(",
"node",
",",
"tuple",
... | Return the leaves in this subtree. | [
"Return",
"the",
"leaves",
"in",
"this",
"subtree",
"."
] | abdc0c53e5114092998f51bf66f1900bc567f0bd | https://github.com/slinderman/pypolyagamma/blob/abdc0c53e5114092998f51bf66f1900bc567f0bd/pypolyagamma/binary_trees.py#L77-L92 | train | 39,238 |
slinderman/pypolyagamma | pypolyagamma/binary_trees.py | choices | def choices(tree):
"""
Get the 'address' of each leaf node in terms of internal
node choices
"""
n = len(leaves(tree))
addr = np.nan * np.ones((n, n-1))
def _addresses(node, index, choices):
# index is the index of the current internal node
# choices is a list of (indice, 0/1) choices made
if np.isscalar(node):
for i, choice in choices:
addr[node, i] = choice
return index
elif isinstance(node, tuple) and len(node) == 2:
newindex = _addresses(node[0], index+1, choices + [(index, 0)])
newindex = _addresses(node[1], newindex, choices + [(index, 1)])
return newindex
else:
raise Exception("Not a tree!")
_addresses(tree, 0, [])
return addr | python | def choices(tree):
"""
Get the 'address' of each leaf node in terms of internal
node choices
"""
n = len(leaves(tree))
addr = np.nan * np.ones((n, n-1))
def _addresses(node, index, choices):
# index is the index of the current internal node
# choices is a list of (indice, 0/1) choices made
if np.isscalar(node):
for i, choice in choices:
addr[node, i] = choice
return index
elif isinstance(node, tuple) and len(node) == 2:
newindex = _addresses(node[0], index+1, choices + [(index, 0)])
newindex = _addresses(node[1], newindex, choices + [(index, 1)])
return newindex
else:
raise Exception("Not a tree!")
_addresses(tree, 0, [])
return addr | [
"def",
"choices",
"(",
"tree",
")",
":",
"n",
"=",
"len",
"(",
"leaves",
"(",
"tree",
")",
")",
"addr",
"=",
"np",
".",
"nan",
"*",
"np",
".",
"ones",
"(",
"(",
"n",
",",
"n",
"-",
"1",
")",
")",
"def",
"_addresses",
"(",
"node",
",",
"inde... | Get the 'address' of each leaf node in terms of internal
node choices | [
"Get",
"the",
"address",
"of",
"each",
"leaf",
"node",
"in",
"terms",
"of",
"internal",
"node",
"choices"
] | abdc0c53e5114092998f51bf66f1900bc567f0bd | https://github.com/slinderman/pypolyagamma/blob/abdc0c53e5114092998f51bf66f1900bc567f0bd/pypolyagamma/binary_trees.py#L95-L119 | train | 39,239 |
slinderman/pypolyagamma | pypolyagamma/distributions.py | BernoulliRegression.max_likelihood | def max_likelihood(self, data, weights=None, stats=None, lmbda=0.1):
"""
As an alternative to MCMC with Polya-gamma augmentation,
we also implement maximum likelihood learning via gradient
descent with autograd. This follows the pybasicbayes
convention.
:param data: list of tuples, (x,y), for each dataset.
:param weights: Not used in this implementation.
:param stats: Not used in this implementation.
"""
import autograd.numpy as anp
from autograd import value_and_grad, hessian_vector_product
from scipy.optimize import minimize
assert weights is None
assert stats is None
if not isinstance(data, list):
assert isinstance(data, tuple) and len(data) == 2
data = [data]
# Define a helper function for the log of the logistic fn
def loglogistic(psi):
return psi - anp.log(1+anp.exp(psi))
# optimize each row of A and b
for n in range(self.D_out):
# Define an objective function for the n-th row of hstack((A, b))
# This is the negative log likelihood of the n-th column of data.
def nll(abn):
an, bn = abn[:-1], abn[-1]
T = 0
ll = 0
for (x, y) in data:
T += x.shape[0]
yn = y[:, n]
psi = anp.dot(x, an) + bn
ll += anp.sum(yn * loglogistic(psi))
ll += anp.sum((1 - yn) * loglogistic(-1. * psi))
# Include a penalty on the weights
ll -= lmbda * T * anp.sum(an**2)
ll -= lmbda * T * bn**2
return -1 * ll / T
abn0 = np.concatenate((self.A[n], self.b[n]))
res = minimize(value_and_grad(nll), abn0,
tol=1e-3,
method="Newton-CG",
jac=True,
hessp=hessian_vector_product(nll))
assert res.success
self.A[n] = res.x[:-1]
self.b[n] = res.x[-1] | python | def max_likelihood(self, data, weights=None, stats=None, lmbda=0.1):
"""
As an alternative to MCMC with Polya-gamma augmentation,
we also implement maximum likelihood learning via gradient
descent with autograd. This follows the pybasicbayes
convention.
:param data: list of tuples, (x,y), for each dataset.
:param weights: Not used in this implementation.
:param stats: Not used in this implementation.
"""
import autograd.numpy as anp
from autograd import value_and_grad, hessian_vector_product
from scipy.optimize import minimize
assert weights is None
assert stats is None
if not isinstance(data, list):
assert isinstance(data, tuple) and len(data) == 2
data = [data]
# Define a helper function for the log of the logistic fn
def loglogistic(psi):
return psi - anp.log(1+anp.exp(psi))
# optimize each row of A and b
for n in range(self.D_out):
# Define an objective function for the n-th row of hstack((A, b))
# This is the negative log likelihood of the n-th column of data.
def nll(abn):
an, bn = abn[:-1], abn[-1]
T = 0
ll = 0
for (x, y) in data:
T += x.shape[0]
yn = y[:, n]
psi = anp.dot(x, an) + bn
ll += anp.sum(yn * loglogistic(psi))
ll += anp.sum((1 - yn) * loglogistic(-1. * psi))
# Include a penalty on the weights
ll -= lmbda * T * anp.sum(an**2)
ll -= lmbda * T * bn**2
return -1 * ll / T
abn0 = np.concatenate((self.A[n], self.b[n]))
res = minimize(value_and_grad(nll), abn0,
tol=1e-3,
method="Newton-CG",
jac=True,
hessp=hessian_vector_product(nll))
assert res.success
self.A[n] = res.x[:-1]
self.b[n] = res.x[-1] | [
"def",
"max_likelihood",
"(",
"self",
",",
"data",
",",
"weights",
"=",
"None",
",",
"stats",
"=",
"None",
",",
"lmbda",
"=",
"0.1",
")",
":",
"import",
"autograd",
".",
"numpy",
"as",
"anp",
"from",
"autograd",
"import",
"value_and_grad",
",",
"hessian_... | As an alternative to MCMC with Polya-gamma augmentation,
we also implement maximum likelihood learning via gradient
descent with autograd. This follows the pybasicbayes
convention.
:param data: list of tuples, (x,y), for each dataset.
:param weights: Not used in this implementation.
:param stats: Not used in this implementation. | [
"As",
"an",
"alternative",
"to",
"MCMC",
"with",
"Polya",
"-",
"gamma",
"augmentation",
"we",
"also",
"implement",
"maximum",
"likelihood",
"learning",
"via",
"gradient",
"descent",
"with",
"autograd",
".",
"This",
"follows",
"the",
"pybasicbayes",
"convention",
... | abdc0c53e5114092998f51bf66f1900bc567f0bd | https://github.com/slinderman/pypolyagamma/blob/abdc0c53e5114092998f51bf66f1900bc567f0bd/pypolyagamma/distributions.py#L222-L278 | train | 39,240 |
slinderman/pypolyagamma | pypolyagamma/distributions.py | TreeStructuredMultinomialRegression.resample | def resample(self, data, mask=None, omega=None):
"""
Multinomial regression is somewhat special. We have to compute the
kappa functions for the entire dataset, not just for one column of
the data at a time.
"""
if not isinstance(data, list):
assert isinstance(data, tuple) and len(data) == 2, \
"datas must be an (x,y) tuple or a list of such tuples"
data = [data]
if mask is None:
mask = [np.ones(y.shape, dtype=bool) for x, y in data]
# Resample auxiliary variables if they are not given
if omega is None:
omega = self._resample_auxiliary_variables(data)
# Make copies of parameters (for sample collection in calling methods)
self.A = self.A.copy()
self.b = self.b.copy()
D = self.D_in
for n in range(self.D_out):
# Resample C_{n,:} given z, omega[:,n], and kappa[:,n]
prior_Sigma = np.zeros((D + 1, D + 1))
prior_Sigma[:D, :D] = self.sigmasq_A[n]
prior_Sigma[D, D] = self.sigmasq_b[n]
prior_J = np.linalg.inv(prior_Sigma)
prior_h = prior_J.dot(np.concatenate((self.mu_A[n], [self.mu_b[n]])))
lkhd_h = np.zeros(D + 1)
lkhd_J = np.zeros((D + 1, D + 1))
for d, m, o in zip(data, mask, omega):
if isinstance(d, tuple):
x, y = d
else:
x, y = d[:, :D], d[:, D:]
augx = np.hstack((x, np.ones((x.shape[0], 1))))
J = o * m
h = self.kappa_func(y) * m
lkhd_J += (augx * J[:, n][:, None]).T.dot(augx)
lkhd_h += h[:, n].T.dot(augx)
post_h = prior_h + lkhd_h
post_J = prior_J + lkhd_J
joint_sample = sample_gaussian(J=post_J, h=post_h)
self.A[n, :] = joint_sample[:D]
self.b[n] = joint_sample[D] | python | def resample(self, data, mask=None, omega=None):
"""
Multinomial regression is somewhat special. We have to compute the
kappa functions for the entire dataset, not just for one column of
the data at a time.
"""
if not isinstance(data, list):
assert isinstance(data, tuple) and len(data) == 2, \
"datas must be an (x,y) tuple or a list of such tuples"
data = [data]
if mask is None:
mask = [np.ones(y.shape, dtype=bool) for x, y in data]
# Resample auxiliary variables if they are not given
if omega is None:
omega = self._resample_auxiliary_variables(data)
# Make copies of parameters (for sample collection in calling methods)
self.A = self.A.copy()
self.b = self.b.copy()
D = self.D_in
for n in range(self.D_out):
# Resample C_{n,:} given z, omega[:,n], and kappa[:,n]
prior_Sigma = np.zeros((D + 1, D + 1))
prior_Sigma[:D, :D] = self.sigmasq_A[n]
prior_Sigma[D, D] = self.sigmasq_b[n]
prior_J = np.linalg.inv(prior_Sigma)
prior_h = prior_J.dot(np.concatenate((self.mu_A[n], [self.mu_b[n]])))
lkhd_h = np.zeros(D + 1)
lkhd_J = np.zeros((D + 1, D + 1))
for d, m, o in zip(data, mask, omega):
if isinstance(d, tuple):
x, y = d
else:
x, y = d[:, :D], d[:, D:]
augx = np.hstack((x, np.ones((x.shape[0], 1))))
J = o * m
h = self.kappa_func(y) * m
lkhd_J += (augx * J[:, n][:, None]).T.dot(augx)
lkhd_h += h[:, n].T.dot(augx)
post_h = prior_h + lkhd_h
post_J = prior_J + lkhd_J
joint_sample = sample_gaussian(J=post_J, h=post_h)
self.A[n, :] = joint_sample[:D]
self.b[n] = joint_sample[D] | [
"def",
"resample",
"(",
"self",
",",
"data",
",",
"mask",
"=",
"None",
",",
"omega",
"=",
"None",
")",
":",
"if",
"not",
"isinstance",
"(",
"data",
",",
"list",
")",
":",
"assert",
"isinstance",
"(",
"data",
",",
"tuple",
")",
"and",
"len",
"(",
... | Multinomial regression is somewhat special. We have to compute the
kappa functions for the entire dataset, not just for one column of
the data at a time. | [
"Multinomial",
"regression",
"is",
"somewhat",
"special",
".",
"We",
"have",
"to",
"compute",
"the",
"kappa",
"functions",
"for",
"the",
"entire",
"dataset",
"not",
"just",
"for",
"one",
"column",
"of",
"the",
"data",
"at",
"a",
"time",
"."
] | abdc0c53e5114092998f51bf66f1900bc567f0bd | https://github.com/slinderman/pypolyagamma/blob/abdc0c53e5114092998f51bf66f1900bc567f0bd/pypolyagamma/distributions.py#L436-L488 | train | 39,241 |
IdentityPython/pyop | src/pyop/authz_state.py | AuthorizationState.create_authorization_code | def create_authorization_code(self, authorization_request, subject_identifier, scope=None):
# type: (oic.oic.message.AuthorizationRequest, str, Optional[List[str]]) -> str
"""
Creates an authorization code bound to the authorization request and the authenticated user identified
by the subject identifier.
"""
if not self._is_valid_subject_identifier(subject_identifier):
raise InvalidSubjectIdentifier('{} unknown'.format(subject_identifier))
scope = ' '.join(scope or authorization_request['scope'])
logger.debug('creating authz code for scope=%s', scope)
authorization_code = rand_str()
authz_info = {
'used': False,
'exp': int(time.time()) + self.authorization_code_lifetime,
'sub': subject_identifier,
'granted_scope': scope,
self.KEY_AUTHORIZATION_REQUEST: authorization_request.to_dict()
}
self.authorization_codes[authorization_code] = authz_info
logger.debug('new authz_code=%s to client_id=%s for sub=%s valid_until=%s', authorization_code,
authorization_request['client_id'], subject_identifier, authz_info['exp'])
return authorization_code | python | def create_authorization_code(self, authorization_request, subject_identifier, scope=None):
# type: (oic.oic.message.AuthorizationRequest, str, Optional[List[str]]) -> str
"""
Creates an authorization code bound to the authorization request and the authenticated user identified
by the subject identifier.
"""
if not self._is_valid_subject_identifier(subject_identifier):
raise InvalidSubjectIdentifier('{} unknown'.format(subject_identifier))
scope = ' '.join(scope or authorization_request['scope'])
logger.debug('creating authz code for scope=%s', scope)
authorization_code = rand_str()
authz_info = {
'used': False,
'exp': int(time.time()) + self.authorization_code_lifetime,
'sub': subject_identifier,
'granted_scope': scope,
self.KEY_AUTHORIZATION_REQUEST: authorization_request.to_dict()
}
self.authorization_codes[authorization_code] = authz_info
logger.debug('new authz_code=%s to client_id=%s for sub=%s valid_until=%s', authorization_code,
authorization_request['client_id'], subject_identifier, authz_info['exp'])
return authorization_code | [
"def",
"create_authorization_code",
"(",
"self",
",",
"authorization_request",
",",
"subject_identifier",
",",
"scope",
"=",
"None",
")",
":",
"# type: (oic.oic.message.AuthorizationRequest, str, Optional[List[str]]) -> str",
"if",
"not",
"self",
".",
"_is_valid_subject_identif... | Creates an authorization code bound to the authorization request and the authenticated user identified
by the subject identifier. | [
"Creates",
"an",
"authorization",
"code",
"bound",
"to",
"the",
"authorization",
"request",
"and",
"the",
"authenticated",
"user",
"identified",
"by",
"the",
"subject",
"identifier",
"."
] | 7b1385964f079c39752fce5f2dbcf458b8a92e56 | https://github.com/IdentityPython/pyop/blob/7b1385964f079c39752fce5f2dbcf458b8a92e56/src/pyop/authz_state.py#L82-L106 | train | 39,242 |
IdentityPython/pyop | src/pyop/authz_state.py | AuthorizationState.create_access_token | def create_access_token(self, authorization_request, subject_identifier, scope=None):
# type: (oic.oic.message.AuthorizationRequest, str, Optional[List[str]]) -> se_leg_op.access_token.AccessToken
"""
Creates an access token bound to the authentication request and the authenticated user identified by the
subject identifier.
"""
if not self._is_valid_subject_identifier(subject_identifier):
raise InvalidSubjectIdentifier('{} unknown'.format(subject_identifier))
scope = scope or authorization_request['scope']
return self._create_access_token(subject_identifier, authorization_request.to_dict(), ' '.join(scope)) | python | def create_access_token(self, authorization_request, subject_identifier, scope=None):
# type: (oic.oic.message.AuthorizationRequest, str, Optional[List[str]]) -> se_leg_op.access_token.AccessToken
"""
Creates an access token bound to the authentication request and the authenticated user identified by the
subject identifier.
"""
if not self._is_valid_subject_identifier(subject_identifier):
raise InvalidSubjectIdentifier('{} unknown'.format(subject_identifier))
scope = scope or authorization_request['scope']
return self._create_access_token(subject_identifier, authorization_request.to_dict(), ' '.join(scope)) | [
"def",
"create_access_token",
"(",
"self",
",",
"authorization_request",
",",
"subject_identifier",
",",
"scope",
"=",
"None",
")",
":",
"# type: (oic.oic.message.AuthorizationRequest, str, Optional[List[str]]) -> se_leg_op.access_token.AccessToken",
"if",
"not",
"self",
".",
"... | Creates an access token bound to the authentication request and the authenticated user identified by the
subject identifier. | [
"Creates",
"an",
"access",
"token",
"bound",
"to",
"the",
"authentication",
"request",
"and",
"the",
"authenticated",
"user",
"identified",
"by",
"the",
"subject",
"identifier",
"."
] | 7b1385964f079c39752fce5f2dbcf458b8a92e56 | https://github.com/IdentityPython/pyop/blob/7b1385964f079c39752fce5f2dbcf458b8a92e56/src/pyop/authz_state.py#L108-L119 | train | 39,243 |
IdentityPython/pyop | src/pyop/authz_state.py | AuthorizationState._create_access_token | def _create_access_token(self, subject_identifier, auth_req, granted_scope, current_scope=None):
# type: (str, Mapping[str, Union[str, List[str]]], str, Optional[str]) -> se_leg_op.access_token.AccessToken
"""
Creates an access token bound to the subject identifier, client id and requested scope.
"""
access_token = AccessToken(rand_str(), self.access_token_lifetime)
scope = current_scope or granted_scope
logger.debug('creating access token for scope=%s', scope)
authz_info = {
'iat': int(time.time()),
'exp': int(time.time()) + self.access_token_lifetime,
'sub': subject_identifier,
'client_id': auth_req['client_id'],
'aud': [auth_req['client_id']],
'scope': scope,
'granted_scope': granted_scope,
'token_type': access_token.BEARER_TOKEN_TYPE,
self.KEY_AUTHORIZATION_REQUEST: auth_req
}
self.access_tokens[access_token.value] = authz_info
logger.debug('new access_token=%s to client_id=%s for sub=%s valid_until=%s',
access_token.value, auth_req['client_id'], subject_identifier, authz_info['exp'])
return access_token | python | def _create_access_token(self, subject_identifier, auth_req, granted_scope, current_scope=None):
# type: (str, Mapping[str, Union[str, List[str]]], str, Optional[str]) -> se_leg_op.access_token.AccessToken
"""
Creates an access token bound to the subject identifier, client id and requested scope.
"""
access_token = AccessToken(rand_str(), self.access_token_lifetime)
scope = current_scope or granted_scope
logger.debug('creating access token for scope=%s', scope)
authz_info = {
'iat': int(time.time()),
'exp': int(time.time()) + self.access_token_lifetime,
'sub': subject_identifier,
'client_id': auth_req['client_id'],
'aud': [auth_req['client_id']],
'scope': scope,
'granted_scope': granted_scope,
'token_type': access_token.BEARER_TOKEN_TYPE,
self.KEY_AUTHORIZATION_REQUEST: auth_req
}
self.access_tokens[access_token.value] = authz_info
logger.debug('new access_token=%s to client_id=%s for sub=%s valid_until=%s',
access_token.value, auth_req['client_id'], subject_identifier, authz_info['exp'])
return access_token | [
"def",
"_create_access_token",
"(",
"self",
",",
"subject_identifier",
",",
"auth_req",
",",
"granted_scope",
",",
"current_scope",
"=",
"None",
")",
":",
"# type: (str, Mapping[str, Union[str, List[str]]], str, Optional[str]) -> se_leg_op.access_token.AccessToken",
"access_token",... | Creates an access token bound to the subject identifier, client id and requested scope. | [
"Creates",
"an",
"access",
"token",
"bound",
"to",
"the",
"subject",
"identifier",
"client",
"id",
"and",
"requested",
"scope",
"."
] | 7b1385964f079c39752fce5f2dbcf458b8a92e56 | https://github.com/IdentityPython/pyop/blob/7b1385964f079c39752fce5f2dbcf458b8a92e56/src/pyop/authz_state.py#L121-L146 | train | 39,244 |
IdentityPython/pyop | src/pyop/authz_state.py | AuthorizationState.exchange_code_for_token | def exchange_code_for_token(self, authorization_code):
# type: (str) -> se_leg_op.access_token.AccessToken
"""
Exchanges an authorization code for an access token.
"""
if authorization_code not in self.authorization_codes:
raise InvalidAuthorizationCode('{} unknown'.format(authorization_code))
authz_info = self.authorization_codes[authorization_code]
if authz_info['used']:
logger.debug('detected already used authz_code=%s', authorization_code)
raise InvalidAuthorizationCode('{} has already been used'.format(authorization_code))
elif authz_info['exp'] < int(time.time()):
logger.debug('detected expired authz_code=%s, now=%s > exp=%s ',
authorization_code, int(time.time()), authz_info['exp'])
raise InvalidAuthorizationCode('{} has expired'.format(authorization_code))
authz_info['used'] = True
access_token = self._create_access_token(authz_info['sub'], authz_info[self.KEY_AUTHORIZATION_REQUEST],
authz_info['granted_scope'])
logger.debug('authz_code=%s exchanged to access_token=%s', authorization_code, access_token.value)
return access_token | python | def exchange_code_for_token(self, authorization_code):
# type: (str) -> se_leg_op.access_token.AccessToken
"""
Exchanges an authorization code for an access token.
"""
if authorization_code not in self.authorization_codes:
raise InvalidAuthorizationCode('{} unknown'.format(authorization_code))
authz_info = self.authorization_codes[authorization_code]
if authz_info['used']:
logger.debug('detected already used authz_code=%s', authorization_code)
raise InvalidAuthorizationCode('{} has already been used'.format(authorization_code))
elif authz_info['exp'] < int(time.time()):
logger.debug('detected expired authz_code=%s, now=%s > exp=%s ',
authorization_code, int(time.time()), authz_info['exp'])
raise InvalidAuthorizationCode('{} has expired'.format(authorization_code))
authz_info['used'] = True
access_token = self._create_access_token(authz_info['sub'], authz_info[self.KEY_AUTHORIZATION_REQUEST],
authz_info['granted_scope'])
logger.debug('authz_code=%s exchanged to access_token=%s', authorization_code, access_token.value)
return access_token | [
"def",
"exchange_code_for_token",
"(",
"self",
",",
"authorization_code",
")",
":",
"# type: (str) -> se_leg_op.access_token.AccessToken",
"if",
"authorization_code",
"not",
"in",
"self",
".",
"authorization_codes",
":",
"raise",
"InvalidAuthorizationCode",
"(",
"'{} unknown'... | Exchanges an authorization code for an access token. | [
"Exchanges",
"an",
"authorization",
"code",
"for",
"an",
"access",
"token",
"."
] | 7b1385964f079c39752fce5f2dbcf458b8a92e56 | https://github.com/IdentityPython/pyop/blob/7b1385964f079c39752fce5f2dbcf458b8a92e56/src/pyop/authz_state.py#L148-L171 | train | 39,245 |
IdentityPython/pyop | src/pyop/authz_state.py | AuthorizationState.create_refresh_token | def create_refresh_token(self, access_token_value):
# type: (str) -> str
"""
Creates an refresh token bound to the specified access token.
"""
if access_token_value not in self.access_tokens:
raise InvalidAccessToken('{} unknown'.format(access_token_value))
if not self.refresh_token_lifetime:
logger.debug('no refresh token issued for for access_token=%s', access_token_value)
return None
refresh_token = rand_str()
authz_info = {'access_token': access_token_value, 'exp': int(time.time()) + self.refresh_token_lifetime}
self.refresh_tokens[refresh_token] = authz_info
logger.debug('issued refresh_token=%s expiring=%d for access_token=%s', refresh_token, authz_info['exp'],
access_token_value)
return refresh_token | python | def create_refresh_token(self, access_token_value):
# type: (str) -> str
"""
Creates an refresh token bound to the specified access token.
"""
if access_token_value not in self.access_tokens:
raise InvalidAccessToken('{} unknown'.format(access_token_value))
if not self.refresh_token_lifetime:
logger.debug('no refresh token issued for for access_token=%s', access_token_value)
return None
refresh_token = rand_str()
authz_info = {'access_token': access_token_value, 'exp': int(time.time()) + self.refresh_token_lifetime}
self.refresh_tokens[refresh_token] = authz_info
logger.debug('issued refresh_token=%s expiring=%d for access_token=%s', refresh_token, authz_info['exp'],
access_token_value)
return refresh_token | [
"def",
"create_refresh_token",
"(",
"self",
",",
"access_token_value",
")",
":",
"# type: (str) -> str",
"if",
"access_token_value",
"not",
"in",
"self",
".",
"access_tokens",
":",
"raise",
"InvalidAccessToken",
"(",
"'{} unknown'",
".",
"format",
"(",
"access_token_v... | Creates an refresh token bound to the specified access token. | [
"Creates",
"an",
"refresh",
"token",
"bound",
"to",
"the",
"specified",
"access",
"token",
"."
] | 7b1385964f079c39752fce5f2dbcf458b8a92e56 | https://github.com/IdentityPython/pyop/blob/7b1385964f079c39752fce5f2dbcf458b8a92e56/src/pyop/authz_state.py#L190-L208 | train | 39,246 |
slinderman/pypolyagamma | pypolyagamma/utils.py | _psi_n | def _psi_n(x, n, b):
"""
Compute the n-th term in the infinite sum of
the Jacobi density.
"""
return 2**(b-1) / gamma(b) * (-1)**n * \
np.exp(gammaln(n+b) -
gammaln(n+1) +
np.log(2*n+b) -
0.5 * np.log(2*np.pi*x**3) -
(2*n+b)**2 / (8.*x)) | python | def _psi_n(x, n, b):
"""
Compute the n-th term in the infinite sum of
the Jacobi density.
"""
return 2**(b-1) / gamma(b) * (-1)**n * \
np.exp(gammaln(n+b) -
gammaln(n+1) +
np.log(2*n+b) -
0.5 * np.log(2*np.pi*x**3) -
(2*n+b)**2 / (8.*x)) | [
"def",
"_psi_n",
"(",
"x",
",",
"n",
",",
"b",
")",
":",
"return",
"2",
"**",
"(",
"b",
"-",
"1",
")",
"/",
"gamma",
"(",
"b",
")",
"*",
"(",
"-",
"1",
")",
"**",
"n",
"*",
"np",
".",
"exp",
"(",
"gammaln",
"(",
"n",
"+",
"b",
")",
"-... | Compute the n-th term in the infinite sum of
the Jacobi density. | [
"Compute",
"the",
"n",
"-",
"th",
"term",
"in",
"the",
"infinite",
"sum",
"of",
"the",
"Jacobi",
"density",
"."
] | abdc0c53e5114092998f51bf66f1900bc567f0bd | https://github.com/slinderman/pypolyagamma/blob/abdc0c53e5114092998f51bf66f1900bc567f0bd/pypolyagamma/utils.py#L9-L19 | train | 39,247 |
slinderman/pypolyagamma | pypolyagamma/utils.py | _tilt | def _tilt(omega, b, psi):
"""
Compute the tilt of the PG density for value omega
and tilt psi.
:param omega: point at which to evaluate the density
:param psi: tilt parameter
"""
return np.cosh(psi/2.0)**b * np.exp(-psi**2/2.0 * omega) | python | def _tilt(omega, b, psi):
"""
Compute the tilt of the PG density for value omega
and tilt psi.
:param omega: point at which to evaluate the density
:param psi: tilt parameter
"""
return np.cosh(psi/2.0)**b * np.exp(-psi**2/2.0 * omega) | [
"def",
"_tilt",
"(",
"omega",
",",
"b",
",",
"psi",
")",
":",
"return",
"np",
".",
"cosh",
"(",
"psi",
"/",
"2.0",
")",
"**",
"b",
"*",
"np",
".",
"exp",
"(",
"-",
"psi",
"**",
"2",
"/",
"2.0",
"*",
"omega",
")"
] | Compute the tilt of the PG density for value omega
and tilt psi.
:param omega: point at which to evaluate the density
:param psi: tilt parameter | [
"Compute",
"the",
"tilt",
"of",
"the",
"PG",
"density",
"for",
"value",
"omega",
"and",
"tilt",
"psi",
"."
] | abdc0c53e5114092998f51bf66f1900bc567f0bd | https://github.com/slinderman/pypolyagamma/blob/abdc0c53e5114092998f51bf66f1900bc567f0bd/pypolyagamma/utils.py#L21-L29 | train | 39,248 |
aloetesting/aloe_django | aloe_django/management/commands/harvest.py | Command.run_from_argv | def run_from_argv(self, argv):
"""
Set the default Gherkin test runner for its options to be parsed.
"""
self.test_runner = test_runner_class
super(Command, self).run_from_argv(argv) | python | def run_from_argv(self, argv):
"""
Set the default Gherkin test runner for its options to be parsed.
"""
self.test_runner = test_runner_class
super(Command, self).run_from_argv(argv) | [
"def",
"run_from_argv",
"(",
"self",
",",
"argv",
")",
":",
"self",
".",
"test_runner",
"=",
"test_runner_class",
"super",
"(",
"Command",
",",
"self",
")",
".",
"run_from_argv",
"(",
"argv",
")"
] | Set the default Gherkin test runner for its options to be parsed. | [
"Set",
"the",
"default",
"Gherkin",
"test",
"runner",
"for",
"its",
"options",
"to",
"be",
"parsed",
"."
] | 672eac97c97644bfe334e70696a6dc5ddf4ced02 | https://github.com/aloetesting/aloe_django/blob/672eac97c97644bfe334e70696a6dc5ddf4ced02/aloe_django/management/commands/harvest.py#L25-L31 | train | 39,249 |
aloetesting/aloe_django | aloe_django/management/commands/harvest.py | Command.handle | def handle(self, *test_labels, **options):
"""
Set the default Gherkin test runner.
"""
if not options.get('testrunner', None):
options['testrunner'] = test_runner_class
return super(Command, self).handle(*test_labels, **options) | python | def handle(self, *test_labels, **options):
"""
Set the default Gherkin test runner.
"""
if not options.get('testrunner', None):
options['testrunner'] = test_runner_class
return super(Command, self).handle(*test_labels, **options) | [
"def",
"handle",
"(",
"self",
",",
"*",
"test_labels",
",",
"*",
"*",
"options",
")",
":",
"if",
"not",
"options",
".",
"get",
"(",
"'testrunner'",
",",
"None",
")",
":",
"options",
"[",
"'testrunner'",
"]",
"=",
"test_runner_class",
"return",
"super",
... | Set the default Gherkin test runner. | [
"Set",
"the",
"default",
"Gherkin",
"test",
"runner",
"."
] | 672eac97c97644bfe334e70696a6dc5ddf4ced02 | https://github.com/aloetesting/aloe_django/blob/672eac97c97644bfe334e70696a6dc5ddf4ced02/aloe_django/management/commands/harvest.py#L33-L40 | train | 39,250 |
aloetesting/aloe_django | aloe_django/__init__.py | django_url | def django_url(step, url=None):
"""
The URL for a page from the test server.
:param step: A Gherkin step
:param url: If specified, the relative URL to append.
"""
base_url = step.test.live_server_url
if url:
return urljoin(base_url, url)
else:
return base_url | python | def django_url(step, url=None):
"""
The URL for a page from the test server.
:param step: A Gherkin step
:param url: If specified, the relative URL to append.
"""
base_url = step.test.live_server_url
if url:
return urljoin(base_url, url)
else:
return base_url | [
"def",
"django_url",
"(",
"step",
",",
"url",
"=",
"None",
")",
":",
"base_url",
"=",
"step",
".",
"test",
".",
"live_server_url",
"if",
"url",
":",
"return",
"urljoin",
"(",
"base_url",
",",
"url",
")",
"else",
":",
"return",
"base_url"
] | The URL for a page from the test server.
:param step: A Gherkin step
:param url: If specified, the relative URL to append. | [
"The",
"URL",
"for",
"a",
"page",
"from",
"the",
"test",
"server",
"."
] | 672eac97c97644bfe334e70696a6dc5ddf4ced02 | https://github.com/aloetesting/aloe_django/blob/672eac97c97644bfe334e70696a6dc5ddf4ced02/aloe_django/__init__.py#L38-L51 | train | 39,251 |
divio/aldryn-apphooks-config | aldryn_apphooks_config/managers/base.py | QuerySetMixin.namespace | def namespace(self, namespace, to=None):
"""
Filter by namespace. Try to guess which field to use in lookup.
Accept 'to' argument if you need to specify.
"""
fields = get_apphook_field_names(self.model)
if not fields:
raise ValueError(
ugettext(
'Can\'t find any relation to an ApphookConfig model in {0}'
).format(self.model.__name__)
)
if to and to not in fields:
raise ValueError(
ugettext(
'Can\'t find relation to ApphookConfig model named '
'"{0}" in "{1}"'
).format(to, self.model.__name__)
)
if len(fields) > 1 and to not in fields:
raise ValueError(
ugettext(
'"{0}" has {1} relations to an ApphookConfig model.'
' Please, specify which one to use in argument "to".'
' Choices are: {2}'
).format(
self.model.__name__, len(fields), ', '.join(fields)
)
)
else:
if not to:
to = fields[0]
lookup = '{0}__namespace'.format(to)
kwargs = {lookup: namespace}
return self.filter(**kwargs) | python | def namespace(self, namespace, to=None):
"""
Filter by namespace. Try to guess which field to use in lookup.
Accept 'to' argument if you need to specify.
"""
fields = get_apphook_field_names(self.model)
if not fields:
raise ValueError(
ugettext(
'Can\'t find any relation to an ApphookConfig model in {0}'
).format(self.model.__name__)
)
if to and to not in fields:
raise ValueError(
ugettext(
'Can\'t find relation to ApphookConfig model named '
'"{0}" in "{1}"'
).format(to, self.model.__name__)
)
if len(fields) > 1 and to not in fields:
raise ValueError(
ugettext(
'"{0}" has {1} relations to an ApphookConfig model.'
' Please, specify which one to use in argument "to".'
' Choices are: {2}'
).format(
self.model.__name__, len(fields), ', '.join(fields)
)
)
else:
if not to:
to = fields[0]
lookup = '{0}__namespace'.format(to)
kwargs = {lookup: namespace}
return self.filter(**kwargs) | [
"def",
"namespace",
"(",
"self",
",",
"namespace",
",",
"to",
"=",
"None",
")",
":",
"fields",
"=",
"get_apphook_field_names",
"(",
"self",
".",
"model",
")",
"if",
"not",
"fields",
":",
"raise",
"ValueError",
"(",
"ugettext",
"(",
"'Can\\'t find any relatio... | Filter by namespace. Try to guess which field to use in lookup.
Accept 'to' argument if you need to specify. | [
"Filter",
"by",
"namespace",
".",
"Try",
"to",
"guess",
"which",
"field",
"to",
"use",
"in",
"lookup",
".",
"Accept",
"to",
"argument",
"if",
"you",
"need",
"to",
"specify",
"."
] | 5b8dfc7516982a8746fc08cf919c6ab116335d62 | https://github.com/divio/aldryn-apphooks-config/blob/5b8dfc7516982a8746fc08cf919c6ab116335d62/aldryn_apphooks_config/managers/base.py#L13-L48 | train | 39,252 |
divio/aldryn-apphooks-config | aldryn_apphooks_config/admin.py | ModelAppHookConfig._app_config_select | def _app_config_select(self, request, obj):
"""
Return the select value for apphook configs
:param request: request object
:param obj: current object
:return: False if no preselected value is available (more than one or no apphook
config is present), apphook config instance if exactly one apphook
config is defined or apphook config defined in the request or in the current
object, False otherwise
"""
if not obj and not request.GET.get(self.app_config_attribute, False):
config_model = get_apphook_model(self.model, self.app_config_attribute)
if config_model.objects.count() == 1:
return config_model.objects.first()
return None
elif obj and getattr(obj, self.app_config_attribute, False):
return getattr(obj, self.app_config_attribute)
elif request.GET.get(self.app_config_attribute, False):
config_model = get_apphook_model(self.model, self.app_config_attribute)
return config_model.objects.get(
pk=int(request.GET.get(self.app_config_attribute, False))
)
return False | python | def _app_config_select(self, request, obj):
"""
Return the select value for apphook configs
:param request: request object
:param obj: current object
:return: False if no preselected value is available (more than one or no apphook
config is present), apphook config instance if exactly one apphook
config is defined or apphook config defined in the request or in the current
object, False otherwise
"""
if not obj and not request.GET.get(self.app_config_attribute, False):
config_model = get_apphook_model(self.model, self.app_config_attribute)
if config_model.objects.count() == 1:
return config_model.objects.first()
return None
elif obj and getattr(obj, self.app_config_attribute, False):
return getattr(obj, self.app_config_attribute)
elif request.GET.get(self.app_config_attribute, False):
config_model = get_apphook_model(self.model, self.app_config_attribute)
return config_model.objects.get(
pk=int(request.GET.get(self.app_config_attribute, False))
)
return False | [
"def",
"_app_config_select",
"(",
"self",
",",
"request",
",",
"obj",
")",
":",
"if",
"not",
"obj",
"and",
"not",
"request",
".",
"GET",
".",
"get",
"(",
"self",
".",
"app_config_attribute",
",",
"False",
")",
":",
"config_model",
"=",
"get_apphook_model",... | Return the select value for apphook configs
:param request: request object
:param obj: current object
:return: False if no preselected value is available (more than one or no apphook
config is present), apphook config instance if exactly one apphook
config is defined or apphook config defined in the request or in the current
object, False otherwise | [
"Return",
"the",
"select",
"value",
"for",
"apphook",
"configs"
] | 5b8dfc7516982a8746fc08cf919c6ab116335d62 | https://github.com/divio/aldryn-apphooks-config/blob/5b8dfc7516982a8746fc08cf919c6ab116335d62/aldryn_apphooks_config/admin.py#L49-L72 | train | 39,253 |
divio/aldryn-apphooks-config | aldryn_apphooks_config/admin.py | ModelAppHookConfig._set_config_defaults | def _set_config_defaults(self, request, form, obj=None):
"""
Cycle through app_config_values and sets the form value according to the
options in the current apphook config.
self.app_config_values is a dictionary containing config options as keys, form fields as
values::
app_config_values = {
'apphook_config': 'form_field',
...
}
:param request: request object
:param form: model form for the current model
:param obj: current object
:return: form with defaults set
"""
for config_option, field in self.app_config_values.items():
if field in form.base_fields:
form.base_fields[field].initial = self.get_config_data(request, obj, config_option)
return form | python | def _set_config_defaults(self, request, form, obj=None):
"""
Cycle through app_config_values and sets the form value according to the
options in the current apphook config.
self.app_config_values is a dictionary containing config options as keys, form fields as
values::
app_config_values = {
'apphook_config': 'form_field',
...
}
:param request: request object
:param form: model form for the current model
:param obj: current object
:return: form with defaults set
"""
for config_option, field in self.app_config_values.items():
if field in form.base_fields:
form.base_fields[field].initial = self.get_config_data(request, obj, config_option)
return form | [
"def",
"_set_config_defaults",
"(",
"self",
",",
"request",
",",
"form",
",",
"obj",
"=",
"None",
")",
":",
"for",
"config_option",
",",
"field",
"in",
"self",
".",
"app_config_values",
".",
"items",
"(",
")",
":",
"if",
"field",
"in",
"form",
".",
"ba... | Cycle through app_config_values and sets the form value according to the
options in the current apphook config.
self.app_config_values is a dictionary containing config options as keys, form fields as
values::
app_config_values = {
'apphook_config': 'form_field',
...
}
:param request: request object
:param form: model form for the current model
:param obj: current object
:return: form with defaults set | [
"Cycle",
"through",
"app_config_values",
"and",
"sets",
"the",
"form",
"value",
"according",
"to",
"the",
"options",
"in",
"the",
"current",
"apphook",
"config",
"."
] | 5b8dfc7516982a8746fc08cf919c6ab116335d62 | https://github.com/divio/aldryn-apphooks-config/blob/5b8dfc7516982a8746fc08cf919c6ab116335d62/aldryn_apphooks_config/admin.py#L74-L95 | train | 39,254 |
divio/aldryn-apphooks-config | aldryn_apphooks_config/admin.py | ModelAppHookConfig.get_config_data | def get_config_data(self, request, obj, name):
"""
Method that retrieves a configuration option for a specific AppHookConfig instance
:param request: the request object
:param obj: the model instance
:param name: name of the config option as defined in the config form
:return value: config value or None if no app config is found
"""
return_value = None
config = None
if obj:
try:
config = getattr(obj, self.app_config_attribute, False)
except ObjectDoesNotExist: # pragma: no cover
pass
if not config and self.app_config_attribute in request.GET:
config_model = get_apphook_model(self.model, self.app_config_attribute)
try:
config = config_model.objects.get(pk=request.GET[self.app_config_attribute])
except config_model.DoesNotExist: # pragma: no cover
pass
if config:
return_value = getattr(config, name)
return return_value | python | def get_config_data(self, request, obj, name):
"""
Method that retrieves a configuration option for a specific AppHookConfig instance
:param request: the request object
:param obj: the model instance
:param name: name of the config option as defined in the config form
:return value: config value or None if no app config is found
"""
return_value = None
config = None
if obj:
try:
config = getattr(obj, self.app_config_attribute, False)
except ObjectDoesNotExist: # pragma: no cover
pass
if not config and self.app_config_attribute in request.GET:
config_model = get_apphook_model(self.model, self.app_config_attribute)
try:
config = config_model.objects.get(pk=request.GET[self.app_config_attribute])
except config_model.DoesNotExist: # pragma: no cover
pass
if config:
return_value = getattr(config, name)
return return_value | [
"def",
"get_config_data",
"(",
"self",
",",
"request",
",",
"obj",
",",
"name",
")",
":",
"return_value",
"=",
"None",
"config",
"=",
"None",
"if",
"obj",
":",
"try",
":",
"config",
"=",
"getattr",
"(",
"obj",
",",
"self",
".",
"app_config_attribute",
... | Method that retrieves a configuration option for a specific AppHookConfig instance
:param request: the request object
:param obj: the model instance
:param name: name of the config option as defined in the config form
:return value: config value or None if no app config is found | [
"Method",
"that",
"retrieves",
"a",
"configuration",
"option",
"for",
"a",
"specific",
"AppHookConfig",
"instance"
] | 5b8dfc7516982a8746fc08cf919c6ab116335d62 | https://github.com/divio/aldryn-apphooks-config/blob/5b8dfc7516982a8746fc08cf919c6ab116335d62/aldryn_apphooks_config/admin.py#L113-L138 | train | 39,255 |
divio/aldryn-apphooks-config | aldryn_apphooks_config/admin.py | ModelAppHookConfig.get_form | def get_form(self, request, obj=None, **kwargs):
"""
Provides a flexible way to get the right form according to the context
For the add view it checks whether the app_config is set; if not, a special form
to select the namespace is shown, which is reloaded after namespace selection.
If only one namespace exists, the current is selected and the normal form
is used.
"""
form = super(ModelAppHookConfig, self).get_form(request, obj, **kwargs)
if self.app_config_attribute not in form.base_fields:
return form
app_config_default = self._app_config_select(request, obj)
if app_config_default:
form.base_fields[self.app_config_attribute].initial = app_config_default
get = copy.copy(request.GET)
get[self.app_config_attribute] = app_config_default.pk
request.GET = get
elif app_config_default is None and request.method == 'GET':
class InitialForm(form):
class Meta(form.Meta):
fields = (self.app_config_attribute,)
form = InitialForm
form = self._set_config_defaults(request, form, obj)
return form | python | def get_form(self, request, obj=None, **kwargs):
"""
Provides a flexible way to get the right form according to the context
For the add view it checks whether the app_config is set; if not, a special form
to select the namespace is shown, which is reloaded after namespace selection.
If only one namespace exists, the current is selected and the normal form
is used.
"""
form = super(ModelAppHookConfig, self).get_form(request, obj, **kwargs)
if self.app_config_attribute not in form.base_fields:
return form
app_config_default = self._app_config_select(request, obj)
if app_config_default:
form.base_fields[self.app_config_attribute].initial = app_config_default
get = copy.copy(request.GET)
get[self.app_config_attribute] = app_config_default.pk
request.GET = get
elif app_config_default is None and request.method == 'GET':
class InitialForm(form):
class Meta(form.Meta):
fields = (self.app_config_attribute,)
form = InitialForm
form = self._set_config_defaults(request, form, obj)
return form | [
"def",
"get_form",
"(",
"self",
",",
"request",
",",
"obj",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"form",
"=",
"super",
"(",
"ModelAppHookConfig",
",",
"self",
")",
".",
"get_form",
"(",
"request",
",",
"obj",
",",
"*",
"*",
"kwargs",
")"... | Provides a flexible way to get the right form according to the context
For the add view it checks whether the app_config is set; if not, a special form
to select the namespace is shown, which is reloaded after namespace selection.
If only one namespace exists, the current is selected and the normal form
is used. | [
"Provides",
"a",
"flexible",
"way",
"to",
"get",
"the",
"right",
"form",
"according",
"to",
"the",
"context"
] | 5b8dfc7516982a8746fc08cf919c6ab116335d62 | https://github.com/divio/aldryn-apphooks-config/blob/5b8dfc7516982a8746fc08cf919c6ab116335d62/aldryn_apphooks_config/admin.py#L140-L164 | train | 39,256 |
aloetesting/aloe_django | aloe_django/steps/models.py | _models_generator | def _models_generator():
"""
Build a hash of model verbose names to models
"""
for app in apps.get_app_configs():
for model in app.get_models():
yield (str(model._meta.verbose_name).lower(), model)
yield (str(model._meta.verbose_name_plural).lower(), model) | python | def _models_generator():
"""
Build a hash of model verbose names to models
"""
for app in apps.get_app_configs():
for model in app.get_models():
yield (str(model._meta.verbose_name).lower(), model)
yield (str(model._meta.verbose_name_plural).lower(), model) | [
"def",
"_models_generator",
"(",
")",
":",
"for",
"app",
"in",
"apps",
".",
"get_app_configs",
"(",
")",
":",
"for",
"model",
"in",
"app",
".",
"get_models",
"(",
")",
":",
"yield",
"(",
"str",
"(",
"model",
".",
"_meta",
".",
"verbose_name",
")",
".... | Build a hash of model verbose names to models | [
"Build",
"a",
"hash",
"of",
"model",
"verbose",
"names",
"to",
"models"
] | 672eac97c97644bfe334e70696a6dc5ddf4ced02 | https://github.com/aloetesting/aloe_django/blob/672eac97c97644bfe334e70696a6dc5ddf4ced02/aloe_django/steps/models.py#L29-L37 | train | 39,257 |
aloetesting/aloe_django | aloe_django/steps/models.py | get_model | def get_model(name):
"""
Convert a model's verbose name to the model class. This allows us to
use the models verbose name in steps.
"""
model = MODELS.get(name.lower(), None)
assert model, "Could not locate model by name '%s'" % name
return model | python | def get_model(name):
"""
Convert a model's verbose name to the model class. This allows us to
use the models verbose name in steps.
"""
model = MODELS.get(name.lower(), None)
assert model, "Could not locate model by name '%s'" % name
return model | [
"def",
"get_model",
"(",
"name",
")",
":",
"model",
"=",
"MODELS",
".",
"get",
"(",
"name",
".",
"lower",
"(",
")",
",",
"None",
")",
"assert",
"model",
",",
"\"Could not locate model by name '%s'\"",
"%",
"name",
"return",
"model"
] | Convert a model's verbose name to the model class. This allows us to
use the models verbose name in steps. | [
"Convert",
"a",
"model",
"s",
"verbose",
"name",
"to",
"the",
"model",
"class",
".",
"This",
"allows",
"us",
"to",
"use",
"the",
"models",
"verbose",
"name",
"in",
"steps",
"."
] | 672eac97c97644bfe334e70696a6dc5ddf4ced02 | https://github.com/aloetesting/aloe_django/blob/672eac97c97644bfe334e70696a6dc5ddf4ced02/aloe_django/steps/models.py#L166-L176 | train | 39,258 |
aloetesting/aloe_django | aloe_django/steps/models.py | reset_sequence | def reset_sequence(model):
"""
Reset the ID sequence for a model.
"""
sql = connection.ops.sequence_reset_sql(no_style(), [model])
for cmd in sql:
connection.cursor().execute(cmd) | python | def reset_sequence(model):
"""
Reset the ID sequence for a model.
"""
sql = connection.ops.sequence_reset_sql(no_style(), [model])
for cmd in sql:
connection.cursor().execute(cmd) | [
"def",
"reset_sequence",
"(",
"model",
")",
":",
"sql",
"=",
"connection",
".",
"ops",
".",
"sequence_reset_sql",
"(",
"no_style",
"(",
")",
",",
"[",
"model",
"]",
")",
"for",
"cmd",
"in",
"sql",
":",
"connection",
".",
"cursor",
"(",
")",
".",
"exe... | Reset the ID sequence for a model. | [
"Reset",
"the",
"ID",
"sequence",
"for",
"a",
"model",
"."
] | 672eac97c97644bfe334e70696a6dc5ddf4ced02 | https://github.com/aloetesting/aloe_django/blob/672eac97c97644bfe334e70696a6dc5ddf4ced02/aloe_django/steps/models.py#L179-L185 | train | 39,259 |
aloetesting/aloe_django | aloe_django/steps/models.py | _dump_model | def _dump_model(model, attrs=None):
"""
Dump the model fields for debugging.
"""
fields = []
for field in model._meta.fields:
fields.append((field.name, str(getattr(model, field.name))))
if attrs is not None:
for attr in attrs:
fields.append((attr, str(getattr(model, attr))))
for field in model._meta.many_to_many:
vals = getattr(model, field.name)
fields.append((field.name, '{val} ({count})'.format(
val=', '.join(map(str, vals.all())),
count=vals.count(),
)))
print(', '.join(
'{0}={1}'.format(field, value)
for field, value in fields
)) | python | def _dump_model(model, attrs=None):
"""
Dump the model fields for debugging.
"""
fields = []
for field in model._meta.fields:
fields.append((field.name, str(getattr(model, field.name))))
if attrs is not None:
for attr in attrs:
fields.append((attr, str(getattr(model, attr))))
for field in model._meta.many_to_many:
vals = getattr(model, field.name)
fields.append((field.name, '{val} ({count})'.format(
val=', '.join(map(str, vals.all())),
count=vals.count(),
)))
print(', '.join(
'{0}={1}'.format(field, value)
for field, value in fields
)) | [
"def",
"_dump_model",
"(",
"model",
",",
"attrs",
"=",
"None",
")",
":",
"fields",
"=",
"[",
"]",
"for",
"field",
"in",
"model",
".",
"_meta",
".",
"fields",
":",
"fields",
".",
"append",
"(",
"(",
"field",
".",
"name",
",",
"str",
"(",
"getattr",
... | Dump the model fields for debugging. | [
"Dump",
"the",
"model",
"fields",
"for",
"debugging",
"."
] | 672eac97c97644bfe334e70696a6dc5ddf4ced02 | https://github.com/aloetesting/aloe_django/blob/672eac97c97644bfe334e70696a6dc5ddf4ced02/aloe_django/steps/models.py#L188-L212 | train | 39,260 |
aloetesting/aloe_django | aloe_django/steps/models.py | _model_exists_step | def _model_exists_step(self, model, should_exist):
"""
Test for the existence of a model matching the given data.
"""
model = get_model(model)
data = guess_types(self.hashes)
queryset = model.objects
try:
existence_check = _TEST_MODEL[model]
except KeyError:
existence_check = test_existence
failed = 0
try:
for hash_ in data:
match = existence_check(queryset, hash_)
if should_exist:
assert match, \
"%s does not exist: %s" % (model.__name__, hash_)
else:
assert not match, \
"%s exists: %s" % (model.__name__, hash_)
except AssertionError as exc:
print(exc)
failed += 1
if failed:
print("Rows in DB are:")
for existing_model in queryset.all():
_dump_model(existing_model,
attrs=[k[1:]
for k in data[0].keys()
if k.startswith('@')])
if should_exist:
raise AssertionError("%i rows missing" % failed)
else:
raise AssertionError("%i rows found" % failed) | python | def _model_exists_step(self, model, should_exist):
"""
Test for the existence of a model matching the given data.
"""
model = get_model(model)
data = guess_types(self.hashes)
queryset = model.objects
try:
existence_check = _TEST_MODEL[model]
except KeyError:
existence_check = test_existence
failed = 0
try:
for hash_ in data:
match = existence_check(queryset, hash_)
if should_exist:
assert match, \
"%s does not exist: %s" % (model.__name__, hash_)
else:
assert not match, \
"%s exists: %s" % (model.__name__, hash_)
except AssertionError as exc:
print(exc)
failed += 1
if failed:
print("Rows in DB are:")
for existing_model in queryset.all():
_dump_model(existing_model,
attrs=[k[1:]
for k in data[0].keys()
if k.startswith('@')])
if should_exist:
raise AssertionError("%i rows missing" % failed)
else:
raise AssertionError("%i rows found" % failed) | [
"def",
"_model_exists_step",
"(",
"self",
",",
"model",
",",
"should_exist",
")",
":",
"model",
"=",
"get_model",
"(",
"model",
")",
"data",
"=",
"guess_types",
"(",
"self",
".",
"hashes",
")",
"queryset",
"=",
"model",
".",
"objects",
"try",
":",
"exist... | Test for the existence of a model matching the given data. | [
"Test",
"for",
"the",
"existence",
"of",
"a",
"model",
"matching",
"the",
"given",
"data",
"."
] | 672eac97c97644bfe334e70696a6dc5ddf4ced02 | https://github.com/aloetesting/aloe_django/blob/672eac97c97644bfe334e70696a6dc5ddf4ced02/aloe_django/steps/models.py#L247-L289 | train | 39,261 |
aloetesting/aloe_django | aloe_django/steps/models.py | _write_models_step | def _write_models_step(self, model, field=None):
"""
Write or update a model.
"""
model = get_model(model)
data = guess_types(self.hashes)
try:
func = _WRITE_MODEL[model]
except KeyError:
func = partial(write_models, model)
func(data, field) | python | def _write_models_step(self, model, field=None):
"""
Write or update a model.
"""
model = get_model(model)
data = guess_types(self.hashes)
try:
func = _WRITE_MODEL[model]
except KeyError:
func = partial(write_models, model)
func(data, field) | [
"def",
"_write_models_step",
"(",
"self",
",",
"model",
",",
"field",
"=",
"None",
")",
":",
"model",
"=",
"get_model",
"(",
"model",
")",
"data",
"=",
"guess_types",
"(",
"self",
".",
"hashes",
")",
"try",
":",
"func",
"=",
"_WRITE_MODEL",
"[",
"model... | Write or update a model. | [
"Write",
"or",
"update",
"a",
"model",
"."
] | 672eac97c97644bfe334e70696a6dc5ddf4ced02 | https://github.com/aloetesting/aloe_django/blob/672eac97c97644bfe334e70696a6dc5ddf4ced02/aloe_django/steps/models.py#L378-L391 | train | 39,262 |
aloetesting/aloe_django | aloe_django/steps/models.py | _create_models_for_relation_step | def _create_models_for_relation_step(self, rel_model_name,
rel_key, rel_value, model):
"""
Create a new model linked to the given model.
Syntax:
And `model` with `field` "`value`" has `new model` in the database:
Example:
.. code-block:: gherkin
And project with name "Ball Project" has goals in the database:
| description |
| To have fun playing with balls of twine |
"""
model = get_model(model)
lookup = {rel_key: rel_value}
rel_model = get_model(rel_model_name).objects.get(**lookup)
data = guess_types(self.hashes)
for hash_ in data:
hash_['%s' % rel_model_name] = rel_model
try:
func = _WRITE_MODEL[model]
except KeyError:
func = partial(write_models, model)
func(data, None) | python | def _create_models_for_relation_step(self, rel_model_name,
rel_key, rel_value, model):
"""
Create a new model linked to the given model.
Syntax:
And `model` with `field` "`value`" has `new model` in the database:
Example:
.. code-block:: gherkin
And project with name "Ball Project" has goals in the database:
| description |
| To have fun playing with balls of twine |
"""
model = get_model(model)
lookup = {rel_key: rel_value}
rel_model = get_model(rel_model_name).objects.get(**lookup)
data = guess_types(self.hashes)
for hash_ in data:
hash_['%s' % rel_model_name] = rel_model
try:
func = _WRITE_MODEL[model]
except KeyError:
func = partial(write_models, model)
func(data, None) | [
"def",
"_create_models_for_relation_step",
"(",
"self",
",",
"rel_model_name",
",",
"rel_key",
",",
"rel_value",
",",
"model",
")",
":",
"model",
"=",
"get_model",
"(",
"model",
")",
"lookup",
"=",
"{",
"rel_key",
":",
"rel_value",
"}",
"rel_model",
"=",
"ge... | Create a new model linked to the given model.
Syntax:
And `model` with `field` "`value`" has `new model` in the database:
Example:
.. code-block:: gherkin
And project with name "Ball Project" has goals in the database:
| description |
| To have fun playing with balls of twine | | [
"Create",
"a",
"new",
"model",
"linked",
"to",
"the",
"given",
"model",
"."
] | 672eac97c97644bfe334e70696a6dc5ddf4ced02 | https://github.com/aloetesting/aloe_django/blob/672eac97c97644bfe334e70696a6dc5ddf4ced02/aloe_django/steps/models.py#L441-L473 | train | 39,263 |
aloetesting/aloe_django | aloe_django/steps/models.py | _create_m2m_links_step | def _create_m2m_links_step(self, rel_model_name,
rel_key, rel_value, relation_name):
"""
Link many-to-many models together.
Syntax:
And `model` with `field` "`value`" is linked to `other model` in the
database:
Example:
.. code-block:: gherkin
And article with name "Guidelines" is linked to tags in the database:
| name |
| coding |
| style |
"""
lookup = {rel_key: rel_value}
rel_model = get_model(rel_model_name).objects.get(**lookup)
relation = None
for m2m in rel_model._meta.many_to_many:
if relation_name in (m2m.name, m2m.verbose_name):
relation = getattr(rel_model, m2m.name)
break
if not relation:
try:
relation = getattr(rel_model, relation_name)
except AttributeError:
pass
assert relation, \
"%s does not have a many-to-many relation named '%s'" % (
rel_model._meta.verbose_name.capitalize(),
relation_name,
)
m2m_model = relation.model
for hash_ in self.hashes:
relation.add(m2m_model.objects.get(**hash_)) | python | def _create_m2m_links_step(self, rel_model_name,
rel_key, rel_value, relation_name):
"""
Link many-to-many models together.
Syntax:
And `model` with `field` "`value`" is linked to `other model` in the
database:
Example:
.. code-block:: gherkin
And article with name "Guidelines" is linked to tags in the database:
| name |
| coding |
| style |
"""
lookup = {rel_key: rel_value}
rel_model = get_model(rel_model_name).objects.get(**lookup)
relation = None
for m2m in rel_model._meta.many_to_many:
if relation_name in (m2m.name, m2m.verbose_name):
relation = getattr(rel_model, m2m.name)
break
if not relation:
try:
relation = getattr(rel_model, relation_name)
except AttributeError:
pass
assert relation, \
"%s does not have a many-to-many relation named '%s'" % (
rel_model._meta.verbose_name.capitalize(),
relation_name,
)
m2m_model = relation.model
for hash_ in self.hashes:
relation.add(m2m_model.objects.get(**hash_)) | [
"def",
"_create_m2m_links_step",
"(",
"self",
",",
"rel_model_name",
",",
"rel_key",
",",
"rel_value",
",",
"relation_name",
")",
":",
"lookup",
"=",
"{",
"rel_key",
":",
"rel_value",
"}",
"rel_model",
"=",
"get_model",
"(",
"rel_model_name",
")",
".",
"object... | Link many-to-many models together.
Syntax:
And `model` with `field` "`value`" is linked to `other model` in the
database:
Example:
.. code-block:: gherkin
And article with name "Guidelines" is linked to tags in the database:
| name |
| coding |
| style | | [
"Link",
"many",
"-",
"to",
"-",
"many",
"models",
"together",
"."
] | 672eac97c97644bfe334e70696a6dc5ddf4ced02 | https://github.com/aloetesting/aloe_django/blob/672eac97c97644bfe334e70696a6dc5ddf4ced02/aloe_django/steps/models.py#L478-L518 | train | 39,264 |
aloetesting/aloe_django | aloe_django/steps/models.py | _model_count_step | def _model_count_step(self, count, model):
"""
Count the number of models in the database.
Example:
.. code-block:: gherkin
Then there should be 0 goals in the database
"""
model = get_model(model)
expected = int(count)
found = model.objects.count()
assert found == expected, "Expected %d %s, found %d." % \
(expected, model._meta.verbose_name_plural, found) | python | def _model_count_step(self, count, model):
"""
Count the number of models in the database.
Example:
.. code-block:: gherkin
Then there should be 0 goals in the database
"""
model = get_model(model)
expected = int(count)
found = model.objects.count()
assert found == expected, "Expected %d %s, found %d." % \
(expected, model._meta.verbose_name_plural, found) | [
"def",
"_model_count_step",
"(",
"self",
",",
"count",
",",
"model",
")",
":",
"model",
"=",
"get_model",
"(",
"model",
")",
"expected",
"=",
"int",
"(",
"count",
")",
"found",
"=",
"model",
".",
"objects",
".",
"count",
"(",
")",
"assert",
"found",
... | Count the number of models in the database.
Example:
.. code-block:: gherkin
Then there should be 0 goals in the database | [
"Count",
"the",
"number",
"of",
"models",
"in",
"the",
"database",
"."
] | 672eac97c97644bfe334e70696a6dc5ddf4ced02 | https://github.com/aloetesting/aloe_django/blob/672eac97c97644bfe334e70696a6dc5ddf4ced02/aloe_django/steps/models.py#L522-L538 | train | 39,265 |
aloetesting/aloe_django | aloe_django/steps/mail.py | mail_sent_count | def mail_sent_count(self, count):
"""
Test that `count` mails have been sent.
Syntax:
I have sent `count` emails
Example:
.. code-block:: gherkin
Then I have sent 2 emails
"""
expected = int(count)
actual = len(mail.outbox)
assert expected == actual, \
"Expected to send {0} email(s), got {1}.".format(expected, actual) | python | def mail_sent_count(self, count):
"""
Test that `count` mails have been sent.
Syntax:
I have sent `count` emails
Example:
.. code-block:: gherkin
Then I have sent 2 emails
"""
expected = int(count)
actual = len(mail.outbox)
assert expected == actual, \
"Expected to send {0} email(s), got {1}.".format(expected, actual) | [
"def",
"mail_sent_count",
"(",
"self",
",",
"count",
")",
":",
"expected",
"=",
"int",
"(",
"count",
")",
"actual",
"=",
"len",
"(",
"mail",
".",
"outbox",
")",
"assert",
"expected",
"==",
"actual",
",",
"\"Expected to send {0} email(s), got {1}.\"",
".",
"f... | Test that `count` mails have been sent.
Syntax:
I have sent `count` emails
Example:
.. code-block:: gherkin
Then I have sent 2 emails | [
"Test",
"that",
"count",
"mails",
"have",
"been",
"sent",
"."
] | 672eac97c97644bfe334e70696a6dc5ddf4ced02 | https://github.com/aloetesting/aloe_django/blob/672eac97c97644bfe334e70696a6dc5ddf4ced02/aloe_django/steps/mail.py#L25-L42 | train | 39,266 |
aloetesting/aloe_django | aloe_django/steps/mail.py | dump_emails | def dump_emails(part):
"""Show the sent emails' tested parts, to aid in debugging."""
print("Sent emails:")
for email in mail.outbox:
print(getattr(email, part)) | python | def dump_emails(part):
"""Show the sent emails' tested parts, to aid in debugging."""
print("Sent emails:")
for email in mail.outbox:
print(getattr(email, part)) | [
"def",
"dump_emails",
"(",
"part",
")",
":",
"print",
"(",
"\"Sent emails:\"",
")",
"for",
"email",
"in",
"mail",
".",
"outbox",
":",
"print",
"(",
"getattr",
"(",
"email",
",",
"part",
")",
")"
] | Show the sent emails' tested parts, to aid in debugging. | [
"Show",
"the",
"sent",
"emails",
"tested",
"parts",
"to",
"aid",
"in",
"debugging",
"."
] | 672eac97c97644bfe334e70696a6dc5ddf4ced02 | https://github.com/aloetesting/aloe_django/blob/672eac97c97644bfe334e70696a6dc5ddf4ced02/aloe_django/steps/mail.py#L208-L213 | train | 39,267 |
divio/aldryn-apphooks-config | aldryn_apphooks_config/templatetags/apphooks_config_tags.py | namespace_url | def namespace_url(context, view_name, *args, **kwargs):
"""
Returns an absolute URL matching named view with its parameters and the
provided application instance namespace.
If no namespace is passed as a kwarg (or it is "" or None), this templatetag
will look into the request object for the app_config's namespace. If there
is still no namespace found, this tag will act like the normal {% url ... %}
template tag.
Normally, this tag will return whatever is returned by the ultimate call to
reverse, which also means it will raise NoReverseMatch if reverse() cannot
find a match. This behaviour can be override by suppling a 'default' kwarg
with the value of what should be returned when no match is found.
"""
namespace = kwargs.pop('namespace', None)
if not namespace:
namespace, __ = get_app_instance(context['request'])
if namespace:
namespace += ':'
reverse = partial(
urls.reverse, '{0:s}{1:s}'.format(namespace, view_name))
# We're explicitly NOT happy to just re-raise the exception, as that may
# adversely affect stack traces.
if 'default' not in kwargs:
if kwargs:
return reverse(kwargs=kwargs)
elif args:
return reverse(args=args)
else:
return reverse()
default = kwargs.pop('default', None)
try:
if kwargs:
return reverse(kwargs=kwargs)
elif args:
return reverse(args=args)
else:
return reverse()
except urls.NoReverseMatch:
return default | python | def namespace_url(context, view_name, *args, **kwargs):
"""
Returns an absolute URL matching named view with its parameters and the
provided application instance namespace.
If no namespace is passed as a kwarg (or it is "" or None), this templatetag
will look into the request object for the app_config's namespace. If there
is still no namespace found, this tag will act like the normal {% url ... %}
template tag.
Normally, this tag will return whatever is returned by the ultimate call to
reverse, which also means it will raise NoReverseMatch if reverse() cannot
find a match. This behaviour can be override by suppling a 'default' kwarg
with the value of what should be returned when no match is found.
"""
namespace = kwargs.pop('namespace', None)
if not namespace:
namespace, __ = get_app_instance(context['request'])
if namespace:
namespace += ':'
reverse = partial(
urls.reverse, '{0:s}{1:s}'.format(namespace, view_name))
# We're explicitly NOT happy to just re-raise the exception, as that may
# adversely affect stack traces.
if 'default' not in kwargs:
if kwargs:
return reverse(kwargs=kwargs)
elif args:
return reverse(args=args)
else:
return reverse()
default = kwargs.pop('default', None)
try:
if kwargs:
return reverse(kwargs=kwargs)
elif args:
return reverse(args=args)
else:
return reverse()
except urls.NoReverseMatch:
return default | [
"def",
"namespace_url",
"(",
"context",
",",
"view_name",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"namespace",
"=",
"kwargs",
".",
"pop",
"(",
"'namespace'",
",",
"None",
")",
"if",
"not",
"namespace",
":",
"namespace",
",",
"__",
"=",
"... | Returns an absolute URL matching named view with its parameters and the
provided application instance namespace.
If no namespace is passed as a kwarg (or it is "" or None), this templatetag
will look into the request object for the app_config's namespace. If there
is still no namespace found, this tag will act like the normal {% url ... %}
template tag.
Normally, this tag will return whatever is returned by the ultimate call to
reverse, which also means it will raise NoReverseMatch if reverse() cannot
find a match. This behaviour can be override by suppling a 'default' kwarg
with the value of what should be returned when no match is found. | [
"Returns",
"an",
"absolute",
"URL",
"matching",
"named",
"view",
"with",
"its",
"parameters",
"and",
"the",
"provided",
"application",
"instance",
"namespace",
"."
] | 5b8dfc7516982a8746fc08cf919c6ab116335d62 | https://github.com/divio/aldryn-apphooks-config/blob/5b8dfc7516982a8746fc08cf919c6ab116335d62/aldryn_apphooks_config/templatetags/apphooks_config_tags.py#L14-L60 | train | 39,268 |
divio/aldryn-apphooks-config | aldryn_apphooks_config/utils.py | get_app_instance | def get_app_instance(request):
"""
Returns a tuple containing the current namespace and the AppHookConfig instance
:param request: request object
:return: namespace, config
"""
app = None
if getattr(request, 'current_page', None) and request.current_page.application_urls:
app = apphook_pool.get_apphook(request.current_page.application_urls)
if app and app.app_config:
try:
config = None
with override(get_language_from_request(request, check_path=True)):
namespace = resolve(request.path_info).namespace
config = app.get_config(namespace)
return namespace, config
except Resolver404:
pass
return '', None | python | def get_app_instance(request):
"""
Returns a tuple containing the current namespace and the AppHookConfig instance
:param request: request object
:return: namespace, config
"""
app = None
if getattr(request, 'current_page', None) and request.current_page.application_urls:
app = apphook_pool.get_apphook(request.current_page.application_urls)
if app and app.app_config:
try:
config = None
with override(get_language_from_request(request, check_path=True)):
namespace = resolve(request.path_info).namespace
config = app.get_config(namespace)
return namespace, config
except Resolver404:
pass
return '', None | [
"def",
"get_app_instance",
"(",
"request",
")",
":",
"app",
"=",
"None",
"if",
"getattr",
"(",
"request",
",",
"'current_page'",
",",
"None",
")",
"and",
"request",
".",
"current_page",
".",
"application_urls",
":",
"app",
"=",
"apphook_pool",
".",
"get_apph... | Returns a tuple containing the current namespace and the AppHookConfig instance
:param request: request object
:return: namespace, config | [
"Returns",
"a",
"tuple",
"containing",
"the",
"current",
"namespace",
"and",
"the",
"AppHookConfig",
"instance"
] | 5b8dfc7516982a8746fc08cf919c6ab116335d62 | https://github.com/divio/aldryn-apphooks-config/blob/5b8dfc7516982a8746fc08cf919c6ab116335d62/aldryn_apphooks_config/utils.py#L16-L35 | train | 39,269 |
divio/aldryn-apphooks-config | aldryn_apphooks_config/utils.py | setup_config | def setup_config(form_class, config_model=None):
"""
Register the provided form as config form for the provided config model
This can be used as a decorator by adding a `model` attribute to the config form::
@setup_config
class ExampleConfigForm(AppDataForm):
model = ExampleConfig
:param form_class: Form class derived from AppDataForm
:param config_model: Model class derived from AppHookConfig
:return:
"""
# allow use as a decorator
if config_model is None:
return setup_config(form_class, form_class.model)
app_registry.register('config', AppDataContainer.from_form(form_class), config_model) | python | def setup_config(form_class, config_model=None):
"""
Register the provided form as config form for the provided config model
This can be used as a decorator by adding a `model` attribute to the config form::
@setup_config
class ExampleConfigForm(AppDataForm):
model = ExampleConfig
:param form_class: Form class derived from AppDataForm
:param config_model: Model class derived from AppHookConfig
:return:
"""
# allow use as a decorator
if config_model is None:
return setup_config(form_class, form_class.model)
app_registry.register('config', AppDataContainer.from_form(form_class), config_model) | [
"def",
"setup_config",
"(",
"form_class",
",",
"config_model",
"=",
"None",
")",
":",
"# allow use as a decorator",
"if",
"config_model",
"is",
"None",
":",
"return",
"setup_config",
"(",
"form_class",
",",
"form_class",
".",
"model",
")",
"app_registry",
".",
"... | Register the provided form as config form for the provided config model
This can be used as a decorator by adding a `model` attribute to the config form::
@setup_config
class ExampleConfigForm(AppDataForm):
model = ExampleConfig
:param form_class: Form class derived from AppDataForm
:param config_model: Model class derived from AppHookConfig
:return: | [
"Register",
"the",
"provided",
"form",
"as",
"config",
"form",
"for",
"the",
"provided",
"config",
"model"
] | 5b8dfc7516982a8746fc08cf919c6ab116335d62 | https://github.com/divio/aldryn-apphooks-config/blob/5b8dfc7516982a8746fc08cf919c6ab116335d62/aldryn_apphooks_config/utils.py#L38-L56 | train | 39,270 |
divio/aldryn-apphooks-config | aldryn_apphooks_config/utils.py | _get_apphook_field_names | def _get_apphook_field_names(model):
"""
Return all foreign key field names for a AppHookConfig based model
"""
from .models import AppHookConfig # avoid circular dependencies
fields = []
for field in model._meta.fields:
if isinstance(field, ForeignKey) and issubclass(field.remote_field.model, AppHookConfig):
fields.append(field)
return [field.name for field in fields] | python | def _get_apphook_field_names(model):
"""
Return all foreign key field names for a AppHookConfig based model
"""
from .models import AppHookConfig # avoid circular dependencies
fields = []
for field in model._meta.fields:
if isinstance(field, ForeignKey) and issubclass(field.remote_field.model, AppHookConfig):
fields.append(field)
return [field.name for field in fields] | [
"def",
"_get_apphook_field_names",
"(",
"model",
")",
":",
"from",
".",
"models",
"import",
"AppHookConfig",
"# avoid circular dependencies",
"fields",
"=",
"[",
"]",
"for",
"field",
"in",
"model",
".",
"_meta",
".",
"fields",
":",
"if",
"isinstance",
"(",
"fi... | Return all foreign key field names for a AppHookConfig based model | [
"Return",
"all",
"foreign",
"key",
"field",
"names",
"for",
"a",
"AppHookConfig",
"based",
"model"
] | 5b8dfc7516982a8746fc08cf919c6ab116335d62 | https://github.com/divio/aldryn-apphooks-config/blob/5b8dfc7516982a8746fc08cf919c6ab116335d62/aldryn_apphooks_config/utils.py#L59-L68 | train | 39,271 |
divio/aldryn-apphooks-config | aldryn_apphooks_config/utils.py | get_apphook_field_names | def get_apphook_field_names(model):
"""
Cache app-hook field names on model
:param model: model class or object
:return: list of foreign key field names to AppHookConfigs
"""
key = APP_CONFIG_FIELDS_KEY.format(
app_label=model._meta.app_label,
model_name=model._meta.object_name
).lower()
if not hasattr(model, key):
field_names = _get_apphook_field_names(model)
setattr(model, key, field_names)
return getattr(model, key) | python | def get_apphook_field_names(model):
"""
Cache app-hook field names on model
:param model: model class or object
:return: list of foreign key field names to AppHookConfigs
"""
key = APP_CONFIG_FIELDS_KEY.format(
app_label=model._meta.app_label,
model_name=model._meta.object_name
).lower()
if not hasattr(model, key):
field_names = _get_apphook_field_names(model)
setattr(model, key, field_names)
return getattr(model, key) | [
"def",
"get_apphook_field_names",
"(",
"model",
")",
":",
"key",
"=",
"APP_CONFIG_FIELDS_KEY",
".",
"format",
"(",
"app_label",
"=",
"model",
".",
"_meta",
".",
"app_label",
",",
"model_name",
"=",
"model",
".",
"_meta",
".",
"object_name",
")",
".",
"lower"... | Cache app-hook field names on model
:param model: model class or object
:return: list of foreign key field names to AppHookConfigs | [
"Cache",
"app",
"-",
"hook",
"field",
"names",
"on",
"model"
] | 5b8dfc7516982a8746fc08cf919c6ab116335d62 | https://github.com/divio/aldryn-apphooks-config/blob/5b8dfc7516982a8746fc08cf919c6ab116335d62/aldryn_apphooks_config/utils.py#L71-L85 | train | 39,272 |
divio/aldryn-apphooks-config | aldryn_apphooks_config/utils.py | get_apphook_configs | def get_apphook_configs(obj):
"""
Get apphook configs for an object obj
:param obj: any model instance
:return: list of apphook configs for given obj
"""
keys = get_apphook_field_names(obj)
return [getattr(obj, key) for key in keys] if keys else [] | python | def get_apphook_configs(obj):
"""
Get apphook configs for an object obj
:param obj: any model instance
:return: list of apphook configs for given obj
"""
keys = get_apphook_field_names(obj)
return [getattr(obj, key) for key in keys] if keys else [] | [
"def",
"get_apphook_configs",
"(",
"obj",
")",
":",
"keys",
"=",
"get_apphook_field_names",
"(",
"obj",
")",
"return",
"[",
"getattr",
"(",
"obj",
",",
"key",
")",
"for",
"key",
"in",
"keys",
"]",
"if",
"keys",
"else",
"[",
"]"
] | Get apphook configs for an object obj
:param obj: any model instance
:return: list of apphook configs for given obj | [
"Get",
"apphook",
"configs",
"for",
"an",
"object",
"obj"
] | 5b8dfc7516982a8746fc08cf919c6ab116335d62 | https://github.com/divio/aldryn-apphooks-config/blob/5b8dfc7516982a8746fc08cf919c6ab116335d62/aldryn_apphooks_config/utils.py#L88-L96 | train | 39,273 |
nugget/python-insteonplm | insteonplm/plm.py | IM.data_received | def data_received(self, data):
"""Receive data from the protocol.
Called when asyncio.Protocol detects received data from network.
"""
_LOGGER.debug("Starting: data_received")
_LOGGER.debug('Received %d bytes from PLM: %s',
len(data), binascii.hexlify(data))
self._buffer.put_nowait(data)
asyncio.ensure_future(self._peel_messages_from_buffer(),
loop=self._loop)
_LOGGER.debug("Finishing: data_received") | python | def data_received(self, data):
"""Receive data from the protocol.
Called when asyncio.Protocol detects received data from network.
"""
_LOGGER.debug("Starting: data_received")
_LOGGER.debug('Received %d bytes from PLM: %s',
len(data), binascii.hexlify(data))
self._buffer.put_nowait(data)
asyncio.ensure_future(self._peel_messages_from_buffer(),
loop=self._loop)
_LOGGER.debug("Finishing: data_received") | [
"def",
"data_received",
"(",
"self",
",",
"data",
")",
":",
"_LOGGER",
".",
"debug",
"(",
"\"Starting: data_received\"",
")",
"_LOGGER",
".",
"debug",
"(",
"'Received %d bytes from PLM: %s'",
",",
"len",
"(",
"data",
")",
",",
"binascii",
".",
"hexlify",
"(",
... | Receive data from the protocol.
Called when asyncio.Protocol detects received data from network. | [
"Receive",
"data",
"from",
"the",
"protocol",
"."
] | 65548041f1b0729ae1ae904443dd81b0c6cbf1bf | https://github.com/nugget/python-insteonplm/blob/65548041f1b0729ae1ae904443dd81b0c6cbf1bf/insteonplm/plm.py#L125-L137 | train | 39,274 |
nugget/python-insteonplm | insteonplm/plm.py | IM.connection_lost | def connection_lost(self, exc):
"""Reestablish the connection to the transport.
Called when asyncio.Protocol loses the network connection.
"""
if exc is None:
_LOGGER.warning('End of file received from Insteon Modem')
else:
_LOGGER.warning('Lost connection to Insteon Modem: %s', exc)
self.transport = None
asyncio.ensure_future(self.pause_writing(), loop=self.loop)
if self._connection_lost_callback:
self._connection_lost_callback() | python | def connection_lost(self, exc):
"""Reestablish the connection to the transport.
Called when asyncio.Protocol loses the network connection.
"""
if exc is None:
_LOGGER.warning('End of file received from Insteon Modem')
else:
_LOGGER.warning('Lost connection to Insteon Modem: %s', exc)
self.transport = None
asyncio.ensure_future(self.pause_writing(), loop=self.loop)
if self._connection_lost_callback:
self._connection_lost_callback() | [
"def",
"connection_lost",
"(",
"self",
",",
"exc",
")",
":",
"if",
"exc",
"is",
"None",
":",
"_LOGGER",
".",
"warning",
"(",
"'End of file received from Insteon Modem'",
")",
"else",
":",
"_LOGGER",
".",
"warning",
"(",
"'Lost connection to Insteon Modem: %s'",
",... | Reestablish the connection to the transport.
Called when asyncio.Protocol loses the network connection. | [
"Reestablish",
"the",
"connection",
"to",
"the",
"transport",
"."
] | 65548041f1b0729ae1ae904443dd81b0c6cbf1bf | https://github.com/nugget/python-insteonplm/blob/65548041f1b0729ae1ae904443dd81b0c6cbf1bf/insteonplm/plm.py#L139-L153 | train | 39,275 |
nugget/python-insteonplm | insteonplm/plm.py | IM.add_all_link_done_callback | def add_all_link_done_callback(self, callback):
"""Register a callback to be invoked when the ALDB is loaded."""
_LOGGER.debug('Added new callback %s ', callback)
self._cb_load_all_link_db_done.append(callback) | python | def add_all_link_done_callback(self, callback):
"""Register a callback to be invoked when the ALDB is loaded."""
_LOGGER.debug('Added new callback %s ', callback)
self._cb_load_all_link_db_done.append(callback) | [
"def",
"add_all_link_done_callback",
"(",
"self",
",",
"callback",
")",
":",
"_LOGGER",
".",
"debug",
"(",
"'Added new callback %s '",
",",
"callback",
")",
"self",
".",
"_cb_load_all_link_db_done",
".",
"append",
"(",
"callback",
")"
] | Register a callback to be invoked when the ALDB is loaded. | [
"Register",
"a",
"callback",
"to",
"be",
"invoked",
"when",
"the",
"ALDB",
"is",
"loaded",
"."
] | 65548041f1b0729ae1ae904443dd81b0c6cbf1bf | https://github.com/nugget/python-insteonplm/blob/65548041f1b0729ae1ae904443dd81b0c6cbf1bf/insteonplm/plm.py#L160-L163 | train | 39,276 |
nugget/python-insteonplm | insteonplm/plm.py | IM.add_device_not_active_callback | def add_device_not_active_callback(self, callback):
"""Register callback to be invoked when a device is not responding."""
_LOGGER.debug('Added new callback %s ', callback)
self._cb_device_not_active.append(callback) | python | def add_device_not_active_callback(self, callback):
"""Register callback to be invoked when a device is not responding."""
_LOGGER.debug('Added new callback %s ', callback)
self._cb_device_not_active.append(callback) | [
"def",
"add_device_not_active_callback",
"(",
"self",
",",
"callback",
")",
":",
"_LOGGER",
".",
"debug",
"(",
"'Added new callback %s '",
",",
"callback",
")",
"self",
".",
"_cb_device_not_active",
".",
"append",
"(",
"callback",
")"
] | Register callback to be invoked when a device is not responding. | [
"Register",
"callback",
"to",
"be",
"invoked",
"when",
"a",
"device",
"is",
"not",
"responding",
"."
] | 65548041f1b0729ae1ae904443dd81b0c6cbf1bf | https://github.com/nugget/python-insteonplm/blob/65548041f1b0729ae1ae904443dd81b0c6cbf1bf/insteonplm/plm.py#L165-L168 | train | 39,277 |
nugget/python-insteonplm | insteonplm/plm.py | IM.poll_devices | def poll_devices(self):
"""Request status updates from each device."""
for addr in self.devices:
device = self.devices[addr]
if not device.address.is_x10:
device.async_refresh_state() | python | def poll_devices(self):
"""Request status updates from each device."""
for addr in self.devices:
device = self.devices[addr]
if not device.address.is_x10:
device.async_refresh_state() | [
"def",
"poll_devices",
"(",
"self",
")",
":",
"for",
"addr",
"in",
"self",
".",
"devices",
":",
"device",
"=",
"self",
".",
"devices",
"[",
"addr",
"]",
"if",
"not",
"device",
".",
"address",
".",
"is_x10",
":",
"device",
".",
"async_refresh_state",
"(... | Request status updates from each device. | [
"Request",
"status",
"updates",
"from",
"each",
"device",
"."
] | 65548041f1b0729ae1ae904443dd81b0c6cbf1bf | https://github.com/nugget/python-insteonplm/blob/65548041f1b0729ae1ae904443dd81b0c6cbf1bf/insteonplm/plm.py#L171-L176 | train | 39,278 |
nugget/python-insteonplm | insteonplm/plm.py | IM.send_msg | def send_msg(self, msg, wait_nak=True, wait_timeout=WAIT_TIMEOUT):
"""Place a message on the send queue for sending.
Message are sent in the order they are placed in the queue.
"""
msg_info = MessageInfo(msg=msg, wait_nak=wait_nak,
wait_timeout=wait_timeout)
_LOGGER.debug("Queueing msg: %s", msg)
self._send_queue.put_nowait(msg_info) | python | def send_msg(self, msg, wait_nak=True, wait_timeout=WAIT_TIMEOUT):
"""Place a message on the send queue for sending.
Message are sent in the order they are placed in the queue.
"""
msg_info = MessageInfo(msg=msg, wait_nak=wait_nak,
wait_timeout=wait_timeout)
_LOGGER.debug("Queueing msg: %s", msg)
self._send_queue.put_nowait(msg_info) | [
"def",
"send_msg",
"(",
"self",
",",
"msg",
",",
"wait_nak",
"=",
"True",
",",
"wait_timeout",
"=",
"WAIT_TIMEOUT",
")",
":",
"msg_info",
"=",
"MessageInfo",
"(",
"msg",
"=",
"msg",
",",
"wait_nak",
"=",
"wait_nak",
",",
"wait_timeout",
"=",
"wait_timeout"... | Place a message on the send queue for sending.
Message are sent in the order they are placed in the queue. | [
"Place",
"a",
"message",
"on",
"the",
"send",
"queue",
"for",
"sending",
"."
] | 65548041f1b0729ae1ae904443dd81b0c6cbf1bf | https://github.com/nugget/python-insteonplm/blob/65548041f1b0729ae1ae904443dd81b0c6cbf1bf/insteonplm/plm.py#L178-L186 | train | 39,279 |
nugget/python-insteonplm | insteonplm/plm.py | IM.start_all_linking | def start_all_linking(self, mode, group):
"""Put the IM into All-Linking mode.
Puts the IM into All-Linking mode for 4 minutes.
Parameters:
mode: 0 | 1 | 3 | 255
0 - PLM is responder
1 - PLM is controller
3 - Device that initiated All-Linking is Controller
255 = Delete All-Link
group: All-Link group number (0 - 255)
"""
msg = StartAllLinking(mode, group)
self.send_msg(msg) | python | def start_all_linking(self, mode, group):
"""Put the IM into All-Linking mode.
Puts the IM into All-Linking mode for 4 minutes.
Parameters:
mode: 0 | 1 | 3 | 255
0 - PLM is responder
1 - PLM is controller
3 - Device that initiated All-Linking is Controller
255 = Delete All-Link
group: All-Link group number (0 - 255)
"""
msg = StartAllLinking(mode, group)
self.send_msg(msg) | [
"def",
"start_all_linking",
"(",
"self",
",",
"mode",
",",
"group",
")",
":",
"msg",
"=",
"StartAllLinking",
"(",
"mode",
",",
"group",
")",
"self",
".",
"send_msg",
"(",
"msg",
")"
] | Put the IM into All-Linking mode.
Puts the IM into All-Linking mode for 4 minutes.
Parameters:
mode: 0 | 1 | 3 | 255
0 - PLM is responder
1 - PLM is controller
3 - Device that initiated All-Linking is Controller
255 = Delete All-Link
group: All-Link group number (0 - 255) | [
"Put",
"the",
"IM",
"into",
"All",
"-",
"Linking",
"mode",
"."
] | 65548041f1b0729ae1ae904443dd81b0c6cbf1bf | https://github.com/nugget/python-insteonplm/blob/65548041f1b0729ae1ae904443dd81b0c6cbf1bf/insteonplm/plm.py#L188-L203 | train | 39,280 |
nugget/python-insteonplm | insteonplm/plm.py | IM.add_x10_device | def add_x10_device(self, housecode, unitcode, feature='OnOff'):
"""Add an X10 device based on a feature description.
Current features are:
- OnOff
- Dimmable
- Sensor
- AllUnitsOff
- AllLightsOn
- AllLightsOff
"""
device = insteonplm.devices.create_x10(self, housecode,
unitcode, feature)
if device:
self.devices[device.address.id] = device
return device | python | def add_x10_device(self, housecode, unitcode, feature='OnOff'):
"""Add an X10 device based on a feature description.
Current features are:
- OnOff
- Dimmable
- Sensor
- AllUnitsOff
- AllLightsOn
- AllLightsOff
"""
device = insteonplm.devices.create_x10(self, housecode,
unitcode, feature)
if device:
self.devices[device.address.id] = device
return device | [
"def",
"add_x10_device",
"(",
"self",
",",
"housecode",
",",
"unitcode",
",",
"feature",
"=",
"'OnOff'",
")",
":",
"device",
"=",
"insteonplm",
".",
"devices",
".",
"create_x10",
"(",
"self",
",",
"housecode",
",",
"unitcode",
",",
"feature",
")",
"if",
... | Add an X10 device based on a feature description.
Current features are:
- OnOff
- Dimmable
- Sensor
- AllUnitsOff
- AllLightsOn
- AllLightsOff | [
"Add",
"an",
"X10",
"device",
"based",
"on",
"a",
"feature",
"description",
"."
] | 65548041f1b0729ae1ae904443dd81b0c6cbf1bf | https://github.com/nugget/python-insteonplm/blob/65548041f1b0729ae1ae904443dd81b0c6cbf1bf/insteonplm/plm.py#L205-L220 | train | 39,281 |
nugget/python-insteonplm | insteonplm/plm.py | IM.device_not_active | def device_not_active(self, addr):
"""Handle inactive devices."""
self.aldb_device_handled(addr)
for callback in self._cb_device_not_active:
callback(addr) | python | def device_not_active(self, addr):
"""Handle inactive devices."""
self.aldb_device_handled(addr)
for callback in self._cb_device_not_active:
callback(addr) | [
"def",
"device_not_active",
"(",
"self",
",",
"addr",
")",
":",
"self",
".",
"aldb_device_handled",
"(",
"addr",
")",
"for",
"callback",
"in",
"self",
".",
"_cb_device_not_active",
":",
"callback",
"(",
"addr",
")"
] | Handle inactive devices. | [
"Handle",
"inactive",
"devices",
"."
] | 65548041f1b0729ae1ae904443dd81b0c6cbf1bf | https://github.com/nugget/python-insteonplm/blob/65548041f1b0729ae1ae904443dd81b0c6cbf1bf/insteonplm/plm.py#L227-L231 | train | 39,282 |
nugget/python-insteonplm | insteonplm/plm.py | IM.aldb_device_handled | def aldb_device_handled(self, addr):
"""Remove device from ALDB device list."""
if isinstance(addr, Address):
remove_addr = addr.id
else:
remove_addr = addr
try:
self._aldb_devices.pop(remove_addr)
_LOGGER.debug('Removed ALDB device %s', remove_addr)
except KeyError:
_LOGGER.debug('Device %s not in ALDB device list', remove_addr)
_LOGGER.debug('ALDB device count: %d', len(self._aldb_devices)) | python | def aldb_device_handled(self, addr):
"""Remove device from ALDB device list."""
if isinstance(addr, Address):
remove_addr = addr.id
else:
remove_addr = addr
try:
self._aldb_devices.pop(remove_addr)
_LOGGER.debug('Removed ALDB device %s', remove_addr)
except KeyError:
_LOGGER.debug('Device %s not in ALDB device list', remove_addr)
_LOGGER.debug('ALDB device count: %d', len(self._aldb_devices)) | [
"def",
"aldb_device_handled",
"(",
"self",
",",
"addr",
")",
":",
"if",
"isinstance",
"(",
"addr",
",",
"Address",
")",
":",
"remove_addr",
"=",
"addr",
".",
"id",
"else",
":",
"remove_addr",
"=",
"addr",
"try",
":",
"self",
".",
"_aldb_devices",
".",
... | Remove device from ALDB device list. | [
"Remove",
"device",
"from",
"ALDB",
"device",
"list",
"."
] | 65548041f1b0729ae1ae904443dd81b0c6cbf1bf | https://github.com/nugget/python-insteonplm/blob/65548041f1b0729ae1ae904443dd81b0c6cbf1bf/insteonplm/plm.py#L233-L244 | train | 39,283 |
nugget/python-insteonplm | insteonplm/plm.py | IM.pause_writing | async def pause_writing(self):
"""Pause writing."""
self._restart_writer = False
if self._writer_task:
self._writer_task.remove_done_callback(self.restart_writing)
self._writer_task.cancel()
await self._writer_task
await asyncio.sleep(0, loop=self._loop) | python | async def pause_writing(self):
"""Pause writing."""
self._restart_writer = False
if self._writer_task:
self._writer_task.remove_done_callback(self.restart_writing)
self._writer_task.cancel()
await self._writer_task
await asyncio.sleep(0, loop=self._loop) | [
"async",
"def",
"pause_writing",
"(",
"self",
")",
":",
"self",
".",
"_restart_writer",
"=",
"False",
"if",
"self",
".",
"_writer_task",
":",
"self",
".",
"_writer_task",
".",
"remove_done_callback",
"(",
"self",
".",
"restart_writing",
")",
"self",
".",
"_w... | Pause writing. | [
"Pause",
"writing",
"."
] | 65548041f1b0729ae1ae904443dd81b0c6cbf1bf | https://github.com/nugget/python-insteonplm/blob/65548041f1b0729ae1ae904443dd81b0c6cbf1bf/insteonplm/plm.py#L314-L321 | train | 39,284 |
nugget/python-insteonplm | insteonplm/plm.py | IM._get_plm_info | def _get_plm_info(self):
"""Request PLM Info."""
_LOGGER.info('Requesting Insteon Modem Info')
msg = GetImInfo()
self.send_msg(msg, wait_nak=True, wait_timeout=.5) | python | def _get_plm_info(self):
"""Request PLM Info."""
_LOGGER.info('Requesting Insteon Modem Info')
msg = GetImInfo()
self.send_msg(msg, wait_nak=True, wait_timeout=.5) | [
"def",
"_get_plm_info",
"(",
"self",
")",
":",
"_LOGGER",
".",
"info",
"(",
"'Requesting Insteon Modem Info'",
")",
"msg",
"=",
"GetImInfo",
"(",
")",
"self",
".",
"send_msg",
"(",
"msg",
",",
"wait_nak",
"=",
"True",
",",
"wait_timeout",
"=",
".5",
")"
] | Request PLM Info. | [
"Request",
"PLM",
"Info",
"."
] | 65548041f1b0729ae1ae904443dd81b0c6cbf1bf | https://github.com/nugget/python-insteonplm/blob/65548041f1b0729ae1ae904443dd81b0c6cbf1bf/insteonplm/plm.py#L381-L385 | train | 39,285 |
nugget/python-insteonplm | insteonplm/plm.py | IM._load_all_link_database | def _load_all_link_database(self):
"""Load the ALL-Link Database into object."""
_LOGGER.debug("Starting: _load_all_link_database")
self.devices.state = 'loading'
self._get_first_all_link_record()
_LOGGER.debug("Ending: _load_all_link_database") | python | def _load_all_link_database(self):
"""Load the ALL-Link Database into object."""
_LOGGER.debug("Starting: _load_all_link_database")
self.devices.state = 'loading'
self._get_first_all_link_record()
_LOGGER.debug("Ending: _load_all_link_database") | [
"def",
"_load_all_link_database",
"(",
"self",
")",
":",
"_LOGGER",
".",
"debug",
"(",
"\"Starting: _load_all_link_database\"",
")",
"self",
".",
"devices",
".",
"state",
"=",
"'loading'",
"self",
".",
"_get_first_all_link_record",
"(",
")",
"_LOGGER",
".",
"debug... | Load the ALL-Link Database into object. | [
"Load",
"the",
"ALL",
"-",
"Link",
"Database",
"into",
"object",
"."
] | 65548041f1b0729ae1ae904443dd81b0c6cbf1bf | https://github.com/nugget/python-insteonplm/blob/65548041f1b0729ae1ae904443dd81b0c6cbf1bf/insteonplm/plm.py#L438-L443 | train | 39,286 |
nugget/python-insteonplm | insteonplm/plm.py | IM._get_first_all_link_record | def _get_first_all_link_record(self):
"""Request first ALL-Link record."""
_LOGGER.debug("Starting: _get_first_all_link_record")
_LOGGER.info('Requesting ALL-Link Records')
if self.aldb.status == ALDBStatus.LOADED:
self._next_all_link_rec_nak_retries = 3
self._handle_get_next_all_link_record_nak(None)
return
self.aldb.clear()
self._next_all_link_rec_nak_retries = 0
msg = GetFirstAllLinkRecord()
self.send_msg(msg, wait_nak=True, wait_timeout=.5)
_LOGGER.debug("Ending: _get_first_all_link_record") | python | def _get_first_all_link_record(self):
"""Request first ALL-Link record."""
_LOGGER.debug("Starting: _get_first_all_link_record")
_LOGGER.info('Requesting ALL-Link Records')
if self.aldb.status == ALDBStatus.LOADED:
self._next_all_link_rec_nak_retries = 3
self._handle_get_next_all_link_record_nak(None)
return
self.aldb.clear()
self._next_all_link_rec_nak_retries = 0
msg = GetFirstAllLinkRecord()
self.send_msg(msg, wait_nak=True, wait_timeout=.5)
_LOGGER.debug("Ending: _get_first_all_link_record") | [
"def",
"_get_first_all_link_record",
"(",
"self",
")",
":",
"_LOGGER",
".",
"debug",
"(",
"\"Starting: _get_first_all_link_record\"",
")",
"_LOGGER",
".",
"info",
"(",
"'Requesting ALL-Link Records'",
")",
"if",
"self",
".",
"aldb",
".",
"status",
"==",
"ALDBStatus"... | Request first ALL-Link record. | [
"Request",
"first",
"ALL",
"-",
"Link",
"record",
"."
] | 65548041f1b0729ae1ae904443dd81b0c6cbf1bf | https://github.com/nugget/python-insteonplm/blob/65548041f1b0729ae1ae904443dd81b0c6cbf1bf/insteonplm/plm.py#L445-L457 | train | 39,287 |
nugget/python-insteonplm | insteonplm/plm.py | IM._get_next_all_link_record | def _get_next_all_link_record(self):
"""Request next ALL-Link record."""
_LOGGER.debug("Starting: _get_next_all_link_record")
_LOGGER.debug("Requesting Next All-Link Record")
msg = GetNextAllLinkRecord()
self.send_msg(msg, wait_nak=True, wait_timeout=.5)
_LOGGER.debug("Ending: _get_next_all_link_record") | python | def _get_next_all_link_record(self):
"""Request next ALL-Link record."""
_LOGGER.debug("Starting: _get_next_all_link_record")
_LOGGER.debug("Requesting Next All-Link Record")
msg = GetNextAllLinkRecord()
self.send_msg(msg, wait_nak=True, wait_timeout=.5)
_LOGGER.debug("Ending: _get_next_all_link_record") | [
"def",
"_get_next_all_link_record",
"(",
"self",
")",
":",
"_LOGGER",
".",
"debug",
"(",
"\"Starting: _get_next_all_link_record\"",
")",
"_LOGGER",
".",
"debug",
"(",
"\"Requesting Next All-Link Record\"",
")",
"msg",
"=",
"GetNextAllLinkRecord",
"(",
")",
"self",
"."... | Request next ALL-Link record. | [
"Request",
"next",
"ALL",
"-",
"Link",
"record",
"."
] | 65548041f1b0729ae1ae904443dd81b0c6cbf1bf | https://github.com/nugget/python-insteonplm/blob/65548041f1b0729ae1ae904443dd81b0c6cbf1bf/insteonplm/plm.py#L459-L465 | train | 39,288 |
nugget/python-insteonplm | insteonplm/plm.py | IM.x10_all_units_off | def x10_all_units_off(self, housecode):
"""Send the X10 All Units Off command."""
if isinstance(housecode, str):
housecode = housecode.upper()
else:
raise TypeError('Housecode must be a string')
msg = X10Send.command_msg(housecode, X10_COMMAND_ALL_UNITS_OFF)
self.send_msg(msg)
self._x10_command_to_device(housecode, X10_COMMAND_ALL_UNITS_OFF, msg) | python | def x10_all_units_off(self, housecode):
"""Send the X10 All Units Off command."""
if isinstance(housecode, str):
housecode = housecode.upper()
else:
raise TypeError('Housecode must be a string')
msg = X10Send.command_msg(housecode, X10_COMMAND_ALL_UNITS_OFF)
self.send_msg(msg)
self._x10_command_to_device(housecode, X10_COMMAND_ALL_UNITS_OFF, msg) | [
"def",
"x10_all_units_off",
"(",
"self",
",",
"housecode",
")",
":",
"if",
"isinstance",
"(",
"housecode",
",",
"str",
")",
":",
"housecode",
"=",
"housecode",
".",
"upper",
"(",
")",
"else",
":",
"raise",
"TypeError",
"(",
"'Housecode must be a string'",
")... | Send the X10 All Units Off command. | [
"Send",
"the",
"X10",
"All",
"Units",
"Off",
"command",
"."
] | 65548041f1b0729ae1ae904443dd81b0c6cbf1bf | https://github.com/nugget/python-insteonplm/blob/65548041f1b0729ae1ae904443dd81b0c6cbf1bf/insteonplm/plm.py#L678-L686 | train | 39,289 |
nugget/python-insteonplm | insteonplm/plm.py | PLM.connection_made | def connection_made(self, transport):
"""Start the PLM connection process.
Called when asyncio.Protocol establishes the network connection.
"""
_LOGGER.info('Connection established to PLM')
self.transport = transport
self._restart_writer = True
self.restart_writing()
# Testing to see if this fixes the 2413S issue
self.transport.serial.timeout = 1
self.transport.serial.write_timeout = 1
self.transport.set_write_buffer_limits(128)
# limit = self.transport.get_write_buffer_size()
# _LOGGER.debug('Write buffer size is %d', limit)
if self._aldb.status != ALDBStatus.LOADED:
asyncio.ensure_future(self._setup_devices(), loop=self._loop) | python | def connection_made(self, transport):
"""Start the PLM connection process.
Called when asyncio.Protocol establishes the network connection.
"""
_LOGGER.info('Connection established to PLM')
self.transport = transport
self._restart_writer = True
self.restart_writing()
# Testing to see if this fixes the 2413S issue
self.transport.serial.timeout = 1
self.transport.serial.write_timeout = 1
self.transport.set_write_buffer_limits(128)
# limit = self.transport.get_write_buffer_size()
# _LOGGER.debug('Write buffer size is %d', limit)
if self._aldb.status != ALDBStatus.LOADED:
asyncio.ensure_future(self._setup_devices(), loop=self._loop) | [
"def",
"connection_made",
"(",
"self",
",",
"transport",
")",
":",
"_LOGGER",
".",
"info",
"(",
"'Connection established to PLM'",
")",
"self",
".",
"transport",
"=",
"transport",
"self",
".",
"_restart_writer",
"=",
"True",
"self",
".",
"restart_writing",
"(",
... | Start the PLM connection process.
Called when asyncio.Protocol establishes the network connection. | [
"Start",
"the",
"PLM",
"connection",
"process",
"."
] | 65548041f1b0729ae1ae904443dd81b0c6cbf1bf | https://github.com/nugget/python-insteonplm/blob/65548041f1b0729ae1ae904443dd81b0c6cbf1bf/insteonplm/plm.py#L752-L770 | train | 39,290 |
nugget/python-insteonplm | insteonplm/plm.py | Hub.connection_made | def connection_made(self, transport):
"""Start the Hub connection process.
Called when asyncio.Protocol establishes the network connection.
"""
_LOGGER.info('Connection established to Hub')
_LOGGER.debug('Transport: %s', transport)
self.transport = transport
self._restart_writer = True
self.restart_writing()
if self._aldb.status != ALDBStatus.LOADED:
asyncio.ensure_future(self._setup_devices(), loop=self._loop) | python | def connection_made(self, transport):
"""Start the Hub connection process.
Called when asyncio.Protocol establishes the network connection.
"""
_LOGGER.info('Connection established to Hub')
_LOGGER.debug('Transport: %s', transport)
self.transport = transport
self._restart_writer = True
self.restart_writing()
if self._aldb.status != ALDBStatus.LOADED:
asyncio.ensure_future(self._setup_devices(), loop=self._loop) | [
"def",
"connection_made",
"(",
"self",
",",
"transport",
")",
":",
"_LOGGER",
".",
"info",
"(",
"'Connection established to Hub'",
")",
"_LOGGER",
".",
"debug",
"(",
"'Transport: %s'",
",",
"transport",
")",
"self",
".",
"transport",
"=",
"transport",
"self",
... | Start the Hub connection process.
Called when asyncio.Protocol establishes the network connection. | [
"Start",
"the",
"Hub",
"connection",
"process",
"."
] | 65548041f1b0729ae1ae904443dd81b0c6cbf1bf | https://github.com/nugget/python-insteonplm/blob/65548041f1b0729ae1ae904443dd81b0c6cbf1bf/insteonplm/plm.py#L795-L808 | train | 39,291 |
nugget/python-insteonplm | insteonplm/devices/__init__.py | create | def create(plm, address, cat, subcat, firmware=None):
"""Create a device from device info data."""
from insteonplm.devices.ipdb import IPDB
ipdb = IPDB()
product = ipdb[[cat, subcat]]
deviceclass = product.deviceclass
device = None
if deviceclass is not None:
device = deviceclass(plm, address, cat, subcat,
product.product_key,
product.description,
product.model)
return device | python | def create(plm, address, cat, subcat, firmware=None):
"""Create a device from device info data."""
from insteonplm.devices.ipdb import IPDB
ipdb = IPDB()
product = ipdb[[cat, subcat]]
deviceclass = product.deviceclass
device = None
if deviceclass is not None:
device = deviceclass(plm, address, cat, subcat,
product.product_key,
product.description,
product.model)
return device | [
"def",
"create",
"(",
"plm",
",",
"address",
",",
"cat",
",",
"subcat",
",",
"firmware",
"=",
"None",
")",
":",
"from",
"insteonplm",
".",
"devices",
".",
"ipdb",
"import",
"IPDB",
"ipdb",
"=",
"IPDB",
"(",
")",
"product",
"=",
"ipdb",
"[",
"[",
"c... | Create a device from device info data. | [
"Create",
"a",
"device",
"from",
"device",
"info",
"data",
"."
] | 65548041f1b0729ae1ae904443dd81b0c6cbf1bf | https://github.com/nugget/python-insteonplm/blob/65548041f1b0729ae1ae904443dd81b0c6cbf1bf/insteonplm/devices/__init__.py#L55-L67 | train | 39,292 |
nugget/python-insteonplm | insteonplm/devices/__init__.py | create_x10 | def create_x10(plm, housecode, unitcode, feature):
"""Create an X10 device from a feature definition."""
from insteonplm.devices.ipdb import IPDB
ipdb = IPDB()
product = ipdb.x10(feature)
deviceclass = product.deviceclass
device = None
if deviceclass:
device = deviceclass(plm, housecode, unitcode)
return device | python | def create_x10(plm, housecode, unitcode, feature):
"""Create an X10 device from a feature definition."""
from insteonplm.devices.ipdb import IPDB
ipdb = IPDB()
product = ipdb.x10(feature)
deviceclass = product.deviceclass
device = None
if deviceclass:
device = deviceclass(plm, housecode, unitcode)
return device | [
"def",
"create_x10",
"(",
"plm",
",",
"housecode",
",",
"unitcode",
",",
"feature",
")",
":",
"from",
"insteonplm",
".",
"devices",
".",
"ipdb",
"import",
"IPDB",
"ipdb",
"=",
"IPDB",
"(",
")",
"product",
"=",
"ipdb",
".",
"x10",
"(",
"feature",
")",
... | Create an X10 device from a feature definition. | [
"Create",
"an",
"X10",
"device",
"from",
"a",
"feature",
"definition",
"."
] | 65548041f1b0729ae1ae904443dd81b0c6cbf1bf | https://github.com/nugget/python-insteonplm/blob/65548041f1b0729ae1ae904443dd81b0c6cbf1bf/insteonplm/devices/__init__.py#L70-L79 | train | 39,293 |
nugget/python-insteonplm | insteonplm/devices/__init__.py | Device.id_request | def id_request(self):
"""Request a device ID from a device."""
import inspect
curframe = inspect.currentframe()
calframe = inspect.getouterframes(curframe, 2)
_LOGGER.debug('caller name: %s', calframe[1][3])
msg = StandardSend(self.address, COMMAND_ID_REQUEST_0X10_0X00)
self._plm.send_msg(msg) | python | def id_request(self):
"""Request a device ID from a device."""
import inspect
curframe = inspect.currentframe()
calframe = inspect.getouterframes(curframe, 2)
_LOGGER.debug('caller name: %s', calframe[1][3])
msg = StandardSend(self.address, COMMAND_ID_REQUEST_0X10_0X00)
self._plm.send_msg(msg) | [
"def",
"id_request",
"(",
"self",
")",
":",
"import",
"inspect",
"curframe",
"=",
"inspect",
".",
"currentframe",
"(",
")",
"calframe",
"=",
"inspect",
".",
"getouterframes",
"(",
"curframe",
",",
"2",
")",
"_LOGGER",
".",
"debug",
"(",
"'caller name: %s'",
... | Request a device ID from a device. | [
"Request",
"a",
"device",
"ID",
"from",
"a",
"device",
"."
] | 65548041f1b0729ae1ae904443dd81b0c6cbf1bf | https://github.com/nugget/python-insteonplm/blob/65548041f1b0729ae1ae904443dd81b0c6cbf1bf/insteonplm/devices/__init__.py#L187-L194 | train | 39,294 |
nugget/python-insteonplm | insteonplm/devices/__init__.py | Device.product_data_request | def product_data_request(self):
"""Request product data from a device.
Not supported by all devices.
Required after 01-Feb-2007.
"""
msg = StandardSend(self._address,
COMMAND_PRODUCT_DATA_REQUEST_0X03_0X00)
self._send_msg(msg) | python | def product_data_request(self):
"""Request product data from a device.
Not supported by all devices.
Required after 01-Feb-2007.
"""
msg = StandardSend(self._address,
COMMAND_PRODUCT_DATA_REQUEST_0X03_0X00)
self._send_msg(msg) | [
"def",
"product_data_request",
"(",
"self",
")",
":",
"msg",
"=",
"StandardSend",
"(",
"self",
".",
"_address",
",",
"COMMAND_PRODUCT_DATA_REQUEST_0X03_0X00",
")",
"self",
".",
"_send_msg",
"(",
"msg",
")"
] | Request product data from a device.
Not supported by all devices.
Required after 01-Feb-2007. | [
"Request",
"product",
"data",
"from",
"a",
"device",
"."
] | 65548041f1b0729ae1ae904443dd81b0c6cbf1bf | https://github.com/nugget/python-insteonplm/blob/65548041f1b0729ae1ae904443dd81b0c6cbf1bf/insteonplm/devices/__init__.py#L196-L204 | train | 39,295 |
nugget/python-insteonplm | insteonplm/devices/__init__.py | Device.assign_to_all_link_group | def assign_to_all_link_group(self, group=0x01):
"""Assign a device to an All-Link Group.
The default is group 0x01.
"""
msg = StandardSend(self._address,
COMMAND_ASSIGN_TO_ALL_LINK_GROUP_0X01_NONE,
cmd2=group)
self._send_msg(msg) | python | def assign_to_all_link_group(self, group=0x01):
"""Assign a device to an All-Link Group.
The default is group 0x01.
"""
msg = StandardSend(self._address,
COMMAND_ASSIGN_TO_ALL_LINK_GROUP_0X01_NONE,
cmd2=group)
self._send_msg(msg) | [
"def",
"assign_to_all_link_group",
"(",
"self",
",",
"group",
"=",
"0x01",
")",
":",
"msg",
"=",
"StandardSend",
"(",
"self",
".",
"_address",
",",
"COMMAND_ASSIGN_TO_ALL_LINK_GROUP_0X01_NONE",
",",
"cmd2",
"=",
"group",
")",
"self",
".",
"_send_msg",
"(",
"ms... | Assign a device to an All-Link Group.
The default is group 0x01. | [
"Assign",
"a",
"device",
"to",
"an",
"All",
"-",
"Link",
"Group",
"."
] | 65548041f1b0729ae1ae904443dd81b0c6cbf1bf | https://github.com/nugget/python-insteonplm/blob/65548041f1b0729ae1ae904443dd81b0c6cbf1bf/insteonplm/devices/__init__.py#L206-L214 | train | 39,296 |
nugget/python-insteonplm | insteonplm/devices/__init__.py | Device.delete_from_all_link_group | def delete_from_all_link_group(self, group):
"""Delete a device to an All-Link Group."""
msg = StandardSend(self._address,
COMMAND_DELETE_FROM_ALL_LINK_GROUP_0X02_NONE,
cmd2=group)
self._send_msg(msg) | python | def delete_from_all_link_group(self, group):
"""Delete a device to an All-Link Group."""
msg = StandardSend(self._address,
COMMAND_DELETE_FROM_ALL_LINK_GROUP_0X02_NONE,
cmd2=group)
self._send_msg(msg) | [
"def",
"delete_from_all_link_group",
"(",
"self",
",",
"group",
")",
":",
"msg",
"=",
"StandardSend",
"(",
"self",
".",
"_address",
",",
"COMMAND_DELETE_FROM_ALL_LINK_GROUP_0X02_NONE",
",",
"cmd2",
"=",
"group",
")",
"self",
".",
"_send_msg",
"(",
"msg",
")"
] | Delete a device to an All-Link Group. | [
"Delete",
"a",
"device",
"to",
"an",
"All",
"-",
"Link",
"Group",
"."
] | 65548041f1b0729ae1ae904443dd81b0c6cbf1bf | https://github.com/nugget/python-insteonplm/blob/65548041f1b0729ae1ae904443dd81b0c6cbf1bf/insteonplm/devices/__init__.py#L216-L221 | train | 39,297 |
nugget/python-insteonplm | insteonplm/devices/__init__.py | Device.enter_linking_mode | def enter_linking_mode(self, group=0x01):
"""Tell a device to enter All-Linking Mode.
Same as holding down the Set button for 10 sec.
Default group is 0x01.
Not supported by i1 devices.
"""
msg = ExtendedSend(self._address,
COMMAND_ENTER_LINKING_MODE_0X09_NONE,
cmd2=group,
userdata=Userdata())
msg.set_checksum()
self._send_msg(msg) | python | def enter_linking_mode(self, group=0x01):
"""Tell a device to enter All-Linking Mode.
Same as holding down the Set button for 10 sec.
Default group is 0x01.
Not supported by i1 devices.
"""
msg = ExtendedSend(self._address,
COMMAND_ENTER_LINKING_MODE_0X09_NONE,
cmd2=group,
userdata=Userdata())
msg.set_checksum()
self._send_msg(msg) | [
"def",
"enter_linking_mode",
"(",
"self",
",",
"group",
"=",
"0x01",
")",
":",
"msg",
"=",
"ExtendedSend",
"(",
"self",
".",
"_address",
",",
"COMMAND_ENTER_LINKING_MODE_0X09_NONE",
",",
"cmd2",
"=",
"group",
",",
"userdata",
"=",
"Userdata",
"(",
")",
")",
... | Tell a device to enter All-Linking Mode.
Same as holding down the Set button for 10 sec.
Default group is 0x01.
Not supported by i1 devices. | [
"Tell",
"a",
"device",
"to",
"enter",
"All",
"-",
"Linking",
"Mode",
"."
] | 65548041f1b0729ae1ae904443dd81b0c6cbf1bf | https://github.com/nugget/python-insteonplm/blob/65548041f1b0729ae1ae904443dd81b0c6cbf1bf/insteonplm/devices/__init__.py#L241-L254 | train | 39,298 |
nugget/python-insteonplm | insteonplm/devices/__init__.py | Device.enter_unlinking_mode | def enter_unlinking_mode(self, group):
"""Unlink a device from an All-Link group.
Not supported by i1 devices.
"""
msg = StandardSend(self._address,
COMMAND_ENTER_UNLINKING_MODE_0X0A_NONE,
cmd2=group)
self._send_msg(msg) | python | def enter_unlinking_mode(self, group):
"""Unlink a device from an All-Link group.
Not supported by i1 devices.
"""
msg = StandardSend(self._address,
COMMAND_ENTER_UNLINKING_MODE_0X0A_NONE,
cmd2=group)
self._send_msg(msg) | [
"def",
"enter_unlinking_mode",
"(",
"self",
",",
"group",
")",
":",
"msg",
"=",
"StandardSend",
"(",
"self",
".",
"_address",
",",
"COMMAND_ENTER_UNLINKING_MODE_0X0A_NONE",
",",
"cmd2",
"=",
"group",
")",
"self",
".",
"_send_msg",
"(",
"msg",
")"
] | Unlink a device from an All-Link group.
Not supported by i1 devices. | [
"Unlink",
"a",
"device",
"from",
"an",
"All",
"-",
"Link",
"group",
"."
] | 65548041f1b0729ae1ae904443dd81b0c6cbf1bf | https://github.com/nugget/python-insteonplm/blob/65548041f1b0729ae1ae904443dd81b0c6cbf1bf/insteonplm/devices/__init__.py#L256-L264 | train | 39,299 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.